Skip to content

Commit

Permalink
ByteFormat: fixed bug in decode from slice
Browse files Browse the repository at this point in the history
  • Loading branch information
asterite committed Dec 3, 2016
1 parent 30a1f96 commit ecf01be
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 5 deletions.
12 changes: 12 additions & 0 deletions spec/std/io/byte_format_spec.cr
Expand Up @@ -78,6 +78,12 @@ describe IO::ByteFormat do
IO::ByteFormat::LittleEndian.encode(0x1234_i16, bytes)
bytes.should eq(Bytes[0x34, 0x12])
end

it "writes int16 to larger slice" do
bytes = Bytes[0, 0, 0, 0]
IO::ByteFormat::LittleEndian.encode(0x1234_i16, bytes)
bytes.should eq(Bytes[0x34, 0x12, 0, 0])
end
end
end

Expand Down Expand Up @@ -139,6 +145,12 @@ describe IO::ByteFormat do
int.should eq(0x1234_i16)
end

it "reads int16 from larger slice" do
bytes = Bytes[0x34, 0x12, 0, 0]
int = IO::ByteFormat::LittleEndian.decode(Int16, bytes)
int.should eq(0x1234_i16)
end

it "reads float32" do
bytes = Bytes[0xB6, 0xF3, 0x9D, 0x3F]
float = IO::ByteFormat::LittleEndian.decode(Float32, bytes)
Expand Down
12 changes: 7 additions & 5 deletions src/io/byte_format.cr
Expand Up @@ -127,28 +127,30 @@ module IO::ByteFormat
{% for mod in %w(LittleEndian BigEndian) %}
module {{mod.id}}
{% for type, i in %w(Int8 UInt8 Int16 UInt16 Int32 UInt32 Int64 UInt64) %}
{% bytesize = 2 ** (i / 2) %}

def self.encode(int : {{type.id}}, io : IO)
buffer = pointerof(int).as(UInt8[{{2 ** (i / 2)}}]*).value
buffer = pointerof(int).as(UInt8[{{bytesize}}]*).value
buffer.reverse! unless SystemEndian == self
io.write(buffer.to_slice)
end

def self.encode(int : {{type.id}}, bytes : Bytes)
buffer = pointerof(int).as(UInt8[{{2 ** (i / 2)}}]*).value
buffer = pointerof(int).as(UInt8[{{bytesize}}]*).value
buffer.reverse! unless SystemEndian == self
buffer.to_slice.copy_to(bytes)
end

def self.decode(type : {{type.id}}.class, io : IO)
buffer = uninitialized UInt8[{{2 ** (i / 2)}}]
buffer = uninitialized UInt8[{{bytesize}}]
io.read_fully(buffer.to_slice)
buffer.reverse! unless SystemEndian == self
buffer.to_unsafe.as(Pointer({{type.id}})).value
end

def self.decode(type : {{type.id}}.class, bytes : Bytes)
buffer = uninitialized UInt8[{{2 ** (i / 2)}}]
bytes.copy_to(buffer.to_slice)
buffer = uninitialized UInt8[{{bytesize}}]
bytes.to_slice[0, {{bytesize}}].copy_to(buffer.to_slice)
buffer.reverse! unless SystemEndian == self
buffer.to_unsafe.as(Pointer({{type.id}})).value
end
Expand Down

0 comments on commit ecf01be

Please sign in to comment.