Spec chapters

21. Buffers, ownership and defer

Buf(T) is a buffer of T on the heap, with a length fixed until it is resized. a.alloc(n, v) makes one holding n copies of v (T is v’s type, or the element type the context expects); a.free(b) frees it (E103 for a value that owns nothing, except in a generic instance, where freeing a storable value that owns nothing does nothing, so one generic container serves owned and plain values alike); a.resize(&b, n, v) changes its length to n, filling new elements with v. A negative length panics with negative buffer length. a.push(&b, v) moves v in at the end (a buffer has a capacity: a push onto a full one raises it to 4 if it is below 2, and doubles it otherwise, so a push costs amortized O(1)), and a.pop(&b) moves the last element out as a ?T (null when b is empty); a pushed value is not copied, so it may be an owned one. A Buf(?U) pops a ??U, unwrapped with two orelses, the outer one for an empty buffer: (a.pop(&b) orelse 0) orelse -1. These three work only on a Buf (E103).

A buffer is used like an array: b[i] (bounds-checked; b[i] = v needs a var or an inout parameter), @len(b), for (b), and b[lo..hi], a slice of it. These borrow it, and so does passing it to a plain parameter. Everything else moves it: assigning it, passing it to a sink parameter, returning it, a.free(b) and a.push(&bs, b).

Borrowed and sink parameters. A plain parameter of an owned type borrows the caller’s value for the call: the function may read it, index it, slice it, loop over it, copy plain fields out of it and pass it on to another plain parameter, but not move any of it (free it, return it, assign it, pass it to sink, @forget it; E144), and it does not have to give it away. Like a slice, a borrow cannot outlive the call. A sink parameter takes the value over: the caller’s variable is moved, and the function must give it away on every path (E135). The call is written the same either way, f(b). One value may be borrowed by several arguments of a call; it may not be both borrowed and passed as inout (E117), and a value moved into a sink parameter may not appear in another argument. A borrowed temporary would never be freed, so count(a.alloc(2, 0)) is E133 unless count takes it by sink; .empty may be borrowed. A function value follows the modes in its type (section 19).

// expect: 3
// expect: 3
uses alloc, io

fn count(b: Buf(i64)) i64 {
    return @len(b)
}

fn eat(a: Allocator, sink b: Buf(i64)) void {
    a.free(b)
}

fn main(io: Io, a: Allocator) void {
    const b = a.alloc(3, 0)
    io.print(count(b))       // borrowed: b is still owned here
    io.print(count(b))
    eat(a, b)                 // moved
}
// error: E144
uses alloc

fn eat(a: Allocator, b: Buf(i64)) void {
    a.free(b)                 // b is only borrowed: declare it sink b
}

fn main(a: Allocator) void {
    const b = a.alloc(3, 0)
    eat(a, b)
    a.free(b)
}

Each buffer has one owner. A move hands it on, and the variable it came from owns nothing until it is assigned a new buffer. The compiler follows every path through each function and checks:

  • a variable is not used after its buffer was moved (E136), so nothing is used after being freed and nothing is freed twice;
  • every buffer is moved before its owner goes away: at the end of its block, at a return, break or continue, and where a try returns an error; and a variable that still owns one is not assigned another (E135). So nothing leaks. An inout buffer parameter belongs to the caller, so it must own a buffer whenever the function returns. A buffer moved into a struct or array literal, or into a sink argument, belongs to what is being made until it is made, so a later try in the same literal or call, or a catch or orelse there that leaves, would lose it (E135): in V{ .a = try make(a), .b = try make(a) }, compute the parts into locals first;
  • paths that join agree on what was moved (after an if, a switch, a catch, the right side of and/or), and an iteration of a loop leaves each buffer from outside it as it found it (E134);
  • while for (b) iterates over a buffer, the body may change its elements but not move, reassign or resize it (E137). It may pass b, or a struct holding it, as inout to a function that cannot move, reassign or resize b either: the compiler sums up, for each function, which parts of its inout parameters it may change, directly or through the functions it calls, so s.bump() inside for (s.items) is fine when bump only changes s.hits. An Allocator method is always taken to resize what it is given, so a.push(&b, x) in the loop stays E137.

An owned value moved into a call may not appear in another argument of it (E117), so a slice of it cannot outlive it. Owned values cannot be compared or printed, except a Buf(u8), which is text (section 8).

