struct — 0.1.0

org.pycforge.struct · Author: PyCForge

License: GPL-3.0-only · Created: 2026-11-14

Runtime conversion · Direct declared calls

Using this import · Functions · Conversion contract · Worked examples

Function index

calcsize · pack · unpack

Overview

Encode and decode portable records with owned immutable byte storage.

Using this import

Use *import struct as w and explicit <, > or ! byte order. Byte literals and bytes integer sequences preserve embedded zero bytes.

Author's limitations

Runtime only. pack(format, *values), unpack(format, buffer) and calcsize(format) accept positional arguments only; no *args/**kwargs expansion or function values. Arguments evaluate once, left to right. The format is an ASCII string of at most 4096 bytes starting with < (little endian), > or ! (big endian), with no alignment. Supported codes: x c ? b B h H i I l L q Q f d s, decimal repeat counts and ASCII whitespace between codes. At most 64 values and 1 MiB per record. s counts bytes in one field, including 0s; x pads with zero bytes. c requires exactly one byte. s truncates or zero-pads its bytes input. Integer fields accept int64/bool only, with checked signed/unsigned field ranges. Q unpack above INT64_MAX raises OverflowError. f and d use finite IEEE binary32/binary64; f input must lie within [-FLT_MAX, FLT_MAX]; float32 rounding requires round-to-nearest. Nonfinite values raise ValueError and float32 overflow raises OverflowError. ? uses Runtime truth without custom truth callbacks. unpack requires owned bytes of exactly calcsize length and returns an owned tuple. Its c/s values own independent copied storage. pack returns immutable owned bytes. No input is mutated or retained by a result. Malformed/unsupported formats, field types/ranges and size/count mismatches raise the qualified error member (struct.error); wrong format/buffer types raise TypeError. Runtime work/allocation exhaustion is fatal. Failed operations release partial allocations; live results need roots at GC boundaries. Helpers never collect internally. No native/default/= formats, e p n N P, bytearray, memoryview, external buffers, Struct objects, pack_into, unpack_from, iter_unpack, codecs or custom __index__. Core bytes supports literals, bytes(), integer zero-fill, bytes identity, list/tuple/range of byte integers, length, integer indexing/iteration, owned slices, concatenation, repetition, truth, comparison, membership, hashing and representation. Other bytes constructors and methods are outside this initial profile. Existing lazy-iterators/0.1 continues to refuse direct bytes inputs; use an explicit list of byte integers.

Release notes

Initial portable binary record profile.

Conversion contract

Use *import struct in the module preamble. Each signature states accepted positions, names and defaults. A slash marks positional-only parameters; a star marks keyword-only parameters. Argument expansion, function values and Typed conversion are unsupported.

Runtime only. pack(format, *values), unpack(format, buffer) and calcsize(format) accept positional arguments only; no *args/**kwargs expansion or function values. Arguments evaluate once, left to right. The format is an ASCII string of at most 4096 bytes starting with < (little endian), > or ! (big endian), with no alignment. Supported codes: x c ? b B h H i I l L q Q f d s, decimal repeat counts and ASCII whitespace between codes. At most 64 values and 1 MiB per record. s counts bytes in one field, including 0s; x pads with zero bytes. c requires exactly one byte. s truncates or zero-pads its bytes input. Integer fields accept int64/bool only, with checked signed/unsigned field ranges. Q unpack above INT64_MAX raises OverflowError. f and d use finite IEEE binary32/binary64; f input must lie within [-FLT_MAX, FLT_MAX]; float32 rounding requires round-to-nearest. Nonfinite values raise ValueError and float32 overflow raises OverflowError. ? uses Runtime truth without custom truth callbacks. unpack requires owned bytes of exactly calcsize length and returns an owned tuple. Its c/s values own independent copied storage. pack returns immutable owned bytes. No input is mutated or retained by a result. Malformed/unsupported formats, field types/ranges and size/count mismatches raise the qualified error member (struct.error); wrong format/buffer types raise TypeError. Runtime work/allocation exhaustion is fatal. Failed operations release partial allocations; live results need roots at GC boundaries. Helpers never collect internally. No native/default/= formats, e p n N P, bytearray, memoryview, external buffers, Struct objects, pack_into, unpack_from, iter_unpack, codecs or custom __index__. Core bytes supports literals, bytes(), integer zero-fill, bytes identity, list/tuple/range of byte integers, length, integer indexing/iteration, owned slices, concatenation, repetition, truth, comparison, membership, hashing and representation. Other bytes constructors and methods are outside this initial profile. Existing lazy-iterators/0.1 continues to refuse direct bytes inputs; use an explicit list of byte integers.

struct.error: struct.error (qualified except/raise member)

struct.calcsize(format, /) -> int64

Calculate the record byte size.

Normalized semantic slots: format. These slots are supplied by the engine; the signature above defines source arguments and defaults.

Validate the bounded portable format and return its byte size.

Result must fit signed int64; nonfinite or out-of-range results raise an exception.

Argument 1: format: positional-only

Returns: int64

View example: packet-roundtrip

struct.pack(format, /, *values [0..64 positional values]) -> owned-bytes

Encode a portable binary record.

Normalized semantic slots: format, values. These slots are supplied by the engine; the signature above defines source arguments and defaults.

Pack up to 64 values into new immutable owned bytes with explicit byte order.

Argument 1: format: positional-only

Argument 2: values: positional-only

Returns: owned-bytes

View example: packet-roundtrip

struct.unpack(format, buffer, /) -> binary-record

Decode an exact binary record.

Normalized semantic slots: format, buffer. These slots are supplied by the engine; the signature above defines source arguments and defaults.

Decode exactly one record into a new tuple with independent byte fields.

Argument 1: format: positional-only

Argument 2: buffer: positional-only

Returns: binary-record

View example: packet-roundtrip

Worked examples

Compare your run with the expected output below. The SDK checks conversion when authoring a package. Opening Help and registering a package do not execute the examples.

Example: packet-roundtrip

*import struct as w
def main():
    packet = w.pack(">4sH?", b"PCF!", 1023, True)
    print(list(packet))
    print(w.unpack(">4sH?", packet))
    print(w.calcsize(">4sH?"))
    return 0

Expected standard output:

[80, 67, 70, 33, 3, 255, 1]
(b'PCF!', 1023, True)
7

Expected exit code: 0