Skip to content

StructModel

StructModel is the primary base class for creating binary-serializable data structures. It extends Pydantic's BaseModel to provide seamless conversion between Python objects and packed binary data.

Overview

Use StructModel when you need to:

  • Serialize Python objects to binary format for network protocols, file formats, or IPC
  • Deserialize binary data back into validated Python objects
  • Interface with C programs or libraries expecting specific struct layouts
  • Define data structures that can work in both dynamic (Python-to-Python) and C-compatible modes

Quick Example

from pydantic import Field
from pdc_struct import StructModel, StructConfig, ByteOrder, StructMode

class Point(StructModel):
    x: float = Field(description="X coordinate")
    y: float = Field(description="Y coordinate")

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

# Create and serialize
point = Point(x=1.5, y=2.5)
data = point.to_bytes()  # Pack to binary

# Deserialize
restored = Point.from_bytes(data)
assert restored.x == 1.5

Operating Modes

StructModel supports two operating modes configured via StructConfig:

Mode Description Use Case
C_COMPATIBLE Fixed-size structs without headers C interop, embedded systems
DYNAMIC Variable-size with header metadata Python-to-Python communication

See the Operating Modes guide for detailed information.

Supported Field Types

StructModel automatically handles these Python types:

  • Numeric: int, float, bool, Int8, UInt8, Int16, UInt16
  • Text/Binary: str (with max_length), bytes (with max_length)
  • Network: ipaddress.IPv4Address
  • Identifiers: uuid.UUID
  • Enums: Enum, IntEnum
  • Nested: Other StructModel or BitFieldModel instances

Class Reference

StructModel

Bases: BaseModel

Base model for struct-compatible Pydantic models