Owned structs and containers. A struct with a Buf field, an array of buffers and a buffer of buffers are owned too: they move like a buffer, and a.free(v) frees everything they hold, the elements of an array or buffer in order and a struct’s fields last declared first (they may depend on earlier ones). A !T or ?T of one must be unwrapped right away (try, catch, orelse), so it cannot be a field or a union member; an owned value cannot be a pointer’s target (E133). Borrowing from a temporary, as in @len(make(a)) or make_list(a).len, is E133 too: nothing could free it.

The fields of a struct variable are followed one by one. Moving v.data (freeing it, passing it on) leaves v partly moved: its other fields can still be used, but v as a whole cannot (E136) until v.data = ... gives it a buffer again. When v goes away, every buffer field must have been moved (E135). An inout struct parameter must own all its buffers again when the function returns, so a method fn push(inout self: List, ...) may resize self.data in place.

Elements of arrays and buffers are not followed: xs[i] can be borrowed (xs[i][j], @len(xs[i]), xs[i].len, &xs[i]), but moving it out or assigning over it is E139. Elements are swapped instead:

  • Buf(T).empty (or .empty where the type is known) is a buffer with no elements, which owns no memory and costs nothing to free;
  • @swap(&xs, i, j) exchanges two elements of a buffer, an array or an inout slice, so it needs no value to leave behind and works on any element type: this is how std/sort reorders elements that own buffers. Each index is checked (index out of bounds), and i == j changes nothing. The container must be writable, as for xs[i] = v.
  • @replace(&p, v) puts v in the place p and returns what was there; @take(&p) is @replace(&p, Buf(T).empty) for a buffer place. The place is found first, then the value is computed. The value may not mention the place’s variable at all, not even another field of it (E117): @replace(&v.data, v.len) is rejected, unlike the field-by-field rule for inout arguments.

a.alloc, a.resize and @splat copy their fill value, so for owned elements it must be made of .empty buffers (E140): a.alloc(n, Buf(u8).empty), List{ .data = .empty, .len = 0 }. An array literal moves each element in, as a struct literal moves its fields: [_]Buf(u8){ first, second } takes both over, and [2]Buf(i64){ .empty, .empty } owns nothing yet. Shrinking a buffer of buffers with a.resize frees the elements cut off. While for (xs) |x| iterates over owned elements, x only borrows each one (moving it is E139), and the body may not swap elements of xs (E137).

Owned unions. A union with an owned member (a buffer, an owned struct, or a value holding one) is owned too, and moves like a buffer. Building one (Msg{ .text = b }) moves the payload in; a member without a payload owns nothing (.ping, which may also fill a.alloc). a.free(m) frees the payload of the member that is live. Only that member is live, so the union is followed as one value: it is moved whole or not at all.

A switch over an owned union reads it from a place, or takes one a call has just made (switch (tx.try_send(v)), switch (@replace(&xs[i], .ping))) when each member whose payload is owned has an arm of its own that captures it: that arm owns the capture and gives it away (E135). An element is a place, not such a result: its buffer still owns the payload, so a capture of it only borrows (E139 to move it). A payload an arm leaves uncaptured (an else, |_|, or an arm for several members) would stay in the temporary and never be freed: E133. Each capture borrows the payload, unless its arm moves the capture or any part of it: then that arm takes the payload out, which moves the union, and the capture is owned there and must be given away like any local (E135). An arm for members that own nothing has nothing to free, so it agrees with the others either way; arms whose payload is owned must agree with each other (E134): all take it out, or none does. After the switch the union is moved if the arms took it out, and owned (to free or pass on) otherwise. A union that cannot be moved here, such as a plain parameter or an element of a buffer, only lends its payload: moving the capture is E139.

// expect: hello
// expect: 5
// expect: 3
uses alloc, io

const Msg = union(enum) {
    text: Buf(u8)
    nums: Buf(i64)
    ping

    fn show(self: Msg, io: Io) void {
        switch (self) {
            .text => |t| {
                io.print(t)                // borrowed
            }
            .nums => |n| {
                io.print(@len(n))
            }
            .ping => {
                io.print("ping")
            }
        }
    }
}

// Takes the payload out: m is moved by the arms that move their capture.
fn size(a: Allocator, sink m: Msg) i64 {
    switch (m) {
        .text => |t| {
            const n = @len(t)
            a.free(t)
            return n
        }
        .nums => |n| {
            const k = @len(n)
            a.free(n)
            return k
        }
        .ping => {
            return 0                       // nothing to free
        }
    }
}

