Skip to reference

std.bytes

wolf-std d58f9e1 · toolchain pin verified against wolf 0.2.41 (0261597). Source signatures and documentation; execution support is stated in each module.

All modules · Plain text · Stability tier: core

Module

std.bytes — raw byte operations, including shared equality with no early exit at source level for equal public lengths. Stability tier: core. The nine-function historical account below predates is_equal_fixed_work; that helper adds no timing certificate to the original byte operations.

This module had no code for five sprints, s37 gave it a producer, and s81 closed the circle. str.bytes() produces the byte view (List[byte] since sc35 — one octet per element, and the TYPE says 0..255 now) on all three lanes, and str_from_utf8 — the prelude's validating way back, landed at s81 (wolf-lang#58, F-0057 CLOSED) — is what to_str delegates to. All nine reviewed functions are code now; the module has no contract left. is_utf8 keeps its job, because the question "are these bytes text?" has a boolean answer a caller may want without the text.

**to_str had unequal lanes for exactly one sprint, and it has three now.** str_from_utf8 is PURE (no I13 capability, no sandbox category — the second such family after json_*) and executed on the compiler rungs alone at sc13, where lupin 0.1.11 answered unsupported: str_from_utf8 does not resolve — the generic unknown-name refusal rather than a reasoned decline, which is why it was filed as drift (F-0075). lupin 0.1.12 resolves it and the finding is CLOSED, re-measured with its own reproducer at the sc14 pin, so all nine functions here are three-lane and the module has neither a contract nor an unequal row left.