Source code in pdc_struct/models/struct_model.py
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
class StructModel(BaseModel):
    """Base model for struct-compatible Pydantic models"""

    # Class variables
    struct_config: ClassVar[StructConfig] = StructConfig()
    _field_handlers: ClassVar[Dict[str, TypeHandler]] = {}

    def __init__(self, **data):
        if "packed_value" in data:
            packed_value = data.pop("packed_value")
            # Create temporary instance to unpack the values
            unpacked = self.__class__.from_bytes(packed_value)
            # Get the field values from the unpacked instance
            field_values = {
                name: getattr(unpacked, name) for name in self.model_fields.keys()
            }
            # Let explicit values override packed values
            field_values.update(data)
            data = field_values

        super().__init__(**data)

    @classmethod
    def __pydantic_init_subclass__(cls, **kwargs):
        """Initialize a StructModel subclass."""
        super().__pydantic_init_subclass__(**kwargs)

        # Validate struct_config options
        if not isinstance(cls.struct_config.mode, StructMode):
            raise ValueError(
                f"Invalid mode: {cls.struct_config.mode}. Must be a StructMode enum value."
            )

        if not isinstance(cls.struct_config.version, StructVersion):
            raise ValueError(
                f"Invalid version: {cls.struct_config.version}. Must be a StructVersion enum value."
            )

        if not isinstance(cls.struct_config.byte_order, ByteOrder):
            raise ValueError(
                f"Invalid byte_order: {cls.struct_config.byte_order}. Must be a ByteOrder enum value."
            )

        # Cache handlers and validate fields
        cls._field_handlers = {}
        for (
            field_name,
            field,
        ) in cls.model_fields.items():  # noqa - model_fields property returns dict
            # For C_COMPATIBLE mode, validate Optional fields have defaults
            if cls.struct_config.mode == StructMode.C_COMPATIBLE and is_optional_type(
                field.annotation
            ):
                # Check for either default value or default_factory
                if field.default is None and field.default_factory is None:
                    python_type = unwrap_optional_type(field.annotation)
                    raise ValueError(
                        f"Field '{field_name}': Optional fields in C_COMPATIBLE mode must have "
                        f"either a default value or default_factory. Add either "
                        f"'= {python_type.__name__}()' or define a default value."
                    )

            # Get the actual type and its handler
            python_type = unwrap_optional_type(field.annotation)
            try:
                handler = TypeHandlerMeta.get_handler(python_type)
            except NotImplementedError as e:
                raise NotImplementedError(f"Field '{field_name}': {e}")

            # Cache the handler
            cls._field_handlers[field_name] = handler

            try:
                handler.validate_field(field)
            except ValueError as e:
                raise ValueError(f"Field '{field_name}': {e}")

    def clone(self, **field_updates: Any) -> "StructModel":
        """Create a new instance with the same field values, optionally overriding specific fields.

        This method creates a copy of the current instance through serialization/deserialization,
        then applies any provided field updates. Useful for creating variations of an existing
        struct without modifying the original.

        Args:
            **field_updates: Field values to override in the new instance.
                Any fields not specified will retain their values from the current instance.

        Returns:
            A new instance of the same class with the specified updates applied.

        Example:
            >>> from pdc_struct import StructModel, StructConfig, StructMode
            >>>
            >>> class Point(StructModel):
            ...     x: float
            ...     y: float
            ...     z: float
            ...
            ...     struct_config = StructConfig(mode=StructMode.C_COMPATIBLE)
            >>>
            >>> origin = Point(x=0.0, y=0.0, z=0.0)
            >>> # Create a new point with only z changed
            >>> elevated = origin.clone(z=10.0)
            >>> elevated.x, elevated.y, elevated.z
            (0.0, 0.0, 10.0)
            >>> # Original is unchanged
            >>> origin.z
            0.0
        """
        return self.__class__(packed_value=self.to_bytes(), **field_updates)

    @classmethod
    def struct_format_string(cls) -> str:
        """Get the struct format string that would be used for packing/unpacking.

        Returns the struct format string that represents the complete model, including
        byte order and all fields.

        Returns:
            str: The struct format string (e.g. '<dds10s?' for little-endian double,
                double, 10-char string, bool).

        Example:
            >>> from pydantic import Field
            >>> from pdc_struct import StructModel, StructConfig, ByteOrder, StructVersion
            >>>
            >>> class Point(StructModel):
            ...     x: float = Field(description="X coordinate")
            ...     y: float = Field(description="Y coordinate")
            ...     label: str = Field(json_schema_extra={"max_length": 10}, description="Point label")
            ...     active: bool = Field(default=True, description="Whether point is active")
            ...
            ...     struct_config = StructConfig(
            ...         include_header=True,
            ...         version=StructVersion.V1,
            ...         byte_order=ByteOrder.LITTLE_ENDIAN
            ...     )
            >>>
            >>> Point.struct_format_string()
            '<dd10s?'
        """
        return cls.get_struct_format()

    @classmethod
    def struct_size(cls) -> int:
        """Return the size in bytes of the struct when packed.

        For C_COMPATIBLE mode this is the exact size.
        For DYNAMIC mode this is less relevant as optional data is not packed - largest possible size is returned
        """
        return struct.calcsize(cls.struct_format_string())

    @classmethod
    def get_struct_format(
        cls,
        present_fields: Optional[list] = None,
        byte_order: Optional[ByteOrder] = None,
    ) -> str:
        """Generate struct format string from model fields.

        Args:
            present_fields: Optional list of fields to include in format string.
                           If None, includes all fields.
            byte_order: Optional ByteOrder to override the struct_config's endianness.
                       Used primarily for nested structs to match parent endianness.
        """
        format_parts = []
        fields_to_process = (
            present_fields or cls.model_fields.keys()
        )  # noqa - model_fields property returns dict

        for field_name in fields_to_process:
            field = cls.model_fields[
                field_name
            ]  # noqa - model_fields property returns dict
            handler = cls._field_handlers[field_name]
            format_parts.append(handler.get_struct_format(field))

        # Use override_endian if provided, otherwise use struct_config's byte_order
        effective_byte_order = byte_order or cls.struct_config.byte_order
        return effective_byte_order.value + "".join(format_parts)

    def _pack_value(
        self, field_name: str, value: Any, byte_order: Optional[ByteOrder] = None
    ) -> Any:
        """Pack a single value using its handler."""
        if value is None:
            return None

        field = self.model_fields[field_name]
        handler = self._field_handlers[field_name]

        # Let the handler validate if the value is acceptable
        if not handler.is_valid_value(value):
            expected_type = field.annotation
            if is_optional_type(expected_type):
                expected_type = get_args(expected_type)[0]
            raise TypeError(
                [
                    {
                        "loc": (field_name,),
                        "msg": f"Expected {expected_type.__name__}, got {type(value).__name__}",
                        "type": "type_error",
                    }
                ]
            )

        if byte_order is not None:
            temp_config = StructConfig(
                mode=self.struct_config.mode,
                version=self.struct_config.version,
                byte_order=byte_order,
                propagate_byte_order=self.struct_config.propagate_byte_order,
            )
        else:
            temp_config = self.struct_config

        return self._field_handlers[field_name].pack(
            value, field=field, struct_config=temp_config
        )

    @classmethod
    def _unpack_value(
        cls, field_name: str, value: Any, byte_order: Optional[ByteOrder] = None
    ) -> Any:
        """Unpack a single value using its handler.

        Args:
            field_name: Name of the field to unpack
            value: Value to unpack
            byte_order: Optional ByteOrder to override the struct_config's endianness.
                       Used primarily for nested structs to match parent endianness.
        """
        if value is None:
            return None

        field = cls.model_fields[field_name]  # noqa - property is a dict

        # Create a temporary struct_config with the overridden byte_order if provided
        if byte_order is not None:
            temp_config = StructConfig(
                mode=cls.struct_config.mode,
                version=cls.struct_config.version,
                byte_order=byte_order,
                propagate_byte_order=cls.struct_config.propagate_byte_order,
            )
        else:
            temp_config = cls.struct_config

        return cls._field_handlers[field_name].unpack(
            value, field=field, struct_config=temp_config
        )

    def to_bytes(self, override_endian: Optional[ByteOrder] = None) -> bytes:
        """Convert model instance to bytes using configured mode and version.

        Serializes the model's field values into a binary representation suitable for
        storage, network transmission, or C interoperability. The output format depends
        on the configured mode (C_COMPATIBLE or DYNAMIC).

        Args:
            override_endian: Optional ByteOrder to override the struct_config's endianness.
                            Used primarily for nested structs to match parent endianness.

        Returns:
            bytes: The packed binary data according to the configured mode.

        Raises:
            ValueError: If mode or version is unsupported.
            StructPackError: If packing fails due to invalid field values.

        Example:
            >>> from pdc_struct import StructModel, StructConfig, StructMode, ByteOrder
            >>>
            >>> class Point(StructModel):
            ...     x: float
            ...     y: float
            ...
            ...     struct_config = StructConfig(
            ...         mode=StructMode.C_COMPATIBLE,
            ...         byte_order=ByteOrder.LITTLE_ENDIAN
            ...     )
            >>>
            >>> point = Point(x=1.0, y=2.0)
            >>> data = point.to_bytes()
            >>> len(data)
            16
            >>> # Restore the point from bytes
            >>> restored = Point.from_bytes(data)
            >>> restored.x, restored.y
            (1.0, 2.0)
        """
        # Validate version - currently only V1 is supported
        if self.struct_config.version != StructVersion.V1:
            raise ValueError(
                f"Unsupported struct version: {self.struct_config.version}"
            )

        # Get effective byte order
        byte_order = override_endian or self.struct_config.byte_order

        # Route based on mode
        match self.struct_config.mode:
            case StructMode.C_COMPATIBLE:
                return self._to_bytes_v1_c_compatible(byte_order)
            case StructMode.DYNAMIC:
                return self._to_bytes_v1_dynamic(byte_order)
            case _:
                raise ValueError(f"Unsupported mode: {self.struct_config.mode}")

    def _to_bytes_v1_c_compatible(self, byte_order: ByteOrder) -> bytes:
        """Pack data in C-compatible mode (V1).

        In C_COMPATIBLE mode:
        - No header is included
        - Fixed struct format
        - No optional fields allowed

        Args:
            byte_order: ByteOrder to use for packing. This overrides the struct_config's
                       byte_order setting.

        Returns:
            bytes: The packed binary data.

        Raises:
            StructPackError: If packing fails
        """
        try:
            # Get format string with overridden byte order
            format_string = self.get_struct_format(byte_order=byte_order)
            values = []

            # Pack each field using its handler
            for field_name, field in self.model_fields.items():
                value = getattr(self, field_name)
                # Pass byte_order to pack_value for nested structs
                values.append(
                    self._pack_value(field_name, value, byte_order=byte_order)
                )

            return struct.pack(format_string, *values)

        except struct.error as e:
            raise StructPackError(f"Failed to pack struct data: {e}")

    def _to_bytes_v1_dynamic(self, byte_order: ByteOrder) -> bytes:
        """Pack data in dynamic mode (V1).

        In DYNAMIC mode:
        - Header is always included (version, flags)
        - Optional fields use bitmap
        - Field presence is tracked in bitmap

        Args:
            byte_order: ByteOrder to use for packing. This overrides the struct_config's
                       byte_order setting.

        Returns:
            bytes: The packed binary data including header and optional bitmap.

        Raises:
            StructPackError: If packing fails
        """
        try:
            # Check for optional fields in the model
            has_optional = any(
                is_optional_type(field.annotation)
                for field in self.model_fields.values()
            )

            # Create bitmap and get present fields
            if has_optional:
                bitmap, present_fields = create_field_bitmap(self)
            else:
                bitmap = bytes([0])  # Empty bitmap
                present_fields = list(self.model_fields.keys())

            # Pack the data fields
            packed = b""
            if present_fields:
                # Get format string for present fields only, using provided byte order
                format_string = self.get_struct_format(
                    present_fields, byte_order=byte_order
                )
                values = []

                # Pack each present field using its handler
                for field_name in present_fields:
                    value = getattr(self, field_name)
                    values.append(
                        self._pack_value(field_name, value, byte_order=byte_order)
                    )

                packed = struct.pack(format_string, *values)

            # Create header - use provided byte order for header flags
            flags = HeaderFlags.LITTLE_ENDIAN
            if byte_order == ByteOrder.BIG_ENDIAN:
                flags |= HeaderFlags.BIG_ENDIAN
            if has_optional:
                flags |= HeaderFlags.HAS_OPTIONAL_FIELDS

            header = bytes(
                [
                    self.struct_config.version.value,  # Version
                    flags,  # Flags
                    0,  # Reserved
                    0,  # Reserved
                ]
            )

            return header + bitmap + packed

        except struct.error as e:
            raise StructPackError(f"Failed to pack struct data: {e}")

    @classmethod
    def from_bytes(
        cls: Type[T], data: bytes, override_endian: Optional[ByteOrder] = None
    ) -> T:
        """Create model instance from bytes using configured mode and version.

        Deserializes binary data back into a validated model instance. The input format
        must match the configured mode (C_COMPATIBLE or DYNAMIC). All field values are
        validated through Pydantic after unpacking.

        Args:
            data: The packed binary data to unpack. Must be exactly the right size for
                C_COMPATIBLE mode, or contain a valid header for DYNAMIC mode.
            override_endian: Optional ByteOrder to override the struct_config's endianness.
                            Used primarily for nested structs to match parent endianness.

        Returns:
            An instance of the model class with fields populated from the binary data.

        Raises:
            ValueError: If mode or version is unsupported.
            StructUnpackError: If unpacking fails due to truncated data, invalid header,
                or version mismatch.

        Example:
            >>> from pdc_struct import StructModel, StructConfig, StructMode, ByteOrder
            >>> from pdc_struct.c_types import UInt8, UInt16
            >>>
            >>> class Sensor(StructModel):
            ...     sensor_id: UInt8
            ...     reading: UInt16
            ...
            ...     struct_config = StructConfig(
            ...         mode=StructMode.C_COMPATIBLE,
            ...         byte_order=ByteOrder.BIG_ENDIAN
            ...     )
            >>>
            >>> # Parse binary data from a sensor device
            >>> raw_data = b'\\x01\\x03\\xe8'  # sensor_id=1, reading=1000
            >>> sensor = Sensor.from_bytes(raw_data)
            >>> sensor.sensor_id
            1
            >>> sensor.reading
            1000
        """
        # Validate version - currently only V1 is supported
        if cls.struct_config.version == StructVersion.V1:
            # Route based on mode
            match cls.struct_config.mode:
                case StructMode.C_COMPATIBLE:
                    return cls._from_bytes_v1_c_compatible(data, override_endian)
                case StructMode.DYNAMIC:
                    return cls._from_bytes_v1_dynamic(data, override_endian)
        # No defaults needed-We validate that the options are valid enum values in post init checks

    @classmethod
    def _from_bytes_v1_c_compatible(
        cls: Type[T], data: bytes, byte_order: Optional[ByteOrder] = None
    ) -> T:
        """Unpack data in C-compatible mode (V1).

        In C_COMPATIBLE mode:
        - No header to process
        - Fixed struct format
        - No optional fields

        Args:
            data: The packed binary data
            byte_order: Optional ByteOrder to override the struct_config's endianness.
                       Used primarily for nested structs to match parent endianness.

        Returns:
            An instance of the model class

        Raises:
            StructUnpackError: If unpacking fails
        """
        try:
            # Get format string with overridden byte order if provided
            format_string = cls.get_struct_format(byte_order=byte_order)

            # Unpack raw values
            values = struct.unpack(format_string, data)

            # Build field dictionary using handlers
            field_dict = {}
            for (field_name, field), value in zip(cls.model_fields.items(), values):
                field_dict[field_name] = cls._unpack_value(
                    field_name, value, byte_order=byte_order
                )

            return cls.model_validate(field_dict)

        except struct.error as e:
            raise StructUnpackError(f"Failed to unpack struct data: {e}")

    @classmethod
    def _from_bytes_v1_dynamic(
        cls: Type[T],
        data: bytes,
        ignore_header_endian: bool = False,
        byte_order: Optional[ByteOrder] = None,
    ) -> T:
        """Unpack data in dynamic mode (V1).

        In DYNAMIC mode:
        - Header must be processed
        - Optional fields use bitmap
        - Field presence tracked in bitmap

        Args:
            data: The packed binary data
            ignore_header_endian: If True, uses provided byte_order or model's configured
                                byte order instead of the one specified in the header
            byte_order: Optional ByteOrder to override the struct_config's endianness.
                       Used primarily for nested structs to match parent endianness.
                       Only used if ignore_header_endian is True.

        Returns:
            An instance of the model class

        Raises:
            StructUnpackError: If unpacking fails
        """
        try:
            # Set initial byte order from override or config
            effective_byte_order = byte_order or cls.struct_config.byte_order

            # Handle header
            if len(data) < 4:
                raise StructUnpackError("Data too short to contain header")

            version_byte, flags = data[0], data[1]
            data = data[4:]  # Skip header

            # Verify version
            try:
                version = StructVersion(version_byte)
            except ValueError:
                raise StructUnpackError(f"Unsupported struct version: {version_byte}")

            if version != cls.struct_config.version:
                raise StructUnpackError(
                    f"Version mismatch: expected {cls.struct_config.version}, got {version}"
                )

            # Check endianness from header unless ignored
            if not ignore_header_endian:
                effective_byte_order = (
                    ByteOrder.BIG_ENDIAN
                    if flags & HeaderFlags.BIG_ENDIAN
                    else ByteOrder.LITTLE_ENDIAN
                )

            # Handle optional fields
            if flags & HeaderFlags.HAS_OPTIONAL_FIELDS:
                data, present_fields = parse_field_bitmap(data, cls)
            else:
                # Skip empty bitmap byte
                data = data[1:]
                present_fields = list(cls.model_fields.keys())

            # If no fields present in completely optional model
            if not present_fields:
                field_dict = {name: None for name in cls.model_fields.keys()}
                return cls.model_validate(field_dict)

            # Create format string and unpack using effective byte order
            format_string = (
                effective_byte_order.value + cls.get_struct_format(present_fields)[1:]
            )
            values = struct.unpack(format_string, data)

            # Build field dictionary using handlers
            field_dict = {}
            for name, value in zip(present_fields, values):
                field_dict[name] = cls._unpack_value(
                    name, value, byte_order=effective_byte_order
                )

            # Set None for missing optional fields
            for name, field in cls.model_fields.items():
                if name not in field_dict and is_optional_type(field.annotation):
                    field_dict[name] = None

            return cls.model_validate(field_dict)

        except struct.error as e:
            raise StructUnpackError(f"Failed to unpack struct data: {e}")

