17. Capabilities
A capability is something the core does not have: the standard streams,
command-line arguments, files, the network, threads and heap allocation
so far. A file declares the capabilities it needs on a uses line:
uses alloc, io
Naming an unknown capability, or one twice, is E128. Each capability comes with a value type that is the only way to use it:
| Capability | Value | Methods |
|---|---|---|
io |
Io |
io.print(x, ...): prints one or more values (integers, floats, bool, text, enums, Addr) one after another, with nothing between them, and then a newline, to standard output: io.print(w, ": ", n); io.eprint(x, ...): the same, to standard error, after everything printed before it; io.read_line(a, &line) !bool: replaces the Buf(u8) line with the next line of standard input, without its \n or \r\n, and returns false at the end of the input, with line empty (an empty line returns true; a last line without a line ending is a line); io.read_line_max(a, &line, max) !bool: the same, but a line of more than max bytes, not counting its line ending, fails with error.LineTooLong, and a negative max panics; io.read_all(a) !Buf(u8): the rest of standard input, byte for byte. All three show what was printed before them first, need uses alloc too, and fail with error.IoFailed |
args |
Args |
args.len() i64: how many arguments there are, counting the program’s name; args.get(i) str: argument i, where 0 is the program’s name and the first argument given is 1; an index out of range panics; args.env(name) ?str: the environment variable called name (text), or null when it is not set or name is empty or holds = or a 0 byte, or, on Windows, is not UTF-8. The environment is, like the arguments, what the program was started with, so it is the same args capability. On Windows each call keeps a UTF-8 copy of the value for the rest of the program, so read a variable once rather than in a loop |
net |
Net |
net.tcp_connect(host, port) !TcpConn, net.tcp_listen(host, port) !TcpListener, net.udp_bind(host, port) !UdpSocket, net.resolve(host, port) !Addr, net.poller() !Poller: see below |
thread |
Threads |
threads.spawn(f, x, ...) Thread: runs f(x, ...) on a new thread; threads.channel(T, n) Receiver(T): a channel of T that holds up to n values (with 0, a sender waits for the receiver); see below |
fs |
Fs |
fs.read(a, path) !Buf(u8): the whole file; fs.write(path, data) !void: the file holds exactly the text data, replacing what it held; fs.open(path) !Reader, fs.create(path) !Writer (a new or emptied file), fs.append(path) !Writer: open files; fs.open_dir(path) !DirReader, fs.make_dir(path) !void, fs.remove_file(path) !void, fs.remove_dir(path) !void, fs.rename(from, to) !void, fs.stat(path) !Stat, fs.real_path(a, path) !Buf(u8): directories and names; see below |
alloc |
Allocator |
a.concat(s, t, ...) Buf(u8): two or more texts, one after another (section 8); a.leak(t) str: a copy of the text t that is never freed; a.append_str(&b, s), a.append_int(&b, n), a.append_float(&b, x): text at the end of a Buf(u8), section 8; a.int_str(n) Buf(u8): the integer n in decimal; a.float_str(x) Buf(u8): the float x as io.print writes it; a.cstr(s) *u8, a.str_from_c(p) Buf(u8): C strings, section 20; a.create(v) *T: a pointer to a copy of v; a.alloc(n, v) Buf(T), a.free(b), a.resize(&b, n, v), a.push(&b, v), a.pop(&b) ?T: buffers, section 21 |
fs is separate from io so that a file’s uses line says what it can
reach: a program that only prints cannot touch a file.
The clock and random bytes are not capabilities: reading them changes
nothing outside the program and reaches nothing in it, so any code may.
std/time has time.now() i64, the time in nanoseconds since 1970-01-01
UTC, from the system’s clock, which may be set back, and
time.monotonic() i64, nanoseconds since an unspecified start, never
decreasing, for measuring how long something took; failing to read a
clock panics cannot read the clock. std/rand has rand.fill(&b[lo..hi]),
which replaces every byte of a writable []u8 (section 12) with bytes from
the system’s cryptographic random source (getentropy, or
BCryptGenRandom on Windows): &b[0..] for a whole Buf(u8), or
&key[0..] for an array, so a key never passes through a Buf; failing to
read them panics cannot read random bytes. Code that declares no
capability gives the same results on the same input only when it reads
neither.
// expect: true true
uses io
const time = @import("std/time")
const rand = @import("std/rand")
fn main(io: Io) void {
const t0 = time.monotonic()
var key: [32]u8 = @splat(0)
rand.fill(&key[0..])
var any = false
for (key[0..]) |x| {
any = any or x != 0
}
io.print(any, " ", time.monotonic() >= t0)
}
// expect: 5
uses alloc, fs, io
fn main(io: Io, files: Fs, a: Allocator) !void {
try files.write("egg_spec_fs.txt", "hello")
const text = try files.read(a, "egg_spec_fs.txt")
defer a.free(text)
io.print(@len(text))
}
A path and data are text (section 8), and a file is bytes: fs.read makes
no assumption about its encoding, and the Buf(u8) belongs to the caller
(section 21). fs.read uses alloc too, so its file declares both.
fs.write does not create directories, and a write that fails may leave the
file incomplete. A failure is one of these errors:
| Error | Means |
|---|---|
error.NotFound |
no such file, or a directory on the path is missing |
error.PermissionDenied |
the system refused access |
error.IsDirectory |
the path names a directory |
error.InvalidPath |
the path holds a 0 byte, is too long, or is not a name the system accepts (on Windows, a path that is not UTF-8) |
error.IoFailed |
anything else, such as a full disk |
error.AlreadyExists |
make_dir of a name that is taken |
error.NotEmpty |
remove_dir of a directory that holds something |
error.NotDirectory |
remove_dir or open_dir of something that is not a directory |
// fails: NotFound
uses alloc, fs
fn main(files: Fs, a: Allocator) !void {
const text = try files.read(a, "/nonexistent/egg/file")
a.free(text)
}
Open files. For a file read or written bit by bit, fs.open,
fs.create and fs.append return an owned value. Reading and writing are
two types, so using the wrong one is a compile error:
| Type | Methods |
|---|---|
Reader |
r.read_line(a, &line) !bool, r.read_line_max(a, &line, max) !bool and r.read_all(a) !Buf(u8), as on Io; r.read(a, &buf, n) !i64: up to n bytes in place of what buf held, how many, and 0 at the end; r.seek(pos) !void: the next read starts at byte pos of the file (a negative pos panics; past the end, reads find the end); r.close() |
Writer |
w.print(x, ...) !void: as io.print; w.write(text) !void: the bytes, nothing added; w.flush() !void: sends what is buffered to the system; w.close() |
A Reader or Writer is owned, like an owned struct with no deinit: one
that is not closed on every path is E135, and one used after close is
E136. It can be held by an owned struct that closes it in its deinit, but
only fs makes one (E142), and its methods need uses fs.
A file or directory a program opens is closed in a child process that C
code it calls may start, once the child runs another program: it is
close-on-exec on Unix from the moment it is opened, and not inheritable on
Windows. A child made by fork alone, which runs no other program, still
shares it. Standard input, output and error are inherited.
close cannot fail, so it fits a defer. Writing is buffered, so a failure
such as a full disk may appear only when the buffer is sent: finish with
try w.flush(), or a failure in what is left is lost when close runs.
Reading with read_line, read_line_max, read_all or read needs uses alloc too, and
reads and writes fail with error.IoFailed; open, create and append
fail as fs.read does.
// expect: hello
// expect: done
uses alloc, fs, io
fn save(files: Fs) !void {
const w = try files.create("egg_spec_note.txt")
defer w.close()
try w.print("hello")
try w.flush()
}
fn main(io: Io, files: Fs, a: Allocator) !void {
try save(files)
const r = try files.open("egg_spec_note.txt")
defer r.close()
var line: Buf(u8) = .empty
defer a.free(line)
while (try r.read_line(a, &line)) {
io.print(line)
}
io.print("done")
}
Directories and names. fs.make_dir(path) makes one directory, whose
parent must exist. Removing names the kind of thing removed:
fs.remove_file removes a file (a directory is error.IsDirectory) and
fs.remove_dir an empty directory (error.NotEmpty otherwise), so a
mistyped path cannot remove the wrong thing. A symbolic link to a file is removed
with remove_file, and what it points at stays. fs.rename(from, to)
moves a file or directory to a new name, replacing a file already called
to; whether a directory can replace another one depends on the system,
so give a directory a name that is free.
fs.stat(path) !Stat tells what a path names, following symbolic links. A
Stat is a plain value with three fields: kind, a FileKind (.file,
.dir or .other, such as a device), size, the bytes of a file (0
for anything else), and modified, when it was last written, in
nanoseconds since 1970-01-01 UTC as time.now() counts them (as finely as
the file system keeps it; a time before 1677-09-21T00:12:43.145224192Z or
after 2262-04-11T23:47:16.854775807Z, which an i64 of nanoseconds cannot
hold, is the smallest or largest i64). fs.real_path(a, path) !Buf(u8) is the absolute path
with every symbolic link, . and .. resolved, for checking that a path
stays inside a directory; it fails with error.NotFound unless the path
exists. Stat, FileKind and DirReader are names of the language, as
Reader is.
fs.open_dir(path) !DirReader lists a directory. Like a Reader, a
DirReader is owned and closed with d.close(). d.next(a, &name) !bool
replaces the Buf(u8) name with the next entry’s name, without the
directory in front, and returns false after the last one. . and .. are
left out, and the order is the system’s: sort the names to get one. A
name created or removed while the listing runs may or may not be seen.
next needs uses alloc too and fails with error.IoFailed.
// expect: 2 entries, 7 bytes
uses alloc, fs, io
fn sizes(io: Io, files: Fs, a: Allocator, dir: str) !void {
const d = try files.open_dir(dir)
defer d.close()
var name: Buf(u8) = .empty
defer a.free(name)
var n: i64 = 0
var bytes: i64 = 0
while (try d.next(a, &name)) {
const path = a.concat(dir, "/", name)
defer a.free(path)
const st = try files.stat(path)
if (st.kind == .file) {
n = n + 1
bytes = bytes + st.size
}
}
io.print(n, " entries, ", bytes, " bytes")
}
fn main(io: Io, files: Fs, a: Allocator) !void {
try files.make_dir("egg_spec_dir")
try files.write("egg_spec_dir/a", "abc")
try files.write("egg_spec_dir/b", "defg")
try sizes(io, files, a, "egg_spec_dir")
try files.remove_file("egg_spec_dir/a")
try files.remove_file("egg_spec_dir/b")
try files.remove_dir("egg_spec_dir")
}
The network. host is a name or an IPv4 or IPv6 address, and port
is 0 to 65535 (a panic otherwise); port 0 asks the system for a free one.
Everything blocks, so a server handles one connection
at a time, unless it hands each to a thread.
| Type | Methods |
|---|---|
TcpConn |
c.read_line(a, &line) !bool, c.read_line_max(a, &line, max) !bool, c.read_all(a) !Buf(u8): as on Io, up to when the other side closes; c.read(a, &buf, n) !i64: what has arrived, up to n bytes, in place of what buf held, and 0 at the end; c.write(text) !void: all of it, at once; c.set_timeout(ms) !void; c.peer_ip(a) !Buf(u8): the numeric IP address of the peer, without a DNS lookup; c.clone() !TcpConn: another handle to the same connection; c.close() |
TcpListener |
l.accept() !TcpConn: waits for the next connection; l.port() i64; l.close() |
UdpSocket |
u.recv_from(a, &buf, n) !Addr: the next datagram, in place of what buf held, and who sent it; what does not fit in n bytes is lost; u.send_to(addr, data) !void; u.set_timeout(ms) !void; u.port() i64; u.close() |
Addr |
addr.port() i64; io.print shows it, as 127.0.0.1:80 or [::1]:80 |
TcpConn, TcpListener and UdpSocket are owned, like a Reader, and
only Net makes them, or c.clone() another TcpConn. A clone lets one
thread read a connection while another writes it: it starts with nothing
buffered (what the original had read ahead stays with it), the timeout is
the connection’s and applies to both, and the connection closes when every
handle is closed. Calling a method on a connection or file that is not in a
variable, such as (try c.clone()).write(s), is an error (E133), since
nothing would close it; close is the exception. Addr is a plain value, copied freely. read_line,
read_line_max, read, read_all, recv_from and peer_ip need uses alloc too.
Nothing is buffered on the way out, so there is no flush, and close cannot
fail. set_timeout bounds each later read and write (0 means none; negative
panics), not connecting or accepting.
| Error | Meaning |
|---|---|
error.HostNotFound |
the name is unknown or has no address, or holds a 0 byte |
error.ConnectionRefused |
nothing listens at that port |
error.ConnectionReset |
the other side went away |
error.AddressInUse |
something already holds that port |
error.TimedOut |
set_timeout’s time passed |
error.PermissionDenied |
the system refused, as for a low port |
error.IoFailed |
any other failure, such as a name server that does not answer |
error.LineTooLong |
read_line_max met a longer line. Its first bytes are gone and reading would go on inside it, so treat the input as bad |
error.Closed |
a Poller has no socket by that token (any more), or not of that kind |
A line from the network can be any length, so read_line lets the other
side use all the memory: use read_line_max for anything you do not trust.
The other side closing normally is not an error: read returns 0 and
read_line returns false.
Many sockets on one thread: Poller
Every method above waits. A Poller serves many sockets from one thread
instead: it waits until some are ready, and then reads, writes and accepts
on them without waiting.
| Type | Methods |
|---|---|
Poller |
p.add(conn, interest) !i64: takes the TcpConn and returns its token; p.add_listener(l) !i64: takes the TcpListener; p.want(t, interest) !void: what to wait for on a connection; p.remove(t) !TcpConn: hands the connection back; p.wait(a, &events, ms) !i64: waits until some sockets are ready or ms milliseconds pass (-1: no limit, 0: does not wait; below -1 panics), and puts in events (a Buf(PollEvent), in place of what it held) one event for each, and how many; p.accept(t) !?TcpConn: a connection waiting at listener t, or null if none is; p.read(t, a, &buf, n) !?i64: what has arrived, up to n bytes, in place of what buf held, and how much, or null if nothing has; with n above 0, a 0 is the end (an n of 0 reads nothing and returns 0); p.write(t, text) !i64: how much of text went out now, maybe none; p.waker() !Waker; p.close(): closes the poller and every socket in it |
Waker |
w.wake(): makes the poller’s wait return now, with an event of token -1; w.close() |
PollEvent |
a plain struct: token: i64, readable: bool, writable: bool, hangup: bool (the other side closed or the socket failed) |
Interest |
an enum: .read, .write, .read_write |
The poller owns what is added to it, so the variable given to add cannot
be used after (E136), and a Poller and a Waker must be closed (E135),
as a TcpConn. Tokens count up from 1 and are not used again, so an event
for a socket removed while handling the same batch finds error.Closed.
A connection handed back by remove, and one accept gives, waits again
on every method; one added waits on none.
Readiness is level-triggered: a socket with something to read is reported
by every wait until it is read, so handling part of an event is not
missing it; bytes a connection had read ahead before it was added count as
something to read. A Waker can go to another thread (it is owned, and
moves as a Sender does); waking a poller that is closed does nothing.
One poller is for one thread at a time; serve more cores with a poller
each. Underneath: epoll on Linux, kqueue on macOS and the BSDs, WSAPoll
on Windows, poll elsewhere.
// An echo server on one thread, and a client of it.
// expect: hello
uses alloc, io, net
fn main(io: Io, net: Net, a: Allocator) !void {
const p = try net.poller()
defer p.close()
const listener = try net.tcp_listen("127.0.0.1", 0)
const port = listener.port()
const lt = try p.add_listener(listener)
const client = try net.tcp_connect("127.0.0.1", port)
defer client.close()
try client.set_timeout(5000)
try client.write("hello\n")
var events: Buf(PollEvent) = .empty
defer a.free(events)
var buf: Buf(u8) = .empty
defer a.free(buf)
// What has come of the line so far: a read may return part of it.
var line_in: Buf(u8) = .empty
defer a.free(line_in)
var echoed = false
while (!echoed) {
_ = try p.wait(a, &events, 5000)
var i = 0
while (i < @len(events)) {
const e = events[i]
i = i + 1
if (e.token == lt) {
while (try p.accept(lt)) |c| {
_ = try p.add(c, .read)
}
} else if (try p.read(e.token, a, &buf, 4096)) |n| {
if (n == 0) {
const gone = try p.remove(e.token)
gone.close()
} else {
a.append_str(&line_in, buf)
if (@len(line_in) > 4096) {
// No line is that long: a client could send
// bytes forever. Let it go.
const gone = try p.remove(e.token)
gone.close()
echoed = true
} else if (line_in[@len(line_in) - 1] == '\n') {
// A write may send part: the rest goes out
// waiting, the connection taken back for it.
const sent = try p.write(e.token, line_in)
if (sent < @len(line_in)) {
const c = try p.remove(e.token)
defer c.close()
try c.write(line_in[sent..])
}
echoed = true
}
}
}
}
}
var line: Buf(u8) = .empty
defer a.free(line)
if (try client.read_line(a, &line)) {
io.print(line)
}
}
// expect: 5
uses alloc, io, net
fn main(io: Io, net: Net, a: Allocator) !void {
const server = try net.tcp_listen("127.0.0.1", 0)
defer server.close()
const client = try net.tcp_connect("127.0.0.1", server.port())
defer client.close()
const peer = try server.accept()
defer peer.close()
try client.write("hello")
var buf: Buf(u8) = .empty
defer a.free(buf)
io.print(try peer.read(a, &buf, 16))
}
Threads. threads.spawn(f, x, ...) runs f(x, ...) at once on a new
system thread, for f a function returning void. It returns an owned
Thread, which must end with t.join(), which waits for it, or
t.detach(), which lets it run on; one that does neither is E135. When
main returns, the program ends, detached threads with it. A panic on any
thread ends the program, and so does failing to start a thread.
Nothing is shared but what is made to be. The arguments must be things a
thread can own: f takes owned values by sink, so they move to the new
thread, and plain values by copy. A parameter that would lend something to
it, inout, a slice or a plain owned value, is E148, as is a function that
returns a value. So two threads never reach the same memory, without
locks, except through a Shared(T), which no thread can change, or an
Atomic (below). Capability values
are plain values, and strs never change, so both may be passed. Raw pointers
in an allow unsafe file are the exception: what they point at is not
checked.
One print is one line: lines of different threads do not mix.
Channels. A channel carries values between threads: threads.channel(T,
n) returns its Receiver(T). With n of 0, send returns only once the value
has been received, so the two threads meet; a negative n panics (a channel's
capacity cannot be negative), and a negative literal is E103. Each
sender comes from it. Both ends are owned, and only Threads makes them.
| Type | Methods |
|---|---|
Receiver(T) |
rx.recv() ?T: the next value, waiting for one; null when every sender has closed and nothing is left; rx.recv_timeout(ms) ?T: the same, but waiting at most ms milliseconds, and null when none came in time (ms is an i64; 0 does not wait; a negative ms panics: negative timeout); rx.sender() Sender(T); rx.clone() Receiver(T); rx.close() |
Sender(T) |
tx.send(v): takes v, waiting while the channel is full (and for the receiver, with n of 0); tx.try_send(v) TrySend(T): the same without waiting, see below; tx.clone() Sender(T); tx.close() |
tx.try_send(v) never waits: v goes to a receiver already waiting or
into the channel’s room, or it comes back. Its result is a TrySend(T),
a union of .sent (v went), .full with v (no room now, and with n of 0
no receiver waiting) and .closed with v (every Receiver has closed,
where send panics). A switch on it handles all three, and gets v back
whenever it did not go: a queue that drops what it has no room for, such
as one of spans or log lines, frees it there.
switch (tx.try_send(line)) {
.sent => {}
.full, .closed => |back| { ... } // E127: one member per capture
}
examples/channel_try_send.egg is the tested version, with plain and
owned values, a channel with no room and one whose receivers closed.
A value sent moves, so an owned one still has one owner. Values from one
sender arrive in order. Threads waiting in send take their turns in the order
they came, and so do threads waiting in recv or recv_timeout: none can be
passed over forever. A waiting select stands in the same lines, each arm in
the line of its channel. A channel with no sender yet gives null, so make
the senders before receiving, and a thread that keeps a sender it never
closes makes recv wait forever.
A channel can have several receivers: each thread of a pool takes its own
rx.clone(), and each value goes to one of them, whichever is free. Values
from one sender still leave in order, but what the receivers then do with
them may finish in any order. To add up results, send them to one thread on a
second channel; threads share nothing else.
Owned values cannot be lost: closing the last Receiver of a channel that
still holds owned values panics (a channel closed with values left in it),
and sending once all its Receivers are closed panics for any type (send on
a closed channel). Plain values left in a closed channel are dropped. Receive
until recv gives null. A channel cannot carry a ?T or !T of an owned T (E133).
// expect: 3
uses alloc, io, thread
fn work(io: Io, a: Allocator, sink data: Buf(i64)) void {
defer a.free(data)
io.print(@len(data))
}
fn main(io: Io, a: Allocator, threads: Threads) void {
const t = threads.spawn(work, io, a, a.alloc(3, 0))
t.join()
}
// expect: 49
uses alloc, io, thread
fn square(sink tx: Sender(i64), n: i64) void {
defer tx.close()
tx.send(n * n)
}
fn main(io: Io, threads: Threads) void {
const rx = threads.channel(i64, 1)
defer rx.close()
const t = threads.spawn(square, rx.sender(), 7)
while (rx.recv()) |v| {
io.print(v)
}
t.join()
}
// expect: 30
uses io, thread
fn double(sink jobs: Receiver(i64), sink out: Sender(i64)) void {
defer jobs.close()
defer out.close()
while (jobs.recv()) |n| {
out.send(n * 2)
}
}
fn main(io: Io, threads: Threads) void {
const jobs = threads.channel(i64, 4)
const queue = jobs.sender()
const results = threads.channel(i64, 4)
defer results.close()
const a = threads.spawn(double, jobs.clone(), results.sender())
const b = threads.spawn(double, jobs, results.sender())
var n = 1
while (n <= 5) {
queue.send(n)
n = n + 1
}
queue.close()
var total = 0
while (results.recv()) |r| {
total = total + r
}
a.join()
b.join()
io.print(total)
}
Select. select waits on several channels at once, then runs one arm:
select {
jobs => |j| { ... } // received j from the Receiver jobs
done.send(n) => { ... } // n went out on the Sender done
timeout(100) => { ... } // nothing could go within 100 ms
closed => { ... } // every channel received from is closed
}
It runs once, like switch: a loop goes around it, and break and
continue in an arm act on that loop. First the head of every arm is
evaluated, in order (each channel, each value to send, the milliseconds),
then it waits until some arm can go: a receive when a value is there, a
send when there is room. With n of 0 a send needs a receiver waiting: to
another select waiting to receive, the value is handed over at once; to a
thread waiting in recv, the select goes on once it has taken the value, as
with send. When several arms can go, each is as likely as any other (they are
tried in a random order); once it waits, the first of its arms to be served
goes. A channel whose senders have all closed and that is empty is skipped;
once every channel it receives from is like that, the closed arm runs. A
select of only receiving arms must have one, so a loop around it ends; beside
a sending arm it could never run, since a send goes out or panics (send on a closed channel). Without
timeout, a select waits for as long as it takes; timeout(ms) follows the
rules of recv_timeout (0 does not wait; a negative ms panics).
A receiving arm whose values are owned must name the value (=> |v|) and give
it away in the arm. A sent value moves only if its arm runs: in the other arms
it is still yours, so an owned one is sent from a variable or a field, and the
other arms give it away themselves (E134 otherwise). A head cannot try
(E153). Inside select’s braces, timeout(...) and closed name these arms.
// expect: 7
// expect: kept 2
uses alloc, io, thread
fn give(sink tx: Sender(i64)) void {
defer tx.close()
tx.send(7)
}
fn offer(io: Io, a: Allocator, tx: Sender(Buf(u8)), sink b: Buf(u8)) void {
select {
tx.send(b) => {
}
timeout(0) => {
io.print("kept ", @len(b))
a.free(b)
}
}
}
fn main(io: Io, a: Allocator, threads: Threads) void {
const nums = threads.channel(i64, 0)
defer nums.close()
const t = threads.spawn(give, nums.sender())
while (true) {
select {
nums => |n| {
io.print(n)
}
closed => {
break
}
}
}
t.join()
const full = threads.channel(Buf(u8), 0)
defer full.close()
const tx = full.sender()
defer tx.close()
offer(io, a, tx, a.alloc(2, 0))
}
Shared values. As in Erlang, memory threads share is either never
changed or reached only through operations that cannot race; there are no
locks. threads.share(v) moves v into a Shared(T), which every thread
holding one reads at once, without copying: s.get() lends its T for
the expression it is in, as a plain parameter is lent (index it, slice it,
read its fields, pass it to a plain parameter; moving it, writing to it,
passing it as inout or keeping it in a local borrow is E139, E002, E105
or E121). s.copy(a) is a T of the caller’s own, every buffer in it
copied, to change or keep. s.clone() is another holder of the same
value, to send to another thread or move into one; s.close() ends a
holder, and the last one frees the value. Shared(T) is owned (E135 if
not closed), and T is any value type without an owned struct, a channel’s
end, a file or socket (copying could not duplicate them) or a pointer
(E155). Use get; copy is for the value that will be changed.
Atomics. threads.atomic(n) is an Atomic: an i64 every thread
holding one reads and changes in single steps. x.load() reads it,
x.store(v) writes it, x.add(d) adds d and returns the new value (an
overflow panics integer overflow, as + does: the value has wrapped by
then, but the program is ending), x.swap(v) writes v and returns the old
value, and x.compare_swap(expected, v) writes v if the value is
expected, and returns the old value either way, so a loop that retries
has the value to retry with. All are sequentially consistent. x.clone()
and x.close() hold and end it, as for a Shared(T).
Handles in containers. A Shared(T) or an Atomic may be an element
of a Buf or an array, or a field of a struct, like a buffer: a.free
ends each one it reaches as close does. That only drops a holder; the
value behind it is freed by the last holder to go, whoever made it, not
by the a.free that dropped this one.
// expect: general 2 2
// expect: rooms 2, visits 2
uses alloc, io, thread
const Room = struct {
name: Buf(u8)
members: Buf(Buf(u8))
}
const Seat = struct {
room: Shared(Room)
visits: Atomic
}
fn main(io: Io, a: Allocator, threads: Threads) void {
var members: Buf(Buf(u8)) = .empty
a.push(&members, a.concat("ann", ""))
a.push(&members, a.concat("bob", ""))
const room = threads.share(Room{ .name = a.concat("general", ""), .members = members })
const visits = threads.atomic(0)
var seats: Buf(Seat) = .empty
defer a.free(seats) // closes every handle in it
a.push(&seats, Seat{ .room = room.clone(), .visits = visits.clone() })
a.push(&seats, Seat{ .room = room, .visits = visits })
for (seats) |seat| {
_ = seat.visits.add(1)
}
io.print(seats[0].room.get().name, " ", @len(seats[1].room.get().members), " ", seats[0].visits.load())
var rooms: Buf(Shared(Room)) = .empty
a.push(&rooms, seats[0].room.clone())
a.push(&rooms, seats[1].room.clone())
io.print("rooms ", @len(rooms), ", visits ", seats[1].visits.load())
a.free(rooms) // two holders fewer; seats still hold the room
}
Concurrent maps. threads.map(K, V) is a ConcurrentMap(K, V), a
hash map that every thread holding one reads and changes at once, like
Erlang’s ETS or Go’s sync.Map. K is any key with a canonical form, as
for a HashMap (below; E157 otherwise): text (str or Buf(u8), looked
up by any text), an integer, or a struct, array or union of keys. The
map keeps its own copy of each key, its canonical bytes, and entries
gives keys of the caller’s own read back from them. V is what a
Shared(V) may hold (E155). A V that owns
nothing is kept in place and read as a copy: m.get(k) is a ?V. Any
other V is kept as a Shared(V): m.get(k) is a ?Shared(V), another
holder of the value, read with get without copying and closed when
done. Changing a value is putting a new one: whoever still holds the old
one reads it as it was, and keeps it alive until it closes it.
| Method | Does |
|---|---|
m.get(k) |
the value, or null |
m.put(a, k, v) |
v in for k; the value it replaces, or null |
m.put_new(a, k, v) |
v in, if k has none; whether it went in (if not, v is freed) |
m.take(k) |
k’s value taken out, or null |
m.remove(k) |
k’s value taken out and ended; whether there was one |
m.contains(k), m.count() |
whether k has a value; how many pairs there are |
m.add(a, k, d) |
for a ConcurrentMap(K, i64): d added to k’s value (0 if new) in place; the sum (an overflow panics) |
m.put_if(a, k, expected, v) |
v in, if k’s value is still expected; whether it went in (if not, v is freed: a retry builds a new one) |
m.remove_if(k, expected) |
k’s value taken out and ended, if it is still expected |
m.entries(a) |
a Buf(MapEntry(K, V)): every pair, in the order the keys went in (a key put again keeps its place; one taken out and put back goes last), e.key (of the caller’s own: text as a Buf(u8), any other key a copy) and e.val as get gives it |
m.clone(), m.close() |
another holder; one fewer, the last freeing every value |
expected is what get gave, and is checked against the value k has
when put_if runs, not against what happened since. A value kept in
place (a number, bool, enum or str; E103 for others) is compared
with ==: if another thread changed it and changed it back, it matches.
A Shared(V) is compared by identity, and no other value can take its
place while the caller holds it, so a match means no other put came in
between. Either way, on false, read again, build a new value and retry. No code of the program
runs while the map is locked: a read only copies a value or holds a
handle once more. The map is in shards, each a table behind its own lock
(as many as four per CPU, rounded up to a power of two), so threads
working on different keys seldom wait for each other; count and
entries go shard by shard, each as it was at one moment.
Hashing. A ConcurrentMap and a std/map HashMap hash their keys
with SipHash-1-3 under a key of their own: the first map a program makes
reads one from the system’s random source, and each map derives its own
from it, so no one can choose keys that all land in one bucket and slow
the map down (HashDoS). Nothing a program can see depends on it: a
ConcurrentMap’s entries are in the order the pairs went in, removals
or not; a HashMap’s are too until its first remove, which moves the
last pair into the gap. The environment
variable EGG_HASH_SEED (a number) replaces the random key, to make a
run’s internal layout repeat while debugging.
A key hashes and compares by its canonical bytes, so a struct, an enum, a
union or an array is a key with nothing to write: an integer is its
type’s width of bytes, least significant first; a bool 0 or 1; an enum
member, or a union’s live member, its index in 4 bytes (then the
member); text is its bytes, after its length in 8 bytes when it is part
of a larger key (so {a: "ab", b: "c"} and {a: "a", b: "bc"} are two
keys); a struct’s fields and an array’s elements come in order, and no
padding is read. Text inside a key is a Buf(u8), which a map can copy.
A float is not a key (NaN is not equal to itself); key by
@floatBits(x). Nor are pointers, handles or optionals (E157).
// expect: ann
// expect: put_if true, then false
// expect: 2 rooms, 4000 hits from 4 threads
uses alloc, io, thread
const Room = struct {
name: Buf(u8)
members: Buf(Buf(u8))
}
fn room(a: Allocator, name: []u8, who: []u8) Room {
var members: Buf(Buf(u8)) = .empty
a.push(&members, a.concat(who, ""))
return Room{ .name = a.concat(name, ""), .members = members }
}
fn visit(a: Allocator, sink hits: ConcurrentMap(str, i64), sink done: Sender(i64)) void {
defer done.close()
var i = 0
while (i < 1000) {
_ = hits.add(a, "general", 1)
i = i + 1
}
hits.close()
done.send(1)
}
fn main(io: Io, a: Allocator, threads: Threads) void {
const rooms = threads.map(Buf(u8), Room)
defer rooms.close()
_ = rooms.put_new(a, "general", room(a, "general", "ann"))
_ = rooms.put_new(a, "random", room(a, "random", "bob"))
const g = rooms.get("general") orelse return
defer g.close()
io.print(g.get().members[0]) // read in place
// A change made from what was read goes in only if the value is still
// that one: the same handle, so no other put came in between.
const first = rooms.put_if(a, "general", g, room(a, "general", "cy"))
const second = rooms.put_if(a, "general", g, room(a, "general", "dan"))
io.print("put_if ", first, ", then ", second)
const hits = threads.map(str, i64)
defer hits.close()
const done = threads.channel(i64, 4)
defer done.close()
var i = 0
while (i < 4) {
threads.spawn(visit, a, hits.clone(), done.sender()).detach()
i = i + 1
}
var finished = 0
while (done.recv()) |n| {
finished = finished + n
}
const all = rooms.entries(a)
defer a.free(all) // the keys, and a holder of each room
io.print(@len(all), " rooms, ", hits.get("general") orelse 0, " hits from ", finished, " threads")
}
// expect: 4 readers saw 11 bytes
// expect: hello world 2
// expect: copy hello world!
// expect: 10
uses alloc, io, thread
const Post = struct {
id: i64
body: Buf(u8)
}
fn read(sink post: Shared(Post), sink seen: Atomic, sink done: Sender(i64)) void {
defer done.close()
done.send(@len(post.get().body))
post.close()
_ = seen.add(1)
seen.close()
}
fn show(io: Io, p: Post) void {
io.print(p.body, " ", p.id)
}
fn main(io: Io, a: Allocator, threads: Threads) void {
const post = threads.share(Post{ .id = 2, .body = a.concat("hello", " world") })
const seen = threads.atomic(0)
const results = threads.channel(i64, 4)
var i = 0
while (i < 4) {
threads.spawn(read, post.clone(), seen.clone(), results.sender()).detach()
i = i + 1
}
var bytes = 0
while (results.recv()) |n| {
bytes = n
}
results.close()
io.print(seen.load(), " readers saw ", bytes, " bytes")
show(io, post.get()) // lent, not copied
var mine = post.copy(a) // a Post of its own
defer a.free(mine)
a.append_str(&mine.body, "!")
io.print("copy ", mine.body)
post.close()
// Doubled in a loop that retries: compare_swap gives the value to retry with.
var cur = seen.load()
while (true) {
const old = seen.compare_swap(cur, cur * 2 + 2)
if (old == cur) {
break
}
cur = old
}
io.print(seen.load())
seen.close()
}
// error: E139
uses alloc, io, thread
const Post = struct { id: i64, body: Buf(u8) }
fn main(io: Io, a: Allocator, threads: Threads) void {
const post = threads.share(Post{ .id = 1, .body = a.concat("a", "b") })
const p = post.get() // would take the body from every holder
io.print(p.id)
post.close()
}
// panic: integer overflow
uses thread
fn main(threads: Threads) void {
const x = threads.atomic(9223372036854775807)
_ = x.add(1)
x.close()
}
Capability values cannot be created or compared. main receives them
from the runtime, and other code gets them as arguments; they may be
stored in locals and struct fields like any value.
The check (E130). A function uses a capability when it calls a
method of its value, or calls a function that uses it. The compiler
follows the call graph, across files and through generic instances, and
rejects a function whose file does not declare every capability it uses.
So a file without uses io cannot print, even with an Io it was given,
and even inside a generic function instantiated with Io: it can only
pass the value on. The error is reported where the capability enters the
file: at the method call, or at the call into another file.
// error: E130
fn main(io: Io) void {
io.print(1) // no `uses io`
}
String literals, a.leak copies and a.create pointers live as long as
the program: they are never freed, so nothing can use them after being
freed. Memory that is freed comes as a Buf(T), whose owner the compiler
checks (section 21).
// expect: total: 42
// expect: -7
uses alloc, io
const Log = struct {
io: Io
a: Allocator
fn show(self: Log, label: str, n: i64) void {
const text = self.a.int_str(n)
defer self.a.free(text)
self.io.print(label, text)
}
}
fn main(io: Io, a: Allocator) void {
const log = Log{ .io = io, .a = a }
log.show("total: ", 42)
const text = a.int_str(-7)
defer a.free(text)
io.print(text)
}
eggc lists the capabilities a function uses when the language server
shows it (hover).