fn main(io: Io, a: Allocator) void {
    const m = Msg{ .text = a.concat("hel", "lo") }
    m.show(io)
    io.print(size(a, m))
    var box: Buf(Msg) = .empty
    defer a.free(box)                      // frees each live payload
    a.push(&box, Msg{ .nums = a.alloc(3, 0) })
    a.push(&box, .ping)
    const first = size(a, a.pop(&box) orelse .ping)
    io.print(first + size(a, a.pop(&box) orelse .ping))
}
// error: E134
uses alloc, io

const Msg = union(enum) { text: Buf(u8), nums: Buf(i64), ping }

fn main(io: Io, a: Allocator) void {
    const m = Msg{ .text = a.concat("a", "b") }
    switch (m) {
        .text => |t| {
            a.free(t)                      // takes m's payload out
        }
        .nums => |n| {
            io.print(@len(n))              // but this arm keeps it
        }
        .ping => {}
    }
}

Owned structs. const Db = owned struct { ... } declares a struct that is owned for itself, with or without buffers: a resource such as an open file or a database handle, which must be released exactly once. It moves like a buffer, so a copy cannot release it again (E136), and it must be given away on every path (E135, E134). Only the file that declares it may build one (Db{ ... }) or end one with @forget(v), which runs nothing (E142); everywhere else a value comes from that file’s functions and ends by being passed to one that takes it by sink, such as fn close(sink self: Db) void { ...; @forget(self) }. Methods that only read it take self, methods that change it inout self; only its file may change its fields (assign them, pass them as inout, @replace them; E142), though any file may read them. @forget ends only the struct itself: buffers in its fields must still be freed, and it needs a variable or a field of one, not a temporary (E133).

An owned struct may have a deinit: fn deinit(sink self: T) void, or fn deinit(sink self: T, a: Allocator) void (E143 for any other shape). It is what a.free calls to end one, so it must end everything the struct holds, and a struct holding owned structs ends each by its deinit. Only with a deinit may an owned struct, or something holding one, be freed with a.free or be an element of an array or a Buf (E141). Neither a.alloc, a.resize nor @splat can copy one into elements (E140): fill a Buf with a.push. A deinit is never called on its own: a local must still be ended explicitly (E135), with x.deinit() (x.deinit(a) for the form that takes an allocator) or any other sink self method.

A struct holding an owned struct is owned, and is followed field by field as above.

// expect: open 1
// expect: 101
// expect: closed 1
uses io

const File = owned struct {
    fd: i64

    fn write(inout self: File, io: Io, n: i64) void {
        io.print(100 * self.fd + n)
    }

    fn close(sink self: File, io: Io) void {
        io.print("closed 1")
        @forget(self)
    }
}

fn open(io: Io) File {
    io.print("open 1")
    return File{ .fd = 1 }
}

fn main(io: Io) void {
    var f = open(io)
    defer f.close(io)
    f.write(io, 1)
}
// error: E135
uses io

const File = owned struct {
    fd: i64

    fn close(sink self: File) void {
        @forget(self)
    }
}

fn main(io: Io) void {
    const f = File{ .fd = 1 }
    io.print(f.fd)          // f is never closed
}
// expect: 2
// expect: 1
// expect: 2
uses alloc, io

const Conn = owned struct {
    id: i64

    fn deinit(sink self: Conn) void {
        @forget(self)
    }
}

fn open(id: i64) Conn {
    return Conn{ .id = id }
}

fn main(io: Io, a: Allocator) void {
    var pool: Buf(Conn) = .empty
    defer a.free(pool)               // deinit on each one left
    a.push(&pool, open(1))
    a.push(&pool, open(2))
    io.print(@len(pool))
    const c = a.pop(&pool) orelse return
    io.print(@len(pool))
    io.print(c.id)
    c.deinit()
}

defer. defer e runs the void expression e when its block is left, however that happens: at its end, at return (after the value is computed), break, continue, or a try that returns an error. Several run last first. errdefer e, only in a function returning !T, runs only when the function returns an error. Neither may contain try (E118). The ownership check counts what they do at every way out, so defer a.free(b) right after making b frees it exactly once.

// expect: 10
// expect: 20
// expect: 5
uses alloc, io

fn sum(xs: []i64) i64 {
    var total = 0
    for (xs) |x| {
        total = total + x
    }
    return total
}