struct_config = StructConfig() class-attribute

clone(**field_updates)

Create a new instance with the same field values, optionally overriding specific fields.

This method creates a copy of the current instance through serialization/deserialization, then applies any provided field updates. Useful for creating variations of an existing struct without modifying the original.

Parameters:

Name Type Description Default
**field_updates Any

Field values to override in the new instance. Any fields not specified will retain their values from the current instance.

{}

Returns:

Type Description
StructModel

A new instance of the same class with the specified updates applied.

Example

from pdc_struct import StructModel, StructConfig, StructMode

class Point(StructModel): ... x: float ... y: float ... z: float ... ... struct_config = StructConfig(mode=StructMode.C_COMPATIBLE)

origin = Point(x=0.0, y=0.0, z=0.0)

Create a new point with only z changed

elevated = origin.clone(z=10.0) elevated.x, elevated.y, elevated.z (0.0, 0.0, 10.0)

Original is unchanged

origin.z 0.0

Source code in pdc_struct/models/struct_model.py
def clone(self, **field_updates: Any) -> "StructModel":
    """Create a new instance with the same field values, optionally overriding specific fields.

    This method creates a copy of the current instance through serialization/deserialization,
    then applies any provided field updates. Useful for creating variations of an existing
    struct without modifying the original.

    Args:
        **field_updates: Field values to override in the new instance.
            Any fields not specified will retain their values from the current instance.

    Returns:
        A new instance of the same class with the specified updates applied.

    Example:
        >>> from pdc_struct import StructModel, StructConfig, StructMode
        >>>
        >>> class Point(StructModel):
        ...     x: float
        ...     y: float
        ...     z: float
        ...
        ...     struct_config = StructConfig(mode=StructMode.C_COMPATIBLE)
        >>>
        >>> origin = Point(x=0.0, y=0.0, z=0.0)
        >>> # Create a new point with only z changed
        >>> elevated = origin.clone(z=10.0)
        >>> elevated.x, elevated.y, elevated.z
        (0.0, 0.0, 10.0)
        >>> # Original is unchanged
        >>> origin.z
        0.0
    """
    return self.__class__(packed_value=self.to_bytes(), **field_updates)

