Open Source

PDC Struct

Binary serialization for Pydantic models, including C-compatible structs for network protocols.

terminal
pip install pdc-struct

PDC Struct is a Pydantic extension for binary serialization. It combines Pydantic’s validation with Python’s struct module, bridging high-level Python data models and low-level binary formats.

Two modes

  • C-compatible: fixed-size layouts that interoperate directly with C structs and network protocols.
  • Dynamic: flexible, compact encoding for Python-to-Python communication.

Features

  • Full Pydantic validation combined with struct packing rules.
  • Configurable byte order and alignment.
  • Integers, floats, strings, enums, UUIDs, IP addresses and more.
  • Boundary checking on every field.

Example

An ARP packet (RFC 826), packed in network byte order:

from enum import IntEnum
from ipaddress import IPv4Address
from pydantic import Field
from pdc_struct import StructModel, StructConfig, StructMode, ByteOrder
from pdc_struct.c_types import UInt8, UInt16

class Operation(IntEnum):
    REQUEST = 1
    REPLY = 2

class ARPPacket(StructModel):
    hardware_type: UInt16 = 1             # Ethernet
    protocol_type: UInt16 = 0x0800        # IPv4
    hw_addr_len: UInt8 = 6
    proto_addr_len: UInt8 = 4
    operation: UInt16                     # an Operation value
    sender_hw_addr: bytes = Field(struct_length=6)
    sender_proto_addr: IPv4Address
    target_hw_addr: bytes = Field(struct_length=6)
    target_proto_addr: IPv4Address

    struct_config = StructConfig(
        mode=StructMode.C_COMPATIBLE,
        byte_order=ByteOrder.BIG_ENDIAN,
    )

packet = ARPPacket(
    operation=Operation.REQUEST,
    sender_hw_addr=b"\x00\x11\x22\x33\x44\x55",
    sender_proto_addr=IPv4Address("192.168.1.100"),
    target_hw_addr=bytes(6),
    target_proto_addr=IPv4Address("192.168.1.1"),
)
data = packet.to_bytes()
assert ARPPacket.from_bytes(data) == packet

Requires Python 3.11+ and Pydantic 2.