// Takes the buffer, frees it, and returns a new one.
fn doubled(a: Allocator, sink b: Buf(i64)) Buf(i64) {
    var out = a.alloc(@len(b), 0)
    for (b) |x, i| {
        out[i] = 2 * x
    }
    a.free(b)
    return out
}

fn range(a: Allocator, n: i64) !Buf(i64) {
    var b = a.alloc(n, 0)
    errdefer a.free(b)       // only if an error leaves the function
    var i = 0
    while (i < n) {
        if (i > 99) {
            return error.TooLong
        }
        b[i] = i + 1
        i = i + 1
    }
    return b
}

fn main(io: Io, a: Allocator) !void {
    var b = try range(a, 4)
    defer a.free(b)          // whatever b owns when main returns
    io.print(sum(b[0..]))
    b = doubled(a, b)        // moved in, and a new buffer back
    io.print(sum(b[0..]))
    a.resize(&b, 5, 0)
    io.print(@len(b))
}
// expect: 3
// expect: 33
// expect: 2
uses alloc, io

const List = struct {
    data: Buf(i64)
    len: i64

    fn push(inout self: List, a: Allocator, x: i64) void {
        if (self.len == @len(self.data)) {
            a.resize(&self.data, 2 * self.len + 1, 0)
        }
        self.data[self.len] = x
        self.len = self.len + 1
    }
}

fn main(io: Io, a: Allocator) void {
    var l = List{ .data = .empty, .len = 0 }
    l.push(a, 1)
    l.push(a, 2)
    l.push(a, 30)
    io.print(l.len)
    io.print(l.data[0] + l.data[1] + l.data[2])
    a.free(l)                // frees l.data

    var rows = a.alloc(2, Buf(u8).empty)
    defer a.free(rows)       // frees each row, then rows
    a.free(@replace(&rows[1], a.alloc(2, 7)))
    const row = @take(&rows[1])
    io.print(@len(row))
    a.free(row)
}
// error: E136
uses alloc, io

fn main(io: Io, a: Allocator) void {
    const b = a.alloc(3, 0)
    a.free(b)
    io.print(b[0])          // b was moved by a.free
}
// error: E135
uses alloc, io

fn main(io: Io, a: Allocator) void {
    const b = a.alloc(3, 0)
    io.print(@len(b))       // b is never freed
}
// error: E134
uses alloc, io

fn main(io: Io, a: Allocator) void {
    const b = a.alloc(3, 0)
    if (@len(b) > 2) {
        a.free(b)            // freed on one path only
    }
    io.print(1)
}

Pools instead of an arena. There is no arena allocator that frees everything at once: nothing could stop a value allocated from it from being used after the arena is gone. Data that is built together and dropped together goes in a pool instead: a Buf of plain records that refer to each other by index. The pool is one owned value, so one a.free releases all of it. An index is a plain i64: one from another pool, or one left over after a pop, reads the wrong record or panics with index out of bounds, but never touches freed memory (a wrapper such as const NodeId = struct { i: i64 } keeps indices of different pools apart). A record that holds its own Buf is freed record by record; to keep it at one free per pool, put variable-length parts in a shared pool too and keep a start and a count, which suits data built once and then read, such as a syntax tree:

// expect: 0 1 3 4 2 5
// expect: 20
uses alloc, io

const Op = enum { num, add, mul }

// A node's children are kids[first_kid .. first_kid + kid_count].
const Node = struct { op: Op, val: i64, first_kid: i64, kid_count: i64 }

const Tree = struct {
    nodes: Buf(Node)
    kids: Buf(i64)

    fn num(inout self: Tree, a: Allocator, v: i64) i64 {
        a.push(&self.nodes, Node{ .op = .num, .val = v, .first_kid = 0, .kid_count = 0 })
        return @len(self.nodes) - 1
    }

    // l and r are built first, so their ids go to the end of kids.
    fn bin(inout self: Tree, a: Allocator, op: Op, l: i64, r: i64) i64 {
        const first = @len(self.kids)
        a.push(&self.kids, l)
        a.push(&self.kids, r)
        a.push(&self.nodes, Node{ .op = op, .val = 0, .first_kid = first, .kid_count = 2 })
        return @len(self.nodes) - 1
    }

    fn eval(self: Tree, id: i64) i64 {
        const n = self.nodes[id]
        if (n.op == .num) {
            return n.val
        }
        var acc: i64 = 0
        if (n.op == .mul) {
            acc = 1
        }
        for (self.kids[n.first_kid..n.first_kid + n.kid_count]) |k| {
            if (n.op == .add) {
                acc = acc + self.eval(k)
            } else {
                acc = acc * self.eval(k)
            }
        }
        return acc
    }
}