struct_format_string() classmethod

Get the struct format string that would be used for packing/unpacking.

Returns the struct format string that represents the complete model, including byte order and all fields.

Returns:

Name Type Description
str str

The struct format string (e.g. '<dds10s?' for little-endian double, double, 10-char string, bool).

Example

from pydantic import Field from pdc_struct import StructModel, StructConfig, ByteOrder, StructVersion

class Point(StructModel): ... x: float = Field(description="X coordinate") ... y: float = Field(description="Y coordinate") ... label: str = Field(json_schema_extra={"max_length": 10}, description="Point label") ... active: bool = Field(default=True, description="Whether point is active") ... ... struct_config = StructConfig( ... include_header=True, ... version=StructVersion.V1, ... byte_order=ByteOrder.LITTLE_ENDIAN ... )

Point.struct_format_string() '<dd10s?'

Source code in pdc_struct/models/struct_model.py
@classmethod
def struct_format_string(cls) -> str:
    """Get the struct format string that would be used for packing/unpacking.

    Returns the struct format string that represents the complete model, including
    byte order and all fields.

    Returns:
        str: The struct format string (e.g. '<dds10s?' for little-endian double,
            double, 10-char string, bool).

    Example:
        >>> from pydantic import Field
        >>> from pdc_struct import StructModel, StructConfig, ByteOrder, StructVersion
        >>>
        >>> class Point(StructModel):
        ...     x: float = Field(description="X coordinate")
        ...     y: float = Field(description="Y coordinate")
        ...     label: str = Field(json_schema_extra={"max_length": 10}, description="Point label")
        ...     active: bool = Field(default=True, description="Whether point is active")
        ...
        ...     struct_config = StructConfig(
        ...         include_header=True,
        ...         version=StructVersion.V1,
        ...         byte_order=ByteOrder.LITTLE_ENDIAN
        ...     )
        >>>
        >>> Point.struct_format_string()
        '<dd10s?'
    """
    return cls.get_struct_format()

