Skip to content

Bytes

Build, share, and decode binary buffers with []byte, which is List[byte].

Binary data uses the ordinary sequence type. There is no nominal bytes struct, no Buffer, and no separate slice type.

Spelling Meaning
[]byte List[byte] — owned, growable
bytes an alias for the same thing, declared beside List
byte an alias for u8, so byte literals carry the u8 suffix

Byte methods come from an impl on one instantiation, not from a protocol: impl List[u8] in stdlib/bytes.at extends exactly that one, so List[int] grows no is_valid_utf8 and every spelling of a byte list gets all of them. There is no Bytes or Buffer trait, and nothing needs one.

fn main() void {
    mut greeting: []byte = []
    greeting.append_string("hello")
    greeting.push(33u8)             // '!'
    println(string.from_utf8(greeting).ok() ?? "")
}

Building a buffer

A mut []byte is the string builder. push appends one byte, extend copies another byte list in one memory.copy, append_string adds a string’s UTF-8 bytes, and append_int / append_float write decimal ASCII straight into the reserved tail with no intermediate string allocation.

fn status_line(code int, reason string) []byte {
    mut out: []byte = List.new[byte](64)
    out.append_string("HTTP/1.1 ")
    out.append_int(code)
    out.push(32u8)                  // space
    out.append_string(reason)
    out.append_string("\r\n")
    return out
}

fn main() void {
    println(string.from_utf8(status_line(404, "Not Found")).ok() ?? "")
}

List.new[byte](n) reserves storage up front — the argument is a capacity hint, not a length — and reserve(additional) grows an existing buffer without changing its logical length. Neither changes what len() reports.

clear() resets the length to zero but keeps the capacity, which makes a single buffer reusable across a loop instead of allocating per iteration:

fn render_rows(count int) []string {
    mut buf: []byte = List.new[byte](64)
    mut rows: []string = []
    for i in 0..count {
        buf.clear()
        buf.append_string("row ")
        buf.append_int(i.to_int())
        rows.push(string.from_utf8(buf.clone()).ok() ?? "")
    }
    return rows
}

fn main() void {
    for row in render_rows(3) {
        println(row)
    }
}

extend copies from any byte list, which includes a string’s bytes and a slice of another buffer:

fn concat(header string, payload []byte, trailer []byte) []byte {
    mut packet: []byte = []
    packet.extend(header.to_bytes())
    packet.extend(payload)
    packet.extend(trailer)
    return packet
}

fn main() void {
    joined := concat("HTTP ", "200".to_bytes(), "\r\n".to_bytes())
    println(string.from_utf8(joined).ok() ?? "")
}

Views share storage

buf[range] answers with another []byte over the same allocation. Creating one copies nothing, which makes it the right thing to hand to anything that only reads. Ranges are half-open, and an out-of-bounds end or a start past the end stops the program, or gives None from buf.get(range) — carve the view once and handle absence explicitly.

fn checksum(data &[]byte) int {
    mut sum := 0
    mut i: usize = 0
    for i < data.len().to_usize() {
        sum = (sum + (data.get(i) ?? 0u8).to_int()) % 65_536
        i = i + 1
    }
    return sum
}

fn main() void {
    frame := "payload".to_bytes()
    println("${checksum(frame.get(0..4) ?? [])}")
}
error FrameError { Short }

fn body(frame &[]byte, header_len int) &[]byte ! FrameError {
    match frame.get(header_len.to_usize()..frame.len().to_usize()) {
        Some(view) => return view
        None => error Short
    }
}

fn main() void {
    match body("....payload".to_bytes(), 4) {
        Ok(rest) => println("${rest.len()} bytes after the header")
        Err(e) => println("short frame")
    }
}

Because a view shares the parent’s allocation, keep the parent alive while the view is in use, and copy out when the bytes must outlive it.

The surface is List’s

There is no byte-specific protocol to learn. len(), is_empty(), get(i), push, extend, clear, reserve and slice are List’s, unchanged, and get answers byte? — None for an out-of-range index, so a scan needs no bounds check of its own.

The byte-specific methods are the ones about what the bytes mean rather than about storage:

