pak.packets.aligned_packet

Packets which align their fields.

class AlignedPacket(*, ctx=None, **fields)

Bases: Packet

A Packet which aligns its fields.

The fields of an AlignedPacket are aligned in the same way the fields of a struct would be in C or C++, including the ending padding.

The header of an AlignedPacket is not taken into account when aligning fields.

Warning

An AlignedPacket must have at least one field to be used in full.

classmethod alignment(*, ctx=None)

Gets the total alignment of the AlignedPacket.

Parameters:

ctx (Packet.Context or None) – The context for the AlignedPacket.

Returns:

The total alignment of the AlignedPacket.

Return type:

int

Examples

>>> import pak
>>> class MyPacket(pak.AlignedPacket):
...     first: pak.Int16
...     second: pak.Int32
...     third: pak.Int8
...
>>> MyPacket.alignment()
4
pack_without_header(*, ctx=None)

Overrides Packet.pack_without_header() to handle alignment padding.

size(*, ctx=None)

Overrides Packet.size() to handle alignment padding.

classmethod unpack(buf, *, ctx=None)

Overrides Packet.unpack() to handle alignment padding.

async classmethod unpack_async(reader, *, ctx=None)

Overrides Packet.unpack_async() to handle alignment padding.

class AlignedHeader(packet=None, /, *, ctx=None, **fields)

Bases: Header, AlignedPacket

A Packet.Header which aligns its fields.

This is not the default header of AlignedPacket since AlignedPackets may often have headers which do not align their fields, nor even have any header at all. Additionally, there are unaligned Packets which may have headers which align their fields.

This class is nevertheless still provided however as the double inheritance required may be tricky to get right.

Note

There is no alignment performed between the header and the Packet proper.

Examples

>>> import pak
>>> class MyPacket(pak.Packet):
...     id = 1
...     field: pak.UInt64
...     class Header(pak.AlignedHeader):
...         id:   pak.UInt8
...         size: pak.UInt16
...
>>> MyPacket.Header.alignment()
2
>>> # The '\xAA' byte represents alignment padding.
>>> MyPacket.Header.unpack(b"\x01\xAA\x08\x00")
MyPacket.Header(id=1, size=8)
>>> MyPacket(field=2).pack()
b'\x01\x00\x08\x00\x02\x00\x00\x00\x00\x00\x00\x00'