struct_size() classmethod

Return the size in bytes of the struct when packed.

For C_COMPATIBLE mode this is the exact size. For DYNAMIC mode this is less relevant as optional data is not packed - largest possible size is returned

Source code in pdc_struct/models/struct_model.py
@classmethod
def struct_size(cls) -> int:
    """Return the size in bytes of the struct when packed.

    For C_COMPATIBLE mode this is the exact size.
    For DYNAMIC mode this is less relevant as optional data is not packed - largest possible size is returned
    """
    return struct.calcsize(cls.struct_format_string())

to_bytes(override_endian=None)

Convert model instance to bytes using configured mode and version.

Serializes the model's field values into a binary representation suitable for storage, network transmission, or C interoperability. The output format depends on the configured mode (C_COMPATIBLE or DYNAMIC).

Parameters:

Name Type Description Default
override_endian Optional[ByteOrder]

Optional ByteOrder to override the struct_config's endianness. Used primarily for nested structs to match parent endianness.

None

Returns:

Name Type Description
bytes bytes

The packed binary data according to the configured mode.

Raises:

Type Description
ValueError

If mode or version is unsupported.

StructPackError

If packing fails due to invalid field values.

Example

from pdc_struct import StructModel, StructConfig, StructMode, ByteOrder

class Point(StructModel): ... x: float ... y: float ... ... struct_config = StructConfig( ... mode=StructMode.C_COMPATIBLE, ... byte_order=ByteOrder.LITTLE_ENDIAN ... )