THE ARGUMENT POSITION IS A LEND NOW, AND EIGHT OF THESE NINE FUNCTIONS STOP COPYING (s89, wolf-lang#86, F-0072 CLOSED — the ask this header carried for two sprints, answered in the shape it asked for). s77 made s.bytes() the receiver's own {ptr, len} wherever the call was CONSUMED (for b in s.bytes(), s.bytes().len) and materialized it everywhere else — including in an ARGUMENT, which is how every function here receives its bytes, so bytes.len(s.bytes()) took a heap copy of s for a length it was going to read in place. s89 is the region checker's argument one scale down: a view handed to a callee is LENT for the call, the callee may read it, and it may not outlive the call. So write bytes.find(s.bytes(), needle) and the view crosses without a copy.

Three consequences worth knowing before writing against it.

- The verdict is the CALLEE's, and it is decided from its body. A parameter every one of whose uses is one of s77's read positions (or a re-lend into another lendable parameter) is lendable; anything the analysis has not proved materializes exactly as before, which is never wrong and only slower. Eight of the nine below are lendable and to_str is not: it hands its parameter to str_from_utf8, and a builtin consumer materializes. That is upstream's measurement (wolf_mem's byteview suite, a_builtin_consumer_materializes), cited here rather than restated, because no lane in this repository can observe an allocation (§9's sc12 rule). - A lend that would outlive its call is REFUSED, not quietly copied — E1015, with the one-word fix in the diagnostic: bind the bytes first (let bs = s.bytes() materializes) and the bound list is an ordinary value the callee may own. Nothing in this module trips it; the shape that would is a function returning its own List[byte] parameter. - **from_str is the way IN and still allocates, which is its job.** A function that RETURNS a list must own it, so the copy is the price of having a VALUE rather than a walk — and a caller who only wants to walk should write for b in s.bytes() or call std.str's walks, which do. The Bytes type this header has wanted since sc05 is still the thing that would make the interim currency real; the lend is what made the interim stop costing a copy per call.

What this module is FOR is unchanged and worth restating in that light: bytes a program HOLDS (a decoder's output, a list it built, a buffer it was handed) rather than bytes it is walking through once. A one-pass walk over a string's bytes belongs in std.str and is written there.

**THE TYPE IS List[byte], AND THE INTERIM IS OVER (sc35).** For nine sprints this header carried a recorded interim — the currency was List[int], one element per byte, and the ELEMENT CONTRACT (0..255) was a promise the library made and the type could not keep. Both halves of the wait have landed. D72 / s135 gave the language [type.byte] — an 8-bit unsigned octet whose List[byte] strides by 1 — and s136 (wolf-lang#231) moved the eight byte BUILTINS to it, which is the half that decided whether this module could spend the type. So every signature below is the rename this header promised, and nothing else moved: from_str is still s.bytes(), to_str is still str_from_utf8(b)?, and not one function here gained a conversion loop.

What the rename is worth, measured through THIS module's own producers rather than synthetically (F-0104's after-table, re-run at the io sites — docs/findings.md): a 64 KiB buffer read by std.fs.read_bytes charges 65,584 native and 65,536 checked, where the same read as List[int] charged 1,048,560 and 1,048,576. 16.0x -> 1.00x native, 16.0x -> 1.00x checked. The native number is not the 2.0x sc34 predicted for a byte buffer, and the reason is s136's: a PRODUCER mints its list at exact capacity through one memcpy, so it pays no push-growth history at all — the 48 is one list header. The 2.0x is still what a list this module GROWS by push costs, and that residue is [mem.region.account.1]'s, not the element width's.

Three things about the element contract are now the TYPE's job and not this module's. A List[byte] cannot hold 300, cannot hold -1, and cannot hold a non-byte — so is_utf8's "an element outside 0..255 answers false" clause is unreachable rather than merely untested, to_str's matching row is too, and hex.encode's §11 assert has one fewer thing to defend. The clauses stay documented where the REASONING is still worth having (a validator answers, an encoder traps) and are marked unreachable where the type now forbids the input.

**The element is a byte, so reading one is a byte and widening is SPELLED.** at returns byte — it is b[i], and b[i] on a List[byte] is an octet — so a caller comparing it to a number writes bytes.at(b, i) as int == 0x80 or bytes.at(b, i) == 0x80 as byte. That is [type.byte.op]'s rule and not this module's opinion: byte against int is the ordinary type mismatch, and every arithmetic operator widens to int anyway. Comparing two bytes needs no cast at all, which is why find, starts_with and ends_with did not change a line of their bodies.

**Why these five duplicate std.list's names, and why that is right.** len, is_empty, at, find, starts_with and ends_with all have std.list counterparts, and the reason to have both is measured rather than aesthetic: std.list's are GENERIC, and a generic std function runs on the interpreter lane alone (both compiler rungs refuse monomorphization at a module boundary, F-0026), while these are monomorphic over List[byte] and run on all three. A program that has bytes wants the byte-tier operations to be available wherever it compiles. The vocabulary is §8's, deliberately: one concept, one name, across all of std — len, is_empty, find, starts_with, ends_with, slice, at.

What byte-land buys, in one line each. ends_with is trivial here and needed the boundary primitive over str; slice can never split a code point because there are no code points here; at is legal indexing where s[i] is refused for str (D25 licenses exactly this). The freedom has a price, and it is the whole reason to_str validates: bytes are where the UTF-8 invariant is ALLOWED to be absent.

The border post, and why it took five sprints — kept because the reason is the design. to_str was a reviewed contract from sc05 to sc12 and the blocker was never tables: nothing in the language built a str from a number (no char, no from_utf8, no strbuf.push_byte, probed four ways at four pins), so the MATERIALIZATION step had nowhere to happen while the VALIDATION half sat here written and tested as is_utf8. An ASCII-only to_str would have been a border post that refuses text, which §9 forbids, so the function waited.

What it waited for is exactly what landed. s77 made the byte view bit-identical to a str and deliberately emitted no path back, naming the reason in the compiler's own words — the view "cannot become a str … a List[int] -> str conversion would have to VALIDATE (wolf-std's bytes.to_str, still blocked, and this is why: it wants a checked primitive, not a cast)". s81 wrote that primitive: a {utf8} row rather than a trap, a cast nowhere in it, and the same six rejection classes is_utf8 enumerates plus one this library could not have raised at all (an element that is not a byte). std did not lower its standard and the toolchain did not take the shortcut; the border post is the same function the sc05 contract described, four lines long.

Types and traits

No public declarations in this section.

Functions and methods

is_equal_fixed_work

fn · Source line 172

pub fn is_equal_fixed_work(a: List[byte], b: List[byte]) -> bool

Byte equality with no early exit at source level for equal lengths. Unequal lengths return false immediately: lengths are public inputs. Equal-length inputs visit every pair, OR-fold their XOR differences, and test the accumulated result once. Empty inputs compare equal. Total: no error row, no traps on well-typed inputs. Pure, comptime-safe. This source contract is NOT a fixed-time certification of generated code, runtime operations, allocation, or any execution tier. Review generated code separately at the exact compiler/backend/runtime pins.

bytes.is_equal_fixed_work("abc".bytes(), "abc".bytes()) == true
bytes.is_equal_fixed_work("abc".bytes(), "abd".bytes()) == false
bytes.is_equal_fixed_work("".bytes(), "x".bytes()) == false

len

fn · Source line 190

pub fn len(b: List[byte]) -> int

The number of bytes in b. O(1). Total: no error row, no traps.

bytes.len("wolf".bytes()) == 4
bytes.len("é".bytes()) == 2
bytes.len("".bytes()) == 0

is_empty

fn · Source line 200

pub fn is_empty(b: List[byte]) -> bool

Whether b holds no bytes. Total: no error row, no traps.

bytes.is_empty("".bytes()) == true
bytes.is_empty("x".bytes()) == false

at

fn · Source line 219

pub fn at(b: List[byte], i: int) -> byte

The byte at index i. BYTE INDEXING IS LEGAL HERE — it is the whole point of this type (D25 licenses b[i] exactly where it refuses s[i]), and this function is the spelling that does not presume the answer to F-0011's builtin-versus-std question.

Traps bounds when i is out of range — the language's own fault from the language's own indexing, because a caller that could have checked len and did not has violated a contract (§8). The recoverable spelling is std.list.get, which raises none.

bytes.at("hé".bytes(), 0) as int == 104
bytes.at("hé".bytes(), 1) as int == 195
bytes.at("hé".bytes(), 2) == 169 as byte

slice

fn · Source line 241

pub fn slice(b: List[byte], from: int, to: int) -> List[byte]

The bytes in [from, to), as a fresh list. Never splits a code point, because there are no code points here — the freedom this view sells.

Traps assert when the range is out of order (to < from), starts below zero, or ends past len(b). This is a recorded delta from the reviewed contract, which said bounds: with List[byte] as the interim currency there is no slice SYNTAX to inherit the language's fault from, so the check is std's own and the kind is the one std can raise (§2 — either way it is a caller contract violation, and either way the process ends). It becomes bounds when Bytes lands with a slicing form.

bytes.len(bytes.slice("wolf".bytes(), 1, 3)) == 2
bytes.at(bytes.slice("wolf".bytes(), 1, 3), 0) as int == 111
bytes.len(bytes.slice("wolf".bytes(), 2, 2)) == 0
bytes.len(bytes.slice("wolf".bytes(), 0, 4)) == 4

find

fn · Source line 280

pub fn find(b: List[byte], needle: List[byte]) -> int ! {none}

The index of the first occurrence of needle in b; none when it does not occur. The empty needle occurs at 0, exactly as str.find's does. A needle longer than b is a miss, not a fault. Total otherwise: no traps.

(bytes.find("wolf".bytes(), "lf".bytes()) else 0 - 1) == 2
(bytes.find("wolf".bytes(), "z".bytes()) else 0 - 1) == 0 - 1
(bytes.find("wolf".bytes(), "".bytes()) else 0 - 1) == 0

starts_with

fn · Source line 317

pub fn starts_with(b: List[byte], prefix: List[byte]) -> bool

Whether b begins with prefix; the empty prefix always does. Total: no error row, no traps.

bytes.starts_with("wolf".bytes(), "wo".bytes()) == true
bytes.starts_with("wolf".bytes(), "lf".bytes()) == false
bytes.starts_with("wolf".bytes(), "".bytes()) == true

ends_with

fn · Source line 345

pub fn ends_with(b: List[byte], suffix: List[byte]) -> bool

Whether b ends with suffix; the empty suffix always does. Total: no error row, no traps.

Note what byte-land buys: this one is three lines here and needed the boundary primitive to exist at all over str, where the tail offset may fall inside a code point.

bytes.ends_with("wolf".bytes(), "lf".bytes()) == true
bytes.ends_with("wolf".bytes(), "wo".bytes()) == false
bytes.ends_with("wolf".bytes(), "".bytes()) == true

from_str

fn · Source line 393

pub fn from_str(s: str) -> List[byte]

s's bytes — infallible, because a valid str is always valid bytes. The bare-noun/as_-grade direction of §1 (a view, not a conversion of meaning). It is no longer the only producer: std.fs.read_bytes and std.fs.read_chunk hand back bytes that were never a str (s90, F-0044 closed), which is the case this module's element contract was always written for. str.bytes(s) is the same view from the other side.

This function materializes, and after s77 that is a statement about its SIGNATURE rather than about the pin. The language's s.bytes() is the receiver's own pointer and length when it is consumed on the spot; returning it — which is all this function does — is one of the positions that still copies, and it must be, because the list outlives the expression that produced it. So the allocation is the price of having a value rather than a walk, and a caller who only wants to walk should write for b in s.bytes() (or call std.str's walks, which do). Total: no error row, no traps beyond allocation.

Call it when you want to KEEP the bytes, not to pass them. Since s89 an argument is a lend, so bytes.len(s.bytes()) is the spelling that hands the eight lendable functions below the string's own two words, while bytes.len(bytes.from_str(s)) allocates a list in order to throw it away. Reach for this function when the list outlives the call: a buffer a program accumulates into, a decoder's output, anything held across statements — which is what the doc examples below still do wherever a value is what the reader needs to see.

bytes.at(bytes.from_str("A"), 0) as int == 65
bytes.len(bytes.from_str("🐺")) == 4
bytes.at(bytes.from_str("🐺"), 0) as int == 240

to_str

fn · Source line 441

pub fn to_str(b: List[byte]) -> str ! {utf8}

b as text, VALIDATED — the border post D24 demands, the one place in wolf where bytes become a str, and the reason str needs no validity check anywhere else.

Rows: utf8, and nothing else. Nothing here traps, including for input this module's own element contract calls impossible: a stray continuation byte, a truncated sequence, an overlong form, a surrogate (U+D800..U+DFFF), a scalar above U+10FFFF, a byte that begins no sequence (C0, C1, F5..FF), and an element outside 0..255 are all a MISS. Bytes are data — §2's rule, and the same reasoning that makes is_utf8 answer false rather than trapping on a non-byte.

An interior NUL is VALID and is not a terminator: a wolf str carries its length, so to_str of [119, 0, 102] is a three-byte string.

is_utf8 is this function's predicate half and the two agree by measurement, not by construction — they are different code (one is a decoder written here in divisions and range tests, the other is the toolchain's), and tests/bytes/to_str_border.lu walks the classes through both and asserts they answer the same. Ask is_utf8 for a boolean; call to_str when you want the text.

Pure: str_from_utf8 carries no I13 capability and no sandbox category, so with json_* it is the second such builtin family and the D33 sandbox has no reason to refuse it. That is a statement about the SANDBOX and not a promise about comptime, because the engine cannot reach this function for an unrelated reason: List[byte]() inside a comptime fn is unsupported at resolve (F-0077), and a List is the only way to spell the argument. Measured, both compiler rungs, rather than inferred from the absence of a capability.

Delegates to the prelude's str_from_utf8 (s81, wolf-lang#58). Three lanes as of the sc14 pins: both compiler rungs had it at s81 and lupin 0.1.12 resolves it too (F-0075, filed at sc13 and closed one release later), so this function's test columns are all lit and no caller pays a lane for reading text out of bytes.

(bytes.to_str(bytes.from_str("wolf é")) else "?") == "wolf é"
(bytes.to_str(List[byte]()) else "?") == ""
var lone = List[byte]()
(mut lone).push(128 as byte)
(bytes.to_str(lone) else "?") == "?"

is_utf8

fn · Source line 480

pub fn is_utf8(b: List[byte]) -> bool

Whether b is well-formed UTF-8 — the predicate half of to_str, and the one function here that reads the bytes as text rather than as numbers. The empty sequence is valid.

It stays hand-written now that to_str exists, and the reason has OUTLIVED the reason it was written for. It was kept at sc13 because it had three lanes where to_str had two (F-0075, since closed), and that argument is spent; what is not spent is the other one: two independent decoders that must agree are worth more than one. The agreement is a test (tests/bytes/to_str_border.lu) rather than a tautology, and it is the test that would catch either side drifting — this module's RFC 3629 reading or the toolchain's.

It rejects everything the standard rejects, not merely truncation: a stray continuation byte, a truncated multi-byte sequence, an OVERLONG form (C0 80 for U+0000, E0 80 80, F0 80 80 80), a surrogate (U+D800..U+DFFF, ED A0 80), a scalar above U+10FFFF (F4 90 80 80), and the bytes C0, C1, F5..FF which begin no sequence at all.

**An element outside 0..255 makes it false, not a trap.** §11 has element-range violations trap assert, and that rule is an ENCODER's: hex.encode must not render a number it was not given. A validator is the opposite case — the question "are these bytes text?" has an answer for a non-byte, the answer is no, and a predicate that traps is a predicate every caller must guard before calling, which defeats it.

Total: no error row, no traps.

bytes.is_utf8("héllo 🐺".bytes()) == true
bytes.is_utf8("".bytes()) == true
var bad = List[byte]()
(mut bad).push(255 as byte)
bytes.is_utf8(bad) == false

Constants

No public declarations in this section.

Errors and row tags

Tags named by public signatures: none, utf8. Their conditions are documented on the functions that return them.

No public declarations in this section.