Skip to content

Commit 61fbb0b

Browse files
committed
Add method to return offset of specified struct attribute
1 parent fbbb149 commit 61fbb0b

File tree

1 file changed

+15
-0
lines changed

1 file changed

+15
-0
lines changed

lib/binary_struct.rb

+15
Original file line numberDiff line numberDiff line change
@@ -126,6 +126,21 @@ def each(&block)
126126
self.definition.each_slice(2, &block)
127127
end
128128

129+
def offset(attr)
130+
offset = 0
131+
self.definition.each_slice(2) do |format, name|
132+
return offset if name == attr
133+
134+
type,count = format[0,1], format[1..-1]
135+
count = count.empty? ? 1 : count.to_i
136+
size = BinaryStruct::SIZES[type]
137+
138+
offset += BinaryStruct::STRING_FORMATS.include?(type) ?
139+
size * count : size
140+
end
141+
offset
142+
end
143+
129144
#
130145
# Methods to handle the old style of calling
131146
#

0 commit comments

Comments
 (0)