point = Point(x=1.0, y=2.0) data = point.to_bytes() len(data) 16

Restore the point from bytes

restored = Point.from_bytes(data) restored.x, restored.y (1.0, 2.0)

Source code in pdc_struct/models/struct_model.py
def to_bytes(self, override_endian: Optional[ByteOrder] = None) -> bytes:
    """Convert model instance to bytes using configured mode and version.

    Serializes the model's field values into a binary representation suitable for
    storage, network transmission, or C interoperability. The output format depends
    on the configured mode (C_COMPATIBLE or DYNAMIC).

    Args:
        override_endian: Optional ByteOrder to override the struct_config's endianness.
                        Used primarily for nested structs to match parent endianness.

    Returns:
        bytes: The packed binary data according to the configured mode.

    Raises:
        ValueError: If mode or version is unsupported.
        StructPackError: If packing fails due to invalid field values.

    Example:
        >>> from pdc_struct import StructModel, StructConfig, StructMode, ByteOrder
        >>>
        >>> class Point(StructModel):
        ...     x: float
        ...     y: float
        ...
        ...     struct_config = StructConfig(
        ...         mode=StructMode.C_COMPATIBLE,
        ...         byte_order=ByteOrder.LITTLE_ENDIAN
        ...     )
        >>>
        >>> point = Point(x=1.0, y=2.0)
        >>> data = point.to_bytes()
        >>> len(data)
        16
        >>> # Restore the point from bytes
        >>> restored = Point.from_bytes(data)
        >>> restored.x, restored.y
        (1.0, 2.0)
    """
    # Validate version - currently only V1 is supported
    if self.struct_config.version != StructVersion.V1:
        raise ValueError(
            f"Unsupported struct version: {self.struct_config.version}"
        )

    # Get effective byte order
    byte_order = override_endian or self.struct_config.byte_order

    # Route based on mode
    match self.struct_config.mode:
        case StructMode.C_COMPATIBLE:
            return self._to_bytes_v1_c_compatible(byte_order)
        case StructMode.DYNAMIC:
            return self._to_bytes_v1_dynamic(byte_order)
        case _:
            raise ValueError(f"Unsupported mode: {self.struct_config.mode}")

