Spec chapters

8. Strings

str is an immutable sequence of bytes: a literal, a slice of a str, or a copy made by a.leak (section 17). None of them is ever freed, so a str is always valid.

  • @len(s) is its length in bytes; s[i] is the byte at i, a u8, compared with a character literal as s[i] == 'h'; s[lo..hi] and s[lo..] are strs.
  • == compares contents. for (s) |b| visits each byte.
  • A str holds text that lives as long as the program, so it is copied freely. Text a program builds is a Buf(u8) it owns and frees: a.concat(s, t) and a.int_str(n) (section 17).
// expect: 5
// expect: 104
// expect: ell
// expect: true
uses io

fn main(io: Io) void {
    const s = "hello"
    io.print(@len(s))
    io.print(s[0])
    io.print(s[1..4])
    io.print(s[1..] == "ello")
}
// expect: 13
// expect: 3
uses io

fn main(io: Io) void {
    const crlf = "\r\n"
    io.print(crlf[0])        // \r is byte 13
    io.print(@len("a\r\n"))
}

Text that is freed: Buf(u8)

Text a program builds is a Buf(u8): an ordinary buffer (section 21), which owns its bytes and is freed with a.free. Three Allocator methods add text at its end, growing it as a.push does:

Written Adds
a.append_str(&b, s) the bytes of the text s
a.append_int(&b, n) the integer n in decimal
a.append_float(&b, x) the float x as io.print writes it

Text here is a str, a []u8, a Buf(u8), or a slice of one of them; each is only read. Text in any of these forms:

  • is lent to a []u8 parameter (fn count(s: []u8) i64 takes count("abc"), count(b) and count(b[1..])). A slice cannot be stored, so the bytes cannot outlive a Buf(u8) that is freed or grown;
  • prints with io.print, as its bytes;
  • compares with == and != by its bytes, whatever kind each side is (b == "id=7", b[0..2] == s); a slice may be compared directly;
  • orders with <, <=, > and >= by its bytes, as unsigned numbers, a text sorting before any longer one it starts ("ab" < "abc", "B" < "a"); text and a number cannot be ordered (E103);
  • is copied by a.concat(s, t, ...) into a new Buf(u8), or by a.leak(t) into a str that is never freed: a.leak(b) keeps the text of b after b is freed, at the cost of memory for the rest of the program.

The Buf(u8) itself follows the buffer rules: a.append_str(&b, b) is E117, growing it while for (b) reads it is E137, and a temporary one cannot be lent (E133). Appending needs a Buf(u8) and text (E103).

// expect: id=7, x=1.5
// expect: true
// expect: 2
uses io, alloc

fn count(s: []u8, c: u8) i64 {
    var n: i64 = 0
    for (s) |x| {
        if (x == c) {
            n = n + 1
        }
    }
    return n
}

fn main(io: Io, a: Allocator) void {
    var b: Buf(u8) = .empty
    defer a.free(b)
    a.append_str(&b, "id=")
    a.append_int(&b, 7)
    a.append_str(&b, ", x=")
    a.append_float(&b, 1.5)
    io.print(b)
    io.print(b[0..4] == "id=7")
    io.print(count(b, 61))
}