From f47b18adc8a7217b8c676ac76c419fdd7125ee1a Mon Sep 17 00:00:00 2001 From: Jason Frey Date: Fri, 22 May 2015 13:40:24 -0400 Subject: [PATCH] Add support for Hash definition Closes #7 --- lib/binary_struct.rb | 1 + spec/binary_struct_spec.rb | 18 ++++++++++++++++++ 2 files changed, 19 insertions(+) diff --git a/lib/binary_struct.rb b/lib/binary_struct.rb index b479fff..0725f8b 100644 --- a/lib/binary_struct.rb +++ b/lib/binary_struct.rb @@ -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 diff --git a/spec/binary_struct_spec.rb b/spec/binary_struct_spec.rb index 30ef286..37bbcaa 100644 --- a/spec/binary_struct_spec.rb +++ b/spec/binary_struct_spec.rb @@ -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 @@ -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) @@ -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) } @@ -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