fn main(io: Io, a: Allocator) void {
    var t = Tree{ .nodes = .empty, .kids = .empty }
    defer a.free(t)                  // the whole tree: two buffers
    // (2 + 3) * (4 * 1)
    const sum = t.bin(a, .add, t.num(a, 2), t.num(a, 3))
    const prod = t.bin(a, .mul, t.num(a, 4), t.num(a, 1))
    const root = t.bin(a, .mul, sum, prod)
    var ids: Buf(u8) = .empty
    defer a.free(ids)
    for (t.kids) |k| {
        a.append_int(&ids, k)
        a.append_str(&ids, " ")
    }
    io.print(ids[0..@len(ids) - 1])
    io.print(t.eval(root))
}

Struct of arrays: MultiArrayList(T). MultiArrayList(T), for a struct T with at least one field (E156), holds a list of T the way a pool of records is often laid out for speed: one column per field, all in one allocation, so a loop over one field reads only that field’s memory (as Zig’s MultiArrayList, whose name it takes). A MultiArrayList(T) is owned like a Buf: MultiArrayList(T).empty (or .empty) owns nothing, it is moved, borrowed and freed by a.free(s) like a buffer, and it may be a field, an element or a Shared value. Its methods:

Method Does
s.append(a, v) moves the T v in at the end (capacity doubles, as for a.push)
s.len() how many elements, as i64
s.get(i) element i, copied out as a T (index out of bounds unless 0 <= i < s.len())
s.set(i, v) element i replaced by v, field by field
s.replace(i, v) puts v in at i and returns the element that was there
s.pop() the last element as a ?T, removed; null when empty
s.swap_remove(i) removes element i and returns it, moving the last element into its place
s.items(.f) the column of field f, a []F viewing s

append, set, replace, pop and swap_remove change s, which must be a var or an inout parameter (E105); the others borrow it. Each column is a place of its own, as each field of a struct is: s.items(.x) borrows s.x, not all of s, so the rules for local slices (section 12) let inout xs = &s.items(.x) write one column while another is read or written, and &s.items(.x) may be passed to an inout slice parameter beside s.items(.vx) in the same call (E117 only for the same column). get, set, replace and everything that changes s’s length touch every column; len touches none, so it may be read while a column is written.

T’s fields may own memory, as a Buf’s elements may (an owned struct needs a deinit, E141). Such an element exists only as its columns, so nothing copies it out or drops it: get and set are E139 for it. A field of one is borrowed from its column, s.items(.name)[i], and swapped through a writable column with @replace or @take; whole elements go in with append and replace (moved, as into a sink parameter) and come out with replace, pop and swap_remove, which hand them to the caller to free or pass on. a.free(s) frees every element’s fields.

// expect: 10 30 50
uses alloc, io

const Particle = struct { x: i64, vx: i64 }

fn step(inout xs: []i64, vs: []i64) void {
    for (vs) |v, i| {
        xs[i] = xs[i] + v
    }
}

fn main(io: Io, a: Allocator) void {
    var ps: MultiArrayList(Particle) = .empty
    defer a.free(ps)
    var i: i64 = 0
    while (i < 3) {
        ps.append(a, Particle{ .x = 10 * i, .vx = i + 1 })
        i = i + 1
    }
    inout xs = &ps.items(.x)             // one column written ...
    const vs = ps.items(.vx)             // ... while another is read
    for (vs) |v, j| {
        xs[j] = xs[j] + 9 * v
    }
    step(&ps.items(.x), ps.items(.vx))
    io.print(ps.get(0).x, " ", ps.get(1).x, " ", ps.get(2).x)
}
// error: E149
uses alloc, io

const Particle = struct { x: i64, vx: i64 }

fn main(io: Io, a: Allocator) void {
    var ps: MultiArrayList(Particle) = .empty
    defer a.free(ps)
    ps.append(a, Particle{ .x = 1, .vx = 2 })
    const xs = ps.items(.x)
    ps.append(a, Particle{ .x = 3, .vx = 4 })   // may move the column xs views
    io.print(xs[0])
}