Skip to content

Commit

Permalink
Merge pull request #9 from Fryguy/add_hash_support_for_definition
Browse files Browse the repository at this point in the history
Add support for Hash definition
  • Loading branch information
Fryguy committed May 22, 2015
2 parents 80e6a26 + f47b18a commit 242b530
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 0 deletions.
1 change: 1 addition & 0 deletions lib/binary_struct.rb
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ def definition=(value)
if value.kind_of?(self.class)
@definition = value.definition.dup
else
value = value.to_a.map(&:reverse).flatten if value.kind_of?(Hash)
value = Array(value)
self.class.validate_definition(value)
@definition = value
Expand Down
18 changes: 18 additions & 0 deletions spec/binary_struct_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,17 @@
]
STRUCT_DEF_SIZE = 19

STRUCT_DEF_HASH = {
:quad => 'Q',
'long' => 'L',
:short => 'S',
nil => 'C',
:binary => 'b5',
'none' => 'a0',
:unused => 'a',
'bc' => 'a2',
}

STRUCT_DEF_ASTERISK = ['a*', :word]
STRUCT_DEF_ASTERISK_SIZE = 0 # '*' is ignored

Expand All @@ -28,10 +39,12 @@
"bc" => "BC",
"none" => ""
}
STRUCT_DECODED_HASH2 = STRUCT_DECODED_HASH.merge(:unused => "0")

it('.new') { expect { BinaryStruct.new }.not_to raise_error }
it('.new with definition') { expect { BinaryStruct.new(STRUCT_DEF) }.not_to raise_error }
it('.new with definition with *') { expect { BinaryStruct.new(STRUCT_DEF_ASTERISK) }.not_to raise_error }
it('.new with Hash defintion') { expect { BinaryStruct.new(STRUCT_DEF_HASH) }.not_to raise_error }
it '.new with another BinaryStruct' do
s = BinaryStruct.new(STRUCT_DEF)
s2 = BinaryStruct.new(s)
Expand All @@ -46,6 +59,7 @@

it('#definition=') { expect { BinaryStruct.new.definition = STRUCT_DEF }.not_to raise_error }
it('#definition= with definition with *') { expect { BinaryStruct.new.definition = STRUCT_DEF_ASTERISK }.not_to raise_error }
it('#definition= with Hash defintion') { expect { BinaryStruct.new.definition = STRUCT_DEF_HASH }.not_to raise_error }

it('#definition= with unrecognized format') { expect { BinaryStruct.new.definition = STRUCT_DEF_UNRECOGNIZED_FORMAT }.to raise_error(RuntimeError) }
it('#definition= with unsupported format') { expect { BinaryStruct.new.definition = STRUCT_DEF_UNSUPPORTED_FORMAT }.to raise_error(RuntimeError) }
Expand All @@ -63,6 +77,10 @@
expect(BinaryStruct.new(STRUCT_DEF_ASTERISK).decode("Testing")).to eq(:word => "Testing")
end

it '#decode with Hash defintion' do
expect(BinaryStruct.new(STRUCT_DEF_HASH).decode(STRUCT_ENCODED_STR)).to eq(STRUCT_DECODED_HASH2)
end

it '#decode against multiple records' do
expect(BinaryStruct.new(STRUCT_DEF).decode(STRUCT_ENCODED_STR * 10, 10)).to eq([STRUCT_DECODED_HASH] * 10)
end
Expand Down

0 comments on commit 242b530

Please sign in to comment.