Core API: Alignment and Padding

construct.Padding(length, pattern='\x00')

Padding field that adds bytes when building, discards bytes when parsing.

Parameters:
  • length – length of the padding, an integer or a context function returning such an integer
  • pattern – padding pattern as b-character, default is \x00
Raises:

PaddingError – when strict is set and actual parsed pattern differs from specified

Example:

>>> d = Padding(4)
>>> d.build(None)
b'\x00\x00\x00\x00'
>>> d.parse(b"****")
None
>>> d.sizeof()
4
construct.Padded(length, subcon, pattern='\x00')

Appends additional null bytes to achieve a fixed length. Fails if actual data is longer than specified length. Note that subcon can actually be variable size, its the eventual size during building that determines actual padding.

Raises:PaddingError – when parsed or build data is longer than the length

Example:

>>> d = Padded(4, Byte)
>>> d.build(255)
b'\xff\x00\x00\x00'
>>> d.parse(_)
255
>>> d.sizeof()
4

>>> d = Padded(4, VarInt)
>>> d.build(1)
b'\x01\x00\x00\x00'
>>> d.build(70000)
b'\xf0\xa2\x04\x00'
construct.Aligned(modulus, subcon, pattern='\x00')

Appends additional null bytes to achieve a length that is shortest multiple of a modulus.

Parameters:
  • modulus – the modulus to final length, an integer or a context function returning such an integer
  • subcon – the subcon to align
  • pattern – optional, the padding pattern, a bytes character (default is x00)

Example:

>>> d = Aligned(4, Int16ub)
>>> d.parse(b'\x00\x01\x00\x00')
1
>>> d.sizeof()
4
construct.AlignedStruct(modulus, *subcons, **kw)

Makes a structure where each field is aligned to the same modulus (it is a struct of aligned fields, not an aligned struct).

See also

Uses Aligned() and Struct().

Parameters:
  • modulus – passed to each member
  • *subcons – subcons that make up the Struct
  • **kw – named subcons, extend the Struct

Example:

>>> d = AlignedStruct(4, "a"/Int8ub, "b"/Int16ub)
>>> d.build(dict(a=1,b=5))
b'\x01\x00\x00\x00\x00\x05\x00\x00'
>>> d.parse(_)
Container(a=1)(b=5)
>>> d.sizeof()
8