This post is about Python's Construct library
THE CODE
These are the definitions of my constructs:
from construct import *
AttributeHandleValuePair = "attribute_handle_value_pair" / Struct(
"handle" / Int16ul,
"value" / Bytes(this._.length - 2)
)
AttReadByTypeResponse = "read_by_type_response" / Struct(
"length" / Int8ul, # The size in bytes of each handle/value pair
"attribute_data_list" / AttributeHandleValuePair[2]
)
THE PROBLEM
Trying to run the following command:
AttReadByTypeResponse.sizeof(dict(length=4, attribute_data_list=[dict(handle=1, value=2), dict(handle=3, value=4)])
I receive the following error:
SizeofError: cannot calculate size, key not found in context
sizeof -> read_by_type_response -> attribute_data_list -> attribute_handle_value_pair -> value
WHAT I FOUND OUT
The size of the value
field for each attribute_handle_value_pair
is derived from the length
field of its parent. I think that the sizeof()
method is trying to calculate the size of attribute_handle_value_pair
first, while the length
field of read_by_type_response
is still undefined, therefore it cannot calculate its size.
I tried changing the the length of the value
field to a static value and it worked well.
MY QUESTION
How can I calculate the sizeof()
for a construct that is depending of its parent construct?
Should I redesign the way this protocol is modeled? If so then how?