Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions lib/binary_struct.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
#
Expand Down
4 changes: 4 additions & 0 deletions spec/binary_struct_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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 }

Expand Down