from_bytes(data, override_endian=None) classmethod

Create model instance from bytes using configured mode and version.

Deserializes binary data back into a validated model instance. The input format must match the configured mode (C_COMPATIBLE or DYNAMIC). All field values are validated through Pydantic after unpacking.

Parameters:

Name Type Description Default
data bytes

The packed binary data to unpack. Must be exactly the right size for C_COMPATIBLE mode, or contain a valid header for DYNAMIC mode.

required
override_endian Optional[ByteOrder]

Optional ByteOrder to override the struct_config's endianness. Used primarily for nested structs to match parent endianness.

None

Returns:

Type Description
T

An instance of the model class with fields populated from the binary data.

Raises:

Type Description
ValueError

If mode or version is unsupported.

StructUnpackError

If unpacking fails due to truncated data, invalid header, or version mismatch.

Example

from pdc_struct import StructModel, StructConfig, StructMode, ByteOrder from pdc_struct.c_types import UInt8, UInt16

class Sensor(StructModel): ... sensor_id: UInt8 ... reading: UInt16 ... ... struct_config = StructConfig( ... mode=StructMode.C_COMPATIBLE, ... byte_order=ByteOrder.BIG_ENDIAN ... )

Parse binary data from a sensor device

raw_data = b'\x01\x03\xe8' # sensor_id=1, reading=1000 sensor = Sensor.from_bytes(raw_data) sensor.sensor_id 1 sensor.reading 1000

