Strings

A str is a pointer to a NUL-terminated sequence of bytes. Literals live in the binary, everything built at runtime lives in the arena and is released with the scope that created it.

Literals and escapes

s = "Hello world\n"
quote = "she said \"hi\""     // double quote
tab = "a\tb"
crlf = "line\r\n"
empty = ""
c = 'x'                       // a char, not a str
nul = '\0'

Supported escapes: \n, \t, \r, \0, \". There is no \\ escape for a literal backslash; build one with "" + int_to_char(92) when needed. Adjacent literals inside parentheses are concatenated at compile time (see Program structure). Non-ASCII text is passed through as raw bytes: strlen("é") is 2.

Building strings

#include <libstd/stdio>

name = "TryC"
n = 3
msg = "Hello " + name + ", you have " + itoa(n) + " items\n"
print(msg)

line = "-" * 20 + "\n"       // repetition
initial = "" + 'T'            // a one-character string from a char
Hello TryC, you have 3 items
--------------------

Conversions: itoa(int or long) -> str, ftoa(float) -> str (six decimals, rounded like C's %f; nan, inf, -inf), char_to_int/int_to_char between a byte and its code. print accepts numbers directly and converts them the same way.

Comparing

== and != compare contents: the same length and the same bytes, all of them, also after a NUL byte inside a sealed string. Two equal strings allocated separately are equal.

a = "abc"
b = "ab" + "c"
if a == b:
    print("same content\n")
if startswith(a, "ab") == 1:
    print("prefix\n")

Indexing and length

s = "hello"
first = s[0]                 // 'h', a char
print(strlen(s), "\n")       // 5
s[0] = 'H'                   // strings are mutable bytes
bounds of s[i]

On a sealed string (see below) s[i] is checked against the length in its header, like a[i] on an array. A read may go up to the terminator, s[len], so while s[i] != '\0' loops keep working; a write must stay below it. Anything else, a negative index included, stops the program with "string index out of bounds" and the crash report. A string that is not sealed (a buffer you are still filling, an interior pointer s + n, a string from C) has no length to check against, so there s[i] is still a plain byte access; inside unsafe: the check is off. Where the compiler can prove the index in bounds it leaves the check out. It reasons on what the function itself says about the index: the conditions of its ifs and loops, the assignments, the accesses already made, and what stays true across the turns of a loop (a counter that starts at 0 and only grows stays at or above 0). So s[i + 1] under s[i] != '\0', s[i] under i < n with n = strlen(s), text[offset + k] under k < len_word and offset <= len_text - len_word, and a loop that walks back from len - 1 to 0 all go unchecked. The terminator counts too: a sealed string always has it at len (rt_str_seal writes it, and a checked write never reaches it), so s[i] != '\0' means i < len. Index arithmetic is 32-bit, and every proof also shows that no sum wraps around: that is what the length limit below is for. A literal is stored in read-only memory: writing into one crashes.

The length header

A str value is still a pointer to NUL-terminated bytes, but the 16 bytes before the pointer are a header the runtime owns (see Runtime internals): a tag that says "this is a string with a valid length" and the length itself. A string is at most 231 − 2 bytes long (about 2 GiB), so that every index up to len, and the one after it, fits in an int: building, growing or measuring a longer one stops the program with "string too long". Java and C# have the same kind of limit. A string that carries it is sealed, and strlen on it costs one compare instead of a scan; == between two sealed strings of different lengths answers without touching the bytes. Sealed by construction: literals, the result of +, *, itoa/ftoa, substrget/get_chars_in_range, the rows of a Reader, readfile, input/readline. Not sealed: a raw buffer from rt_alloc_up that you fill yourself (call rt_str_seal(buf, len) when done), an interior pointer s + n, and any string that comes from C. For those strlen scans exactly as before, so nothing breaks; it is only slower.

Two rules follow. A string from a C library (char*) has no header: type it ptr char and copy it with str_from_c(p) (or measure it with strlen_c), never read its length as if it were a str. And never shorten a sealed string by writing a NUL into it: the header would keep the old length. Cut it with substrget instead; under --check-arena a stale length is reported as soon as strlen sees it.

Common operations

All in libstd/string (#include <libstd/string>). A selection:

FunctionDoes
strlen(s)length in bytes, a long (positions and counts below are long too)
findsubstr(s, sub), find_char(s, c), rfind(s, c)first/last position, -1 if absent
startswith(s, p), endswith(s, p)1 on match, -1 otherwise
substrget(s, n), get_chars_in_range(s, a, b)copies: the first n bytes, the bytes in [a, b)
strip(s, chars), lstrip, rstripremove leading/trailing characters; "" means whitespace
replace(s, old, new)replace every occurrence
split_count(s, sep), split_next(s, sep, off)split on a separator, one piece per call
joiner_new(sep), joiner_add, joiner_resultjoin pieces with a separator
new_reader(text), reader_next_rowiterate a text line by line
#include <libstd/string>

off = 0 as long
while 1:
    off, piece = split_next("a,b,c", ",", off)
    print(piece, "\n")
    if off == -1:
        break

Cost model

Every + allocates a new string in the arena (one 512-byte block minimum) and copies its operands. A chain of strings and characters such as "x: " + itoa(i) + " y: " + itoa(j) + "\n" is built with a single allocation, not one per +, and s * n fills a single buffer. In a loop this is usually fine because the temporaries die with the iteration, but building a long string with repeated s = s + piece would copy the growing prefix every time. The compiler avoids the quadratic cost with a self-concatenation fast path: when a variable, local or global, is reassigned as x = x + term or x = x + a + b + ..., the compiler switches x to a growable buffer with cached length and spare capacity: the append is in place while the buffer is exclusive and has room, otherwise it doubles. 200,000 one-character appends run in a few milliseconds.

When the pointer is copied somewhere else (another variable, a call argument, a list or dict, a field, a pointer into the buffer, a cast), the buffer becomes shared and the next append copies it first, so the copy never sees the string change.

Strings as bytes and pointers

Because a str is a pointer, it doubles as the byte-buffer type of the language: rt_alloc_up(n) gives a zeroed buffer of n bytes (rt_alloc(n) as str is the same inside unsafe:), sys_read(fd, buf, n) fills it, buf + offset is pointer arithmetic (an interior pointer into the same allocation, see The arena), and memcpy(dst, src, n) copies raw bytes. This is the C side of the language; the memory safety page discusses its consequences.