Skip to content

Commit

Permalink
Merge pull request #9 from spider-gazelle/feat/from-slice
Browse files Browse the repository at this point in the history
feat(serialisation): add `BinData.from_slice`
  • Loading branch information
stakach authored Oct 27, 2020
2 parents c1ace07 + e9a8215 commit c7d6c13
Show file tree
Hide file tree
Showing 4 changed files with 14 additions and 2 deletions.
2 changes: 1 addition & 1 deletion shard.yml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
name: bindata
version: 1.7.0
version: 1.8.0

development_dependencies:
ameba:
Expand Down
7 changes: 7 additions & 0 deletions spec/bindata_spec.cr
Original file line number Diff line number Diff line change
@@ -1,6 +1,13 @@
require "./helper"

describe BinData do
it "should parse an object from a Slice" do
r = Header.new
r.name = "foo"
slice = r.to_slice
Header.from_slice(slice).name.should eq "foo"
end

it "should parse an object from an IO" do
io = IO::Memory.new
io.write_bytes 5
Expand Down
2 changes: 1 addition & 1 deletion spec/bitfield_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ describe BinData::BitField do
io = IO::Memory.new
io.write_byte(0x80)
expect_raises BinData::ParseError, "failed to parse ByteSized.bitfield.header" do
obj = io.read_bytes(ByteSized)
io.read_bytes(ByteSized)
end
end
end
5 changes: 5 additions & 0 deletions src/bindata.cr
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,11 @@ abstract class BinData
IO::ByteFormat::SystemEndian
end

def self.from_slice(bytes : Slice, format : IO::ByteFormat = IO::ByteFormat::SystemEndian)
io = IO::Memory.new(bytes)
from_io(io, format)
end

def to_slice
io = IO::Memory.new
io.write_bytes self
Expand Down

0 comments on commit c7d6c13

Please sign in to comment.