diff --git a/lib/binary_struct.rb b/lib/binary_struct.rb index 0725f8b..505a068 100644 --- a/lib/binary_struct.rb +++ b/lib/binary_struct.rb @@ -126,6 +126,21 @@ def each(&block) self.definition.each_slice(2, &block) end + def offset(attr) + offset = 0 + self.definition.each_slice(2) do |format, name| + return offset if name == attr + + type,count = format[0,1], format[1..-1] + count = count.empty? ? 1 : count.to_i + size = BinaryStruct::SIZES[type] + + offset += BinaryStruct::STRING_FORMATS.include?(type) ? + size * count : size + end + offset + end + # # Methods to handle the old style of calling # diff --git a/spec/binary_struct_spec.rb b/spec/binary_struct_spec.rb index 37bbcaa..054ca32 100644 --- a/spec/binary_struct_spec.rb +++ b/spec/binary_struct_spec.rb @@ -109,6 +109,10 @@ expect(dup_def).to eq(STRUCT_DEF) end + it "#offset to specified attribute" do + expect(BinaryStruct.new(STRUCT_DEF).offset(:short)).to eq(12) + end + context "old style methods" do after(:each) { BinaryStruct.clear_structs_by_definition_cache }