Core API: Lazy equivalents

construct.LazyStruct(*subcons, **kw)

Equivalent to Struct construct, however fixed size members are parsed on demand, others are parsed immediately. If entire struct is fixed size then entire parse is essentially one seek.

See also

Equivalent to Struct().

construct.LazySequence(*subcons, **kw)

Equivalent to Sequence construct, however fixed size members are parsed on demand, others are parsed immediately. If entire sequence is fixed size then entire parse is essentially one seek.

See also

Equivalent to Sequence().

construct.LazyRange(min, max, subcon)

Equivalent to Range construct, but members are parsed on demand. Works only with fixed size subcon.

See also

Equivalent to Range().

construct.OnDemand(subcon)

Allows for on-demand (lazy) parsing. When parsing, it will return a parameterless function that when called, will return the parsed value. Object is cached after first parsing, so non-deterministic subcons will be affected. Works only with fixed size subcon.

Parameters:subcon – the subcon to read/write on demand, must be fixed size

Example:

>>> OnDemand(Byte).parse(b"\xff")
<function OnDemand._parse.<locals>.<lambda> at 0x7fdc241cfc80>
>>> _()
255
>>> OnDemand(Byte).build(16)
b'\x10'

Can also re-build from the lambda returned at parsing.

>>> OnDemand(Byte).parse(b"\xff")
<function OnDemand._parse.<locals>.<lambda> at 0x7fcbd9855f28>
>>> OnDemand(Byte).build(_)
b'\xff'
construct.OnDemandPointer(offset, subcon)

An on-demand pointer. Is both lazy and jumps to a position before reading.

See also

Base OnDemand() and Pointer() construct.

Parameters:
  • offset – an int or a context function that returns absolute stream position, where the construction would take place, can return negative integer as position from the end backwards
  • subcon – the subcon that will be parsed or built at the offset stream position

Example:

>>> OnDemandPointer(lambda ctx: 2, Byte).parse(b"\x01\x02\x03garbage")
<function OnDemand._parse.<locals>.effectuate at 0x7f6f011ad510>
>>> _()
3
construct.LazyBound(subconfunc)

A lazy-bound construct that binds to the construct only at runtime. Useful for recursive data structures (like linked lists or trees), where a construct needs to refer to itself (while it doesn’t exist yet).

Parameters:subconfunc – a context function returning a Construct (derived) instance, can also return Pass or itself

Example:

>>> st = Struct(
...     "value"/Byte,
...     "next"/If(this.value > 0, LazyBound(lambda ctx: st)),
... )
...
>>> st.parse(b"\x05\x09\x00")
Container(value=5)(next=Container(value=9)(next=Container(value=0)(next=None)))
...
>>> print(st.parse(b"\x05\x09\x00"))
Container:
    value = 5
    next = Container:
        value = 9
        next = Container:
            value = 0
            next = None