Skip to content

Headerutil

Cross-platform binary header serialization utilities.

This module provides tools for creating fixed-size binary headers that maintain metadata about files in a cross-platform, non-user-readable format.

BinaryHeaderCodec

A robust codec for serializing and deserializing fixed-size binary headers.

This class provides a clean API for packing and unpacking various data types to/from binary format, with consistent endianness handling and comprehensive error checking. Designed for creating cross-platform file headers in binary form.

Parameters:

Name Type Description Default
endianness Endianness

Byte order for serialization (default: NETWORK)

NETWORK
Example

codec = BinaryHeaderCodec(Endianness.NETWORK) data = codec.pack_uint32(42) value = codec.unpack_uint32(data) assert value == 42

Source code in bionemo/scdl/schema/headerutil.py
 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
class BinaryHeaderCodec:
    """A robust codec for serializing and deserializing fixed-size binary headers.

    This class provides a clean API for packing and unpacking various data types
    to/from binary format, with consistent endianness handling and comprehensive
    error checking. Designed for creating cross-platform file headers in binary form.

    Args:
        endianness: Byte order for serialization (default: NETWORK)

    Example:
        >>> codec = BinaryHeaderCodec(Endianness.NETWORK)
        >>> data = codec.pack_uint32(42)
        >>> value = codec.unpack_uint32(data)
        >>> assert value == 42
    """

    def __init__(self, endianness: Endianness = Endianness.NETWORK):
        """Initialize the codec with specified byte order."""
        self.endianness = endianness.value

    # Integer packing/unpacking methods

    def pack_uint8(self, value: int) -> bytes:
        """Pack an 8-bit unsigned integer.

        Args:
            value: Integer value (0-255)

        Returns:
            1-byte binary representation

        Raises:
            HeaderSerializationError: If value is out of range
        """
        self._validate_uint_range(value, 0, 255, "uint8")
        return struct.pack(f"{self.endianness}B", value)

    def unpack_uint8(self, data: bytes) -> int:
        """Unpack an 8-bit unsigned integer.

        Args:
            data: Binary data (must be at least 1 byte)

        Returns:
            Unpacked integer value

        Raises:
            HeaderSerializationError: If data is insufficient or invalid
        """
        self._validate_data_length(data, 1, "uint8")
        return struct.unpack(f"{self.endianness}B", data[:1])[0]

    def pack_uint16(self, value: int) -> bytes:
        """Pack a 16-bit unsigned integer.

        Args:
            value: Integer value (0-65535)

        Returns:
            2-byte binary representation

        Raises:
            HeaderSerializationError: If value is out of range
        """
        self._validate_uint_range(value, 0, 65535, "uint16")
        return struct.pack(f"{self.endianness}H", value)

    def unpack_uint16(self, data: bytes) -> int:
        """Unpack a 16-bit unsigned integer.

        Args:
            data: Binary data (must be at least 2 bytes)

        Returns:
            Unpacked integer value

        Raises:
            HeaderSerializationError: If data is insufficient or invalid
        """
        self._validate_data_length(data, 2, "uint16")
        return struct.unpack(f"{self.endianness}H", data[:2])[0]

    def pack_uint32(self, value: int) -> bytes:
        """Pack a 32-bit unsigned integer.

        Args:
            value: Integer value (0-4294967295)

        Returns:
            4-byte binary representation

        Raises:
            HeaderSerializationError: If value is out of range
        """
        self._validate_uint_range(value, 0, 4294967295, "uint32")
        return struct.pack(f"{self.endianness}I", value)

    def unpack_uint32(self, data: bytes) -> int:
        """Unpack a 32-bit unsigned integer.

        Args:
            data: Binary data (must be at least 4 bytes)

        Returns:
            Unpacked integer value

        Raises:
            HeaderSerializationError: If data is insufficient or invalid
        """
        self._validate_data_length(data, 4, "uint32")
        return struct.unpack(f"{self.endianness}I", data[:4])[0]

    def pack_uint64(self, value: int) -> bytes:
        """Pack a 64-bit unsigned integer.

        Args:
            value: Integer value (0-18446744073709551615)

        Returns:
            8-byte binary representation

        Raises:
            HeaderSerializationError: If value is out of range
        """
        self._validate_uint_range(value, 0, 18446744073709551615, "uint64")
        return struct.pack(f"{self.endianness}Q", value)

    def unpack_uint64(self, data: bytes) -> int:
        """Unpack a 64-bit unsigned integer.

        Args:
            data: Binary data (must be at least 8 bytes)

        Returns:
            Unpacked integer value

        Raises:
            HeaderSerializationError: If data is insufficient or invalid
        """
        self._validate_data_length(data, 8, "uint64")
        return struct.unpack(f"{self.endianness}Q", data[:8])[0]

    # Floating point packing/unpacking methods

    def pack_float16(self, value: float) -> bytes:
        """Pack a 16-bit (half-precision) floating point number.

        Args:
            value: Float value

        Returns:
            2-byte binary representation

        Raises:
            HeaderSerializationError: If value cannot be represented
        """
        try:
            return struct.pack(f"{self.endianness}e", value)
        except (struct.error, OverflowError) as e:
            raise HeaderSerializationError(f"Cannot pack float16 value {value}: {e}")

    def unpack_float16(self, data: bytes) -> float:
        """Unpack a 16-bit (half-precision) floating point number.

        Args:
            data: Binary data (must be at least 2 bytes)

        Returns:
            Unpacked float value

        Raises:
            HeaderSerializationError: If data is insufficient or invalid
        """
        self._validate_data_length(data, 2, "float16")
        return struct.unpack(f"{self.endianness}e", data[:2])[0]

    def pack_float32(self, value: float) -> bytes:
        """Pack a 32-bit (single-precision) floating point number.

        Args:
            value: Float value

        Returns:
            4-byte binary representation

        Raises:
            HeaderSerializationError: If value cannot be represented
        """
        try:
            return struct.pack(f"{self.endianness}f", value)
        except (struct.error, OverflowError) as e:
            raise HeaderSerializationError(f"Cannot pack float32 value {value}: {e}")

    def unpack_float32(self, data: bytes) -> float:
        """Unpack a 32-bit (single-precision) floating point number.

        Args:
            data: Binary data (must be at least 4 bytes)

        Returns:
            Unpacked float value

        Raises:
            HeaderSerializationError: If data is insufficient or invalid
        """
        self._validate_data_length(data, 4, "float32")
        return struct.unpack(f"{self.endianness}f", data[:4])[0]

    # String and array methods (for variable-length data)

    def pack_string(self, value: str, max_length: int | None = None) -> bytes:
        """Pack a UTF-8 string with length prefix.

        Args:
            value: String to pack
            max_length: Optional maximum length limit

        Returns:
            Binary data: 4-byte length + UTF-8 encoded string

        Raises:
            HeaderSerializationError: If string is too long or encoding fails
        """
        if not isinstance(value, str):
            raise HeaderSerializationError(f"Expected string, got {type(value)}")

        try:
            encoded_string = value.encode("utf-8")
        except UnicodeEncodeError as e:
            raise HeaderSerializationError(f"Cannot encode string to UTF-8: {e}")

        length = len(encoded_string)

        if max_length is not None and length > max_length:
            raise HeaderSerializationError(f"String too long: {length} bytes > {max_length} bytes limit")

        return self.pack_uint32(length) + encoded_string

    def unpack_string(self, data: bytes, max_length: int | None = None) -> Tuple[str, int]:
        """Unpack a UTF-8 string with length prefix.

        Args:
            data: Binary data starting with 4-byte length prefix
            max_length: Optional maximum length limit

        Returns:
            Tuple of (unpacked string, total bytes consumed)

        Raises:
            HeaderSerializationError: If data is invalid or string too long
        """
        if len(data) < 4:
            raise HeaderSerializationError("Insufficient data for string length")

        length = self.unpack_uint32(data[:4])

        if max_length is not None and length > max_length:
            raise HeaderSerializationError(f"String too long: {length} bytes > {max_length} bytes limit")

        if len(data) < 4 + length:
            raise HeaderSerializationError(f"Insufficient data for string: need {4 + length} bytes, got {len(data)}")

        try:
            string_value = data[4 : 4 + length].decode("utf-8")
        except UnicodeDecodeError as e:
            raise HeaderSerializationError(f"Cannot decode UTF-8 string: {e}")

        return string_value, 4 + length

    def pack_fixed_string(self, value: str, size: int, padding: bytes = b"\x00") -> bytes:
        """Pack a string into a fixed-size field with padding.

        Useful for creating truly fixed-size headers where string fields
        have a predetermined maximum size.

        Args:
            value: String to pack
            size: Fixed size of the field in bytes
            padding: Byte value to use for padding (default: null bytes)

        Returns:
            Fixed-size binary data

        Raises:
            HeaderSerializationError: If string is too long or parameters invalid
        """
        if not isinstance(value, str):
            raise HeaderSerializationError(f"Expected string, got {type(value)}")

        if size <= 0:
            raise HeaderSerializationError(f"Size must be positive, got {size}")

        if len(padding) != 1:
            raise HeaderSerializationError(f"Padding must be single byte, got {len(padding)} bytes")

        try:
            encoded = value.encode("utf-8")
        except UnicodeEncodeError as e:
            raise HeaderSerializationError(f"Cannot encode string to UTF-8: {e}")

        if len(encoded) > size:
            raise HeaderSerializationError(f"String too long: {len(encoded)} bytes > {size} bytes field size")

        return encoded + padding * (size - len(encoded))

    def unpack_fixed_string(self, data: bytes, size: int, padding: bytes = b"\x00") -> str:
        """Unpack a string from a fixed-size field, removing padding.

        Args:
            data: Binary data (must be at least size bytes)
            size: Size of the fixed field in bytes
            padding: Padding byte to strip (default: null bytes)

        Returns:
            Unpacked string with padding removed

        Raises:
            HeaderSerializationError: If data is insufficient or invalid
        """
        if len(data) < size:
            raise HeaderSerializationError(f"Insufficient data: need {size} bytes, got {len(data)}")

        if len(padding) != 1:
            raise HeaderSerializationError(f"Padding must be single byte, got {len(padding)} bytes")

        field_data = data[:size]
        # Remove trailing padding
        string_data = field_data.rstrip(padding)

        try:
            return string_data.decode("utf-8")
        except UnicodeDecodeError as e:
            raise HeaderSerializationError(f"Cannot decode UTF-8 string: {e}")

    # Validation helper methods

    def _validate_uint_range(self, value: int, min_val: int, max_val: int, type_name: str) -> None:
        """Validate that an integer value is within the valid range for its type."""
        if not isinstance(value, int):
            raise HeaderSerializationError(f"Expected integer for {type_name}, got {type(value)}")

        if value < min_val or value > max_val:
            raise HeaderSerializationError(f"{type_name} value {value} out of range [{min_val}, {max_val}]")

    def _validate_data_length(self, data: bytes, required_length: int, type_name: str) -> None:
        """Validate that data has sufficient length for unpacking."""
        if not isinstance(data, (bytes, bytearray)):
            raise HeaderSerializationError(f"Expected bytes for {type_name}, got {type(data)}")

        if len(data) < required_length:
            raise HeaderSerializationError(
                f"Insufficient data for {type_name}: need {required_length} bytes, got {len(data)}"
            )

    # Utility methods for working with headers

    def calculate_header_size(self, field_specs: List[Tuple[str, Union[int, str]]]) -> int:
        """Calculate the total size of a header given field specifications.

        Args:
            field_specs: List of (field_type, size) tuples where:
                - field_type: 'uint8', 'uint16', 'uint32', 'uint64', 'float16', 'float32', 'fixed_string'
                - size: For fixed_string, the size in bytes; ignored for other types

        Returns:
            Total header size in bytes

        Example:
            >>> codec = BinaryHeaderCodec()
            >>> size = codec.calculate_header_size([
            ...     ('uint32', None),      # 4 bytes
            ...     ('uint16', None),      # 2 bytes
            ...     ('fixed_string', 64),  # 64 bytes
            ...     ('float32', None)      # 4 bytes
            ... ])
            >>> assert size == 74
        """
        size_map = {"uint8": 1, "uint16": 2, "uint32": 4, "uint64": 8, "float16": 2, "float32": 4}

        total_size = 0
        for field_type, field_size in field_specs:
            if field_type == "fixed_string":
                if not isinstance(field_size, int) or field_size <= 0:
                    raise HeaderSerializationError(f"fixed_string requires positive integer size, got {field_size}")
                total_size += field_size
            elif field_type in size_map:
                total_size += size_map[field_type]
            else:
                raise HeaderSerializationError(f"Unknown field type: {field_type}")

        return total_size

