2.3. Helper Functions

namedstruct.sizefromlen(limit, *properties)

Factory to generate a function which get size from specified field with limits. Often used in nstruct “size” parameter.

To retrieve size without limit, simply use lambda expression: lambda x: x.header.length

Parameters:
  • limit – the maximum size limit, if the acquired value if larger then the limit, BadLenError is raised to protect against serious result like memory overflow or dead loop.
  • properties – the name of the specified fields. Specify more than one string to form a property path, like: sizefromlen(256, ‘header’, ‘length’) -> s.header.length
Returns:

a function which takes a NamedStruct as parameter, and returns the length value from specified property path.

namedstruct.packsize(*properties)

Revert to sizefromlen, store the struct size (len(struct)) to specified property path. The size includes padding. To store the size without padding, use packrealsize() instead. Often used in nstruct “prepack” parameter.

Parameters:properties – specified field name, same as sizefromlen.
Returns:a function which takes a NamedStruct as parameter, and pack the size to specified field.
namedstruct.packrealsize(*properties)

Revert to sizefromlen, pack the struct real size (struct._realsize()) to specified property path. Unlike packsize, the size without padding is stored. Often used in nstruct “prepack” parameter.

Parameters:properties – specified field name, same as sizefromlen.
Returns:a function which takes a NamedStruct as parameter, and pack the size to specified field.
namedstruct.packvalue(value, *properties)

Store a specified value to specified property path. Often used in nstruct “init” parameter.

Parameters:
  • value – a fixed value
  • properties – specified field name, same as sizefromlen.
Returns:

a function which takes a NamedStruct as parameter, and store the value to property path.

namedstruct.packexpr(func, *properties)

Store a evaluated value to specified property path. Often used in nstruct “prepack” parameter.

Parameters:
  • func – a function which takes a NamedStruct as parameter and returns a value, often a lambda expression
  • properties – specified field name, same as sizefromlen.
Returns:

a function which takes a NamedStruct as parameter, and store the return value of func to property path.