Skip to content

ADR 0015: bytes values: a pointer and a length

Status: Final Type: Feature Created: 2026-07-28 Amends: 0014 (appends IR16: an arithmetic operand is a value promotion is defined over) Related-ADRs: 0004 and 0025 (the Str whose representation a bytes shares), 0026 (the ownership discipline it follows), 0043 (encode and decode), 0016 (pygo.net, the first consumer), 0029, 0030 and 0066 (a bytes as a union case, a container member and an optional). Provenance: arbitrations A3, A12, A13, A45, A174; upstream question U13.

Context

pygo.net (ADR 0016) makes a compiled pygo program serve TCP, and sockets deal in bytes; until this ADR the compiler refused b"..." outright and postyp.Bytes was declared with no lowering behind it. This ADR first fixed the type to what a socket needs. Binary files, bytes fields, bytes in unions and containers then waited on a bytes that is released, and eight Shed Skin census programs waited on those, so on 2026-10-29 the owner decided that a bytes is represented as a Str is (A174).

Decision

  1. A bytes is one counted allocation, headered like a Str. ADR 0025's header (count, length, an unused code-point count) sits before the data. The value is one machine word pointing at the data. Binary data contains NUL by definition, so a string of bytes that ends at the first zero byte is not a byte string; the length is stored and each operation reads it from the header. The type is incomplete outside the bytes runtime: no code outside it dereferences a bytes.

  2. A literal is its blob. Each backend emits a bytes literal as it emits a Str literal object, immortal by the header and holding the length, so evaluating a literal allocates nothing. b"" is one immortal empty object.

  3. Counted as a Str is (0026): a frame owns what an owning helper hands over, a function returning bytes hands over a reference, and a rebinding releases the old value. A bytes has counters of its own and a per-task leak report, so each report says what the type left. It is copied where it crosses: pygo.net's receive builds a bytes holding a copy and frees its buffer. A task argument is copied by the spawner and released by the body, as a Str is (A64), since counts are not atomic.

  4. The operations are CPython's. len counts bytes, where Str's counts code points; the difference is the point of the type. Comparison is memcmp over the common prefix, then by length, which is CPython's ordering on bytes and what strcmp cannot give once NUL is a legal element. Truthiness is non-emptiness. b[i] is one bounds-checked byte load, an int, raising IndexError. A slice follows CPython's slice adjustment. a + b, b * n and n * b (empty for n <= 0) and sep.join(xs) over a list, a generator or a tuple of bytes each make a new counted bytes; join is one lowering with str.join. bytes(xs) of a list of ints makes one byte per int and raises CPython's ValueError("bytes must be in range(0, 256)") before anything else is read. encode and decode are 0043's.

b"..." % args with a literal format is lowered piece by piece, every argument evaluated once and first. A literal piece is the bytes themselves. A numeric conversion (d, i, x, f and the rest, with a width, a precision and the - and 0 flags) is the Str conversion's ASCII text encoded. %c of an int is that byte, with CPython's OverflowError outside range(256). A bytes under %s or %b gives its bytes, and %% gives %. The pieces are joined as bytes. Joining them as a Str and encoding the result would be wrong for a literal byte or a %c above 0x7f, which UTF-8 spells in two bytes. Other conversions are refused by name.

The text of a bytes is CPython's repr: b'...', or b"..." when the data holds a ' and no "; the backslash, the quote, tab, newline and return escaped; any other byte below 0x20 or from 0x7f up as \xhh. It is what print, str, repr and an f-string give, what the printing of a container or union holding a bytes shows, and the text of a missing bytes key's KeyError.

int.to_bytes and int.from_bytes lower with byteorder the literal "big" or "little" and signed a literal bool, raising CPython's errors with their messages: a negative length is a ValueError, a negative int unsigned and an int that does not fit are OverflowErrors. A length past eight bytes fills with the sign, as an arbitrary-width int does. Where int grows (0075), a to_bytes of a value past 64 bits gives CPython's bytes, a length past 64 bits raises CPython's OverflowError, and a from_bytes of any length is CPython's value. With the 64-bit int, a value that needs more than 64 bits is the integer overflow every 64-bit int operation is (0002): a debug build stops naming it, a release build keeps the low 64 bits. from_bytes takes a bytes; CPython also takes any iterable of ints, which stays refused.