__init__(endianness=Endianness.NETWORK)

Initialize the codec with specified byte order.

Source code in bionemo/scdl/schema/headerutil.py
62
63
64
def __init__(self, endianness: Endianness = Endianness.NETWORK):
    """Initialize the codec with specified byte order."""
    self.endianness = endianness.value

calculate_header_size(field_specs)

Calculate the total size of a header given field specifications.

Parameters:

Name Type Description Default
field_specs List[Tuple[str, Union[int, str]]]

List of (field_type, size) tuples where: - field_type: 'uint8', 'uint16', 'uint32', 'uint64', 'float16', 'float32', 'fixed_string' - size: For fixed_string, the size in bytes; ignored for other types

required

Returns:

Type Description
int

Total header size in bytes

Example

codec = BinaryHeaderCodec() size = codec.calculate_header_size([ ... ('uint32', None), # 4 bytes ... ('uint16', None), # 2 bytes ... ('fixed_string', 64), # 64 bytes ... ('float32', None) # 4 bytes ... ]) assert size == 74

Source code in bionemo/scdl/schema/headerutil.py
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
def calculate_header_size(self, field_specs: List[Tuple[str, Union[int, str]]]) -> int:
    """Calculate the total size of a header given field specifications.

    Args:
        field_specs: List of (field_type, size) tuples where:
            - field_type: 'uint8', 'uint16', 'uint32', 'uint64', 'float16', 'float32', 'fixed_string'
            - size: For fixed_string, the size in bytes; ignored for other types

    Returns:
        Total header size in bytes

    Example:
        >>> codec = BinaryHeaderCodec()
        >>> size = codec.calculate_header_size([
        ...     ('uint32', None),      # 4 bytes
        ...     ('uint16', None),      # 2 bytes
        ...     ('fixed_string', 64),  # 64 bytes
        ...     ('float32', None)      # 4 bytes
        ... ])
        >>> assert size == 74
    """
    size_map = {"uint8": 1, "uint16": 2, "uint32": 4, "uint64": 8, "float16": 2, "float32": 4}

    total_size = 0
    for field_type, field_size in field_specs:
        if field_type == "fixed_string":
            if not isinstance(field_size, int) or field_size <= 0:
                raise HeaderSerializationError(f"fixed_string requires positive integer size, got {field_size}")
            total_size += field_size
        elif field_type in size_map:
            total_size += size_map[field_type]
        else:
            raise HeaderSerializationError(f"Unknown field type: {field_type}")

    return total_size

pack_fixed_string(value, size, padding=b'\x00')

Pack a string into a fixed-size field with padding.

Useful for creating truly fixed-size headers where string fields have a predetermined maximum size.

Parameters:

Name Type Description Default
value str

String to pack

required
size int

Fixed size of the field in bytes

required
padding bytes

Byte value to use for padding (default: null bytes)

b'\x00'

Returns:

Type Description
bytes

Fixed-size binary data

Raises:

Type Description
HeaderSerializationError

If string is too long or parameters invalid

Source code in bionemo/scdl/schema/headerutil.py
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
def pack_fixed_string(self, value: str, size: int, padding: bytes = b"\x00") -> bytes:
    """Pack a string into a fixed-size field with padding.

    Useful for creating truly fixed-size headers where string fields
    have a predetermined maximum size.

    Args:
        value: String to pack
        size: Fixed size of the field in bytes
        padding: Byte value to use for padding (default: null bytes)

    Returns:
        Fixed-size binary data

    Raises:
        HeaderSerializationError: If string is too long or parameters invalid
    """
    if not isinstance(value, str):
        raise HeaderSerializationError(f"Expected string, got {type(value)}")

    if size <= 0:
        raise HeaderSerializationError(f"Size must be positive, got {size}")

    if len(padding) != 1:
        raise HeaderSerializationError(f"Padding must be single byte, got {len(padding)} bytes")

    try:
        encoded = value.encode("utf-8")
    except UnicodeEncodeError as e:
        raise HeaderSerializationError(f"Cannot encode string to UTF-8: {e}")

    if len(encoded) > size:
        raise HeaderSerializationError(f"String too long: {len(encoded)} bytes > {size} bytes field size")

    return encoded + padding * (size - len(encoded))

pack_float16(value)

Pack a 16-bit (half-precision) floating point number.

Parameters:

Name Type Description Default
value float

Float value

required

Returns:

Type Description
bytes

2-byte binary representation

Raises:

Type Description
HeaderSerializationError

If value cannot be represented

Source code in bionemo/scdl/schema/headerutil.py
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
def pack_float16(self, value: float) -> bytes:
    """Pack a 16-bit (half-precision) floating point number.

    Args:
        value: Float value

    Returns:
        2-byte binary representation

    Raises:
        HeaderSerializationError: If value cannot be represented
    """
    try:
        return struct.pack(f"{self.endianness}e", value)
    except (struct.error, OverflowError) as e:
        raise HeaderSerializationError(f"Cannot pack float16 value {value}: {e}")

pack_float32(value)

Pack a 32-bit (single-precision) floating point number.

Parameters:

Name Type Description Default
value float

Float value

required

Returns:

Type Description
bytes

4-byte binary representation

Raises:

Type Description
HeaderSerializationError

If value cannot be represented

Source code in bionemo/scdl/schema/headerutil.py
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
def pack_float32(self, value: float) -> bytes:
    """Pack a 32-bit (single-precision) floating point number.

    Args:
        value: Float value

    Returns:
        4-byte binary representation

    Raises:
        HeaderSerializationError: If value cannot be represented
    """
    try:
        return struct.pack(f"{self.endianness}f", value)
    except (struct.error, OverflowError) as e:
        raise HeaderSerializationError(f"Cannot pack float32 value {value}: {e}")

pack_string(value, max_length=None)

Pack a UTF-8 string with length prefix.

Parameters:

Name Type Description Default
value str

String to pack

required
max_length int | None

Optional maximum length limit

None

Returns:

Type Description
bytes

Binary data: 4-byte length + UTF-8 encoded string

Raises:

Type Description
HeaderSerializationError

If string is too long or encoding fails

Source code in bionemo/scdl/schema/headerutil.py
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
def pack_string(self, value: str, max_length: int | None = None) -> bytes:
    """Pack a UTF-8 string with length prefix.

    Args:
        value: String to pack
        max_length: Optional maximum length limit

    Returns:
        Binary data: 4-byte length + UTF-8 encoded string

    Raises:
        HeaderSerializationError: If string is too long or encoding fails
    """
    if not isinstance(value, str):
        raise HeaderSerializationError(f"Expected string, got {type(value)}")

    try:
        encoded_string = value.encode("utf-8")
    except UnicodeEncodeError as e:
        raise HeaderSerializationError(f"Cannot encode string to UTF-8: {e}")

    length = len(encoded_string)

    if max_length is not None and length > max_length:
        raise HeaderSerializationError(f"String too long: {length} bytes > {max_length} bytes limit")

    return self.pack_uint32(length) + encoded_string

pack_uint16(value)

Pack a 16-bit unsigned integer.

Parameters:

Name Type Description Default
value int

Integer value (0-65535)

required

Returns:

Type Description
bytes

2-byte binary representation

Raises:

Type Description
HeaderSerializationError

If value is out of range

Source code in bionemo/scdl/schema/headerutil.py
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
def pack_uint16(self, value: int) -> bytes:
    """Pack a 16-bit unsigned integer.

    Args:
        value: Integer value (0-65535)

    Returns:
        2-byte binary representation

    Raises:
        HeaderSerializationError: If value is out of range
    """
    self._validate_uint_range(value, 0, 65535, "uint16")
    return struct.pack(f"{self.endianness}H", value)

pack_uint32(value)

Pack a 32-bit unsigned integer.

Parameters:

Name Type Description Default
value int

Integer value (0-4294967295)

required

Returns:

Type Description
bytes

4-byte binary representation

Raises:

Type Description
HeaderSerializationError

If value is out of range

Source code in bionemo/scdl/schema/headerutil.py
128
129
130
131
132
133
134
135
136
137
138
139
140
141
def pack_uint32(self, value: int) -> bytes:
    """Pack a 32-bit unsigned integer.

    Args:
        value: Integer value (0-4294967295)

    Returns:
        4-byte binary representation

    Raises:
        HeaderSerializationError: If value is out of range
    """
    self._validate_uint_range(value, 0, 4294967295, "uint32")
    return struct.pack(f"{self.endianness}I", value)

pack_uint64(value)

Pack a 64-bit unsigned integer.

Parameters:

Name Type Description Default
value int

Integer value (0-18446744073709551615)

required

Returns:

Type Description
bytes

8-byte binary representation

Raises:

Type Description
HeaderSerializationError

If value is out of range

Source code in bionemo/scdl/schema/headerutil.py
158
159
160
161
162
163
164
165
166
167
168
169
170
171
def pack_uint64(self, value: int) -> bytes:
    """Pack a 64-bit unsigned integer.

    Args:
        value: Integer value (0-18446744073709551615)

    Returns:
        8-byte binary representation

    Raises:
        HeaderSerializationError: If value is out of range
    """
    self._validate_uint_range(value, 0, 18446744073709551615, "uint64")
    return struct.pack(f"{self.endianness}Q", value)

pack_uint8(value)

Pack an 8-bit unsigned integer.

Parameters:

Name Type Description Default
value int

Integer value (0-255)

required

Returns:

Type Description
bytes

1-byte binary representation

Raises:

Type Description
HeaderSerializationError

If value is out of range

Source code in bionemo/scdl/schema/headerutil.py
68
69
70
71
72
73
74
75
76
77
78
79
80
81
def pack_uint8(self, value: int) -> bytes:
    """Pack an 8-bit unsigned integer.

    Args:
        value: Integer value (0-255)

    Returns:
        1-byte binary representation

    Raises:
        HeaderSerializationError: If value is out of range
    """
    self._validate_uint_range(value, 0, 255, "uint8")
    return struct.pack(f"{self.endianness}B", value)

unpack_fixed_string(data, size, padding=b'\x00')

Unpack a string from a fixed-size field, removing padding.

Parameters:

Name Type Description Default
data bytes

Binary data (must be at least size bytes)

required
size int

Size of the fixed field in bytes

required
padding bytes

Padding byte to strip (default: null bytes)

b'\x00'

Returns:

Type Description
str

Unpacked string with padding removed

Raises:

Type Description
HeaderSerializationError

If data is insufficient or invalid

Source code in bionemo/scdl/schema/headerutil.py
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
def unpack_fixed_string(self, data: bytes, size: int, padding: bytes = b"\x00") -> str:
    """Unpack a string from a fixed-size field, removing padding.

    Args:
        data: Binary data (must be at least size bytes)
        size: Size of the fixed field in bytes
        padding: Padding byte to strip (default: null bytes)

    Returns:
        Unpacked string with padding removed

    Raises:
        HeaderSerializationError: If data is insufficient or invalid
    """
    if len(data) < size:
        raise HeaderSerializationError(f"Insufficient data: need {size} bytes, got {len(data)}")

    if len(padding) != 1:
        raise HeaderSerializationError(f"Padding must be single byte, got {len(padding)} bytes")

    field_data = data[:size]
    # Remove trailing padding
    string_data = field_data.rstrip(padding)

    try:
        return string_data.decode("utf-8")
    except UnicodeDecodeError as e:
        raise HeaderSerializationError(f"Cannot decode UTF-8 string: {e}")

unpack_float16(data)

Unpack a 16-bit (half-precision) floating point number.

Parameters:

Name Type Description Default
data bytes

Binary data (must be at least 2 bytes)

required

Returns:

Type Description
float

Unpacked float value

Raises:

Type Description
HeaderSerializationError

If data is insufficient or invalid

Source code in bionemo/scdl/schema/headerutil.py
207
208
209
210
211
212
213
214
215
216
217
218
219
220
def unpack_float16(self, data: bytes) -> float:
    """Unpack a 16-bit (half-precision) floating point number.

    Args:
        data: Binary data (must be at least 2 bytes)

    Returns:
        Unpacked float value

    Raises:
        HeaderSerializationError: If data is insufficient or invalid
    """
    self._validate_data_length(data, 2, "float16")
    return struct.unpack(f"{self.endianness}e", data[:2])[0]

unpack_float32(data)

Unpack a 32-bit (single-precision) floating point number.

Parameters:

Name Type Description Default
data bytes

Binary data (must be at least 4 bytes)

required

Returns:

Type Description
float

Unpacked float value

Raises:

Type Description
HeaderSerializationError

If data is insufficient or invalid

Source code in bionemo/scdl/schema/headerutil.py
239
240
241
242
243
244
245
246
247
248
249
250
251
252
def unpack_float32(self, data: bytes) -> float:
    """Unpack a 32-bit (single-precision) floating point number.

    Args:
        data: Binary data (must be at least 4 bytes)

    Returns:
        Unpacked float value

    Raises:
        HeaderSerializationError: If data is insufficient or invalid
    """
    self._validate_data_length(data, 4, "float32")
    return struct.unpack(f"{self.endianness}f", data[:4])[0]

unpack_string(data, max_length=None)

Unpack a UTF-8 string with length prefix.

Parameters:

Name Type Description Default
data bytes

Binary data starting with 4-byte length prefix

required
max_length int | None

Optional maximum length limit

None

Returns:

Type Description
Tuple[str, int]

Tuple of (unpacked string, total bytes consumed)

Raises:

Type Description
HeaderSerializationError

If data is invalid or string too long

Source code in bionemo/scdl/schema/headerutil.py
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
def unpack_string(self, data: bytes, max_length: int | None = None) -> Tuple[str, int]:
    """Unpack a UTF-8 string with length prefix.

    Args:
        data: Binary data starting with 4-byte length prefix
        max_length: Optional maximum length limit

    Returns:
        Tuple of (unpacked string, total bytes consumed)

    Raises:
        HeaderSerializationError: If data is invalid or string too long
    """
    if len(data) < 4:
        raise HeaderSerializationError("Insufficient data for string length")

    length = self.unpack_uint32(data[:4])

    if max_length is not None and length > max_length:
        raise HeaderSerializationError(f"String too long: {length} bytes > {max_length} bytes limit")

    if len(data) < 4 + length:
        raise HeaderSerializationError(f"Insufficient data for string: need {4 + length} bytes, got {len(data)}")

    try:
        string_value = data[4 : 4 + length].decode("utf-8")
    except UnicodeDecodeError as e:
        raise HeaderSerializationError(f"Cannot decode UTF-8 string: {e}")

    return string_value, 4 + length

unpack_uint16(data)

Unpack a 16-bit unsigned integer.

Parameters:

Name Type Description Default
data bytes

Binary data (must be at least 2 bytes)

required

Returns:

Type Description
int

Unpacked integer value

Raises:

Type Description
HeaderSerializationError

If data is insufficient or invalid

Source code in bionemo/scdl/schema/headerutil.py
113
114
115
116
117
118
119
120
121
122
123
124
125
126
def unpack_uint16(self, data: bytes) -> int:
    """Unpack a 16-bit unsigned integer.

    Args:
        data: Binary data (must be at least 2 bytes)

    Returns:
        Unpacked integer value

    Raises:
        HeaderSerializationError: If data is insufficient or invalid
    """
    self._validate_data_length(data, 2, "uint16")
    return struct.unpack(f"{self.endianness}H", data[:2])[0]

unpack_uint32(data)

Unpack a 32-bit unsigned integer.

Parameters:

Name Type Description Default
data bytes

Binary data (must be at least 4 bytes)

required

Returns:

Type Description
int

Unpacked integer value

Raises:

Type Description
HeaderSerializationError

If data is insufficient or invalid

Source code in bionemo/scdl/schema/headerutil.py
143
144
145
146
147
148
149
150
151
152
153
154
155
156
def unpack_uint32(self, data: bytes) -> int:
    """Unpack a 32-bit unsigned integer.

    Args:
        data: Binary data (must be at least 4 bytes)

    Returns:
        Unpacked integer value

    Raises:
        HeaderSerializationError: If data is insufficient or invalid
    """
    self._validate_data_length(data, 4, "uint32")
    return struct.unpack(f"{self.endianness}I", data[:4])[0]

unpack_uint64(data)

Unpack a 64-bit unsigned integer.

Parameters:

Name Type Description Default
data bytes

Binary data (must be at least 8 bytes)

required

Returns:

Type Description
int

Unpacked integer value

Raises:

Type Description
HeaderSerializationError

If data is insufficient or invalid

Source code in bionemo/scdl/schema/headerutil.py
173
174
175
176
177
178
179
180
181
182
183
184
185
186
def unpack_uint64(self, data: bytes) -> int:
    """Unpack a 64-bit unsigned integer.

    Args:
        data: Binary data (must be at least 8 bytes)

    Returns:
        Unpacked integer value

    Raises:
        HeaderSerializationError: If data is insufficient or invalid
    """
    self._validate_data_length(data, 8, "uint64")
    return struct.unpack(f"{self.endianness}Q", data[:8])[0]

unpack_uint8(data)

Unpack an 8-bit unsigned integer.

Parameters:

Name Type Description Default
data bytes

Binary data (must be at least 1 byte)

required

Returns:

Type Description
int

Unpacked integer value

Raises:

Type Description
HeaderSerializationError

If data is insufficient or invalid

Source code in bionemo/scdl/schema/headerutil.py
83
84
85
86
87
88
89
90
91
92
93
94
95
96
def unpack_uint8(self, data: bytes) -> int:
    """Unpack an 8-bit unsigned integer.

    Args:
        data: Binary data (must be at least 1 byte)

    Returns:
        Unpacked integer value

    Raises:
        HeaderSerializationError: If data is insufficient or invalid
    """
    self._validate_data_length(data, 1, "uint8")
    return struct.unpack(f"{self.endianness}B", data[:1])[0]

Endianness

Bases: Enum

Byte order specifications for binary data serialization.

Source code in bionemo/scdl/schema/headerutil.py
28
29
30
31
32
33
class Endianness(Enum):
    """Byte order specifications for binary data serialization."""

    NETWORK = (
        "!"  # Network byte order (same as big-endian). This is a good standard, used by Protobuf and other libraries.
    )

HeaderSerializationError

Bases: Exception

Raised when header serialization/deserialization fails.

Source code in bionemo/scdl/schema/headerutil.py
39
40
41
42
class HeaderSerializationError(Exception):
    """Raised when header serialization/deserialization fails."""

    pass