Method Meaning
is_valid_utf8() strict UTF-8 validation
string.from_utf8(bytes) string ! Utf8Error — validate, then move the block into a string
append_int(n) / append_float(x) decimal ASCII, written in place
append_string(s) a string’s UTF-8 bytes
encode_hex() / encode_hex_upper() hexadecimal ASCII
encode_base64() and three siblings RFC 4648 §4 and §5
encode_base32() RFC 4648 §6

A function that reads bytes takes a []byte and serves owned buffers and views alike, since a view is one:

const HEX: string = "0123456789abcdef"

fn hex_digit(nibble int) byte {
    return HEX.to_bytes().get(nibble.to_usize()) ?? 48u8
}

fn hexdump(data []byte) string {
    mut out: []byte = List.new[byte](data.len() * 3)
    mut i: usize = 0
    for i < data.len().to_usize() {
        if i > 0.to_usize() { out.push(32u8) }
        b := (data.get(i) ?? 0u8).to_int()
        out.push(hex_digit((b >> 4) & 0xF))
        out.push(hex_digit(b & 0xF))
        i = i + 1
    }
    return string.from_utf8(out).ok() ?? ""
}

fn main() void {
    owned := "AB".to_bytes()
    println(hexdump(owned))
    println(hexdump("AB".to_bytes()))
}

Note the shape of that loop: the output buffer is the accumulator. Do not write this particular one — data.encode_hex() is the same answer in one call, and is covered under Encodings below — but the shape is the one to copy, because there is no string.join to reach for — it is not declared (see Availability below), and a []byte you append to is faster anyway.

tail_ptr() is a low-level pointer at the unused tail, intended for the stdlib and host wrappers. Do not retain it across buffer mutation, scope exit, or a suspension point unless a lower-level contract pins the allocation.

Text conversion

Text and bytes never convert implicitly. The compiler rejects the confusion:

fn as_text(data []byte) string {
    return data
}

The conversions are explicit in both directions:

fn conversions(text string, data []byte) int {
    owned: []byte = text.to_bytes()
    decoded: string? = string.from_utf8(data.clone()).ok()
    valid: bool = data.is_valid_utf8()
    return owned.len() + (decoded ?? "").len() + (if valid { 1 } else { 0 })
}

fn main() void {
    println("${conversions("hi", "there".to_bytes())}")
}

string.from_utf8 performs strict Unicode validation and then hands the bytes’ own block to the string, copying nothing: overlong encodings, surrogate code points, truncated sequences, stray continuation bytes, and values above U+10FFFF are all rejected, and the error, Utf8Error, says how many leading bytes were valid (valid_up_to). It returns a Result, and forgetting that is a type error, not a silent lossy decode; .ok() is the Option:

fn decode(data []byte) string {
    return string.from_utf8(data)
}

If your protocol wants replacement characters instead of rejection, implement that policy yourself — the standard decoder is strict, never lossy.

error WireError { NotUtf8 }

fn strict(payload []byte) string ! WireError {
    match string.from_utf8(payload) {
        Ok(text) => return text
        Err(_) => error NotUtf8
    }
}

fn lenient(payload []byte) string {
    return string.from_utf8(payload).ok() ?? "<binary>"
}

fn main() void {
    println(lenient("ok".to_bytes()))
}

Encodings

Hex, base64 in all four RFC 4648 spellings, and base32. The encoders are methods on []byte; the decoders are on string, beside to_int and to_float, because reading text is the text’s job.

fn main() void {
    raw := "foobar".to_bytes()
    println(raw.encode_hex())                     // 666f6f626172
    println(raw.encode_hex_upper())               // 666F6F626172
    println(raw.encode_base64())                  // Zm9vYmFy
    println(raw.encode_base32())                  // MZXW6YTBOI======
}
Encoder Writes
encode_hex() / encode_hex_upper() two characters per byte
encode_base64() RFC 4648 §4, =-padded
encode_base64_unpadded() §4 with no padding — what a JWT carries
encode_base64_url() RFC 4648 §5, - and _, =-padded
encode_base64_url_unpadded() §5 with no padding
encode_base32() RFC 4648 §6, uppercase, =-padded

Reading one back answers bytes?, and the decoders are strict:

fn main() void {
    hex := "666f6f"
    match hex.decode_hex().ok() {
        Some(raw) => println("${raw.len()} bytes")
        None => println("not hex")
    }
    encoded := "Zm9vYmFy"
    println((encoded.decode_base64().ok() ?? []).encode_hex())
}