sum, min and max of a list[bytes] are refused by name (CPython's sum of bytes is a TypeError).

  1. A bytes is held wherever a Str is: a field, a list element, a dict key or value and a set member, a union case (0029), and bytes | None, whose payload pointer is null for None (0066's thin family). Each container releases it with itself; copy.deepcopy shares it as the immutable value it is.

  2. A bytearray local, and nothing more of bytearray. Shed Skin's sokoban copies a board with bytearray(data), writes into the copy, and returns bytes(data2). A name bound in a function only by name = bytearray(...) (of a bytes, of an int, or of nothing) holds a new bytes that only that name holds. ba[i] = v checks the value, raising CPython's ValueError("byte must be in range(0, 256)"), then the index, raising IndexError("bytearray index out of range"), in CPython's order, and writes in place. ba[i] and len(ba) read it, and bytes(ba) copies it out, so a later write cannot reach the copy. Any other read of the name is refused before the function is lowered, since it could share the buffer: a shared buffer written in place would need a mutable type this compiler does not have.

  3. bytes is a value, unlike a handle, and saying so cost more than adding a row. The test for an opaque value was "not numeric and not Str", stated over kinds so that the next type is refused by default. It is now "not numeric and not in a named set of non-numeric value types". The set is keyed by identity because postyp gives Str and Bytes the same kind, 's'. A kind test would have admitted Bytes from the day it was declared, which is the accept-then-wrong shape.

The same collision is why three permissive fallbacks had to be closed by hand; each was so ordinary that all backends would have compiled it in agreement. promote(Bytes, Bytes) is Bytes, so b1 + b2 emitted arithmetic on two pointers; truth's fallthrough is != 0, which on a pointer is True for any value a bytes can hold; and bytes resolves in an annotation position, so bytes(x) and str(b) both reached the cast machinery. Each now has its own lowering or diagnostic. The verifier also gained IR16 (ADR 0014) so that no non-numeric operand can reach arithmetic by a route the frontend misses.

  1. A bytes may cross a task boundary; it was the first val added to pygo's sendable set since the set was created. It qualifies for the same reason Str does: a Python bytes is immutable, so copy.deepcopy returns the same object interpreted, and passing a copy compiled is indistinguishable, so pygo D15's copy-on-send invariant holds. Chan[bytes] is not lowered: a channel moves an element by memcpy of a fixed size, and a bytes payload sits behind a pointer, the same aggregate-element question as Chan[list[int]] (A13).

  2. A distinct C type in the ABI vocabulary. The C type of a bytes maps to Bytes, distinct from const char *. Two types that share a kind and a machine width are the pair an ABI check must be able to tell apart; one row for both would make them interchangeable at each runtime-helper boundary, the class IR13 exists to catch. A handle is opaque to this compiler, so no C type can name it (void *); bytes is a value whose layout the runtime owns, so it can.

  3. A bytes stops at the stable C ABI. An exported signature taking or returning one is refused (PP501). The C type in a generated header is incomplete, with a runtime helper as the only constructor, so a C caller could hold one and not make one. Such a caller wants (const char *, int64_t); choosing that is an ABI decision (spec §9.1, upstream U13). Str exports because a NUL-terminated const char * is a type C already has. A private helper taking bytes compiles into an extension module unchanged.

Consequences

  • bytes values compile on all three backends and are byte-identical to CPython, interior NUL included, a case ADR 0004's original Str representation rejected outright. pygo.net is expressible (ADR 0016), and so are binary files (0061).
  • Opening the type opened all annotation positions at once, so the narrowness of what a bytes can do is enforced at each operation.
  • A program that holds a bytes links the Str unit (its repr is a Str), and one that links the list or object runtime links the bytes unit.
  • The first descriptor representation was A3's length-prefixed Str prototyped: it showed the gains (interior NUL, chr(0), an O(1) len) and the cost of the literal path. The Str migration of 0025 took the header instead of the descriptor, which closed A3, and A174 brought bytes onto the same header.