Source code in pdc_struct/models/struct_model.py
@classmethod
def from_bytes(
    cls: Type[T], data: bytes, override_endian: Optional[ByteOrder] = None
) -> T:
    """Create model instance from bytes using configured mode and version.

    Deserializes binary data back into a validated model instance. The input format
    must match the configured mode (C_COMPATIBLE or DYNAMIC). All field values are
    validated through Pydantic after unpacking.

    Args:
        data: The packed binary data to unpack. Must be exactly the right size for
            C_COMPATIBLE mode, or contain a valid header for DYNAMIC mode.
        override_endian: Optional ByteOrder to override the struct_config's endianness.
                        Used primarily for nested structs to match parent endianness.

    Returns:
        An instance of the model class with fields populated from the binary data.

    Raises:
        ValueError: If mode or version is unsupported.
        StructUnpackError: If unpacking fails due to truncated data, invalid header,
            or version mismatch.

    Example:
        >>> from pdc_struct import StructModel, StructConfig, StructMode, ByteOrder
        >>> from pdc_struct.c_types import UInt8, UInt16
        >>>
        >>> class Sensor(StructModel):
        ...     sensor_id: UInt8
        ...     reading: UInt16
        ...
        ...     struct_config = StructConfig(
        ...         mode=StructMode.C_COMPATIBLE,
        ...         byte_order=ByteOrder.BIG_ENDIAN
        ...     )
        >>>
        >>> # Parse binary data from a sensor device
        >>> raw_data = b'\\x01\\x03\\xe8'  # sensor_id=1, reading=1000
        >>> sensor = Sensor.from_bytes(raw_data)
        >>> sensor.sensor_id
        1
        >>> sensor.reading
        1000
    """
    # Validate version - currently only V1 is supported
    if cls.struct_config.version == StructVersion.V1:
        # Route based on mode
        match cls.struct_config.mode:
            case StructMode.C_COMPATIBLE:
                return cls._from_bytes_v1_c_compatible(data, override_endian)
            case StructMode.DYNAMIC:
                return cls._from_bytes_v1_dynamic(data, override_endian)

get_struct_format(present_fields=None, byte_order=None) classmethod

Generate struct format string from model fields.

Parameters:

Name Type Description Default
present_fields Optional[list]

Optional list of fields to include in format string. If None, includes all fields.

None
byte_order Optional[ByteOrder]

Optional ByteOrder to override the struct_config's endianness. Used primarily for nested structs to match parent endianness.

None
Source code in pdc_struct/models/struct_model.py
@classmethod
def get_struct_format(
    cls,
    present_fields: Optional[list] = None,
    byte_order: Optional[ByteOrder] = None,
) -> str:
    """Generate struct format string from model fields.

    Args:
        present_fields: Optional list of fields to include in format string.
                       If None, includes all fields.
        byte_order: Optional ByteOrder to override the struct_config's endianness.
                   Used primarily for nested structs to match parent endianness.
    """
    format_parts = []
    fields_to_process = (
        present_fields or cls.model_fields.keys()
    )  # noqa - model_fields property returns dict

    for field_name in fields_to_process:
        field = cls.model_fields[
            field_name
        ]  # noqa - model_fields property returns dict
        handler = cls._field_handlers[field_name]
        format_parts.append(handler.get_struct_format(field))

    # Use override_endian if provided, otherwise use struct_config's byte_order
    effective_byte_order = byte_order or cls.struct_config.byte_order
    return effective_byte_order.value + "".join(format_parts)

See Also