Whitespace is not skipped, a character outside the alphabet is a refusal rather than a zero, and a tail carrying bits the encoder could never have set is refused too. That last one is the rule that is easy to leave out and the one that matters: "Zg==" decodes to "f" and "Zh==" does not decode at all, because the four spare bits of a two-character base64 tail are zero by construction. Two spellings for one answer is how a signature compared against a re-encoding gets talked past.

fn main() void {
    canonical := "Zg=="
    spelled_twice := "Zh=="
    println("${(canonical.decode_base64().ok() ?? []).len()} byte")
    match spelled_twice.decode_base64().ok() {
        Some(raw) => println("accepted, which is the defect")
        None => println("refused")
    }
}

Padding is optional on the way in — every base64url field in a JWT is unpadded by RFC 7515 §2 — but padding that does not reach a group boundary is refused. Base32 takes uppercase only, which is what its encoder writes; hex takes both cases, because there is an encoder here for each.

Embedding a file

bytes.embed("fonts/Inter.ttf") is the bytes of a file of the package, read when the program is built and placed in its constant data: a []byte that costs nothing to make at run time and works on every target. The path is a string literal, from the directory of the file that calls it. A path that is not a literal, that climbs out of the package (../other/x), that starts at the root of the file system, or that names no file is refused where it is written (ATOLL2129).

The file is an input of the build, as the sources are: a build after it changes compiles again, and one after it did not is the build it was. A program that embeds nothing reads no file for it.

Empty buffers

An empty []byte reports len() == 0 and is_empty() == true, and get on one answers None at every index. Prefer get over pointer arithmetic for exactly that reason.

fn first_byte(data []byte) byte? {
    if data.is_empty() { return None }
    return data.get(0.to_usize())
}

fn main() void {
    empty: []byte = []
    println("${first_byte("A".to_bytes()) ?? 0u8} ${first_byte(empty) ?? 0u8}")
}

A worked example

A length-prefixed frame codec: build into a buffer, parse with get and slice, and decode text only at the boundary.

error CodecError { Short, BadLength, NotUtf8 }

const HEADER_LEN: int = 5

fn encode(kind byte, payload string) []byte {
    body := payload.to_bytes()
    mut frame: []byte = List.new[byte](HEADER_LEN + body.len())
    frame.push(kind)
    // 4-byte big-endian length.
    n := body.len()
    frame.push(((n >> 24) & 0xFF).to_u8())
    frame.push(((n >> 16) & 0xFF).to_u8())
    frame.push(((n >> 8) & 0xFF).to_u8())
    frame.push((n & 0xFF).to_u8())
    frame.extend(body)
    return frame
}

fn read_length(frame &[]byte) int {
    mut n := 0
    mut i := 1
    for i < HEADER_LEN {
        n = (n << 8) | (frame.get(i.to_usize()) ?? 0u8).to_int()
        i = i + 1
    }
    return n
}

fn decode(frame &[]byte) string ! CodecError {
    if frame.len() < HEADER_LEN { error Short }
    declared := read_length(frame)
    if declared != frame.len() - HEADER_LEN { error BadLength }
    match frame.get(HEADER_LEN.to_usize()..frame.len().to_usize()) {
        None => error Short
        Some(body) => match string.from_utf8(body.clone()).ok() {
            Some(text) => return text
            None => error NotUtf8
        }
    }
}

fn main() void {
    frame := encode(7u8, "ping")
    match decode(frame) {
        Ok(text) => println("kind=${frame.get(0.to_usize()) ?? 0u8} payload=${text}")
        Err(e) => println("bad frame")
    }
}

Availability

Everything on this page compiles.

Two neighbouring signatures are worth knowing. int.to_radix(base) compiles — measured. And string.join(items, sep) is not a declaration at all: there is no static join on string, so a call is ATOLL2003 from atoll check. List.join is the one that exists, and it is a method on the list: items.join(sep).

Signature Status
int.to_radix(base) lowers
string.join(items, sep) not declared — write items.join(sep)

Accumulate into a mut []byte instead of joining, and format hex or binary from a digit table as hexdump above does.

Type to search…

↑↓ navigate↵ selectEsc close