RUNTIME VALUE CONVERSIONS

Runtime bytes and binary records

Use immutable byte values for binary data and the struct conversion import for portable records with explicit byte order.

Use binary file operations to read or write records on disk. A fixed-length bytearray can be filled with readinto. Use bytes(buffer) to make an independent immutable record.

Byte values

A byte is an integer from 0 through 255. Byte values preserve embedded NUL and high-bit bytes without interpreting them as UTF-8. Supported constructors are byte literals, bytes(), bytes(count) for zero-filled storage, bytes(existing_bytes), bytes(bytearray_buffer), bytes(open_mapping) and bytes(list_or_tuple_or_range) containing byte integers. Booleans are accepted as integers. Negative counts and out-of-range elements raise ValueError; unsupported input types raise TypeError.

Use len, integer indexing, iteration, slices, concatenation, repetition, truth tests, equality, ordering, membership, dictionary/set keys and repr/str/ascii. Indexing and iteration return integers; slicing returns owned bytes. Use bytes for an immutable parameter or result and bytearray for a fixed-length writable buffer. Converting a bytearray or open mapping to bytes takes a snapshot. Element assignment is forbidden. Memoryview, text codecs, bytes methods, arbitrary iterator constructors and custom conversion hooks are unsupported.

def main():
    data = bytes([80, 0, 255])
    print(data, list(data), data[-1])
    print(data[::-1], b"PCF" + data, 0 in data)
    return 0

Pack and unpack

In Runtime mode, declare *import struct. The bundled package provides pack(format, *values), unpack(format, buffer) and calcsize(format). Here *values describes zero to 64 explicitly written positional values; source-level argument expansion and keyword arguments are unsupported. Arguments evaluate once, from left to right. Unpack requires exactly one complete record and always returns a tuple.

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

This produces the bytes [80, 67, 70, 33, 3, 255, 1], the tuple (b'PCF!', 1023, True), and size 7.

Map a binary file

Use Memory-mapped files for shared edits, private copies, and scanning with a read loop. Pass a byte slice such as view[:4] to struct.unpack when a record lives inside a mapping.

Format codes

The ASCII format string must start with < for little endian, or >/! for big endian. Sizes are fixed and no alignment is inserted. Decimal counts precede a code without intervening whitespace. ASCII whitespace between codes is ignored.

CodesWidth and value
b / B1-byte signed / unsigned integer.
h / H2-byte signed / unsigned integer.
i / I, l / L4-byte signed / unsigned integer on every supported host.
q / Q8-byte signed / unsigned integer, within Runtime's signed int64 value domain.
f / dFinite IEEE binary32 / binary64. f inputs must be within ±FLT_MAX and use round-to-nearest.
?1-byte truth value. Packing uses Runtime truth; unpacking treats any nonzero byte as True.
cOne bytes value of length one for each repetition.
NsOne bytes field of N bytes, truncated or zero-padded when packing. 0s still consumes one value.
NxN zero padding bytes when packing; consumes no value.

Errors and limits

Catch malformed formats, unsupported codes, field type/range errors, and record size/count mismatches with except s.error: (or your chosen import alias). This is separate from ValueError. Wrong format/buffer types raise TypeError. Unpacking Q above INT64_MAX and packing a float32 overflow raise OverflowError. Nonfinite float fields raise ValueError. The profile permits at most 4096 format bytes, 64 values and 1 MiB per record. Native/default/= formats, e p n N P, Struct objects, pack_into, unpack_from, iter_unpack and external buffers are unsupported.

The format must be a string and the buffer must be owned bytes. Qualified literal raises and tuples of exception types are supported. Exception-object binding with as and first-class error aliases are unsupported. Runtime allocation and work exhaustion remain fatal; they cannot be caught as struct.error or Exception.

Ownership and authoring

Each byte value owns one allocation containing its length and octets. Pack creates independent storage. Unpack creates a tuple and independently owned c/s fields; it retains no reference to the input buffer. Failed calls release their partial allocations and leave inputs unchanged. Results belong to their originating Runtime context and need live roots at collection boundaries. The C caller constructor pv_bytes(context, data, length) copies its input; a NULL data pointer requests zero fill. Existing C root and context-destruction rules apply.

The SDK's Portable binary records starter exposes the same three kernels through BinaryFunction and crucible.binary-records/0.1. Authors may choose independent namespaces and export names. The engine supplies formats, ownership, guards and Help; SDK verification checks conversion only. Native execution and compiler qualification belong to PyCForge. The older lazy-iterators/0.1 profile continues to reject direct bytes inputs; use an explicit list of byte integers for those pipelines.