Skip to content

Commit ecf01be

Browse files
author
Ary Borenszweig
committed
ByteFormat: fixed bug in decode from slice
1 parent 30a1f96 commit ecf01be

File tree

2 files changed

+19
-5
lines changed

2 files changed

+19
-5
lines changed

spec/std/io/byte_format_spec.cr

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,12 @@ describe IO::ByteFormat do
7878
IO::ByteFormat::LittleEndian.encode(0x1234_i16, bytes)
7979
bytes.should eq(Bytes[0x34, 0x12])
8080
end
81+
82+
it "writes int16 to larger slice" do
83+
bytes = Bytes[0, 0, 0, 0]
84+
IO::ByteFormat::LittleEndian.encode(0x1234_i16, bytes)
85+
bytes.should eq(Bytes[0x34, 0x12, 0, 0])
86+
end
8187
end
8288
end
8389

@@ -139,6 +145,12 @@ describe IO::ByteFormat do
139145
int.should eq(0x1234_i16)
140146
end
141147

148+
it "reads int16 from larger slice" do
149+
bytes = Bytes[0x34, 0x12, 0, 0]
150+
int = IO::ByteFormat::LittleEndian.decode(Int16, bytes)
151+
int.should eq(0x1234_i16)
152+
end
153+
142154
it "reads float32" do
143155
bytes = Bytes[0xB6, 0xF3, 0x9D, 0x3F]
144156
float = IO::ByteFormat::LittleEndian.decode(Float32, bytes)

src/io/byte_format.cr

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -127,28 +127,30 @@ module IO::ByteFormat
127127
{% for mod in %w(LittleEndian BigEndian) %}
128128
module {{mod.id}}
129129
{% for type, i in %w(Int8 UInt8 Int16 UInt16 Int32 UInt32 Int64 UInt64) %}
130+
{% bytesize = 2 ** (i / 2) %}
131+
130132
def self.encode(int : {{type.id}}, io : IO)
131-
buffer = pointerof(int).as(UInt8[{{2 ** (i / 2)}}]*).value
133+
buffer = pointerof(int).as(UInt8[{{bytesize}}]*).value
132134
buffer.reverse! unless SystemEndian == self
133135
io.write(buffer.to_slice)
134136
end
135137

136138
def self.encode(int : {{type.id}}, bytes : Bytes)
137-
buffer = pointerof(int).as(UInt8[{{2 ** (i / 2)}}]*).value
139+
buffer = pointerof(int).as(UInt8[{{bytesize}}]*).value
138140
buffer.reverse! unless SystemEndian == self
139141
buffer.to_slice.copy_to(bytes)
140142
end
141143

142144
def self.decode(type : {{type.id}}.class, io : IO)
143-
buffer = uninitialized UInt8[{{2 ** (i / 2)}}]
145+
buffer = uninitialized UInt8[{{bytesize}}]
144146
io.read_fully(buffer.to_slice)
145147
buffer.reverse! unless SystemEndian == self
146148
buffer.to_unsafe.as(Pointer({{type.id}})).value
147149
end
148150

149151
def self.decode(type : {{type.id}}.class, bytes : Bytes)
150-
buffer = uninitialized UInt8[{{2 ** (i / 2)}}]
151-
bytes.copy_to(buffer.to_slice)
152+
buffer = uninitialized UInt8[{{bytesize}}]
153+
bytes.to_slice[0, {{bytesize}}].copy_to(buffer.to_slice)
152154
buffer.reverse! unless SystemEndian == self
153155
buffer.to_unsafe.as(Pointer({{type.id}})).value
154156
end

0 commit comments

Comments
 (0)