Preface
Within the narrative and theoretical scope of the book, this appendix serves primarily to demonstrate how a memory-safe, C-successor language ought to define its semantic boundaries, rather than to provide a drop-in replacement for a rigorous ISO-level standard.
In this context, CobaltC can best be described as a systems language designed to address the safety problems of C while adopting a more robust structural model.
If nothing else, it illustrates the exact pain points and formal guarantees required to make a safe systems programming language actually function.
As argued throughout The Wrong Memory essays, attempting to tack a "safe subset" onto an inherently unsafe language usually fails because the core language semantics still allow invariant violations. By embedding ownership and borrowing into the core type system, CobaltC makes safety an intrinsic property of the language rather than an optional discipline imposed upon it.
CobaltC unashamedly draws on the ownership and memory-safety techniques demonstrated by Rust. Although Rust isn't the origin of most of these ideas, its significant contribution was demonstrating how they could be combined into a practical, high-performance systems language. CobaltC adopts that safety architecture without attempting to reproduce Rust's syntax or overall language philosophy. Instead, it applies the broader body of ideas to the problem identified in Appendix II: making semantic invariants such as ownership, lifetime, aliasing, mutability, and bounds properties that the compiler can represent and enforce, rather than obligations the programmer must maintain by convention.
The CobaltC Proposition
The distinction is perhaps easiest to see in a deliberately small example. Allocate some storage, keep a second name for it, destroy the storage, and use the second name.
#include <stdlib.h>
int main(void)
{
int* data = malloc(3 * sizeof *data);
data[0] = 7;
int* alias = data; /* a second name for the same storage */
free(data); /* the storage is gone... */
return alias[0]; /* ...but this still compiles, and reads
the wrong memory */
}
C accepts this program without complaint — GCC and Clang compile it
silently even with every common warning enabled. At best, a modern
compiler may warn about a case this obvious; move the free
behind one function call and the warning disappears, while the bug does
not. The program compiles, runs, and reads the wrong memory.
The fact that alias still refers to freed storage exists
only in the programmer's head.
"You have the power. Don't screw it up."
import std;
fn main()
{
Vec<i32> data = Vec::new();
Vec::push(&mut data, 7);
ref<i32, shared> alias = &data[0]; // a second name for the same storage
drop(data); // ✗ rejected before the program runs:
// diag.destroy-while-aliased
printf("%v\n", *alias);
}
The same program, the same shape — allocate, alias, destroy, use — and
it does not run. The fact that alias still points into
data lives in the language, so destroying data
underneath it is refused before the program starts, with a named
diagnostic: heuristic warnings on one side, a semantic guarantee on the
other.
"You have the power. Let’s prove you’re exercising it correctly."
The guarantee is not bought by removing capability. Below, two exclusive (mutable) references into the same array are held at once — something safety-minded languages commonly refuse — legal here because the compiler has proven they touch disjoint elements. CobaltC forbids the crime, not the capability.
import std;
fn main()
{
array<i32, 2> values = [0, 0];
// Two mutable (exclusive) references into the same array, allowed
// because their targets are statically proven to be disjoint
// (pointing both at values[0] is rejected before the program runs:
// diag.aliasing-conflict).
ref<i32, exclusive> a = &mut values[0];
ref<i32, exclusive> b = &mut values[1];
*a = 7;
*b = 8;
}
CobaltC retains the same fine-grained control, while allowing the compiler
to establish the relevant safety properties: a and b
refer to distinct elements of values, their mutable accesses
are disjoint, and the underlying storage remains owned by values.
This guide describes the CobaltC specification, edition 2026.112802.
Introduction
Why CobaltC exists, what it promises, and which features were chosen to keep those promises.
import std;
fn main()
{
printf("hello, world\n");
}hello, world
What CobaltC is
CobaltC is a small systems programming language with a C-family surface syntax. It is designed around one idea: the facts that correct low-level code depends on should live in the language, not in the programmer's memory. When you write C, you have to remember that a pointer is still valid, that an integer cannot overflow here, that a buffer has been initialised, that nobody else is writing to that struct right now, and that this handle is closed exactly once. CobaltC's goal is that every such fact is either represented and checked by the language, or explicitly marked as trusted by you.
CobaltC is not a safe language obtained by removing low-level capability. You still get deterministic control over resources, raw storage, foreign functions, threads, and predictable data layout. What changes is that each of those capabilities comes with a precise account of what is checked, when it is checked, and what you are asserting when the language cannot check it.
The tools: cobc and cobfmt
cobc is the compiler, and the one command a program needs: it
checks a program, runs it, runs its tests and shows the standard library's documentation (below,
Running a program). It checks the program against the specification's
rules — the parser, name resolution and the static checks — then translates it to plain C and
compiles that with the system's C compiler (GCC or Clang) against cbrt, its run-time library. A
compiled program keeps every run-time check the specification requires except those the
compiler proves can never fail — the rest becomes ordinary C — so it does what the specification
says or stops with a named fault. cobc --keep-c leaves the
generated C beside the executable if you want to read what your program became;
Reading the C that cobc generates, below, says what is in it
and what you can do with it.
cobfmt is the formatter: it lays out a source file in the style
this guide uses and changes nothing else (below).
A third program, cobmodel, is not needed to write programs: it is an
executable model of the rules about references and threads, written from the specification alone,
that lists every outcome the rules allow a small program over every schedule of its threads. The
project checks the compiler against it, and you can ask it about a result that surprised you
(§19, Every schedule, from the rules).
The test suites hold cobc to the specification on every program, under both GCC
and Clang: every conformance case, every showcase and every complete example in this guide.
cobc is written in CobaltC and compiles itself; its runtime is C. A new
machine builds it with a C compiler alone, from the C of its own source kept in the repository
(gcc impl/bootstrap/boot.c -o boot && ./boot), and the compiler so built proves itself by writing
that C again, byte for byte (D-0326).
Everything in this guide runs on x86-64 Linux. cobc also builds Windows programs
with a MinGW-w64 GCC, on Windows itself or from Linux with --target x86_64-pc-windows-gnu (D-0255;
the repository's README says how), and the formatter cobfmt runs there too.
cobc) and formatter (cobfmt) are available
here; the repository's README says how to
build them.The objectives
The language design was derived from a short list of objectives, in priority order. Where two objectives conflict, the earlier one wins.
- Preserve semantic invariants. Arithmetic stays in range, references point at live objects, a resource has exactly one owner, an object is initialised before it is read, two threads never race on one location, and external data is treated as a claim until validated.
- Safety of valid safe programs. A well-formed program that writes no
unsafeblock of its own cannot violate any of those invariants on any conforming implementation. The standard library's own bodies do useunsafe(aVecwrites its elements through a raw pointer); those blocks are the implementation's to keep true, each listed in the specification with the fact that justifies it, so they cost the program nothing (§20, Who asserts what). If the language cannot establish a fact, the operation is one of: statically rejected, dynamically checked, explicitly fallible (returns aResultorOption), explicitly trusted (insideunsafe), or simply not provided. - Consistency and composability. A handful of mechanisms that combine cleanly, instead of many overlapping features. Every value-placing construct (declarations, arguments, fields, returns) follows one rule; every access (through a name, a field, an index, a reference) follows one rule.
- Formal precision and deterministic diagnostics. The specification is written as rules, so two implementations must reject exactly the same programs and report the same named diagnostic. Every error you see has a stable identifier such as
diag.aliasing-conflict. - A small language. Every feature starts as absent and must earn its place. The result is a language you can hold in your head: no traits, no inheritance, no exceptions, no implicit conversions beyond the two coercions (text and sequences fit the type declared for them), no operator overloading, no macros.
- Low-level capability. Raw pointers, manual allocation, FFI, threads, and defined representation are all available, gated by
unsafewhere the language cannot check them.
Which features were chosen, and why
Each mechanism in CobaltC exists because a specific invariant needed a home. The table below is the map from objective to feature; the rest of this guide explains each feature in turn.
| Invariant to protect | Mechanism CobaltC provides | Where to read |
|---|---|---|
| Arithmetic stays in range | Integer + - * and / % are checked: overflow is a fault, never silent wrap. Wrapping, saturating and checked_ families are explicit opt-ins. There are no implicit numeric conversions; widen, narrow, reinterpret and friends are named calls. | §06 |
| A resource is owned once and released once | Resource types (anything that owns something, marked resource or containing a resource) have a single holder. Assigning or passing one moves it. The old name becomes stale. Destruction is automatic at scope end, in reverse order, running the type's drop destructor. | §07 |
| No conflicting simultaneous access | Two reference modes: ref<T, shared> (read-only, any number) and ref<T, exclusive> (read and write, alone). Conflicts are checked at every use, so a stale or conflicting reference is always caught. There is no mut on variables: mutability is a property of the access path, not the binding. | §08, §09 |
| A reference never outlives what it points at | References cannot be returned or stored beyond their referent's scope; the obvious cases are rejected at compile time, the rest at run time. A function returning a reference borrows from its one reference parameter without annotations; with several, a from clause names the ones the result may come from. | §10 |
| No read of uninitialised storage | Definite assignment: a variable must be written on every path before it is read. Aggregates are initialised whole. | §11 |
| Types mean what they say | Nominal typing, no subtyping, and two coercions, both about a value fitting the type declared for its position: text (a literal, a str or &s is the String or StringView declared) and sequences (&v is the slice declared); nothing else converts. Generics are monomorphic: each use with concrete types becomes its own copy of the function, so there is no run-time type information; a type parameter's operations come from one of six built-in bounds. Type inference is local: auto infers from the initialiser, and generic arguments come from arguments or the expected type. | §12 |
| Evaluation order is defined | Strict left-to-right evaluation everywhere. Blocks, if and match are expressions. | §13, §14 |
| Function interfaces carry the whole contract | A by-value resource parameter takes ownership; a shared reference can only read; an exclusive reference can mutate but not destroy; a reference result comes from the one reference parameter, or from those a from clause names. Closures declare their captures and the language checks the list. | §15 |
| Aggregates are whole and exhaustive | Structs, fixed arrays and enums with payloads. Array indexing is bounds-checked. match must be exhaustive. | §16 |
| Names are unambiguous | Modules with export/import, private by default. Name resolution is a fixed, documented order. | §17 |
| Failure is never silent | Two channels only: a checked fault is fatal and unwinds destructors; recoverable errors are Result values with the ? operator. There is no catch. | §18 |
| Threads do not race | spawn/join with owning handles; a mutex whose interior is reachable only through a lock guard. The same aliasing rules apply across threads. A fault in a spawned thread ends that thread alone and reaches its supervisor as a value; any wait can be cancelled; deadlocks are reported. | §19 |
| External data is a claim, not a fact | unsafe blocks record what you assert. rawptr<T>, reclaim, allocate and unsafe extern fn are the only doors to the outside, and FFI signatures are restricted to plain types. | §20 |
| A text literal is a value; owned text is a resource | A string literal "…" is a str: a copyable value like an integer, valid UTF-8 by construction, never owned or freed. printf writes one. Owned, growable text is String, a resource: moved, destroyed at scope end, built from a str (a literal written where a String is declared becomes one there) or validated from bytes. | §21 |
| The library proves the language is sufficient | Vec<T>, String and Rc<T> are written in CobaltC itself, using nothing the language does not give you. | §21 |
What CobaltC deliberately leaves out
These are considered decisions, not gaps. Each one either duplicated an existing mechanism or would have hidden a semantic fact the language wants to keep visible.
- Implicit conversions and subtyping.
i32andi64never mix silently. - User-defined traits or bounds. A type parameter's operations come from six built-in bounds —
eq,ordered,number,integer,clone,plain(§12) — and nothing else: there is no way to declare a new bound. Your own struct or enum satisfiesclonealone, by its fields or its ownT::clone; to compare or combine values of your own types in generic code, pass the operation in as a function value. - Exceptions. A fault terminates the program after running destructors; expected failure is a
Result. - Garbage collection. Ownership and scope-end destruction are deterministic;
Rc<T>is a library type. - Character literals, and indexing or slicing a
str. Astris a whole value; its bytes are reached withstr_byte, and a single byte is writtenb'a': au8, or the wider unsigned type its context asks for (§06). AStringis sliced into views,&s[i..j], and taken apart byStringView::split,findandchars(§21). Text that arrives from outside is still bytes untilString::from_utf8validates it. - Method-call syntax. A call names the function's owner and writes the borrow it takes:
Vec::push(&mut v, x), neverv.push(x). The mode of every access path is visible where the path is formed, and.means one thing, field access. This is final (CHG-0132): no receiver sugar, no uniform call syntax, no auto-borrowing dot, no chaining. - A
mutqualifier on bindings,switchandgoto,import … asrenaming, partial initialisation, lifetime annotations (a function with several reference parameters names its result's sources withfrom, §10), memory orders weaker than sequential consistency.std::sync'sAtomic(§19) is sequentially consistent.
How to read this guide
The next section is a complete program you can read top to bottom to absorb the
syntax. After that there is one section per chapter of the normative specification, numbered the
same way (§06 to §22) so you can cross-reference. If you are new, a good order is: the tour, then
§22 (syntax reference), then §06 onward. Each section ends with a short list of rules of thumb.
A reader who wants the model behind the rules — the abstract state, how references are formed and
end, the one conflict check, what is decided before a program runs and what while it runs, threads
and the trust boundary — can read spec/OVERVIEW.md, a prose account of the specification that
cites, paragraph by paragraph, the rules it explains.
Every code block that is a complete program has been compiled and run by cobc,
under both GCC and Clang, and does what the guide says it does. A green
runs badge means it executes to completion; a red badge names the
diagnostic the language reports for that program. Diagnostics are labelled static (the
program is rejected before it runs) or dynamic (a checked fault at run time); where a check
is static only when the operands are literal, both labels may appear in the text. Comments inside
examples use ✓ for accepted lines and ✗ for rejected ones.
The language and its standard library are still moving: an edition may change
what an earlier one accepted, and the specification's register says so in each such edition's row.
When a part is offered as stable it is first a candidate for thirty days, then
stable, and after that a program written against it keeps compiling and keeps doing what it
did, apart from a repair that closes a soundness hole or a change announced a release ahead
(spec/STABILITY.md).
Running a program
Save a program as a .cb file. cobc --run program.cb compiles it to native code
in a temporary directory, runs it and deletes what it built; cobc -o program program.cb keeps the
executable, program. cobc takes the program's entry file (it may name other files as modules,
§17); its own options go before the file, and words after it are the program's arguments
(cobc --run program.cb a b). A program can also be a script: a first line
#!/usr/bin/env -S cobc --run is read as a comment (D-0337, spec/22), so after chmod +x program.cb
the file runs as ./program.cb a b; only the first line may start with #!. Under --run, cobc exits with the program's own status, 0 when it
runs to completion; a rejected program's diagnostic is printed and cobc exits with status 1.
cobc --check program.cb runs only the checks made before a program starts, and prints the same
diagnostic for a program it rejects; nothing is built or run, so a program that reads input, writes files or serves the network can be
checked without doing so. Given a directory, it checks every .cb file in it. A rejected program
gets every error that stands on its own, in source order, then a line counting them (D-0321,
D-0323): errors of the text's syntax first, then names, then types and references, each kind only
when the one before found nothing; within a function, one for each statement, except that a statement
using a local that a failed statement declared without a written type, or left unknown, is not
checked (a last line says so), so that no error is reported that only follows from another.
cobc --doc Vec::push shows an item of the standard library with its
documentation; --doc Vec a type and its functions, --doc std::text a module, --doc widen one of
the language's own functions, and --doc --find WORD… the items whose name, signature or summary has
every word. A program's own
item takes precedence over an imported one of the same name (§17): a struct Vec or fn min beside
import std; hides std's silently; --warn-shadow, given first, makes cobc note each such
name on standard error, with its file and line, and otherwise behave as before.
There is no project file and no build step besides these commands. A program that
spans several files names them itself: module parser "./parser.cb"; loads a file as a module, its
path relative to the file that says so (§17), and extern "./fast.c"; or extern "z"; links C code
of the program's own or an installed library (§20). cobc main.cb then builds the whole program
from that one file, and cobc --run main.cb runs it, with nothing else to keep in step (D-0231).
How long a build takes, and --lto
cobc writes the program's C, the std it reaches included, as one file, and the
C compiler compiles it as one file with no link-time optimisation. A program that uses little of std
builds in a second or two. One that reaches much of it takes longer: http_get brings in the HTTP
client, TLS, X.509 and compression, some 94,000 lines of C, and a nine-line program calling it builds in
about 28 s at the default -O 2 and 19 s at -O 0 on a four-core machine (measured with other builds
running), of which about 5 s is cobc's own work and the rest the C compiler. Every build is an honest
compile: cobc keeps no cache of earlier builds, so building a program again costs the whole time
again.
cobc --lto compiles a large program's C in parts instead, at most eight, all at
once on the machine's cores, and links them with link-time optimisation where the C compiler has it
(GCC's -flto; Clang's ThinLTO, through Clang's own lld or through gold); a program of under a
megabyte of C stays one part. Measured once each in both forms under the same load:
| Program | one file (default) | --lto |
|---|---|---|
the http_get program, GCC, -O 2 / -O 0 | 27.7 s / 19.4 s | 22.3 s / 14.5 s |
showcase/tier12/dns_over_http.cb, GCC / Clang | 48.1 s / 53.6 s | 44.0 s / 36.5 s |
showcase/tier11/token_gate.cb, GCC / Clang | 49.4 s / 57.2 s | 47.9 s / 39.8 s |
the compiler itself (impl/cobc/main.cb), GCC | 880 s | 488 s (the one-file build ran under twice the load) |
The programs it builds are a few per cent larger and run about as fast. On the
benchmark workloads (bench/), each one part in either form, the instruction counts are within 4%:
GCC's -flto on one file changes its inlining, and hashcount then runs 4% more instructions. The
compiler built with --lto is 9% larger and runs 4% more instructions, 7–9% slower (writing a large program's C, or checking itself), which is why impl/build.sh builds every tool as one file. So
--lto is worth it for the edit-and-build loop of a large program on a machine with cores to spare,
most of all with Clang; for the build you keep, and for a small program, the default is as good or
better. Either way the program behaves the same.
Testing a program
Tests live beside the code they test, in unittest blocks: a block at the top level of a
file or a module, with an optional name. A test sees the module's private items, and is checked every
time the program is, so a test that no longer compiles stops the build at once. Nothing runs it until
you ask for a test run.
import std;
fn parse_port(StringView s) : Option<u16>
{
match (StringView::parse<u32>(s))
{
Ok(n) : if (n > 65535) { None } else { Some(narrow<u16>(n)) },
Err(_) : None,
}
}
unittest "parse_port: bounds"
{
assert(parse_port("0") == Some(0));
assert(parse_port("65535") == Some(65535));
assert(parse_port("65536") == None);
}
unittest
{
assert(parse_port("x") == None);
}
fn main()
{
printf("%v\n", parse_port("8080") == Some(8080));
}true
cobc --run port.cb runs the program as always. cobc --unittest --run port.cb builds
and runs its tests instead of main, each in a thread of its own: a failed assert, or any other
fault, is reported, and the next test still runs. cobc --unittest -o port_tests port.cb keeps the
test program.
test port.cb:12 parse_port: bounds ... ok
test port.cb:19 ... ok
2 tests: 2 passed, 0 failed
The exit status is 1 when a test failed, so a test run can gate a build.
--unittest-filter TEXT runs only the tests whose name contains TEXT. A file that holds only
a library and its tests needs no main. A /// comment on a test right after a function makes it
that function's example in the generated documentation (D-0230).
All code in this guide uses Allman brace style (every opening brace on its own line) and four-space indentation. That is a documentation convention: CobaltC ignores whitespace between tokens, so any brace placement is equally valid.
cobfmt, the formatter, writes that style for you: cobfmt program.cb rewrites the
file in place (through a link, keeping its permissions; a read-only file is left as it is), cobfmt --backup src/ does every .cb file under src/ and keeps each changed
file's previous contents as NAME.cb.format.bak, and cobfmt --check src/ only lists the files it
would change (for a test or a commit hook). It changes layout and nothing else: indentation, braces,
spacing, blank lines, the : of a match's arms and of a bitstruct's fields aligned in one column, and trailing comments kept
in theirs. Before writing, it checks that the result is the same program token for token, so
formatting can never change what a program does. It keeps your line breaks — a short
if (n == 0) { return; } stays on one line, though a function's body always opens on its own line — and it never breaks a line
of its own accord: where a line ends is yours to decide. With --width N it breaks a line longer than N characters
that holds a list of arguments, parameters or array elements, one item per line. cobfmt --help lists the rest. cobfmt runs on Windows as well as
Linux, and it keeps a file's Windows line endings (\r\n) as they are.
Reading the C that cobc generates
cobc does not produce machine code itself. Once the shared front end has checked
your program, cobc translates it into one C file and hands that file to GCC or Clang, which
builds the executable against libcbrt.a, the run-time library. Normally the C file is deleted
afterwards; cobc --keep-c -o prog prog.cb keeps it as prog.c, beside prog (without -o,
a.out gets a.c). Under --run without -o it lives in a temporary directory and is deleted
with it. If the C compiler ever rejects the file, cobc keeps it whatever you asked and prints
its path.
The file is the complete translation of your program, not an excerpt: nothing but
libcbrt.a is needed to build it. Even a seven-line program comes to a few hundred lines,
because the file carries everything it uses, in this order:
- The run-time interface,
cbrt.h, copied in at the top: the C declarations of everycb_…function the program calls. /* ---- types ---- */: each struct, enum and generic instantiation as a C struct, each followed by a_Static_assertthat its size and alignment are the ones the specification fixes.Vec<i32>becomesstruct s_std__Vec_Li32_R./* ---- string literals ---- */: your text literals as byte arrays./* ---- functions ---- */: one C function for each function the program actually uses,std's included, and one copy per instantiation of a generic one (f_std__Vec__push_Li32_RisVec::pushfori32). Yourmainisf_main; every other function isstatic, so the C compiler may inline it where it is called.- Call thunks and type descriptors: what
fnvalues and the run-time checks need to know about each type. int main, last: it hands the program's arguments to the runtime and startsf_main.
Inside a function, the C follows your statements one by one, and every run-time
check the specification requires is an explicit line, so you can see exactly which checks your
code still pays for. This is printf("%v\n", v[0]); with v a Vec<i32> (without the
#line directives described below):
cb_at(0u, 7u); // now at line 7 of file 0, for diagnostics
struct s_std__Vec_Li32_R *v9 = &(l_v_1);
if (t8 >= v9->len) cb_fault("diag.index-out-of-bounds", CB_NOLOC, 0);
int32_t *e10 = v9->ptr + (int64_t)t8; // the element's address
int32_t t11 = (*e10);Elsewhere you will meet cb_borrow, cb_read and cb_write (the access and
aliasing checks of §08–§09), __builtin_add_overflow and its relatives (checked arithmetic, §06),
and cb_frame_push, cb_stmt_push and their _pop partners (the bookkeeping that runs
destructors at scope end). A check the compiler has proved can never fail is simply absent.
Each line of C made from one of your statements is preceded by a directive such as
#line 7 "prog.cb", which tells the C compiler which line of your file the next line of C came
from. The C compiler's own messages, a debugger and a sanitizer then name prog.cb:7 rather than a
line of prog.c; code made for std keeps the C file's own numbering. cobc --no-line-directives
leaves the directives out, for reading the C on its own terms.
What you can do with it
- Read it to see how a construct is compiled, which checks a loop costs, or why one way of writing it is faster than another. Performance (chapter P) collects what such reading and measuring found.
- Build it yourself, with your own flags.
cobc's own build ofprog.cis the command below, andcobc -vprints the exact one it runs, with the real path oflibcbrt.a(and anyexternC file's compilation), ready to paste and change;-O2is the default level andlibcbrt.asits beside thecobcexecutable. Add-g -O0for a build to step through in a debugger,-fsanitize=address,undefinedto have the sanitizers watch it,-march=nativeor-flto, or leave out-wto see the C compiler's warnings, whichcobcsilences. - Debug it.
cobc -O0 -g prog.cbcompiles with debug information and keeps it in the executable;gdb progthen stops at and steps through the lines ofprog.cb, and a sanitizer build (--ccnaming a wrapper that adds-fsanitize=address) reports a memory error inunsafecode at its.cbline. A fault names the line it happened at, not the calls that led there: for those, givegdbthe commandbreak exitbeforerun, andbtat the stop lists each call with its.cbline and its arguments.perf annotateshows the C beside them. - Report a compiler bug. If GCC or Clang rejects the generated C, that kept file and the C compiler's message are the whole report.
gcc -std=gnu11 -O2 -ffp-contract=off -fno-optimize-sibling-calls -w -fpeel-loops prog.c \
-L /path/to/cobc/dir -lcbrt -lpthread -ldl -lm \
-Wl,--gc-sections -Wl,--strip-debug -o progKeep -std=gnu11 and the two -f flags when you change the rest; each is part of
the program's meaning. -ffp-contract=off stops the C compiler fusing a * b + c into one
fused multiply-add with a single rounding, since the specification rounds each operation on its
own (§06). -fno-optimize-sibling-calls keeps every call a real call, so a recursion too deep for
the stack stops with the fault diag.stack-exhausted, instead of being turned into a loop
that runs to completion. -fpeel-loops (Clang: -mllvm -unroll-threshold=300) only makes
loops faster: a loop of a few iterations known before it runs, such as foreach (c in 0..9), is
unrolled whole, as GCC does at -O3 and Rust's compiler at -O. A program that links its own C code (extern "./mine.c";, §20) also
needs that code compiled and added before -lcbrt; cobc -v shows both commands. The last two
options only make the executable smaller: they leave out the parts of the runtime the program does
not use, and the runtime's debug information (a hello world is about 54 KB with them, 0.5 MB
without); drop them if you link a -g build to debug. cobc -s also leaves out the symbol table
(--strip-all in place of --strip-debug, about 44 KB), which only profilers and debuggers read.
cobc, and it is only correct with the
libcbrt.a built alongside the same cobc. cobc refuses a mismatched runtime, but a build by hand
skips that check.Why compile to C
Compiling through C is a long tradition rather than a shortcut: C++ began as Cfront, which translated it into C, and Nim, Vala, Cython and several Scheme compilers work this way today. Few compilers write machine code entirely on their own; most hand the last step to a shared back end such as LLVM or GCC's. C as the target brings:
- Portability for free. Wherever there is a C compiler, the language can run.
- Decades of optimisation for free. GCC's and Clang's
-O2do register allocation, inlining, vectorisation and instruction scheduling better than a young compiler could. - Readable output. You can see what your program became, which is what
--keep-cis for; LLVM IR or assembly would be far harder to read. - Easy C interoperation. Calling C functions and linking C libraries is natural, which is what
unsafe extern fn(§20) needs.
What it costs
- C's own rules come along. The generated C must avoid C's undefined behaviour, and it has to keep up as C compilers grow stricter: code an older compiler accepted with a warning, a newer one may reject outright.
- Less control. Some things C cannot say directly (exact stack layout, particular calling conventions, precise debug information), so they are worked around with flags such as
-ffp-contract=offabove. - Slower builds. Every build includes a full C compilation.
- A debugger sees C. The
#linedirectives (above) letgdbstep through your.cblines, but the variables, types and functions it shows are the C's (l_v_1,struct s_std__Vec_Li32_R,f_main).
For CobaltC the trade is a good one. Its central promise is that a compiled program
does exactly what the specification says, checks included, and letting GCC and Clang do the
machine-code work leaves cobc free to get the semantics and the checks exactly right.
A tour in one program
A complete, runnable program that introduces the syntax and the main capabilities, and the mistakes the compiler stops, before the reference sections begin.
Here is a complete program. Read it once for the shape of the syntax; every
construct it uses has its own section later. cobc --run tour.cb runs it and prints the output
shown below the code.
// ------------------------------------------------------------------
// A first CobaltC program: a temperature log.
//
// One page that touches most of what CobaltC is for: structs, an enum
// with payloads and `match`, a resource with a destructor, Vec, String
// and HashMap, references the compiler checks, slices, Option, Result
// and `?`, checked arithmetic, generics, a closure, and two threads
// sharing a counter through a mutex.
// ------------------------------------------------------------------
import std;
// A module. Its `export` items are reached as `limits::COLD`; the rest
// stay inside. A `const` is a value fixed when the program is compiled.
module limits
{
export const i32 COLD = 150; // tenths of a degree
export const i32 HOT = 300;
}
// A plain struct: copied on assignment, comparable with ==.
struct Reading
{
i32 tenths; // temperature in tenths of a degree
u8 sensor;
}
// An enum. Variants may carry a payload.
enum Verdict
{
Cold(i32),
Fine,
Hot(i32)
}
// `ref<Reading, shared>` is a read-only reference. `if` is an expression,
// so the function's value is whichever branch runs.
fn judge(ref<Reading, shared> r) : Verdict
{
if (r.tenths < limits::COLD)
{
Cold(limits::COLD - r.tenths)
}
else if (r.tenths > limits::HOT)
{
Hot(r.tenths - limits::HOT)
}
else
{
Fine
}
}
// A resource: something that owns other things. It is moved, never
// copied, and destroyed exactly once, automatically, at scope end.
resource struct Log
{
Vec<Reading> entries;
HashMap<String, u32> per_sensor; // readings counted by sensor name
}
// The destructor. It is never called directly; the language runs it.
fn Log::drop(ref<Log, exclusive> self)
{
printf("L%d\n", Vec::len(&self.entries)); // printf's format is checked when compiled
}
fn record(ref<Log, exclusive> log, i32 tenths, u8 sensor)
{
Vec::push(&mut log.entries, Reading { .tenths = tenths, .sensor = sensor });
String key = sprintf("sensor-%d", sensor);
*HashMap::entry(&mut log.per_sensor, &key, 0) += 1; // a String key is looked up by its view
}
// A slice is a borrowed run of elements. Arithmetic never wraps
// silently: `checked_add` gives None on overflow, and `?` on an Option
// returns that None from this function at once.
fn average(slice<Reading, shared> rs) : Option<i32>
{
if (slice_len(rs) == 0)
{
return None;
}
i32 total = 0;
foreach (r in rs)
{
total = checked_add(total, r.tenths)?;
}
Some(total / narrow<i32>(slice_len(rs))) // `narrow` checks that the value fits
}
// A fallible function returns a Result. Err carries the offending byte.
fn digit(u8 b) : Result<i32, u8>
{
if (b > b'9' || b < b'0')
{
return Err(b);
}
Ok(widen<i32>(b - b'0')) // widening is always safe, still spelled out
}
// `?` unwraps an Ok, or returns the Err from this function at once.
fn parse_two(u8 hi, u8 lo) : Result<i32, u8>
{
i32 h = digit(hi)?;
i32 l = digit(lo)?;
Ok(h * 10 + l)
}
// A generic function: T is any integer type, fixed at each call.
fn larger<T: integer>(T a, T b) : T
{
if (a > b) { a } else { b }
}
// Runs on its own thread: counts the hot readings in its half of the
// log into a counter the two threads share. Only the lock reaches it.
fn count_hot(ref<mutex<u32>, shared> hot, slice<Reading, shared> part) : usize
{
foreach (r in part)
{
if (r.tenths > limits::HOT)
{
*lock(hot) += 1;
}
}
slice_len(part)
}
fn main()
{
Log log = Log { .entries = Vec::new(), .per_sensor = HashMap::new() };
record(&mut log, 120, 1);
record(&mut log, 215, 1);
record(&mut log, 340, 2);
record(&mut log, 310, 2);
// Loop over the entries through a shared reference to each one.
// `match` takes the Verdict apart; it must handle every variant.
foreach (r in &log.entries) // r : ref<Reading, shared>
{
match (judge(r))
{
Cold(by) : printf("C%d ", by), // "C" then the shortfall
Fine : printf("F "),
Hot(by) : printf("H%d ", by), // "H" then the excess
}
}
printf("\n");
// A lookup gives an Option; a pattern condition takes it apart.
if (Some(n) = HashMap::get(&log.per_sensor, "sensor-2"))
{
printf("sensor-2: %d\n", *n);
}
// A slice of the Vec, and an average that cannot overflow unseen.
if (Some(avg) = average(&log.entries[0 .. 2]))
{
printf("avg %d\n", avg);
}
// Sorting, and a closure: `to_f` captures nothing, `offset` is read.
Vec<i32> temps = Vec::new();
foreach (r in &log.entries)
{
Vec::push(&mut temps, r.tenths);
}
Vec::sort(&mut temps);
i32 offset = 32;
auto to_f = [offset](i32 tenths)
{
tenths * 9 / 50 + offset
};
printf("coldest %dF, warmest %dF\n", to_f(temps[0]), to_f(temps[3]));
// Result handling: `b"42"` is a byte-array literal (52 and 50).
auto digits = b"42";
if (Ok(v) = parse_two(digits[0], digits[1]))
{
printf("%d %d\n", v, larger(v, 17)); // T := i32
}
// Two threads share the counter through a mutex; each gets its own
// half of the log as a slice. `join` waits and gives the result.
auto hot = Mutex::new(0: u32);
auto h1 = spawn(count_hot, &hot, &log.entries[0 .. 2]);
auto h2 = spawn(count_hot, &hot, &log.entries[2 .. 4]);
usize seen = join(h1) + join(h2);
printf("%d of %d readings hot\n", *lock(&hot), seen);
} // `log` is destroyed here: its destructor prints "L4", then its Vec and HashMap are freed.C30 F H40 H10 sensor-2: 2 avg 167 coldest 53F, warmest 93F 42 42 2 of 4 readings hot L4
What the compiler stops
The program above is correct, so it shows what CobaltC lets you write. Just as much of the language is what it will not let through. Each of these mistakes, a one-line change to the same kind of code, is rejected before the program runs, with a diagnostic that names the rule; what cannot be decided in advance is checked while the program runs, and stops it at the line where it happens (§08–§10).
import std;
struct Reading
{
i32 tenths;
u8 sensor;
}
fn main()
{
Vec<Reading> entries = Vec::new();
Vec::push(&mut entries, Reading { .tenths = 120, .sensor = 1 });
ref<Reading, shared> first = Vec::index_shared(&entries, 0);
Vec::push(&mut entries, Reading { .tenths = 215, .sensor = 1 }); // ✗ the push may move the elements
printf("%d\n", first.tenths); // while `first` still points into them
}import std;
resource struct Log
{
Vec<i32> entries;
}
fn archive(Log l) // takes the log: it is destroyed when this call ends
{
}
fn main()
{
Log log = Log { .entries = Vec::new() };
archive(log); // `log` moves into the call
Vec::push(&mut log.entries, 7); // ✗ `log` no longer owns anything
}import std;
fn digit(u8 b) : Result<i32, u8>
{
if (b > b'9' || b < b'0')
{
return Err(b);
}
Ok(widen<i32>(b - b'0'))
}
fn main()
{
digit(b'x'); // ✗ an error dropped on the floor would go unseen
// Handle it (`?`, `match`, `if (Err(e) = …)`), or say you mean to drop
// it: `_ = digit(b'x');` discards the value on purpose.
}import std;
fn main()
{
i32 tenths = 2000000000;
i32 twice = tenths * 2; // ✗ the product does not fit in an i32: no silent wrap
printf("%d\n", twice);
}enum Verdict
{
Cold(i32),
Fine,
Hot(i32)
}
fn label(Verdict v) : i32
{
match (v) // ✗ `Hot` is not handled: every variant must be
{
Cold(by) : -by,
Fine : 0,
}
}
fn main()
{
label(Fine);
}Reading a diagnostic
This is what cobc prints for the first example above, a reference kept across a
push:
error[diag.aliasing-conflict]: `first` still borrows `entries`, so it cannot be written or borrowed `mut` here; end that borrow first
--> tour.cb:14:15
|
14 | Vec::push(&mut entries, Reading { .tenths = 215, .sensor = 1 });
| ^
= repair: end the conflicting reference (let its holder go out of scope) before this access, or use `shared` on both sides
- The first line says what went wrong.
errormeans the program was rejected before it ran; a check that fails while the program runs is afaultinstead (fault[diag.index-out-of-bounds]: index 5 is out of bounds for length 3), and the program stops there. In the brackets is the diagnostic's identifier: it is the same in every implementation and every version, and the specification's diagnostic registry has an entry for each. -->gives the file, the line and the column, in the form editors and terminals turn into a link.- The source line, with carets under the token the rule applies to.
= repair:is the registry's advice for this diagnostic.
A habit from another language gets the CobaltC form in the message itself:
v.len() is answered with Vec::len(x, ...), let x = 1; with i32 x = 1; or auto x = 1;, x as
u64 with widen<T>(x), println! with printf, and a misspelt name with the nearest one that exists
(Vec::psh gets "did you mean Vec::push?"). CARD.md, at the top of the repository, lists the habits and their
messages with the syntax, the tools, the diagnostics and every item of the standard library on one
page.
cobc --explain --check tour.cb adds the registry's whole entry: the rule of the
specification that rejected the program, the invariant it protects, what it required and what it
observed, and the examples that show it. cobc --explain --run prog.cb shows a fault during the run
that way too, as does a compiled program run with COBALTC_EXPLAIN=1 in its environment.
A line that begins internal error in cobc: is not about your program: it is a bug
in the tool, which exits with status 4 and names the place in its own source. Please report it with
the program that caused it.
What you just saw
- Declarations are type-first, like C:
i32 x = 5;,Vec<Reading> entries;.autoinfers the type from the initialiser. Function return types follow a colon:fn judge(…) : Verdict. - Blocks,
ifandmatchare expressions. The last expression in a block, with no semicolon, is the block's value.judgereturns whatever branch of theifruns. - Conditions need parentheses (
if (c),while (c),match (e));matcharms arePattern : expression,, and amatchmust cover every variant (a missing one is rejected, above). A pattern can also be a condition:if (Some(n) = HashMap::get(…))runs its block only when the lookup found something, withnbound. &xis a shared (read-only) reference and&mut xan exclusive one. The compiler checks every use: a reference kept into theVecacross apush, a value used after it moved, are rejected before the program runs (above).&log.entries[0 .. 2]is a slice, a borrowed run of elements.Logis aresource: it owns aVecand aHashMap. Its destructorfn Log::dropruns at the end ofmain, then its fields are freed. Passing or assigning a resource moves it.String,HashMapandsprintf.sprintf("sensor-%d", s)builds aString;*HashMap::entry(&mut m, key, 0) += 1counts. The standard library lives in the modulestd, imported byimport std;.- Errors are values. A
Resultmust be used (dropping one is rejected),?returns anError aNoneearly, andchecked_addturns an overflow intoNone. Plain arithmetic that overflows is never silent: it is rejected when the compiler can see it, and stops the program when it happens. - No implicit numeric conversions.
widen<i32>(b - b'0')andnarrow<i32>(n)say what happens to the representation;narrowchecks that the value fits. - Library calls are qualified:
Vec::push(&mut v, x),Vec::sort(&mut v),HashMap::get(&m, "k"). There is no method-call syntax. - Generics, closures and threads.
larger<T: integer>works for any integer type;to_fis a closure whose capture list names what it uses;spawnstarts a thread andjoinwaits for its result. The two threads share their counter only through amutex:lockis the only way in.
Further showcases can be found in the repository's showcase directory; its README describes them all.
Core language and std
Which parts of CobaltC are the language itself, always available, and which come from the standard library and need import std;.
CobaltC comes in two layers. The core language is always there: its
types, its constructs, and a set of intrinsics, functions defined by a rule of the
specification rather than by a body. The standard library, std, is a module,
written mostly in CobaltC itself. Nothing of std is in scope until a module writes
import std;, and each module imports it for itself (§17). This page says which
layer each part belongs to.
// No `import std;`: only the core language.
fn main() : u8
{
array<i32, 4> a = [3, 4, 5, 6];
i32 s = 0;
foreach (x in a)
{
s += x;
}
u32 m = max_value<u32>();
s += narrow<i32>(m % 10); // 4294967295 % 10 is 5
narrow<u8>(s) // the exit status: 23
}fn main()
{
printf("hello\n"); // ✗ diag.unbound-name (static): printf is std's
}Core: always available, no import
Types built into the language
- Integers
i8–i128,u8–u128,isize,usize; floatsf32,f64 bool,str(string literals),void/()array<T, N>,slice<T, shared>andslice<T, exclusive>ref<T, shared>andref<T, exclusive>,rawptr<T>fn(…) : Rvalues and closureshandle<T>(a thread),mutex<T>,guard<T>
Language constructs
struct, bitstruct, enum (with numeric codes), resource, destructors (Type::drop),
generics with the built-in bounds eq, ordered, number, integer, clone and plain, match with
nested, literal and text patterns, if and while (either with a pattern as the condition), for,
foreach (over collections and ranges), break, continue, ?, const, modules and import, unsafe,
unsafe extern fn and extern "code";.
Intrinsics
| Group | Names |
|---|---|
| Resources | drop |
| Conversions | widen, narrow, checked_narrow, narrow_wrapping, reinterpret, to_float, to_int |
| Bits | count_ones, leading_zeros, trailing_zeros, rotate_left, rotate_right |
| Arithmetic | wrapping_add/sub/mul, saturating_add/sub/mul, checked_add/sub/mul/div/rem, checked_neg |
| Numeric limits | min_value, max_value |
| Layout | sizeof, alignof |
str and slices | str_len, str_byte, str_ptr, slice_len |
| Faults and compile-time checks | fault, static_assert |
| Threads | spawn, join, cancel, join_status, Mutex::new, lock |
Vectors (simd<τ, N>) | simd_load, simd_store, simd_eq, simd_ne, simd_lt, simd_le, simd_gt, simd_ge, simd_select, simd_any, simd_all, simd_min, simd_max, simd_sum, simd_reduce_min, simd_reduce_max |
Raw memory (most need unsafe) | rawptr_of, reinterpret_ptr, dangling, null_rawptr, allocate, deallocate, reclaim, release, copy_raw, read_volatile, write_volatile |
allocate returns a Result, which a program can use without the import even though it
cannot name the Result type without it.
Intrinsics private to std
key_hash, key_eq, key_less, key_less_at, swap_places, append_native,
text_write, parse_check, parse_value, str_slice (beneath StringView::of), and the names
that begin with $: the machinery std's own code is built on. A program cannot call them, nor
std's private externs stderr_write, which eprintf writes through, and stdout_flush, beneath
flush_stdout.
std: needs import std;
Mostly written in CobaltC itself; a few parts are provided natively by each
implementation. std is divided into submodules by subject, and import std; brings in all of
them, so a program never needs to know which holds what; the column says, for a program that wants
one subject alone (import std::text;). §21 covers it in full.
| Area | Items | Submodule |
|---|---|---|
| Core types | Option<T>, Result<T, E>, AllocError; unwrap, unwrap_or, expect, ok_or, is_some/is_none/is_ok/is_err; map_err | std::core |
| Collections | Vec<T> (push, pop, index, insert, remove, swap_remove, retain, dedup, clone, from_slice, filled, from_fn, append, contains, position, reverse, truncate, swap, clear, …), HashMap<K, V>, HashSet<K>, Queue<T>, PriorityQueue<T>, slice_parts | std::collections |
| Sorting | Vec::sort, sort_by, binary_search, binary_search_by | std::collections |
| Ownership helpers | Box<T>, Rc<T>, Weak<T> | std::memory |
| Values behind references | swap, replace, overwrite | std::core |
| Numeric helpers | min, max, abs, pow, clamp, gcd, is_nan, is_finite (over the built-in bounds) | std::math |
| Floating-point functions | sqrt, floor, ceil, round, trunc, ln, exp, log2, log10, sin, cos, tan, asin, acos, atan, atan2, powf | std::math |
| Random numbers | Rng, a seeded pseudo-random generator (Rng::from_os for a fresh seed, Rng::shuffle); os_random_bytes, os_random_u64 for secrets; uuid_v4 | std::random |
| Networking | TcpListener (bind, accept), TcpStream (connect, read_line, read, write, printf, shutdown_write, try_clone, timeouts, keepalive), UdpSocket (send_to, recv_from, connect, send, recv), IpAddr, SocketAddr, resolve, NetError | std::net |
| Other programs | Command (arg, current_dir, env, output, status, spawn), Child (read_output_line, read_error_line, write_input, wait, terminate, kill), process_id, watch_interrupts, interrupt_requested, exit | std::process |
| Bytes | Vec::push_le, push_be, read_le, read_be | std::collections |
| Checksum | crc32 (CRC-32/IEEE; catches accidents, not tampering) | std::crypto |
| Text | String, StringView (split, lines, split_whitespace, chars, code_point, find, trim, starts/ends_with, strip_prefix/suffix, parse), String::append, push_code_point, sprintf, String::appendf, the ASCII tests and case changes, Utf8Error, ParseError | std::text |
| Output | printf, eprintf, flush_stdout; the extern stdout_write | std::io |
| Checks | assert | std::core |
| Input | read_line, read_all, read_all_bytes; the extern stdin_read | std::io |
| Files | File (open, create, create_new, append, open_rw, read, read_line, write, seek, position, flush, len, close, …), read_file, write_file, read_bytes, write_bytes, FileError | std::fs |
| Directories and paths | make_dir, remove_file, remove_dir, rename, list_dir, path_kind, make_dir_all, remove_dir_all, copy_file, file_info, the path_ functions (join, parent, file_name, stem, extension, is_absolute, normalize, canonical) | std::fs |
| Arguments and environment | arg_count, arg and the extern arg_bytes; Args (flag, option, options, finish, help); env_var, current_dir, set_current_dir, temp_dir, home_dir, current_exe, hostname | std::env |
| Clocks | monotonic_ns, unix_seconds, sleep_ms; dates and times are DateTime | std::time |
| Concurrency | Channel<T> (new, send, recv, try_recv, recv_timeout_ms, close), cpu_count, try_join, is_finished, ThreadFailure (text, diagnostic, is_cancelled) | std::sync |
| Cryptography | sha256, sha384, sha512, sha1 (legacy), blake2b, hmac_sha256, hmac, digest_eq, hkdf_sha256, chacha20_poly1305_seal/open, aes_gcm_seal/open, x25519, ecdh, ed25519_sign/verify, ecdsa_sign/verify, rsa_sign_pss/verify_pss, hash_password/verify_password; to_hex, from_hex, base64_encode, base64_decode in std::text | std::crypto; to_hex, from_hex, base64_encode, base64_decode: std::encoding |
| HTTP | http_get, http_post, HttpClient, Url, form_decode/form_encode; HttpServer (bind, bind_tls), HttpConnection::request/respond | std::http |
| JSON | Json (parse, text, pretty, get, at, as_*, set, push), JsonMember | std::encoding::json |
| Compression | deflate/inflate, zlib_deflate/zlib_inflate, gzip/gunzip, adler32, CompressError | std::compress |
| Databases | PgConnection::connect, query, execute, run_script; PgValue, PgResult, PgRow::get, get_i64, get_f64, get_bool, get_bytes, get_datetime | std::database::postgres |
| Big integers | BigUint (add, sub, mul, div_rem, mod_pow, shifts, text, parse, bytes) | std::math |
| Certificates and TLS | Certificate, TrustStore, verify_chain; TlsStream (connect, client, server, read, read_line, read_exact, write, peer_certificate, close) | std::x509, std::tls |
| Dates and times | DateTime (from_unix, now, new, to_unix, to_iso, from_iso, to_http_date, from_http_date, weekday, less, to_local, to_iso_local), Weekday, unix_ms, iso_from_unix_ms, unix_ms_from_iso, local_offset_seconds — UTC, and the machine's local time | std::time |
What may surprise you
printfandassertarestd, not core: a program without the import cannot print.Vec,StringandOptionarestd, butarray,str,slice,handleandmutexare core.swap, the one to use, isstd;swap_places, which it is built on, is private tostd.minandmaxarestd;min_valueandmax_valueare core.sqrt,roundand the other floating-point functions arestd(std::math), not core: they are ordinary library functions, so they need the import, and a function of your own namedroundis an ordinary name.
CobaltC for C programmers
What carries over from C, what the same words mean here, the habits the compiler stops, and how error handling works in place of return codes, errno, NULL and abort.
If you write C, most of CobaltC will look familiar and a few things will look wrong. This section is the shortest path from one to the other: it says what you can keep doing, what the same spelling means here, which three habits the compiler will stop, and, at the greatest length, how a program reports and handles failure, because that is where C and CobaltC differ most and where the reference sections take the longest to connect. Everything here is said again, more fully, in the sections it links to; this is the map.
What carries over
Declarations are type-first, blocks are braces, statements end in ;, comments start with
//, and printf is printf. if, while, for (init; cond; step), break, continue and
return are what you expect, and &&, ||, !, the arithmetic, bitwise and comparison operators
have C's spellings and precedences. A struct is a struct, written with C99's designated initialisers
and nothing else: Point { .x = 3, .y = 4 }. main may return a u8, which is the process's exit
status, and the program's arguments are arg_count() and arg(i).
import std;
struct Point
{
i32 x;
i32 y;
}
fn main() : u8
{
Point p = Point { .x = 3, .y = 4 };
i32 sum = 0;
for (i32 i = 0; i < 5; i += 1)
{
sum += i;
}
if (sum == 10 && p.x < p.y)
{
printf("sum %d, point (%d, %d)\n", sum, p.x, p.y);
}
0
}sum 10, point (3, 4)
Three small things in that program are not C. fn main() : u8 puts the return type after a
colon, as every function does. import std; brings in the standard library, which is where printf
lives; without it the name is unknown (Core language and std). And the last line
of main is 0 with no return and no semicolon: a block's final expression is its value, so
if, match and plain blocks are expressions too, which is how CobaltC does without the ?:
operator. return 0; would also have been fine.
The same words, a different meaning
| In C | In CobaltC | Where |
|---|---|---|
int, long, unsigned, size_t | sized types only: i8 i16 i32 i64, u8 u16 u32 u64, usize isize; f32 f64; bool. Literals take a suffix or the expected type. | §06 |
char, 'a' | u8 and the byte literal b'a'; text is str, never an array of char | §06, §21 |
char *, const char * | str (a literal, read-only), String (owned, growable), StringView (a borrowed view); UTF-8 bytes with a length, no terminator | §21 Which text type? |
T *p | ref<T, shared> (&x, read-only) or ref<T, exclusive> (&mut x, read-write); never null, never dangling; rawptr<T> only inside unsafe | §08, §09, §20 |
T a[N] | array<T, N>, indexed with a bounds check; Vec<T> for a growable one; slice<T, m> for a view of part of either | §16, §21 |
NULL, -1, EOF as "no value" | Option<T>: Some(v) or None | below |
int return code and errno | Result<T, E>: Ok(v) or Err(e), E an enum you declare | below |
enum | enum, whose variants may carry a payload: Invalid(usize) | §16 |
switch | match, exhaustive, no fall-through, arms pattern : expression, | §16 |
?: | if (c) { a } else { b } as an expression; ? means something else (below) | §14 |
i++, --i | i += 1, i -= 1; there is no ++ | §13 |
(long) x, implicit promotion | widen<i64>(x), narrow<u8>(x) (checked), to_float<f64>(x), to_int<i32>(f); nothing converts on its own | §06 |
sizeof x, sizeof(T) | sizeof<T>(), alignof<T>() | §12 |
#include "x.h", static | import std;, module m "./x.cb";, export on what others may use; no headers, no preprocessor | §17 |
typedef, #define N 10 | no aliases; const usize N = 10; is a compile-time constant | §11, §17 |
[[deprecated("…")]] (C23) | the same spelling, but a use is an error unless you build with --allow-deprecated; [[removed("…")]] on a tombstone keeps the name and refuses every use; no other attribute exists | §17 |
malloc/realloc/free | Vec, String, Box, Rc; freed when their owner's scope ends | §07, §21 |
a struct with a cleanup function you must remember to call | resource struct with fn T::drop, run automatically when the value's scope ends, on every path | §07 |
goto cleanup; | nothing: destructors run on early return, on ?, and while a fault unwinds | §07, §18 |
assert(c), abort() | assert(c, "fmt", …), never compiled out; exit(status) | §18, below |
setjmp/longjmp, signals | no equivalent: a fault cannot be caught (a thread's can be contained, §19) | §18 |
pthread_create, a shared global | spawn(f, args…) and join(h); shared data only through a mutex<T> or an Atomic<T>; there are no mutable globals | §19 |
_Atomic, atomic_fetch_add | Atomic<T> (an integer of up to 64 bits), Atomic::fetch_add(&a, n); always sequentially consistent, and overflow faults unless you call the _wrapping form | §19 |
atomic_bool, _Atomic(T *), atomic_thread_fence, C++20 atomic::wait/notify_one | AtomicBool, AtomicPtr<T>, atomic_fence(), Atomic::wait(&a, v)/Atomic::notify_one(&a); no memory_order argument anywhere | §19 |
GCC/Clang __attribute__((vector_size(16))), <immintrin.h> intrinsics | simd<f32, 4> and kin: the same vector types, with + - * lane by lane and simd_ intrinsics; portable, no per-processor names | §16 |
struct layout, alignas(64) | the same layout as C for the same members; struct S align(64) { … } on the type | §16 |
extern int f(int); and the linker | unsafe extern fn f(i32 x) : i32; plus extern "./f.c"; or extern "m";; cobc compiles and links | §20 |
passing a struct or a const char * to C, reading a returned char * | a plain struct crosses by value as it is; text goes as CString::new(s) and CString::ptr(&c), comes back with unsafe { String::from_c(p) }; is_null(p) tests for NULL | §20 |
Two spellings deserve a warning because they parse and mean something else. ? after an
expression is not the start of a conditional: it propagates an error and returns from the
function (below). And &x always makes a reference the compiler tracks, never an address you can
add to; the address is rawptr_of(&x), usable only in unsafe.
Three habits the compiler stops
Overflow is not silent. In C, unsigned arithmetic wraps and signed overflow
is undefined. Here +, - and * are checked: a result that leaves the type faults the program
with diag.arith-overflow, division by zero with diag.div-by-zero. When you want wrapping, say so
with wrapping_add and friends; when you want to detect it, checked_add returns an Option
(§06).
import std;
fn bump(u8 x) : u8
{
x + 10 // checked: faults when the sum leaves u8
}
fn main()
{
printf("%d\n", bump(100));
bump(250); // ✗ diag.arith-overflow (dynamic)
}110
Nothing converts implicitly. int to long, char to int, float to
double, a pointer to bool: none of it happens. Every change of representation is a named
intrinsic, and the ones that can lose information check the value (§06, Conversions are
explicit). The error message tells you which one to write. The two coercions the language does
have are about text and sequences fitting their declaration (StringView v = &s;,
slice<u8, shared> b = &v;), never about numbers (§12).
fn main()
{
i32 a = 5;
i64 b = a; // ✗ diag.type-mismatch: write widen<i64>(a)
}Pointers do not escape. A reference to a local cannot be returned or stored
anywhere that outlives the local; a reference into a Vec cannot be kept across a push that may
move the elements; a value cannot be used after it was moved. These are rejected before the program
runs where the compiler can see them (diag.reference-escapes-scope, diag.stale-binding) and
stop the program at the first use otherwise (§09, §10). There is no dangling pointer to find later.
A function may still return a reference into what it was given: with one reference parameter
nothing is written, and with several a from clause names those the result may come from
(§10).
fn dangling() : ref<i32, shared>
{
i32 local = 5;
&local // ✗ diag.reference-escapes-scope
}
fn main()
{
dangling();
}Memory: no malloc, no free
Every value has one owner, and when the owner's scope ends the value is destroyed, on every
path out of the scope: a normal end, an early return, a ? that returns an error, or the unwinding
of a fault. A Vec frees its buffer, a String its bytes, a File closes. Your own type joins in by
being declared resource and giving fn T::drop, the destructor, which runs first; the fields follow.
This replaces the cleanup: label, the matching free for each malloc, and the fclose someone
forgot on one error path. Passing or assigning a resource moves it: the new name owns it, the
old name is dead, and using the old name is an error. Plain values (numbers, bool, references,
small structs of them) are copied as in C.
import std;
resource struct Connection
{
String name;
}
fn Connection::drop(ref<Connection, exclusive> self)
{
printf("close %s\n", &self.name);
}
fn use_it()
{
Connection c = Connection { .name = "primary" };
printf("using %s\n", &c.name);
} // c ends here: drop runs, then the String is freed
fn main()
{
use_it();
Vec<i32> v = Vec::new(); // grows as needed; freed when v ends
for (i32 i = 0; i < 5; i += 1)
{
Vec::push(&mut v, i * i);
}
printf("%d items, last %d\n", Vec::len(&v), v[4]);
}using primary close primary 5 items, last 16
Library calls name the type they belong to and write the borrow they take: Vec::push(&mut
v, x), Vec::len(&v). There is no v.push(x); the . is only field access. The mode of every
access, & or &mut, is visible at the call (§08).
Strings
A string is bytes with a length, in UTF-8, with no terminating zero. A literal is a str:
read-only, indexed by byte with str_byte(s, i), measured with str_len(s). Text you build or own is
a String (a literal where a String is declared, String::append, sprintf); text you only look at, passed to a
function, is a StringView (§21, Which text type?). Comparison is == on the text
(s == "quit", a == b), never on pointers, and %s prints any of the three.
import std;
fn main()
{
str lit = "héllo"; // UTF-8 bytes, no terminator
printf("%d bytes\n", str_len(lit));
String s = "abc";
String::append(&mut s, "def");
printf("%s has %d bytes; third is %d\n", &s, StringView::len(&s), str_byte("abc", 2));
}6 bytes abcdef has 6 bytes; third is 99
Error handling, from the beginning
C has one mechanism for everything that can go wrong, and it is a convention: a function
returns a value that means failure (-1, NULL, EOF, false), perhaps sets errno, and the caller
checks, or does not. Bugs and expected failures travel the same road, nothing forces the check, and
cleanup on the way out is the caller's problem. CobaltC separates the two kinds of failure and gives
each its own mechanism, and that separation is the thing to learn first; the syntax follows from
it.
| An error value | A fault | |
|---|---|---|
| What it is | An expected failure the program may recover from: bad input, a missing file, a full queue, a lookup that finds nothing | A violated rule of the language: overflow, an index out of range, a dead reference, a failed assert, an unwrap of nothing |
| How it travels | As a value: Result<T, E> or Option<T>, returned like any other value | It does not: the thread unwinds every scope, running destructors, and the program ends with the fault's name and exit status 1 |
| Who decides | The caller, with match, ?, if (Some(x) = …), unwrap_or | Nobody: there is no catch (a spawned thread's fault can be contained at its join, §19) |
| In C terms | the return code, done so that it cannot be ignored | abort(), done so that it runs your cleanup first |
The rule of thumb: if a failure is part of normal operation, it is an error value; if it can
only happen because the program is wrong, let the fault fire and fix the program. Do not wrap
arithmetic in Result, and do not assert that a file exists.
Option in place of NULL and sentinels
Option<T> is Some(v) or None. It is a plain two-variant enum from std, not a pointer,
so a function that may have nothing to return says so in its type and the caller cannot forget to
look: there is no way to use the T without taking the Option apart. There are four ways to take it
apart, and C programmers tend to reach for the last one first.
import std;
fn find(ref<Vec<i32>, shared> v, i32 wanted) : Option<usize>
{
foreach (i in 0 .. Vec::len(v))
{
if ((*v)[i] == wanted)
{
return Some(i);
}
}
None
}
fn main()
{
Vec<i32> v = Vec::new();
Vec::push(&mut v, 5);
Vec::push(&mut v, 8);
Vec::push(&mut v, 13);
match (find(&v, 8)) // 1. match: both cases, side by side
{
Some(i) : printf("found at %d\n", i),
None : printf("absent\n"),
}
if (Some(i) = find(&v, 13)) // 2. a pattern as the condition
{
printf("13 at %d\n", i);
}
usize at = Option::unwrap_or(find(&v, 99), 0); // 3. a default
printf("%d\n", at);
while (Some(x) = Vec::pop(&mut v)) // the same, as a loop
{
printf("%d ", x);
}
printf("\n");
}found at 1 13 at 2 0 13 8 5
The fourth way is Option::unwrap(o), or Option::expect(o, "why it must be there"): it
gives the value or faults with diag.unwrap-failed. That is the right tool exactly when None would
mean the program is wrong, as assert is; in a library function, or anywhere the caller could
reasonably have passed nothing, it is the wrong one, because it turns the caller's input into your
crash. If you find yourself writing if (Option::is_some(&o)) { … Option::unwrap(o) … }, write the
if (Some(x) = o) form instead: it binds the value and checks in one step.
Result in place of return codes and errno
Result<T, E> is Ok(v) or Err(e). E is any type, and the idiom is an enum you declare
for the module, one variant per way things fail, carrying what the caller needs to say something
useful (Invalid(usize): at which position). Compared with an int and errno: the value and the
failure are one object, so they cannot get out of step; the error carries data, not a number to look
up; and a Result that is not looked at is rejected by the compiler (diag.result-discarded), so the
one failure mode C cannot prevent, the ignored return code, does not compile. If you really mean to
drop it, say so: _ = save(x);.
import std;
fn save(i32 n) : Result<void, str>
{
if (n < 0) { Err("negative") } else { Ok(()) }
}
fn main()
{
save(-1); // ✗ diag.result-discarded: in C this error would vanish; here it cannot
}std's own functions follow the same shape. File::open is Result<File, FileError>;
StringView::parse<u32> is Result<u32, ParseError>; HashMap::get is Option<ref<V, shared>>. Every
std error enum has a text function that gives a short sentence for a message
(FileError::text(&e)), which is what a program prints when it gives up (§21).
?: the early return, in one character
Most C error handling is the same four lines repeated: call, test the code, clean up, return
the code to the caller. ? is those four lines. Written after an expression of type Result<T, E>, in
a function whose own return type is Result<_, E>, it yields the T when the value is Ok and
otherwise returns the Err from the enclosing function at once, running the destructors of
everything in scope on the way, as any return does. Inside a function returning Option, ? does
the same for None. Three things follow, and they are the three things that confuse newcomers:
- The function must be able to return the error.
?on aResult<T, E>needs an enclosing return type ofResult<_, E>, with the sameE. In a function returningu8or nothing,?is rejected:diag.propagate-outside-fallible-context. Somain, which returnsu8or nothing, cannot use?; the pattern below deals with that. - Different error types do not mix on their own. A function that calls into two libraries with two error enums must convert each to its own:
Result::map_err(r, f)appliesfto theErrand leaves anOkalone, and a closure[](ParseError e) : ConfigError { BadNumber(e) }is the usualf, wrapping the inner error in a variant of the outer. The conversion is explicit at each boundary, and that is where you decide what the caller is told. OptionandResultdo not mix either.Option::ok_or(o, e)turnsNoneintoErr(e)so that?can return it:u32 n = Option::ok_or(checked_add(a, b), TooLarge)?;reads "the sum, or report TooLarge".Result::ok(r)goes the other way, dropping the error.
The whole shape of a program
Put together, a CobaltC program that can fail has three layers, and the layering is what to
copy. At the bottom, functions return Result with the module's error enum and use ? to pass
failures up. In the middle, a function converts foreign errors into that enum with map_err and
ok_or, so the layer above sees one type. At the top, main cannot use ? and should not try: it
calls one function that does the work and returns a Result, matches once, prints the error's text
to standard error and returns a non-zero status. That match is the only place in the program that
decides how a failure is reported, which is where a C programmer expects perror and exit(1) to
be.
import std;
enum ConfigError
{
MissingValue,
BadNumber(ParseError),
OutOfRange(u32),
}
fn ConfigError::text(ref<ConfigError, shared> e) : String
{
match (e)
{
MissingValue : "no value given",
BadNumber(pe) : sprintf("not a number (%s)", ParseError::text(pe)),
OutOfRange(n) : sprintf("%d is not a port", *n),
}
}
fn port(StringView text) : Result<u16, ConfigError>
{
if (StringView::len(text) == 0)
{
return Err(MissingValue);
}
u32 n = Result::map_err(StringView::parse<u32>(text), [](ParseError e) : ConfigError { BadNumber(e) })?;
if (n > 65535)
{
return Err(OutOfRange(n));
}
Ok(narrow<u16>(n))
}
fn run() : Result<void, ConfigError>
{
u16 p = port("8080")?; // Err returns from run here, if it is one
printf("port %d\n", p);
u16 q = port("99999")?;
printf("port %d\n", q);
Ok(())
}
fn main() : u8
{
match (run())
{
Ok(_) : 0,
Err(e) :
{
eprintf("config: %s\n", &ConfigError::text(&e));
1
},
}
}port 8080
Read port against the C version you would write: the if (!s[0]) return -1;, the
strtoul with its endptr and errno check, the range test, each returning a different negative
number the caller has to know. Here each failure is a named variant, the parse error from std is
kept inside BadNumber rather than flattened to a code, and run has no error handling at all: two
? and the happy path. The exit status is 1 and the message is on standard error, so the program
behaves as a shell expects, and the output above shows only what reached standard output before the
second port failed.
import std;
fn port(StringView text) : Result<u16, ParseError>
{
StringView::parse<u16>(text)
}
fn main() : u8
{
u16 p = port("8080")?; // ✗ diag.propagate-outside-fallible-context: main returns u8, not a Result
0
}? error? is not a switch default and not the ternary operator; it is return Err(e) with the
cleanup done for you. When it is rejected, the message says the function cannot return the error:
either give the function a Result return type and let the caller decide, or handle the value here
with match.Faults: what abort() should have been
A fault is the language refusing to continue: an overflow, an index out of range, a division by
zero, an unwrap of None, a false assert, a reference used after its referent ended. Nothing in
the program can catch it, which is the point: the code after the failed check would have run on a
state the check protected. What a fault does do, unlike abort(), is unwind. The faulting thread
leaves every open scope in order, running every destructor, so files are closed and locks released,
and only then does the program end, printing the fault's name, its location and the source line, with
exit status 1.
import std;
resource struct Connection
{
str name;
}
fn Connection::drop(ref<Connection, exclusive> self)
{
printf("closed %s\n", self.name); // runs while the fault unwinds
}
fn third(ref<array<i32, 3>, shared> a, usize i) : i32
{
(*a)[i]
}
fn main()
{
Connection c = Connection { .name = "db" };
array<i32, 3> a = [1, 2, 3];
printf("%d\n", third(&a, 2));
printf("%d\n", third(&a, 3)); // ✗ diag.index-out-of-bounds (dynamic): c is closed first
}3 closed db
assert is the one fault you raise yourself. Unlike C's, it is never compiled out, so it is
a statement about the program that holds in every build; and its message is a printf format whose
arguments are evaluated only when the condition is false, so a precise message costs nothing while
things are right.
import std;
fn average(ref<Vec<i32>, shared> v) : i32
{
assert(Vec::len(v) > 0, "average of %d values", Vec::len(v));
i32 sum = 0;
foreach (x in v)
{
sum += *x;
}
sum / narrow<i32>(Vec::len(v))
}
fn main()
{
Vec<i32> v = Vec::new();
Vec::push(&mut v, 4);
Vec::push(&mut v, 6);
printf("%d\n", average(&v));
Vec::clear(&mut v);
average(&v); // ✗ diag.assert-failed (dynamic): "average of 0 values"
}5
Whether something should be an assert or an Err is the same question as before: can a
correct program, given legitimate input, reach it? An empty Vec passed to average by a caller who
read it from a file can, so in a real program average would return Option<i32>; the assert is
right only if the caller has already guaranteed the length. When a fault happens in a thread you
spawned, it ends that thread alone and becomes the thread's result, which join raises and
try_join hands over as a value (§19, When a thread fails); the main
thread's fault always ends the program.
The idioms, side by side
| C | CobaltC |
|---|---|
if (p == NULL) return -1; | ? on an Option in a function returning Option; or Option::ok_or(o, MyError)? in one returning Result |
if (rc < 0) { cleanup(); return rc; } | T v = call()?; with the module's error type; destructors do the cleanup |
if (rc < 0) { cleanup(); return MY_ERR; } | Result::map_err(call(), [](TheirError e) : MyError { Wrapped(e) })? |
switch (rc) { case E_A: … case E_B: … } | match (e) { A : …, B(detail) : …, }, every variant covered |
perror("open"); exit(1); | in main: Err(e) : { eprintf("open: %s\n", FileError::text(&e)); 1 } |
x = f(); /* ignore */ | _ = f();, the only way to drop a Result |
assert(n > 0); | assert(n > 0, "n was %d", n); |
abort(), exit(EXIT_FAILURE) | exit(1), after unwinding; or return 1 from fn main() : u8 |
a flag ok threaded through a loop | while (Some(item) = next(&mut it)) { … } or foreach, with ? inside a Result-returning function |
errno read after the call | the payload of the Err variant, or E::text(&e) for a sentence |
Building and calling C
There is no header, no object file to manage and no Makefile. cobc prog.cb compiles the
program and the files it names with module m "./m.cb";, then links; cobc --run prog.cb builds it
and runs it at once; cobc --check prog.cb only checks. Calling C is a declaration and a file: unsafe extern fn area(i32
w, i32 h) : i32; promises the signature, extern "./shapes.c"; names the source (or extern "m"; a
library), and every call sits in an unsafe block, because the compiler cannot see what the C does
(§20). The types at the boundary are the C-compatible ones: sized integers, floats, bool,
rawptr<T>. Everything you have written in C stays callable; what changes is that the boundary is
marked, and the safe side of it keeps every guarantee of this section.
- Reach for
Optionwhere you reached forNULLor-1, forResultwhere you reached for a return code, and for a fault (assert) only where the program would be wrong. - Give each module one error enum, convert foreign errors into it with
map_errandok_orat the boundary, and use?everywhere else. - Let
mainmatch once: printE::text(&e)to standard error and return a non-zerou8. - Trust the destructors: there is no cleanup label to jump to, because every path out of a scope runs them.
CobaltC and Rust
What the two languages share, where they part company, and the price and payoff of each choice: when a check happens, what a type says, generics, threads, failure, unsafe and the surface.
Rust and CobaltC want the same things: no null, no dangling reference, no data race, no
use after free, one owner per resource, every failure a value or a named stop, and all of it
without a garbage collector or a hidden runtime. A Rust programmer will recognise most of CobaltC
on sight, which makes the places where the two part company the interesting ones. This section
goes through them: when a check happens, what a type says, how generic code is written, how
threads share, how failure is reported, what unsafe means, and what the surface looks like. It
takes no side. Each choice has a price and a payoff, and the point is to say what they are. Rust is
a mature language with a large ecosystem; CobaltC is a small one with a complete written semantics
and a compiler held to it. Which matters more depends on what you are doing.
What the two share
- Ownership and moves. A resource has one owner; assigning or passing it moves it, and the old name is unusable afterwards. In Rust every non-
Copytype moves; in CobaltC a type is either plain (copied) or a resource (moved), decided by its declaration:structorresource struct, and anything that holds a resource. - Shared or exclusive access, never both. Rust's
&Tand&mut Tare CobaltC'sref<T, shared>andref<T, exclusive>, written&xand&mut xin both. Any number of readers, or one writer, to one object at a time. - Destruction at scope end. Rust's
Dropis CobaltC'sType::drop; both run in reverse order of declaration, on every path out, including a panic or a fault. Option,Resultand?. The same two types, the same operator, the same habit of making absence and failure part of a function's type. Neither has exceptions.- Enums with payloads and exhaustive
match. A closed set of alternatives, each carrying data, taken apart by patterns the compiler checks for completeness. - Generics compiled per use. Both monomorphise: a generic function becomes one copy per set of concrete types, with no run-time type information.
- Explicit conversions. Neither converts numeric types silently. Rust writes
asandFrom; CobaltC writeswiden,narrowandreinterpret. - A marked boundary. Raw pointers and foreign functions live inside
unsafein both, and both say that safe code cannot break the language's guarantees.
When a check happens
This is the difference everything else follows from. Whether a reference is used after its object has gone, or while another part of the program writes through a second reference, depends on what the program does when it runs; no checker can decide it exactly for every program. Each language turns that into a question it can answer, and they turn it in opposite directions.
Rust decides at compile time, by over-approximating. Every reference type
carries a lifetime, an upper bound on how long the reference may be used, written as 'a or filled
in by three elision rules. Every function signature states how its result's lifetime relates to its
parameters'. The borrow checker then checks each function body against its own signature, one
function at a time, following the flow of the code to see which borrows are live where. Nothing is
checked at run time, and nothing is paid at run time. The price is that the checker must be
conservative: when it cannot prove a program safe, it rejects it, correct or not, and the programmer
restructures, adds annotations, or steps into unsafe. Two exclusive references into one vector at
indices known only at run time, a struct that refers into itself, a reference kept across a call
that might reallocate: all rejected, because the proof is not in the text.
CobaltC decides at run time, against the actual state. A reference carries no
lifetime; its validity is a fact about the running program: which object it reaches, whether that
object still exists, which other references to it are live and in what mode. The language's rules
are written over that state, and the compiled program checks them at each access the compiler has
not proved safe. The price is a run-time cost and a fault instead of a compile error: a mistake becomes a
named diagnostic at the step that commits it, in the run that reaches it, and a path no test runs
is a path no check has run. The payoff is that no lifetime annotation is needed (a function with
several reference parameters names its result's sources with from) and no correct program is
refused for lack of a proof. Both languages are in fact hybrids. Rust keeps run-time checks for
the cases its static rule cannot express (RefCell, Mutex, Rc, bounds, and overflow in debug
builds); CobaltC rejects at compile time what its checker can see without running the program
(§10, §14), which includes every conflict among the references a
function holds in its own variables and parameters that the program's text decides. The difference is
the default, and what each asks of the programmer where the default fails.
import std;
fn main()
{
Vec<i32> v = Vec::filled(4, 0);
usize i = 1;
usize j = 3;
ref<i32, exclusive> a = &mut v[i]; // two exclusive references into one vector,
ref<i32, exclusive> b = &mut v[j]; // at indices known only now
*a = 10;
*b = 20;
printf("%v %v\n", v[1], v[3]);
}10 20
Rust refuses that program: with i and j unknown, it cannot prove the two borrows
disjoint, so the programmer writes split_at_mut or indexes twice. CobaltC accepts it and checks
the indices as the borrows are made. Run it with j = 1 and the second borrow is the fault
diag.aliasing-conflict, at that line, in that run. Rust's answer is the same in both cases and
arrives before the program exists; CobaltC's is different in the two cases and arrives when it
runs.
import std;
struct Holder
{
ref<i32, shared> r;
}
fn stash(ref<Holder, exclusive> h, ref<i32, shared> r)
{
h.r = r;
}
fn main()
{
i32 outer = 1;
Holder h = Holder { .r = &outer };
{
i32 inner = 2;
stash(&mut h, &inner); // a reference to inner, stored by a function
printf("%v\n", *h.r); // fine: inner is alive
}
printf("%v\n", *h.r); // h may still refer to inner, which ended with its block
} // ✗ diag.destroy-while-aliased, at the checkIn Rust, Holder would be Holder<'a>, stash would take &mut Holder<'a> and &'a i32,
and the call would not compile, because h outlives inner. A CobaltC signature says what a
function's result may refer to (its one reference parameter, or those its from clause
names), but not what it stores through one parameter into another. The checker's facts still show
that h may refer to inner when inner's block ends, and h is read after it: a fault certain
on that path, so it is refused when the program is checked ([Certain-Fault-Refused], D-0340),
not left to the run. A function that returns the
reference, or a struct holding it (h = keep(&inner) with fn keep(ref<i32, shared> r) : Holder),
is tied to its argument by its signature and is rejected before the run. So is the same escape
written in one function, with no call between:
import std;
struct Holder
{
ref<i32, shared> r;
}
fn main()
{
i32 outer = 1;
Holder h = Holder { .r = &outer };
{
i32 inner = 2;
h = Holder { .r = &inner }; // ✗ diag.reference-escapes-scope, before the program runs
}
printf("%v\n", *h.r);
}Moving or destroying a value while a reference to it is live, and writing to a vector while
a reference into it is live, are likewise compile-time errors in both languages when the two uses
are in one function (§08, §10). Both also catch them across
functions: Rust through signatures and lifetimes, CobaltC through what each function does with its
reference parameters, which its checker works out from the function bodies (§14).
Where the conflict goes through a reference kept inside a data structure, as with Holder above,
CobaltC catches it at run time.
import std;
fn main()
{
String s = "text";
ref<String, shared> r = &s;
String t = s; // ✗ diag.move-while-aliased: r still borrows s
printf("%v\n", StringView::len(r));
}What a type says
Because Rust's checks are static, its types must carry what the checker needs; because CobaltC's are dynamic, its types carry less and its run-time state carries the rest. That shows up in four places.
| Rust | CobaltC | |
|---|---|---|
| A reference | &'a T, &'a mut T: a lifetime (usually elided) bounds every use | ref<T, shared>, ref<T, exclusive>: no lifetime; validity is checked at each use (§09) |
| A struct holding a reference | struct Holder<'a> { r: &'a i32 }: the lifetime is a parameter of the type | struct Holder { ref<i32, shared> r; }: the reference is tied to the storage holding it and the object it reaches, at run time (§10) |
| A function returning a reference | the result's lifetime is related to a parameter's by elision or by writing 'a; any relation can be stated | elided when exactly one parameter is a reference; with two or more, a from clause names the ones it may come from (from a, from a, b), the call borrows each of them, and the rest may only be probed, never kept (§10); without the clause it is refused (diag.lifetime-elision-ambiguous). One set of sources covers the whole result: parts from different sources are not expressible |
| What may cross to another thread | Send and Sync marker traits, checked at compile time; spawn wants 'static data, scoped threads borrow | any value moves but an Rc or what holds one (diag.not-thread-safe, refused when compiled, or a fault when an Rc is used in another thread); a reference may be lent for the thread's life and is checked at run time (§19) |
fn longest<'a>(a: &'a str, b: &'a str) -> &'a str {
if a.len() >= b.len() { a } else { b }
}import std;
fn longer(ref<String, shared> a, ref<String, shared> b) : ref<String, shared> from a, b
{
if (StringView::len(a) >= StringView::len(b)) { a } else { b } // ✓ the result is a or b
}
fn main()
{
String x = "abc";
String y = "de";
ref<String, shared> l = longer(&x, &y); // l borrows x and y
printf("%v\n", StringView::len(l));
}3
Rust relates the two parameters to the result by naming one lifetime for all three;
CobaltC names the parameters instead (D-0318, §10). Both say the same thing here: the call borrows
both arguments while the result is used. What CobaltC cannot say is a result whose parts come
from different sources, such as a pair with one reference from each argument, or one input
outliving another ('a: 'b): it has no names for lifetimes (that choice is final, D-0011 and
CHG-0022), so such a function returns indices or owned values instead. In exchange, a CobaltC
signature never needs a lifetime, and a reference stored in a Vec, a HashMap or a closure needs
no type parameter to say how long it lives.
Generics: traits against bounds
Rust's generics are organised by traits: a type implements a trait, a generic function
requires one (T: Ord), and traits also serve as interfaces, as operator overloading, as the
mechanism for iteration, formatting, conversion, and, through dyn Trait, as run-time
polymorphism. Most of Rust's expressiveness and most of its learning curve are there. CobaltC has
no traits. A generic parameter takes one of six built-in bounds, eq, ordered, number,
integer, clone or plain, which name what the language itself knows about a type
(§12); a type joins clone by defining T::clone, and nothing else is
user-extensible. There is no operator overloading, no interface a user type can implement, and no
run-time dispatch except through function values and closures. Where a Rust program would define a
trait and implement it for several types, a CobaltC program writes an enum of those types and a
match, or passes the behaviour as a function value. That is a real limit on what can be
abstracted over, chosen so that a call always names the function it calls
(§15).
Neither language has inheritance. Both monomorphise, so generic code costs nothing at run
time in either. Rust infers types across a whole function, forwards and backwards; CobaltC's
inference flows downward only, from a declaration or an expected type into an expression, which is
why its variables are usually declared with a type and auto is the exception.
Mutability
Rust marks the binding: let x is immutable, let mut x may be assigned and borrowed
exclusively, and a &mut can only be taken from a mut binding. CobaltC marks nothing on a
variable: any variable may be assigned, and the question is only ever about references, which are
shared or exclusive (§08). What Rust's mut buys is documentation and a
compile-time refusal to change what was declared unchanging; what CobaltC's absence of it buys is
one fewer word on every declaration and no second meaning for mut. Both make a const a
compile-time constant only.
Integers
Both have the same sized integer types and the same wrapping_, saturating_ and
checked_ operations. They differ on what plain + does when it overflows. In Rust it panics in
a debug build and wraps in a release build unless overflow checks are turned on; a shipped program
usually wraps. In CobaltC it is a fault, always (§06): there is no build in which an overflow is silent. The compiled cost of that
choice is measurable and modest (P): on the repository's benchmarks a CobaltC
program compiled through C runs between about the same time as the Rust program and about twice
it, and much of the gap is the arithmetic checks that a Rust release build leaves out.
Threads
Rust makes a data race a type error: a value crosses to another thread only if it is
Send, is shared only if it is Sync, and spawn requires what it captures to live for the whole
program, so sharing goes through Arc<Mutex<T>> or a scoped thread whose borrows the checker can
see end. CobaltC's spawn moves its arguments or lends a reference for the thread's life, and the
check that two threads never touch one object incompatibly is the same run-time alias check as
within one thread; a mutex guard, an Atomic, a Channel or an Arc are the ways to share on
purpose (§19). What that gives CobaltC, and Rust does not set out to give, is an
account of every schedule: a program's threads interleave at the granularity of single operations
under rules the specification states, so --explore can run a program under many schedules and
report every distinct outcome, and a wait that no thread can end is a diagnostic, diag.deadlock,
rather than a hang. Rust has no equivalent in the language; it has tools outside it. Both unwind a
failed thread and hand the failure to whoever joins it; both poison a mutex the failed thread held.
CobaltC has no condition variables and no memory orderings weaker than sequential consistency; Rust
has both.
Failure
Both languages separate expected failure, a Result or an Option the caller handles, from
a bug, which stops the program. Rust's stop is a panic: it unwinds the thread, running destructors,
can be caught with catch_unwind, and in a release build an overflow or an out-of-bounds index may
be a panic or, for overflow, nothing at all. CobaltC's stop is a fault: every fault has a name in a
registry (the appendix) and a location, it unwinds running destructors, and it
is contained only at the two
boundaries the language names, a supervised thread and a C-callable library entry
(§18). Rust's error enums are usually hand-written or generated by a library;
CobaltC's are hand-written, with map_err and ok_or at the edges. ? means the same thing.
Unsafe
In both, unsafe marks where the programmer, not the language, vouches for a claim. In Rust
the claims are about the absence of undefined behaviour: a raw pointer is valid, aliasing rules are
respected, a foreign function's contract holds; a wrong claim is undefined behaviour, and the rules
for what unsafe code may assume are still being settled (Stacked Borrows, Tree Borrows). In CobaltC
the claims are stated as side-conditions of named trusted rules (§20): a raw
read or write, a reclaim of raw memory, a call across the boundary, each with what it asserts. The
standard library's own unsafe blocks are listed with their claims. The compiled program trusts
the claim, as Rust does. Both languages hold that safe code cannot break
the invariants; neither can promise anything once a trusted claim is false.
The surface
| Rust | CobaltC | |
|---|---|---|
| Declarations | let x: T = …;, let mut | T x = …;, auto x = …;; no mut |
| Functions | fn f(x: T) -> U { … } | fn f(T x) : U { … } |
| Methods | impl T { fn m(&self) }, called x.m() | fn T::m(ref<T, shared> x), called T::m(&x); there is no method-call syntax, by decision (§22) |
| Patterns | match v { Some(x) => …, None => … } | match (v) { Some(x) : …, None : …, } |
| Closures | |x| x + k, captures inferred | [k](i32 x) : i32 { x + k }, captures listed (§15) |
| Loops | loop, while, for x in iter | while, for (init; cond; step), foreach (x in &v) |
| Text | &'static str, String, &str | str, String, StringView: a constant, owned text, a view (§21, "Which text type?") |
| Conversions | x as T, T::from(x), x.into() | widen<T>(x), narrow<T>(x), reinterpret<T>(x); as is reserved |
| Formatting | println!("{x} {y:?}"), a macro | printf("%v %v\\n", x, y), a built-in whose format is checked |
| Modules | mod, use, crates, pub | module, import, export; one standard library, no package manager (§17) |
| Macros | declarative and procedural | none |
| Traits | trait, impl … for, dyn | six built-in bounds; T::clone and T::drop by name |
Semantics and tooling
Rust's meaning is given by its reference, its compiler and its test suite, with a formal
specification (Ferrocene) written after the fact and a model of unsafe code still in research. It
has one compiler, cargo, crates.io, rustdoc, rust-analyzer, clippy and Miri, a stable
release since 2015, and targets from microcontrollers to every major operating system. CobaltC's
meaning is its specification, written as rules before the implementation; the compiler is held to
those rules on every conformance case, every showcase and every example in this guide, and a model
checker enumerates the small programs' outcomes. It has a compiler through C, a formatter, a standard library with no third-party code, and two
targets, x86-64 Linux and Windows. One is a production language with an ecosystem; the other is a
language whose whole behaviour can be read, run and argued about.
§06Arithmetic and numeric types
spec/06-arithmetic.mdChecked integer arithmetic, explicit conversions, how literals get their types, and the sizes and limits of types.
Numbers are where silent corruption usually starts, so CobaltC's arithmetic is
checked by default: an operation whose mathematical result does not fit its type does not
wrap around, it faults. Every other policy (wrapping, saturating, or returning None) is a named
function you call on purpose. Types never convert implicitly; every change of representation is a
named intrinsic with a documented behaviour.
Numeric types
| Type | Meaning | Notes |
|---|---|---|
i8 i16 i32 i64 i128 | signed integers of the given width | two's complement |
u8 u16 u32 u64 u128 | unsigned integers of the given width | |
isize usize | signed / unsigned integers of address width | the types of indices, lengths, sizes and pointer offsets; the width (16, 32, 64 or 128 bits) is fixed and documented by each implementation |
f32 f64 | IEEE 754 binary32 / binary64 | ±Inf and NaN are ordinary values; float arithmetic never faults |
bool | true or false | produced by comparisons and && || ! |
There is no implicit promotion: i32 + i64 is a type error, and a u8 cannot be passed
where an i32 is expected. Unary minus applies only to signed and float types.
Literals
Integer literals are digit strings: decimal, or hexadecimal, octal or binary after 0x,
0o or 0b (0xFF, 0o755, 0b1010), with no sign. A decimal literal of two or more digits does not
start with 0: C reads 0755 as octal, so it is refused, and the message names 0o755 and 755. A _ between two digits groups them and
is ignored: 1_000_000, 0xFFFF_0000, 3.141_592 (anywhere else, a _ is a syntax error). A literal's
type comes from, in order: an explicit suffix 123: u8; the expected type at that position
(a declared variable type, a parameter type, a field type, or the other operand of the same
operator); otherwise the default, i32 for integers and f64 for floats. An expression made only
of literals and operators takes the expected type as a whole, so u64 x = 1024 * 1024 * 1024 * 16;
is computed in u64, while auto y = 65536 * 65536; has no expected type, is an i32, and
overflows. A literal that does not
fit its type is a static error. A minus written directly before an integer literal is checked
with it, as one negative value, so -2147483648 is the smallest i32. A type's limits also
have names, min_value<i32>() and max_value<i32>() (below). Float literals are digits . digits, with an
optional exponent (1.5e-3, 2.5E3, or 1e5 with no fraction), optionally suffixed : f32;
one too large for its type (1e400) is a static error, not infinity. A byte character b'a'
is one ASCII character or an escape (b'\n', b'\'', b'\x7f'), for writing bytes readably
in code that parses. It is a number like any other literal and takes an unsigned type from its
context (u32 c = …; c == b'|' compares two u32s), and is a u8 when nothing fixes its type;
a signed context is a type error. A string literal "…" is a str unless its position declares
a String or a StringView, and a byte literal b"…" an array<u8, N> unless its position
declares a slice<u8, shared>, where it is a slice of bytes that live as long as the program
(§12, §22).
import std;
fn main()
{
auto a = 5; // i32: no suffix, no expected type
u8 b = 200; // u8 from the declared type; 200 fits
auto c = 7: u64; // u64 from the suffix
auto d = b + 1; // the 1 takes u8 from b; d is u8
auto e = 2.5; // f64
f32 f = 0.5: f32;
f64 tiny = 1.5e-3; // an exponent: 0.0015
u8 comma = b','; // a byte character: 44
u32 mask = 0xFF00; // hexadecimal; also 0o17 (octal) and 0b1010 (binary)
u64 ns = 1_000_000_000; // _ groups digits: one second in nanoseconds
u64 sixteen_gib = 16 * 1024 * 1024 * 1024; // literals only: computed in u64
i64 g = -1; // the expected type reaches through unary minus
i32 lo = -2147483648; // min(i32): 2147483648 alone would not fit
assert(d == 201);
assert(g < 0);
assert(lo + 2147483647 == -1);
assert(tiny == 0.0015 && comma == 44 && mask == 65280);
assert(sixteen_gib == 17_179_869_184 && ns == 1000000000);
static_assert(sizeof<u64>() == 8); // sizeof and alignof are intrinsics returning usize
static_assert(alignof<u16>() == 2);
}fn main()
{
256: u8; // ✗ diag.literal-out-of-range (static): 256 does not fit u8
}Checked arithmetic
+, - and * on integers fault with diag.arith-overflow when the result leaves the
type's range. / and % truncate toward zero (the remainder takes the sign of the dividend);
dividing by zero is diag.div-by-zero, and the one overflowing division, the minimum value of a
signed type divided by -1, is diag.div-overflow. Negating the minimum signed value is an
overflow too. When the operands are known — literals, constants, or operations on them nested to
any depth, 100 * 99999 * 100000 / 2 in a printf argument as much as in a declaration — the fault
is detected statically and the program is rejected ([Literal-Expression-Folded], D-0340);
otherwise it is a run-time fault that terminates the program (see §18). A local
initialized with a literal counts as that literal until something writes it, borrows it or
captures it in a closure, so u8 x = 200; u8 y = x + 100; is rejected too. After such a write,
or after an if that writes it on only one branch, the check happens at run time.
fn add(i32 a, i32 b) : i32
{
a + b // checked: faults if the sum leaves i32
}
fn main()
{
add(2147483647, 1); // ✗ diag.arith-overflow (dynamic): 2^31 does not fit i32
}fn main()
{
2147483647 + 1; // ✗ diag.arith-overflow (static): both operands are literals
}fn div(i32 a, i32 b) : i32
{
a / b
}
fn main()
{
div(-2147483647 - 1, -1); // ✗ diag.div-overflow (dynamic): -MIN does not fit
}Choosing a different overflow policy
When wrapping or clamping is what you actually want, say so. The wrapping_ and
saturating_ families never fault; the checked_ family returns an Option so the caller can
decide. These are ordinary generic calls with the operand type inferred from the arguments.
| Call | Result | On overflow |
|---|---|---|
wrapping_add(a, b), wrapping_sub, wrapping_mul | same type | wraps modulo 2N |
saturating_add(a, b), saturating_sub, saturating_mul | same type | clamps to the type's minimum or maximum |
checked_add(a, b), checked_sub, checked_mul, checked_div, checked_rem | Option<T> | None (also for division by zero) |
checked_neg(a) | Option<T> | None for the most negative value, and for any non-zero unsigned value |
import std;
fn main()
{
u8 top = 255;
assert(wrapping_add(top, 1: u8) == 0); // 255 + 1 wraps to 0
assert(saturating_add(top, 9: u8) == 255); // clamps at the maximum
match (checked_add(top, 1: u8))
{
Some(_) : // must not happen
{
assert(false, "unreachable");
},
None : {}, // overflow reported as None
}
match (checked_add(1: u8, 1: u8))
{
Some(v) :
{
assert(v == 2);
},
None :
{
assert(false, "unreachable");
},
}
}Shifts, bitwise operators and comparison
<<and>>take au32shift amount that must be less than the type's bit width; anything else isdiag.shift-amount-out-of-range. Left shift discards high bits by definition (it is not an overflow); right shift is arithmetic on signed types.&,|,^and~work on any integer type;!is boolean not.== != < <= > >=compare two operands of the same type and yieldbool. Floats follow IEEE rules: every comparison involvingNaNis false except!=.
import std;
fn main()
{
u32 one = 1;
assert(one << 4 == 16);
static_assert(-8 >> 1 == -4); // arithmetic shift keeps the sign
static_assert((12 & 10) == 8);
static_assert((12 | 3) == 15);
static_assert((6 ^ 3) == 5);
static_assert(~0 == -1);
f64 zero = 0.0;
auto nan = zero / zero; // floats do not fault
assert(!(nan == nan));
assert(nan != nan);
}Conversions are explicit
There is exactly one way to change a number's type: call the intrinsic that names the conversion. Each takes the target type as a type argument.
Five intrinsics work on an integer's bits directly: count_ones(x), leading_zeros(x) and
trailing_zeros(x) (each a u32; zero gives the type's width), and rotate_left(x, k) and
rotate_right(x, k) (by k modulo the width, keeping x's type). They act on the value's cell
image, so a negative i8 has eight ones, and none of them faults (D-0123).
| Intrinsic | From → to | Behaviour |
|---|---|---|
widen<U>(x) | integer to a wider integer whose range contains every value; f32 to f64 | always exact, never faults (u8 → i32, i32 → i64, f32 → f64) |
narrow<U>(x) | any integer to any integer | checked: diag.narrowing-overflow if x does not fit |
checked_narrow<T>(x) | any integer to any integer | Option<T>: Some(x) when x fits T, else None — for a value from outside, where a fault would be wrong (D-0122) |
narrow_wrapping<U>(x) | any integer to any integer | keeps the low bits, never faults |
reinterpret<U>(x) | between the signed and unsigned types of one width (and usize ⇄ isize); between a float and an integer of its width (f32 ⇄ u32/i32, f64 ⇄ u64/i64) | the same bit pattern read as the other type |
to_float<U>(x) | any integer or float to f32/f64 | nearest representable value (ties to even); beyond the target's range an infinity, as float arithmetic gives; NaN stays NaN |
to_int<U>(x) | float to integer | truncates toward zero; checked: infinities, NaN and out-of-range values fault |
import std;
fn main()
{
u8 small = 200;
i32 wide = widen<i32>(small); // always safe
assert(wide == 200);
assert(narrow<u8>(wide) == 200); // fits, so it succeeds
static_assert(narrow_wrapping<u8>(300) == 44); // 300 mod 256
static_assert(reinterpret<i32>(4294967295: u32) == -1);
f64 f = to_float<f64>(wide);
assert(to_int<i32>(f * 1.5) == 300);
usize n = 12;
assert(narrow<i32>(n) == 12); // usize → i32 is a narrowing, so it is checked
}Between the two float types: widen<f64>(x) takes an f32 to an f64 exactly, and
to_float<f32>(x) takes an f64 to the nearest f32, rounding as float arithmetic does. There
is no widen<f32> of an f64, since most f64 values have no exact f32. reinterpret gives
a float's IEEE-754 bits as an integer of the same width, and turns such an integer back into a
float, with no unsafe.
import std;
fn main()
{
f32 sample = 0.1;
f64 d = widen<f64>(sample); // exact: 0.100000001490116...
assert(to_float<f32>(d) == sample); // and back, rounded, to the same f32
static_assert(to_float<f32>(1.0 / 3.0) == 0.33333334: f32);
u64 bits = reinterpret<u64>(-2.0);
assert(bits >> 63 == 1); // the sign bit
assert(reinterpret<f64>(bits) == -2.0);
static_assert(reinterpret<u32>(1.0: f32) == 0x3f80_0000: u32);
static_assert(max_value<f32>() == 3.4028235e38: f32); // the largest finite f32
}fn to_byte(i32 x) : u8
{
narrow<u8>(x) // checked at run time
}
fn main()
{
to_byte(300); // ✗ diag.narrowing-overflow (dynamic)
}widen is only accepted where every value of the source fits the target, so it can never
lose one: widen<u64> of an i32 is a static error, because a negative i32 has no u64
value. narrow works between any two integer types, and never faults where the value fits.
Use it for usize and isize: whether usize → u64 is a widening depends on the address
width, so narrow<u64>(n) is the spelling that is accepted by every implementation.
fn to_u64(i32 x) : u64
{
widen<u64>(x) // ✗ diag.type-mismatch (static): -1 has no u64 value; use narrow
}
fn main()
{
to_u64(1);
}Sizes and limits of types
Four intrinsics describe a type rather than a value. Each takes the type as its type argument, written explicitly, and no other arguments.
| Intrinsic | Result | Meaning | For |
|---|---|---|---|
sizeof<T>() | usize | the bytes a T occupies, padding included | any type |
alignof<T>() | usize | the alignment a T's address must have, in bytes | any type |
min_value<T>() | T | the smallest value of T (for a float, the most negative finite one) | integer and float types |
max_value<T>() | T | the largest value of T (for a float, the largest finite one) | integer and float types |
Every fixed-width type has the same size and limits on every implementation:
sizeof<i32>() is 4 and max_value<i32>() is 2147483647. isize and usize have the address
width, which each implementation documents, so for them the intrinsics are the portable way to
write a size or limit, where a literal is not. A struct's size and alignment follow from its
fields (§16): each field is aligned, and the struct's alignment is its largest field's.
import std;
struct Pair
{
u8 tag;
u32 value;
}
fn main()
{
static_assert(sizeof<i32>() == 4);
static_assert(sizeof<u64>() == 8);
static_assert(alignof<u64>() == 8); // a number is aligned to its own size
static_assert(sizeof<bool>() == 1);
static_assert(sizeof<array<u16, 10>>() == 20); // an array has no padding
static_assert(alignof<Pair>() == 4); // its largest field's alignment
static_assert(sizeof<Pair>() == 8); // tag, 3 bytes of padding, value
static_assert(sizeof<usize>() == sizeof<isize>()); // the address width, whatever it is
static_assert(min_value<i8>() == -128);
static_assert(max_value<u8>() == 255);
static_assert(max_value<i32>() == 2147483647);
static_assert(min_value<u64>() == 0);
static_assert(max_value<usize>() == ~(0: usize)); // every bit set, at any address width
static_assert(wrapping_add(max_value<i32>(), 1) == min_value<i32>());
}Limits are most often the starting value of a search, a bound to clamp against, or a value that means "none". Here are all three:
import std;
// The spread of a list: start the minimum at the largest i64 and the
// maximum at the smallest, so the first element replaces both.
fn spread(ref<Vec<i64>, shared> v) : i64
{
i64 lo = max_value<i64>();
i64 hi = min_value<i64>();
foreach (p in v)
{
i64 x = *p;
if (x < lo)
{
lo = x;
}
if (x > hi)
{
hi = x;
}
}
hi - lo
}
// Clamp into i32's range, then narrow: the narrow can no longer fault.
fn clamp_to_i32(i64 x) : i32
{
if (x > widen<i64>(max_value<i32>()))
{
max_value<i32>()
}
else if (x < widen<i64>(min_value<i32>()))
{
min_value<i32>()
}
else
{
narrow<i32>(x)
}
}
// The index of the first b, or usize's maximum for "not found".
fn find(ref<Vec<u8>, shared> v, u8 b) : usize
{
foreach (i, x in v)
{
if (*x == b)
{
return i;
}
}
max_value<usize>()
}
fn main()
{
Vec<i64> v = Vec::new();
Vec::push(&mut v, 7);
Vec::push(&mut v, -3);
Vec::push(&mut v, 12);
assert(spread(&v) == 15);
assert(clamp_to_i32(5000000000) == 2147483647);
assert(clamp_to_i32(-5000000000) == -2147483648);
assert(clamp_to_i32(42) == 42);
Vec<u8> bytes = Vec::new();
Vec::push(&mut bytes, 10);
Vec::push(&mut bytes, 20);
assert(find(&bytes, 20) == 1);
assert(find(&bytes, 99) == max_value<usize>());
}A generic function may use the limits of its own type parameter. It cannot do arithmetic
on a T without a bound (§12), but it can produce a T's limit and pass it on. Each use is
checked when the function is instantiated, so a T that is not an integer type is rejected before
the program runs.
import std;
// The value inside, or T's maximum if there is none.
fn or_max<T>(Option<T> r) : T
{
match (r)
{
Some(x) : x,
None : max_value<T>(),
}
}
fn main()
{
u64 big = 5000000000;
assert(or_max(checked_mul(big, big)) == max_value<u64>()); // the product overflows u64
assert(or_max(checked_add(2: i32, 3)) == 5);
}fn main()
{
max_value<bool>(); // ✗ diag.type-mismatch (static): only number types have these
}fn main()
{
max_value<i32>() + 1; // ✗ diag.arith-overflow (dynamic): a limit is a value, not a literal
}- Default arithmetic is checked. If you want wrapping, write
wrapping_add; if you want to handle overflow, writechecked_addand match on theOption. - Never expect a conversion to happen for you. Reach for
widenfirst; usenarrow(checked) ornarrow_wrapping(deliberate truncation) when going the other way. - Use
usizefor lengths and indices,isizefor pointer offsets, and suffix a literal (5: u8) when the context does not already fix its type. - Floats never fault. Remember that
NaNis unequal to itself. - Write a type's limits as
min_value<T>()andmax_value<T>(). Forisizeandusizethey are the only portable spelling.
§07Resources, ownership and destruction
spec/07-resource-authority.mdResource types have exactly one owner, move instead of copying, and are destroyed automatically and exactly once.
Some values are just data: an i32, a bool, a struct of numbers. Copying them is
harmless. Other values own something that must be released exactly once: a heap buffer, a
file handle, a lock, a thread. CobaltC calls the second kind resources, and the
rules in this section exist so that a resource always has exactly one owner, is never copied, and
is destroyed exactly once, at a predictable moment, whether or not you remember to do it.
Plain types and resource types
A type is a resource if it is declared with the resource keyword, or if any of its
fields, elements or payloads is a resource. Vec<T>, String, Rc<T>, a thread handle, a
mutex and a lock guard are all resources. Numbers, bool, references, raw pointers and function
values are plain. A struct of plain fields is plain; a struct containing a Vec is a resource by
derivation, with no keyword needed.
struct Point // plain: two numbers
{
i32 x;
i32 y;
}
struct Path // a resource by derivation: it contains a Vec
{
Vec<Point> points;
}
resource struct Handle // a resource by declaration: it manages something
{ // beyond its fields (an OS handle, say)
i32 fd;
}One owner: moves, not copies
A resource lives in exactly one place. When you initialise a variable from it, pass it by
value to a function, store it in a field, or return it, the resource moves: the new place
becomes the owner and the old name becomes stale. Using a stale name is an error
(diag.stale-binding), caught at compile time when the move is visible in the same function and at
run time otherwise. A name moved on only some paths (in one branch of an if, or in a loop body that
runs again) counts as moved: give it a new value on every path before using it again. Nothing is ever
copied silently, so there can never be two owners.
resource struct Token
{
i32 id;
}
fn consume(Token t) // a by-value resource parameter takes ownership
{
} // t is destroyed here, at the callee's scope exit
fn main()
{
Token t = Token { .id = 1 };
consume(t); // ✓ t moves into consume
consume(t); // ✗ diag.stale-binding: t no longer owns anything
}import std;
fn main()
{
Vec<i32> v = Vec::new();
auto w = v; // moves the Vec into w; v is now stale
Vec::push(&mut w, 1); // ✓ use the new owner
}Because a resource is never copied, it cannot appear where a copy would be made: you
cannot compare two Vecs with ==, and you cannot read one out of a field of a live struct. Take
a reference instead (§09), or move the whole container.
import std;
fn main()
{
Vec<i32> a = Vec::new();
Vec<i32> b = Vec::new();
auto same = a == b; // ✗ diag.read-of-resource: comparison would copy both
}Automatic destruction
Every resource is destroyed automatically: a named resource when the block that declared
it ends, and a temporary (an unnamed call result or literal) at the end of the statement that
created it. Locals are destroyed in reverse order of creation. A struct's resource fields are
destroyed after the struct's own destructor, innermost first, in reverse declaration order. A
return, break, continue or run-time fault unwinds the same way. There is no way to leak a
resource, so there is no leak diagnostic.
You can also destroy a resource early with drop(x). Afterwards x is stale until you give
it a new value: once x's value has gone, moved away or dropped, x = e gives it a new one, which
is destroyed at the end of x's own block like its first value. A value whose end only frees memory
(a String, a Vec, a HashMap, a Weak, an Option or struct made of such: a *quiet* type, D-0194) is simply
replaced: s = "new"; destroys the old String there. Assigning over any other
resource that is still there is an error (diag.overwrite-of-live-resource), because its end does
something you should see: a destructor of yours runs, a file closes, a thread is joined. Write
overwrite(&mut x, e), which destroys the old value and stores the new one, or drop it first. The same
holds for a field (g.file = f;) and for a write through a reference (*r = v;, r.rows = v;): where
the compiler can see the old value is still there, it rejects the assignment before the program runs;
elsewhere, the run does. What counts is whether the value there owns anything: a None of an
Option<File> owns nothing, so o = Some(f); over it is fine, while a Some must be dropped
first. A type declared resource, or with a destructor, always owns. Declaring the name again in
the same block does not: that is diag.duplicate-local (§11).
import std;
fn make() : Vec<i32>
{
Vec<i32> v = Vec::new();
Vec::push(&mut v, 1);
v // moved out to the caller, not destroyed here
}
fn main()
{
{
auto result = make(); // result owns the Vec now
Vec::push(&mut result, 2);
} // destroyed here, at the caller's block exit
make(); // an unstored temporary: destroyed at this `;`
Vec<i32> v = Vec::new();
drop(v); // ✓ destroyed early; v is now stale
v = Vec::new(); // ✓ v's value has gone, so v takes a new one
Vec::push(&mut v, 3);
}Destructors
A type gets a destructor by declaring an associated function named drop that takes an
exclusive reference to the value and returns nothing. The language calls it exactly once, when the
resource is destroyed; you may not call it yourself. Inside it you can mutate the value but not
move out of it. Field resources are destroyed after the body runs. The type must be a resource:
declare it resource struct. A plain struct is copied and never destroyed, so a destructor on one
would never run, and is refused (diag.destructor-on-plain-type).
import std;
resource struct Tagged
{
str tag;
}
fn Tagged::drop(ref<Tagged, exclusive> self)
{
printf("%s", self.tag); // runs once, when this Tagged is destroyed
}
resource struct Holder
{
Tagged a;
Tagged b;
}
fn main()
{
Tagged x = Tagged { .tag = "1" };
Tagged y = Tagged { .tag = "2" };
Holder h = Holder { .a = Tagged { .tag = "3" }, .b = Tagged { .tag = "4" } };
printf("\n");
} // h first (its fields in reverse order: 4 then 3), then y, then x4321
4321.Things the rules forbid
import std;
resource struct Lock
{
u32 id;
}
fn Lock::drop(ref<Lock, exclusive> self)
{
printf("released %u\n", self.id);
}
fn main()
{
Vec<i32> v = Vec::new();
v = Vec::new(); // fine: a Vec of numbers is quiet, the old one is destroyed
Lock l = Lock { .id = 1 };
l = Lock { .id = 2 }; // ✗ diag.overwrite-of-live-resource: lock 1's release would be hidden
}The fix is overwrite(&mut l, Lock { .id = 2 });, which destroys the old Lock there (and
prints its release where you wrote it), or drop(l); first. Two more rejections you will meet:
drop(v) twice is diag.stale-binding (the first drop ended v); and moving a resource out of a
field of a live struct (auto inner = holder.field;) is diag.move-out-of-field, because the struct
would be left half-owned. Move the whole struct, or take a reference to the field.
- If a type owns something, it is a resource: mark it
resourceand give it adrop. Types that merely contain resources become resources automatically. - Passing a resource by value hands it over. To let a callee look without taking, pass
&x; to let it modify, pass&mut x. - Do not fight scope-end destruction. Put a resource in the smallest block that needs it and let the block end release it.
drop(x)is for early release. After it,xis gone until you give it a new value (x = e) or declare the name again.
§08Aliasing: shared and exclusive access
spec/08-alias-validity.mdAny number of readers, or one writer, never both. The rule is checked at every access, so a conflict cannot go unnoticed.
Two pieces of code touching one object at the same time is the root of most memory bugs: an iterator invalidated by a push, a struct half-updated by two threads, a buffer freed while something still points into it. CobaltC's answer is a discipline on access paths: every way of reaching an object (its name, a reference, a field projection) has a mode, and the modes that may coexist are fixed.
Two modes
| Mode | Written | May | Coexists with |
|---|---|---|---|
shared | &x, type ref<T, shared> | read | any number of other shared paths |
exclusive | &mut x, type ref<T, exclusive> | read and write; and, for the owner, move or destroy | nothing else that overlaps |
A variable's own name is always an exclusive path: there is no mut keyword on bindings,
because whether you may write is decided by what references currently exist, not by how the variable
was declared. Restricting access is what a borrow does.
The one rule
At every read and every write, the language checks: is there another live path to
the same storage whose mode conflicts with this access? Shared and shared never conflict.
Anything involving an exclusive path conflicts, unless the other path is an ancestor of
this one (the thing it was borrowed from). Forming a conflicting borrow is reported at once as
diag.aliasing-conflict; so is using the owner while a conflicting borrow lives.
fn main()
{
i32 x = 1;
auto r1 = &x; // ✓ shared
auto r2 = &x; // ✓ any number of shared readers; the owner may still read x
x = 2; // ✗ diag.aliasing-conflict: writing while r1, r2 are live
i32 sum = *r1 + *r2;
}fn main()
{
i32 x = 1;
auto r1 = &mut x; // ✓ exclusive
auto r2 = &x; // ✗ diag.aliasing-conflict: r1 is exclusive and still live
*r1 = 2;
}The checker knows what each function does through each of its reference parameters: which fields it may read and which it may write, worked out from the function's body and the functions it calls. So a call that passes two references to the same storage, where the function writes through one while the other is in use, is rejected at the call, and the diagnostic says what the function does through which argument.
fn set_then_read(ref<i32, exclusive> a, ref<i32, shared> b) : i32
{
*a = 1;
*b
}
fn main()
{
i32 x = 0;
set_then_read(&mut x, &x); // ✗ diag.aliasing-conflict: set_then_read writes x through argument 1
}Most conflicts are reported before the program runs, marked (static): whenever the
program's text shows that a conflicting reference is live. That covers a borrow held in a variable, a
reborrow through a reference or a guard (&*r, &r.f), the binder of a match (&e) arm, the
arguments a thread was spawned with, until join, and what a called function does through its
parameters. What only the values decide is checked at run time, marked (dynamic): two arguments
that meet only for some values (two elements of one array chosen by computed indexes) when the call
is made, from what the function may do with them; references kept inside data structures when the
conflicting access runs.
import std;
fn set_then_read(ref<i32, exclusive> a, ref<i32, shared> b) : i32
{
*a = 1;
*b
}
fn main()
{
array<i32, 2> v = [0, 0];
usize i = 1;
usize j = i * 1;
set_then_read(&mut v[i], &v[j]); // ✗ diag.aliasing-conflict (dynamic), at the call, when i == j
}struct Counter
{
i32 hits;
i32 misses;
}
fn bump(ref<Counter, exclusive> c)
{
auto n = &mut c.hits; // a reborrow of c.hits, through c
c.misses = 0; // ✓ a different field
c.hits = 0; // ✗ diag.aliasing-conflict (static): n still borrows c.hits
*n += 1;
}
fn main()
{
Counter k = Counter { .hits = 0, .misses = 0 };
bump(&mut k);
}When does a borrow end?
A reference lives as long as something holds it. A reference passed straight to a call
dies when the statement ends, which is why consecutive calls that each borrow the same variable are
fine. A reference, slice or StringView kept in a local variable lives until the last statement
of its block that uses it, and ends there. So does any other local that holds references but
owns nothing to destroy: the Option<ref<V, shared>> that HashMap::get returns, or a struct of
references. Using it inside a loop, a branch or a nested block
counts as a use by that whole statement, so a reference used in a loop lives through the loop.
A reference variable lives to the end of its block, as before, when a closure captures it, when
another reference was borrowed through it, or when a variable that can hold references (a
Vec<StringView>, say) shares a statement with it and is used later, since that variable may
keep a reference derived from it. A reference to data that holds no references (a
ref<Vec<i32>, exclusive> parameter, a StringView) cannot keep one, so it counts only in a
statement that could rebind it: one that assigns it, borrows it with &mut, or captures it in a
closure.
import std;
fn main()
{
String cur = "abc";
slice<u8, shared> b = StringView::as_bytes(&cur);
assert(slice_len(b) == 3); // the last use of b: it ends after this statement
String::clear(&mut cur); // ✓ nothing borrows cur any more
assert(StringView::len(&cur) == 0);
HashMap<String, u32> m = HashMap::new();
HashMap::insert(&mut m, "a", 1);
Option<ref<u32, shared>> hit = HashMap::get(&m, "a");
assert(Option::is_some(&hit)); // the last use of hit
HashMap::insert(&mut m, "b", 2); // ✓ hit no longer borrows m
}Assigning a reference a new referent is no use of the one it had ([Ref-Reassign-Releases],
D-0341): a cursor cur = &steps[i]; reassigned at the end of a loop's round holds no loan between
its last read and the assignment, so steps[i].visited = true; there is accepted, in both builds.
import std;
fn main()
{
Vec<i32> v = Vec::new();
Vec::push(&mut v, 1);
ref<i32, shared> first = &v[0];
foreach (k in 0..2: i32)
{
printf("%v\n", *first); // used in the loop: first lives through the whole loop
Vec::push(&mut v, k); // ✗ diag.aliasing-conflict: first still borrows v
}
}A block ends every borrow it holds, so wrapping a borrow in a block still works, and reads well when a borrow should visibly end.
import std;
fn main()
{
Vec<i32> nums = Vec::new();
Vec::push(&mut nums, 10); // the borrow dies at this `;`
Vec::push(&mut nums, 20); // ✓ a fresh borrow; nothing conflicts
i32 x = 1;
{
auto r = &mut x; // r lives until the end of this block
*r = 5;
}
x += 1; // ✓ r is gone
assert(x == 6);
}Reborrowing and ancestors
A path derived from another (a reborrow &*r, or a field projection r.a) has that path
as its ancestor. Ancestors never conflict with their descendants, but the ancestor cannot be used in
a conflicting way while a descendant lives. Once the descendants are gone, the ancestor is usable
again.
import std;
fn main()
{
i32 x = 1;
{
auto r1 = &mut x;
{
auto r2 = &*r1; // ✓ a shared reborrow, child of r1
assert(*r2 == 1); // writing through r1 here would be diag.aliasing-conflict
}
*r1 = 3; // ✓ r2 is gone, the parent is usable again
}
assert(x == 3); // ✓ r1 is gone, the owner is usable again
}Disjoint fields
Conflicts are decided by overlap of storage, not by which variable the paths come from. Two exclusive borrows of different fields of the same struct do not overlap and may coexist.
import std;
struct Pair
{
i32 a;
i32 b;
}
fn main()
{
Pair p = Pair { .a = 1, .b = 2 };
auto ra = &mut p.a;
auto rb = &mut p.b; // ✓ disjoint from p.a
p.b = 30; // ✗ diag.aliasing-conflict: rb is a live exclusive path to p.b
*ra = 10;
*rb = 20;
}The write to p.b above is rejected because rb, a live exclusive path to exactly that
storage, still exists until the block ends. The same applies to reading p.b through the owner: an
exclusive child excludes every non-ancestor access, reads included, until it is gone. Confine the
borrows to a block and the owner is free again:
import std;
struct Pair
{
i32 a;
i32 b;
}
fn main()
{
Pair p = Pair { .a = 1, .b = 2 };
{
auto ra = &mut p.a;
auto rb = &mut p.b;
*ra = 10;
*rb = 20; // reading p.a or p.b here would conflict with the live exclusive borrows
}
assert(p.a == 10); // ✓ both borrows ended with the block
assert(p.b == 20);
}Shared means read-only, all the way down
An exclusive path can only be derived from an exclusive path. Given a ref<T, shared>
you cannot write through it and cannot reborrow it exclusively: the mode is part of the reference's
type, so a function's signature tells the caller exactly what it may do. The other direction is
always allowed: an exclusive reference can be passed to a function that asks for a shared one, and
the function gets a shared reborrow of it (as if you had written &*r). With v : ref<Vec<T>,
exclusive>, Vec::len(v) just works; likewise a slice<T, exclusive> for a slice<T, shared>.
struct P
{
i32 a;
}
fn bump(ref<P, shared> p)
{
p.a = 1; // ✗ diag.write-through-shared
}
fn main()
{
P v = P { .a = 0 };
bump(&v);
}All the way down includes the references a value holds. Read through a ref<S, shared>, an
exclusive reference stored in S comes out as a shared one: you can read through it, keep it, pass
it or return it as a ref<T, shared>, but not write through it. A copy of a value that holds an
exclusive reference cannot be taken out through a shared reference either, and clone cannot copy
one (diag.borrow-exceeds-source). A fn field is checked when it is called: a closure that writes a
variable it captured cannot be called through a shared reference to the struct that holds it
(diag.borrow-exceeds-source, at run time, since a fn type does not show what the closure
captured). To change something through a value others share, put it in a mutex (§19).
import std;
struct Counter
{
ref<i32, exclusive> total;
}
fn peek(ref<Counter, shared> c) : i32
{
*c.total // ✓ reading is fine
}
fn bump(ref<Counter, shared> c)
{
*c.total = *c.total + 1; // ✗ diag.write-through-shared
}
fn main()
{
i32 n = 0;
Counter c = Counter { .total = &mut n };
printf("%v\n", peek(&c));
bump(&c);
}Moving or destroying needs solitude
Moving a resource, or destroying it (with drop or at scope end), requires that no other
path to it exists at all. Otherwise a reference would be left pointing at nothing.
import std;
fn main()
{
Vec<i32> v = Vec::new();
auto r = &v;
drop(v); // ✗ diag.destroy-while-aliased: r is still live
usize n = Vec::len(r); // (because r is used here)
}import std;
fn take(Vec<i32> v)
{
}
fn main()
{
Vec<i32> v = Vec::new();
auto r = &v;
take(v); // ✗ diag.move-while-aliased: r still reaches v
usize n = Vec::len(r); // (because r is used here)
}- Borrow shared (
&x) by default; borrow exclusively (&mut x) only for the duration of the change. - Keep references short-lived. Passing
&mut vdirectly as an argument creates a borrow that ends at the semicolon. - If the checker complains about a conflict, end the earlier borrow: put it in its own block, or reorder the code so the write happens after the last use of the reference.
- Field-level borrows are precise: borrowing
p.aexclusively leavesp.bfree.
§09References
spec/09-identity-origin-extent.mdReferences are copyable values that name a place; dereferencing gives you that place back with every check intact.
A reference is the value form of an access path: a way to reach an object without owning it. References are plain values (copyable, no destroy authority) and carry their mode in their type. Raw pointers are a different thing entirely and live in §20.
Forming and using references
| Syntax | Meaning |
|---|---|
&e | a ref<T, shared> to the place e |
&mut e | a ref<T, exclusive> to the place e |
*r | the place r refers to: read it in an expression, assign to it, borrow it again, or project a field or element |
r.f, r[i] | field access and indexing look through a reference automatically |
r1 == r2 | identity: true only if both refer to the same storage of the same object (*r1 == *r2 compares the values; between two ref<T, _> of a T: eq the identity form is warned of, diag.reference-identity) |
The operand of & must be a place: a variable, a field, an element, or *r.
You cannot borrow a temporary such as a call result or a literal (&make()); bind it to a variable
first. This is rejected rather than given a lifetime because the temporary would end at the
semicolon and take the reference with it.
import std;
struct Pair
{
i32 a;
i32 b;
}
fn main()
{
i32 x = 5;
{
auto r = &mut x;
*r += 1; // read and write through the same reference
}
assert(x == 6);
Pair p = Pair { .a = 1, .b = 2 };
auto rp = &p;
assert(rp.a == 1); // auto-deref: rp.a means (*rp).a
auto ra = &p.a;
auto rb = &p.b;
assert(!(ra == rb)); // different fields, so different identities
auto ra2 = &p.a;
assert(ra == ra2); // same field of the same object
ref<i32, shared> copy = ra; // references are plain values: copying is fine
assert(*copy == 1);
}fn make() : i32
{
5
}
fn main()
{
auto r = &make(); // ✗ diag.borrow-of-non-place: a call result is not a place
}The one place a temporary may be borrowed is as an argument: f(&make()) or
printf("%v", &sprintf(…)). The value lives until the end of the statement, and the call is over
before then. This works when the call's own result is not a reference, since such a result could
carry the borrow out. An operator's result, the value ? gives, and a number or bool literal
may be borrowed there too: is_three(&(k + 1)), Vec::len(&names()?), is_three(&3); so may
a block's value, the usual form after C hands over memory: Vec::len(&unsafe { Vec::from_c_bytes(p)
}), or f(&{ String::copy(name) }) where f takes a StringView. An if or a
match is not borrowed in place even there: bind its value first. A literal takes the type the parameter refers to, so &3 passed where a ref<u64, shared> is
expected is a reference to a u64.
import std;
fn total(ref<Vec<i32>, shared> v) : i32
{
i32 t = 0;
foreach (x in v)
{
t += *x;
}
t
}
fn make(i32 n) : Vec<i32>
{
Vec<i32> v = Vec::new();
for (i32 i = 1; i <= n; i += 1)
{
Vec::push(&mut v, i);
}
v
}
fn is_three(ref<u64, shared> x) : bool
{
*x == 3
}
fn main()
{
assert(total(&make(4)) == 10); // the Vec lives until the end of this statement
printf("%v\n", &sprintf("%v-%v", 1, 2));
u64 k = 2;
assert(is_three(&(k + 1))); // an operator's result
assert(is_three(&3)); // a literal, as a u64
}Part of a temporary may be borrowed there too: a field (StringView::len(&person().name)),
an element, or a slice of an array literal or a call's result (sum(&[1, 2, 3][0..2])). A String
that a call returns may be viewed the same way, so a computed path needs no binding:
read_file(&sprintf("%s/%s", dir, name)) (where a StringView is declared, &s of a String is
its view, D-0302). It lives as
long as the temporary does, to the end of the statement. A field can also be moved out of a
temporary, String n = person().name;: the rest of the temporary ends at once, as if the struct had
been destructured. That needs a struct without a destructor of its own.
import std;
struct Person
{
String name;
String city;
}
fn person() : Person
{
Person { .name = "Ada", .city = "London" }
}
fn sum(slice<i32, shared> xs) : i32
{
i32 t = 0;
foreach (x in xs)
{
t += *x;
}
t
}
fn main()
{
assert(StringView::len(&person().name) == 3); // a field of a temporary, borrowed
assert(sum(&[1, 2, 3][0..2]) == 3); // a slice of an array literal
assert(StringView::len(&person().city[0..3]) == 3); // a view of a temporary's String
String n = person().name; // moved out; `city` ends here
assert(n == "Ada");
}References inside structs
A reference may be stored in a field. It then lives as long as the struct that holds it, which in turn may not outlive the referent (§10).
import std;
struct View
{
ref<i32, shared> r;
}
fn main()
{
i32 x = 1;
auto v = View { .r = &x }; // the borrow is held by v's object
assert(*v.r == 1); // ✓ valid as long as v lives
}References as parameters
Passing &x or &mut x to a function creates a borrow that the parameter holds for the
duration of the call and releases when the call returns. Inside the function the parameter is an
ordinary reference. A parameter of type ref<T, exclusive> can be passed on to another call
directly, without a new &mut, because it already is an exclusive reference.
import std;
fn bump(ref<i32, exclusive> counter) : i32
{
*counter += 1;
*counter
}
fn bump_twice(ref<i32, exclusive> c) : i32
{
bump(c); // pass the reference on as a value
bump(c)
}
fn main()
{
i32 n = 0;
assert(bump(&mut n) == 1); // the borrow lives for the call only
assert(bump_twice(&mut n) == 3);
assert(n == 3);
}- Use
&xto lend,&mut xto lend for writing. The callee's signature tells you which it needs. *ris a place, so*r = v,&*r, and(*r).fall work; for fields,r.fis the same as(*r).f.- Bind a call result before keeping a borrow of it; borrowing one just for a call,
f(&make()), is fine. ==on references asks whether they point at the same thing, not whether the values are equal; compare*a == *bfor values.
§10Lifetimes and temporal validity
spec/10-temporal-validity.mdA reference is checked statically where the escape is visible and dynamically everywhere else; either way it never outlives its target.
A reference must never outlive the object it refers to. CobaltC enforces this with two
layers: a lexical check that rejects the obvious escapes before the program runs, and a use-time
check that catches everything else as diag.stale-binding at the first use of a dead reference. No
lifetime annotations exist; the language decides validity from where things are declared and, for
a function's result, from its reference parameters or the ones its from clause names.
A reference cannot leave its referent's scope
If a reference to a local is returned from the function, or stored into a variable
declared in an enclosing block, it is rejected statically as diag.reference-escapes-scope.
fn dangling() : ref<i32, shared>
{
i32 x = 1;
&x // ✗ diag.reference-escapes-scope: x dies with this call
}
fn main()
{
auto r = dangling();
*r;
}The corrected form returns the value itself: fn ok() : i32 { i32 x = 1; x }.
When the escape is not lexically visible (the reference is stored through another reference, into an aggregate the checker cannot see the owner of, or through a call), the static rule does not fire and the run-time check takes over. The program is still rejected, just later.
struct Holder
{
ref<i32, shared> r;
}
fn stash(ref<Holder, exclusive> h)
{
i32 local = 5;
h.r = &local; // a store through a reference: not lexically visible as an escape
} // local ends here; whatever h points at now holds a dead reference
fn main()
{
i32 outer = 0;
auto held = Holder { .r = &outer };
stash(&mut held);
*held.r; // ✗ diag.stale-binding (dynamic): first use of the dead reference
}Returning references from functions
A function may return a reference, a view, or a value holding them, as long as the
checker can tell what the result points into, because each caller is checked against that. With
one reference-typed parameter there is only one answer, so nothing is written: the result is
understood to point into whatever that argument pointed at. This is the shape of most library
accessors (Vec::index_shared, Rc::get). With two or more reference parameters, the signature
says which ones the result may come from, with a from clause (below). With none, there is
nothing for the result to point into, and it may not be a reference
(diag.lifetime-elision-ambiguous names both of these last cases).
import std;
struct Pair
{
i32 a;
i32 b;
}
fn first(ref<Pair, shared> p) : ref<i32, shared>
{
&p.a // ✓ one reference parameter: the result borrows from it
}
fn main()
{
Pair pr = Pair { .a = 1, .b = 2 };
auto y = first(&pr); // y is a shared borrow of pr.a, held by y
assert(*y == 1);
}Because y above is known to borrow from pr, a later pr.a = 3; while y is still in
use is an aliasing conflict (§08), exactly as if you had written auto y = &pr.a;.
from clausefn pick(ref<i32, shared> p1, ref<i32, shared> p2) : ref<i32, shared>
{ // ✗ diag.lifetime-elision-ambiguous: which argument does the
p1 // result depend on? The language will not guess: write
} // `from p1` (or `from p1, p2`) after the result typeNaming the result's sources: from
A from clause after the result type names the parameters a function's result may refer
into. It is the one way to return a reference, a view or a value holding them (Vec<StringView>,
Option<ref<T, shared>>) from a function that takes more than one reference parameter, and it is
needed only there: with one reference parameter the result is understood to come from it.
The clause is a promise in the signature, and the checker holds both sides to it:
| The function body | Each caller | |
|---|---|---|
| a parameter the clause names | may be returned, stored in the result, kept | its argument stays borrowed for as long as the result is used |
| a reference parameter it leaves out | may only be probed: compared, measured, searched for, passed where nothing can keep it (diag.result-source-kept) | its argument is free again as soon as the call returns |
The usual case names one source. Here the key is only searched for, so the caller may change it while the result is still in use:
import std;
fn after(StringView line, StringView key) : StringView from line
{
match (StringView::find(line, key))
{
Some(i) : &line[i + StringView::len(key)..$],
None : &line[0..0],
}
}
fn main()
{
String line = "name=ada";
String key = "name=";
StringView v = after(&line, &key);
String::append(&mut key, "!"); // ✓ key was only probed
assert(v == "ada");
}The standard library does the same: StringView::split(StringView v, StringView sep) :
Vec<StringView> from v returns views of v alone, so the separator can be any text, and
HashMap::get(m, key) is declared from m, so the key you look up with is not held by the
answer. The clause is checked against the body, whatever a caller passes:
import std;
fn bad(StringView a, StringView b) : StringView from a
{
b // ✗ diag.result-source-kept: `from a` says the result is not `b`
}When the result may be any of several parameters, as the run decides, name each of them:
from a, b, or as many as there are. A lookup that falls back to a default is the common
shape:
import std;
// The value for `key`, or `fallback` when there is none.
fn setting(ref<HashMap<String, String>, shared> config, StringView key, ref<String, shared> fallback) : ref<String, shared> from config, fallback
{
match (HashMap::get(config, key))
{
Some(v) : v,
None : fallback,
}
}
fn main()
{
HashMap<String, String> config = HashMap::new();
HashMap::insert(&mut config, "colour", "blue");
String plain = "none";
ref<String, shared> c = setting(&config, "colour", &plain);
ref<String, shared> s = setting(&config, "size", &plain);
printf("%s %s\n", c, s);
}blue none
The checker does not follow which source the run picks: it knows only that the result is one of them. So every named argument stays borrowed while the result is used, and the result lives no longer than the shortest-lived of them:
import std;
fn longer(ref<String, shared> a, ref<String, shared> b) : ref<String, shared> from a, b
{
if (StringView::len(a) >= StringView::len(b))
{
a
}
else
{
b
}
}
fn main()
{
String x = "abc";
String y = "de";
ref<String, shared> l = longer(&x, &y);
String::append(&mut y, "!"); // ✗ diag.aliasing-conflict: l may be y
printf("%s\n", l);
}import std;
fn longer(ref<String, shared> a, ref<String, shared> b) : ref<String, shared> from a, b
{
if (StringView::len(a) >= StringView::len(b))
{
a
}
else
{
b
}
}
fn main()
{
String x = "abc";
ref<String, shared> l = &x;
{
String y = "de";
l = longer(&x, &y); // ✗ diag.reference-escapes-scope: l may be y, which ends here
}
printf("%s\n", l);
}When to use it. Write from when a function with two or more reference
parameters returns something that refers into them: name the parameters the result can actually
come from, and leave out the ones the body only looks at (a key, a needle, a separator, a
comparison's other side). Name several only when the result really may be any of them. Leave the
clause off when there is one reference parameter (it is implied) or when the result holds no
reference (diag.result-source-invalid). Each parameter is named once.
What it costs. Nothing at run time: the clause is checked before the program runs and adds no instructions or checks to the compiled program; the compiler reads it only to learn that a left-out view argument is probed, which lets it pass that view without a tracked copy of its own. The cost is in what callers may do. Every argument the clause names stays borrowed while the result is used, so a name the body never needs (accepted, and sound) only takes freedom away from callers; and a parameter the clause leaves out may only be probed in the body, directly. The check follows no flow, so a body that copies such a parameter into a local and then only measures the local is still rejected: probe the parameter itself.
What it cannot say. One clause covers the whole result. A result whose parts come from different arguments (a pair holding a reference from each) has no clause that says so: return indices into the arguments, or owned values, instead. Nor is there a way to say that one argument outlives another; CobaltC has no lifetime names (Rust's comparison).
Growth invalidates element references
A Vec may move its elements to a new buffer when it grows. A reference to an element
obtained before a push that reallocates is stale afterwards. Where the checker can see both the
borrow and the push in one function, it rejects the program; where it cannot (the push happens
through a reference parameter, say), the stale reference faults at its next use. Either way it does
not read freed memory.
import std;
fn main()
{
Vec<i32> v = Vec::new();
Vec::push(&mut v, 10);
auto first = Vec::index_shared(&v, 0); // a shared borrow into v, held by first
Vec::push(&mut v, 20); // ✗ diag.aliasing-conflict: an exclusive borrow of v
*first; // while first (derived from v) is still live
}- Return values, not references, unless the result points into a reference parameter: with one such parameter that is implied, with several the
fromclause names the ones it may come from. - Do not store a reference in a variable that outlives the block where the referent was declared.
- Re-fetch element references after any call that may grow or shrink a
Vec. - If you see
diag.stale-binding, ask what ended the referent: a scope exit, a move, adrop, or a reallocation.
§11Initialisation
spec/11-initialization.mdEvery variable is written before it is read, on every path, and every aggregate is built whole; constants name values known before the program runs.
Reading storage that has never been written is undefined behaviour in C. In CobaltC it is impossible in a well-formed program: a variable declared without an initialiser must be assigned on every path before it is read, and the check is static. Aggregates are always initialised whole.
Declarations
| Form | Meaning |
|---|---|
T x = e; | declare x of type T, initialised from e (which is checked against T) |
auto x = e; | declare x with the type of e |
T x; | declare x uninitialised; the type is required because there is nothing to infer from |
Name { f1, f2 } = e; | destructure a struct: bind each field to its name and consume the struct |
Initialising from a plain value copies it; from a resource, moves it; from a temporary such as a struct literal or a call result, adopts it.
One name, one declaration per block
A block declares a name once. A second i32 total further down the same block is
diag.duplicate-local, which says where the first one is: to change the variable, assign to it
(total = 10;); for a value of another type, give it another name. A function's parameters count
as declared in its body, and so do the names a foreach, a for header, a match arm or an
if-pattern binds for the block they govern, so fn f(i32 n) { i32 n = n * 2; } is rejected
too: write n = n * 2;.
A block inside it may reuse the name: the inner variable shadows the outer one
until the inner block ends, and the outer one is untouched. Separate blocks, successive loops and
separate match arms each have their own names, and a local may take the name of a function or a
constant (a program's own names never clash with names added to std later). Languages differ
here: Rust lets any declaration shadow, Java and C# forbid shadowing a local even from an inner
block; CobaltC follows C and C++. Every local can already be assigned, so a second declaration in
the same block would only hide a mistake.
import std;
fn main()
{
i32 total = 0;
total += 4; // ✓ change it by assigning
{
i32 total = 100; // ✓ an inner block's own total
assert(total == 100);
}
assert(total == 4); // the outer one is untouched
i32 total = 10; // ✗ diag.duplicate-local: declared above, in this block
}Constants
const τ NAME = e; names a value, at the top level of any module or inside a function (below). NAME can be used
wherever its value could, with the visibility, export, import and qualified paths of any item.
e must be a constant expression: literals, other constants, operators, struct, array and
variant literals of constant expressions and their fields and elements (SCREEN.w, PRIMES[2]),
a function's name, and the pure intrinsics (min_value, sizeof, widen, …). A constant cannot be a resource, cannot depend on itself, and cannot be
assigned to or borrowed; an overflow in computing one is reported at the constant, before the
program runs. Integer, float, bool and str constants cost nothing at run time: each use becomes
the literal.
import std;
const u64 KIB = 1024;
const u64 MIB = KIB * KIB;
const u32 READ = 0x1;
const u32 WRITE = 0x2;
const u32 READ_WRITE = READ | WRITE;
const i32 LOWEST = -2147483648;
struct Size
{
u32 w;
u32 h;
}
const Size SCREEN = Size { .w = 640, .h = 480 };
fn main()
{
static_assert(MIB == 1048576);
static_assert(READ_WRITE == 3);
static_assert(LOWEST < 0);
static_assert(SCREEN.w * SCREEN.h == 307200); // a field of a constant is a constant
}A constant is typed exactly as a declaration τ x = e; would be: in
const u64 MIB = 1024 * 1024; the literals are u64s, and an initializer that overflows its type,
such as const i32 BIG = 65536 * 65536;, is rejected at the constant. const auto NAME = e; takes
its type from e, as auto x = e; does: const auto MIB = KIB * KIB; is a u64 when KIB is, and
a bare literal is an i32 (or an f64). When e alone does not settle a type — None, say —
write the type.
A constant can also be declared inside a function, as a statement: const u8 LIMIT = 200;. It is
the same kind of constant, but its name is scoped like a local: it can be used from its
declaration to the end of its block, and an inner block can declare another constant or a variable
of the same name, which hides it there (in its own block, a second declaration of the name is
diag.duplicate-local, above). A local variable, even one set from a literal, is
not a constant — any later statement could change it — so static_assert cannot use it; name the
value with const when you want the check made before the program runs. A local constant's
initializer can use other constants, but not a local variable or the function's type
parameters.
import std;
fn checksum(slice<u8, shared> data) : u32
{
const u32 PRIME = 16777619; // FNV-1a: the 32-bit prime and offset basis
const u32 SEED = 2166136261;
static_assert(PRIME % 2 == 1);
u32 h = SEED;
foreach (b in data)
{
h = wrapping_mul(h ^ widen<u32>(*b), PRIME);
}
h
}
fn main()
{
u8 b = 200;
auto d = b + 1; // a variable: checked when the program runs
assert(d == 201);
const u8 B = 200;
const auto D = B + 1; // constants: checked before it runs (auto: D is a u8)
static_assert(D == 201, "D is %v", D);
array<u8, 3> abc = [97, 98, 99];
assert(checksum(&abc) == 440920331);
}const means known when the program is compiled
A const can never change: assigning to it, or borrowing it with &mut, is rejected when
the program is compiled. A constant is not a variable at all, but stands for its value,
so assigning to it is like assigning to a literal. Copying its value out is fine: i32 y = LIMIT;
gives a variable y, which can change, while LIMIT stays as it is.
import std;
const i32 LIMIT = 10;
fn main()
{
i32 y = LIMIT; // a copy of the value: y is an ordinary variable
y += 1;
LIMIT = 11; // ✗ diag.type-mismatch: a constant cannot be assigned
}What makes it a constant is when its value is known: before the program runs, like
const in Rust, Go and C# or constexpr in C++. That differs from C, C++, Java or JavaScript, where
const (or final) often marks a variable that is set once, at run time, and never reassigned.
const usize N = arg_count(); is diag.const-not-constant, because the value is only known once
the program runs.
CobaltC has no read-only local variables either: every local can be assigned. It does not need
them for safety, because every change to a variable shows where it happens. Only two things can
change a local: an assignment to its name in its own function, or an exclusive reference to it,
&mut x, which must be written out where it is made. A function given &x or a copy of x cannot
change it; while a shared reference to it is in use, nothing can (diag.aliasing-conflict, §8); and
threads share changing state only through a mutex. So to see whether x can change, look in its
function for x = and &mut x. To lend a value without letting it change, lend it with &.
import std;
fn peek(ref<i32, shared> r) : i32
{
*r // may read; writing *r is diag.write-through-shared
}
fn bump(ref<i32, exclusive> r)
{
*r += 1;
}
fn main()
{
i32 limit = 10; // a variable: it can be assigned, as every local can
assert(peek(&limit) == 10); // &limit: the callee can only read it
bump(&mut limit); // the one way another function changes it, visible here
assert(limit == 11);
ref<i32, shared> view = &limit;
assert(*view == 11); // while view is in use, nothing may write limit
limit = 12; // ✓ view's last use is above, so it no longer holds limit
assert(limit == 12);
}Definite assignment
import std;
fn main()
{
i32 x; // uninitialised
bool c = true;
if (c)
{
x = 1;
}
else
{
x = 2;
}
assert(x == 1); // ✓ assigned on both paths
}fn main()
{
i32 x;
bool c = false;
if (c)
{
x = 1;
}
i32 y = x + 1; // ✗ diag.use-of-uninitialized: no write on the else path
}The analysis is purely about the function's own control flow: it does not know that c
happens to be true. If it cannot prove a write on some path, the program is rejected (this is one
of the few checks where "unknown" means rejected rather than "check at run time").
The rule is about reads. A variable may reach the end of its scope without ever being written, on a path that returns early or when a fault ends the function first; it then ends with nothing: there is no value, so no destructor runs and nothing is released (D-0327).
Aggregates are initialised whole
You cannot declare a struct uninitialised and then fill its fields one by one. A struct literal supplies every field at once; after that, individual fields can be assigned freely.
import std;
struct Pair
{
i32 a;
i32 b;
}
fn main()
{
Pair p = Pair { .a = 1, .b = 2 }; // every field, exactly once, in any order
p.a = 10; // ✓ a field write on an initialised object
assert(p.a == 10);
assert(p.b == 2);
}Destructuring a struct
import std;
struct Entry
{
String item;
i64 change;
}
fn main()
{
Entry e = Entry { .item = "pens", .change = -3 };
Entry { item, change } = e; // binds `item` and `change`; e is consumed
assert(StringView::len(&item) == 4 && change == -3);
}This is the only pattern form outside match and the pattern conditions of if and while (§14). It names fields of the struct,
each once, in any order, and consumes the struct: a resource field moves out to its new binding, a
plain one is copied. It is how a struct gives up a resource it holds (the library's
String::into_bytes uses it to hand back the Vec<u8>), since a resource field cannot otherwise
be moved out of a struct that lives on. field : name binds a field to another name, so two values
of one type can be taken apart side by side, and a final .. stands for the fields not named:
they are not bound, and those holding resources are destroyed when the block ends. Naming a field
twice, or leaving one out without .., is a type error, and a struct with its own destructor
cannot be destructured, since the destructor would then run on a struct whose fields had left it
(diag.move-out-of-field).
import std;
struct Entry
{
String item;
i64 change;
String note;
}
fn main()
{
Entry a = Entry { .item = "pens", .change = -3, .note = String::new() };
Entry b = Entry { .item = "ink", .change = 5, .note = String::new() };
Entry { item : first, change : da, .. } = a; // renamed; `note` is left and ends with the block
Entry { item : second, change : db, .. } = b;
assert(StringView::len(&first) + StringView::len(&second) == 7 && da + db == 2);
}- Prefer
T x = e;orauto x = e;. Declare uninitialised only when the value genuinely comes from a branch, and then assign in every branch. - Build structs with a literal that names every field. Assign fields afterwards if needed.
autoneeds an initialiser it can learn a type from;auto v = Vec::new();is rejected becauseTis unknown (§12).
§12The type system
spec/12-type-system.mdNominal types with two coercions (text and sequences fit the type declared for them; nothing else converts), monomorphic generics (one copy per use with concrete types) with five built-in bounds, and local inference that only flows downward.
CobaltC's type system is deliberately plain: every type is exactly what it is declared to be, nothing converts to anything else, and generics are templates instantiated with concrete types. What it gives you in return is that the type of every expression is decidable from the text, and that a function signature is a complete statement of what the function may do with its arguments.
The built-in types
| Type | Values | Resource? |
|---|---|---|
integers, f32, f64, bool | numbers and truth values (§06) | no |
str | text: a valid UTF-8 byte sequence, written "…"; a whole value like an integer, not a reference and not owned (§21) | no |
void (type) / () (value) | the unit type; the type of assignments, of if without else, of loops and of functions with no return type. Written void in type position and () as a value. | no |
ref<T, shared>, ref<T, exclusive> | references (§09) | no |
rawptr<T> | raw addresses (§20) | no |
array<T, N> | N values of T in a row, N a constant expression (§16) | if T is |
slice<T, shared>, slice<T, exclusive> | a borrowed run of elements of an array or Vec (§16) | no |
fn(T1, T2) : R | function values | no |
handle<T>, mutex<T>, guard<T> | threads and locks (§19) | yes |
struct, enum | user-declared aggregates (§16) | if marked resource or any part is |
bitstruct | named runs of bits packed into one unsigned integer, u8 to u128 (§16) | no |
never | the type of return, break and continue: an expression that never yields a value, accepted wherever any type is expected; written only as a function's result, fn die(…) : never (D-0340) | n/a |
Nominal, exact, two coercions
Two types are the same only if they have the same name and the same type arguments.
ref<i32, shared> and ref<i32, exclusive> are different types. There is no subtyping, and no
implicit conversion between types — not between integer widths, not from T to ref<T, m>, not
from Option<T> to T — with two exceptions, which the rules call coercions. Both are about a
value fitting the type declared for its position: text (a literal, a str value
or &s of a String is the String or the StringView declared, §21) and
sequences (&v of a Vec or an array is the slice declared, and an array literal
of literals is a slice of static data, §16). Each coercion is exactly the expression you could have
written yourself, and the same positions still reject an i32 where an i64 is declared, or any
other typed value. A literal is not a third exception but a different thing: it has no type of its
own until its position gives it one, so u64 x = 5; types the literal rather than converting a
value.
fn takes_i64(i64 x) : i64
{
x
}
fn main()
{
i32 y = 5;
takes_i64(y); // ✗ diag.type-mismatch: i32 is not i64; write takes_i64(widen<i64>(y))
}A bare integer literal is the one flexible thing: takes_i64(5) is fine, because the
literal takes its type from the parameter (§06).
Equality
== and != are defined for numbers, bool, (), str (bytewise), references (identity), raw pointers
(address), and for structs, arrays and enums whose parts are all comparable (element by element;
enums must have the same variant and equal payloads). They are not defined for function values or
for anything that is a resource, with one exception: two Strings compare by their text.
< <= > >= order numbers, bool (false before true), and text: two strs, two
Strings or two StringViews, by their bytes, a prefix first (for UTF-8 that is code point
order). A String operand is not copied or moved: it is borrowed for the comparison, as &s would
be, so it stays usable afterwards.
import std;
fn main()
{
String a = "app";
String b = "apple";
assert(a != b && a < b); // text order: a prefix first
assert("b" > "abc");
assert(false < true);
String c = a; // a was only borrowed by the comparisons; it can still move
assert(c == "app");
}Generics
Functions, structs and enums can take type parameters. Generics are monomorphic:
each use with a different set of concrete types is a separate copy of the declaration, compiled
as if you had written it out with those types: identity(5) and
identity(2.5) below call two functions, one for i32 and one for f64. So there is no run-time type
information, no boxing and no indirect call at call sites; the cost is one copy per combination
of types used. Inside a generic body a value of a type parameter T can be stored, passed, returned,
referenced and moved. To do more with it — compare it, add it — give T a bound (below).
import std;
struct Box<T>
{
T value;
}
enum Maybe<T>
{
Just(T),
Nothing
}
fn identity<T>(T x) : T
{
x // all a bare T can do: be moved around
}
fn boxed<T>(T x) : Box<T>
{
Box { .value = x } // the field type is T, so this is fine
}
fn main()
{
assert(identity(5) == 5); // T := i32, from the argument
assert(identity<i64>(5) == 5); // T given explicitly: name<Type>(...)
Box<i32> b = Box { .value = 7 }; // Box's T from the declared type
assert(b.value == 7);
Box<Vec<u8>> c = boxed(Vec::new()); // both T's from the declared type of c
assert(Vec::len(&c.value) == 0);
}Bounds
A function's type parameter may carry one of six bounds, written after a colon:
fn max<T: ordered>(T a, T b) : T. Each of the first four names a fixed set of types and the
operators every one of them has, and each includes the ones before it; clone says a value of T
can be copied (below); plain that its bytes mean the same anywhere (§20):
| Bound | Satisfied by | Allows on a T |
|---|---|---|
eq | integers, floats, bool, str, String; and every key type: a struct or enum whose fields (payloads) are all integers, bool, str, String or such types (D-0110, D-0271) | == != |
ordered | the same | also < <= > >= |
number | integers, floats | also + - * / %, unary -, += and the like; integer literals |
integer | integers | also & | ^ ~, << >> |
clone | everything above; String, Rc<T>, Box<T: clone>, Vec<T: clone>, the hash tables; a type with its own T::clone; a struct or enum whose fields are all clone (D-0116) | clone(&x): an independent copy |
plain | numbers, bool, raw pointers, simd, and arrays, structs or enums of those: bytes that mean the same anywhere (no resource, reference, handle, mutex, guard, function value or str) | none of its own; what Vec::from_raw and copy_to_raw move across raw memory (§20) |
clone — by its
fields, or by a fn T::clone(ref<T, shared> self) : T you declare, recognised by its name as
T::drop is — and eq and ordered when it is a key type (D-0271): its == is field-by-field
equality and its < the order Vec::sort gives it, field by field in declaration order, an enum by
variant order and then payload. So a < b holds exactly when Vec::sort puts a before b, and
a == b exactly when a hash table treats them as one key. It never satisfies number or
integer, and a type with a float field satisfies nothing but clone and plain: to combine values
of your own types in generic code, or order a struct otherwise than by its fields, pass the operation
in as a function value, as Vec::sort_by takes less.import std;
fn largest<T: ordered>(slice<T, shared> xs) : T
{
T best = xs[0];
foreach (x in xs)
{
if (*x > best) { best = *x; }
}
best
}
fn total<T: number>(slice<T, shared> xs) : T
{
T sum = 0; // a literal takes T's type, a float one too
foreach (x in xs)
{
sum += *x;
}
sum
}
fn main()
{
array<i32, 3> a = [4, -2, 9];
array<f64, 2> f = [1.5, 2.25];
assert(largest(&a) == 9);
assert(total(&a) == 11);
assert(total(&f) == 3.75);
}The body is checked once against the bound: a + b in a function whose T is only
ordered is diag.unbounded-type-parameter. Each call is checked for a type that satisfies it:
largest of a struct with a float field is diag.type-mismatch, and the message names the field.
Each use is also checked at its concrete type, so -x at T = u32 is still rejected there. Structs
and enums take no bounds; put them on the functions that use the operations.
import std;
struct Point // a key type: two integers
{
i32 x;
i32 y;
}
fn largest<T: ordered>(slice<T, shared> xs) : T
{
T best = xs[0];
foreach (x in xs)
{
if (*x > best) { best = *x; }
}
best
}
fn main()
{
Point p = Point { .x = 1, .y = 2 };
Point q = Point { .x = 1, .y = 3 };
assert(p < q && p == Point { .x = 1, .y = 2 }); // field by field: x, then y
Vec<Point> v = Vec::new();
Vec::push(&mut v, q);
Vec::push(&mut v, p);
assert(Vec::contains(&v, &p)); // Vec::contains wants T: eq
assert(largest(&v) == q); // the generic above, at T = Point
Vec::sort(&mut v); // the same order as <
assert(v[0] == p && v[0] < v[1]);
}clone(&x) copies a value of any clone type: a plain one by reading it, String and the
containers by their own clone, and a struct or enum of clone fields by a copy the compiler
derives, field by field. A resource type — one with a destructor — declares its own T::clone or
has none, because only it knows how to copy what it manages. Generic code says what it needs with
the bound:
import std;
struct Person
{
String name; // Person is clone: every field is
u32 age;
}
enum Shape
{
Dot,
Labelled(String), // Shape is clone too
}
resource struct Ticket
{
u32 id;
}
fn Ticket::drop(ref<Ticket, exclusive> self)
{
}
fn Ticket::clone(ref<Ticket, shared> self) : Ticket // a resource says how it is copied
{
Ticket { .id = self.id + 1000 }
}
fn pair_up<T: clone>(ref<T, shared> x) : Vec<T> // needs T: clone to call clone(x)
{
Vec<T> v = Vec::new();
Vec::push(&mut v, clone(x));
Vec::push(&mut v, clone(x));
v
}
fn main()
{
Person a = Person { .name = "Ada", .age = 36 };
Person b = clone(&a); // derived: name copied, age copied
String::push_ascii(&mut b.name, b'!');
assert(a.name == "Ada" && b.name == "Ada!");
Shape s = Labelled("x");
Shape s2 = clone(&s);
Vec<Person> people = pair_up(&a);
Vec<String> names = Vec::from_fn(2, [](usize i) : String { sprintf("n%d", i) });
Vec<String> copy = Vec::clone(&names); // Vec::clone needs T: clone; String is
Ticket t = Ticket { .id = 1 };
Vec<Ticket> tickets = Vec::filled(2, clone(&t)); // Ticket::clone, three times
assert(Vec::len(&people) == 2 && Vec::len(©) == 2 && tickets[1].id == 2001);
}A derived clone copies a list or a tree at any depth. A type that links to one more
of itself through Box<T> or Option<Box<T>> (a list's Option<Box<Node>>, a Branch(Box<Tree>))
is a chain, and its derived clone goes on past a thousand links with a loop, as destroying the
chain does, so ten million links copy as well as ten. A tree, a struct with two such links
(left and right) or an enum variant with fields that holds them (Add { Box<Expr> a; Box<Expr> b; }),
goes on past a thousand levels with a loop over a stack of its own. The fields are still copied in
the order the rule gives. A type that links to itself only through another type
(Node(Box<Pair>), Pair holding the links) still takes a call for each level: its clone and
Pair's are two functions, each made from its own type's declaration.
Destroying a list or a tree takes no call for each level either, in every form, where nothing
observable follows a link's destruction: the link is the last field destroyed (fields go last
declared first), or the fields destroyed after it only free memory, as a String does. A list whose
nodes hold a String beside the link, a tree whose nodes hold one beside two links, and an enum
list are destroyed at two million levels as at ten. A field declared before the link that runs
another destructor (a type with a drop of its own, a Vec<String>) is destroyed after the whole rest of
the list, so that list's destruction takes a call for each node; declare such a field after the link
when the list may be deep.
Inference is local and downward. A type parameter is found from, in order: an
explicit type argument (identity<i64>(5)), the type of an argument in the same call, or the
expected type where the call appears (a declared variable type, a parameter type, a field
type). An unsuffixed literal argument comes last: it takes the type the other arguments or the
expected type give its parameter, so with i64 x, pick(true, 0, x) makes T an i64 and the 0
with it; only when nothing else fixes T does a literal's own default (i32, f64) decide.
Nothing is ever inferred from how a value is used later, so a call that fixes nothing is
rejected:
import std;
fn main()
{
auto v = Vec::new(); // ✗ diag.cannot-infer-type-parameter: nothing says what T is
Vec::push(&mut v, 1); // (a later use does not count)
}The same holds when the call is an argument to another generic call. Mutex::new<T> is
one: with auto nothing reaches it, so nothing reaches the Vec::new() inside it either. Give the
outer binding its type and both are fixed.
import std;
fn main()
{
mutex<Vec<u8>> m = Mutex::new(Vec::new()); // T of Mutex::new, then T of Vec::new, from the declaration
mutex<i64> big = Mutex::new(5000000000); // and the literal is an i64 for the same reason
assert(Vec::len(&*lock(&m)) == 0);
}import std;
fn main()
{
auto m = Mutex::new(Vec::new()); // ✗ diag.cannot-infer-type-parameter: nothing fixes Vec's T
}import std;
struct Box<T>
{
T value;
}
fn identity<T>(T x) : T
{
x
}
fn pick<T>(bool first, T a, T b) : T
{
if (first) { a } else { b }
}
fn main()
{
Vec<i32> a = Vec::new(); // T from the declaration
Box<Vec<u8>> c = Box { .value = Vec::new() }; // both T's from the declared type
Vec::push(&mut c.value, 200); // the literal becomes u8 from the field type
assert(Vec::len(&c.value) == 1);
assert(Vec::len(&a) == 0);
i64 w = identity<i64>(3); // explicit: name<Type>(...)
assert(w == 3);
i64 big = 5000000000;
Vec<i64> both = Vec::new();
Vec::push(&mut both, pick(true, 0, big)); // T from big; the 0 is an i64
assert(both[0] == 0);
}auto and the expected type
auto x = e; gives x the type of e. Since inference is downward only, auto works
whenever e has a type of its own: a literal (i32/f64 by default), an arithmetic expression, a
call whose type parameters are already fixed, a struct literal with a concrete type. Where e
needs help (Vec::new()), write the type on the left instead: auto m = Mutex::new(HashMap::new());
cannot know the map's types, but mutex<HashMap<String, i64>> m = Mutex::new(HashMap::new()); can.
The branches of an if or match share one type, and a branch that is only a literal takes it from
the others: in auto n = if (big) { count } else { 0 }; with count : i64, the 0 is an i64.
import std;
fn main()
{
i64 count = 5000000000;
auto n = if (count > 10) { count } else { 0 }; // 0 : i64, from the other branch
Option<i64> o = None;
auto m = match (o) { None : -1, Some(v) : v }; // -1 : i64, from the Some arm
assert(n + m == 4999999999);
mutex<HashMap<String, i64>> totals = Mutex::new(HashMap::new()); // the declaration fixes K and V
assert(HashMap::len(&*lock(&totals)) == 0);
}- Write the type you mean; the language will not adjust it for you. Convert integers with
widen/narrow, and take references explicitly. - Use
autofreely for values whose type is obvious from the right-hand side, and a written type for empty containers and generic constructors. - Keep generic code to plumbing (containers, wrappers, moving values around). Anything that computes on
Tneeds a concrete type. - A
voidfunction returns(); you may write: voidexplicitly or leave the return type off.
§13Expressions
spec/13-expression-semantics.mdPlaces versus values, strict left-to-right evaluation, and the operators.
CobaltC has a small expression language with a fixed evaluation order and a clear line
between places (things you can assign to or borrow) and values. Almost everything
is an expression, including blocks, if and match, which is what lets you write
i32 x = if (c) { 1 } else { 2 };.
Places and values
A place is a variable name, a field access e.f, an index e[i], or a
dereference *r. A place can be read (yielding its value), written (place = e), borrowed
(&place, &mut place), or projected further. Everything else, such as a literal, an arithmetic
result, a call result or a struct literal, is a value or a temporary. Reading a place that holds a
resource is not allowed (that would copy the resource, §07); such a place may only be moved,
borrowed, or destructured.
import std;
struct Pair
{
i32 a;
array<i32, 3> items;
}
fn main()
{
Pair p = Pair { .a = 1, .items = [10, 20, 30] };
p.a = 99; // a field is a place
p.items[1] = 200; // so is an element
{
auto r = &mut p.items[2];
*r = 300; // and so is *r
}
assert(p.a == 99);
assert(p.items[1] == 200);
assert(p.items[2] == 300);
}Evaluation order
Every expression is evaluated strictly left to right: the left operand before the right,
the callee before its arguments, arguments in written order, struct-literal fields in written order.
Assignment evaluates the target place first, then the value. && and || short-circuit: the right
operand runs only when needed.
import std;
fn bump(ref<i32, exclusive> counter) : i32
{
*counter += 1;
*counter
}
fn main()
{
i32 n = 0;
i32 left = bump(&mut n);
i32 right = bump(&mut n);
assert(left == 1); // the first call ran first
assert(right == 2);
bool touched = false;
if (true || bump(&mut n) == 0) // the right side is never evaluated
{
touched = true;
}
assert(touched);
assert(n == 2);
}Expressions that produce values
import std;
fn main()
{
bool c = true;
i32 x = if (c) // if is an expression; both arms must have one type
{
1
}
else
{
2
};
i32 y = // a block's value is its trailing expression
{
i32 t = x * 3;
t + 1
};
Option<i32> o = Some(x);
i32 z = match (o) // so is match
{
Some(v) : v * 10,
None : 0,
};
assert(x == 1);
assert(y == 4);
assert(z == 10);
i32 w = 0;
w = 5; // assignment is an expression of type void
assert(w == 5);
}if, while or match used as a statement needs no semicolon after its
closing brace. When one of them is the right-hand side of a declaration or assignment, the
statement as a whole still ends with ;, as in i32 x = if (c) { 1 } else { 2 };.Operator precedence
From tightest to loosest binding. Comparison is non-associative: a < b < c is a
syntax error, and a < b == c needs parentheses.
| Level | Operators | Notes |
|---|---|---|
| postfix | e.f e[i] e(args) e? | field, index, call, propagate |
| unary | -e !e ~e &e &mut e *e | negate, boolean not, bitwise not, borrow, dereference |
| multiplicative | * / % | left-associative |
| additive | + - | left-associative; p + n on a rawptr is pointer offset (§20) |
| shift | << >> | the right operand is a u32 |
| bitwise and | & | |
| bitwise xor | ^ | |
| bitwise or | | | |
| comparison | == != < <= > >= | non-associative |
| logical and | && | short-circuit |
| logical or | || | short-circuit |
| assignment | = += -= *= /= %= &= |= ^= <<= >>= | right-associative; the left side must be a place |
x op= e is x = x op e with x evaluated once: the same types, the same overflow
check (x += 1 can overflow), the same write rules. Evaluating the place once matters only when it
contains a call, as in *Vec::index_exclusive(&mut v, i) += 1, which calls index_exclusive once.
There is no ++ or --; write += 1.
hi << 8 | lo is
(hi << 8) | lo. Unlike C, the bitwise operators bind tighter than comparisons, so
x & 1 == 0 parses as (x & 1) == 0. When in doubt, add parentheses.- Use
if,matchand blocks as values instead of declaring a variable and assigning in each branch. - Side effects in one operand are visible to the next: order is defined, so you may rely on it, but readers will thank you for not making them.
- Parenthesise mixed comparisons and bitwise expressions.
§14Control flow and scopes
spec/14-control-flow.mdBlocks, if, while, for, foreach, break and continue; scope exit as the moment of destruction; and the fixed line between compile-time and run-time checks.
Control flow is C's if, while and for, without switch and goto, plus
expression-valued if and match and a foreach over collections. What is new is how carefully the language ties scope to destruction, and
the precise line between what the compiler proves and what the run time checks.
Blocks and scopes
A block { … } opens a scope. Variables declared in it die when it ends, in reverse
order; resources are destroyed at that point (§07); references held by those variables end too. A
block is an expression: its value is its trailing expression, or () if there is none. Every
statement is a scope of its own for temporaries: a value created during a statement and not stored
anywhere is destroyed at the semicolon.
if and else
if (cond) { … } else { … } with mandatory parentheses and mandatory braces. else if
chains as expected. An if without else has type void; an if used as a value needs both arms,
of the same type.
The condition may also be a pattern test, if (Some(x) = e) { … } else { … }: it means
match (e) { Some(x) : { … }, _ : { … } }, so x exists in the first block only, e is consumed
exactly as that match would consume it, and the whole if can be a value. Any match pattern
works — nested (Ok(Some(l))), a literal (if (0 = n)), a qualified variant — as long as it can
fail: a bare name on the left of = is the assignment it always is, which is not a bool and is
rejected, so if (x = e) never silently tests anything. A match stays the form when both cases
do work, and the only form that checks every case is handled.
import std;
fn main()
{
HashMap<String, i32> ages = HashMap::new();
HashMap::insert(&mut ages, "Ada", 36);
if (Some(a) = HashMap::get(&ages, "Ada"))
{
assert(*a == 36); // a: ref<i32, shared>, in scope here only
}
Option<i32> o = Some(4);
i32 doubled = if (Some(x) = o) { x * 2 } else { 0 };
assert(doubled == 8);
Result<Option<i32>, str> r = Ok(Some(7));
if (Ok(Some(n)) = r) { assert(n == 7); } else { assert(false); }
if (Err(_) = r) { assert(false); }
}while, for, break, continue
while (cond) { … } loops while cond holds; for (init; cond; step) { … } is C's
counted loop: init runs once (a declaration there belongs to the loop), cond is tested before
each iteration, and step runs after each one. Any of the three may be left out; a missing cond
is true, so for (;;) loops until a break. The body is a fresh scope each iteration, so
anything declared inside it is destroyed before the next test. break exits the innermost loop;
continue goes to its next iteration, running a for's step first. Both are typed never and
must appear inside a loop. A body is always a block, so C's trap for (…); (an empty loop, then a
block that runs once) is a syntax error here, and the message says to remove the ;.
A while condition may be a pattern test too: while (Some(x) = e) { … } is
while (true) { match (e) { Some(x) : { … }, _ : break } } — e is evaluated again each time
round, the body runs with x bound while the pattern matches, and the first value that does not
match ends the loop. That last point matters for a Result: while (Ok(Some(line)) = read_line())
stops at the end of input and on a read error alike, which is the loop's written decision; a loop
that must tell them apart keeps the match.
import std;
fn main()
{
Vec<String> stack = Vec::from_fn(3, [](usize i) : String { sprintf("job %d", i) });
usize done = 0;
while (Some(job) = Vec::pop(&mut stack)) // each job moved out, destroyed at the body's end
{
if (StringView::ends_with(&job, "1")) { continue; }
done += 1;
}
assert(done == 2 && Vec::len(&stack) == 0);
u32 n = 10;
while (Some(m) = checked_sub(n, 3)) // stops when the subtraction would go below zero
{
n = m;
}
assert(n == 1);
}import std;
fn main()
{
i32 sum = 0;
i32 i = 0;
while (i < 10)
{
i += 1;
if (i == 3)
{
continue; // skip 3
}
if (i == 7)
{
break; // stop before adding 7
}
sum += i;
}
assert(sum == 1 + 2 + 4 + 5 + 6);
Vec<i32> v = Vec::new();
Vec::push(&mut v, 4);
Vec::push(&mut v, 9);
i32 total = 0;
for (usize k = 0; k < Vec::len(&v); k += 1) // an index loop; foreach (below) is shorter
{
total += v[k];
}
assert(total == 13);
u32 odd = 0;
for (u32 j = 0; j < 10; j += 1)
{
if (j % 2 == 0)
{
continue; // still runs j += 1
}
odd += j;
}
assert(odd == 25);
}fn main()
{
break; // ✗ diag.break-outside-loop
}Loops that only end by returning. A while (true) that no break leaves can
end only by return, a fault or exit, so nothing after it ever runs: its type is never, like
return's (D-0175). A function may therefore end with such a loop and needs no value after it. A
break inside a nested loop leaves only that loop and does not count; a break that leaves the
while (true) itself makes it an ordinary loop again, after which the function must still give its
value. Only the literal true has this meaning: the compiler does not look into a condition that
merely happens to stay true. There is no separate loop keyword; while (true) is the way to say
"forever".
import std;
// The first line that starts with `#`, read until one does; no value is
// needed after the loop, because nothing after it can run.
fn first_comment(ref<Vec<String>, shared> lines) : usize
{
usize i = 0;
while (true)
{
if (StringView::starts_with(&lines[i], "#"))
{
return i;
}
i += 1;
}
}
fn main()
{
Vec<String> lines = Vec::new();
Vec::push(&mut lines, "x = 1");
Vec::push(&mut lines, "# note");
printf("line %v\n", first_comment(&lines));
}line 1
foreach
foreach (x in c) { … } visits every element of a Vec, an array, a slice, a HashSet or a
HashMap, in order: by index for a Vec or an array, in insertion order for a set or a map. How
the loop holds the collection is written at the loop, the same three ways a function takes a
value:
| Written | Each element is | Afterwards |
|---|---|---|
foreach (x in c) | the element itself, moved out of c | c is gone: the loop consumed it |
foreach (x in &c) | a shared reference, ref<T, shared>: read it | c is unchanged and usable |
foreach (x in &mut c) | an exclusive reference: *x = … changes the element | c is usable, with its changes |
Use &c most of the time. A second name gives the position: foreach (i, x in &v) has
i : usize. A HashMap is always looped over with two names, the key and the value:
foreach (k, v in &m), or three to have the position too, foreach (i, k, v in &m). printf prints what a reference refers to, so printf("%d", x) works
with x a ref<i32, shared>; elsewhere write *x for the number.
import std;
fn shout(String s) // takes ownership
{
printf("%s!\n", &s);
}
fn main()
{
Vec<String> names = Vec::new();
Vec::push(&mut names, "ada");
Vec::push(&mut names, "lin");
foreach (i, name in &names) // read: names is still usable afterwards
{
printf("%d: %s\n", i, name);
}
Vec<i32> numbers = Vec::new();
Vec::push(&mut numbers, 3);
Vec::push(&mut numbers, 5);
foreach (n in &mut numbers) // change in place
{
*n *= 2;
}
foreach (n in &numbers)
{
printf("%d ", n); // printf reads through the reference
}
printf("\n");
HashMap<str, u32> stock = HashMap::new();
HashMap::insert(&mut stock, "pens", 12);
HashMap::insert(&mut stock, "ink", 3);
foreach (item, count in &stock)
{
printf("%-5s %2d\n", item, count);
}
foreach (name in names) // consume: each String moves into shout
{
shout(name);
}
// names is gone here; using it would be diag.stale-binding
}0: ada 1: lin 6 10 pens 12 ink 3 ada! lin!
The loop's borrow of the collection lasts the whole loop, so a body that tries to change
the collection itself (push to it, clear it) is rejected before the program runs, the same
aliasing rule as anywhere else. There is no iterator invalidation to debug. A consuming loop
left early, by break, return or a fault, destroys the elements it had not reached, exactly
once.
import std;
fn main()
{
Vec<i32> v = Vec::new();
Vec::push(&mut v, 1);
foreach (x in &v)
{
Vec::push(&mut v, *x); // ✗ diag.aliasing-conflict (static): v is borrowed by the loop
}
}An array of plain values, such as array<i32, 5>, is copied by the by-value form:
foreach (i, e in arr) walks a copy, so arr is neither borrowed nor used up, a write to
arr[j] in the body is allowed (and not seen by e), and arr is still there afterwards. To change
the elements themselves, loop over &mut arr and write through the reference: *e = …. While
that loop runs, arr is borrowed by it, so reach the elements through e, not through arr[j].
import std;
fn main()
{
array<i32, 5> arr = [0, 0, 0, 0, 0];
foreach (i, e in &mut arr)
{
*e = narrow<i32>(i) * 10; // write through the element's reference
}
arr[4] += 1; // direct indexing works too, outside the loop
foreach (i, e in &arr)
{
printf("[%v] = %v\n", i, *e);
}
}[0] = 0 [1] = 10 [2] = 20 [3] = 30 [4] = 41
Counting with a range
foreach (x in lo..hi) counts from lo up to, not including, hi, the same way
&a[lo..hi] takes elements lo up to hi. So 0..n runs exactly n times, and 1..10 stops at
9. A second name gives the position, counted from 0: foreach (i, x in lo..hi). Both bounds are
evaluated once, lo first. If hi is not above lo, the body never runs.
foreach (x in lo..=hi) includes hi, and so reaches a type's largest value without an overflow:
foreach (b in 0..=255: u8) visits all 256 bytes, and when hi is below lo it runs no turn.
x has the bounds' integer type. A plain number takes the other bound's type, so with
u8 top, 0..top counts in u8. Two plain numbers are usize, so the counter can index an
array or a Vec directly; for a negative range, give one bound a type: -3..0: i32. Bounds of two different types are
rejected rather than converted. Neither form overflows at its type's largest value: lo..hi stops
before hi, and lo..=hi stops at it.
import std;
fn main()
{
foreach (v in 1..10)
{
printf("%v ", v);
}
printf("\n");
auto names = ["ada", "lin", "kay"];
foreach (i in 0..3) // i : usize, so it can index
{
printf("%v: %v\n", i, names[i]);
}
u8 top = 255;
foreach (i, b in 253..top) // b : u8; i is the position
{
printf("step %v is %v\n", i, b);
}
}1 2 3 4 5 6 7 8 9 0: ada 1: lin 2: kay step 0 is 253 step 1 is 254
Counting up to and including the end
lo..=hi is the range that includes hi. It is the one to use when the last value is the
type's largest, which lo..hi cannot reach (0..256 is not a u8), and it reads as what it does:
1..=10 is one to ten (spec/14 [Foreach-Range-Inclusive]).
import std;
fn main()
{
// 1 + 2 + ... + 10: the last number is counted.
u32 sum = 0;
foreach (k in 1..=10: u32)
{
sum += k;
}
printf("sum %v\n", sum);
// Every i8, the largest included; the counter never overflows.
i32 n = 0;
foreach (x in min_value<i8>()..=max_value<i8>())
{
n += 1;
}
printf("%v values of i8\n", n);
// A top below the bottom runs no turn.
foreach (x in 3..=1: i32)
{
printf("never %v\n", x);
}
}sum 55 256 values of i8
A range to count over is written only in a foreach (a slice's lo..hi, §16, is the same
notation for elements). It is not a value you can store, and it has no step; lo..=hi
is its inclusive form, which a slice does not have. To count down or in steps, use a for loop.
Early exit and unwinding
return, break, continue, and a run-time fault all leave scopes the same way: every
statement scope and block between here and the target is exited in order, destroying what each one
owns. A return e first moves e out so it survives the unwinding. You never have to write
cleanup code on an early exit.
What is checked when
Many rules in this guide say a program is "rejected" in one example and "faults at run
time" in another. The boundary is fixed by the language, not left to the compiler's cleverness, so
that every implementation accepts and rejects the same programs. A compiler may prove more than this
checker does and leave out the run-time checks it has proved unnecessary (that is what cobc does; see
the performance chapter), but it may not accept a program the language rejects or reject one it accepts:
the checks made before the run are the language's, and cobc --check makes exactly those. Within one
function body, the
checker tracks a few facts about each variable: whether it has been moved from, whether it has been
initialised, which references were visibly borrowed from it, and whether a reference to it has been
handed somewhere the checker cannot follow (a call, a field, a thread). At each checked operation
the outcome is one of three:
| Outcome | When | Effect |
|---|---|---|
| proven | the tracked facts guarantee the condition | no run-time check |
| refuted | the tracked facts guarantee it fails | the program is rejected (a static diagnostic) |
| unknown | the facts do not decide (a value computed at run time, a loop merged two states, a reference kept inside a data structure) | the run-time check runs, and faults if it fails (a dynamic diagnostic) |
For values, the analysis looks only at literals. So 2147483647 + 1 is refuted statically
and add(2147483647, 1) is checked when add runs. For references a function holds in its own
variables and parameters, the checker also knows what every function does through each reference
parameter: which fields it may read and which it may write. So a call that hands a function &mut x
and &x, where the function writes through the first, is refuted at the call, and so is a call that
writes what a live reference of the caller still borrows. The diagnostic names the function and what
it does through which argument. Two references chosen by computed indexes into one array are told apart
only by their values, so the call checks them when it is made, from what the function may do with them,
whichever way its body then goes; references kept inside data structures are checked when used.
Three exceptions are stricter: definite assignment (§11), a use of a variable that may have been moved
(§7), and reference escape (§10) reject on "unknown" rather than deferring.
- Let scopes do your cleanup. Open a block to bound a borrow or a lock; close it to release.
- A
whilebody is re-entered fresh each iteration; declare per-iteration variables inside it. - Prefer trailing expressions to
returnat the end of a function; usereturnfor early exits. - If a diagnostic says static, the checker saw the problem in the text; if dynamic, it saw it when the values arrived. Both are the same rule.
§15Functions and closures
spec/15-function-semantics.mdSignatures that state the whole contract, associated functions, function values, and closures with checked capture lists.
Functions in CobaltC carry their whole contract in the signature. A parameter's type says
whether the function takes ownership, may only look, or may modify; a reference result says where
it may come from, the one reference parameter or those a from clause names (§10). Closures are ordinary structs
that capture what they use, and the capture list is checked, not trusted.
Declaring and calling
import std;
// Parameters are type-first; the return type follows a colon.
fn area(i32 w, i32 h) : i32
{
w * h // the trailing expression is the result
}
// No return type means void; `return;` leaves early.
fn clamp_in_place(ref<i32, exclusive> x, i32 hi)
{
if (*x <= hi)
{
return;
}
*x = hi;
}
// An associated function: a plain function whose name is qualified by a type.
struct Rect
{
i32 w;
i32 h;
}
fn Rect::square(i32 side) : Rect
{
Rect { .w = side, .h = side }
}
fn Rect::area(ref<Rect, shared> r) : i32
{
area(r.w, r.h)
}
fn fact(i32 n) : i32
{
if (n <= 1) // recursion needs nothing special
{
1
}
else
{
n * fact(n - 1)
}
}
fn main()
{
i32 v = 50;
clamp_in_place(&mut v, 10);
assert(v == 10);
auto sq = Rect::square(4);
assert(Rect::area(&sq) == 16); // called by qualified name; there is no method syntax
assert(fact(5) == 120);
}Recursion needs nothing special, and its depth is limited only by the stack. Every
implementation allows at least 10 000 nested calls, and cobc allows far more: it runs a
program and each of its threads on a large stack. A call beyond the limit is not a crash but a
fault at the call, diag.stack-exhausted, so a recursion that runs away ends with a diagnostic
like any other failure; so does a call whose own locals (a large array) are more than the stack
has left.
A parameter list and an argument list may end with a comma, as array and struct literals
may: handy when a long call is split one argument per line. A comma is never the whole list:
f(,) is a syntax error.
import std;
fn span(
i32 from,
i32 to,
) : i32
{
to - from
}
fn main()
{
assert(span(
3,
10,
) == 7);
}What a parameter type promises
| Parameter type | The caller writes | The callee may | After the call |
|---|---|---|---|
plain T (numbers, plain structs) | f(x) | use its own copy | the caller's x is unchanged |
resource T (Vec<i32>, handle<T>, …) | f(v) | own it: mutate, move on, or let it be destroyed at its scope end | the caller's v is stale |
ref<T, shared> | f(&x) | read through it | the borrow is released; x is unchanged |
ref<T, exclusive> | f(&mut x) | read and write through it, but not destroy or move x | the borrow is released; x may have changed |
Function values
A function type is written fn(T1, T2) : R (or fn(T1) for a void result). A
parameter of that type accepts a function with that signature, or a closure with the same
parameters and result. Function values cannot be compared.
A closure's type is fn(parameters) : result, the result being what its body gives. Where
a fn type is expected, as when a closure is declared fn(u32) : u32 f = … or passed to such a
parameter, the body is checked against that result, and its literals take that type. A closure
declared with auto takes its body's own type: [](u32 x) { 1 } gives an i32, as auto y = 1
does. A closure can be stored like any value: in a variable, a field, a Vec<fn(…) : …> or a
Box, and called from there. A closure without move stored in a container declared outside the
block of a variable it captures (Vec::push(&mut fs, [i]() : usize { i * 10 }) in a loop over i)
is refused, diag.destroy-while-aliased: the container would keep a borrow of i past its block;
write move [i]. So is such a closure given a name first (auto c = [i]() …; Vec::push(&mut fs,
c);), or assigned to an element or a field of the container (fs[0] = [i]() …).
A function value owns the closure it holds and destroys it when it ends. Copying the value
(g = f, passing it by value) copies the closure with its captures, so each copy keeps its own
state. The one exception is a closure that owns a resource, such as a move closure that captured a
String: copying it would duplicate the resource, so it moves instead, and the value it
came from is left empty. Calling an empty function value is diag.stale-binding; the function type
does not say what its closure owns, so this is found when the program runs. Calling through a
reference, a field or an element ((*f)(x), (t.run)(), (fs[i])()) calls the value where it is
and moves nothing.
Closures
Functions do not nest: a fn declared inside another function is a syntax error, unless it
is a function of a type declared in the same block (fn T::name, §16). A function needed only
inside another is written there as a closure, which can also use the variables around it.
A closure is written [captures](params) { body }, in the style of a C++ lambda. The
bracket must list exactly the outer variables the body uses, no more and no fewer; it is
documentation that the compiler checks (diag.capture-list-mismatch). How each variable is captured
is decided by the body, not the list: a variable the body only reads is captured by shared
reference; one the body writes, borrows exclusively, or moves is captured by exclusive reference.
Prefix move to capture by value instead, moving resources into the closure. The result type is
taken from the body, or from the fn(…) : R the closure is passed as; write it after the
parameters, as for a function, when neither says enough: [](i64 a) : i64 { 0 }.
import std;
fn main()
{
auto zero = [](i64 a) : i64 { 0 }; // without `: i64` the 0 would be an i32
auto small = [](u8 a) : bool { a < 10 };
assert(zero(5000000000) == 0 && small(3));
}import std;
fn apply(fn(i32) : i32 f, i32 x) : i32
{
f(x)
}
fn main()
{
i32 k = 10;
auto add_k = [k](i32 x) // k is read only: captured as ref<i32, shared>
{
x + k
};
assert(add_k(5) == 15);
assert(apply(add_k, 4) == 14); // a closure where a fn(i32) : i32 is expected
Vec<i32> v = Vec::new();
Vec::push(&mut v, 7);
auto reader = move [v]() // v moves into the closure; the closure owns it now
{
v[0]
};
assert(reader() == 7);
assert(reader() == 7); // calling twice is fine: nothing is consumed
} // reader is destroyed here, and its Vec with itfn main()
{
i32 x = 1;
i32 unused = 2;
auto f = [x, unused]() // ✗ diag.capture-list-mismatch: unused is not used by the body
{
x
};
f();
}A closure that captures by reference holds those borrows for as long as the closure
object lives, so the captured variables are subject to the usual aliasing rules until it goes out
of scope: a closure that writes total blocks every other use of total while it exists. Put such
closures in a block, or use move. Calling a closure borrows it shared for the call: its writes go
through the captures, which are checked as any reference is, so a closure that writes a capture
cannot be called through a shared reference to it.
A move closure that changes a value it captured changes the closure itself, so a call
borrows it exclusively. Such a counter is called from its own binding; called while a shared
reference to it lives, the call is diag.aliasing-conflict (reported before the program runs
when that reference is certainly still in use), and called through a shared reference it is
diag.borrow-exceeds-source.
import std;
fn main()
{
i32 n = 0;
auto next = move [n]() : i32 // n is the closure's own copy
{
n = n + 1;
n
};
assert(next() == 1);
assert(next() == 2); // the copy keeps its value between calls
assert(n == 0); // the original was copied, not borrowed
}fn main()
{
i32 total = 0;
{
auto add = [total](i32 x) // the body writes total: captured as ref<i32, exclusive>
{
total += x;
};
add(5);
add(7);
} // add ends here and releases its borrow of total
i32 seen = total; // ✓ 12: no borrow remains
}Generic functions
fn name<T>(...) declares type parameters; see §12 for what a body may do with T and
how T is inferred at each call.
main
A program is a set of declarations with exactly one main at the top level, taking no
parameters: fn main(), or fn main() : u8. Execution is the evaluation of main(); the program's
observable behaviour is its termination outcome (success or a named fault) plus the sequence of
extern calls it makes.
A main that returns a u8 sets the program's exit status; fn main()
exits with 0. Returning from main runs every destructor still pending and waits for every
thread, as leaving any block does, so the status is reported only after all of that. A fault
still ends the program with its diagnostic instead. The arguments the program was started with
come from arg_count() and arg(i) (§21); argument 0 is the first one after the program, not the
program's name.
cobc --run greet.cb Adarunsimport std;
fn main() : u8
{
if (arg_count() != 1)
{
printf("usage: greet NAME\n");
return 2; // exit status 2
}
match (arg(0))
{
Ok(name) :
{
printf("hello, %v\n", &name);
0
},
Err(_) :
{
printf("the name is not UTF-8\n");
1
},
}
}hello, Ada
Run with no argument, the same program prints its usage line and exits with status 2.
A main with parameters, or returning anything other than u8, is rejected with
diag.no-main.
- Choose the parameter kind that says the least: a shared reference if the function only reads, an exclusive reference if it modifies, by value only if it needs to keep the thing.
- Return values rather than out-parameters; a struct or an enum is cheap to return.
- List every captured variable in the closure brackets and let the compiler tell you if you got it wrong.
- Use
moveclosures for anything that outlives the current block or runs on another thread.
§16Structs, arrays, enums and match
spec/16-aggregates.mdThe four aggregate kinds, how they nest, and exhaustive matching over enums with payloads.
CobaltC has four aggregate kinds: structs (named fields), bitstructs (named runs of bits
packed into one unsigned integer), arrays (a fixed number of elements) and enums (one of several
variants, each with an optional payload). They compose freely, and all but bitstructs generically. match is how you take an enum apart, and it must handle every variant.
Structs
import std;
struct Point
{
i32 x;
i32 y;
}
struct Segment
{
Point from; // structs nest by value
Point to;
}
fn main()
{
auto a = Point { .x = 1, .y = 2 }; // every field, once, in any order
Point b = Point { .y = 2, .x = 1 };
assert(a == b); // plain structs compare field by field
auto s = Segment { .from = a, .to = Point { .x = 4, .y = 6 } };
s.to.y = 7; // nested fields are places
assert(s.to.y == 7);
Point c = a; // plain structs copy
c.x = 100;
assert(a.x == 1);
}Field initialisers use C99's designated form .name = value. Fields are private to the
module that declares the struct unless marked export (§17). A struct with no fields is allowed.
Mark a struct resource if it manages something beyond its fields (§07).
bitstruct: named bits of one integer
A bitstruct is a struct whose fields are runs of bits of one unsigned integer, its backing
type: bitstruct Instr : u32 { op : 6; rd : 5; rs : 5; imm : 16; }. The fields are laid out from
the low bit up in declaration order and must fill the backing type exactly (name the unused bits,
pad : 3;). Each field has the smallest unsigned type that holds its width — u8 up to 8 bits,
u16 up to 16, and so on — and is read and written like any field, i.op, i.imm = 500. A write
that does not fit its field faults with diag.narrowing-overflow, or is rejected outright when the
value is a literal; nothing is ever truncated. Instr::bits(i) is the whole integer and
Instr::from_bits(w) the fields of one, both total. A bitstruct is a plain value: copied by a read,
clone, equal by its bits, a HashMap key, and its bytes in raw memory are the integer's. A field
has no address of its own, so it cannot be borrowed — borrow the whole value — and a bitstruct is
not taken apart by destructuring. Byte order is not its concern: Vec::push_le and push_be write
it out (D-0119), and an unsafe extern fn takes Instr::bits(i).
import std;
bitstruct Double : u64
{
mantissa : 52; // bits 0 .. 52
exponent : 11; // bits 52 .. 63
sign : 1; // bit 63
}
bitstruct Instr : u32
{
op : 6;
rd : 5;
rs : 5;
imm : 16;
}
fn main()
{
Double d = Double::from_bits(reinterpret<u64>(-2.5));
assert(d.sign == 1 && d.exponent == 1024); // exponent: u16, sign: u8
d.exponent = 1023; // fits in 11 bits: checked
assert(reinterpret<f64>(Double::bits(d)) == -1.25);
Instr i = Instr { .op = 3, .rd = 1, .rs = 2, .imm = 500 };
u32 word = Instr::bits(i);
assert(word == 3 | 1 << 6 | 2 << 11 | 500 << 16);
Instr j = Instr::from_bits(word);
assert(j == i && sizeof<Instr>() == 4);
j.imm = 65535; // the largest 16-bit value
assert(j.imm == 65535 && j.op == 3);
}import std;
bitstruct Flags : u8 { carry : 1; zero : 1; pad : 6; }
fn main()
{
Flags f = Flags { .carry = 2, .zero = 0, .pad = 0 }; // ✗ 2 does not fit 1 bit: diag.narrowing-overflow
}Arrays
array<T, N> holds exactly N elements; N is a constant expression — a literal, a const name (m::N too), or + - * / % & | ^ << >> ~ ( ) over them, or min_value, max_value, widen, narrow of an integer type, or sizeof and alignof of any type the program lays out (const usize S = sizeof<u32>(); then array<u8, S>; array<u8, sizeof<Vec<u8>>()>; not a type parameter), computed before the program runs (D-0126); outside parentheses > ends it, so Vec<array<u8, N * 2>> reads as expected. The literal form is [a, b,
c]. Indexing takes a usize and is bounds-checked: a literal index out of range is rejected
statically, a computed one faults at run time with diag.index-out-of-bounds. Arrays of plain
elements are plain (copied on assignment); an array of resources is a resource.
import std;
fn sum(ref<array<i32, 4>, shared> a) : i32
{
i32 t = 0;
foreach (i in 0..4)
{
t += a[i]; // indexing looks through the reference
}
t
}
fn main()
{
array<i32, 4> a = [10, 20, 30, 40];
a[2] = 33;
assert(sum(&a) == 103);
auto grid = [[1, 2], [3, 4]]; // array<array<i32, 2>, 2>
assert(grid[1][0] == 3);
array<u32, 256> counts = [0; 256]; // one value in every element
counts[65] += 1;
auto flags = [false; 8]; // array<bool, 8>
array<str, 3> names = [
"ann",
"bo",
"cy", // a trailing comma is allowed
];
assert(counts[65] == 1 && !flags[7] && names[2] == "cy");
}[v; N] makes an array of N copies of v, which is evaluated once. N is written as in
the type array<T, N>, a constant expression: a number, a constant (const usize W = 24; then
array<u8, W> and [0; W], in this module or, qualified, a visible one of another,
array<u8, screen::W>), or arithmetic on them ([0; W * 2]). Because the value is copied, its type must be plain: a
String or other resource, a reference, or a function value cannot be repeated
(diag.read-of-resource or diag.type-mismatch); build such arrays element by element, or
use a Vec.
fn get(array<i32, 3> a, usize i) : i32
{
a[i] // checked against 3 when the index arrives
}
fn main()
{
array<i32, 3> a = [1, 2, 3];
get(a, 3); // ✗ diag.index-out-of-bounds (dynamic)
}Arrays of arrays
CobaltC has no separate multidimensional array type. An array's element can itself be an
array, so a grid, a cube, or anything with more dimensions is the one constructor used again:
array<array<i64, 3>, 2> is an array of 2 elements, each an array<i64, 3>. The same holds for the
literal forms, [[1, 2, 3], [4, 5, 6]] and [[0; 3]; 2], and for auto, which infers the nesting
from the literal.
Two directions are worth keeping straight:
- The type reads from the inside out. In
array<array<array<i64, 3>, 2>, 4>the innermostarray<i64, 3>is a row of 3 numbers, the nextarray<…, 2>holds 2 such rows (a block), and the outermostarray<…, 4>holds 4 blocks. The length written last is the outermost one. - Indexing and loops go from the outside in.
cube[i][j][k]picks blocki(below 4), then rowjof it (below 2), then elementkof that row (below 3). Nested loops follow the same order: the outer loop walks the blocks, the innermost the elements of one row, so the elements are visited in the order they lie in memory.
Each index is checked against its own length. Because every level is an ordinary array,
cube[1] is a whole block and cube[1][0] a whole row, values you can copy, pass and loop over.
Writing those inner types out gets long; where the type is clear from the right-hand side, auto
reads better. To print every value, nest one foreach per level: foreach (i, block in &cube)
borrows each block, and the loop inside it over block borrows each row of that block, so nothing
is copied.
import std;
fn main()
{
// Read the type from the inside out: rows of 3 i64s, 2 rows to a
// block, 4 blocks.
array<array<array<i64, 3>, 2>, 4> cube = [[[0; 3]; 2]; 4];
// Index from the outside in: cube[block][row][column].
foreach (i in 0..4)
{
foreach (j in 0..2)
{
foreach (k in 0..3)
{
cube[i][j][k] = narrow<i64>(100 * i + 10 * j + k);
}
}
}
printf("cube[3][1][2] = %v\n", cube[3][1][2]);
// Print every value: each loop borrows one level of the one outside it.
foreach (i, block in &cube)
{
foreach (j, row in block)
{
printf("cube[%v][%v]:", i, j);
foreach (x in row)
{
printf(" %v", x);
}
printf("\n");
}
}
// `auto` spares spelling the inner types; each is a copy (the elements are plain).
auto block = cube[1]; // array<array<i64, 3>, 2>
auto row = block[0]; // array<i64, 3>
auto grid = [[1, 2, 3], [4, 5, 6]]; // array<array<i32, 3>, 2>
printf("row %v %v %v, grid[1][2] = %v\n", row[0], row[1], row[2], grid[1][2]);
}cube[3][1][2] = 312 cube[0][0]: 0 1 2 cube[0][1]: 10 11 12 cube[1][0]: 100 101 102 cube[1][1]: 110 111 112 cube[2][0]: 200 201 202 cube[2][1]: 210 211 212 cube[3][0]: 300 301 302 cube[3][1]: 310 311 312 row 100 101 102, grid[1][2] = 6
For a growable sequence use Vec<T> (§21). A Vec is indexed the same way, v[i]: it
reads through Vec::index_shared, and writes (an assignment, &mut v[i]) through
Vec::index_exclusive, so every rule about borrowing the Vec applies.
Slices
A slice is a borrowed run of consecutive elements of an array, a Vec, or another slice:
&a[i..j] is elements i up to (not including) j, and &mut a[i..j] the same for writing. Inside
the brackets, $ stands for the length of what is being indexed, so &a[0..$] is all of it and
&a[$ - 3 .. $] the last three, and v[$ - 1] is a Vec's last element. $ is a usize like any
index, so v[$ - 1] of an empty v is an overflow fault, never a wrapped-around index.
The type is slice<T, shared> or slice<T, exclusive>. One parameter of that type takes any
array, any Vec, or part of either, so a function need not be written once per container or per
array length. slice_len(s) is its length; s[i] is bounds-checked; foreach works over it. A
slice is a borrow like a reference: while it lives, the elements it views cannot be changed except
through it, its source cannot be pushed to or popped from, and a slice of a local cannot be returned.
import std;
// Sorts any run of i32 in place: an array, a Vec, or part of one.
fn sort(slice<i32, exclusive> s)
{
for (usize i = 1; i < slice_len(s); i += 1)
{
usize j = i;
while (j > 0 && s[j - 1] > s[j])
{
i32 t = s[j - 1];
s[j - 1] = s[j];
s[j] = t;
j -= 1;
}
}
}
fn sum(slice<i32, shared> s) : i32
{
i32 total = 0;
foreach (x in s)
{
total += *x;
}
total
}
fn main()
{
auto a = [5, 3, 9, 1, 7, 2];
sort(&mut a[0..3]); // only the first three: [3, 5, 9, 1, 7, 2]
assert(a[0] == 3 && a[3] == 1);
assert(sum(&a[$ - 3 .. $]) == 10); // the last three
Vec<i32> v = Vec::new();
foreach (x in [40, 10, 30, 20])
{
Vec::push(&mut v, x);
}
sort(&mut v); // the same function, on a Vec
assert(v[0] == 10 && v[$ - 1] == 40);
v[0] += 1; // indexing a Vec, written
assert(sum(&v) == 101);
}import std;
fn main()
{
Vec<i32> v = Vec::new();
Vec::push(&mut v, 1);
auto s = &v[0..1];
Vec::push(&mut v, 2); // ✗ diag.aliasing-conflict: s still borrows v
i32 first = s[0]; // (because s is used here)
}A slice borrows only its own elements. Two slices of one array or Vec conflict only if their
ranges share an element, so a buffer can be split into parts that are each written through their
own exclusive slice, at the same time: the halves of a divide-and-conquer algorithm, or one part per
thread. What reaches the whole source (&mut v, Vec::push) still conflicts with every live slice
of it.
import std;
fn sum_into(slice<u64, exclusive> s, u64 start) : u64
{
u64 total = 0;
foreach (i in 0..slice_len(s))
{
s[i] = start + widen<u64>(i);
total += s[i];
}
total
}
fn main()
{
Vec<u64> v = Vec::new();
for (usize i = 0; i < 100; i += 1)
{
Vec::push(&mut v, 0);
}
usize mid = slice_len(&v) / 2;
{
slice<u64, exclusive> left = &mut v[0 .. mid]; // elements 0 .. 50
slice<u64, exclusive> right = &mut v[mid .. $]; // elements 50 .. 100: disjoint
auto a = spawn(sum_into, left, 0: u64); // each half filled by its own thread
auto b = spawn(sum_into, right, 1000: u64);
assert(join(a) + join(b) == 1225 + 51225);
}
assert(v[49] == 49 && v[50] == 1000);
}Vectors: simd<τ, N>
A simd<τ, N> is N numbers that one processor instruction works on together: four f32s in
a 16-byte register, thirty-two u8s in a 32-byte one. Arithmetic on two vectors applies to every
lane at once, so a loop that steps eight elements at a time does eight elements' work per step. The
type is portable: cobc compiles it to the target's vector instructions (SSE, AVX or NEON, chosen by
-march), or to pairs of narrower ones where the target has no register that wide, with the same
results either way.
| Allowed | |
|---|---|
| Lanes | an integer type (not i128/u128), f32 or f64 |
| Shapes | N a power of two from 2, and N × size 8, 16, 32 or 64 bytes: simd<f32, 4>, simd<f32, 8>, simd<u8, 16>, simd<i64, 2>, simd<f64, 8> … |
| Making one | an array literal or [x; N] where a simd is expected; simd_load<V>(s, i) from a slice |
| Lanes | v[i] read and assigned (checked); never borrowed |
| Operators | + - * (and / for floats), & | ^ ~ and shifts for integers, == != on the whole; both operands one simd type |
| Lane-wise | simd_lt and kin give masks; simd_select, simd_any, simd_all; simd_min, simd_max |
| Reductions | simd_sum, simd_reduce_min, simd_reduce_max, from lane 0 to the last |
Integer lanes are checked as integers are everywhere: if any lane of a + b overflows, the
program faults. Where wrapping is the intent, as in hashing or a sum that cannot overflow,
wrapping_add, wrapping_mul and saturating_add take vectors too, and they are the fast path. Float
lanes follow IEEE 754 with no fused multiply-add, and simd_sum adds left to right, so a result is fixed
bit for bit by the specification; it can differ from a scalar loop's, which adds in another order.
import std;
// Eight lanes at a time, then the few left over one at a time.
fn dot(slice<f32, shared> a, slice<f32, shared> b) : f32
{
simd<f32, 8> acc = [0.0; 8];
usize i = 0;
while (i + 8 <= slice_len(a))
{
acc = acc + simd_load<simd<f32, 8>>(a, i) * simd_load<simd<f32, 8>>(b, i);
i += 8;
}
f32 s = simd_sum(acc);
while (i < slice_len(a))
{
s += a[i] * b[i];
i += 1;
}
s
}
fn main()
{
Vec<f32> a = Vec::filled(19, 0.5: f32);
Vec<f32> b = Vec::filled(19, 2.0: f32);
printf("%v\n", dot(&a, &b));
}19.0
A comparison of two vectors is a mask: lanes of the same width holding -1 where the
comparison holds and 0 where it does not. simd_select(m, a, b) takes each lane from a or b by the
mask, which replaces a branch inside the loop.
import std;
fn main()
{
simd<i32, 8> v = [3, -1, 4, -1, -5, 9, -2, 6];
simd<i32, 8> m = simd_lt(v, [0; 8]); // -1 where v[i] < 0
simd<i32, 8> abs = simd_select(m, -v, v);
printf("%v %v\n", simd_sum(abs), simd_any(simd_gt(v, [8; 8])));
simd<u8, 16> bytes = [250; 16];
simd<u8, 16> w = wrapping_add(bytes, [10; 16]); // 4 in every lane
simd<u8, 16> s = saturating_add(bytes, [10; 16]); // 255 in every lane
printf("%v %v\n", w[0], s[15]);
}31 true 4 255
How much a vector gains depends on the machine and the C compiler. On a processor with only
128-bit SSE registers, an 8-lane f32 dot product ran about twice as fast as the scalar loop with GCC
and over three times as fast with Clang; with AVX2 (cobc -march=native on such a machine) the 8
lanes fit one register. Data far larger than the cache is limited by memory bandwidth whichever form
you write.
Types declared inside a function
A struct, enum or bitstruct used by one function can be declared inside it, as a
statement, and so can its functions, fn T::name(…) (a destructor too). It is an ordinary type whose name is
scoped like a local: usable from its declaration to the end of its block. Two functions can each
have their own Entry. A local type and its functions see module items and the local types and
constants around them, but not the function's variables or type parameters; a plain local function
is written as a closure (§15).
import std;
fn shortest(ref<Vec<String>, shared> words) : usize
{
struct Entry // visible only in this function
{
usize len;
usize at;
}
fn Entry::better(ref<Entry, shared> a, ref<Entry, shared> b) : bool
{
a.len < b.len || (a.len == b.len && a.at < b.at)
}
Entry best = Entry { .len = max_value<usize>(), .at = 0 };
foreach (i, w in words)
{
Entry e = Entry { .len = StringView::len(w), .at = i };
if (Entry::better(&e, &best))
{
best = e;
}
}
best.at
}
fn main()
{
Vec<String> w = Vec::new();
Vec::push(&mut w, "banana");
Vec::push(&mut w, "fig");
Vec::push(&mut w, "pea");
assert(shortest(&w) == 1); // "fig": as short as "pea", and first
}A bitstruct declared in a function is the same as one at module level: it gets its
Name::bits and Name::from_bits, and its fields read and write in the same way. A packed header
that one decoder reads can live inside that decoder.
import std;
fn payload_len(u16 raw) : u16
{
bitstruct Header : u16 // bits 0..4, 4..14, 14..16
{
kind : 4;
len : 10;
flags : 2;
}
Header h = Header::from_bits(raw);
h.len
}
fn main()
{
assert(payload_len(0x0123) == 18); // 0x0123 >> 4 is 0x12
assert(payload_len(0xFFFF) == 1023);
}Enums and match
An enum lists its variants; each may carry one payload type, or named fields (below).
Variant names are used bare (Cold(3), Fine) or qualified (Verdict::Fine) when two visible
enums share a name. A variant with no payload behaves as if it carried ().
match (e) { … } compares the discriminant and runs the arm for that variant. Each arm is
Variant(binder) : expression, for a payload, Variant : expression, for none, or
_ : expression, as a catch-all; a comma follows each arm, and the one after the last may be left out
(match (k) { A : 1, B : 2 } on one line). There is at least one arm, and the
arms must cover every variant or include _. Arms are expressions, so a match produces a value; use a block as the arm body
for statements. Arms are tried in order and the first that fits is taken. An arm never runs on into the
next, so it needs no break; a break in an arm leaves the enclosing loop, and --check warns
(diag.match-arm-break) when an arm for a literal value does its work and then ends with break;, as a case of a C switch does.
import std;
enum Shape
{
Circle(i32), // radius
Square(i32), // side
Dot
}
fn area(Shape s) : i32
{
match (s)
{
Circle(r) : 3 * r * r, // the payload is bound to r for this arm
Square(w) : w * w,
Dot : 0,
}
}
fn is_round(Shape s) : bool
{
match (s)
{
Circle(_) : true, // _ as a binder ignores the payload
_ : false, // a wildcard arm covers the rest
}
}
fn main()
{
assert(area(Circle(2)) == 12);
assert(area(Shape::Dot) == 0);
assert(is_round(Square(1)) == false);
array<Shape, 2> shapes = [Circle(1), Square(3)];
assert(area(shapes[1]) == 9);
}enum Sign
{
Pos,
Neg,
Zero
}
fn describe(Sign s) : i32
{
match (s)
{
Pos : 1,
Neg : -1, // ✗ diag.non-exhaustive-match: Zero is not covered
}
}
fn main()
{
describe(Zero);
}Nested patterns
Inside the parentheses, a pattern can say what the payload itself must be, as deep as
needed: Ok(Some(line)) matches an Ok whose payload is a Some, and binds the Some's
payload. A name there is a binder, unless it is a variant's name (Some(None)), and _ ignores
that level. Since a variant has one payload (one struct, for a variant with fields), an arm binds one name, the innermost payload it
reaches, unless that payload is a struct taken apart by a struct pattern (below). Every value must reach some arm (the error names one that does not, such as
Ok(None)), and every arm must be reachable: an arm whose values all go to earlier arms is
rejected, since it could never run.
import std;
fn classify(Result<Option<i32>, ParseError> r) : i32
{
match (r)
{
Ok(Some(n)) : n, // two levels tested, the inner payload bound
Ok(None) : 0,
Err(Invalid(at)) : -100 - narrow<i32>(at),
Err(_) : -1,
}
}
fn main()
{
assert(classify(Ok(Some(7))) == 7);
assert(classify(Ok(None)) == 0);
assert(classify(Err(Invalid(3))) == -103);
assert(classify(Err(Empty)) == -1);
}import std;
fn main()
{
Option<Option<i32>> o = Some(None);
i32 v = match (o)
{
Some(Some(x)) : x,
Some(None) : 1,
Some(_) : 2, // ✗ diag.unreachable-arm: every Some went to the arms above
None : 0,
};
}Struct patterns
Where a binder could stand, a struct pattern can take the payload apart at once:
Some(Question { name, end }) binds name and end, as Question { name, end } = q; would after
binding q. The rules are destructuring's (§11): every field is named once, or .. stands for the
rest; end : e binds a field to another name; and the fields are taken by value, so a String
field moved out consumes the value matched, as any binder of a resource payload does. A struct
pattern always fits, so it counts as a binder for exhaustiveness. It works in match arms and in
if and while patterns. Through a reference (match (&o)) each name is a reference to its
field, shared or exclusive as the reference is, as every binder through a reference is (D-0324);
nothing is moved out.
import std;
struct Question
{
String name;
u32 end;
}
fn ask(u32 k) : Option<Question>
{
if (k == 0)
{
return None;
}
Some(Question { .name = "who", .end = k })
}
fn main()
{
if (Some(Question { name, end }) = ask(4))
{
assert(name == "who" && end == 4);
}
u32 n = match (ask(7))
{
Some(Question { end : e, .. }) : e, // renamed; `name` left and ended
None : 0,
};
assert(n == 7);
}Variants with fields
A variant that carries several values names them, as a struct names its fields (D-0324):
Bin { u8 op; Box<Expr> a; Box<Expr> b; }. It is made by naming them, Expr::Bin { .op = b'+', .a =
…, .b = … }, and matched by naming them, Expr::Bin { op, a, b }, with .. and renaming as in a
struct pattern, always with the enum's name, so that it does not read as a struct of its own. Its
payload is one struct the implementation adds beside the enum, which messages call Expr::Bin; a
binder for the whole payload (Expr::Bin(x)) is refused, since its type could not be written.
import std;
enum Account
{
Open { String owner; i64 balance; },
Closed,
}
fn deposit(ref<Account, exclusive> a, i64 amount)
{
match (a)
{
Account::Open { balance, .. } : { *balance += amount; }, // a reference to the field
Account::Closed : {},
}
}
fn main()
{
Account a = Account::Open { .owner = "kim", .balance = 10 };
deposit(&mut a, 5);
if (Account::Open { owner, balance } = a)
{
assert(owner == "kim" && balance == 15);
}
}Literal patterns
A pattern can also be a literal: an integer (3, -1, 0x10), a byte (b'x'), true or
false. It can stand alone, when the value being matched is an integer or a bool, or at the end
of a nested pattern: Ok(0), Some(b'\n'). This is CobaltC's multi-way branch in place of switch,
and it is checked: a literal must be of the type it is compared with, a repeated case is an arm that
can never run, and an integer match needs a _ arm, since literals never list every value
(true and false do cover a bool). Text is matched the same way: a match on a str, a
String or a StringView takes text literals ("get" : …), compared byte for byte where the text
is, so a String you match on is still yours afterwards; Some("quit") works inside a payload too,
and if ("quit" = cmd) as a condition. Floats are not patterns. With that, patterns are _, a
literal, a variant, and a variant with a pattern for its payload; there is nothing else to learn.
import std;
fn step(u8 op, i64 acc) : i64
{
match (op)
{
0x01 : acc + 1, // a byte from an instruction stream
0x02 : acc * 2,
0x10 : 0,
_ : acc, // any other opcode: no effect
}
}
fn is_end(Result<usize, FileError> r) : bool
{
match (r)
{
Ok(0) : true, // a read of 0 bytes: the end of the file
Ok(_) : false,
Err(_) : true,
}
}
fn main()
{
array<u8, 5> program = [0x01, 0x02, 0x02, 0x7f, 0x01];
i64 acc = 0;
foreach (op in program)
{
acc = step(op, acc);
}
assert(acc == 5);
assert(is_end(Ok(0)) && !is_end(Ok(16)));
}import std;
fn opcode(StringView word) : i32
{
match (word)
{
"load" : 1,
"store" : 2,
"jump" : 3,
_ : -1, // any other word: not an instruction
}
}
fn is_quit(ref<String, shared> line) : bool
{
match (*line) // a String is read where it is, not moved
{
"quit" : true,
"exit" : true,
_ : false,
}
}
fn main()
{
assert(opcode("jump") == 3 && opcode("halt") == -1);
String cmd = "exit";
assert(is_quit(&cmd) && StringView::len(&cmd) == 4);
Option<String> first = Some("load");
i32 k = match (first) { Some("load") : 1, Some(_) : 2, None : 0, };
assert(k == 1);
}Ranges and several values
An arm names one pattern: there are no range patterns (10..15 : …) and no lists of
alternatives (1, 4, 6 : … or 1 | 4 | 6 : …); each is a syntax error. Two forms cover these cases.
To test a range, match on the test itself: the condition is a bool, and true and false cover
it, so no _ arm is needed. Write the bounds as a range would mean them, the upper one left out
(v < 15 for 10..15).
import std;
fn check(i32 v)
{
match (v >= 10 && v < 15) // 10 to 14, as 10..15 would mean
{
true : printf("%v\n", v),
false : printf("%v is not in the correct range\n", v),
}
}
fn main()
{
check(12);
check(15);
check(9);
}12 15 is not in the correct range 9 is not in the correct range
For several values that share an action, give each value its own arm, and put an action
longer than a line in a function the arms call: the match still checks every literal's type and
reports a repeated one. When the values are the whole question, match on the test instead, as for a
range. For a longer list, keep the values in an array and ask contains, or in a HashSet when the
list is built at run time. Text works the same way: one arm per word.
import std;
fn weekend(ref<array<str, 7>, shared> names, u32 day)
{
printf("%v is a weekend day\n", names[widen<usize>(day)]);
}
fn describe(u32 day)
{
array<str, 7> names = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
match (day)
{
0 : weekend(&names, day), // one arm per value; the shared action in a function
6 : weekend(&names, day),
_ : printf("%v is a weekday\n", names[widen<usize>(day)]),
}
}
fn is_square(u32 v) : bool
{
match (v == 1 || v == 4 || v == 9) // several values as one test: true and false cover it
{
true : true,
false : false,
}
}
fn main()
{
describe(0);
describe(3);
assert(is_square(4) && !is_square(5));
array<u32, 6> small = [2, 3, 5, 7, 11, 13]; // a longer list
Vec<u32> primes = Vec::from_slice(&small);
assert(Vec::contains(&primes, 7) && !Vec::contains(&primes, 9)); // a number is its own probe
str cmd = "exit";
bool quit = match (cmd)
{
"quit" : true,
"exit" : true,
_ : false,
};
assert(quit);
}Sun is a weekend day Wed is a weekday
import std;
fn main()
{
u8 op = 2;
i32 cycles = match (op)
{
1 : 3,
2 : 5,
1 : 4, // ✗ diag.unreachable-arm: 1 is taken by the first arm
_ : 1,
};
}Binders and named constants
A name on its own is a pattern too. If it names a constant of integer or bool type, it is
that constant's value, a literal by name (PUSH : …); if it names a variant, it is that variant;
otherwise it is a new binding for the whole value, which matches anything, like _, and is
usually the last arm (other : …). A binding of a resource moves it, as a payload binding does.
Mistaking a constant for a binding cannot go unnoticed: a match on an integer then lacks _.
import std;
const u8 PUSH = 0x01;
const u8 POP = 0x02;
fn describe(u8 op) : i32
{
match (op)
{
PUSH : 1,
POP : 2,
other : 100 + widen<i32>(other), // every other opcode, bound to `other`
}
}
fn main()
{
assert(describe(1) == 1);
assert(describe(2) == 2);
assert(describe(9) == 109);
}Matching through a reference
match (e) binds each payload by value: a plain one is copied, and a resource one (a
String, a Vec, a Box) is moved out, which consumes the enum. To look at an enum without
taking it apart, match a reference to it: match (&e) binds each payload as a shared reference,
match (&mut e) as an exclusive one, through which the payload can be changed. A scrutinee that
already is a reference, such as a function's ref<Expr, shared> parameter, binds in its own mode.
The enum is not consumed, and the usual borrow rules apply to what is bound: nothing can replace
the enum while a payload reference is still in use. This is how a tree built from Boxes (§21)
is walked. A payload that is a Box is bound through it by *x: Neg(*x) binds x to the
expression inside the box, a reference in the scrutinee's mode, as Box::get(b) (or Box::get_mut)
of the box's binder b gives it; matched by value, x is the value itself, the box consumed as
Box::into_inner(b) consumes it (D-0301). *x stands only inside a variant's parentheses, and
only where the payload is a Box.
import std;
enum Expr
{
Num(i64),
Neg(Box<Expr>),
}
fn eval(ref<Expr, shared> e) : i64
{
match (e) // e is a reference: n and x are references too
{
Num(n) : *n,
Neg(*x) : -eval(x), // x : ref<Expr, shared>, through the Box
}
}
fn main()
{
Expr e = Neg(Box::new(Neg(Box::new(Num(7)))));
assert(eval(&e) == 7);
Option<String> name = Some("ada");
match (&mut name) // change the payload in place
{
Some(s) : String::push_ascii(s, b'!'),
None : {},
}
usize len = match (&name) // look without consuming
{
Some(s) : StringView::len(s),
None : 0,
};
assert(len == 4);
String kept = Option::unwrap_or(name, String::new()); // name still owns its String
assert(StringView::len(&kept) == 4);
}A nested pattern looks through a reference payload in the same way. HashMap::get gives
an Option<ref<V, shared>>; when V is an enum, Some(Num(v)) matches its variant through the
reference and binds v as a reference of that mode, so a lookup is taken apart in one match. A
literal compares through a reference too: Some(0) against an Option<ref<u32, shared>>. The
binder borrows what the reference borrows, so the map cannot change while v is in use.
import std;
enum Cell
{
Num(i64),
Text(String),
Empty,
}
fn width(Option<ref<Cell, shared>> c) : i64
{
match (c)
{
Some(Num(v)) : *v, // v : ref<i64, shared>
Some(Text(t)) : narrow<i64>(widen<u64>(StringView::len(t))),
Some(Empty) : 0,
None : -1,
}
}
fn main()
{
HashMap<u32, Cell> sheet = HashMap::new();
HashMap::insert(&mut sheet, 1, Num(12));
HashMap::insert(&mut sheet, 2, Text("total"));
assert(width(HashMap::get(&sheet, 1)) == 12 && width(HashMap::get(&sheet, 2)) == 5);
assert(width(HashMap::get(&sheet, 9)) == -1);
match (HashMap::get_mut(&mut sheet, 1))
{
Some(Num(v)) : { *v += 1; }, // v : ref<i64, exclusive>
_ : {},
}
assert(width(HashMap::get(&sheet, 1)) == 13);
}An arm that takes the payload consumes the enum
If the enum carries a resource payload, an arm that binds that payload by value
moves it into the binder and consumes the enum: if that arm ran, the scrutinee is stale
afterwards. This is what makes match (Vec::pop(&mut v)) { Some(x) : …, None : … } hand you the
popped element. An arm that takes nothing out — _, a payload-less variant, or Some(_) — leaves
the scrutinee alone, so match (o) { None : …, _ : use(o) } is fine. To look inside and keep the
enum whatever the arm, match on a reference to it (above).
import std;
enum Slot
{
Full(Vec<i32>),
Empty
}
fn main()
{
Vec<i32> payload = Vec::new();
Vec::push(&mut payload, 4);
auto s = Slot::Full(payload); // payload moves into the enum
usize n = match (s) // the Full arm consumes s
{
Full(v) : Vec::len(&v), // v owns the Vec for the arm, and destroys it at the arm's end
Empty : 0,
};
assert(n == 1);
Option<String> o = Some("kept");
match (o)
{
None : {},
_ : // takes nothing out: o is still here
{
String t = Option::unwrap_or(o, String::new());
assert(StringView::len(&t) == 4);
},
}
}Numeric codes
An enum without payloads can carry a number per variant, for a file format, a protocol or
a C interface: enum Op : u8 { Add = 1, Sub, Mul = 10 }. The type after the colon is the code
type, any integer type. A variant without = n takes the previous code plus one (the first, 0).
Two variants may not share a code. The enum then has two associated functions:
Op::code(e) gives a variant's code, and Op::from_code(n) gives Some(variant) for a code
in use and None for any other.
import std;
enum Op : u8
{
Add = 1,
Sub, // 2
Mul = 10,
}
fn main()
{
assert(Op::code(Sub) == 2 && Op::code(Mul) == 10);
match (Op::from_code(10))
{
Some(Mul) : {},
_ : { assert(false); },
}
assert(Op::from_code(3) == None);
}Generic aggregates
struct Box<T> { T value; } and enum Maybe<T> { Just(T), Nothing } declare families of
types. std's Option<T> and Result<T, E> are ordinary enums of exactly this kind (§21).
Type arguments may be left off a literal when the declared type of the variable, parameter or field
fixes them (§12).
Layout
A struct is laid out as C lays out the same members in the same order (D-0250): each
field at the first offset its alignment allows after the previous one, and the end padded to the
largest alignment. So C code given a rawptr<S> finds every field where its own offsetof says
(§20). Arrays are contiguous with no padding; an enum is a discriminant of documented width followed
by the largest payload, aligned, with one exception (D-0298): an enum of two variants, one with no
payload and one holding a Box, is the Box alone, and the other variant is the null pointer. So
Option<Box<T>> is one pointer, as a nullable T * is in C, and a linked node costs what it costs
in C. sizeof<T>() and alignof<T>() report the result (examples in §06, "Sizes and limits of
types").
align(N) after a struct's name raises its alignment to N, a power of two up to 4096
(D-0251), and pads its size to a multiple of it, so every element of an array or Vec of it starts
on an N boundary. It is C's alignas on a type. The usual reason is to give data that threads
change a cache line of its own: two counters on one 64-byte line make the cores take the line from
each other on every write, though they never touch the same counter. align raises and never
lowers; a field gets an alignment by being of an aligned struct type.
import std;
struct Rec
{
u8 a; // offset 0
u64 b; // offset 8: the first multiple of 8 after 1
u16 c; // offset 16; the size rounds 18 up to 24
}
struct Slot align(64) // one cache line each
{
Atomic<u64> count;
}
fn main()
{
static_assert(sizeof<Rec>() == 24 && alignof<Rec>() == 8);
static_assert(sizeof<Slot>() == 64 && sizeof<array<Slot, 4>>() == 256);
array<Slot, 2> per_thread = [Slot { .count = Atomic::new(0: u64) }, Slot { .count = Atomic::new(0: u64) }];
_ = Atomic::fetch_add(&per_thread[1].count, 1);
assert(Atomic::load(&per_thread[1].count) == 1);
}- Reach for an enum whenever a value is one of several cases;
matchforces you to handle each one. - Use
_sparingly: a wildcard arm silently absorbs variants you add later. - Give match arms a block body when they need statements, and remember the comma after each arm.
- Build aggregates whole with a literal, then mutate fields as places.
§17Modules and name resolution
spec/17-modules.mdmodule, export and import; re-export; private by default; a module's body may be another file; a fixed lookup order for every name.
Modules group declarations and control which names are visible where. They introduce no new semantics: ownership, borrowing and every other rule apply unchanged across module boundaries.
Declaring modules
module name { … } encloses any declarations, including nested modules. Everything is
private by default: usable from its own module and the modules nested inside it. export
on a declaration makes it usable from outside. An exported item inside a private module is only
reachable where that module is.
Each declaration adds one qualified name (bank::fee, bank::Account::open,
Shape::Circle), and a name may be added only once, so declaring fee twice in bank is
diag.duplicate-item. The same simple name in two different modules is two different names. An
associated function fn T::name belongs in the module that declares T; anywhere else it is
diag.foreign-associated-fn, so no program can add to, or replace, the functions of std's
Vec.
module bank
{
export fn fee(i32 amount) : i32
{
percent(amount, 2) // a private helper is visible inside its own module
}
fn percent(i32 v, i32 pct) : i32
{
v * pct / 100
}
export module audit // nested modules; both must be exported to reach `twice`
{
export fn twice(i32 v) : i32
{
fee(v) * 2 // the enclosing module's items are in scope
}
}
}
fn main()
{
std::assert(bank::fee(1000) == 20); // qualified with ::
std::assert(bank::audit::twice(1000) == 40);
}module inner
{
fn helper() : i32 // not exported
{
42
}
}
fn main()
{
inner::helper(); // ✗ diag.name-not-visible
}import
import a::b::name; lets name be used unqualified in the importing module. It creates no
alias and no copy; it only extends name lookup. There is no import … as renaming: if two
imports would give one name two meanings, qualify.
module maths
{
export fn square(i32 v) : i32
{
v * v
}
}
import maths::square;
fn main()
{
std::assert(square(6) == 36); // resolves through the import
std::assert(maths::square(7) == 49); // the qualified form still works
}import m; naming a module does two things: m itself resolves, as with any import, and
every item m exports, including the variants of its exported enums, can be used unqualified, except
its submodules, which keep their paths (std::text) or are imported themselves. This
is how programs use the standard library: import std;. A name is looked up in a fixed order: the
module's own declarations first, then single-name imports, then module imports, then the
enclosing modules. So a module's own printf wins over std::printf, which stays reachable by its
full name. If two imported modules both export a name, using that name unqualified is
diag.ambiguous-name; importing both is fine, so a module that gains an export never breaks a
program that does not use it. An import acts only in the module that writes it: a nested module, or
a module in a file of its own, writes its own import std;.
import std;
module shapes
{
import std;
export enum Shape
{
Square(i32),
Dot,
}
export fn show(Shape s) // not `describe`: `std` exports one, and two imports of a name must be qualified
{
match (s)
{
Square(_) : printf("square\n"),
Dot : printf("dot\n"),
}
}
}
import shapes;
fn printf(str s) // the root's own printf is found before std::printf
{
std::printf("> ");
std::printf("%v", s);
}
fn main()
{
show(Square(2)); // shapes::show and shapes::Shape::Square, unqualified
printf("done\n");
}square > done
Re-export: export import
An import can be exported like any other declaration. export import p; in a module M
does what import p; does, and also passes on what p brings in as M's own items: every item
the module p exports, or the one item p names. A program that imports M then finds those names
as if M had declared them, and M::name works too. They are the same items, not copies: a type
passed on this way is one type under two paths. This is how a library divided into modules is still
used with one import, and how std itself is built (§21): import std; brings in std::text,
std::io and the rest because std re-exports each of them.
import std;
module geometry
{
export module shapes
{
export struct Square
{
export i32 side;
}
export fn area(Square s) : i32
{
s.side * s.side
}
}
export module units
{
export fn cm(i32 n) : i32
{
n * 10
}
}
export import geometry::shapes; // shapes' items become geometry's
export import geometry::units::cm; // one item only
}
import geometry;
fn main()
{
Square s = Square { .side = cm(2) }; // geometry::shapes::Square, through geometry
printf("%v\n", area(s));
geometry::shapes::Square t = geometry::Square { .side = 1 }; // one type, two paths
printf("%v\n", area(t));
}400 1
Only what is exported passes through: a private item never becomes reachable by being
re-exported. A name the module already has for a different item is diag.duplicate-item; the same
item arriving twice, or two modules re-exporting each other, is not an error.
Constants as items
A const declared at a module's top level is an item like a function: it is private unless
marked export, it can be imported, and other modules name it by its path (config::LIMIT).
Constants themselves, and the static_assert checks built on them, are described with
declarations (§11) and with assertions (§18). The specification keeps their rules in its modules
chapter (spec/17 §1a and §1b), because a constant is an item.
A module in another file
A module's body can be a separate file. module geo "./geometry.cb"; means exactly
module geo { … } with the file's declarations as the body: the same visibility, the same
import, the same lookup. The declaring file names the module; the other file's top level is
anonymous, just as an inline body is. The path is relative to the directory of the file that
writes it, so a file can itself declare file-backed modules with paths relative to its own
location, and a library moves as a unit. Use forward slashes and stay inside the tree (no leading
/, no ..); anything beyond that is up to the implementation.
// geometry.cb -- the body of a module. Nothing here names the module;
// the file that declares it does. Only `export` items are visible there.
export struct Rect
{
export f64 w;
export f64 h;
}
export fn area(Rect r) : f64
{
r.w * r.h
}
fn scale_factor() : f64 // private to this module
{
1.0
}// main.cb -- run this one: `cobc --run main.cb`
module geo "./geometry.cb"; // module geo { … } with geometry.cb's items as the body
import geo::Rect;
fn main()
{
Rect r = Rect { .w = 3.0, .h = 4.0 };
std::assert(geo::area(r) == 12.0); // qualified, as with any module
// geo::scale_factor(); // ✗ diag.name-not-visible: private, exactly as in one file
}Three things are rejected before anything runs: a path that names no file
(diag.module-file-not-found), a file whose body would load itself again through some chain of
declarations (diag.module-cycle), and one file named by two declarations
(diag.module-file-duplicate — it would be two distinct modules and two distinct Rect types).
A fn main in a loaded file is just the item geo::main; the program's entry is the root file's
main, and a program with none is diag.no-main. A diagnostic inside a loaded file is reported
against that file and its own line.
A library in several files
Files and re-export (above) together give a library that is split across files but used with
one import. Its root file declares the parts, keeps its helpers in a private module, and passes on
what users should see: here every exported item of shapes, and cm alone from units. The
helpers are usable everywhere inside the library and nowhere outside it, and the files can be
reorganized later without changing any program that imports the root.
// geometry.cb -- the library's root: what `import geometry;` brings in
export module shapes "shapes.cb";
export module units "units.cb";
module detail "detail.cb"; // private: the library's own helpers
export import geometry::shapes; // every exported item of shapes
export import geometry::units::cm; // one item; units::mm keeps its path// shapes.cb
export struct Square
{
export i32 side;
}
export fn Square::new(i32 side) : Square
{
Square { .side = side }
}
export fn area(Square s) : i32
{
detail::square(s.side) // geometry's private module, visible inside geometry
}// units.cb
export fn cm(i32 n) : i32
{
n * 10
}
export fn mm(i32 n) : i32
{
n
}// detail.cb -- exported from a private module: reachable only inside geometry
export fn square(i32 v) : i32
{
v * v
}// main.cb -- run this one: `cobc --run main.cb`
import std;
module geometry "geometry.cb";
import geometry;
fn main()
{
Square s = Square::new(cm(2)); // shapes and units, through one import
printf("%v\n", area(s));
printf("%v\n", geometry::units::mm(5)); // not passed on: written in full
// geometry::detail::square(3); // ✗ diag.name-not-visible: detail is private
}400 5
How a name is found
An unqualified name is first looked up as a local variable or parameter. Failing that, in
this order: an item of the current module; an import in the current module whose last segment
matches; an item of an enclosing module, outward to the root; finally a variant: first of the
enums of this module, or else of the nearest enclosing module with one of that name, and only if
there is none, of an imported enum. So your own enum Shape { …, Empty } keeps its bare Empty even
though std's ParseError has an Empty too. And where a value is written, a type the earlier steps
find is passed over, since a type is no value: your enum Report { File(u64), … } keeps its bare
File(n) beside import std;, which exports the struct File, and File in a type position is still
std's (D-0266). More than one candidate at a step is
diag.ambiguous-name; none at all is
diag.unbound-name. A qualified name a::b::c starts by resolving a the same way and then walks
into it, checking visibility at the end.
Two special cases: an associated function declared as fn Type::name(…) is addressed as
Type::name (or mod::Type::name from outside), and an enum's variants are addressable as
Enum::Variant as well as bare.
fn main()
{
does_not_exist(1); // ✗ diag.unbound-name
}Structs and fields across modules
A struct or enum declared in a module is an item like any other: export it to use it
outside. Each field has its own visibility too; write export i32 x; for fields that
callers may read and write directly, and leave the rest private to give the module full control
over its invariants.
module shapes
{
export struct Rect
{
export i32 w; // visible to users of the module
export i32 h;
i32 cached_area; // private: only this module's functions may touch it
}
}module shapes
{
export struct Rect
{
export i32 w;
i32 cached_area;
}
}
fn main()
{
auto r = shapes::Rect { .w = 1, .cached_area = 0 }; // ✗ diag.name-not-visible: cached_area is private
}Naming a private field from outside its module — reading it, writing it, giving it in a
struct literal, or destructuring it — is diag.name-not-visible, the same diagnostic as for a
private function. Give the module a constructor function if callers need to build the struct.
There are no read-only (const) fields: in CobaltC const means a value known before the
program runs (§11 constants), not "fixed once built". A field that other code may read but not
change is a private field with an exported function that reads it. Only the module can then change
it, which is also what keeps the module's invariant in one place.
import std;
module bank
{
export struct Account
{
export u32 id; // callers may read and write it
i64 balance; // private: changed only by this module
}
export fn Account::open(u32 id, i64 deposit) : Account
{
std::assert(deposit >= 0, "an account opens with a deposit, not a debt");
Account { .id = id, .balance = deposit }
}
export fn Account::balance(ref<Account, shared> a) : i64
{
a.balance
}
export fn Account::withdraw(ref<Account, exclusive> a, i64 amount) : bool
{
if (amount > a.balance)
{
return false; // the invariant: the balance never goes below zero
}
a.balance -= amount;
true
}
}
fn main()
{
auto acct = bank::Account::open(7, 100);
assert(bank::Account::balance(&acct) == 100); // read through the module
assert(!bank::Account::withdraw(&mut acct, 500));
assert(bank::Account::withdraw(&mut acct, 30));
assert(bank::Account::balance(&acct) == 70);
// acct.balance = 1000000; // ✗ diag.name-not-visible: only bank can change it
}Retiring a name: [[deprecated]] and [[removed]]
A name that should no longer be used is marked where it is declared. [[deprecated("what to
write instead")]] before a function, a type, a constant, a static, a module, a field or a variant makes
every use of it an error (diag.deprecated-use) whose message is the attribute's; the program builds
again with --allow-deprecated, which reports each use as a warning instead, so the warnings are the
list of what is left to change. When the name is gone for good, its declaration becomes a
tombstone, the head and ;: [[removed("…")]] fn old;. A use of it is diag.removed-use,
which no flag accepts, and the name stays taken, so nothing else can be declared with it. A use inside a
retired declaration itself, or in the unittest right after one, does not count (D-0303).
import std;
[[deprecated("call total instead")]]
fn sum(i32 a, i32 b) : i32
{
a + b
}
fn total(i32 a, i32 b) : i32
{
a + b
}
fn main()
{
printf("%d\n", sum(1, 2)); // ✗ diag.deprecated-use (static): `sum` is deprecated: call total instead
}The attributes are these two; there is no [[nodiscard]], [[inline]] or [[maybe_unused]]
(_ = e;, the compiler and the absence of unused warnings cover those). std retires its names the same
way: String::from_str was deprecated and is now removed, since a literal is already the String where one is
declared and String::copy copies any other text (D-0305); the String:: copies of the StringView text
functions went the same way, since &s is a view where one is declared (D-0306).
- Start every module with everything private; export only what callers need.
- Prefer qualified calls (
maths::square(x)) in code that reads like a library;importthe handful of names you use constantly. - Module boundaries are not safety boundaries:
unsafeis lexical (§20). To confine trusted code, keep the functions that wrap it un-exported. - Split a program across files with
module m "./m.cb";, one file per module; keep paths relative and let the declaring file do the naming.
§18Errors and failure
spec/18-error-failure-semantics.mdFatal checked faults that unwind, assertions checked at run time or before the program runs, and recoverable Result values with the ? operator. Nothing in between.
There are exactly two ways for something to go wrong in CobaltC, and they never mix. A
checked fault is the language catching a violated invariant (overflow, an index out
of range, a stale reference, a conflicting borrow): it is fatal. An error value is
your program reporting an expected failure (bad input, a full buffer) through Result or Option:
it is data, and the caller decides what to do. There are no exceptions and no catch.
Checked faults
When a run-time check fails, the current thread unwinds every open scope, running every destructor exactly as a normal scope exit would, and the program terminates reporting the fault by name. Nothing can intercept this within a thread. (A fault in a thread you spawned ends that thread alone, and its failure becomes a value at the thread's boundary: §19, When a thread fails.) The point is that a fault cannot corrupt state or leak an external resource on the way out, and that a program that reaches its end has never once violated a checked rule.
import std;
resource struct Guarded
{
i32 tag;
}
fn Guarded::drop(ref<Guarded, exclusive> self)
{
// runs during unwinding, before the program terminates
}
fn divide(i32 a, i32 b) : i32
{
a / b
}
fn main()
{
Guarded g = Guarded { .tag = 1 };
Vec<i32> v = Vec::new();
divide(1, 0); // ✗ diag.div-by-zero (dynamic): v and g are destroyed, then the program ends
}Assertions: assert
assert(c) states something the program relies on at that point: when c is false, the
program stops with the checked fault diag.assert-failed, naming the line, and unwinds like any
other fault. assert(c, "format", args…) adds a message, formatted as printf formats, so the
failure can say which values were wrong. The condition is always evaluated, exactly once: there is
no build in which assertions are left out. The message, and its arguments, are only evaluated when
the condition is false, so they cost nothing while it holds. Every example in this guide checks its
own results with assert; a condition that is constant is checked with static_assert (below)
before the program runs.
A failed comparison of two numbers or bools shows both values (D-0322): assert(total == 10)
reports assertion failed: 9 == 10, and with a message, the message followed by (9 == 10). Each
side is evaluated once, the left first, as the comparison evaluates them. assert(a && b) is tested
term by term, so the failure is the first false term's, with its values when it is a comparison; b
is evaluated only when a holds, as && evaluates it.
import std;
fn average(ref<Vec<u32>, shared> v) : u32
{
u32 sum = 0;
foreach (x in v)
{
sum += *x;
}
sum / narrow<u32>(Vec::len(v))
}
fn main()
{
Vec<u32> v = Vec::new();
Vec::push(&mut v, 4);
Vec::push(&mut v, 8);
assert(average(&v) == 6);
usize cap = 1;
assert(Vec::len(&v) <= cap, "%v items exceed the capacity %v", Vec::len(&v), cap);
// ✗ diag.assert-failed (dynamic), reporting "2 items exceed the capacity 1"
}Requirements: requires
A condition a function needs of its arguments belongs to its caller, and a requires block
between the signature and the body says so: each requirement is a condition, then optionally the
fault it is (named as fault(d) names one) and a message (as assert's), ending with ;. They are
checked in order when the function is called, before its body runs, so a later one may rely on an
earlier one. A false one is reported at the call, the line where the mistake is, as
diag.precondition-failed unless the requirement names another; a function std calls back, or one
run by spawn, reports the program's call or the spawn. A call whose literal arguments, or
literal-bound locals, make a requirement false is rejected before the program runs. std states its
own preconditions this way: Vec::remove's is i < v.len, index_out_of_bounds;.
import std;
fn average(ref<Vec<u32>, shared> v) : u32
requires
{
Vec::len(v) > 0, "average of an empty list";
}
{
u32 sum = 0;
foreach (x in v)
{
sum += *x;
}
sum / narrow<u32>(Vec::len(v))
}
fn main()
{
Vec<u32> v = Vec::new();
Vec::push(&mut v, 4);
Vec::push(&mut v, 8);
printf("%v\n", average(&v));
Vec<u32> none = Vec::new();
printf("%v\n", average(&none)); // ✗ diag.precondition-failed (dynamic), at this line
}6
The line between the two is who must change when the condition fails. A condition on the
parameters at the top of a body is a requirement; what a function believes of its own state part-way
through, and what a test expects, stays an assert. A requirement states a programming error: input
from outside the program (a file, the network, C) is checked into a Result, never guarded by a
requirement. It costs its condition once per call, and nothing where none is written.
Faults are named diag.… and listed in the appendix. A program that faults prints the
name, the rule that fired, what was required and what was observed, and a repair
hint.
Static assertions
static_assert(c) and static_assert(c, "why") check a constant condition when the program
is compiled, not when it runs: a false one stops it with diag.static-assert-failed and shows the
message. As with assert, the message may carry values, static_assert(D == 201, "D is %v", D),
provided they are constants too. The condition is a constant expression (the same kind a const has, §11), so it can use
constants, sizeof, alignof, the limits and the conversions. It is checked in every function,
called or not, and in a generic function once for each type it is used with, so
static_assert(sizeof<T>() <= 8, "…") limits what T may be. At run time it does nothing. For a
condition only known as the program runs, use assert (above): a static_assert whose condition
names a local variable, calls a function or is not a bool is rejected before the program runs,
with diag.static-assert-not-constant, which says so.
import std;
struct Header
{
u32 magic;
u16 version;
u16 flags;
u64 length;
}
const usize BUF = 4096;
// Stores a value that must fit in one machine word.
fn word<T>(T x) : T
{
static_assert(sizeof<T>() <= 8, "word<T> needs T to fit in 8 bytes");
x
}
fn main()
{
static_assert(sizeof<Header>() == 16, "Header must match the C struct");
static_assert(BUF & (BUF - 1) == 0, "BUF must be a power of two");
assert(word(5: i64) == 5 && word(2.5) == 2.5);
}import std;
fn main()
{
i32 x = 1;
static_assert(x == 1); // ✗ diag.static-assert-not-constant: x is a variable;
// write assert(x == 1), or const i32 X = 1;
}fn word<T>(T x) : T
{
static_assert(sizeof<T>() <= 8, "word<T> needs T to fit in 8 bytes");
x
}
fn main()
{
word(1: i128); // ✗ diag.static-assert-failed (static): an i128 is 16 bytes
}Result, Option and ?
Result<T, E> is Ok(T) or Err(E); Option<T> is Some(T) or None. Both are plain
enums of std, taken apart with match. The postfix ? operator unwraps a Result: on Ok(v) it
yields v, on Err(e) it returns Err(e) from the enclosing function immediately. That function
must therefore return Result<_, E> with exactly the same E; convert first with
Result::map_err(r, f) if the error types differ. On an Option, ? works the same way inside a
function that itself returns an Option: Some(v) gives v, None returns None at once, so
usize end = checked_add(start, n)?; reads "the sum, or give up" (D-0130). Nothing converts between
the two: in a function returning a Result, Option::ok_or(o, e) turns the Option into a
Result — Ok(v) from Some(v), Err(e) from None — so
u8 c = Option::ok_or(peek(p), fail(p, "expected a value"))?; reads "the byte, or return that
error". Where a default will do, Option::unwrap_or(o, d) and
Result::unwrap_or(r, d) give the value, or d when there is none; the default (and ok_or's
error) is evaluated either way, and one that goes unused is destroyed. Result::ok(r) turns a
Result into an Option, dropping the error. Where there must be a value,
Option::unwrap(o) and Result::unwrap(r) give it or fault with diag.unwrap-failed, and
Option::expect(o, "…") and Result::expect(r, "…") do the same with your message.
import std;
fn main()
{
Vec<String> names = Vec::new();
Vec::push(&mut names, "ada");
Vec<String> copy = Vec::clone(&names); // each String copied by its clone (§12)
String first = Option::expect(Vec::pop(&mut copy), "the copy has one name");
first = "grace"; // a String is quiet: the old one is destroyed
u32 n = Result::unwrap(StringView::parse<u32>("42"));
assert(first == "grace" && n == 42 && Vec::len(&names) == 1);
Option<u32> none = None;
u32 fails = Option::expect(none, "no value where one was promised");
// ✗ diag.unwrap-failed (dynamic), reporting "no value where one was promised"
}import std;
fn digit(u8 b) : Result<i32, u8>
{
if (b > b'9' || b < b'0') // not a digit
{
return Err(b);
}
Ok(widen<i32>(b - b'0'))
}
fn two_digits(u8 hi, u8 lo) : Result<i32, u8>
{
i32 h = digit(hi)?; // Err returns from two_digits right here
i32 l = digit(lo)?;
Ok(h * 10 + l)
}
fn main()
{
match (two_digits(b'4', b'2'))
{
Ok(v) :
{
assert(v == 42);
},
Err(_) :
{
assert(false, "unreachable");
},
}
match (two_digits(b'4', b'x'))
{
Ok(_) :
{
assert(false, "unreachable");
},
Err(e) :
{
assert(e == b'x');
},
}
}import std;
fn f() : i32
{
Result<i32, i32> r = Ok(1);
r? // ✗ diag.propagate-outside-fallible-context: f does not return Result<_, i32>
}
fn main()
{
f();
}Because ? is just a match in disguise, it consumes a resource-bearing Result the
same way a match would, and the early return runs destructors like any other.
A Result is never dropped silently: an expression statement whose value is a
Result, such as a bare call write_all(&f, &data);, is diag.result-discarded, since the error it
may carry would vanish. Handle it (?, match, unwrap), or say that you mean to ignore it with
_ = e;, which evaluates e and destroys the value at once. _ = e; works for any value.
A thread's Result is no different ([Handle-Result-Lost], D-0340): a handle<Result<…>> that may
end without join is refused, and one kept in a Vec that ends unjoined after its thread gave
Err stops the program with diag.result-discarded.
The rule behind both, and behind most of what follows ([Certain-Fault-Refused], D-0340): a fault
that is certain once a path is taken is refused when the program is checked, even when whether
that path runs depends on input. The run-time checks are for what the checker cannot know.
import std;
fn check(i32 n) : Result<i32, str>
{
if (n < 0) { Err("negative") } else { Ok(n) }
}
fn main()
{
_ = check(-1); // ignored on purpose
assert(Result::unwrap(check(2)) == 2);
}import std;
fn check(i32 n) : Result<i32, str>
{
if (n < 0) { Err("negative") } else { Ok(n) }
}
fn main()
{
check(-1); // ✗ diag.result-discarded: the error would vanish unseen
}Choosing a channel
| Situation | Use |
|---|---|
| Input that may legitimately be malformed, a container that may be empty, an allocation that may fail | Result / Option; let the caller decide |
| A condition that can only be false if the program is wrong (an index you computed, arithmetic on trusted values) | let the language's checked fault fire; do not wrap it |
| Recovering from overflow rather than faulting | checked_add and friends return Option (§06) |
| Recovering from allocation failure | call allocate yourself; Vec and Rc treat failure as a fault |
- Reserve faults for bugs. If a failure is part of normal operation, return a
Result. - Use
?to keep the happy path readable; keep error types consistent within a call chain andmap_errat the boundaries. - Trust the unwinding: a fault runs your destructors, so external handles are released even on the way down.
§19Concurrency
spec/19-concurrency.mdThreads owned by handles, a fault contained to its thread and handed over as a value, cancellation at any wait, deadlocks reported, mutexes reachable only through guards, channels, and the same aliasing rules everywhere.
CobaltC's concurrency is small: threads you start and must join, and a mutex whose contents can only be reached by locking it. The aliasing rules of §08 already forbid two threads from touching one object in conflicting ways, so most of the work is done before this section starts. What the primitives add is a way to share mutable state on purpose, safely.
Threads: spawn and join
spawn(f, args…) runs f(args…) on a new thread and returns a handle<R>, where R is
f's return type. f must be a named function, a move closure, or a closure that captures
nothing ([]); a closure borrowing locals of the spawning thread is rejected:
diag.spawn-borrow-closure. Arguments are passed exactly as for a
call: plain values are copied, resources move to the new thread, references are lent. join(h)
waits for the thread and returns its result, consuming the handle. The result may itself be a
reference (or carry one, in a struct or an Option): the handle then holds the borrow until the
join hands it over, so the source cannot be written meanwhile. A handle is a resource: if it is
still alive when its scope ends, the thread is joined then and its result discarded, so a thread
never outlives its handle. What a thread borrows is still checked at every use, as in any call: if
the referent ends first (a handle kept in a variable declared outside the borrowed local's block,
or an element released by a reallocating Vec::push), the thread's next use of it is
diag.stale-binding.
import std;
fn work(i32 n) : i32
{
n * 2
}
fn main()
{
auto h = spawn(work, 21); // the handle owns the thread
assert(join(h) == 42); // wait and take the result
Vec<i32> data = Vec::new();
Vec::push(&mut data, 5);
auto h2 = spawn(move [data]() // a move closure carries the Vec to the other thread
{
Vec::len(&data)
});
assert(join(h2) == 1);
{
auto h3 = spawn(work, 1);
} // unjoined: joined automatically here, result discarded
}fn main()
{
i32 x = 5;
auto h = spawn([x](i32 n) // ✗ diag.spawn-borrow-closure: the closure borrows x
{
n + x
}, 1);
join(h);
}A reference passed to spawn is held by the new thread until it finishes, so the
spawning thread may not use the referent in a conflicting way before join(h). Whether the thread
happened to finish first would otherwise decide the outcome; the checker rejects the program
instead.
fn read(ref<i32, shared> r) : i32
{
*r
}
fn main()
{
i32 x = 1;
auto h = spawn(read, &x); // the thread borrows x until join(h)
i32 y = x; // ✓ reading alongside a shared borrow
x = 2; // ✗ diag.aliasing-conflict (static): the thread may still be reading x
join(h);
}Sharing state: mutex and guard
Mutex::new(v) wraps a value in a mutex<T>. The value inside is reachable only through
lock(&m), which returns a guard<T>: an exclusive path into the interior that exists for as long
as the guard does. *g is the place inside. The guard is a resource; dropping it, or letting its
scope end, unlocks the mutex. Only one guard can exist at a time; another thread's lock waits.
Locking a mutex your own thread already holds is a fault, diag.mutex-reentrant-lock, not a
deadlock.
A mutex is shared between threads by passing &m, a ref<mutex<T>, shared>. Any number
of threads may hold that shared reference; it is the one case where an exclusive path (the lock
guard) is allowed to coexist with shared references to the same object, because the lock itself
serialises access.
import std;
fn worker(ref<mutex<i32>, shared> m, i32 n) : i32
{
foreach (i in 0..n)
{
auto g = lock(m); // blocks until the mutex is free
*g += 1;
} // each iteration's guard is destroyed here, unlocking
n
}
fn main()
{
auto m = Mutex::new(0);
auto h1 = spawn(worker, &m, 3); // both threads hold a shared reference to m
auto h2 = spawn(worker, &m, 4);
i32 a = join(h1);
i32 b = join(h2);
assert(a + b == 7);
i32 total = *lock(&m); // a temporary guard: it lives until the semicolon
assert(total == 7); // whatever the interleaving, every increment was serialised
}fn main()
{
auto m = Mutex::new(0);
auto g1 = lock(&m);
auto g2 = lock(&m); // ✗ diag.mutex-reentrant-lock: this thread already holds it
}A reference taken through a guard ends with the guard. &*lock(&m) is a reference for the
statement it is written in, since the guard is a temporary; a reference through a bound guard lasts
until drop(g) or the guard's block. A reference kept longer would reach the value while another
thread holds the lock, and is refused (diag.destroy-while-aliased): bind the guard for as long as the
reference is needed, or copy what you need out.
import std;
fn main()
{
mutex<String> m = Mutex::new("hello");
ref<String, shared> r = &*lock(&m); // the guard ends at this semicolon
{
guard<String> g = lock(&m);
String::append(&mut *g, ", world");
}
printf("%v\n", StringView::len(r)); // ✗ diag.destroy-while-aliased: r outlived its guard
}Through a guard, a field or element of the locked value is reached directly, as through a
reference: g.count, g.items[0], Vec::push(&mut g.items, x) mean (*g).count and so on. *g
is how you name the whole value.
A mutex may also be a field: a struct holding one or more mutexes is shared by
reference like a bare one, each thread locking the field it needs (lock(&board.scores)). Each
mutex field is its own lock.
import std;
struct Stats
{
u32 hits;
Vec<u32> seen;
}
struct Board
{
mutex<Stats> stats;
mutex<u32> rounds;
}
fn play(ref<Board, shared> b, u32 me) : u32
{
{
auto g = lock(&b.stats); // one mutex field...
g.hits += 1; // g.hits is (*g).hits
Vec::push(&mut g.seen, me);
}
auto r = lock(&b.rounds); // ...and another, locked independently
*r += 1;
me
}
fn main()
{
Board b = Board { .stats = Mutex::new(Stats { .hits = 0, .seen = Vec::new() }), .rounds = Mutex::new(0: u32) };
{
auto x = spawn(play, &b, 1);
auto y = spawn(play, &b, 2);
assert(join(x) + join(y) == 3);
}
auto g = lock(&b.stats);
assert(g.hits == 2 && Vec::len(&g.seen) == 2 && *lock(&b.rounds) == 2);
}One integer between threads: Atomic
When all the threads share is one integer (a counter, a stop flag, a sequence number, a
running maximum) a mutex is more than it needs. Atomic<T> from std (std::sync, D-0249) holds an
integer of up to 64 bits that threads change with no lock: Atomic::new(v), then Atomic::load(&a),
Atomic::store(&a, v), Atomic::swap, Atomic::fetch_add and fetch_sub (with _wrapping forms),
fetch_and, fetch_or, fetch_xor, fetch_max, fetch_min, fetch_update, and
Atomic::compare_exchange(&a, expected, new). AtomicBool is the same for a flag. Every one
takes a shared reference, like lock, and each is indivisible: no increment is lost, and every
thread sees all the operations in one order (sequential consistency). The fetch_ functions give the
value they found.
An atomic operation costs more than a plain read or write: each is a point where every thread
agrees on an order, and the runtime keeps its bookkeeping for the object around it. Use atomics for
counters, flags and sequence numbers, not as the storage of a large shared array: a board of cells
each an Atomic<u8> was many times slower than giving each thread its own rows and exchanging the
edges under a mutex.
The integer itself is private to std, so it is never read or written any other way, and an
Atomic is a resource, so it is never copied. fetch_add faults on overflow as + does, and
leaves the value unchanged. State of more than one integer still belongs in a mutex: two atomics
updated one after the other can be seen half done.
import std;
fn worker(ref<Atomic<u64>, shared> hits, ref<AtomicBool, shared> stop) : u64
{
u64 mine = 0;
while (!AtomicBool::load(stop) && mine < 1000)
{
_ = Atomic::fetch_add(hits, 1); // no lock, no lost increment
mine += 1;
}
mine
}
fn main()
{
Atomic<u64> hits = Atomic::new(0: u64);
AtomicBool stop = AtomicBool::new(false);
u64 done = 0;
{
auto a = spawn(worker, &hits, &stop);
auto b = spawn(worker, &hits, &stop);
done = join(a) + join(b);
}
AtomicBool::store(&stop, true);
assert(Atomic::load(&hits) == done);
}compare_exchange replaces the value only if it is still the one you read, and otherwise
tells you what it found. That is the step under every lock-free update: read, compute, try, and
start again from what the other thread left.
import std;
fn note_max(ref<Atomic<u64>, shared> best, u64 x)
{
u64 seen = Atomic::load(best);
while (x > seen)
{
match (Atomic::compare_exchange(best, seen, x))
{
Ok(_) : seen = x, // ours went in
Err(now) : seen = now, // another thread got there first: compare again
}
}
}
fn main()
{
Atomic<u64> best = Atomic::new(0: u64);
{
auto a = spawn(note_max, &best, 17);
auto b = spawn(note_max, &best, 42);
join(a);
join(b);
}
assert(Atomic::load(&best) == 42);
}That loop is common enough that std has it: Atomic::fetch_max(&best, x) (and fetch_min).
Atomic::fetch_update(&a, f) is the general form: it calls f with the value it found, stores what
f gives (Some(new)) or leaves it (None), and starts again if another thread changed the value
in between, so f should compute only from its argument.
An atomic that the whole program shares need not be passed around at all: declared static
at the top level, it is reached by name from any function and any thread. Its first value is a
literal of its lane type (static Atomic<u64> HITS = 0;, static AtomicBool STOP = false;), and it
is used through a shared reference, &HITS; only atomics can be statics (spec/17 §1a′,
rule.module.static).
import std;
static Atomic<u64> HITS = 0;
fn count(u64 n)
{
for (u64 i = 0; i < n; i += 1)
{
_ = Atomic::fetch_add(&HITS, 1);
}
}
fn main()
{
{
auto a = spawn(count, 1000);
auto b = spawn(count, 1000);
join(a);
join(b);
}
printf("%v\n", Atomic::load(&HITS));
}2000
Waiting for an atomic to change
A loop that reads an atomic until it changes keeps a core busy. Atomic::wait(&a, v) sleeps
while a holds v instead, and returns once it holds something else; the thread that changes it
calls Atomic::notify_one(&a) (wake one waiter) or Atomic::notify_all(&a) after the change. A
notification can never be lost between the waiter's check and its sleep, and a waiter woken while the
value is still v simply waits again. With these an atomic is a latch, a semaphore or a one-shot
event. A wait that nothing can end is reported, as a deadlock is (diag.deadlock).
import std;
// A countdown latch: the main thread sleeps until every worker has finished.
fn work(ref<Atomic<u32>, shared> left, ref<Atomic<usize>, shared> total, usize n)
{
_ = Atomic::fetch_add(total, n * n);
if (Atomic::fetch_sub(left, 1) == 1) // the last one out
{
Atomic::notify_all(left);
}
}
fn main()
{
Atomic<u32> left = Atomic::new(4: u32);
Atomic<usize> total = Atomic::new(0: usize);
Vec<handle<void>> hs = Vec::new();
foreach (k in 1..5)
{
Vec::push(&mut hs, spawn(work, &left, &total, k));
}
while (true)
{
u32 n = Atomic::load(&left);
if (n == 0)
{
break;
}
Atomic::wait(&left, n); // sleeps until the count moves
}
assert(Atomic::load(&total) == 1 + 4 + 9 + 16);
while (Vec::len(&hs) > 0)
{
join(Option::unwrap(Vec::pop(&mut hs)));
}
}Three smaller tools complete the set. AtomicPtr<T> holds a rawptr<T> (load, store,
swap, compare_exchange) for lock-free structures over memory from allocate; storing and loading
addresses is safe, reading through them is unsafe as always. spin_hint() tells the processor a
loop is spinning (its pause instruction); call it in the body of a short polling loop. atomic_fence()
is a full fence, for raw, volatile and C memory only: CobaltC's own operations are already sequentially
consistent, so a program without unsafe never needs it.
fetch_add costs the same in every order; only
plain stores are dearer. Keeping one order is what lets --explore and the language's own rules
describe every thread's behaviour as an interleaving of steps.Meeting, counting, doing once: Barrier, Semaphore, Once
Three waiting patterns come ready-made in std::sync (D-0260), each an atomic or two and a wait
loop, shared by reference as a mutex is. A Barrier::new(n) is a meeting point: Barrier::wait(&b)
blocks until n threads have called it, then releases them together and is ready for the next round;
it answers true to the last thread to arrive, so one thread of each round can report. A
Semaphore::new(k) is k permits: acquire takes one, waiting while there is none, release gives one
back, so at most k threads are inside at once; made with 0 permits it hands events from one thread to
another, one release per acquire; try_acquire takes a permit only if one is free. A Once does
something exactly once, by whichever thread gets there first: Once::call(&o, f) runs f on the first
caller's thread, and every other call waits for that run to finish and then returns without running f.
Should f fault, the Once is as it was and the next caller runs f again.
import std;
fn phase(ref<Barrier, shared> b, ref<Semaphore, shared> slots, ref<Once, shared> setup, ref<Atomic<u32>, shared> inside, u32 id) : u32
{
Once::call(setup, [inside]() { Atomic::store(inside, 0); }); // one thread sets up; the rest wait for it
u32 peak = 0;
for (u32 round = 0; round < 3; round += 1)
{
Semaphore::acquire(slots); // at most two threads in here at once
peak = max(peak, Atomic::fetch_add(inside, 1) + 1);
_ = Atomic::fetch_sub(inside, 1);
Semaphore::release(slots);
if (Barrier::wait(b)) // everyone finishes the round before anyone starts the next
{
printf("round %v done\n", round); // the last to arrive says so
}
}
peak
}
fn main()
{
Barrier b = Barrier::new(4);
Semaphore slots = Semaphore::new(2);
Once setup = Once::new();
Atomic<u32> inside = Atomic::new(99: u32);
Vec<handle<u32>> hs = Vec::new();
for (u32 i = 0; i < 4; i += 1)
{
Vec::push(&mut hs, spawn(phase, &b, &slots, &setup, &inside, i));
}
u32 peak = 0;
foreach (h in hs)
{
peak = max(peak, join(h));
}
printf("never more than two inside: %v\n", peak <= 2);
}round 0 done round 1 done round 2 done never more than two inside: true
A barrier for more threads than will ever arrive, or an acquire no thread can release, is a
wait that cannot end, and the program reports diag.deadlock instead of hanging, as for any
Atomic::wait.
Passing values: Channel
A Channel<T> from std (std::sync) is a queue between threads, shared by reference as a mutex is.
Channel::new(cap) holds at most cap values (at least 1). Channel::send(&ch, v) moves v in,
waiting while the channel is full; Channel::recv(&ch) moves the oldest value out as Some(v),
waiting while it is empty. A value in a channel has one owner, the channel, so a String or a
Vec travels between threads without being shared or copied. A waiting thread uses no processor
time.
Channel::close(&ch) says nothing more is coming: the values already sent are still
received, and then recv gives None, which is what ends a receiver's loop. A send after
close does not lose its value: it gives it back as Err(v). Destroying a channel destroys the
values left in it, oldest first. The usual shape is a pool of workers: the main thread sends the
jobs, closes the channel, and joins the workers, each of which stops at None.
import std;
fn worker(ref<Channel<u64>, shared> jobs, ref<Channel<u64>, shared> results)
{
while (true)
{
match (Channel::recv(jobs))
{
Some(n) : Channel::send(results, n * n),
None : break, // closed and empty: this worker is done
}
}
}
fn main()
{
Channel<u64> jobs = Channel::new(4); // at most 4 jobs waiting at once
Channel<u64> results = Channel::new(16);
{
auto a = spawn(worker, &jobs, &results);
auto b = spawn(worker, &jobs, &results);
foreach (i in 1..11: u64)
{
_ = Channel::send(&jobs, i); // waits while the channel is full
}
Channel::close(&jobs); // the workers stop once it is empty
join(a);
join(b);
}
Channel::close(&results);
u64 total = 0;
while (Some(sq) = Channel::recv(&results)) // None once it is closed and empty
{
total += sq;
}
assert(total == 385); // 1 + 4 + … + 100, whichever worker did which
Channel<String> names = Channel::new(1);
Channel::close(&names);
match (Channel::send(&names, "late"))
{
Ok(_) : assert(false, "unreachable"),
Err(s) : assert(StringView::len(&s) == 4), // closed: the value comes back
}
}A wait that can never end because no other thread exists — the main thread receiving
from an empty channel, or sending to a full one, with no spawned thread running — is a fault,
diag.channel-deadlock. A wait among several threads that none of them can end (two threads each
receiving from the other's channel, locks taken in opposite orders) is diag.deadlock (§19's
Deadlock section).
import std;
fn main()
{
Channel<i32> ch = Channel::new(1);
_ = Channel::send(&ch, 1);
_ = Channel::send(&ch, 2); // ✗ diag.channel-deadlock: full, and no one to receive
}Without waiting for ever (D-0185). Channel::try_recv(&ch) answers at once:
Ok(Some(v)) a value, Ok(None) nothing there, Err(()) closed and empty — three answers, because a
loop that also watches a socket or interrupt_requested() must tell "nothing yet" from "the
senders are done". Channel::recv_timeout_ms(&ch, ms) waits at most ms milliseconds for the same
three answers. cpu_count() is how many threads the machine runs at once, the size to give a pool.
Owning a share: Arc
Everything above shares by reference, and a reference does not outlive its frame: a function that
spawns a worker over a local counter and returns the handle is refused (diag.reference-escapes-scope,
[Ref-Escape-Through-Facts], D-0340): the thread may still hold the reference when the frame ends,
as a reference returned through a binding (StringView w = &local; w) would. When a thread must outlive the frame that made what it shares — a pool of
workers, a server that hands its handle back — each thread owns a share instead: Arc<T> from
std::memory (D-0259) is Rc with atomic counts. Arc::clone(&a) (or clone(&a)) makes another handle
to the same value; handles move into threads and are dropped there, and the value is destroyed once, by
whichever handle ends last. Arc::get(&a) is a shared reference, so the value changes only through a
mutex or an Atomic inside it. Arc::downgrade gives an ArcWeak, which keeps the memory but not the
value, as Weak does for Rc.
import std;
struct Started
{
handle<u64> worker;
Arc<mutex<Vec<u64>>> log;
}
fn work(Arc<mutex<Vec<u64>>> log, u64 n) : u64
{
u64 sum = 0;
for (u64 i = 1; i <= n; i += 1)
{
sum += i;
auto g = lock(Arc::get(&log));
Vec::push(&mut *g, i);
}
sum
}
// Spawns a worker that shares the log, and returns both: the worker outlives this frame.
fn start(u64 n) : Started
{
Arc<mutex<Vec<u64>>> log = Arc::new(Mutex::new(Vec::new()));
handle<u64> h = spawn(work, clone(&log), n);
Started { .worker = h, .log = log }
}
fn main()
{
Started { worker, log } = start(10);
u64 sum = join(worker);
printf("sum %v, logged %v entries\n", sum, Vec::len(&*lock(Arc::get(&log))));
}sum 55, logged 10 entries
Arc carries no special bound on its value: whatever is inside is subject to the same
checks as anything reached through a shared reference. The one thing it cannot hold is an Rc: an Arc
whose value holds one is refused by spawn (diag.not-thread-safe), since two threads would update one
count that is not synchronised.import std;
fn churn(Rc<String> r) : usize
{
Rc<String> c = Rc::clone(&r);
StringView::len(Rc::get(&c))
}
fn main()
{
Rc<String> a = Rc::new("shared across threads");
handle<usize> h = spawn(churn, Rc::clone(&a)); // ✗ diag.not-thread-safe: an Rc's count is not atomic
printf("%v %v\n", join(h), StringView::len(Rc::get(&a)));
}fn value held in a parameter, a field or a Vec of callbacks has
captured, so a closure that captured an Rc and reaches spawn that way is accepted when compiled. It is
caught when it runs: an Rc or Weak remembers the thread that made it, and clone, get, downgrade,
dropping or upgrade in any other thread faults with diag.not-thread-safe ("an Rc made in another
thread"), so two threads never update one count. An Rc that a thread makes and ends itself is fine, and so is
an Arc anywhere.How threads run
Every CobaltC thread is a thread of the operating system. In a program built by cobc
they run at once, on as many cores as the machine has. The checks of §08 and §10 still run as the
program goes, in every thread, and two threads that use the same object meet in them: that is how
a conflict between threads is caught at the access that would have raced.
To keep threads from slowing each other down, the run-time checks keep each thread's records apart. What a thread makes, and what is moved into it, are its own; most checks on them involve no other thread. Where threads do meet:
- Data reached through a reference to another thread's (
spawn(f, &v)) stays the owner's, and each access through it is checked against the owner's records too. It works, and costs a little more on every access than data the thread owns. - Waiting — on
join, on alocksomeone else holds, on a full or emptyChannel— stops only the waiting thread, which spins briefly before it sleeps: most waits for a lock are short. Locking, sending and receiving involve no other thread's checks. - A block that only reads and writes through its guard (
{ auto g = lock(&m); *g += 1; }, plain data inside, no earlyreturn) costs a lock and an unlock and no guard object:cobcmakes none for it. The lock lives in the mutex's own state cells (its holder, whether a thread waits, whether it is poisoned): an uncontended lock and its unlock are one compare-and-swap each plus the thread's note of what it holds, which is what finds deadlocks and poisons a failed thread's mutexes; about 30 ns a lock, against 11 ns for C'spthread_mutex_lockand unlock. - Running code of the program on a value's end — a destructor you wrote, a
fnvalue, aBox— briefly pauses the other threads' checks. Everything else the runtime does at a block's end stays within the threads involved.
So the program that runs fastest in parallel gives each thread its work: move a chunk of the
data into the thread (an argument it takes by value, which then belongs to it) and hand the result
back through join or a Channel. The performance chapter's Threads
section has the figures.
import std;
fn total(Vec<u64> chunk) : u64
{
u64 t = 0;
foreach (x in &chunk)
{
t += *x;
}
t
}
fn main()
{
Vec<handle<u64>> hs = Vec::new();
foreach (k in 0..4: u64)
{
Vec<u64> chunk = Vec::new(); // made here, then moved into its thread
foreach (i in 0..1000: u64)
{
Vec::push(&mut chunk, k * 1000 + i);
}
Vec::push(&mut hs, spawn(total, chunk)); // `chunk` now belongs to that thread
}
u64 sum = 0;
while (Vec::len(&hs) > 0)
{
sum += join(Option::unwrap(Vec::pop(&mut hs)));
}
assert(sum == 7998000); // 0 + 1 + … + 3999
}The guarantee
What a program without unsafe can rely on, however its threads are timed (rule.conc.guarantee):
- No data races. Two threads never touch the same storage at once with one of them writing. Either something orders the two accesses (a
join, a mutex's lock, a value sent and received), or the second access isdiag.aliasing-conflict. - One step at a time. Every run is some interleaving of the threads' steps, each step whole: a thread never sees half of another's write, and there is no reordering to reason about.
- Nothing undefined. An access that is not allowed is a diagnostic, in every interleaving.
A reference passed to spawn belongs to the new thread from the moment of the spawn, until
the thread ends, even before it has run a single step. Timing can still choose between two permitted
outcomes: a thread that has already finished holds nothing, so an access that would have conflicted
with it while it ran is fine afterwards. Use join (or a channel) to make the order part of the
program. Deadlock is not ruled out, but it is reported rather than left to hang (below).
How the guarantee is checked: beyond the test suites, a separate program,
cobmodel (impl/model), runs a fragment of the language straight from the rules, with every
interleaving of its threads, and lists every outcome they allow. Tens of thousands of generated
programs about references, threads, mutexes, channels and vectors of references have been compared
with what cobc --explore does, and the project's gate compares a sample of them on every change.
This is evidence, not a proof: it covers that fragment, up to the program sizes it tried. You can run
it on your own small programs too: Every schedule, from the rules:
cobmodel, below.
import std;
fn bump(ref<i64, exclusive> x, ref<Channel<u8>, shared> go)
{
_ = Channel::recv(go); // waits, holding x
*x += 1;
}
fn main()
{
Vec<i64> v = Vec::filled(4, 0: i64);
Channel<u8> go = Channel::new(1);
{
auto h = spawn(bump, &mut v[0], &go);
i64 other = v[1]; // fine: another element
i64 same = v[0]; // ✗ diag.aliasing-conflict: the thread holds v[0]
_ = Channel::send(&go, 1);
join(h);
}
}An exclusive reference belongs to one thread. Copying a ref<T, exclusive>
copies one path, and two copies in two threads would be two writers no check could tell apart. So
spawn and Channel::send lend each exclusive reference they hand over: the thread gets a path
of its own, borrowed from yours, and your copy conflicts with it until that thread is done with it.
Lending the same reference to two threads at once is diag.aliasing-conflict, and so is writing through
your copy while it is lent. A thread may use an exclusive reference only if it was handed it this way:
one it finds inside a struct it was lent, inside a Vec moved to it, or inside a mutex belongs to the
thread that made it, and using it faults while that thread runs. To give a thread exclusive access to
something, pass the reference to spawn or send it through a channel.
fn bump(ref<i32, exclusive> a)
{
*a += 1;
}
fn main()
{
i32 x = 0;
ref<i32, exclusive> r = &mut x;
auto h1 = spawn(bump, r); // r is lent to this thread until join(h1)
auto h2 = spawn(bump, r); // ✗ diag.aliasing-conflict: r is lent already
join(h1);
join(h2);
}When a thread fails
A checked fault in a thread you spawned ends that thread: it unwinds, its destructors run, the threads it started are stopped and waited for (cancelled, then joined; what they report, their own fault or the cancellation, is discarded), and its result becomes the failure — its own, never one of theirs. The rest of the program goes on. This is what lets a server give each connection a thread and survive a bug in one of them. Nothing continues in a state the failed check protected:
- A mutex the thread held is poisoned. Its interior may be half-changed, so the next
lockof it faults withdiag.mutex-poisoned. The poison goes with the mutex: moved to another binding or into a struct's field, it stays poisoned, while a mutex made later in the same storage starts unlocked (D-0310). - A thread lent an exclusive reference is not contained. Given one at
spawn, or by locking a mutex whose contents can hold one (receiving from aChannelof&mutreferences, say), it may be changing data that belongs to a thread still running, so its fault ends the program at once, as a fault always did. - The main thread's fault ends the program, as before.
Nobody has to ask for this. join(h) of a failed thread raises its failure again in the joiner,
and so does the handle's end if nobody joined it: a program that never looks at failures still fails
as a whole, one scope at a time. To take a failure as a value, use try_join(h), which returns
Result<R, ThreadFailure>. ThreadFailure::text is the report the program would have printed,
diagnostic its diag.… name. is_finished(&h) says, without waiting, whether a thread has ended,
so one loop can accept new work and collect the threads that are done.
import std;
fn handler(usize i) : u64
{
Vec<u64> v = Vec::filled(3, 7: u64);
v[i] // a bug when i >= 3
}
fn main()
{
usize served = 0;
usize failed = 0;
foreach (i in 0..5)
{
match (try_join(spawn(handler, i)))
{
Ok(_) : served += 1,
Err(f) :
{
String d = ThreadFailure::diagnostic(&f);
assert(d == "diag.index-out-of-bounds");
failed += 1;
},
}
}
assert(served == 3 && failed == 2); // the program went on after both
}import std;
fn handler(usize i) : u64
{
Vec<u64> v = Vec::new();
v[i]
}
fn main()
{
auto h = spawn(handler, 0);
join(h); // ✗ diag.index-out-of-bounds (dynamic): raised again here
}import std;
fn update(ref<mutex<i64>, shared> m, usize i)
{
auto g = lock(m);
*g += 1;
Vec<i64> v = Vec::new();
*g += v[i]; // faults while holding the lock
}
fn main()
{
mutex<i64> m = Mutex::new(0: i64);
_ = try_join(spawn(update, &m, 0));
auto g = lock(&m); // ✗ diag.mutex-poisoned (dynamic): *g may be half-updated
}Stopping a thread: cancel
cancel(&h) asks a thread to stop. Its current wait, or its next one, ends with the fault
diag.thread-cancelled, contained like any other: the thread unwinds and its result is that
failure. The waits are join, lock, a channel's send and recv, sleep_ms, every socket
operation, and a read of standard input that waits for its next line (read_line, stdin_read), so
a handler blocked reading a client that never writes, or a thread waiting for a key, can be stopped.
A thread that never waits finishes its work, and one inside another call outside the program (a
file, a child process) is stopped at its next wait. A supervisor cancelled while it waits in join
cancels the thread it was joining too, and waits for it. A thread cancelled while it holds a guard unwinds like a
faulting one: the mutex is poisoned, since what it was changing may be half-changed. ThreadFailure::is_cancelled tells a cancellation from a bug, and a
handle whose thread you cancelled raises nothing when it ends. Together with a channel this is
"first answer wins" without a select: start one thread per source, all sending to one channel,
take the first value, and cancel the rest.
import std;
fn listen(ref<Channel<u8>, shared> c) : u8
{
Option::unwrap_or(Channel::recv(c), 0) // nobody ever sends
}
fn main()
{
Channel<u8> c = Channel::new(1);
auto h = spawn(listen, &c);
cancel(&h); // its wait ends at once
match (try_join(h))
{
Ok(_) : assert(false),
Err(f) : assert(ThreadFailure::is_cancelled(&f)),
}
}Deadlock
A wait that can never end is diag.deadlock, reported where it happens. A thread whose
join or lock would close a cycle (it waits on a thread that, through holders and joins, waits on
it) faults at once. And when every thread is waiting on another thread, a mutex or a channel, with
none on the clock, a socket or input, the runtime faults one thread of a cycle, or, if there is no
cycle, the threads at the ends of the chains of waits (those waiting on a channel); the threads
waiting on them then get the failure through join, or find the mutex poisoned. The result does
not depend on timing. A channel wait while some thread is in a socket call or asleep is never
called a deadlock: that thread may send when its call returns. Give such a wait a limit
(recv_timeout_ms) or cancel it from a supervisor. Like any fault in a spawned thread it is contained, so two deadlocked handlers in
a server are reported and the server goes on. (The main thread waiting alone on a channel is still
diag.channel-deadlock.)
import std;
fn waits(ref<Channel<u8>, shared> c)
{
_ = Channel::recv(c); // nobody will send
}
fn main()
{
Channel<u8> c = Channel::new(1);
auto h = spawn(waits, &c);
join(h); // ✗ diag.deadlock (dynamic): every thread waits, none can go on
}Exploring schedules: --explore
A result that depends on timing is easy to miss: the timing you test is rarely the one that
goes wrong. cobc --explore N prog.cb compiles the program once and runs it N times, each under a
different order of its threads chosen by a seed, and groups the runs by outcome (output and exit
status). One outcome is what you want; more than one means the program's result depends on timing,
and cobc exits with 1. Each outcome comes with a seed, and cobc --schedule-seed S prog.cb replays
that run exactly, as often as you need to find out why; so does setting COBALTC_SCHEDULE_SEED=S in
a compiled program's environment. Under a schedule the threads take turns one at a time, so
exploration needs no cores and finds orders a parallel run would rarely produce. The first outcome
shows its first eight lines of standard output and three of standard error; each other outcome shows
its lines from the first one where it differs from the first outcome's, and a cut says how many
lines are left out. A run that does not end within ten seconds, or ten times the slowest run that
ended, is stopped and reported as an outcome of its own ("did not end in time"), with its seed; the
replay command repeats --unittest (and its filter) when the tests were explored.
A thread keeps its turn between the points where threads interact -- a spawn, a wait, a mutex
released, a call outside the program -- and now and then between two of the program's checks, which
is where a program whose checks all pass can end differently. A thread that is asleep or in a socket
or input call leaves the schedule until the call returns, so a program that talks to the network explores only
the orders around those calls.
import std;
fn bump(ref<mutex<i64>, shared> m)
{
i64 seen = 0;
{
guard<i64> g = lock(m);
seen = *g;
}
guard<i64> g = lock(m);
*g = seen + 1; // a lost update when the other thread ran in between
}
fn main()
{
mutex<i64> m = Mutex::new(0: i64);
{
auto a = spawn(bump, &m);
auto b = spawn(bump, &m);
}
auto g = lock(&m);
printf("total %v\n", *g);
}$ cobc --explore 50 counter.cb
explored 50 schedules of counter.cb: 2 distinct outcomes
32 runs, exit 0 -- replay: cobc --schedule-seed 1 counter.cb
| total 2
18 runs, exit 0 -- replay: cobc --schedule-seed 2 counter.cb
| total 1Every schedule, from the rules: cobmodel
cobc --run shows what one run did, and cobc --explore N what N schedules did. Neither
can tell you that there is no other outcome: --explore samples, and an order that happens once in a
few hundred schedules is easy to miss with a few dozen. And both are the implementation answering for
itself: the static pass that accepted the program and the runtime that checked it are the ones being
asked. cobmodel answers a different question: what do the specification's rules allow this
program to do, over every schedule?
It is an executable model of the rules this section and §08, §10 and §14 describe, for a
fragment of the language (D-0219). It was written from the specification alone, in CobaltC,
importing std and nothing of the compiler or its runtime (D-0326), so where it and cobc agree,
two readings of the text agree, not one program with itself. It applies the static rules as the
text tabulates them (the flow analysis of spec/14 §6, the escape and last-use rules); for a
program they accept, it runs every interleaving of the threads, one step at a time, by the dynamic
rules (spec/04's state, [Read], [Write], [Borrow], the lending to threads, locks, channels,
atomics and deadlock), merging states it has seen; and it lists every outcome it reached. So it is
also a second implementation of the rules, though not of the language, and the conformance suite's
complement: a conformance case fixes the expected outcome of one program somebody wrote down; the
model computes the outcome set of any program in its fragment, including ones nobody wrote, which
cobmodel enum generates by the thousand. That is how it found gaps in the text, among them a
reference that was proven free of conflicts while a closure still held it (D-0219, D-0243), and bugs
in the tools that the test suites had not.
| The question | The command |
|---|---|
| Is the program accepted? | cobc --check prog.cb |
| What does one run do? | cobc --run prog.cb |
| What do N schedules do, each with a seed to replay? | cobc --explore N prog.cb |
| Does the build with every check kept behave the same? | cobc --all-checks --run prog.cb |
| What do the rules allow, over every schedule? | cobmodel check prog.cb (the fragment only) |
| Does the compiler's static decision hold in every schedule? | cobmodel certify cert.txt prog.cb (the fragment only) |
Here is a program whose result depends on timing in a way a short exploration does not
show. It lends x to a thread through a channel and then writes x: a conflict while the thread
holds the reference, and fine once the thread has finished, since a finished thread holds nothing
(The guarantee, above).
import std;
fn add_hundred(ref<Channel<ref<i32, exclusive>>, shared> ch)
{
match (Channel::recv(ch))
{
Some(r) : { *r = *r + 100; },
None : {},
}
}
fn main()
{
i32 x = 1;
Channel<ref<i32, exclusive>> c = Channel::new(1);
auto t = spawn(add_hundred, &c);
_ = Channel::send(&c, &mut x); // x is lent to the thread
x = 5; // ...which may still hold it
join(t);
printf("%v\n", x);
}$ cobc --explore 8 lend.cb
explored 8 schedules of lend.cb: 1 distinct outcome
8 runs, exit 1 -- replay: cobc --schedule-seed 1 lend.cb
! fault[diag.aliasing-conflict]: this access conflicts with a live reference
! --> lend.cb:18:5
! |
! ... 3 more lines
$ cobmodel check lend.cb
lend.cb: 2 outcome(s), 442 states
diag.aliasing-conflict (dynamic) line 18
[5] okEach outcome is one line: the lines the program printed, in brackets and joined by spaces
(none here for the fault), then how it ended: ok, or the diagnostic, (static) for one found
before the run and (dynamic) for a fault, and its line. cobc --explore 300 lend.cb does find the
second outcome, in 5 of its 300 schedules (--schedule-seed 46 replays one). The model's two
outcomes say the program is wrong whichever you saw: the result depends on timing. Moving
join(t); before the write makes it one outcome, and cobmodel check then says
1 outcome(s), 376 states and [106] ok for x = x + 5; after the join.
--witness prints, under each outcome, one schedule that reaches it, as the steps of the
model's machine: the thread (t0 is main), the function and step, the source line and the step's
action. Read it for the order in which the threads' source lines ran. Cut to the lines that matter,
the schedule for [5] ok is the thread running to its end between the send on line 17 and the
write on line 18:
$ cobmodel check --witness lend.cb
…
[5] ok
…
t0 main:29 line 17 ChanSend
t12 add_hundred:4 line 5 ChanRecv
…
t12 add_hundred:19 line 7 Assign
…
t12 add_hundred:33 line 10 Ret
t0 main:30 line 17 Read
…
t0 main:37 line 18 Assign
…When to use it, and when not
- A threaded result that surprised you, or one you want to be sure is the only one. Cut the program down to the fragment around the threads and references involved and ask the model for the whole set;
--witnessshows how each outcome comes about, andcobc --schedule-seedreplays a run of it that--explorefound. - Is it the compiler or the rules? Every outcome
cobcshows, with any C compiler and with--all-checks, must be in the model's set. One outside it is a bug incobcor in the model, worth a report with both outputs; one inside it is what the rules allow, and its witness shows the schedule that leads to it. - Learning the rules. A small program and its witnesses show exactly when a reference starts and stops conflicting, when a lent place comes back, and where a wait can never end.
- Not for running programs. The fragment is small:
i32values with+and>, references to them, two structs with fixed names (Hold, holding an exclusive reference, andJob, holding a handle),Vecs ofi32, of exclusive references and of handles, two-element arrays, slices, closures,mutex<i32>, channels of exclusive references,Atomic<i32>and atomic statics,if,while,matchon anOptionandprintf("%v\n", e), and functions of your own over those types.impl/model/README.mdlists it exactly. A program outside it is refused, with exit status 2 and a message naming the line where the model stopped reading: for a parameteru8 b, that the typeu8is outside the fragment; for a locali64 x = 1;or aforloop, only the token it did not expect. - Not for large programs. Every interleaving is explored, so the work grows quickly with threads and steps: the 315 programs of the project's sample take about five seconds together, but three threads that each lock a mutex and add to it reach the model's limit of 3,000,000 states in about 45 seconds, and the set then includes the outcome
too-big: incomplete, not wrong. - Not a proof. It covers the program you give it, in the fragment. What it establishes beside the proofs, the certificate and the test suites is in
spec/ASSURANCE.md.
Using it on a directory, in tests and in CI
cobmodel compare DIR runs every .cb file of a directory under cobc and under the model
and reports each program a tool gave an outcome outside the model's set (OUTSIDE, exit status 1),
each program with a model outcome no tool showed (unobserved: advisory, since the tools try a few
schedules and the model all of them), and each program whose set was cut short at the state limit
and a tool went beyond it (truncated: advisory). --cobc PATH names the compiler (by default
cobc from PATH), --explore N runs each program under N schedules rather than once, --cc CC
(repeated) picks the C compilers (by default GCC and Clang), --jobs J runs J programs at once (by
default 2) and --report FILE writes the report there instead of to standard output:
$ cobmodel compare progs --explore 8
unobserved progs/lend.cb: [5] ok
compare: 4 programs, 0 with an outcome outside the model's set, 0 beyond a set cut short at the state limit, 1 with a model outcome no tool showedA program can carry its expected set in its header, one // MODEL: outcome line per outcome
as cobmodel check prints them; compare then also reports header-stale for a program whose
lines no longer match the model's set (advisory: the exit status stays 0, so a CI step that wants it
to fail greps the report for it). That makes a directory of small programs with their headers a test
of both directions: a change to cobc that gives an outcome the rules do not allow fails, and a change
to the rules that changes a set shows in the headers.
cobmodel statics prog.cb gives the static verdict alone, without running anything
(alias.cb: diag.aliasing-conflict (static) line 12, or ok), to set beside cobc --check's.
And cobc --certificate cert.txt prog.cb followed by cobmodel certify cert.txt prog.cb checks the
compiler's decision about which function bodies need no record of their references
(Performance): it runs every interleaving with those bodies kept unrecorded, as
the compiled program keeps them, and reports a fault there as model.decided-but-false, or a
different static verdict, with exit status 1; otherwise it says, for instance, certified: the whole
program decided, 2 outcome(s), 5747 states. cobmodel check itself exits with 0 whatever outcomes
it lists, 2 when a file cannot be read or is outside the fragment.
The project runs all of this whenever the compiler, the runtime, std or the model
changes: the gate's model unit compares impl/model/sample (the hand-written cases, every program
that ever disagreed, and a selection of the enumeration) with cobc --explore 8 under GCC and Clang,
checks each sample program's certificate (impl/tools/certify_model.py), runs cobmodel check
--as-licensed (which also models what the flow table lets a compiler leave out, D-0241), and
replays the model's runs through the mechanised rules in proofs/ (cobmodel trace,
impl/tools/replay_model.py). For a wider sweep, cobmodel enum --size 3 --out DIR --max 3000
writes every program of up to three statements over its alphabet, with its // MODEL: lines, and
--random M --len L --seed S adds M random ones of L statements; impl/model/README.md gives the
commands.
Data parallelism: slice_parts
slice_parts(&mut v, k) splits a vector (or any exclusive slice) into k consecutive
runs as nearly equal as they can be, each an exclusive slice of its own. Give each run to a thread
and the threads write one vector at once, with no lock: the runs are disjoint, and the checker
proves it the way it proves any two ranges apart. The vector is usable again once every thread is
joined. A thread takes a named function here, not a closure: a closure is passed by move (§15), so it
goes to one thread, and one closure cannot run in several threads at once.
import std;
fn square_all(slice<u64, exclusive> s)
{
for (usize i = 0; i < slice_len(s); i += 1)
{
s[i] = s[i] * s[i];
}
}
fn main()
{
Vec<u64> v = Vec::new();
foreach (i in 0..1000: u64)
{
Vec::push(&mut v, i);
}
{
Vec<slice<u64, exclusive>> parts = slice_parts(&mut v, cpu_count());
Vec<handle<void>> hs = Vec::new();
while (Vec::len(&parts) > 0)
{
Vec::push(&mut hs, spawn(square_all, Vec::swap_remove(&mut parts, 0)));
}
foreach (h in hs)
{
join(h);
}
}
assert(v[999] == 998001);
}What is not provided
No memory orderings weaker than sequential consistency (an Atomic is the one lock-free
tool, above), no condition variables, no thread-local storage. Steps of different threads interleave at
the granularity of single operations and every operation sees a consistent state; a join, a
lock, a send or a recv that cannot proceed simply waits. Rc<T> is not thread-safe, and the
checker keeps it in its thread: spawn refuses an Rc or a Weak, or any value that holds or reaches
one, as an argument, a result or a capture (diag.not-thread-safe, spec/19 [Thread-Confined]); one that
reaches another thread by a route the checker cannot follow (a closure held as a plain fn value, a
Channel) faults the first time that thread uses it. Across threads, share a mutex by
reference, pass values through a Channel, or own a share with an Arc.
There is no read-write lock and no condition variable.
--explore or
--schedule-seed (above) they take turns, one at a time. A program that follows the rules gets the
same result either way. Where the language leaves an outcome to timing — writing a variable while
another thread may still be reading it through a reference is diag.aliasing-conflict if the thread
is still running, and fine if it has finished — each run is free to show either permitted outcome,
and two runs may differ.- Every thread has an owner: the handle. Join it explicitly to get the result; let scope end join it if you do not care.
- Supervise threads that may fail:
try_jointakes the failure as a value;cancelthe ones you no longer need. - Lend a thread exclusive access to your data only when its failure should end the program; otherwise move the data in.
- Share a
mutexby shared reference; keep each guard in the smallest block that needs it. - To hand values from thread to thread, send them through a
Channel;closeit when the last value is sent. - Move data into a thread with a
moveclosure or by-value arguments; lend it with references only when the mutex rule allows.
§20Unsafe, raw pointers and FFI
spec/20-trust-boundaries.mdunsafe blocks record what you assert; rawptr, reclaim, allocate and extern fn are the only doors to the outside.
Everything so far is checked. This section is about the doors to the outside world:
raw addresses, manual allocation and foreign functions. CobaltC does not pretend those can be
checked; instead it makes the boundary explicit. Each trusted operation is only legal inside an
unsafe { } block, and the block is your signed statement that the operation's preconditions
hold.
unsafe blocks
unsafe { … } is an ordinary block (it has a value, it opens a scope) with one extra
permission: the trusted operations listed below may appear inside it. Outside, they are rejected
with diag.trusted-outside-unsafe. Nothing else changes: the aliasing, ownership and initialisation
rules still apply to every ordinary access inside an unsafe block.
| Operation | What you assert |
|---|---|
*p (read) / *p = v (write) for p : rawptr<T> | p addresses sizeof<T>() initialised bytes of a T, no live reference reaches them, and no other thread is writing them |
p + n (pointer offset, n : isize) | the result stays within, or one past the end of, one allocation or object |
reclaim<T>(p) | the bytes at p hold a valid T that no ordinary object owns; you now treat them as an object |
release(p, n), copy_raw(dst, src, n), deallocate(p, n, align) | the ranges are valid and nothing live overlaps them; deallocate matches one earlier allocate |
an unsafe extern fn declaration | the linked code has a function of this name with exactly this signature |
a call to an unsafe extern fn | the foreign code honours its signature and touches only what the pointer arguments reach |
Who asserts what
The standard library's own bodies use unsafe: Vec::push writes an element through a raw
pointer, File::write calls the operating system, Rc::clone reclaims its box. Those blocks are not
yours. They belong to the implementation, which must keep every one of them true to conform, and the
specification lists each of them with the fact that makes it hold (spec/21 §0, "What std asserts":
for Vec::push, that len < cap after grow and that no element object was ever established in the
slot). So a program that writes no unsafe of its own has the language's guarantee unconditionally,
and the guarantee is lost only by a false claim in a block the program itself wrote.
Raw pointers
rawptr<T> is an address. It has no mode, no lifetime, and no checks; it is plain and
copyable. Getting one is safe: rawptr_of(&x) (or rawptr_of(&mut x)) takes the address of a
place, and reinterpret_ptr<U>(p) changes the pointee type without changing the address. Using one
to reach memory is trusted.
import std;
fn read_through(rawptr<i32> p) : i32
{
unsafe
{
*p // trusted: the caller passed a pointer to a live i32
}
}
fn main()
{
i32 x = 7;
assert(read_through(rawptr_of(&x)) == 7);
auto bytes = [1: u8, 2: u8, 3: u8];
rawptr<u8> b = reinterpret_ptr<u8>(rawptr_of(&bytes));
unsafe
{
assert(*(b + 2) == 3); // pointer offset, in units of the pointee size
}
}fn bad(rawptr<i32> p) : i32
{
*p // ✗ diag.trusted-outside-unsafe
}
fn main()
{
i32 x = 1;
bad(rawptr_of(&x));
}An address can also be an integer, and an integer an address: rawptr_address(p) gives a
usize, to print, align or keep, and rawptr_from_address<T>(a) makes a pointer from one. The second is
how a program names a device register or memory it mapped itself; nothing checks what lives at a, so
both are written inside unsafe. With the volatile accesses below, that is memory-mapped I/O.
import std;
fn main()
{
unsafe
{
// A device's registers at a fixed address: a status word four bytes past the base.
rawptr<u32> uart = rawptr_from_address<u32>(0x1000_0000);
write_volatile(uart + 1, 0x80);
u32 status = read_volatile(uart + 1);
printf("%v %v\n", status, rawptr_address(uart + 1));
}
}From raw bytes back to objects: reclaim
Raw memory is not an object until you say it is. reclaim<T>(p) is a place
expression: it establishes (or re-attaches to) an object of type T over the bytes at p, and
from then on every ordinary rule applies to it. You can borrow it (&reclaim<T>(p)), assign to
it, or drop it. Reclaiming the same address twice gives the same object, so two references
obtained that way are checked against each other like any two references. This is how Vec
hands out references to its elements.
import std;
fn main()
{
Vec<i32> v = Vec::new();
Vec::push(&mut v, 7);
auto p = rawptr_of(&v[0]); // the element's address; obtaining it is safe
unsafe
{
auto r = &reclaim<i32>(p); // a checked reference to the element, via its address
assert(*r == 7);
}
}Manual allocation
allocate(n, align) returns Result<rawptr<u8>, AllocError>: fresh uninitialised bytes,
or Err. It is safe to call (failure is a value). deallocate(p, n, align) gives them back and is
trusted. A resource written into raw memory with *p = v moves there and is tracked; reading
*p of a resource type moves it back out. Plain data that holds references is tracked too: the cells
it is written to hold those references, exactly as a variable would, until they are released. The
library's Vec::grow in §21 is the reference example of the whole pattern.
When a promise is false
An unsafe block's promises are not checked; that is what makes them promises. If one is
false — *p reads bytes that are not a valid T, reclaim claims cells another object owns, a
foreign function writes past what it was given — the program has left the language's rules at that
step. Everything it did before that step happened exactly as the rules say. From that step on, no
rule says what happens: the program may carry on, print nonsense, fault, or crash, and every one of
those is allowed. None of the guarantees in this guide — no use after free, no data race, no
out-of-bounds access — covers what comes after. A program with no unsafe block makes no promises,
so they cover all of it.
struct Holder
{
Vec<i32> v;
}
fn main()
{
Holder h = Holder { .v = Vec::new() };
rawptr<Vec<i32>> p = reinterpret_ptr<Vec<i32>>(rawptr_of(&h));
unsafe
{
auto taken = *p; // false promise: h still owns these bytes
}
h.v = Vec::new(); // from the line above on, no rule applies
}The tools do not have to notice a broken promise, and in general they cannot. When one does,
it is encouraged to stop with a diagnostic rather than crash, since a report names the problem and a
crash does not; but that is a courtesy, not a rule. Keep unsafe blocks small, so that what each one
promises can be read and checked by eye.
Foreign functions
unsafe extern fn name(params) : ret; declares a function provided from outside. Parameters and
result may only be integers, floats, bool, void, rawptr<T> and plain structs of those (below);
anything else, such as a ref, a String or an enum, is rejected (diag.extern-non-ffi-type), and the
message names the field that is the problem. The declaration itself says unsafe:
no tool can check that the C function really has that name and exactly those
types, and if it does not, every call is wrong, so the promise is marked where it is made, where a
search for unsafe finds it. Without unsafe the declaration is a syntax error. Calling it needs
unsafe too, for what the function does. Its result
is a claim: a genuine value of its declared type, but one whose relationship to anything
else (that a returned length is right, that a pointer is valid) is not established until your code
checks it. An extern fn is only ever called, never passed as a function value: calling a value
needs no unsafe, so the promise would have nowhere to be written.
A C function with a variable argument list is declared as C declares it, with ... after its fixed
parameters: unsafe extern fn snprintf(rawptr<u8> buf, usize n, rawptr<u8> fmt, ...) : i32;. cobc
declares it to C with ..., so every call follows the platform's convention for a variable argument
list (on x86-64 a double travels in a vector register, and the callee is told how many), whether
the function is the C library's (printf, strfmon, open, ioctl, …) or your own C code's. A call
passes the fixed arguments, of their declared types, and then any number of others, each of the type
its own text gives it (a literal's own, i32 or f64; widen<i64>(n) for a long) and each of the
types a parameter may have (a plain struct passes by value), which C promotes as it promotes any
variable argument (float to double, bool and integers narrower than int to int); anything
else is diag.extern-non-ffi-type ([Extern-Call-Variadic], [Extern-Call-Variadic-Arg]). The type of each argument must be the one the format or the function
expects, as in C: nothing checks it. A declaration without ... is a fixed prototype, which is the
wrong call for a variadic function; for the C library's variadic functions cobc knows (the printf
and scanf families, open, fcntl, ioctl, strfmon, error, syscall, …) a declaration without
... is refused, diag.extern-variadic-without-ellipsis, and the message says to add ...
([Extern-Variadic-Without-Ellipsis], D-0339).
std declares two externs: stdout_write(rawptr<u8> buf, usize len) : isize, which
printf (§21) writes through, with the unsafe block inside std, and its counterpart
stdin_read, which read_line reads through. Calling conventions and how code is linked are outside the language
and documented by each implementation; a program names the C code it needs with extern "…";
(below).
cobc calls real C functions, on x86-64 Linux and on Windows: an unsafe extern fn names a
function in the C library or the maths library by its declared name, and any FfiType crosses, pointers
and structs included.
import std;
unsafe extern fn sqrt(f64 x) : f64; // from the maths library
unsafe extern fn labs(i64 x) : i64; // from the C library
unsafe extern fn toupper(i32 c) : i32;
fn main()
{
f64 root = unsafe
{
sqrt(2.0)
};
assert(root * root > 1.9999 && root * root < 2.0001); // a claim, checked before it is trusted
i64 distance = unsafe
{
labs(3 - 10)
};
assert(distance == 7);
assert(unsafe { toupper(99) } == 67); // 'c' -> 'C'
}import std;
fn main()
{
auto msg = b"Hi\n"; // a byte-array literal: array<u8, 3>
rawptr<u8> p = reinterpret_ptr<u8>(rawptr_of(&msg));
isize written = unsafe
{
stdout_write(p, 3) // the extern call; its result is a claim about how much was written
};
}Hi
import std;
unsafe extern fn takes_vec(Vec<i32> v); // ✗ diag.extern-non-ffi-type: a Vec cannot cross the boundary
fn main()
{
}Your own C code
extern "…"; names C or assembly code for the compiler to link, so that the program's unsafe extern fn
declarations can be found in it. It can go anywhere an item can, declares no name, and can be
repeated; each piece of code is linked once. The program still builds with nothing but
cobc main.cb.
| Written | Links | Notes |
|---|---|---|
extern "./shapes.c"; | a C source file | compiled on its own, with the C compiler's warnings shown |
extern "./cpu.S";, extern "./cpu.s"; | an assembly file | assembled by the C compiler; .S is preprocessed first, so #ifdef _WIN32 can pick the calling convention |
extern "./lib/fast.o";, extern "./lib/libfast.a"; | an object file or static library | linked as it is |
extern "./lib/libplugin.so"; | a shared library | found wherever the program is run from |
extern "z"; | an installed library | as cc -lz |
A string beginning ./, ../ or / is a file, and a relative path is relative to the
file it is written in, exactly as in module m "./m.cb";. So a module that wraps some C code can
name it next to itself, and every program that uses the module gets it linked. Anything else is a
library name. A missing file or library is reported at the line that names it.
The usual shape is a module that keeps the unsafe calls to itself and exports safe
functions. Two things make the wrappers below safe. First, rect_area takes u8 sides, so the
product always fits in the C function's int32_t. Second, first_squares lets the C function fill
storage that comes from allocate, because a C function may write only outside the program's live
objects (§20's rule for extern calls); the count it returns is a claim, checked before it is used,
and the values are copied into a Vec.
import std;
module geometry "./geometry.cb";
fn main()
{
printf("%v", geometry::rect_area(6, 7));
printf("\n");
Vec<i64> sq = geometry::first_squares(5);
foreach (x in &sq)
{
printf("%v ", x);
}
printf("\n");
}42 0 1 4 9 16
import std;
extern "./shapes.c"; // relative to this file
unsafe extern fn area(i32 w, i32 h) : i32;
unsafe extern fn squares(rawptr<i64> out, i64 n) : i64;
// u8 sides: the product always fits the C function's int32_t.
export fn rect_area(u8 w, u8 h) : i32
{
unsafe { area(widen<i32>(w), widen<i32>(h)) }
}
// C fills storage from allocate; the count it returns is checked,
// then the values are copied out.
export fn first_squares(u8 n) : Vec<i64>
{
Vec<i64> out = Vec::new();
usize bytes = widen<usize>(n) * sizeof<i64>();
rawptr<u8> raw = match (allocate(bytes, alignof<i64>()))
{
Ok(p) : p,
Err(_) :
{
return out;
},
};
rawptr<i64> buf = reinterpret_ptr<i64>(raw);
i64 written = unsafe { squares(buf, widen<i64>(n)) };
if (written >= 0 && written <= widen<i64>(n))
{
foreach (i in 0..narrow<usize>(written))
{
Vec::push(&mut out, unsafe { *(buf + reinterpret<isize>(i)) });
}
}
unsafe
{
deallocate(raw, bytes, alignof<i64>());
}
out
}#include <stdint.h>
int32_t area(int32_t w, int32_t h)
{
return w * h;
}
// Fills out[0..n) with the first n squares; returns how many it wrote.
int64_t squares(int64_t *out, int64_t n)
{
for (int64_t i = 0; i < n; i++)
{
out[i] = i * i;
}
return n;
}A library C calls
The boundary runs the other way too. An extern fn **with a body** is a function C calls by that
name, with C's calling convention; inside the program it is an ordinary function. Its parameters and
result are the types that cross to C (integers, floats, bool, raw pointers, plain structs of those),
it is not generic, and its name is its C symbol, so two such functions cannot share one, cb_… and
cobalt_… are the runtime's, and a name of C or its library (write, index, time, a C keyword, or one
that begins with _) is refused: it would take the library function's place for the whole program. A
program's own C (extern "x.c";) may call these functions too, on any thread. That includes a thread
the C started itself, which the runtime registers on its first call and releases when it ends. A
program with entry points keeps the runtime's locking on for the whole run. A file of such functions
with no main is a library.
import std;
struct Point
{
f64 x;
f64 y;
}
extern fn midpoint(Point a, Point b) : Point
{
Point { .x = (a.x + b.x) / 2.0, .y = (a.y + b.y) / 2.0 }
}
extern fn checksum(rawptr<u8> data, usize len) : u32
{
Vec<u8> bytes = unsafe { Vec::from_raw(data, len) }; // a copy; the checks cover it from here
u32 sum = 0;
foreach (b in &bytes)
{
sum = wrapping_add(sum, widen<u32>(*b));
}
sum
}
extern fn divide(i64 a, i64 b) : i64
{
a / b // faults on 0, as anywhere
}cobc --lib geo.cb writes libgeo.a, copies the runtime libcbrt.a beside it, and writes geo.h:
each struct that crosses as C declares it (its layout asserted), the library's own three calls, and every
entry point twice.
struct Point { double x; double y; };
COBALT_STATIC_ASSERT(sizeof(struct Point) == 16 && COBALT_ALIGNOF(struct Point) == 8, "layout of Point");
void cobalt_init(void); /* optional: the first call starts the runtime anyway */
void cobalt_shutdown(void); /* writes out what the library has printed */
int cobalt_last_fault(char *buf, size_t n); /* the last fault a _try call contained */
struct Point midpoint(struct Point a, struct Point b);
int midpoint_try(struct Point a, struct Point b, struct Point *result);
uint32_t checksum(uint8_t *data, uint64_t len);
int checksum_try(uint8_t *data, uint64_t len, uint32_t *result);
int64_t divide(int64_t a, int64_t b);
int divide_try(int64_t a, int64_t b, int64_t *result);A C program includes the header and links -lgeo -lcbrt (the header's first line gives the whole
link line for the target). Every check stays on inside the library: a C buffer is taken as a value with
Vec::from_raw (or given back with copy_to_raw), a C string with String::from_c, and from there on
the code is checked CobaltC. A fault inside divide(1, 0) reports and ends the process, as it would in a
program; a fault inside divide_try(1, 0, &q) is contained: the call's frames unwind, divide_try returns
1 with q untouched, and cobalt_last_fault gives the report. The library may be called from any C
thread, several at once. What it prints is written out as each call returns; a C program that buffers its
own stdout flushes it before calling in (or switches buffering off) to keep the two in order.
The header serves C++ too: its declarations have C linkage there (extern "C") and the layout
asserts are spelled for either language. A struct an entry point takes through a rawptr is
declared in full when C can declare it, so C can make one and pass its address; one C cannot
declare (a resource, one holding a String) stays an incomplete struct for C to hold by pointer.
A C program links one CobaltC library: each library carries the runtime's start-up for its own
program, so the CobaltC code a C program calls is built as one library, its other files modules of
it.
main, so there is nothing to run: cobc --check geo.cb checks it,
cobc --unittest --run geo.cb runs its unittest blocks, and cobc --run geo.cb stops with the
command that builds it. cobc --lib builds it, for Linux or, with --target x86_64-pc-windows-gnu,
for Windows.Structs and text across the boundary
A struct crosses by value when it is plain: not a resource, at least one field, and every
field an integer, a float, bool, a rawptr, another such struct, or an array of those. Every
struct is laid out as C lays out the same members in the same order (§16), so the C side declares the
same fields in the same order and the C compiler passes it by the platform's rules. Enums do not
cross (a C enum is an integer on this side), nor bitstructs (pass B::bits(b)), nor arrays on
their own (C passes an array as a pointer), though an array field is fine.
import std;
struct DivT // C's div_t: { int quot; int rem; }
{
i32 quot;
i32 rem;
}
unsafe extern fn div(i32 n, i32 d) : DivT; // a struct result, by value
fn main()
{
DivT r = unsafe
{
div(17, 5)
};
printf("%d remainder %d\n", r.quot, r.rem);
}3 remainder 2
Text is the other everyday crossing. C wants const char *, bytes that end at a NUL; it hands
back char * the same way, or NULL for "none". std::ffi covers both directions:
| Direction | Write | Notes |
|---|---|---|
| to C | CString::new("text")? then CString::ptr(&c) | Err(NulError) if the text already holds a NUL; the address is valid until the CString is dropped, even if it is moved |
| from C | unsafe { String::from_c(p) } | copies up to the NUL; Err(Utf8Error) if not UTF-8; Vec::from_c_bytes for bytes that need not be |
NULL | is_null(p), null_rawptr<T>() | test before reading; String::from_c of NULL faults (diag.null-pointer) |
Taking a CString's address is safe; handing it to C is the unsafe call. String::from_c
itself must sit inside unsafe, as a dereference does, because it reads wherever the pointer points;
for the same reason it can never be passed around as a function value.
import std;
unsafe extern fn getenv(rawptr<u8> name) : rawptr<u8>;
unsafe extern fn strchr(rawptr<u8> s, i32 c) : rawptr<u8>;
// A safe wrapper: the only `unsafe` is here, and NULL becomes `None`.
fn env(StringView name) : Option<String>
{
CString c = Result::expect(CString::new(name), "a name has no NUL");
rawptr<u8> p = unsafe
{
getenv(CString::ptr(&c))
};
if (is_null(p))
{
return None;
}
match (unsafe { String::from_c(p) })
{
Ok(s) : Some(s),
Err(_) : None, // set, but not UTF-8
}
}
fn main()
{
match (env("COBALTC_GUIDE_SURELY_UNSET"))
{
Some(v) : printf("set to %s\n", &v),
None : printf("not set\n"),
}
CString path = Result::expect(CString::new("docs/guide.html"), "no NUL");
rawptr<u8> slash = unsafe
{
strchr(CString::ptr(&path), 47) // '/'
};
String rest = Result::expect(unsafe { String::from_c(slash) }, "UTF-8");
printf("%s\n", &rest);
}not set /guide.html
From claim to fact
Data from outside (bytes read by an extern, a pointer handed back by a library, a length
in a header) starts as a claim. The pattern for turning it into a fact is a validator that returns
Result: the library's String::from_utf8(bytes) (§21) is the canonical example. Once the
validator has accepted the bytes, the resulting String is guaranteed valid UTF-8 for the rest of
its life, because there is no operation that could break it.
- Keep
unsafeblocks tiny and wrap them in a safe function whose signature makes the precondition impossible to violate from outside. - Never let a raw pointer stand in for a reference in an API. Return
ref<T, m>(fromreclaim), taken through a reference to whatever owns the memory, asVec::index_sharedtakes&v, so the result is tied to its owner and callers get checked access. - Validate external data once, at the boundary, into a type that cannot represent the invalid state.
§21The standard library, std
spec/21-standard-library-semantics.mdimport std; Option, Result, the intrinsics, str and printf, and Vec, String, HashMap, HashSet, Queue, PriorityQueue, Rc and Box written in CobaltC.
The standard library is the module std. It holds the Option and Result enums and
the library's error types; the containers and text types, written in CobaltC itself: Vec<T>,
String, StringView, HashMap<K, V>, HashSet<K>, Queue<T>, PriorityQueue<T>, Box<T>, Rc<T>, Weak<T> and Channel<T>
(§19); output, input and files: printf, eprintf, sprintf, read_line, read_file, write_file,
File and the directory functions; the program's arguments, arg_count and arg; and smaller helpers
such as swap, replace, min, max, crc32 and Rng. A program uses it with import std;, or
by qualified paths such as std::Vec. Its source is part of the specification, which is the
language's proof that the mechanisms in this guide are enough to build real containers. A function
joins std when it names one very common intent, so that its name says what a loop or a match
would otherwise have to be read to discover; one that is only shorter, not clearer, stays out. Being
a module, it keeps its private parts private: no program can touch Vec's length or buffer,
String's bytes, a HashMap's table or Rc's count.
std is divided into submodules by subject, and its root passes each one's items on as its
own (export import, §17), so import std; brings in everything and std::Vec names the same type
as std::collections::Vec. A program that wants one subject alone may import just that one. Four
submodules divide again, the same way: std::crypto into digest, kdf, aead and pk,
std::http into client and server, std::database into one submodule per database server,
postgres today, and std::encoding into one submodule per data format or encoding of bytes as
text, json, hex and base64. Each is
re-exported by its parent, so sha256 is also std::crypto::digest::sha256, PgConnection is
std::database::postgres::PgConnection and Json is std::encoding::json::Json. One submodule is declared and not
re-exported: std::extensions, the area an implementation may fill with modules of its own, which the
specification leaves undefined and conformance never tests. A program reaches one only by naming it
(import std::extensions::m;), so its dependence on that implementation shows in its source; the
reference implementation's std::extensions is empty.
What the library asserts, and what it does not
A claim about std rests on one of four tiers, each on the one before: the language's own
guarantee (a program without unsafe blocks of its own has no undefined behaviour); the trusted
library base, the unsafe blocks inside std whose claims the implementation keeps (every one is
listed in spec/21 §0); the conformance suite, which shows that the bodies do what its rows say on the
inputs the rows give; and, for the security-relevant modules, a security profile: the standard
targeted, the vectors held, what is claimed about timing, the limits on input, and what was tested
outside the suite. A green suite is evidence for the third tier and nothing more. The full table is in
spec/21 §0 ("Security profiles"); the short form:
| Module | Standard | Constant time | Limits on input |
|---|---|---|---|
std::crypto::digest | SHA-1, SHA-2, BLAKE2b, CRC-32 | yes; digest_eq compares every byte | none |
std::crypto::kdf | HMAC, HKDF, PBKDF2, Argon2id | yes, except Argon2id's data-dependent half (by design) | Argon2id parameters are checked |
std::crypto::aead | ChaCha20-Poly1305, AES-GCM | yes (bitsliced AES, constant-time GHASH) | key and nonce lengths are checked |
std::crypto::pk | X25519, P-256/P-384, ECDSA, Ed25519, RSA | the private operations, yes; verification and RSA key generation, no | encodings are checked |
std::x509 | X.509, PEM, PKCS #8 keys | not claimed (public data) | a chain of at most ten certificates |
std::tls | TLS 1.3 client and server | the primitives'; digest_eq for Finished | records of at most 16 KiB (+256 encrypted); timeouts |
std::http | HTTP/1.1 | — | head 64 KiB; body max_body (16 MiB); max_redirects (10); timeout_ms |
std::compress | DEFLATE, zlib, gzip | — | output at most the max you pass |
std::encoding::json | JSON | — | nesting at most 512 deep; numbers are f64 |
std::database::postgres | PostgreSQL protocol 3.0, SCRAM-SHA-256 | digest_eq for the server signature | messages at most 1 GiB; results at most max_result (16 MiB) |
Every parser in that table was also fed ten thousand mutated inputs under GCC, Clang and
AddressSanitizer, each in its own thread (the hostile-input round, D-0211): the expectation is an
Err or a clean Ok for every one, never a fault or a crash. The round found two faults, in the PEM
readers and in the HTTP client's status line, both now an Err.
Every module and its items
Below is every module of std with every item it declares, generated from the
reference implementation's source. Names in faint red are not exported: they are the
module's own working parts, which a program cannot name or call, listed so that nothing in the source
is left out. Everything else is exported. An item marked n has no CobaltC body: the
compiler builds it in (printf, sqrt, exit, …), and its documentation is kept by hand in
impl/std/builtins.md. A row headed T:: lists T's
associated functions. A parent module also re-exports the submodules it lists, so their items are its
own too. Each exported name links to its entry in the std
reference, which gives its declaration, its documentation and examples.
std, std::core, std::collections, std::text, std::io, std::fs, std::env, std::memory, std::sync, std::random, std::math, std::stats, std::time, std::process, std::net, std::crypto, std::crypto::digest, std::crypto::kdf, std::crypto::aead, std::crypto::pk, std::x509, std::tls, std::http, std::http::client, std::http::server, std::database, std::database::postgres, std::encoding, std::encoding::json, std::encoding::hex, std::encoding::base64, std::encoding::toml, std::compress, std::ffi, std::extensions
std impl/std/std.cb
| Kind | Items |
|---|---|
| Submodules | core, collections, text, io, fs, env, memory, sync, random, math, stats, time, process, net, crypto, x509, tls, http, database, encoding, compress, ffi, extensions |
| Functions | byte_answer, byte_op, bytes_ptr, code_error, file_error, fs_answer, path_result, path_text, printn |
Externs (unsafe) | clock_read, event_op, file_at, file_op, file_read, file_write, fs_op, fs_query, net_op, os_random, path_op, proc_op, sleep_ns, stderr_write, stdin_read_line, stdout_flush, task_op, thread_id, tz_offset |
std::core impl/std/core.cb
| Kind | Items |
|---|---|
| Types | AllocError, Option, Result |
| Functions | assertn, overwrite, replace, swap |
Option:: | expect, is_none, is_some, ok_or, unwrap, unwrap_or |
Result:: | expect, is_err, is_ok, map_errn, ok, unwrap, unwrap_or |
std::collections impl/std/collections.cb
| Kind | Items |
|---|---|
| Types | Drain, HashDrain, HashEntry, HashMap, HashSet, MapHoles, PriorityQueue, Queue, SetDrain, Vec |
| Functions | cell_names_home, key_before, low_bit, map_place, read_be, read_le, slice_eq, slice_parts, slice_swap, slot_shift |
Vec:: | all, any, append, apply_order, binary_search, binary_search_by, clear, clone, clone_by, contains, contains_ref, count, dedup, drain, drop, eq, extend_from, filled, from_c_bytes, from_fn, from_raw, from_slice, grow, index_exclusive, index_of, index_shared, insert, len, new, pop, position, push, push_be, push_le, remove, reserve, retain, reverse, sort, sort_by, sorted_order, sorted_order_keys, swap, swap_remove, take_raw, truncate |
Drain:: | drop, take, total |
HashMap:: | add_hole, cells_moved, clear, clone, closed_places, compact, contains, contains_ref, contains_str, drain, drop, entry, entry_in, entry_new, entry_owned, find, get, get_mut, get_mut_ref, get_mut_str, get_ref, get_str, has_key, index_of, insert, key_at, len, new, place, put_value, remove, remove_ref, remove_slot, remove_str, reserve_one, reslot, seek, swap_remove, trim, unslot, value_at |
MapHoles:: | below, cover, flags, is_hole, mark, none, unmark |
HashDrain:: | drop, take_key, take_value, total |
HashSet:: | clear, clone, contains, contains_ref, contains_str, difference, drain, insert, intersection, key_at, len, new, remove, remove_ref, remove_str, swap_remove, union |
SetDrain:: | take, total |
Queue:: | back, clear, drop, front, len, new, pop_back, pop_front, push_back, push_front, shift |
PriorityQueue:: | before, clear, len, new, new_by, peek, pop, push, sift_up |
std::text impl/std/text.cb
std::io impl/std/io.cb
| Kind | Items |
|---|---|
| Functions | eprint_str, eprintfn, flush_stdout, print_str, print_string, printfn, read_all, read_all_bytes, read_line |
File:: | printfn |
Externs (unsafe) | stdin_read, stdout_write |
std::fs impl/std/fs.cb
| Kind | Items |
|---|---|
| Types | File, FileError, FileInfo, PathKind |
| Functions | copy_file, copy_permissions, copy_stream, file_error_at, file_info, fs_path_op, list_dir, list_dir_bytes, make_dir, make_dir_all, make_temp_dir, path_canonical, path_extension, path_file_name, path_is_absolute, path_join, path_kind, path_normalize, path_parent, path_stem, read_bytes, read_file, read_link, remove_dir, remove_dir_all, remove_file, rename, write_bytes, write_file |
FileError:: | text |
File:: | append, close, create, create_new, create_private, drop, flush, len, open, open_rw, position, read, read_line, read_line_with_end, read_to_end, seek, start, take, write, write_formatted, write_text |
std::env impl/std/env.cb
| Kind | Items |
|---|---|
| Types | Args |
| Functions | arg, arg_count, current_dir, current_exe, env_var, home_dir, hostname, set_current_dir, temp_dir |
Args:: | clash, command, declared, finish, flag, from, help, is_option, new, option, options, spec, undeclared |
Externs (unsafe) | arg_bytes |
std::memory impl/std/memory.cb
| Kind | Items |
|---|---|
| Types | Arc, ArcBox, ArcWeak, Box, Rc, RcBox, Weak |
| Functions | rc_confined |
RcBox:: | release_weak |
Rc:: | clone, downgrade, drop, get, new |
Weak:: | clone, drop, upgrade |
ArcBox:: | release_weak |
Arc:: | clone, downgrade, drop, get, new |
ArcWeak:: | clone, drop, upgrade |
Box:: | cells, clone, drop, get, get_mut, into_inner, new |
std::sync impl/std/sync.cb
| Kind | Items |
|---|---|
| Types | Atomic, AtomicBool, AtomicPtr, Barrier, BarrierArrival, Channel, ChannelState, Once, OnceRun, Semaphore, ThreadFailure |
| Functions | atomic_fence, bool_byte, cpu_count, failure_text, is_finished, spin_hint, try_join |
ChannelState:: | pop |
Channel:: | close, drop, new, recv, recv_timeout_ms, send, try_recv |
ThreadFailure:: | diagnostic, drop, is_cancelled, text |
Atomic:: | compare_exchange, fetch_add, fetch_add_wrapping, fetch_and, fetch_max, fetch_min, fetch_or, fetch_sub, fetch_sub_wrapping, fetch_update, fetch_xor, load, new, notify_all, notify_one, store, swap, wait |
AtomicBool:: | compare_exchange, fetch_and, fetch_or, fetch_xor, load, new, notify_all, notify_one, store, swap, wait |
AtomicPtr:: | compare_exchange, load, new, store, swap |
Barrier:: | new, wait |
BarrierArrival:: | drop |
Semaphore:: | acquire, available, new, release, try_acquire |
Once:: | call, is_done, new |
OnceRun:: | drop |
std::random impl/std/random.cb
| Kind | Items |
|---|---|
| Types | Rng |
| Functions | os_random_bytes, os_random_u64, os_random_vec, uuid_v4 |
Rng:: | below, from_os, new, next_u64, rotl, shuffle, splitmix, unit_f64 |
std::math impl/std/math.cb
| Kind | Items |
|---|---|
| Types | BigDivision, BigUint |
| Functions | abs, acosn, asinn, atann, atan2n, ceiln, clamp, cosn, expn, floorn, gcd, is_finite, is_nan, lnn, log10n, log2n, max, min, pow, powfn, roundn, sinn, sqrtn, tann, truncn |
BigUint:: | add, bit, bit_len, clone, compare, div_rem, div_small, eq, from_bytes_be, from_u64, is_zero, less, mod_inverse, mod_pow, mul, mul_add_small, parse, rem, shift_left, shift_right, shifted_limbs, sub, text, to_bytes_be, to_bytes_be_padded, trim, zero |
std::stats impl/std/stats.cb
| Kind | Items |
|---|---|
| Types | Summary |
| Functions | describe, float_sum, interpolated, maximum, mean, median, minimum, percentile, sample_stddev, sample_variance, sorted_numbers, squared_deviations, stddev, sum, variance |
std::time impl/std/time.cb
| Kind | Items |
|---|---|
| Types | DateTime, Weekday |
| Functions | days_in_month, floor_div, floor_mod, http_date_words, http_time, iso_byte, iso_digits, iso_from_unix_ms, leap_year, local_offset_seconds, monotonic_ns, month_name, month_number, sleep_ms, unix_ms, unix_ms_from_iso, unix_seconds |
DateTime:: | eq, from_http_date, from_iso, from_unix, less, new, now, read_iso, to_http_date, to_iso, to_iso_local, to_local, to_unix, unix_checked, utc_of, valid, weekday |
Weekday:: | text |
std::process impl/std/process.cb
| Kind | Items |
|---|---|
| Types | Child, ChildInput, ChildOutput, Command, Output |
| Functions | exitn, interrupt_requested, pipe_op, process_id, watch_interrupts |
Command:: | arg, clear_env, current_dir, encode, env, new, output, output_with_input, put, run, spawn, status |
Child:: | cap, close_input, done, drop, id, kill, kill_tree, op, read_error, read_error_line, read_output, read_output_line, take, take_input, take_output, terminate, try_wait, wait, write_input |
ChildInput:: | drop, write |
ChildOutput:: | drop, read, read_line |
std::net impl/std/net.cb
| Kind | Items |
|---|---|
| Types | Datagram, IpAddr, NetError, SocketAddr, TcpListener, TcpStream, UdpSocket |
| Functions | net_addr, net_error, net_num, net_open, resolve |
IpAddr:: | localhost_v4, localhost_v6, parse, text, unspecified_v4, unspecified_v6 |
SocketAddr:: | from_record, new, parse, record, text |
NetError:: | text |
TcpListener:: | accept, bind, drop, local_addr, set_accept_timeout_ms |
TcpStream:: | connect, connect_timeout, drop, local_addr, peer_addr, printfn, read, read_exact, read_line, set_keepalive, set_nodelay, set_read_timeout_ms, set_write_timeout_ms, shutdown_write, take, try_clone, write, write_formatted, write_text |
UdpSocket:: | bind, connect, drop, local_addr, recv, recv_from, send, send_to, set_read_timeout_ms, try_clone |
std::crypto impl/std/crypto.cb
| Kind | Items |
|---|---|
| Submodules | digest, kdf, aead, pk |
| Functions | block_len, hash_len |
| Constants | BLAKE2B_G |
std::crypto::digest impl/std/crypto/digest.cb
| Kind | Items |
|---|---|
| Types | Blake2b, Hasher, HashKind, Sha1, Sha256, Sha384, Sha512 |
| Functions | blake2b, blake2b_absorb, blake2b_block, crc32, digest_eq, hash, sha1, sha1_absorb, sha1_block, sha256, sha256_absorb, sha256_block, sha384, sha512, sha512_absorb, sha512_block, sha512_bytes |
Sha256:: | finish, new, update |
Sha512:: | final_words, finish, new, update |
Sha384:: | finish, new, update |
Sha1:: | finish, new, update |
Hasher:: | finish, new, update |
Blake2b:: | finish, new, new_keyed, update |
| Constants | BLAKE2B_IV, BLAKE2B_SIGMA, CRC32_T, SHA256_K, SHA512_K |
std::crypto::kdf impl/std/crypto/kdf.cb
| Kind | Items |
|---|---|
| Types | Hmac, HmacSha256 |
| Functions | argon2_g, argon2_get, argon2_h_prime, argon2_load, argon2_p, argon2_put, argon2id, b64_decode_unpadded, b64_unpadded, hash_password, hkdf_expand, hkdf_expand_label, hkdf_expand_label_with, hkdf_expand_with, hkdf_extract, hkdf_extract_with, hkdf_sha256, hkdf_with, hmac, hmac_sha256, pbkdf2, pbkdf2_sha256, verify_password |
HmacSha256:: | finish, new, update |
Hmac:: | finish, new, update |
| Constants | MAX_VERIFY_KIB |
std::crypto::aead impl/std/crypto/aead.cb
| Kind | Items |
|---|---|
| Types | AesKey, Poly1305 |
| Functions | aead_tag, aes_block, aes_encrypt4, aes_encrypt_block, aes_expand, aes_gcm_open, aes_gcm_seal, aes_mix_columns, aes_pack, aes_rot1, aes_rot2, aes_rot3, aes_sbox_bytes, aes_sbox_ct, aes_shift_rows, aes_transpose8, aes_unpack, aes_xtime, chacha20, chacha20_poly1305_open, chacha20_poly1305_seal, chacha_block, chacha_quarter, crypto_check_lengths, gcm_block, gcm_bytes, gcm_ctr, gcm_j0, gcm_tag, ghash_bmul64, ghash_mul, ghash_rev64, ghash_update, poly1305, poly1305_blocks |
Poly1305:: | block, finish, new, update_last, update_padded |
| Constants | AES_ROW0, AES_ROW1_HI, AES_ROW1_LO, AES_ROW2_HI, AES_ROW2_LO, AES_ROW3_HI, AES_ROW3_LO |
std::crypto::pk impl/std/crypto/pk.cb
| Kind | Items |
|---|---|
| Types | Borrowed, DerSpan, EcCurve, Ed, EdExpanded, Field, Jacobian, Mont, RsaPrivateKey, RsaPublicKey |
| Functions | biguint_of, curve_b_hex, curve_base, curve_hex, curve_point, der_positive_int, der_push_uint, digest_info_prefix, digest_scalar, ec_affine, ec_mul, ec_private_key, ec_public_key, ec_scalar, ecdh, ecdsa_sign, ecdsa_verify, ed25519_private_key, ed25519_public_key, ed25519_sign, ed25519_verify, ed_add, ed_base, ed_decode, ed_double, ed_encode, ed_expand, ed_identity, ed_mul, ed_order, ed_select, f_add, f_add_raw, f_bit, f_from_be, f_from_mont, f_invert, f_is_zero, f_less, f_nibble, f_select, f_small, f_sub, f_sub_borrow, f_sub_raw, f_to_mont, fe_add, fe_carry, fe_cswap, fe_eq, fe_from_bytes, fe_invert, fe_is_zero, fe_mul, fe_neg, fe_pow_p58, fe_select, fe_sub, fe_to_bytes, field_of, jac_add, jac_double, jac_select, jac_table, jac_twin, jac_twin_bits, le_limbs, limbs7_add, limbs_be, limbs_of, limbs_sub_mod, mgf1, mont_mul, mont_mul_v, mont_new, mont_pow, mont_pow_limbs, p256_ecdh, p256_private_key, p256_public_key, pkcs1v15_encode, probably_prime, random_prime, rsa_generate_key, rsa_open, rsa_private_op, rsa_sign_pkcs1v15, rsa_sign_pss, rsa_verify_pkcs1v15, rsa_verify_pss, sc_bytes, sc_from_hash, sc_mont, small_primes, x25519, x25519_ladder, x25519_private_key, x25519_public_key |
RsaPrivateKey:: | new, public_key |
| Constants | ED_2D, ED_BX, ED_BY, ED_D, ED_SQRT_M1, FE_MASK |
std::x509 impl/std/x509.cb
| Kind | Items |
|---|---|
| Types | CertError, Certificate, CertKey, ChainSearch, Der, EcPrivateKey, EcPublicKey, PrivateKey, SignatureScheme, TrustStore |
| Functions | ascii_lower_eq, certificates_from_pem, chain_search, check_time, common_name_of, curve_oid_hex, der_big, der_bit_string, der_bytes, der_eq_hex, der_expect, der_oid_hex, der_push_len, der_read, der_text, der_time, der_uint, der_wrap, digits, dns_names_allowed, dns_within, ec_private_of, hash_oid, host_allowed, ip_bytes, ip_within, ips_allowed, issuer_ok, key_algorithm, name_matches, names_allowed, pem_block, pem_of, public_key_of, rsa_private_of, same_bytes, sign, signature_algorithm, verify_chain, verify_signature |
CertError:: | text |
CertKey:: | from_der, from_pem, to_der, to_pem |
Certificate:: | matches_host, parse |
TrustStore:: | add, from_pem_file, new, system |
PrivateKey:: | from_der, from_pem, public_key, to_der, to_pem |
std::tls impl/std/tls.cb
| Kind | Items |
|---|---|
| Types | ClientHello, Handshake, Inner, Record, RecordKeys, ServerHello, TlsError, TlsStream |
| Functions | certificate_list, certificate_verify_ok, client_hello, client_hello_parse, derive_secret, finished_data, handshake_record, keys_from, next_message, open_record, push_extension, push_u24, read_record, record_nonce, same_session, scheme_of, seal_record, send_handshake, send_plain_alert, server_hello, server_hello_bytes, server_scheme, suite_hash, suite_key_len, transcript_add, transcript_hash, u16_list, write_all |
TlsError:: | text |
TlsStream:: | client, close, connect, fill, local_addr, peer_addr, peer_certificate, read, read_exact, read_line, server, set_read_timeout_ms, set_write_timeout_ms, write, write_text |
std::http impl/std/http.cb
| Kind | Items |
|---|---|
| Submodules | client, server |
| Types | BodyLength, Conn, Header, HttpError, Param, Reader, Request, Response, Url |
| Functions | ascii_ieq, ascii_ieq_str, available, body_length, chunk_size, conn_close, conn_read, conn_write, connection_has, count_header, default_port, drain_input, field_ok, fill_buffer, find_header, find_param, form_decode, form_encode, form_encode_part, form_part, has_cr, has_header, hex_digit, host_field_ok, host_ok, host_text, http_line, http_line_crlf, http_line_mode, http_newline_from, is_token, is_unreserved, latin1_to_utf8, name_eq, names_eq, percent_decode, percent_encode, port_digits, read_body, read_headers, read_n, read_to_end, reason_phrase, utf8_valid, write_field |
HttpError:: | text |
Url:: | parse, query_pairs, target, text |
Param:: | new |
Header:: | new |
Request:: | header, new |
Response:: | header, text |
| Constants | MAX_HEAD |
std::http::client impl/std/http/client.cb
| Kind | Items |
|---|---|
| Types | HttpClient, IdleConn, StatusLine |
| Functions | exchange, exchange_on, has_scheme, http_get, http_post, idempotent, is_credential, is_framing, method_has_body, not_content_encoding, open_connection, origin_of, parse_status_line, redirect_target, remove_dot_segments, request_bytes |
HttpClient:: | new, send |
| Constants | MAX_INTERIM |
std::http::server impl/std/http/server.cb
| Kind | Items |
|---|---|
| Types | HttpConnection, HttpServer, PendingTls |
| Functions | request_line |
HttpServer:: | accept, bind, bind_tls, local_addr |
HttpConnection:: | close, handshake, next_arrives, peer_addr, read_request, request, respond |
| Constants | DRAIN_MAX |
std::database impl/std/database.cb
| Kind | Items |
|---|---|
| Submodules | postgres |
| Types | Scram |
| Functions | attribute, sasl_hex, sasl_in, sasl_map, sasl_nfkc, saslprep, scram_salted_password |
Scram:: | client_first, respond, start, verify |
| Constants | HANGUL_COUNT, HANGUL_L, HANGUL_S, HANGUL_T, HANGUL_V, SASLPREP_B1, SASLPREP_C12, SASLPREP_CCC, SASLPREP_COMPOSE, SASLPREP_L, SASLPREP_NFKD, SASLPREP_PROHIBITED, SASLPREP_RANDAL, SASLPREP_UNASSIGNED |
std::database::postgres impl/std/database/postgres.cb
| Kind | Items |
|---|---|
| Types | Message, PgColumn, PgConn, PgConnection, PgError, PgParameter, PgReader, PgResult, PgRow, PgServerError, PgSslMode, PgUrl, PgValue |
| Functions | authenticate, broken, collect, connect_url, cstr_at, decode_columns, decode_row, decode_server_error, decoded, float_text, frame, open_tcp, pg_available, pg_close, pg_fill, pg_read, pg_read_n, pg_write, push_cstr, read_message, send_cancel, tag_count |
PgError:: | text |
PgUrl:: | parse |
PgValue:: | text |
PgRow:: | get, get_bool, get_bytes, get_datetime, get_f64, get_i64 |
PgResult:: | column |
PgConnection:: | close, connect, connect_with, execute, parameter, query, run_script, set_timeout_ms |
| Constants | COPY_IN, COPY_OUT, ENCODING_CHANGED, MAX_MESSAGE |
std::encoding impl/std/encoding.cb
| Kind | Items |
|---|---|
| Submodules | json, hex, base64, toml |
std::encoding::json impl/std/encoding/json.cb
| Kind | Items |
|---|---|
| Types | Json, JsonMember, JsonReader, JsonStr |
| Functions | json_digits_end, json_hex4, json_indent, json_number, json_quote, json_quote_bytes, json_space_end, json_string, json_write |
Json:: | as_array, as_bool, as_f64, as_i64, as_object, as_text, at, get, is_null, key_index, lookup, parse, pretty, push, push_member, set, text |
JsonReader:: | digits, number, peek, skip_space, text, value |
| Constants | MAX_DEPTH |
std::encoding::hex impl/std/encoding/hex.cb
| Kind | Items |
|---|---|
| Functions | from_hex, hex_decode, hex_value, to_hex |
std::encoding::base64 impl/std/encoding/base64.cb
| Kind | Items |
|---|---|
| Functions | base64_decode, base64_decode_bytes, base64_encode, base64_value |
std::encoding::toml impl/std/encoding/toml.cb
| Kind | Items |
|---|---|
| Types | TNode, Toml, TomlDateKind, TomlDateTime, TomlMember, TomlReader |
| Functions | tnode_define, tnode_find, tnode_insert, tnode_new, tnode_push, tnode_to_toml, toml_days_in_month, toml_float, toml_hex_digit, toml_inline, toml_is_bare, toml_is_table, toml_is_table_array, toml_key, toml_quote, toml_two_digits, toml_write_table |
Toml:: | as_array, as_bool, as_datetime, as_f64, as_i64, as_table, as_text, at, describe_error, get, lookup, parse, push, read, set, text |
TomlDateTime:: | text |
TomlReader:: | array_value, at_end, basic, comment, date_ahead, datetime, digits, fixed, inline_table, key, key_part, line_end, literal, newline, number, peek, peek_at, prefixed, skip_space_lines, skip_ws, time_ahead, time_part, unicode_escape, value, word |
| Constants | K_ARRAY, K_DOTTED, K_HEADER, K_IMPLICIT, K_VALUE, TNODE_INDEX_AT, TOML_MAX_DEPTH, TOML_RANGE, TOML_TWICE |
std::compress impl/std/compress.cb
| Kind | Items |
|---|---|
| Types | BitOut, BitReader, BitsStep, BitWriter, CompressError, DeflateScan, Huffman, HuffStep, InflateRun, Token, TokenCounts |
| Functions | adler32, bits_step, canonical_codes, code_lengths, deflate, deflate_scan, distance_code, fixed_codes, fixed_distances, gunzip, gzip, hash3, huff_step, inflate, inflate_codes, inflate_from, inflate_run, length_code, put_tokens, read_dynamic, token_counts, write_block, zlib_deflate, zlib_inflate |
CompressError:: | text |
BitReader:: | align, take |
Huffman:: | build, decode |
BitWriter:: | flush, put, put_code |
| Constants | CHAIN_LIMIT, CLEN_ORDER, DIST_BASE, DIST_EXTRA, HASH_SIZE, LENGTH_BASE, LENGTH_EXTRA, MAX_TOKENS, WINDOW |
std::ffi impl/std/ffi.cb
| Kind | Items |
|---|---|
| Types | CString, NulError |
| Functions | copy_to_raw, is_null |
NulError:: | text |
CString:: | as_bytes, from_bytes, len, new, ptr |
std::extensions impl/std/extensions.cb
No items: the reference implementation declares nothing here.
import std::text;
import std::io;
fn main()
{
String s = "only text and output";
printf("%s\n", &s);
}only text and output
This guide writes import std; and the short names throughout; each part below says which
submodule it lives in.
The intrinsics and the text value type str are not part of std. They belong
to the language itself and need no import. This section keeps the two apart, as the specification's
tables do: the intrinsics first, then std at a glance, then each part of std in turn.
Types in std
export enum Option<T>
{
Some(T),
None
}
export enum Result<T, E>
{
Ok(T),
Err(E)
}
export struct AllocError
{
}
export struct Utf8Error
{
export usize offset; // where the first ill-formed sequence starts: bytes before it are UTF-8
}
export enum FileError // why reading or writing failed: a file, or standard input
{
NotFound,
Denied,
Io,
Utf8(Utf8Error),
IsDirectory, // a directory where a file is needed
NotDirectory, // a part of the path that must be a directory is not
NoSpace, // the device, or the quota on it, is full
TooManyOpen, // as many files open as the program or the system may have
NotEmpty, // a directory to remove still holds entries
LinkLoop, // symbolic links on the path loop, or chain too deep
SameFile, // a copy's target is its source
CrossDevice, // a rename to another file system: copy, then remove
NameTooLong, // a name on the path is longer than the system allows
InvalidName, // a name holding NUL, a directory renamed into itself
NotOpenForThat, // a write to a file opened for reading
ArgsTooLong // a command's arguments are more than the system takes
}
export enum ParseError // why parse failed
{
Empty,
Invalid(usize), // the offset of the first byte that does not fit
OutOfRange
}Intrinsics: part of the language
Intrinsics are called like functions; their behaviour is given by rules rather than by a
body, and they need no import. Type arguments are written name<T>(…) where the signature needs
one. Their names are not reserved: a function or variable of your own with the same name is what the
name means, and the intrinsic is used only where there is none.
Values and arithmetic
| Intrinsic | Purpose | See |
|---|---|---|
drop(x) | destroy a resource now | §07 |
wrapping_*, saturating_*, checked_* | alternative overflow policies | §06 |
widen<U>, narrow<U>, checked_narrow<U>, narrow_wrapping<U>, reinterpret<U>, to_float<U>, to_int<U> | numeric conversions | §06 |
count_ones(x), leading_zeros(x), trailing_zeros(x), rotate_left(x, k), rotate_right(x, k) | an integer's bits | §06 |
sizeof<T>(), alignof<T>() | layout queries, in bytes | §06, §16 |
min_value<T>(), max_value<T>() | a number type's smallest and largest value (a float's finite extremes) | §06 |
Text, slices, checks and faults
| Intrinsic | Purpose | See |
|---|---|---|
str_len(s), str_byte(s, i), str_ptr(s) | a str's byte count, one byte (bounds-checked), and the address of its bytes (safe) | §21 |
slice_len(s) | a slice's number of elements (also through a reference) | §16 |
static_assert(c), static_assert(c, "why") | reject the program when the constant c is false | §18 |
fault(name), fault(name, msg) | stop with the run-time fault diag.name (a dynamic diagnostic, _ for -, such as index_out_of_bounds), with msg if given; for code that implements containers as std does | §18 |
Raw memory and threads
| Intrinsic | Purpose | See |
|---|---|---|
dangling<T>() | a well-aligned non-null address that must never be dereferenced; used for empty containers | §21 |
null_rawptr<T>() | address 0, C's NULL, to pass to C or compare with; is_null(p) tests for it | §20 |
rawptr_of(&x), reinterpret_ptr<U>(p) | obtain and retype raw pointers (safe) | §20 |
rawptr_from_address<T>(a), rawptr_address(p) | an address as a pointer, and back (unsafe) | §20 |
reclaim<T>(p), release(p, n), copy_raw(dst, src, n) | raw memory as objects (unsafe) | §20 |
allocate(n, align), deallocate(p, n, align) | raw allocation (deallocate is unsafe) | §20 |
read_volatile(p), write_volatile(p, v) | raw accesses performed exactly as written (unsafe; below) | §20 |
Mutex::new(v), lock(&m) | mutual exclusion | §19 |
Atomic::new(v), Atomic::fetch_add(&a, n) | an integer threads change without a lock | §19 |
spawn(f, args…), join(h) | threads | §19 |
read_volatile(p) and write_volatile(p, v) are raw accesses that the compiler must perform
exactly as written — never merged, dropped or reordered against another volatile access or a call —
for storage that changes on its own, such as a device register (D-0121). They take a rawptr<T> to
a plain T, inside unsafe; a bitstruct (§16) names the register's fields and
Name::from_bits(read_volatile(p)) reads them.
std at a glance
Everything here is an item of std, most of it written in CobaltC, and needs import std;
(or a qualified path). The containers and text types have their own parts of this section below; this
is the rest, for finding a name quickly.
Option, Result and the errors
| Function | Purpose | See |
|---|---|---|
Option::unwrap(o), Option::expect(o, msg), Result::unwrap(r), Result::expect(r, msg) | the value, or the fault diag.unwrap-failed (with msg) when there is none | §18 |
Option::unwrap_or(o, d), Result::unwrap_or(r, d) | the value, or the default d when there is none | §18 |
Option::ok_or(o, e) | the Option as a Result, Err(e) for None, so ? applies to it | §18 |
Result::ok(r) | the Result as an Option: Some of the value, None for an error (which is destroyed) | §18 |
Option::is_some(&o), is_none, Result::is_ok(&r), is_err | which variant, without taking the value | §18 |
Result::map_err(r, f) | convert a Result's error type with f | §18 |
FileError::text(&e), ParseError::text, Utf8Error::text | a std error as a sentence for a person, a str | §21 |
Output, input and the program
| Function | Purpose | See |
|---|---|---|
printf("%v", x) | write a str, a number, a bool, a String (through &), a StringView, or an enum's variant name to standard output | §21 |
printf(fmt, args…), eprintf(fmt, args…), sprintf(fmt, args…), String::appendf(&mut s, fmt, args…) | C-style formatted output, to standard output, to standard error, as a new String or into one, checked when compiled | §21 |
assert(c), assert(c, fmt, args…) | fault with diag.assert-failed (and the formatted message) when c is false | §18 |
flush_stdout() | write out what printf has buffered, for output watched through a pipe while the program runs | §21 |
read_line() | read the next line of standard input as a String | §21 |
read_all(), read_all_bytes() | the rest of standard input at once, as a String or as bytes | §21 |
arg_count(), arg(i) | the number of program arguments, and argument i as a String | §21 |
read_file(path), write_file(path, text) | read a whole file as a String, or replace a file's contents; path and text are StringViews: a literal, or &s of a String | §21 |
stdout_write(buf, len), stdin_read(buf, len), arg_bytes(i, buf, len) | the externs beneath them: raw bytes to standard output, from standard input, and of argument i (unsafe) | §20 |
Numbers
| Function | Purpose | See |
|---|---|---|
StringView::parse<T>(&s) | read a whole String as a number of type T | §21 |
min(a, b), max(a, b) | the smaller or larger of two values of an ordered type (§12) | §21 |
abs(x), pow(x, n) | absolute value and power (n a u32) of a number type (§12), checked as the operators they use | §21 |
sqrt(x), floor(x), ceil(x), round(x), trunc(x) | an f32 or f64's square root and its roundings to an integral value (round: halfway cases away from zero), exact or correctly rounded, so the same bits everywhere | §21 |
ln(x), exp(x), log2(x), log10(x), sin(x), cos(x), tan(x), atan2(y, x), powf(x, y) | an f32 or f64's logarithms, exponential, trigonometry and power, from the platform's maths library (within one unit in the last place; the two operands of atan2 and powf of one type) | §21 |
abs and pow are checked like the operators they use: abs of a signed type's minimum, or a
power that does not fit, is diag.arith-overflow. The floating-point functions (std::math) take
an f32 or an f64 and give the same type; an integer is converted first, sqrt(to_float<f64>(n)).
The logarithms, the exponential, the trigonometric functions and powf come from the platform's
maths library, so their last bit may differ between platforms; sqrt and the roundings are exact
everywhere.
Text: str, String, StringView
CobaltC has three text types, which stand to each other as an array, a vector and a slice
do. A literal "…" is a str: a constant, free to copy, never freed. String is text you own.
StringView is a read-only view of text someone else owns, or of a constant.
Text fits its declaration. Where the declaration says String, a literal is
one (this is the one place a literal allocates). Where it says StringView, a literal, a str and
&s of a String are views, and so is &v of a Vec or an array where a slice is declared.
Nothing turns a view or a String into a str, and a str variable never becomes a String
without String::copy.
Write & on the thing you own and nowhere else: &s for a String, &v for a
Vec; a view, a slice, a str, a literal or a reference you already hold is passed as it is.
[lo..hi] is written only where a part is meant: &s[2..5], never &s[0..$] for the whole.
All three compare with == and < by their bytes, in any combination. Functions that read
text take a StringView; a String-keyed map is asked with any text and allocates only when it
inserts.
import std;
fn shout(StringView t) : String
{
String out = StringView::to_ascii_upper(t);
String::append(&mut out, "!");
out
}
fn main()
{
str fixed = "ready"; // a constant
String owned = "set"; // a literal where a String is declared: one copy, owned
StringView part = &owned[0..2]; // a view of part of it
HashMap<String, i32> seen = HashMap::new();
HashMap::insert(&mut seen, "go", 1);
printf("%v %v %v %v\n", &shout(fixed), &shout(&owned), &shout(part), HashMap::contains(&seen, "go"));
printf("%v %v\n", fixed == "ready", &owned < "tea");
}READY! SET! SE! true true true
str
str is a text constant, String is text you own. Fixed text you write in
your program is a str; text you build, receive or keep ownership of is a String (below). The
end of this section compares them side by side.
A string literal "…" is a value of type str: a sequence of bytes that is valid UTF-8
by construction, because the literal syntax has no way to write an arbitrary byte. A str is not a
reference and not a resource. It behaves exactly like an integer: copying it is free, nothing owns
it, nothing frees it, and you can pass it, store it in a struct or a Vec<str>, compare it with
==, and hand it to another thread without any annotation. Its bytes are reached with str_len
and str_byte; &t[lo..hi] is a StringView of part of it, which never ends. Escapes are \n \r \t \0 \\ \" and
\u{…} for a Unicode scalar value; a literal must close on its own line. Adjacent literals are
one literal, as in C, so longer text is written a line at a time: "one\n" "two\n" is the
single str "one\ntwo\n", and a long printf format can be split the same way.
printf("%v", s) writes a str to standard output. It prints numbers, bool and String
too (see "Printing: printf" below). The unsafe block that reaches the stdout_write extern is inside std, so a
program that only prints never writes unsafe itself.
import std;
struct Named
{
str name;
i32 n;
}
fn shout(StringView s) // a reader of text takes a view; a str is one
{
printf("%v!\n", s);
}
fn main()
{
str greeting = "hello";
str again = greeting; // copied, not moved: greeting stays valid
assert(str_len(greeting) == 5);
assert(str_byte(greeting, 0) == 104);
assert(greeting == again);
static_assert("caf\u{e9}" != "cafe"); // \u{e9} is é, two bytes
assert(str_len("caf\u{e9}") == 5);
auto named = Named { .name = greeting, .n = 1 };
auto copy = named; // a struct of plain values is plain
assert(copy.name == "hello");
Vec<str> words = Vec::new();
Vec::push(&mut words, greeting);
Vec::push(&mut words, "world");
shout(words[1]);
printf("%v\n", greeting);
}world! hello
fn main()
{
str s = "hi";
u8 b = str_byte(s, 2); // ✗ diag.index-out-of-bounds (static): a literal index, refuted ahead of time
}A byte literal b"…" is different: it is an array<u8, N>, exactly the array you
would have written by hand, and admits \xNN for any byte value (and only ASCII characters
otherwise). Use it where bytes are the honest type, such as data handed to stdout_write or to a
validator. Where a slice<u8, shared> is declared it is a slice of bytes that live as long as the
program, as any array literal written out as literals is (D-0314): a binding, a struct's field or
an argument can hold a magic number or a table without a named constant. A named constant's
parts are borrowed the same way, &K[0..2].
import std;
const array<u8, 4> ELF = b"\x7fELF";
struct Format
{
str name;
slice<u8, shared> magic;
}
fn starts_with(slice<u8, shared> data, slice<u8, shared> magic) : bool
{
if (slice_len(data) < slice_len(magic))
{
return false;
}
foreach (i in 0..slice_len(magic))
{
if (data[i] != magic[i])
{
return false;
}
}
true
}
fn main()
{
array<Format, 2> known = [
Format { .name = "zip", .magic = b"PK\x03\x04" },
Format { .name = "elf", .magic = &ELF },
];
slice<u8, shared> file = b"PK\x03\x04rest";
foreach (f in &known)
{
printf("%v %v\n", f.name, starts_with(file, f.magic));
}
}zip true elf false
Vec<T>
In std::collections.
A growable array with a raw buffer, a length and a capacity. It is a resource whose
destructor destroys each element and frees the buffer. A plain element is copied when read
(v[i]); a resource element is only borrowed, or moved out by pop or remove, never copied (so
Vec<Vec<i32>> works without any special support).
| Function | Signature | Notes |
|---|---|---|
Vec::new | () : Vec<T> | T from the expected type or written Vec<i32>::new(); allocates nothing |
Vec::len | (ref<Vec<T>, shared>) : usize | |
Vec::push | (ref<Vec<T>, exclusive>, T) | moves a resource element in; grows 0 → 4 → 8 → …, which relocates elements |
Vec::reserve | (ref<Vec<T>, exclusive>, usize n) | room for n more elements, so the next n pushes do not grow it; the elements are unchanged (D-0129) |
Vec::pop | (ref<Vec<T>, exclusive>) : Option<T> | None when empty; moves a resource element out |
Vec::insert | (ref<Vec<T>, exclusive>, usize i, T) | puts the value at i (i ≤ len), moving the later elements up one |
Vec::remove | (ref<Vec<T>, exclusive>, usize i) : T | takes the element at i out, moving the later elements down one |
Vec::swap_remove | (ref<Vec<T>, exclusive>, usize i) : T | takes the element at i out and moves the last element into its place: no other element moves, the order is not kept |
Vec::retain | (ref<Vec<T>, exclusive>, fn(ref<T, shared>) : bool keep) | keeps the elements keep accepts, in order, and destroys the rest (D-0181) |
Vec::dedup | (ref<Vec<T>, exclusive>) | removes each element equal to the one before it, so a sorted Vec keeps one of each value (T must be eq, D-0181) |
Vec::index_shared | (ref<Vec<T>, shared>, usize) : ref<T, shared> | bounds-checked: diag.index-out-of-bounds |
Vec::index_exclusive | (ref<Vec<T>, exclusive>, usize) : ref<T, exclusive> | as above, for writing |
v[i], &v[i..j] | indexing and slicing (§16) | v[i] reads through index_shared, writes through index_exclusive; $ is Vec::len(&v) |
Vec::clear | (ref<Vec<T>, exclusive>) | destroys every element, first to last; keeps the buffer for reuse |
Vec::truncate | (ref<Vec<T>, exclusive>, usize n) | keeps the first n elements and destroys the rest, last first; n past the length changes nothing |
Vec::clone | (ref<Vec<T: clone>, shared>) : Vec<T> | a copy, element by element, each by clone (§12): Vec<String>, Vec<Vec<u8>>, … |
Vec::clone_by | (ref<Vec<T>, shared>, fn(ref<T, shared>) : T) : Vec<T> | a copy made by the function, one element at a time, when the copy wanted is not the type's own clone |
Vec::from_slice | (slice<T: clone, shared>) : Vec<T> | a new Vec of the slice's elements, each by clone: Vec::from_slice(&bytes[4..$]) |
Vec::filled | (usize n, T x) : Vec<T> | n copies of x by clone: Vec::filled(80, b' '), Vec::filled(3, Vec::filled(4, 0: u8)); T: clone |
Vec::from_fn | (usize n, fn(usize) : T) : Vec<T> | f(0), f(1), …, f(n - 1), any T: a grid is Vec::from_fn(rows, [](usize r) : Vec<u8> { Vec::filled(cols, 0) }) |
Vec::append | (ref<Vec<T>, exclusive>, Vec<T> b) | moves b's elements onto the end, in order; b is consumed |
Vec::extend_from | (ref<Vec<T>, exclusive>, slice<T, shared>) | copies a slice's elements onto the end by clone: Vec::extend_from(&mut out, &bytes); T: clone |
Vec::position | (ref<Vec<T>, shared>, fn(ref<T, shared>) : bool) : Option<usize> | the first index whose element satisfies the test, or None; a closure may capture the key it looks for |
Vec::index_of, Vec::contains | (ref<Vec<T>, shared>, ref<T, shared>) : Option<usize> / : bool | the first index equal to the value, or whether there is one; T: eq — a number, bool, str, String, or a struct or enum of integers, bools and text, with no float field (D-0271); a struct with a float field takes position |
Vec::reverse | (ref<Vec<T>, exclusive>) | the order inverted in place, by swaps; nothing is destroyed |
slice_eq | (slice<T, shared>, slice<T, shared>) : bool | the same length and equal elements in order; T: eq. == does not compare vectors (they are resources): slice_eq(&a, &b) |
Vec::push_le(&mut v, x), Vec::push_be | (ref<Vec<u8>, exclusive>, T: integer) | x's bytes onto a byte Vec, least (le) or most (be) significant first; any width, signed as two's complement (D-0119) |
read_le<T>(&v, at), read_be<T> | (slice<u8, shared>, usize) : T | the T whose bytes start at at; diag.index-out-of-bounds when fewer than sizeof<T>() remain |
crc32(&v) | (slice<u8, shared>) : u32 | CRC-32/IEEE, the checksum of zlib, gzip and PNG; crc32 of "123456789"'s bytes is 0xCBF43926 (§21 of the specification writes the algorithm out) |
When you know how many elements are coming, say so first: Vec::reserve(&mut v, n)
makes room for n more at once, so filling the Vec allocates and copies once instead of every
time it doubles. String::reserve(&mut s, n) does the same for bytes. Neither changes what the
program computes: no function reports a capacity, the length and the elements stay as they were,
and reserving room that is already there does nothing. Like a push that grows, a reserve that
grows moves the elements, so a reference into the old cells is stale afterwards. std's own
builders (String::copy, String::clone, Vec::from_slice) already reserve what they
need.
import std;
fn main()
{
Vec<u32> squares = Vec::new();
Vec::reserve(&mut squares, 1000); // one allocation for all of them
foreach (i in 0..1000: u32)
{
Vec::push(&mut squares, i * i);
}
assert(Vec::len(&squares) == 1000 && squares[999] == 998001);
String line = String::new();
String::reserve(&mut line, 80);
foreach (i in 0..10)
{
String::append(&mut line, "-=-=-=-=");
}
assert(StringView::len(&line) == 80);
}import std;
fn main()
{
Vec<i32> v = Vec::new();
foreach (i in 0..9: i32) // crosses two growth boundaries (4 and 8)
{
Vec::push(&mut v, i * i);
}
assert(Vec::len(&v) == 9);
assert(*Vec::index_shared(&v, 8) == 64);
{
auto slot = Vec::index_exclusive(&mut v, 0);
*slot = 100; // write through an exclusive element reference
} // slot must be gone before v is borrowed again
assert(*Vec::index_shared(&v, 0) == 100);
match (Vec::pop(&mut v))
{
Some(x) :
{
assert(x == 64);
},
None :
{
assert(false, "unreachable");
},
}
Vec<Vec<i32>> nested = Vec::new();
Vec::push(&mut nested, v); // v moves into the outer Vec
assert(Vec::len(Vec::index_shared(&nested, 0)) == 8);
} // nested is destroyed: each inner Vec, then the outer bufferimport std;
fn main()
{
Vec<i32> v = Vec::new();
Vec::push(&mut v, 1);
Vec::index_shared(&v, 5); // ✗ diag.index-out-of-bounds (dynamic)
}The helpers of D-0112 name the loops programs kept writing: filling, building by index,
joining, searching and reversing. filled and extend_from copy plain elements; from_fn and
append are the forms for resources.
import std;
fn main()
{
Vec<u8> row = Vec::filled(4, b'.'); // "...."
Vec<Vec<u8>> grid = Vec::from_fn(3, [](usize r) : Vec<u8> { Vec::filled(4, b'.') });
grid[1][2] = b'#';
Vec<String> names = Vec::from_fn(3, [](usize i) : String { sprintf("n%d", i) });
Vec<String> more = Vec::new();
Vec::push(&mut more, "x");
Vec::append(&mut names, more); // more is consumed
Vec::extend_from(&mut row, &grid[1]); // copies bytes
assert(Vec::len(&names) == 4 && Vec::len(&row) == 8 && row[6] == b'#');
String key = "n1";
assert(Vec::index_of(&names, &key) == Some(1));
assert(Vec::contains(&row, b'#') && !Vec::contains(&row, b'?'));
assert(Vec::position(&names, [key](ref<String, shared> s) : bool { *s == key }) == Some(1));
Vec::reverse(&mut names);
assert(names[0] == "x");
}A String in hand is searched and split by the StringView functions: &s is its view wherever a
StringView is declared (D-0302), so StringView::find(&s, t), starts_with, ends_with, contains, replace,
trim and split take it as it is. And a map keyed by String can be asked with a literal: where a
ref<String, shared> is declared, a literal (or any str) is a reference to a String of its text that
never ends, so HashMap::get(&m, "apple"), contains and remove find the entry a String of the same
text would, without building one (D-0308).
import std;
fn main()
{
String line = " name = Ada, born = 1815 ";
assert(StringView::trim(&line) == "name = Ada, born = 1815");
assert(StringView::find(&line, "born") == Some(14) && StringView::ends_with(&line, " "));
HashMap<String, i64> fields = HashMap::new();
foreach (part in StringView::split(&line, ","))
{
Vec<StringView> kv = StringView::split(part, "=");
match (StringView::parse<i64>(StringView::trim(kv[1])))
{
Ok(n) : { HashMap::insert(&mut fields, String::copy(StringView::trim(kv[0])), n); },
Err(_) : {},
}
}
assert(HashMap::contains(&fields, "born") && !HashMap::contains(&fields, "name"));
match (HashMap::get(&fields, "born"))
{
Some(y) : assert(*y == 1815),
None : assert(false),
}
assert(HashMap::remove(&mut fields, "born") == Some(1815) && HashMap::len(&fields) == 0);
}Binary data: Vec::push_le and Vec::push_be write an integer's bytes in a fixed order and
read_le/read_be read them back, so a file header or a network message never spells a shift by
hand; all four are in std::collections. crc32, the CRC-32/IEEE checksum those formats use
(D-0119), is in std::crypto beside the hashes, but it only catches accidents: anyone can make
data with a chosen CRC, so use a hash or a MAC against tampering (D-0177). A bitstruct (§16)
crosses into bytes the same way, through Name::bits(v).
import std;
fn main()
{
Vec<u8> header = Vec::new();
Vec::push_be(&mut header, 0x89504E47: u32); // a PNG signature's first four bytes, big-endian
Vec::push_le(&mut header, 640: u16); // a little-endian width
Vec::push_le(&mut header, -1: i8);
assert(Vec::len(&header) == 7 && header[0] == 0x89 && header[4] == 0x80 && header[5] == 2);
assert(read_be<u32>(&header, 0) == 0x89504E47 && read_le<u16>(&header, 4) == 640);
assert(read_le<i8>(&header, 6) == -1);
String text = "123456789";
assert(crc32(StringView::as_bytes(&text)) == 0xCBF43926);
}A Vec can hold references. While it does, they count as live borrows: the referent
cannot be written past them, and a stored &mut is the only way in until the element is popped or
the Vec is destroyed.
import std;
fn main()
{
i32 a = 10;
i32 x = 1;
Vec<ref<i32, shared>> readers = Vec::new();
Vec::push(&mut readers, &a);
assert(*readers[0] == 10);
Vec<ref<i32, exclusive>> writers = Vec::new();
Vec::push(&mut writers, &mut x);
*writers[0] = 7; // write through the stored reference
Vec::pop(&mut writers); // the Vec lets go of it
assert(x == 7);
x = 8; // x is free again
}import std;
fn main()
{
i32 x = 1;
Vec<ref<i32, exclusive>> writers = Vec::new();
Vec::push(&mut writers, &mut x);
x = 5; // ✗ diag.aliasing-conflict: the Vec still holds &mut x
}Vec::push is written in CobaltC: a resource struct with a rawptr<T>, an
unsafe write of the new element at ptr + len, and a private grow that calls allocate,
copy_raw and deallocate. Reading it in the specification is the best way to see how the
pieces of §07 and §20 fit together.Random numbers
In std::random.
Rng is a general-purpose pseudo-random generator — for simulations, games, sampling,
randomised tests, shuffling — whose sequence the specification fixes (xoshiro256** seeded through
splitmix64, spec/21 [Rng], so a test in another language can reproduce it), so a program that seeds it
with a constant prints the same numbers on every machine; seed it with
Rng::from_os() for a fresh sequence each run. below(&mut r, n) is unbiased, unit_f64 is in [0, 1).
It is not suitable for cryptographic purposes: its output is predictable from a few values, so
never use it for keys, tokens, nonces, passwords, or anything an adversary must not guess (D-0120).
| Function | Does |
|---|---|
Rng::new(s), Rng::next_u64(&mut r), Rng::below(&mut r, n), Rng::unit_f64(&mut r) | a general-purpose pseudo-random generator (xoshiro256**, fixed by the specification): the same seed gives the same numbers everywhere; below is unbiased in 0 .. n. It is not suitable for cryptographic purposes — keys, tokens, nonces, anything an adversary must not predict (D-0120) |
Rng::shuffle(&mut r, &mut v), uuid_v4() | a slice put in random order (Fisher-Yates; the same seed, the same order everywhere); a version-4 UUID as text, from the operating system's secure source (D-0181) |
import std;
fn main()
{
Rng r = Rng::new(42);
assert(Rng::next_u64(&mut r) == 1546998764402558742); // the specification's check value
Rng dice = Rng::new(7);
u64 total = 0;
foreach (k in 0..100)
{
total += Rng::below(&mut dice, 6) + 1; // a die: 1 .. 6
}
assert(total >= 100 && total <= 600);
f64 x = Rng::unit_f64(&mut dice);
assert(x >= 0.0 && x < 1.0);
}For anything secret, take bytes from the operating system's cryptographically secure source
instead (std::random): os_random_bytes(&mut buf) fills a slice, os_random_u64() gives one
number. These are what keys, session tokens and nonces are made of. Rng::from_os() seeds an Rng
from them, which makes its sequence differ between runs but not secret: the sequence is still
Rng's. Every system cobc compiles for has such a source; if one did not, the call would be the
fault diag.entropy-unavailable, never a quiet fall back to the clock.
import std;
fn main()
{
Vec<u8> token = Vec::filled(16, 0: u8);
os_random_bytes(&mut token);
String hex = String::new();
foreach (byte in &token)
{
String::appendf(&mut hex, "%02x", *byte);
}
assert(StringView::len(&hex) == 32);
Rng shuffle = Rng::from_os(); // differs each run; not for secrets
assert(Rng::below(&mut shuffle, 52) < 52);
}String
In std::text.
A String is a Vec<u8> that is known to be valid UTF-8: owned, heap-allocated text,
a resource. String::new() makes an empty one, String::copy copies any text (a str
value, a view, a part of a text; valid already, so nothing is checked), String::clone(&s) copies a
whole String, and String::from_utf8 validates bytes that came from anywhere else. Owned text from
a literal is the literal itself, wherever a String is declared or fixed: String s = "text";,
s = "text";, a struct literal's String field, an argument whose parameter is a String, the value
a function or a closure declared : String returns, Some("text") where an Option<String> is
expected, an element of an array<String, N> (D-0149, D-0304), and a literal argument whose generic
parameter the other arguments make a String: Result::unwrap_or(arg(0), "default"),
Vec::push(&mut names, "x") for a Vec<String> (D-0162). That is the one place a literal
allocates, and the word String in a declaration nearby says so; a str variable is never
made a String without String::copy, and auto s = "text"; is a str. (String::from_str,
which wrote the same thing a second way, was removed, D-0305.) It changes only through functions that keep it valid UTF-8 — append and
appendf add text, push_ascii an ASCII byte, truncate cuts at a character boundary, clear
empties it — so the guarantee holds for its whole life. from_utf8 is the trust-transition pattern of §20 in
miniature.
| Function | Signature |
|---|---|
String::new | () : String (empty) |
String::from_utf8 | (Vec<u8>) : Result<String, Utf8Error> |
StringView::from_utf8 | (slice<u8, shared>) : Result<StringView, Utf8Error> -- the same check, and a view of the bytes instead of a copy |
String::into_bytes | (String) : Vec<u8> (gives the bytes back, consuming the string) |
String::append | (ref<String, exclusive>, T) for any T %v takes: adds what printf("%v", x) would write |
String::clone | (ref<String, shared>) : String (a copy with the same bytes) |
String::reserve | (ref<String, exclusive>, usize n): room for n more bytes; the text is unchanged (D-0129) |
a == b, a < b | any two texts, of any of the three types, compared by their bytes (s == "x", s < v, t == s), a String borrowed for it, not moved |
String::less, StringView::less | (ref<String, shared>, ref<String, shared>) : bool: byte order, a prefix first, as a < b (§12); Vec::sort(&mut v) sorts text |
StringView::to_ascii_lower, StringView::to_ascii_upper | (ref<String, shared>) : String: a copy with ASCII letters changed; other bytes as they are |
String::truncate | (ref<String, exclusive>, usize n): keeps the first n bytes (n at or beyond the length changes nothing); n inside a character faults diag.not-char-boundary |
String::push_ascii | (ref<String, exclusive>, u8): adds one ASCII byte; one of 128 or more faults diag.not-ascii |
String::clear | (ref<String, exclusive>) (empties it, keeping the buffer) |
For bytes, std has the ASCII tests and conversions a parser needs: ascii_is_digit(b),
ascii_is_alpha, ascii_is_alnum, ascii_is_upper, ascii_is_lower, ascii_is_space (a space,
tab, newline, carriage return, vertical tab or form feed) take a u8 and give a bool;
ascii_to_lower(b) and ascii_to_upper(b) give the u8 with an ASCII letter's case changed.
Unicode case is not provided.
import std;
fn main()
{
assert(ascii_is_digit(b'7') && !ascii_is_alpha(b'7') && ascii_is_space(b'\t'));
assert(ascii_to_upper(b'q') == b'Q');
String shout = StringView::to_ascii_upper(&String::copy("caf\u{e9} au lait"));
assert(shout == "CAF\u{e9} AU LAIT");
}import std;
fn main()
{
String owned = "caf\u{e9}"; // a str's bytes, copied; no validation needed
assert(StringView::len(&owned) == 5); // 5 bytes: é is two of them
assert(StringView::char_count(&owned) == 4); // but 4 characters
assert(Vec::len(&StringView::chars(&owned)) == 4); // each a view of its bytes
Vec<u8> good = Vec::new();
Vec::push(&mut good, 226); // the three bytes of U+20AC, the euro sign
Vec::push(&mut good, 130);
Vec::push(&mut good, 172);
String s = match (String::from_utf8(good)) // good moves in
{
Ok(v) : v,
Err(_) :
{
return;
},
};
assert(StringView::len(&s) == 3);
Vec<u8> back = String::into_bytes(s); // and out again
assert(Vec::len(&back) == 3);
Vec<u8> bad = Vec::new();
Vec::push(&mut bad, 226); // a truncated sequence
Vec::push(&mut bad, 130);
match (String::from_utf8(bad))
{
Ok(_) :
{
assert(false, "unreachable");
},
Err(e) :
{
assert(e.offset == 0);
},
}
}StringView: part of a String, without copying
In std::text.
&s[i..j] on a String gives a StringView: a read-only view of the bytes i to j,
with no copy. Positions are byte positions, $ is the length, and both ends must fall on a
character boundary (cutting through a multi-byte character is diag.not-char-boundary). A view
prints with %s, compares with == to another view or a str, and can be sliced again,
&v[1..$]. It borrows its String exactly as a slice borrows a Vec: while the view lives, the
String cannot be changed, and a view cannot outlive it. String::copy(v) copies it into a
String of its own when it must.
| Function | Result |
|---|---|
StringView::len(v) | its length in bytes |
StringView::of(t) | a view of a str t; a literal where a view is expected is one already (D-0134) |
StringView::as_bytes(v) | the view's bytes as a slice<u8, shared>, not a copy: what a hash, a MAC or a socket write takes (D-0163) |
StringView::find(v, t) | Option<usize>: where the text of the view t first occurs |
StringView::starts_with(v, t), ends_with | bool |
StringView::trim(v), trim_start, trim_end | the view without ASCII white space at its ends |
StringView::split(v, ",") | a Vec<StringView> of the parts, each a view of the same String |
StringView::chars(v) | a Vec<StringView> of its characters, in order, one view each (D-0128) |
StringView::char_count(v) | how many characters it holds (len counts bytes; D-0193) |
StringView::contains(v, t) | bool: whether the text of t occurs in v (D-0139) |
StringView::replace(v, from, to) | a new String: v with every occurrence of from replaced by to, left to right, no overlap; an empty from occurs nowhere |
StringView::join(&parts, sep), String::join(&strings, sep) | a new String: the parts with sep between each two; the inverse of split |
StringView::parse<T>(v) | a number of type T, the whole text or an error; StringView::parse<T>(&s) for a String |
String::copy(v), String::append(&mut s, v) | the text copied into a String |
StringView::find(&s, t) and the rest, for a String s | &s is the view of s where a StringView is declared (D-0302), so each StringView:: function takes a String as &s; &s is that view where nothing declares one. The String:: copies of these functions were removed (D-0306), and String::len, chars, char_count, code_point and parse were removed too (D-0308): StringView::len(&s) and the rest |
Text that a function only reads is a StringView throughout std: a file's path, the text
to search for, the text to write (D-0134). A String passes &s: where a StringView is
declared, &s is its whole-string view, &s[0..$] (D-0302), and a ref<String, shared> in hand
passes itself the same way. A literal passes itself: a str literal where a StringView is expected
is a view of it, and since a str never ends, neither does the view; so does a str held in a
variable (StringView::of(t) spelled out). The borrow is still written: &mut s is not a view, and
a String by value is not one either. (split's separator is text too: split returns views of its
first argument alone, and its declaration says so with from v, §10.)
import std;
fn main()
{
String text = "the cat sat on the mat";
String word = "sat";
assert(StringView::find(&text, &word) == Some(8)); // a String to search for
assert(StringView::find(&text, "mat") == Some(19)); // a literal: already a view
str w = "on";
assert(StringView::find(&text, w) == Some(12)); // a str: a view of it
StringView label = "fixed"; // a view of a literal, for the whole run
printf("%s %d\n", label, StringView::len(label));
}fixed 5
import std;
// The first word of a line: a view into the line itself.
fn first_word(ref<String, shared> s) : StringView
{
StringView t = StringView::trim(s);
match (StringView::find(t, " "))
{
Some(i) : &t[0..i],
None : t,
}
}
fn main()
{
String line = " set width=80, height = 24 ";
assert(first_word(&line) == "set");
StringView args = StringView::trim(&line[6..$]); // "width=80, height = 24"
i64 area = 1;
foreach (field in StringView::split(args, ","))
{
match (StringView::find(field, "="))
{
Some(eq) :
{
StringView value = StringView::trim(&field[eq + 1..$]);
match (StringView::parse<i64>(value))
{
Ok(n) : { area *= n; },
Err(_) : { assert(false, "unreachable"); },
}
},
None : { assert(false, "unreachable"); },
}
}
assert(area == 1920);
printf("%s -> %d\n", args, area);
}width=80, height = 24 -> 1920
Three questions come up so often that they have their own names (D-0139). contains is
find with a yes-or-no answer. replace makes a new String with every occurrence of one text
replaced by another, scanning left to right so occurrences never overlap; the empty text occurs
nowhere, so replacing it changes nothing. join is the inverse of split: the parts with a
separator between each two, from a slice of views (what split gives) or a slice of Strings
(what a program builds). Each takes its texts as StringViews, so a literal, a String as &s
and another view all serve.
import std;
fn main()
{
String path = "/usr/local/lib/cobaltc";
assert(StringView::contains(&path, "/local/") && !StringView::contains(&path, "bin"));
String windows = StringView::replace(&path, "/", "\\"); // a new String; path unchanged
printf("%s\n", &windows);
String aaa = "aaa";
printf("%s\n", &StringView::replace(&aaa, "aa", "b")); // left to right, no overlap: "ba"
Vec<StringView> parts = StringView::split(&path, "/"); // "", "usr", "local", "lib", "cobaltc"
printf("%s\n", &StringView::join(&parts[1..$], " > "));
assert(StringView::join(&parts, "/") == path); // join undoes split
Vec<String> names = Vec::new();
Vec::push(&mut names, "ada");
Vec::push(&mut names, "grace");
printf("%s\n", &String::join(&names, ", "));
}\usr\local\lib\cobaltc ba usr > local > lib > cobaltc ada, grace
import std;
fn main()
{
String name = "ada";
StringView v = &name;
String::push_ascii(&mut name, b'!'); // ✗ diag.aliasing-conflict (static): v still views name
assert(v == "ada");
}Going through the characters
foreach does not take a String itself, and there is no char type; StringView::chars(&s)
gives the characters instead: a Vec<StringView>, one view per character, in order. A character is
one to four bytes of UTF-8 (é is two, most emoji four), so Vec::len of it counts characters where
StringView::len counts bytes. Each view is text like any other: it prints, compares with == to a
str, is matched by text patterns, and appends to a String; and like any view it borrows the
String while it is in use. StringView::chars(v) does the same for a view, such as a word from
split. Building the Vec is one allocation; there is no form that visits the characters without
it, because foreach walks only the collections the language defines and there is no iterator
protocol for a library to plug into (D-0128 explains). Where that matters, walk
StringView::as_bytes(&s) instead.
import std;
fn main()
{
String s = "caf\u{e9} \u{1F600}!";
foreach (c in StringView::chars(&s))
{
printf("[%v]", c);
}
printf("\n%v characters in %v bytes\n", Vec::len(&StringView::chars(&s)), StringView::len(&s));
// Reversed by characters, so the two-byte é and the four-byte emoji stay whole.
Vec<StringView> cs = StringView::chars(&s);
Vec::reverse(&mut cs);
String back = String::new();
foreach (c in &cs)
{
String::append(&mut back, *c);
}
printf("%v\n", &back);
// Positions and text patterns work on each character.
foreach (i, c in StringView::chars(&s))
{
match (c)
{
"\u{e9}" : printf("\u{e9} is character %v\n", i),
"!" : printf("! is character %v\n", i),
_ : {},
}
}
}[c][a][f][é][ ][😀][!] 7 characters in 11 bytes !😀 éfac é is character 3 ! is character 6
Lines, words, prefixes and code points (D-0181). lines splits text at
, dropping a
before it and giving no empty line after a final newline; split_whitespace
gives the words between runs of ASCII whitespace, none empty; strip_prefix(v, t) and
strip_suffix give the rest of the text as Some(view) when it begins (or ends) with t, and
None otherwise, which is how --name=value is read. code_point(v) is the number of the first
character (None for empty text), and String::push_code_point(&mut s, cp) appends one as UTF-8,
turning a surrogate or a value above U+10FFFF into U+FFFD so the String stays valid. Each exists on
a String as &s (StringView::lines(&s), …). StringView::parse<bool> reads exactly true or false.
A foreach over a call of lines, split (its separator a literal), split_whitespace or chars
finds each part as it reaches it and makes no Vec (D-0287, guide chapter P); bind the Vec first only to take its
length or index it, as the example's words does.
import std;
fn main()
{
String config = "name = demo\r\nlevel = 3\n\n# a comment\nflags = loud fast\n";
foreach (line in StringView::lines(&config))
{
if (StringView::starts_with(line, "#") || StringView::len(line) == 0)
{
continue;
}
Vec<StringView> words = StringView::split_whitespace(line);
printf("%v -> %v word(s)\n", words[0], Vec::len(&words) - 2);
}
foreach (a in ["--level=7", "--quiet", "file.txt"])
{
match (StringView::strip_prefix(a, "--level="))
{
Some(v) : printf("level %v\n", Result::unwrap_or(StringView::parse<u32>(v), 0)),
None : printf("other: %s\n", a),
}
}
String s = "é";
printf("U+%04X\n", Option::unwrap_or(StringView::code_point(&s), 0));
String t = String::new();
String::push_code_point(&mut t, 0x1F600);
printf("%v has %v bytes\n", &t, StringView::len(&t));
}name -> 1 word(s) level -> 1 word(s) flags -> 2 word(s) level 7 other: --quiet other: file.txt U+00E9 😀 has 4 bytes
Which text type?
Rust programmers will recognise the pair, and C programmers may wonder why there are two
text types at all. The reason is that a constant should not have to be managed. If "hi" were a
String, every literal would be a heap allocation with an owner: it would be moved, destroyed at
scope end, and allocated again on every pass through a loop, all for text that never changes. So a
literal is a str, which behaves like the number 5. String is kept for text that really does
need an owner.
str | String | StringView | b"…" | |
|---|---|---|---|---|
| What it is | a text constant | owned text | a read-only view of text someone else owns, or of a constant | raw bytes |
| Made by | a literal, a const | a literal where a String is declared; String::copy(t); String::from_utf8(bytes); sprintf | &s, &s[i..j], a literal or a str where a view is declared | b"hello" |
| Type | str | String | StringView | array<u8, N> |
| Ends | never | with its owner | at its last use | as any array |
| Allocates | never | yes | never | no (an ordinary array) |
They stand to each other as an array, a vector and a slice do. Text fits its
declaration (D-0312): where a declaration says String, a literal is one (the one place a
literal allocates); where it says StringView, a literal, a str and &s of a String are views,
as &v of a Vec is a slice where a slice is declared. Nothing turns a view or a String into a
str, and a str variable never becomes a String without String::copy. Those are the
language's only two coercions, and each is exactly the expression you could have written yourself
(&s[0..$], &v[0..$]).
Why str is a type of its own. CobaltC has no lifetime parameters, so a
signature cannot say "this text lives for the whole program" the way Rust's &'static str does; a
type says it instead. A StringView always views something that ends (a String, a buffer, a
parameter), and the checker follows it there: a struct with a StringView field holds a reference
and must end no later than the text it views, and a function with two reference parameters that
returns a view, or a value holding one, names its source with from (D-0319). A str views
nothing that ends. It is a plain value in a const, in a table, in a struct field (the struct
stays plain: copied like a number, kept as long as you like) and in a result: fn name(Color c) :
str needs no from clause whatever it takes. Without str, each of those would be a String,
allocated and owned for text that never changes, or a view tied to something that must outlive
it.
The price is that nothing becomes a str: not a String, not a view. Text read or built at
run time can never be passed where a str is declared, and that decides the type of a parameter.
| Type | Use it for |
|---|---|
str | constants and tables; fields and results that only ever hold text written in the program: a name, a label, a keyword, an error's description |
StringView | every parameter that only reads text while the call runs, to parse, search, compare, print or copy it; a field or result that refers to text owned elsewhere |
String | text built or received at run time that has to be kept |
A str parameter is right in two cases: the function keeps the text after it returns
(Args::flag(&mut a, "loud", "l", "shout") stores the names in a; views would make Args hold
references into its caller's text), or the parameter is a message or a label every caller writes as
a literal (Option::expect(o, "no config")). Anywhere else, take a StringView: fn parse(str s)
cannot parse a line read from a file, while fn parse(StringView s) takes "42", a str, &line
and &line[3..5] alike, at no extra cost.
- Write
&on the thing you own and nowhere else:&sfor aString,&vfor aVec; a view, a slice, astr, a literal or a reference you already hold is passed as it is. - A function that only reads text takes a
StringView, asstd's do: a caller passes"key", astr, a view or&s, and nothing is copied. - All three compare with
==and<by their bytes, in any combination (name == "sha256",s < v). - A
String-keyed map is asked with any text and allocates only whenentryinserts:HashMap::get(&m, "k"),HashMap::get(&m, word); an integer key is asked by its value,HashMap::get(&counts, 7), a struct key by&pos. - Bytes from outside the program stay
Vec<u8>untilString::from_utf8accepts them; bytes that are not text useb"…".
Unicode. All three are UTF-8 bytes, and std works on them as bytes: lengths
and indices count bytes, == and the orderings compare bytes, and StringView::chars hands out the code
points when you need them. std has no Unicode tables (D-0226): case mapping is ASCII only
(StringView::to_ascii_lower), there is no normalization, so "é" and "e\u{301}" are different strings, and no
splitting into user-perceived characters. A program that needs those brings its own tables.
In a generic function the conversion must be the same in every instantiation: one body cannot
view &k for a String and keep it for an integer. A generic lookup takes the key's probe instead,
probe<K>: a view for a String key, the key itself for a number, bool or str, a reference
otherwise. StringView::split(v, sep) takes any text as its separator: its parts are views of v,
and its declaration says so, : Vec<StringView> from v.
Printing: printf
In std::io (printf, eprintf, flush_stdout) and std::text (sprintf, String::appendf).
printf is the one way a program writes output. It is C's, with one difference that matters: the format is checked against its
arguments when the program is compiled. The format must be a string literal; each % specifier
must match its argument's type and there must be exactly one argument per specifier, or the
program is rejected (diag.type-mismatch, or diag.format-invalid for a malformed specifier). So
a printf can never misprint or crash at run time. sprintf(fmt, args…) returns the same text as a
new String (C's sprintf without a buffer to overflow), and String::appendf(&mut s, fmt, args…)
adds it to an existing one. eprintf(fmt, args…) writes the same text to standard error, for
messages that are not the program's output. There is no println; end a line with \n.
Standard output is buffered, so printing line by line is fast. The text reaches the
screen, a pipe or a file in pieces, but never later than the next eprintf, the next read of
standard input, the start of a child that shares standard output (Command::status), and the
program's end, however it ends. On a terminal each line also appears as soon as it is complete. So
the two streams keep the program's order, and a prompt is shown before the program waits for the
answer. Call flush_stdout() only when standard output goes to a pipe or a file and someone watches
it while the program runs: a progress line, a log.
A write to standard output that the system refuses (a full disk) does not stop the program,
but it is not lost silently either: a program that would end with status 0 ends with 1, and says on
standard error that its output was not all written, after a fault's report if it ends by a fault
([Print-Failure]). When the reader of a pipe has gone, as head goes once it has its lines, the program
ends there, as exit(1) ends it: its destructors run and nothing is said ([Print-Reader-Gone]), so
prog | head -3 stops at once, as a C program does. A program started with standard output, error or
input closed (prog >&-) gets the null device in its place, so a file it opens never receives what it
prints; a write to a standard output closed that way counts as refused.
| Specifier | Takes | Prints |
|---|---|---|
%d %i | any integer type | decimal; no %ld/%lld/%zu needed, the type is known |
%u | any integer type | the bits in the value's own width as an unsigned decimal, as C (-1: i32 is 4294967295) |
%x %X %o %b | any integer type | hex, octal, binary (# adds 0x, 0X, 0o, 0b) |
%f %e %g (and %F %E %G) | f32, f64 | fixed, exponent, or shortest of the two, 6 digits by default |
%s | str, &String, StringView, bool | the text |
%v | any of the above | the value as CobaltC writes it (below) |
%% | nothing | a % |
Flags, a width and a precision work as in C: %-8s pads on the right, %05d pads with
zeros, %+d always shows a sign, %.2f rounds to two decimals, %8.3f does both. %v takes a
width and - but not 0, + or a precision, since it writes each value in one fixed form: for
%09 or %.3, use the specifier of the value's own kind (%09d, %.3f, %016x). Widths count
characters, so text in any language lines up; to size a column to its text, count the characters
too, Vec::len(&StringView::chars(&s)), since StringView::len counts bytes. There is no %c. A * in place of the width or
the precision takes it from the next argument, which must be a usize: printf("%*d", w, n),
printf("%.*s", n, &s).
import std;
fn main()
{
usize w = 6;
printf("[%*d]\n", w, 42);
printf("[%-*s]\n", w, "ab");
printf("[%.*f]\n", 2: usize, 3.14159);
}[ 42] [ab ] [3.14]
import std;
fn main()
{
String item = "widget";
u32 qty = 12;
f64 price = 3.5;
printf("%-8s|%5d|%8.2f|%#06x\n", &item, qty, price, 255);
printf("%.1f%% done, %e left\n", 99.5, 0.00042);
String line = sprintf("%s x %d", &item, qty);
String::appendf(&mut line, " = %.2f", price * 12.0);
printf("%v\n", &line);
}widget | 12| 3.50|0x00ff 99.5% done, 4.200000e-04 left widget x 12 = 42.00
import std;
fn main()
{
printf("%d items\n", "twelve"); // ✗ diag.type-mismatch: %d takes an integer
}cobc --run greet.cb with no argumentrunsimport std;
fn main() : u8
{
if (arg_count() != 1)
{
eprintf("usage: greet NAME\n"); // to standard error, not mixed into the output
return 2;
}
match (arg(0))
{
Ok(name) :
{
printf("hello, %s\n", &name);
},
Err(e) :
{
eprintf("greet: the name is not UTF-8 (byte %d)\n", e.offset);
return 1;
},
}
0
}%v: any value
%v is not C's: it writes a value the way CobaltC writes it, whatever its type, so
printf("%v\n", x) needs no thought about x. It takes any of the types below, and nothing else:
a struct or a Vec is a static type error, so printing a composite value means printing its
parts; an enum prints its variant's name. It takes a width and -, but no precision.
| Argument | Written as | Examples |
|---|---|---|
str | its bytes | printf("%v", "hi") → hi |
| any integer type | decimal, - if negative | -42, 18446744073709551615 |
f32, f64 | the shortest digits that read back as the same value | 0.1, 1.0, 0.3333333333333333, 1.0e21, 1.0e-7, NaN, inf |
bool | true or false | |
ref<String, shared> | the string's bytes | printf("%v", &s) |
StringView | its text | printf("%v", word) |
| an enum, or a reference to one | its variant's name (not its payload) | Some, Mul, NotFound |
A float prints as few digits as identify it exactly: 0.1 prints as 0.1, even though
the stored value is slightly more than a tenth, and reading the printed text back gives the same
value. A whole number keeps a .0, so floats and integers look different. Between 0.000001 and
1021 the number is written out in full; beyond that range it gets an exponent. An f32 chooses
its digits as an f32, so 0.1: f32 also prints 0.1. This is the rule JavaScript and Python
use.
%v's argument type is checked where the printf is, and a generic function can print
its own T. The check happens for each type the function is used with, so show below
accepts numbers and text, and would be rejected for a struct.
import std;
fn show<T>(T x) // T is checked where show is used
{
printf("%v\n", x);
}
fn main()
{
show(-42);
show(max_value<u64>());
show(true);
show(0.1);
show(1.0);
show(1.0 / 3.0);
show(0.1: f32);
show(1000000000000000000000.0);
f64 zero = 0.0;
show(zero / zero);
String name = "owned text";
printf("%v", &name); // a String through a reference: name stays usable
printf("\n");
printf("x = %v, y = %v\n", 3, 4.5);
}-42 18446744073709551615 true 0.1 1.0 0.3333333333333333 0.1 1.0e21 NaN owned text x = 3, y = 4.5
import std;
fn main()
{
String s = "text";
printf("%v", s); // ✗ diag.type-mismatch (static): a String prints through &s
}import std;
struct Point
{
i32 x;
i32 y;
}
fn main()
{
printf("%v", Point { .x = 1, .y = 2 }); // ✗ diag.type-mismatch (static): print the fields instead
}Raw bytes are not text, so printf does not take a u8 as a character or a Vec<u8>:
a u8 prints as a number. To write bytes, use the stdout_write extern the way std does, around an
unsafe block. put writes one byte and print_bytes a whole Vec<u8>:
import std;
// Write one byte to standard output.
fn put(u8 b)
{
auto buf = [b]; // an array<u8, 1>
rawptr<u8> p = reinterpret_ptr<u8>(rawptr_of(&buf));
unsafe
{
stdout_write(p, 1); // trusted: p points at one valid byte
}
}
fn print_bytes(ref<Vec<u8>, shared> v)
{
foreach (b in v)
{
put(*b);
}
}
fn main()
{
put(b'a'); // the byte of `a`
printf("%v", b'a'); // a u8 prints as a number: 97
put(b'\n');
Vec<u8> v = Vec::new();
Vec::push(&mut v, b'o');
Vec::push(&mut v, b'k');
Vec::push(&mut v, b'\n');
print_bytes(&v);
}a97 ok
import std;
fn main()
{
str t = "hi";
String s = t; // ✗ diag.type-mismatch (static): t is a str value;
// String::copy(t) makes the String
}import std;
fn main()
{
String s = "hi"; // ✓ a literal where a String is declared is that String (D-0149)
str t = "there";
String u = String::copy(t); // ✓ the explicit, allocating bridge for a str value
assert(StringView::len(&s) == 2 && StringView::len(&u) == 5);
}Reading input
In std::io.
read_line() reads the next line of standard input. It returns a
Result<Option<String>, FileError>:
| Result | Meaning |
|---|---|
Ok(Some(line)) | the next line, without its \n (a final \r\n is removed whole); a last line with no \n counts too |
Ok(None) | the input has ended (and every later call says so again) |
Err(Utf8(e)) | the line is not valid UTF-8; e.offset is the bad byte's position in the line, and the next call reads the line after it |
Err(Io) | the input could not be read |
A line ends at \n, and a \r just before it is removed with it, so a line typed
on Windows reads the same as one typed on Linux. The line is a
String that has already been checked, so a program that reads never writes unsafe, and ?
passes a FileError up to the caller: the same error a file gives (D-0134), whose NotFound and
Denied never come from standard input, so a match that names Io and Utf8 ends with _.
Underneath is the stdin_read extern, the counterpart of stdout_write, which you can call
yourself inside unsafe to read raw bytes.
A program reads standard input from the terminal or from a pipe, for example
printf 'ada\nlin\n' | cobc --run greet.cb. Standard output is flushed before each read, so a prompt
printed with printf appears before the program waits.
import std;
// Greets every line of input; blank lines are skipped.
fn greet_all() : Result<usize, FileError>
{
usize count = 0;
while (Some(name) = read_line()?) // None: the end of input; an error goes back to main
{
if (StringView::len(&name) > 0)
{
printf("hello, %v\n", &name);
count += 1;
}
}
Ok(count)
}
fn main()
{
match (greet_all())
{
Ok(n) :
{
printf("%v greeted\n", n);
},
Err(e) :
{
match (e)
{
Io :
{
printf("could not read input\n");
},
Utf8(u) :
{
printf("not UTF-8 at byte %v\n", u.offset);
},
}
},
}
}A program that needs all of its input before it can start, to sort it or parse it as one
document, takes it at once with read_all() (a String, Err(Utf8(e)) when it is not text) or
read_all_bytes() (a Vec<u8>, any bytes). Each gives what is left after any read_line calls,
line ends exactly as they came, and an empty result at the end of input.
import std;
fn before(ref<StringView, shared> a, ref<StringView, shared> b) : bool
{
((*a) < (*b))
}
// Sorts the lines of its input: `sort` in a few lines.
fn main() : u8
{
String all = match (read_all())
{
Ok(s) : s,
Err(e) :
{
eprintf("sort: %s\n", FileError::text(&e));
return 1;
},
};
Vec<StringView> lines = StringView::split(&all, "\n");
if (Vec::len(&lines) > 0 && StringView::len(lines[Vec::len(&lines) - 1]) == 0)
{
Vec::pop(&mut lines); // the empty piece after the last line end
}
Vec::sort_by(&mut lines, before);
foreach (l in &lines)
{
printf("%s\n", *l);
}
0
}Program arguments
In std::env.
arg_count() is the number of arguments the program was started with, and arg(i)
is argument i as a Result<String, Utf8Error>. Argument 0 is the first one after the program:
cobc --run prog.cb a b and ./prog a b both give a and b, and the program's own name
is not an argument. Each argument is checked on its own, so one that is not UTF-8 is an Err
without affecting the others. arg(i) with i ≥ arg_count() faults diag.index-out-of-bounds,
as indexing a Vec does. Underneath is the arg_bytes extern, which
you can call inside unsafe for an argument's raw bytes.
cobc --run args.cb one tworunsimport std;
fn main()
{
foreach (i in 0..arg_count())
{
match (arg(i))
{
Ok(a) : printf("%v: %v\n", i, &a),
Err(e) : printf("%v: not UTF-8 at byte %v\n", i, e.offset),
}
}
}0: one 1: two
Command-line options: Args
In std::env.
A tool declares its options as it reads them (D-0184): Args::flag(&mut a, "loud", "l", help)
says whether --loud or -l was given and takes every such argument; Args::option(&mut a, "times",
"n", "N", help) gives the value of --times=3, --times 3 or -n 3 (the last one, or None), and
Args::options every value of a repeated option; each call also adds a line to Args::help(&a).
Args::finish(&mut a) then gives what is left — the positional arguments, in order, with everything
after -- among them — or an Err naming the first option nobody declared, or an option missing its
value, for the program to print. A lone - is an argument. Args::new(usage) reads the program's own
arguments; Args::from(items, usage) takes any Vec<String>.
import std;
fn main() : u8
{
Args a = Result::unwrap(Args::new("greet [options] NAME..."));
bool loud = Args::flag(&mut a, "loud", "l", "shout");
bool help = Args::flag(&mut a, "help", "h", "show this help");
usize times = Result::unwrap_or(StringView::parse<usize>(&Option::unwrap_or(Args::option(&mut a, "times", "n", "N", "how many times"), "1")), 1);
if (help)
{
printf("%v", &Args::help(&a));
return 0;
}
Vec<String> names = match (Args::finish(&mut a))
{
Ok(rest) : rest,
Err(m) :
{
eprintf("greet: %v\n", &m);
return 2;
},
};
foreach (i in 0..times)
{
foreach (n in &names)
{
printf("%v, %v!\n", if (loud) { "HELLO" } else { "hello" }, n);
}
}
0
}HELLO, world! HELLO, world!
Run with --help the same program prints:
Usage: greet [options] NAME...
Options:
-l, --loud shout
-h, --help show this help
-n, --times N how many timesDeclaring one name or one letter twice is a fault at the second declaration (-v for both
--verbose and --version would let the first take every -v). A git-style tool, whose command has
options of its own, first calls Args::command(&mut a, "-C") ([Args-Command]): it takes the first argument that is
neither an option nor the value of one of the options named there (the global ones that take a
value), and everything after it, so tool -v commit -m hi gives the command commit -m hi, and the
program's declarations read only -v. The command's options are then read from
Args::from(cmd, "tool commit -m MSG"), whose finish gives the command first.
Numbers and text
In std::text.
String::append(&mut s, x) adds to s exactly what printf("%v", x) would write, for the same
types: a str, any integer, f32/f64, bool, a StringView, or another String through &. So a line can be
built piece by piece and printed, or kept, once. StringView::parse<T>(&s) goes the other way: it reads the
whole String as a number of type T, any integer type, f32 or f64, and returns a
Result<T, ParseError>.
| Result | Meaning |
|---|---|
Ok(v) | the whole text is a number, and it fits in T |
Err(Empty) | the text is empty |
Err(Invalid(k)) | byte k cannot continue a number ("12x4" → 2), or the text ends too early ("-" → 1) |
Err(OutOfRange) | a number, but not one T can hold ("300" as u8) |
Parsing is strict: an optional + or -, then digits, and for a float an optional fraction and
exponent (2.5e-3), or inf or NaN. No spaces anywhere; read_line removes a Windows line’s
\r\n whole, so its lines parse, but a \r from any other source is Invalid. Floats are rounded correctly, and every float %v writes parses back to
the same value. To take a line apart first, split, trim or search it as views (StringView::split(&s, …),
trim, find, the StringView functions above) and parse a piece with StringView::parse<T>.
cobc --run sum.cb 1.5 2 0.25runsimport std;
// Adds up its arguments: `cobc --run sum.cb 1.5 2 x` reports the `x`.
fn main() : u8
{
f64 total = 0.0;
foreach (i in 0..arg_count())
{
String a = Result::unwrap_or(arg(i), String::new());
match (StringView::parse<f64>(&a))
{
Ok(v) : total += v,
Err(_) :
{
String msg = String::new();
String::append(&mut msg, "argument ");
String::append(&mut msg, i);
String::append(&mut msg, " is not a number: ");
String::append(&mut msg, &a);
String::append(&mut msg, "\n");
printf("%v", &msg);
return 1;
},
}
}
String line = String::new();
String::append(&mut line, "total ");
String::append(&mut line, total);
String::append(&mut line, "\n");
printf("%v", &line);
0
}total 3.75
Numeric helpers in std::math (D-0181): clamp(x, lo, hi) holds a value within
bounds; gcd(a, b) is the greatest common divisor, never negative; is_nan(x) and is_finite(x)
ask about a float (an integer is always finite); and asin, acos and atan join the
floating-point functions. Vec::sort orders f32 and f64 too, with every NaN last.
Files
In std::fs.
read_file(path) reads a whole file as a String; write_file(path, text) makes the
file hold exactly text, creating it or replacing what it held. Both take the path, and the text,
as a StringView (D-0134): a literal, read_file("notes.txt"), or a String's whole-string view,
read_file(&path) for a path that came from arg. They return a Result whose error is a
FileError: NotFound,
Denied, Utf8(e) for a file that is not valid UTF-8 (with the offset of the first bad byte), or
Io for anything else. A relative path is relative to the directory the program runs in. Both
tools read and write files. FileError::text(&e) is the error as a sentence for a person
("not found", "permission denied", …), as ParseError::text and Utf8Error::text are for
theirs (D-0117); %v of an error prints its variant's name instead. A parser's error in a file a
person wrote is best placed: ParseError::describe(&e, &text) gives line 3, column 1: unexpected '}'.
| Function | Signature |
|---|---|
read_file | (StringView path) : Result<String, FileError> |
write_file | (StringView path, StringView text) : Result<void, FileError> |
These two handle the whole file at once; File, below, reads and writes one in pieces.
import std;
fn main() : u8
{
String text = "first line\nsecond line\n";
if (Err(_) = write_file("notes.txt", &text))
{
printf("cannot write notes.txt\n");
return 1;
}
String back = Result::unwrap_or(read_file("notes.txt"), String::new());
printf("%v", &back);
match (read_file("no-such-file.txt"))
{
Ok(_) : printf("?\n"),
Err(NotFound) : printf("no-such-file.txt: not found\n"), // a pattern inside a pattern
Err(_) : printf("no-such-file.txt: cannot read it\n"),
}
0
}first line second line no-such-file.txt: not found
Open files: File
In std::fs.
A File is an open file, for what read_file cannot do: bytes that are not text, files
too large to hold, appending to a log. It is a resource, like Vec: it has one owner, can move to
another thread, and its destructor closes it. close closes it too, and reports whether that
worked (for a written file, whether the bytes were stored); after close the File is gone,
so it cannot be used again. Every operation returns a Result whose error is a FileError.
| Function | Does |
|---|---|
File::open(path) | open for reading; the file must exist (path a StringView, as for read_file) |
File::create(path) | open for writing, empty: created, or its contents discarded |
File::append(path) | open for writing at the end, created if missing |
File::open_rw(path) | open for reading and writing, created if missing, contents kept |
File::read_line(&mut f) | the next line without its \n (nor a \r before it), None at the end (as read_line) |
File::read(&mut f, &mut buf, max) | append up to max bytes to a Vec<u8>; how many, 0 at the end |
File::read_to_end(&mut f, &mut buf) | append the rest of the file to a Vec<u8> |
File::write(&mut f, &bytes[i..j]), File::write_text(&mut f, text) | write all of a slice of bytes, or text (a StringView: a literal, or &s of a String) |
File::printf(&mut f, "format", …) | write formatted text, as printf formats it |
File::seek(&mut f, pos), File::len(&f) | move to byte pos (a u64); the length in bytes |
File::create_new(path) | Ok(Some(file)) on a new file, Ok(None) when something is already there: a lock or pid file that two programs race for (D-0181) |
File::create_private(path) | as create_new, a file only its owner may read or write (mode 0600 on Unix, whatever the umask): for a token, a key, a session ([Private-Files]) |
File::flush(&mut f), File::position(&f) | make everything written durable (fsync) — flush, then rename, for a file that must survive a crash; the byte the next read or write starts at (D-0181) |
File::close(f) | close it and say whether that worked |
read_bytes(path), write_bytes(path, &bytes[i..j]) | read_file and write_file for bytes: a Vec<u8> |
Reading is buffered, so read_line is quick, and File::read fills up to what was asked for.
Writing is buffered too (D-0201), so writing a file line by line is fast. The program itself always
sees what it wrote: the bytes reach the file before the same file's next operation, before any
other file operation of the program (opening, read_file, file_info, removing, renaming), before a
child process starts, and when the program ends, however it ends. Another program watching the file
while yours runs sees them at those points; File::flush writes them out at once.
import std;
fn main()
{
File log = Result::expect(File::create("app.log"), "cannot create the log");
foreach (i in 1..4)
{
_ = File::printf(&mut log, "event %v\n", i); // `_ =`: the result is not needed
}
_ = File::close(log);
File input = Result::expect(File::open("app.log"), "cannot open the log");
printf("%v bytes\n", Result::unwrap_or(File::len(&input), 0));
while (Ok(Some(line)) = File::read_line(&mut input)) // stops at the end, or an error
{
printf("read: %s\n", &line);
}
_ = File::seek(&mut input, 6);
Vec<u8> bytes = Vec::new();
_ = File::read(&mut input, &mut bytes, 1);
printf("byte 6 is %v\n", bytes[0]);
}24 bytes read: event 1 read: event 2 read: event 3 byte 6 is 49
Directories, the environment and the clocks
Directories, paths and file metadata in std::fs; the environment in std::env; the clocks in std::time.
Files live in directories, which a program can make, list and clean up; it can also read its
environment and measure time. Paths are StringViews, as for files, and failures are FileErrors.
| Function | Does |
|---|---|
make_dir(path) | make a directory: Ok(true) made, Ok(false) one was already there |
remove_file(path), remove_dir(path) | remove a file, or an empty directory |
rename(from, to) | move a file or directory, replacing a file at to |
list_dir(path) | the names in a directory, sorted: a Vec<String>; list_dir_bytes(path) gives them as bytes, a name that is not UTF-8 among them |
path_kind(path) | File(len), Dir or Other, a link followed; Err(NotFound) when nothing is there |
read_link(path) | Some(target) when path is a symbolic link (not followed), None when it is not: a walker skips links with it ([Read-Link]) |
make_temp_dir(prefix) | a new directory under temp_dir() that only its owner may use, its name prefix and a random UUID |
env_var(name) | Ok(Some(value)), or Ok(None) when the variable is not set |
current_dir() | the working directory, which relative paths start from |
monotonic_ns(), unix_seconds() | a clock for measuring time (never goes back), and the date |
sleep_ms(ms) | the calling thread does nothing for at least ms milliseconds; other threads run meanwhile (D-0124) |
make_dir_all(path), remove_dir_all(path) | make a directory and any missing ones above it; remove a directory and everything in it |
copy_file(from, to) | copy a file, replacing one at to; the number of bytes copied |
file_info(path) | a FileInfo: kind (as path_kind's), len, modified_unix (seconds since 1970) and readonly |
set_current_dir(path) | change the working directory, for the whole program |
temp_dir(), home_dir() | the system's directory for temporary files; the user's home directory, if known |
current_exe(), hostname() | the running program's own executable, for the files installed beside it; the machine's name, for a log line (D-0181) |
FileInfo has no mode or owner, and there is no chmod or
truncate: a program that must shorten a file writes the part it keeps to a new file and renames
that over the old one (rename replaces it at once), and a tool that writes archives gives the files
a mode of its own. A file that holds a secret is made with File::create_private, and temporary
files go in a directory of make_temp_dir's: a fixed name under temp_dir() is one another user of
the machine can make first, or point elsewhere with a link.
Paths have their own functions, because a path's grammar is the operating system's: / on
Unix, \ (and /) on Windows, where C:\ starts an absolute path. They read the text alone and
never touch the file system, except path_canonical, which asks the system where a path really
leads (following links; the path must exist). Use path_join rather than gluing with sprintf:
it puts in the right separator, only one, and an absolute tail replaces the base.
| Function | Gives |
|---|---|
path_join(base, tail) | base and tail with one separator between, as a String |
path_parent(p), path_file_name(p) | Some part, or None: /a/b and c.txt of /a/b/c.txt |
path_stem(p), path_extension(p) | archive.tar and gz of archive.tar.gz; .bashrc has a stem and no extension |
path_is_absolute(p), path_normalize(p) | whether p starts from a root; p with . and x/.. removed, by the text alone |
path_canonical(p) | the absolute path the system resolves p to |
import std;
fn main() : u8
{
DateTime day = DateTime::from_unix(1791022620);
String name = sprintf("app-%d-%02d-%02d.log", day.year, day.month, day.day);
String top = match (make_temp_dir("guide-logs-")) // new, and no other user's
{
Ok(d) : d,
Err(_) : return 1,
};
String dir = path_join(&top, "2026");
if (Err(_) = make_dir_all(&dir))
{
return 1;
}
String log = path_join(&dir, &name);
if (Err(_) = write_file(&log, "started\n"))
{
return 1;
}
String stem = Option::unwrap_or(path_stem(&log), String::new());
String ext = Option::unwrap_or(path_extension(&log), String::new());
printf("%s: stem %s, extension %s, absolute %v\n", &name, &stem, &ext, path_is_absolute(&log));
match (file_info(&log))
{
Ok(i) : printf("%u bytes, written in the last minute: %v\n", i.len, unix_seconds() - i.modified_unix < 60),
Err(e) : printf("file_info: %s\n", FileError::text(&e)),
}
_ = remove_dir_all(&top);
String up = path_normalize("logs/2026/../2025/./app.log");
printf("normalized: %s\n", &up);
0
}app-2026-10-03.log: stem app-2026-10-03, extension log, absolute true 8 bytes, written in the last minute: true normalized: logs/2025/app.log
import std;
fn kind(StringView p) : str
{
match (path_kind(p))
{
Ok(File(_)) : "file",
Ok(Dir) : "directory",
Ok(Other) : "other",
Err(NotFound) : "missing",
Err(_) : "error",
}
}
fn main() : u8
{
if (Err(_) = make_dir("work"))
{
return 1;
}
_ = write_file("work/notes.txt", "remember\n");
_ = rename("work/notes.txt", "work/old.txt");
match (list_dir("work"))
{
Ok(names) :
{
foreach (n in &names)
{
printf("%s\n", n);
}
},
Err(_) : return 1,
}
printf("notes.txt: %s, old.txt: %s\n", kind("work/notes.txt"), kind("work/old.txt"));
_ = remove_file("work/old.txt");
_ = remove_dir("work");
printf("work: %s\n", kind("work"));
u64 t0 = monotonic_ns();
printf("time goes forward: %v\n", monotonic_ns() >= t0);
0
}old.txt notes.txt: missing, old.txt: file work: missing time goes forward: true
Dates and times
In std::time.
A DateTime is a moment in UTC to the second: year (an i64), month, day, hour,
minute and second, all fields a program can read. It converts to and from the seconds of
unix_seconds() and to and from ISO 8601 text, the form logs, file names and protocols use. The
one time zone std knows is the machine's own: DateTime::to_local shifts a moment into it for
showing to a person; there are no named zones and no other zone's rules.
| Function | Does |
|---|---|
DateTime::now(), DateTime::from_unix(s) | the moment now, or s seconds after 1970-01-01T00:00:00Z (before it when negative); every i64 is a moment |
DateTime::new(y, mo, d, h, mi, s) | Some moment, or None when the fields name none (a 30 February, an hour 24, a second 60) |
DateTime::to_unix(&t) | the seconds since 1970; a DateTime written by hand with impossible fields is the fault diag.invalid-datetime |
DateTime::to_iso(&t), DateTime::from_iso(text) | 2026-10-03T10:17:00Z as a String, and back; from_iso also takes a date alone, as its midnight, and gives a ParseError for anything else |
DateTime::weekday(&t), Weekday::text(&w) | the day of the week, Monday … Sunday, and its name |
DateTime::eq(&a, &b), DateTime::less(&a, &b) | the same moment; earlier (fits Vec::sort_by) |
unix_ms() | the wall clock in milliseconds since 1970 |
DateTime::to_local(&t) | the same moment written in the machine's local time, daylight saving included, by the operating system's rule |
DateTime::to_iso_local(&t) | the moment as local ISO 8601 text with its offset, 2024-03-10T03:30:00-04:00: what a local log line wants ([To-Iso-Local]) |
local_offset_seconds(unix) | how many seconds local time is ahead of UTC at that moment (negative when behind) |
Measure elapsed time with monotonic_ns(), never with the wall clock. The wall
clock is whatever the computer's owner or its time service last set it to, and it can jump backwards
while a program runs; unix_seconds(), unix_ms() and DateTime::now() say what time it is,
monotonic_ns() how long something took.
import std;
fn main() : u8
{
DateTime launch = DateTime::from_unix(1791022620);
String text = DateTime::to_iso(&launch);
Weekday w = DateTime::weekday(&launch);
printf("%s, a %s\n", &text, Weekday::text(&w));
DateTime due = match (DateTime::from_iso("2026-12-24"))
{
Ok(t) : t,
Err(e) :
{
printf("bad date: %s\n", ParseError::text(&e));
return 1;
},
};
i64 days = (DateTime::to_unix(&due) - DateTime::to_unix(&launch)) / 86400;
printf("%d whole days to %d-%02d-%02d\n", days, due.year, due.month, due.day);
match (DateTime::from_iso("2026-02-29"))
{
Ok(_) : printf("a leap day?\n"),
Err(e) : printf("2026-02-29: %s\n", ParseError::text(&e)),
}
0
}2026-10-03T10:17:00Z, a Saturday 81 whole days to 2026-12-24 2026-02-29: out of range
Local time is for showing, not for keeping. Store and log UTC, convert with
DateTime::to_local as the last step before printing, and print a local value by its fields: it is a
plain DateTime that knows nothing of its zone, so to_iso of it would end in Z and to_unix of it
is not the moment. For text, DateTime::to_iso_local(&now) writes the local time with its offset
(2024-03-10T03:30:00-04:00), which names the same moment as to_iso's. The offset depends on the machine and on the moment (clocks change twice a year
in many zones), so this program's output differs from place to place:
import std;
fn main() : u8
{
DateTime now = DateTime::now();
DateTime here = DateTime::to_local(&now);
i64 offset = local_offset_seconds(DateTime::to_unix(&now));
str sign = if (offset < 0) { "-" } else { "+" };
i64 magnitude = if (offset < 0) { 0 - offset } else { offset };
printf(
"%s UTC is %04d-%02d-%02d %02d:%02d:%02d here (UTC%s%02d:%02d)\n",
&DateTime::to_iso(&now),
here.year,
here.month,
here.day,
here.hour,
here.minute,
here.second,
sign,
magnitude / 3600,
magnitude % 3600 / 60,
);
0
}Milliseconds and HTTP dates (D-0181). A log line or a JSON document wants the
moment to the millisecond: iso_from_unix_ms(unix_ms()) writes 2026-10-07T12:34:56.789Z, and
unix_ms_from_iso(text) reads it back (from_iso reads the same text and drops the fraction).
DateTime::to_http_date(&t) writes the form HTTP headers carry, Sun, 06 Nov 1994 08:49:37 GMT, and
DateTime::from_http_date(text) reads it and the two older forms a server may still send.
Running other programs
In std::process.
A Command names a program and its arguments; running it starts a child process. There is
no shell in between: each arg reaches the program exactly as written, spaces,
quotes, $ and ; included, so text from a user can be passed as an argument without any way to
run something else. A program that wants a shell's features runs one by name, /bin/sh with -c,
and then quoting is its own business.
| Function | Does |
|---|---|
Command::new(program), Command::arg(&mut c, a) | a command; one more argument |
Command::current_dir(&mut c, dir), Command::env(&mut c, name, value), Command::clear_env(&mut c) | where the child starts; an environment variable for it; start it with no inherited variables |
Command::output(&c), Command::output_with_input(&c, input) | run to the end; an Output with status, stdout and stderr (bytes) |
Command::status(&c) | run to the end with this program's own input and output; the status |
Command::spawn(&c) | start it and return a Child at once, its three streams piped to this program |
Child::write_input, close_input, read_output, read_output_line, read_error | talk to a running child, as to a File |
Child::wait(&mut ch), try_wait, kill | wait for the end (its status), ask without waiting, or end it at once |
A status is the program's exit code, or minus the signal that ended it (-9 after kill
on Unix). Failing to start is a FileError, as every input and output failure is: NotFound
when there is no such program, and Io for an environment name that is empty or holds =. Dropping a
Child closes its pipes but leaves it running, like a job sent to the background; wait for it if
it should finish first (on Unix a dropped child is reaped all the same once it ends, so it leaves no
zombie). wait does not read the child's output: a pipe holds only so much (64 KiB on Linux), and a
child that writes more stops until it is read, so read its output before wait, or use output,
which reads both streams while it waits.
import std;
fn main() : u8
{
Command c = Command::new("/bin/sh");
Command::arg(&mut c, "-c");
Command::arg(&mut c, "echo \"$1 world\"; echo oops >&2; exit 3");
Command::arg(&mut c, "sh");
Command::arg(&mut c, "hello; echo injected"); // one argument, never run as a command
match (Command::output(&c))
{
Ok(o) :
{
String out = Result::unwrap_or(String::from_utf8(Vec::clone(&o.stdout)), String::new());
printf("status %d, said: %s", o.status, &out);
printf("and %u bytes on standard error\n", Vec::len(&o.stderr));
},
Err(e) :
{
printf("could not run it: %s\n", FileError::text(&e));
return 1;
},
}
Command gone = Command::new("no-such-program-anywhere");
if (Err(NotFound) = Command::output(&gone))
{
printf("no-such-program-anywhere: not found\n");
}
0
}status 3, said: hello; echo injected world and 5 bytes on standard error no-such-program-anywhere: not found
Stopping cleanly
Pressing Ctrl-C, or the system asking a service to stop (SIGTERM), ends a program on the
spot. A server that should finish the request in hand and close its files first calls
watch_interrupts(): from then on an interrupt only sets a flag, and interrupt_requested() reads
it. There is no callback; the program's own loop looks at the flag, often enough. A blocking socket
call returns early on an interrupt the program has not yet seen (a listener's accept and a socket's
read give Err(TimedOut)): one that arrives while it waits, or before it began but after the
program last asked interrupt_requested(). Once the program has asked and seen true, the calls of
its clean shutdown (the last replies, a query that tidies up) wait as usual, until another interrupt
arrives; TcpListener::set_accept_timeout_ms bounds how long a quiet server waits before looking
again. A socket call waiting when an interrupt comes returns early even if another thread has seen
the flag since. A second interrupt before the program has looked at the first (it is blocked in
read_line, say, or a long computation) ends it at once, as without watch_interrupts: pressing
Ctrl-C twice always stops a program.
To end the program from anywhere, exit(status) (D-0150): the calling thread's scopes and
frames are unwound and every destructor runs, as they do when a fault ends the program, standard
output is flushed, and the process ends with status, with no diagnostic. Other threads take no
further steps. exit has type never, so it can stand in for any value: None : exit(2) in a
match arm, or exit(1) as a statement after an error message. Returning from main is still the
ordinary way to end; exit is for the place that knows the program is over and is not main.
A helper that prints a message and ends the program declares its result : never (D-0340):
fn die(StringView msg) : never { eprintf("%s\n", msg); exit(1) }. Every path of its body must end
in exit, another : never call or a loop without break, or it is diag.never-returns; a call of
it fits any arm, as exit does: Err(_) : die("bad input") in a match that gives a String.
import std;
resource struct Lock
{
i32 id;
}
fn Lock::drop(ref<Lock, exclusive> self)
{
printf("lock %d released\n", self.id);
}
fn check(i32 value) : i32
{
Lock inner = Lock { .id = 2 };
if (value < 0)
{
eprintf("negative input\n");
exit(3); // inner and outer are released first
}
value * 2
}
fn main() : u8
{
Lock outer = Lock { .id = 1 };
i32 r = check(-5);
printf("never printed %d\n", r);
0
}lock 2 released lock 1 released
import std;
fn main()
{
watch_interrupts();
u64 handled = 0;
while (!interrupt_requested() && handled < 3)
{
handled += 1; // one unit of work: a request, a job, a file
}
printf("handled %u, stopping cleanly\n", handled);
}handled 3, stopping cleanly
Also (D-0181): Child::read_error_line(&mut ch) reads the child's standard error a
line at a time, as read_output_line does its output; Child::terminate(&mut ch) asks it to stop
(SIGTERM on Unix, which a program may catch to finish cleanly) where kill ends it at once; and
process_id() is this program's own number, for a pid file. kill and terminate signal the child
alone: a sh -c "…" killed leaves the commands it started running. Child::kill_tree(&mut ch) (D-0205)
ends the child and every process it started, and theirs (on Linux, found from /proc; on Windows with
taskkill /T). A process that left the tree first, a daemon that forked twice and now has init as its
parent, is not reached.
Streaming between processes (D-0195). A Child's pipes all belong to it, and
every call borrows it exclusively, so one thread cannot write a child's input while another reads
its output. Child::take_input(&mut ch) and Child::take_output(&mut ch) move a pipe out into a
ChildInput or ChildOutput of its own (None if it was already taken): give one to a thread
(spawn(pump, out_a, in_b)) and keep reading the other child here. ChildInput::write,
ChildOutput::read and read_line work as the Child's own calls do; dropping an end closes it, and
an end outlives its Child.
Cryptography, and bytes as text
In std::crypto, with hexadecimal and base64 in std::encoding::hex and std::encoding::base64.
spec/21 §0 names, tested against their published vectors and against OpenSSL and Python's cryptography on loopback and in sweeps, fuzzed continuously (impl/fuzz); not independently audited.sha256(data) is the SHA-256 digest of some bytes, 32 of them as an array<u8, 32>;
hmac_sha256(key, data) is a message authentication code under a key, the way a webhook body,
a session cookie or a signed request is protected. Both come in a streaming form for a message that
arrives in pieces: Sha256::new(), Sha256::update(&mut h, piece) as often as needed,
Sha256::finish(h); HmacSha256 the same. A Sha256 is a plain value, so a copy of a half-done
computation continues on its own. Everything is written in CobaltC (the spec lists it).
Check a MAC with digest_eq, never with ==. digest_eq(a, b) compares every byte
whatever the first difference, so how long the check takes says nothing about how many leading bytes
a sender guessed right. A digest is shown with to_hex and read back with from_hex; bytes that
must travel as text go through base64_encode and base64_decode (RFC 4648, padded). Random keys
come from os_random_bytes. A secret is rarely used as it arrives: hkdf_sha256(salt, secret, info, len)
derives len bytes of key material from it, bound to what they are for by info, so one secret
never keys two purposes (RFC 5869; TLS 1.3's key schedule is this function). When a protocol or
a file format names its hash, hash(kind, data), Hasher, hmac(kind, key, data), Hmac and the
hkdf_*_with(kind, …) forms take a HashKind (Sha2_256, Sha2_384 or Sha2_512) at run time;
the SHA-256 forms are the same functions with Sha2_256.
Encrypting. chacha20_poly1305_seal(key, nonce, aad, plaintext) encrypts and
authenticates (RFC 8439): a 32-byte key, a 12-byte nonce that must never repeat under one key, and
aad, data sent in the clear but protected from change; the result is the ciphertext and a 16-byte
tag. chacha20_poly1305_open gives the plaintext back, or None if a single bit of the message, the
tag or the aad was changed, and never any part of a refused message. Agreeing on a
key. Each side makes x25519_private_key(), sends x25519_public_key(&private), and
computes x25519(&private, &their_public): both get the same 32 bytes, which nobody who
saw only the public keys can (RFC 7748); None means the other side sent a key that must be refused.
Feed the shared secret to hkdf_sha256, never use it as a key directly. The NIST
alternatives. aes_gcm_seal and aes_gcm_open are the same pair with AES-GCM (NIST SP
800-38D), for formats and protocols that require it: the key is 16, 24 or 32 bytes (AES-128, AES-192
or AES-256), the nonce 12. p256_private_key, p256_public_key and p256_ecdh agree on a key over
the P-256 curve; the public key is 65 bytes, and None means a key that must be refused. Where you
choose, X25519 agrees on a key in about half the time P-256 takes; the two AEADs run at about the
same speed (AES-128-GCM and ChaCha20-Poly1305 each about 50 ms a MiB here). All of these take the same steps
whatever the secret bytes are, so their timing reveals nothing but lengths; a key or nonce of the
wrong length is the fault diag.crypto-length.
import std;
fn main()
{
array<u8, 32> alice = x25519_private_key();
array<u8, 32> bob = x25519_private_key();
array<u8, 32> alice_public = x25519_public_key(&alice);
array<u8, 32> bob_public = x25519_public_key(&bob);
array<u8, 32> shared = Option::unwrap(x25519(&alice, &bob_public));
Vec<u8> nothing = Vec::new();
Vec<u8> key = hkdf_sha256(¬hing, &shared, b"example key", 32);
Vec<u8> nonce = Vec::filled(12, 0: u8);
Vec<u8> sealed = chacha20_poly1305_seal(&key, &nonce, b"header", b"attack at dawn");
// Bob derives the same key from his side of the exchange.
array<u8, 32> bobs = Option::unwrap(x25519(&bob, &alice_public));
Vec<u8> bob_key = hkdf_sha256(¬hing, &bobs, b"example key", 32);
match (chacha20_poly1305_open(&bob_key, &nonce, b"header", &sealed))
{
Some(p) : printf("bob reads: %s\n", &Result::unwrap_or(String::from_utf8(p), String::new())),
None : printf("refused\n"),
}
sealed[0] = sealed[0] ^ 1;
printf(
"changed in transit: %s\n",
if (Option::is_none(&chacha20_poly1305_open(
&bob_key,
&nonce,
b"header",
&sealed,
))) { "refused" } else { "accepted" },
);
}bob reads: attack at dawn changed in transit: refused
| Function | Does |
|---|---|
sha256(data), Sha256::new(), Sha256::update(&mut h, data), Sha256::finish(h) | the SHA-256 digest, in one call or in pieces: an array<u8, 32> |
hmac_sha256(key, data), HmacSha256::new(key), update, finish | HMAC-SHA-256 under key (any length; a long key is hashed first) |
digest_eq(a, b) | the same bytes, compared in a time that depends only on the lengths |
hkdf_sha256(salt, ikm, info, len), hkdf_extract(salt, ikm), hkdf_expand(prk, info, len) | HKDF (RFC 5869): len bytes of key material derived from a secret, bound to info; at most 8160 bytes from one extracted key |
chacha20_poly1305_seal(key, nonce, aad, plaintext), chacha20_poly1305_open(key, nonce, aad, sealed) | authenticated encryption (RFC 8439): ciphertext and tag; the plaintext back, or None for anything changed |
chacha20(key, nonce, counter, data), poly1305(key, message) | the stream cipher and the one-time MAC the AEAD is built from |
aes_gcm_seal(key, nonce, aad, plaintext), aes_gcm_open(key, nonce, aad, sealed), aes_encrypt_block(key, block) | AES-GCM (SP 800-38D) with a 16-, 24- or 32-byte key, as the ChaCha20-Poly1305 pair; the bare AES block cipher (FIPS 197) |
x25519_private_key(), x25519_public_key(private), x25519(private, their_public) | key agreement (RFC 7748): a key pair, and the shared secret, None for a public key that must be refused |
p256_private_key(), p256_public_key(private), p256_ecdh(private, their_public) | key agreement over P-256: a 65-byte public key, and the 32-byte shared secret, None for a key that must be refused |
sha512(data), sha384(data), Sha512, Sha384 | the 64- and 48-byte SHA-2 digests, one-shot or streaming |
hash(kind, data) | the digest by a HashKind: Sha2_256, Sha2_384 or Sha2_512 |
rsa_verify_pkcs1v15(&key, kind, digest, sig), rsa_verify_pss(&key, kind, digest, sig) | whether an RSA signature (PKCS #1 v1.5, or PSS with a digest-length salt) is the key's over that digest |
ecdsa_verify(curve, public_key, digest, sig) | whether a DER ECDSA signature on P256 or P384 is the key's over that digest |
hkdf_expand_label(secret, label, context, len) | TLS 1.3's key-schedule step (RFC 8446 §7.1) |
Hasher::new(kind), hmac(kind, key, data), Hmac::new(kind, key), hkdf_with(kind, salt, ikm, info, len), hkdf_extract_with, hkdf_expand_with, hkdf_expand_label_with | the same over a HashKind chosen at run time (SHA-256, SHA-384 or SHA-512); results are Vec<u8> |
ed25519_private_key(), ed25519_public_key(private), ed25519_sign(private, message), ed25519_verify(public, message, sig) | Ed25519 (RFC 8032): 32-byte keys, 64-byte deterministic signatures over the whole message |
ec_private_key(curve), ec_public_key(curve, private), ecdh(curve, private, their_public), ecdsa_sign(curve, private, digest) | P-256 or P-384 keys, key agreement, and a DER ECDSA signature over a digest with an RFC 6979 nonce |
rsa_generate_key(bits), RsaPrivateKey::new(n, e, d, p, q), RsaPrivateKey::public_key(&key), rsa_sign_pkcs1v15(&key, kind, digest), rsa_sign_pss(&key, kind, digest) | an RSA key (1024 to 8192 bits), and signatures in the two encodings the verify functions check |
hash_password(password), verify_password(stored, password) | Argon2id password storage as a PHC string, and its check |
argon2id(password, salt, passes, memory_kib, lanes, len), pbkdf2(kind, password, salt, iterations, len) | the raw key-derivation functions (RFC 9106, RFC 8018) |
blake2b(data, len), Blake2b::new(len), Blake2b::new_keyed(key, len), update, finish | BLAKE2b (RFC 7693): a digest of 1 to 64 bytes, optionally keyed |
to_hex(bytes), from_hex(text) | lowercase hexadecimal and back (ParseError for a non-digit or an odd count) |
base64_encode(bytes), base64_decode(text) | base64 with = padding and back (ParseError for a bad character or length) |
import std;
fn main()
{
array<u8, 32> d = sha256(b"abc");
printf("%s\n", &to_hex(&d));
array<u8, 32> mac = hmac_sha256(b"Jefe", b"what do ya want for nothing?");
printf("%s\n", &to_hex(&mac));
array<u8, 32> again = hmac_sha256(b"Jefe", b"what do ya want for nothing?");
printf("verified: %v\n", digest_eq(&mac, &again));
printf("%s\n", &base64_encode(b"foobar"));
}ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad 5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843 verified: true Zm9vYmFy
Signatures. Three families, each with a key pair, a signing function and a
verifying one. Ed25519 (RFC 8032) is the simplest and the one to choose where you can:
ed25519_private_key(), ed25519_public_key(&private), ed25519_sign(&private,
message) gives 64 bytes, ed25519_verify(&public, message, &sig) says whether they are
that key's signature of that message. Signing is deterministic: the same key and message give the
same bytes, and no random number is involved that could repeat. ECDSA on P256 or P384
(what certificates and TLS mostly carry): ec_private_key(curve), ec_public_key(curve, &k)
(the uncompressed point, 65 or 97 bytes), ecdsa_sign(curve, &k, &digest) (a DER
signature over the digest made with hash; the nonce is derived from the key and the digest as
RFC 6979 says, so it too is deterministic) and ecdsa_verify(curve, public, digest, sig); the same
keys do key agreement with ecdh(curve, &k, &their_public), of which the p256_*
functions are the P-256 case. RSA: rsa_generate_key(2048) makes an RsaPrivateKey
(in seconds), or RsaPrivateKey::new(n, e, d, p, q) builds one
from numbers read elsewhere (None if they do not fit together); rsa_sign_pkcs1v15(&key, kind,
&digest) and rsa_sign_pss(&key, kind, &digest) sign the digest in the two standard
encodings, RsaPrivateKey::public_key(&key) gives the RsaPublicKey that rsa_verify_pkcs1v15 and
rsa_verify_pss check with. Signing with any of them takes the same steps whatever the key; the
RSA operation is blinded and checked against the public key before its result leaves. Verification
uses only public values and answers false for anything malformed.
Keys in files. Keys travel in the encodings every tool writes, in
std::x509: a public key as a SubjectPublicKeyInfo (CertKey::from_der, from_pem, to_der,
to_pem), a private key as PKCS #8 (PrivateKey::from_der, from_pem, to_der, to_pem), where
from_pem also reads the older RSA PRIVATE KEY and EC PRIVATE KEY blocks. A PrivateKey is
RsaPrivate, EcPrivate or Ed25519Private; PrivateKey::public_key(&key) is its CertKey, and
sign(&key, &scheme, message) signs a whole message under a SignatureScheme the way
verify_signature checks it, hashing first where the scheme says so. A certificate's key is a
CertKey too, so a program can check a signature against a certificate it parsed.
import std;
fn main()
{
array<u8, 32> private = ed25519_private_key();
array<u8, 32> public = ed25519_public_key(&private);
array<u8, 64> sig = ed25519_sign(&private, b"release 1.4.0");
printf("genuine: %v\n", ed25519_verify(&public, b"release 1.4.0", &sig));
printf("altered: %v\n", ed25519_verify(&public, b"release 1.4.1", &sig));
// The same key, written the way openssl would.
PrivateKey key = Ed25519Private(private);
String pem = PrivateKey::to_pem(&key);
printf("%s", &pem[0..27]);
printf("\nread back: %v\n", Result::is_ok(&PrivateKey::from_pem(&pem)));
}genuine: true altered: false -----BEGIN PRIVATE KEY----- read back: true
Passwords. Store hash_password(&password), a text like
$argon2id$v=19$m=19456,t=2,p=1$…$… that records the Argon2id parameters and the random salt beside
the result; check a login with verify_password(stored, &attempt). Argon2id (RFC 9106) costs
memory as well as time (19 MiB and two passes here, the OWASP recommendation), so a stolen table
cannot be searched at hardware speed; the parameters can be raised later and old entries still
verify, since each carries its own. Never store a plain sha256 of a password, salted or not. For
the formats that predate Argon2, pbkdf2(kind, password, salt, iterations, len) is PBKDF2 over
HMAC, and argon2id(password, salt, passes, memory_kib, lanes, len) is the raw function.
blake2b(data, len) (RFC 7693, up to 64 bytes, Blake2b::new_keyed for a keyed MAC) is the fast
hash Argon2 is built on. hash_password touches 19 MiB of memory twice, word by word, in well
under a second.
SHA-1 is there too (Sha1, sha1, and Sha1 as a HashKind for hmac,
pbkdf2 and Hasher, D-0181), because older protocols still require it: RFC 6238's one-time
passwords default to HMAC-SHA-1, and git names its objects by it. It is legacy — collisions have been
made — so it is for checking what others produce, never for a new signature.
Big integers
In std::math.
A BigUint is an unsigned integer of any size: add, sub, mul, div_rem (a BigDivision
of quotient and remainder), rem, mod_pow, mod_inverse, clone, shifts, eq and less, and conversions to and from
big-endian bytes and decimal text. It owns its digits, so it is a resource: reassign one with
overwrite, and take a division apart by destructuring. Its operations take time that depends on the
numbers, so it is for public values, never for a secret key.
import std;
fn main()
{
BigUint f = BigUint::from_u64(1);
for (u64 i = 2; i <= 30; i += 1)
{
overwrite(&mut f, BigUint::mul(&f, &BigUint::from_u64(i)));
}
printf("30! = %s\n", &BigUint::text(&f));
BigDivision { quotient, remainder } = BigUint::div_rem(&f, &BigUint::from_u64(1000000007));
printf("mod 1000000007 = %s\n", &BigUint::text(&remainder));
}30! = 265252859812191058636308480000000 mod 1000000007 = 109361473
Statistics
In std::stats.
Descriptive statistics over a slice of numbers of any numeric type (D-0267). sum(&v) adds
in the slice's own type, checked, so an integer sum that does not fit faults as + does. mean,
variance and stddev (of the population: divided by the count), sample_variance and
sample_stddev (divided by one less, for a sample of a larger population), median,
percentile(data, p) (p from 0 to 100, interpolated between the two sorted values it falls between,
as spreadsheets do), minimum and maximum each convert the values to f64 and give an
Option<f64>: None for an empty slice, and for a sample statistic of fewer than two values, because
no data is ordinary input rather than a bug. describe(data) gives the count, minimum, maximum, mean,
standard deviation and median as one Summary. Sums go left to right and the variance takes two
passes, so the same data always gives the same result. A NaN among the values makes a mean a
NaN, sorts last for the median, and is passed over by minimum and maximum.
import std;
fn main()
{
array<f64, 7> scores = [71.5, 88.0, 64.0, 92.5, 79.0, 88.0, 55.5];
printf("mean %.2f, stddev %.2f (sample %.2f)\n",
Option::unwrap(mean(&scores)),
Option::unwrap(stddev(&scores)),
Option::unwrap(sample_stddev(&scores)));
printf("median %v, quartiles %v and %v\n",
Option::unwrap(median(&scores)),
Option::unwrap(percentile(&scores, 25.0)),
Option::unwrap(percentile(&scores, 75.0)));
Vec<i64> sizes = Vec::new();
Vec::push(&mut sizes, 4096);
Vec::push(&mut sizes, 512);
Vec::push(&mut sizes, 1_048_576);
printf(
"%v bytes in %v files, the largest %v\n",
sum(&sizes),
Vec::len(&sizes),
Option::unwrap(maximum(&sizes)),
);
Vec::clear(&mut sizes);
printf("%v\n", Option::is_none(&describe(&sizes)));
}mean 76.93, stddev 12.80 (sample 13.83) median 79.0, quartiles 67.75 and 88.0 1053184 bytes in 3 files, the largest 1048576.0 true
Certificates
In std::x509.
spec/21 §0 names, tested against certificates and keys OpenSSL made and against the system's root bundle, fuzzed continuously (impl/fuzz); not independently audited.Certificate::parse(der) reads an X.509 certificate; certificates_from_pem(text) reads every
certificate in PEM text. A TrustStore holds the roots a chain may end at: TrustStore::system() reads
the operating system's bundle on Unix (on Windows, pass a bundle to TrustStore::from_pem_file).
verify_chain(&leaf, &intermediates, &roots, host, &now) decides whether a server's certificates
prove it is host: the leaf names the host (a DNS name, a one-label wildcard, or an IP address; never
the common name), every certificate is in date and signed by the next, every issuer is a CA, and the
chain ends at a root. The error says why not: HostMismatch, Expired, UnknownAuthority and so on.
Revocation (CRL, OCSP) is not checked.
TLS
In std::tls.
s_client and s_server on loopback, fuzzed continuously (impl/fuzz); not independently audited.TlsStream::connect(addr, server_name, &roots) opens a TLS 1.3 connection: it checks the
server's certificate chain against roots and server_name, and then read, read_exact, write
and close carry data encrypted and authenticated. TlsStream::client(tcp, …) does the same over a
TcpStream the program connected and configured itself (its timeouts apply). The client speaks only
TLS 1.3, with ChaCha20-Poly1305, AES-128-GCM or AES-256-GCM, X25519, P-256 or P-384, and ECDSA,
RSA-PSS or Ed25519 signatures: the set every TLS 1.3 server must support and the common additions; a
failure is a TlsError saying whether it was the network, the certificate, the handshake or an
alert. The example is shown, not run: it needs the network.
import std;
fn main() : u8
{
TrustStore roots = match (TrustStore::system())
{
Ok(t) : t,
Err(_) : return 1,
};
IpAddr ip = Result::unwrap(IpAddr::parse("1.1.1.1"));
TlsStream s = match (TlsStream::connect(SocketAddr::new(ip, 853), "cloudflare-dns.com", &roots))
{
Ok(s) : s,
Err(e) :
{
eprintf("tls: %s\n", TlsError::text(&e));
return 1;
},
};
// … a DNS-over-TLS query: a 2-byte length, then the DNS message …
_ = TlsStream::close(&mut s);
0
}Serving TLS (D-0186). TlsStream::server(tcp, &key, &chain) performs the
handshake as the server, with a PrivateKey (RSA, P-256, P-384 or Ed25519, read with
PrivateKey::from_pem) and the server's certificate chain (certificates_from_pem, the server's
own certificate first); the client's first suite, key share and the key's signature scheme are
chosen, and a client that cannot agree is answered with an alert. Afterwards read_line, read,
write and close work as on the client side, and peer_certificate (None on a server, the
server's certificate on a client) is there for pinning. TcpStream::try_clone has no counterpart
on a TlsStream: its record keys are one state. The example is shown, not run: it needs a key and
a certificate (openssl req -x509 -newkey ed25519 -nodes -subj /CN=localhost -addext
subjectAltName=DNS:localhost makes a self-signed pair for development).
import std;
fn main() : u8
{
PrivateKey key = Result::unwrap(PrivateKey::from_pem(&Result::unwrap(read_file("server.key"))));
Vec<Certificate> chain = certificates_from_pem(&Result::unwrap(read_file("server.crt")));
TcpListener l = Result::unwrap(TcpListener::bind(Result::unwrap(SocketAddr::parse("0.0.0.0:8443"))));
while (true)
{
TcpStream tcp = Result::unwrap(TcpListener::accept(&mut l));
TlsStream s = match (TlsStream::server(tcp, &key, &chain))
{
Ok(s) : s,
Err(e) :
{
eprintf("handshake: %s\n", TlsError::text(&e));
continue;
},
};
while (Some(line) = Result::unwrap_or(TlsStream::read_line(&mut s), None))
{
_ = TlsStream::write_text(&mut s, "echo: ");
_ = TlsStream::write_text(&mut s, &line);
_ = TlsStream::write_text(&mut s, "\n");
}
_ = TlsStream::close(&mut s);
}
0
}HTTP
In std::http.
impl/fuzz); not independently audited.http_get(url) fetches a URL and http_post(url, content_type, body) posts to one; each gives
a Response with its status, reason, headers and whole body, or an HttpError saying what
went wrong (the network, TLS, a malformed URL or message, a limit). Both follow redirects, decode
chunked bodies and speak https through std::tls with the system roots. A program that makes more
than one request, or wants a timeout, a header on every request or a smaller body limit, keeps an
HttpClient and calls HttpClient::send(&mut client, &request): the roots are loaded once, at the
first https request. Url::parse takes a URL apart (scheme, host, port, path, query),
percent_encode and percent_decode handle the escaping, find_header (or
Response::header) finds a header whatever its case, and Response::text gives the body as a String
(an error when it is not UTF-8). HTTP/1.1 only and one connection per request, unless the
client's keep_alive is set (D-0195): then the connection stays open while the server allows, and
the next request to the same host and port goes on it (a server for such a client must not count
on one connection per request). If that connection turns out closed before any answer, a GET, HEAD,
PUT, DELETE, OPTIONS or TRACE is sent again on a fresh one; a POST is not -- the server may have acted
on it -- and is ConnectionClosed for the program to decide. No compression and no cookies; what a server sends compressed it sends only when asked, so plain
requests get plain bodies.
Serving. HttpServer::bind(addr) listens; HttpServer::accept(&mut server)
gives each client's HttpConnection, on which HttpConnection::request(&mut c) parses the next
request (Ok(None) once the client is done, or when it sends nothing more within the server's
timeout_ms: an idle keep-alive connection ends quietly) and HttpConnection::respond(&mut c, status, &headers,
body) writes the answer with the right Content-Length, reason phrase and Connection header,
keeping the connection open when the client asked for that. A malformed request is an Err the
program answers with 400: among them one whose length is ambiguous (two Content-Length fields that
differ, one that is not digits, two Transfer-Encoding fields), one with two Host fields, and one
with a control byte in its target or a field, the forms a proxy and a server could read two ways (or 413 for one over max_body); the connection then closes. Handle each
connection in its own thread with spawn, as the example does; the server speaks plain HTTP (a TLS
server is a later decision). The example is hermetic: its client and server are the same program.
import std;
fn serve(HttpConnection c) : u8
{
while (true)
{
Vec<Header> headers = Vec::new();
Vec::push(&mut headers, Header::new("Content-Type", "text/plain"));
match (HttpConnection::request(&mut c))
{
Ok(Some(req)) :
{
if (req.url == "/health")
{
_ = HttpConnection::respond(&mut c, 200, &headers, b"ok\n");
}
else if (req.method == "POST" && req.url == "/echo")
{
_ = HttpConnection::respond(&mut c, 200, &headers, &req.body);
}
else
{
_ = HttpConnection::respond(&mut c, 404, &headers, b"no such page\n");
}
},
Ok(None) : return 0,
Err(_) :
{
_ = HttpConnection::respond(&mut c, 400, &headers, b"bad request\n");
return 1;
},
}
}
0
}
fn accept_two(HttpServer s) : u8
{
for (usize i = 0; i < 2; i += 1)
{
match (HttpServer::accept(&mut s))
{
Ok(c) : { _ = join(spawn(serve, c)); },
Err(_) : return 1,
}
}
0
}
fn main()
{
HttpServer s = Result::unwrap(HttpServer::bind(SocketAddr::new(IpAddr::localhost_v4(), 0)));
String base = sprintf("http://127.0.0.1:%u", HttpServer::local_addr(&s).port);
auto server = spawn(accept_two, s);
match (http_get(&sprintf("%s/health", &base)))
{
Ok(r) : printf("%u %s: %s", r.status, &r.reason, &Result::unwrap_or(Response::text(&r), String::new())),
Err(e) : printf("error: %s\n", HttpError::text(&e)),
}
match (http_post(&sprintf("%s/echo", &base), "text/plain", b"hello there"))
{
Ok(r) : printf("%u, %s echoed %v bytes: %s\n", r.status, Option::unwrap_or(Response::header(&r, "content-type"), StringView::of("?")), Vec::len(&r.body), &Result::unwrap_or(Response::text(&r), String::new())),
Err(e) : printf("error: %s\n", HttpError::text(&e)),
}
printf("server thread: %u\n", join(server));
}200 OK: ok 200, text/plain echoed 11 bytes: hello there server thread: 0
https, forms and compressed bodies. HttpServer::bind_tls(addr, key, chain)
makes the same server speak https (D-0186): each connection's TLS handshake is done by its first
request (or respond), on the thread that handles the connection, so a client that connects and
never finishes the handshake holds up only its own connection; a client that fails it is
Err(HttpTlsFailure(_)) from that call, and accept's error is an HttpError. A request's query
string and a form body are read with Url::query_pairs(&url) and form_decode(text), each a
Vec<Param> (name, value, compared exactly) searched with find_param, the pairs split at &
only (a ; is part of a value, as browsers and Python read it); form_encode writes one (D-0181).
respond refuses (Err(BadMessage), nothing written) a header whose value holds a CR, an LF or
another control byte, so a value taken from the request, such as a redirect's Location, cannot
split the response; the client refuses such a header, and Url::parse a URL with a space or a
control byte, before anything is sent. The client offers Accept-Encoding: gzip, deflate
and decodes a body a server sends that way, dropping the header, so r.body is always the plain
bytes (D-0183).
import std;
fn main()
{
Vec<Param> form = form_decode("name=Ada+Lovelace¬e=100%25&tag=x&tag=y");
foreach (p in &form)
{
printf("%v = %v\n", &p.name, &p.value);
}
printf("%v\n", Option::unwrap_or(find_param(&form, "note"), StringView::of("-")));
printf("%v\n", &form_encode(&form[0..2]));
Url u = Result::unwrap(Url::parse("https://example.org/search?q=cobalt%20c&page=2"));
printf("%v\n", Option::unwrap_or(find_param(&Url::query_pairs(&u), "q"), StringView::of("-")));
}name = Ada Lovelace note = 100% tag = x tag = y 100% name=Ada+Lovelace¬e=100%25 cobalt c
JSON
In std::encoding::json.
Json::parse(text) reads a JSON document (RFC 8259) into a tree of Json values — JsonNull,
JsonBool, JsonNumber (an f64), JsonText, JsonArray and JsonObject (its members in order) —
and Json::text(&j) writes one back compact, Json::pretty(&j) indented. Reading a tree:
Json::get(&j, "key") and Json::at(&j, i) give a reference to a member or an element, or None,
and as_text, as_i64, as_f64, as_bool, as_array, as_object and is_null ask what a value is.
Building one: Json::set(&mut obj, "key", value) and Json::push(&mut arr, value). An object's
members are a list searched in order, so for one of many thousands of keys append the members with
Json::push_member (no search: the keys must be new) and look keys up through one
Json::key_index(&obj), a HashMap from each key to its member's position. A document that is
not JSON is Err(Invalid(byte)), nothing at all Err(Empty), a number beyond f64 or nesting past
512 levels Err(OutOfRange). Every escape is handled, surrogate pairs included; a whole number is
written without a fraction; a NaN or an infinity, which JSON cannot carry, is written null
(D-0182).
import std;
fn main()
{
Json j = Result::unwrap(Json::parse("{\"name\": \"Ada\", \"born\": 1815, \"langs\": [\"Analytical\", \"Engine\"]}"));
StringView name = Option::unwrap_or(Json::as_text(Option::unwrap(Json::get(&j, "name"))), StringView::of("?"));
i64 born = Option::unwrap_or(Json::as_i64(Option::unwrap(Json::get(&j, "born"))), 0);
printf("%v, born %v, knew", name, born);
foreach (l in Option::unwrap(Json::as_array(Option::unwrap(Json::get(&j, "langs")))))
{
printf(" %v", Option::unwrap_or(Json::as_text(l), StringView::of("?")));
}
printf("\n");
Json out = JsonObject(Vec::new());
Json::set(&mut out, "name", JsonText("Ada"));
Json langs = JsonArray(Vec::new());
Json::push(&mut langs, JsonText("Analytical"));
Json::set(&mut out, "langs", langs);
Json::set(&mut out, "ok", JsonBool(true));
printf("%v\n%v\n", &Json::text(&out), &Json::pretty(&out));
match (Json::parse("{\"a\": [1, 2,]}"))
{
Err(Invalid(at)) : printf("not JSON at byte %v\n", at),
_ : {},
}
}Ada, born 1815, knew Analytical Engine
{"name":"Ada","langs":["Analytical"],"ok":true}
{
"name": "Ada",
"langs": [
"Analytical"
],
"ok": true
}
not JSON at byte 12
TOML
In std::encoding::toml.
Toml::parse(text) reads a TOML 1.0 document (the format of Cargo.toml and most configuration
files) into a tree of Toml values — TomlString, TomlInteger (an i64, exact), TomlFloat,
TomlBool, TomlDateTime, TomlArray and TomlTable (its members in order) — and Toml::text(&t)
writes one back: a table's plain members first, then its sub-tables under [headers] and arrays of
tables under [[headers]]; comments are not kept. The whole language is read: tables and arrays of
tables, dotted keys, inline tables, the four string forms, integers in four bases with underscores,
inf and nan, and the four date-time forms, which a TomlDateTime carries with its kind
(TomlOffsetDateTime, TomlLocalDateTime, TomlLocalDate, TomlLocalTime) and
TomlDateTime::text writes back. Reading a tree is as for JSON — Toml::get(&t, "key"),
Toml::at(&t, i), the as_ functions — with Toml::lookup(&t, "server.ports.1") for a dotted path
(an index where the value is an array; Json::lookup does the same, D-0268). Building one:
Toml::set and Toml::push. A document the format refuses — a key or table defined twice, a value
added to a table a header or an inline table has closed, a bad escape, a month 13 — is
Err(Invalid(byte)), with the byte of the offending key or value; an integer beyond i64 is
Err(OutOfRange). Toml::describe_error(&e, &text) makes a message of it with TOML's reason:
line 2, column 1: a is defined twice. The reader passes the
public toml-test suite for TOML 1.0.
import std;
fn main()
{
String source = "title = \"Service\"\n\n[server]\nhost = \"example.org\"\nports = [80, 443]\nstarted = 2026-10-18T09:30:00Z\n\n[[routes]]\npath = \"/\"\n[[routes]]\npath = \"/api\"\nlimit = 1_000\n";
Toml cfg = Result::unwrap(Toml::parse(&source));
StringView host = Option::unwrap_or(Toml::as_text(Option::unwrap(Toml::lookup(&cfg, "server.host"))), StringView::of("localhost"));
i64 port = Option::unwrap_or(Toml::as_i64(Option::unwrap(Toml::lookup(&cfg, "server.ports.1"))), 8080);
TomlDateTime started = Option::unwrap(Toml::as_datetime(Option::unwrap(Toml::lookup(&cfg, "server.started"))));
printf("%v:%v, started %v\n", host, port, &TomlDateTime::text(&started));
foreach (r in Option::unwrap(Toml::as_array(Option::unwrap(Toml::get(&cfg, "routes")))))
{
i64 limit = match (Toml::get(r, "limit"))
{
Some(v) : Option::unwrap_or(Toml::as_i64(v), 100),
None : 100,
};
printf("route %v limit %v\n", Option::unwrap(Toml::as_text(Option::unwrap(Toml::get(r, "path")))), limit);
}
Toml::set(&mut cfg, "title", TomlString("Service 2"));
printf("%v", &Toml::text(&cfg));
match (Toml::parse("a = 1\na = 2"))
{
Err(Invalid(at)) : printf("not TOML at byte %v\n", at),
_ : {},
}
str twice = "a = 1\na = 2";
match (Toml::parse(twice))
{
Err(e) : printf("%v\n", &Toml::describe_error(&e, twice)),
Ok(_) : {},
}
}example.org:443, started 2026-10-18T09:30:00Z route / limit 100 route /api limit 1000 title = "Service 2" [server] host = "example.org" ports = [80, 443] started = 2026-10-18T09:30:00Z [[routes]] path = "/" [[routes]] path = "/api" limit = 1000 not TOML at byte 6 line 2, column 1: a is defined twice
Compression
In std::compress.
deflate(data) and inflate(data, max) are DEFLATE (RFC 1951), the format under zip, PNG and
git; zlib_deflate/zlib_inflate wrap it with zlib's header and Adler-32 (RFC 1950), and
gzip/gunzip with gzip's header and CRC-32 (RFC 1952), so a .gz file or an HTTP body is one call
away. Decompression takes a max, the most it may produce, and answers Err(Oversize) beyond it — a
small stream can expand without bound, so a limit is always there; Truncated is a stream cut short
and Corrupt(byte) one that is not what it claims, a wrong checksum included. Compression uses one
fixed strategy, so every implementation writes the same bytes, and reads everything other tools
write; adler32 is there beside crc32 (D-0183).
import std;
fn main()
{
String text = String::new();
foreach (i in 0..20)
{
String::append(&mut text, "the same line again and again\n");
}
Vec<u8> packed = gzip(StringView::as_bytes(&text));
printf("%v bytes became %v\n", StringView::len(&text), Vec::len(&packed));
Vec<u8> back = Result::unwrap(gunzip(&packed, 1 << 20));
printf("round trip: %v\n", Vec::len(&back) == StringView::len(&text) && digest_eq(&back, StringView::as_bytes(&text)));
match (gunzip(&packed[0..10], 1 << 20))
{
Err(e) : printf("cut short: %s\n", CompressError::text(&e)),
Ok(_) : {},
}
}600 bytes became 52 round trip: true cut short: compressed data ends early
Databases
In std::database::postgres, re-exported by std::database.
impl/fuzz); not independently audited.A PostgreSQL client, speaking the server's own wire protocol over std::net and std::tls, with
SCRAM-SHA-256 from std::crypto; nothing is linked, so a program that talks to a database still
needs only a C compiler. PgConnection::connect(url) opens a connection from a
postgres://user:password@host:port/database URL (the port 5432 and the database the user's name
when left out), encrypting with TLS and verifying the server's certificate against the system roots
unless the URL says ?sslmode=disable; connect_with(url, &roots, timeout_ms) takes its own
TrustStore (a self-signed server's issuer, say) and timeout. There is no unverified TLS.
PgConnection::query(&mut c, sql, ¶ms) runs one statement with $1, $2, … bound to
the PgValues given (Null, Text, Int, Float, Bool, Bytes): a parameter is sent beside
the statement, never spliced into it, so no quoting is ever needed. The PgResult has the
columns (name and type OID), the rows (each cell Some(text) as the server prints the value,
or None for NULL; read it with PgRow::get(&row, i) and parse it with StringView::parse<T>),
the affected count and the command tag. execute is query for a statement without rows,
giving the count; run_script runs a file of ;-separated statements without parameters, for
schemas and migrations. Transactions are statements: execute(&mut c, "BEGIN", &none) and
"COMMIT" or "ROLLBACK".
An error the server reports is Err(Server(e)) with its severity, SQLSTATE code, message,
detail, hint and position; the connection stays usable after it, as it does after a result
over max_result (16 MiB by default, ResultTooLarge), and after a COPY, which this client does
not do (Unsupported). A network or protocol failure closes the connection, and every later call
gives Disconnected; so does a FATAL error (an administrator ending the session), given as
Server(e), and a SET client_encoding to anything but UTF-8 (Unsupported), since text here is
UTF-8. A reply that does not come within the timeout (30 s from connect) cancels the statement and
waits once more, so the error, or the result of a statement that finished first, is what the server
did; PgConnection::set_timeout_ms(&mut c, ms) gives a long statement more time (0 for none). Notices the server sends collect in
c.notices for the program to read and clear. PgError::text(&e) is a String saying what
went wrong, the server's message included. One connection serves one thread; a program that
queries from several keeps one per thread.
| Function | Does |
|---|---|
PgConnection::connect(url), connect_with(url, &roots, timeout_ms) | open a connection (30 s timeout for connecting and for each read and write, a reply included; the system roots), or with the roots and timeout given |
PgConnection::set_timeout_ms(&mut c, ms) | the timeout for each later read and write (0: none), for statements that take longer |
PgConnection::query(&mut c, sql, ¶ms) | one statement with $n bound to the PgValues: its PgResult (columns, rows, affected, tag) |
PgConnection::execute(&mut c, sql, ¶ms) | the same, giving only the affected count |
PgConnection::run_script(&mut c, sql) | several ;-separated statements, no parameters, results dropped, the first error given |
PgConnection::parameter(&c, name), c.notices, c.max_result | a setting the server reported at startup (server_version, …); the notices received; the most a result may take |
PgRow::get(&row, i), PgResult::column(&res, name) | a cell's text (None for NULL or past the end); a column's index by name |
PgConnection::close(&mut c) | tell the server goodbye and close (a dropped connection is just closed) |
PgUrl::parse(text), PgValue::text(&v) | the URL taken apart; the text a parameter is sent as |
import std;
fn main() : u8
{
PgConnection c = match (PgConnection::connect("postgres://app:secret@db.internal/shop"))
{
Ok(c) : c,
Err(e) :
{
eprintf("connect: %s\n", &PgError::text(&e));
return 1;
},
};
Vec<PgValue> none = Vec::new();
if (Err(e) = PgConnection::run_script(&mut c, "CREATE TABLE IF NOT EXISTS orders (id serial PRIMARY KEY, item text, qty int)"))
{
eprintf("schema: %s\n", &PgError::text(&e));
return 1;
}
Vec<PgValue> order = Vec::new();
Vec::push(&mut order, Text("widget"));
Vec::push(&mut order, Int(3));
match (PgConnection::execute(&mut c, "INSERT INTO orders (item, qty) VALUES ($1, $2)", &order))
{
Ok(n) : printf("inserted %v\n", n),
Err(e) : printf("insert: %s\n", &PgError::text(&e)),
}
Vec<PgValue> at_least = Vec::new();
Vec::push(&mut at_least, Int(2));
match (PgConnection::query(&mut c, "SELECT id, item, qty FROM orders WHERE qty >= $1 ORDER BY id", &at_least))
{
Ok(res) :
{
foreach (row in &res.rows)
{
StringView item = Option::unwrap_or(PgRow::get(row, 1), StringView::of("?"));
i64 qty = Result::unwrap_or(StringView::parse<i64>(Option::unwrap_or(PgRow::get(row, 2), StringView::of("0"))), 0);
printf("%s x %v\n", item, qty);
}
},
Err(Server(e)) : printf("%s: %s\n", &e.code, &e.message),
Err(e) : printf("query: %s\n", &PgError::text(&e)),
}
PgConnection::close(&mut c);
0
}Without a server the pieces can still be seen: the URL's defaults and the text each parameter is sent as.
import std;
fn main()
{
PgUrl u = Result::unwrap(PgUrl::parse("postgresql://app@db.internal"));
printf("%s@%s:%u/%s tls=%v\n", &u.user, &u.host, u.port, &u.database, match (u.sslmode) { Disable : false, VerifyFull : true });
Vec<PgValue> params = Vec::new();
Vec::push(&mut params, Int(-7));
Vec::push(&mut params, Float(0.5));
Vec::push(&mut params, Bool(true));
Vec::push(&mut params, Bytes(Vec::from_slice(b"\x00\xff")));
Vec::push(&mut params, Null);
foreach (v in ¶ms)
{
printf("%s\n", &Option::unwrap_or(PgValue::text(v), "NULL"));
}
}app@db.internal:5432/app tls=true -7 0.5 t \x00ff NULL
A cell read as a value: PgRow::get_i64(&row, i), get_f64, get_bool, get_bytes (D-0181)
and get_datetime (a timestamptz, timestamp or date as a DateTime, by DateTime::from_iso)
give None for NULL, for a column past the end, and for text of another form; get still gives the
text. A Json number is an f64: Float(2.0) is sent as 2, so a whole number goes into an
integer column too (Int(Option::unwrap(Json::as_i64(v))) says so outright).
Networking
In std::net.
TCP connections, UDP datagrams and name resolution, over IPv4 and IPv6. Addresses are values:
an IpAddr (V4 or V6) and a port make a SocketAddr, read from text with SocketAddr::parse
("127.0.0.1:8080", "[::1]:8080") or built with SocketAddr::new(IpAddr::localhost_v4(), 8080);
resolve(host, port) asks the system's resolver.
Sockets block. accept waits for a connection, read for bytes, connect
for the other side. A server handles many connections at once by giving each its own thread:
spawn a function with the accepted TcpStream moved into it, and use a Channel (§19) where
threads must talk. Every socket can have timeouts; a call that waits longer gives
Err(TimedOut), and the socket is still usable. There is no TLS, and nothing is added to what you
send: the bytes that arrive are exactly the bytes written, in order, in pieces of any size, so a
protocol needs its own framing — lines, read with read_line, are the simplest.
| Function | Does |
|---|---|
TcpListener::bind(addr), TcpListener::local_addr(&l) | listen at addr (port 0: any free port); where it listens |
TcpListener::accept(&mut l), set_accept_timeout_ms(&mut l, ms) | the next connection, a TcpStream; give up after ms with Err(TimedOut) |
TcpStream::connect(addr), connect_timeout(addr, ms) | connect to a listener |
TcpStream::read_line(&mut s), read(&mut s, &mut buf, max), read_exact(&mut s, &mut buf, n) | as File's: a line, what has arrived (0: the peer has finished), exactly n bytes |
TcpStream::write(&mut s, data), write_text(&mut s, text), printf(&mut s, fmt, …) | send all of it |
TcpStream::shutdown_write(&mut s) | tell the peer nothing more is coming (it reads 0), and keep reading |
set_read_timeout_ms, set_write_timeout_ms, set_nodelay | per-stream timeouts (0: none); send small writes at once |
UdpSocket::bind(addr), send_to(&mut u, data, to), recv_from(&mut u, max) | datagrams: one message each, with its sender in the Datagram |
UdpSocket::try_clone(&u) | a second handle on the same socket: one thread waits in recv_from while another sends on the clone |
UdpSocket::connect(&mut u, to), send(&mut u, data), recv(&mut u, max) | a socket talking to one peer: recv drops datagrams from anyone else (D-0181) |
TcpStream::try_clone(&s) | a second handle on the same connection, for one thread to read while another writes; the connection closes when the last handle is dropped (D-0185) |
TcpStream::set_keepalive(&mut s, on) | have the system probe an idle connection, so a vanished peer is noticed (D-0181) |
import std;
// One connection: each line back in capitals, until the client finishes.
fn serve(TcpStream s) : u32
{
u32 lines = 0;
while (Ok(Some(line)) = TcpStream::read_line(&mut s))
{
String up = StringView::to_ascii_upper(&line);
if (Err(_) = TcpStream::printf(&mut s, "%s\n", &up))
{
break;
}
lines += 1;
}
lines
}
// Accepts `n` connections, each served by its own thread.
fn listen(TcpListener l, usize n) : u32
{
Vec<handle<u32>> served = Vec::new();
for (usize i = 0; i < n; i += 1)
{
if (Ok(s) = TcpListener::accept(&mut l))
{
Vec::push(&mut served, spawn(serve, s));
}
}
u32 total = 0;
while (Some(h) = Vec::pop(&mut served))
{
total += join(h);
}
total
}
fn ask(SocketAddr at, StringView word) : String
{
match (TcpStream::connect(at))
{
Ok(c) :
{
_ = TcpStream::printf(&mut c, "%s\n", word);
match (TcpStream::read_line(&mut c))
{
Ok(Some(answer)) : answer,
_ : "(no answer)",
}
},
Err(e) : String::copy(NetError::text(&e)),
}
}
fn main() : u8
{
TcpListener l = match (TcpListener::bind(SocketAddr::new(IpAddr::localhost_v4(), 0)))
{
Ok(l) : l,
Err(e) :
{
printf("bind: %s\n", NetError::text(&e));
return 1;
},
};
SocketAddr at = TcpListener::local_addr(&l);
auto server = spawn(listen, l, 3);
foreach (word in ["alpha", "beta", "gamma"])
{
String answer = ask(at, word);
printf("%s -> %s\n", word, &answer);
}
printf("the server answered %u lines\n", join(server));
0
}alpha -> ALPHA beta -> BETA gamma -> GAMMA the server answered 3 lines
A server that runs until it is stopped combines this with watch_interrupts (above): give
the listener an accept timeout, and the accept loop looks at the flag between waits.
import std;
fn main() : u8
{
watch_interrupts();
TcpListener l = match (TcpListener::bind(SocketAddr::new(IpAddr::localhost_v4(), 0)))
{
Ok(l) : l,
Err(_) : return 1,
};
TcpListener::set_accept_timeout_ms(&mut l, 50);
u32 waits = 0;
while (!interrupt_requested() && waits < 3) // a real server: while (!interrupt_requested())
{
match (TcpListener::accept(&mut l))
{
Ok(s) : printf("a client\n"), // spawn a thread for it here
Err(TimedOut) : waits += 1, // nobody came: look at the flag again
Err(e) :
{
printf("accept: %s\n", NetError::text(&e));
return 1;
},
}
}
printf("closing the listener and stopping\n");
0
}closing the listener and stopping
Sorting and searching
In std::collections.
Vec::sort(&mut v) puts a Vec in order: integers by value, false before true, text by
its bytes, and a struct or enum of these field by field in declaration order (an enum by the order
its variants are declared in, then by payload). For any other order, or any other element type, Vec::sort_by(&mut v, less) takes a
function that says whether its first argument goes before its second. Both are stable: elements
that are equal keep the order they had. In a sorted Vec, Vec::binary_search(&v, &key) gives
Ok(i), the first position holding the key, or Err(i), where it would go
(binary_search_by takes the same less).
import std;
struct Player
{
String name;
u32 score;
}
fn higher(ref<Player, shared> a, ref<Player, shared> b) : bool
{
a.score > b.score // higher scores first
}
fn main()
{
Vec<String> names = Vec::new();
Vec::push(&mut names, "mira");
Vec::push(&mut names, "ada");
Vec::push(&mut names, "lin");
Vec::sort(&mut names);
assert(&names[0] == "ada" && &names[2] == "mira");
String who = "lin";
assert(Result::unwrap_or(Vec::binary_search(&names, &who), 99) == 1);
String bob = "bob";
assert(match (Vec::binary_search(&names, &bob))
{
Ok(_) : false,
Err(i) : i == 1, // between "ada" and "lin"
});
Vec<Player> ps = Vec::new();
Vec::push(&mut ps, Player { .name = "a", .score = 3 });
Vec::push(&mut ps, Player { .name = "b", .score = 9 });
Vec::push(&mut ps, Player { .name = "c", .score = 3 });
Vec::sort_by(&mut ps, higher);
assert(ps[0].score == 9);
assert(&ps[1].name == "a" && &ps[2].name == "c"); // equal scores keep their order
}HashMap<K, V> and HashSet<K>
In std::collections.
HashMap<K, V> maps keys to values; HashSet<K> holds a set of keys. A key is an integer,
a bool, a str, a String, or a struct whose fields (an enum whose payloads) are all keys:
struct Pos { i32 x; i32 y; } keys a grid. Any other key type (a float, an array, a struct with a
float field) is a static type error, and the message names the field that is not a key. The map
owns its keys and values. Lookups take the key's probe, so they copy nothing: a
String key is asked with any text ("k", a str, a view, &s), a number, bool or str key
by its value (HashMap::get(&counts, 7)), and a struct key by reference (&pos).
| Function | Does |
|---|---|
HashMap::new(), HashMap::len(&m) | an empty map; the number of entries |
HashMap::insert(&mut m, k, v) | adds k; if it was present, replaces its value and returns the old one as Some |
HashMap::entry(&mut m, k, fresh) | the value for the key k probes as an exclusive reference, adding a copy of the key with fresh first if it is absent (only then is a String key made) |
HashMap::get(&m, k), HashMap::get_mut(&mut m, k) | Some reference to the value, or None |
HashMap::contains(&m, k) | whether the key is present |
HashMap::remove(&mut m, k) | removes the key and returns its value; every other entry keeps its order; quick in any order of removals (the later entries move down together, after many removals) |
HashMap::swap_remove(&mut m, k) | the same, fast: the last entry moves into the removed one's place (D-0134) |
HashMap::key_at(&m, i), HashMap::value_at(&m, i) | entry i, for i < len, in insertion order |
HashMap::clear(&mut m) | removes every entry, destroying keys and values; the map stays usable |
HashMap::clone(&m), HashSet::clone(&s), clone(&m) | a copy of a map or set whose contents are clone (§12); Rc::clone shares instead |
HashSet::new, len, insert, contains, remove, swap_remove, key_at, clear | the same for a set; insert and the removals say whether anything changed |
HashSet::union(&a, &b), HashSet::intersection(&a, &b), HashSet::difference(&a, &b) | a new set of the keys in either, in both, or in a but not b, copied with clone; a and b are unchanged. The result keeps a's order, and union adds b's new keys after it (D-0138) |
Entries are kept in the order they were added, so foreach (k, v in &m) (§14) visits
them in that order, whatever the keys hash to.
key_at and value_at reach entry i directly. remove keeps that order: it leaves the
removed entry's place empty, and the later entries move down together once many places are empty,
so emptying a map one key at a time from its first entry on is as quick as from its last back
(until then key_at and value_at count past the empty places, in logarithmic time);
swap_remove fills the gap with the last entry instead, for a map whose order does not matter.
import std;
fn main()
{
array<str, 9> words = ["the", "cat", "and", "the", "hat", "and", "the", "bat", "sat"];
HashMap<String, u32> counts = HashMap::new();
foreach (w in words)
{
*HashMap::entry(&mut counts, w, 0) += 1; // 0 if new, then + 1
}
foreach (word, n in &counts) // insertion order
{
printf("%-4s %d\n", word, n);
}
String cat = "cat";
match (HashMap::get(&counts, &cat))
{
Some(n) : printf("cat: %d\n", *n),
None : printf("no cat\n"),
}
HashSet<u32> seen = HashSet::new();
u32 x = 7;
while (HashSet::insert(&mut seen, x)) // false once x comes round again
{
x = x * x % 10;
}
printf("%d distinct, back to %d\n", HashSet::len(&seen), x);
}the 3 cat 1 and 2 hat 1 bat 1 sat 1 cat: 1 3 distinct, back to 1
An ordered map or set. std has no tree-ordered map or set (D-0227: a second map
type to learn, for a need no program has shown). The idiom is the one above plus a sort: copy the keys
into a Vec (String::clone for text keys, *k for plain ones), Vec::sort it, and look each key up
again, or walk the sorted Vec beside the map. The map keeps insertion order for everything else, so
the sort costs only when an ordered view is wanted, and Vec::binary_search on the sorted keys answers
"is it there, and where" without the map.
import std;
fn main()
{
HashMap<String, u32> ages = HashMap::new();
HashMap::insert(&mut ages, "mia", 31);
HashMap::insert(&mut ages, "ada", 36);
HashMap::insert(&mut ages, "zed", 28);
HashMap::insert(&mut ages, "bo", 44);
Vec<String> names = Vec::new(); // the keys, copied out
foreach (name, age in &ages)
{
Vec::push(&mut names, String::clone(name));
}
Vec::sort(&mut names); // text sorts by its bytes
foreach (name in &names)
{
printf("%s %d\n", name, *Option::unwrap(HashMap::get(&ages, name)));
}
HashSet<i32> seen = HashSet::new();
HashSet::insert(&mut seen, 30);
HashSet::insert(&mut seen, -4);
HashSet::insert(&mut seen, 12);
Vec<i32> sorted = Vec::new();
foreach (k in &seen)
{
Vec::push(&mut sorted, *k);
}
Vec::sort(&mut sorted);
foreach (k in &sorted)
{
printf("%d ", *k);
}
printf("\n");
}ada 36 bo 44 mia 31 zed 28 -4 12 30
import std;
struct Pos
{
i32 x;
i32 y;
}
enum Tile
{
Wall,
Door(u8),
}
fn main()
{
HashMap<Pos, Tile> grid = HashMap::new();
HashMap::insert(&mut grid, Pos { .x = 0, .y = -1 }, Wall);
HashMap::insert(&mut grid, Pos { .x = 2, .y = 3 }, Door(7));
Pos at = Pos { .x = 2, .y = 3 };
match (HashMap::get(&grid, &at))
{
Some(Door(k)) : assert(*k == 7),
_ : assert(false),
}
HashSet<Tile> seen = HashSet::new(); // an enum of keys is a key too
HashSet::insert(&mut seen, Door(7));
assert(HashSet::contains(&seen, &Door(7)) && !HashSet::contains(&seen, &Wall));
}import std;
fn main()
{
HashMap<f64, str> m = HashMap::new(); // ✗ diag.type-mismatch (static): f64 is not a key type
}import std;
fn show(str name, ref<HashSet<str>, shared> s)
{
printf("%-13s", name);
foreach (i in 0..HashSet::len(s))
{
printf(" %s", *HashSet::key_at(s, i));
}
printf("\n");
}
fn main()
{
HashSet<str> monday = HashSet::new();
HashSet<str> tuesday = HashSet::new();
foreach (n in ["Ann", "Bo", "Cy", "Di"])
{
HashSet::insert(&mut monday, n);
}
foreach (n in ["Cy", "Ed", "Ann"])
{
HashSet::insert(&mut tuesday, n);
}
show("either day:", &HashSet::union(&monday, &tuesday));
show("both days:", &HashSet::intersection(&monday, &tuesday));
show("monday only:", &HashSet::difference(&monday, &tuesday));
}either day: Ann Bo Cy Di Ed both days: Ann Cy monday only: Bo Di
Queue<T> and PriorityQueue<T>
In std::collections.
A Queue<T> hands elements back in the order they arrived: push_back adds at the back,
pop_front takes from the front, each in constant time. It works at the other ends too
(push_front, pop_back), and front and back look without taking. A Vec with a growing
head index does the same job, but its storage never shrinks, and Vec::remove(&mut v, 0) moves
every other element on each call.
A PriorityQueue<T> hands back the least element first, whatever order they arrived in.
PriorityQueue::new() orders by the elements' own order, the one Vec::sort uses (numbers,
bool, text, and structs of them field by field), so a struct whose first field is the
priority needs no comparison function. PriorityQueue::new_by(less) takes the order as a
function, as Vec::sort_by does; for the largest first, pass one that answers "greater".
Elements the order calls equal come out in the order they went in, so equally urgent work is
first come, first served.
| Function | Does |
|---|---|
Queue::new(), Queue::len(&q) | an empty queue; the number of elements |
Queue::push_back(&mut q, x), Queue::push_front(&mut q, x) | adds x at the back, or before the front |
Queue::pop_front(&mut q), Queue::pop_back(&mut q) | takes the front (or back) element as Some, or None when empty |
Queue::front(&q), Queue::back(&q) | Some reference to the front (or back) element, or None; the queue stays as it is |
Queue::clear(&mut q) | destroys every element, front to back; the queue stays usable |
PriorityQueue::new(), PriorityQueue::new_by(less) | an empty queue in the elements' own order, or in less's |
PriorityQueue::push(&mut q, x), PriorityQueue::len(&q) | adds x; the number of elements |
PriorityQueue::pop(&mut q) | takes the least element as Some (of equals, the earliest pushed), or None when empty |
PriorityQueue::peek(&q), PriorityQueue::clear(&mut q) | Some reference to the element pop would take; destroys every element |
Both own their elements and destroy what is left when they end. A reference from front,
back or peek borrows the queue, so the queue cannot change while it is in use. Neither has
foreach or q[i]: a queue is read at its ends.
import std;
fn link(ref<Vec<Vec<usize>>, exclusive> adj, usize a, usize b)
{
Vec::push(&mut (*adj)[a], b);
Vec::push(&mut (*adj)[b], a);
}
fn main()
{
Vec<Vec<usize>> adj = Vec::new();
foreach (_ in 0..7)
{
Vec::push(&mut adj, Vec::new());
}
link(&mut adj, 0, 1);
link(&mut adj, 0, 2);
link(&mut adj, 1, 3);
link(&mut adj, 2, 3);
link(&mut adj, 3, 4);
link(&mut adj, 4, 5);
// Breadth first: everyone one step from 0, then two steps, ...
Vec<u32> steps = Vec::filled(7, max_value<u32>());
Queue<usize> todo = Queue::new();
steps[0] = 0;
Queue::push_back(&mut todo, 0);
while (Some(u) = Queue::pop_front(&mut todo))
{
foreach (v in &adj[u])
{
if (steps[*v] == max_value<u32>())
{
steps[*v] = steps[u] + 1;
Queue::push_back(&mut todo, *v);
}
}
}
foreach (i, s in &steps)
{
if (*s == max_value<u32>())
{
printf("%d: unreachable\n", i);
}
else
{
printf("%d: %d steps\n", i, *s);
}
}
}0: 0 steps 1: 1 steps 2: 1 steps 3: 2 steps 4: 3 steps 5: 4 steps 6: unreachable
import std;
struct Road
{
usize to;
u32 km;
}
struct Visit // ordered by dist, then node: a key
{
u32 dist;
usize node;
}
fn road(ref<Vec<Vec<Road>>, exclusive> map, usize a, usize b, u32 km)
{
Vec::push(&mut (*map)[a], Road { .to = b, .km = km });
Vec::push(&mut (*map)[b], Road { .to = a, .km = km });
}
fn main()
{
Vec<Vec<Road>> map = Vec::new();
foreach (_ in 0..5)
{
Vec::push(&mut map, Vec::new());
}
road(&mut map, 0, 1, 7);
road(&mut map, 0, 2, 2);
road(&mut map, 2, 1, 3);
road(&mut map, 1, 3, 4);
road(&mut map, 2, 3, 9);
road(&mut map, 3, 4, 1);
// Dijkstra: always settle the nearest place not yet settled.
Vec<u32> best = Vec::filled(5, max_value<u32>());
PriorityQueue<Visit> frontier = PriorityQueue::new(); // least first
PriorityQueue::push(&mut frontier, Visit { .dist = 0, .node = 0 });
while (Some(at) = PriorityQueue::pop(&mut frontier))
{
if (at.dist >= best[at.node])
{
continue; // reached sooner already
}
best[at.node] = at.dist;
foreach (r in &map[at.node])
{
PriorityQueue::push(&mut frontier, Visit { .dist = at.dist + r.km, .node = r.to });
}
}
foreach (i, d in &best)
{
printf("to %d: %d km\n", i, *d);
}
}to 0: 0 km to 1: 5 km to 2: 2 km to 3: 9 km to 4: 10 km
import std;
struct Task
{
u8 urgency;
str what;
}
fn more_urgent(ref<Task, shared> a, ref<Task, shared> b) : bool
{
a.urgency > b.urgency
}
fn main()
{
PriorityQueue<Task> inbox = PriorityQueue::new_by(more_urgent); // largest first
PriorityQueue::push(&mut inbox, Task { .urgency = 1, .what = "tidy desk" });
PriorityQueue::push(&mut inbox, Task { .urgency = 5, .what = "server down" });
PriorityQueue::push(&mut inbox, Task { .urgency = 3, .what = "review" });
PriorityQueue::push(&mut inbox, Task { .urgency = 5, .what = "disk full" });
while (Some(t) = PriorityQueue::pop(&mut inbox))
{
printf("%d %s\n", t.urgency, t.what); // equal urgency: first come, first served
}
}5 server down 5 disk full 3 review 1 tidy desk
Rc<T>
In std::memory.
Shared ownership as a library: a reference-counted box. Rc::clone makes another handle
to the same box; the value is destroyed when the last handle is dropped. Access is read-only (a
shared reference); put a mutex inside if you need mutation. Rc is not thread-safe.
A Weak<T>, from Rc::downgrade, keeps the box but not the value: Weak::upgrade is
Some(Rc) while a strong handle exists, else None. It is for a parent pointer, a cache or an
observer list, where an Rc would make a cycle (D-0125). Arc<T> and ArcWeak<T> are the same
with atomic counts, for handles that cross threads (D-0259, §19).
| Function | Signature |
|---|---|
Rc::new | (T) : Rc<T> |
Rc::clone | (ref<Rc<T>, shared>) : Rc<T> |
Rc::get | (ref<Rc<T>, shared>) : ref<T, shared> |
Rc::downgrade | (ref<Rc<T>, shared>) : Weak<T> |
Weak::upgrade | (ref<Weak<T>, shared>) : Option<Rc<T>> |
Weak::clone | (ref<Weak<T>, shared>) : Weak<T> |
Arc::new, Arc::clone, Arc::get, Arc::downgrade | as Rc's, with Arc<T> and ArcWeak<T> |
ArcWeak::upgrade, ArcWeak::clone | as Weak's |
import std;
fn main()
{
Vec<i32> payload = Vec::new();
Vec::push(&mut payload, 42);
auto a = Rc::new(payload); // payload moves into the box; count = 1
auto b = Rc::clone(&a); // count = 2
assert(Vec::len(Rc::get(&b)) == 1);
drop(a); // count = 1; the box survives
assert(Rc::get(&b)[0] == 42);
drop(b); // count = 0: the Vec is destroyed, then the box is freed
}Box<T>
In std::memory.
A value on the heap with exactly one owner: Rc without the count. Box::new(v) moves v
in; Box::get(&b) and Box::get_mut(&mut b) borrow it; Box::into_inner(b) moves it back out; Box::clone(&b) copies a box whose value is clone;
destroying the Box destroys the value. Its main use is a type that contains itself, which needs
something holding a pointer between it and itself: a struct that contains itself directly has no
size, and is rejected with diag.recursive-type.
import std;
struct Node
{
i32 value;
Option<Box<Node>> next; // Option<Node> here would be diag.recursive-type
}
fn main()
{
Option<Box<Node>> list = None;
list = Some(Box::new(Node { .value = 1, .next = list })); // each node owns the next
list = Some(Box::new(Node { .value = 2, .next = list }));
Box<i32> counter = Box::new(41);
*Box::get_mut(&mut counter) += 1;
assert(*Box::get(&counter) == 42);
i32 n = Box::into_inner(counter); // the value back; the Box's memory is freed
assert(n == 42);
} // list: both nodes destroyed, the outer one firstDestroying a chain of Boxes does not use a stack frame per node when each Box is the
last thing its node destroys (its first-declared resource field, as next above): the next node is
destroyed by a loop, in the same order. So a list of a million nodes goes out of scope like any
other value.
import std;
struct Node
{
i32 value;
Option<Node> next; // ✗ diag.recursive-type (static): Node would contain itself
}
fn main()
{
}swap and replace
In std::core.
A value cannot be moved out of something you hold only by reference, since that would leave
a hole. So two values behind references are exchanged by swap(&mut a, &mut b), and one is
exchanged for a new value by replace(&mut r, v), which returns the old one. Two elements of the
same Vec or slice are exchanged by Vec::swap(&mut v, i, j) or slice_swap(s, i, j), which also
handle i == j. Nothing is copied or destroyed: each value just changes place.
overwrite(&mut r, v) is replace for when the old value is not wanted: it stores v and
destroys what was there. Each place is written as an assignment through the reference would
write it, so a live reference that conflicts with either place, such as a shared reborrow
auto s = &*r still in use, makes the exchange fault with diag.aliasing-conflict.
import std;
// Sorts any run of Strings by length: the elements are resources, so
// they are exchanged, never copied out.
fn sort_by_len(slice<String, exclusive> s)
{
for (usize i = 1; i < slice_len(s); i += 1)
{
usize j = i;
while (j > 0 && StringView::len(&s[j - 1]) > StringView::len(&s[j]))
{
slice_swap(s, j - 1, j);
j -= 1;
}
}
}
struct Pair
{
String left;
String right;
}
fn main()
{
Vec<String> words = Vec::new();
foreach (w in ["pear", "fig", "banana", "kiwi"])
{
Vec::push(&mut words, String::copy(w));
}
sort_by_len(&mut words);
assert(StringView::len(&words[0]) == 3 && StringView::len(&words[$ - 1]) == 6);
Pair p = Pair { .left = "L", .right = "RR" };
swap(&mut p.left, &mut p.right);
String old = replace(&mut p.left, "new"); // old is "RR"
assert(StringView::len(&old) == 2 && StringView::len(&p.left) == 3);
}An empty slot is filled by plain assignment: a None owns nothing, so *slot = Some(...)
writes over it (§07). To put a value where one may already be, use replace, which hands the old
one back to you.
import std;
struct Node
{
i64 val;
Option<Box<Node>> next;
}
// Appends at the tail: walk to the empty link, then fill it.
fn push_back(ref<Option<Box<Node>>, exclusive> head, i64 v)
{
ref<Option<Box<Node>>, exclusive> slot = head;
while (true)
{
match (&mut *slot)
{
Some(b) : { slot = &mut Box::get_mut(b).next; },
None : { break; },
}
}
*slot = Some(Box::new(Node { .val = v, .next = None })); // slot holds None: nothing to lose
}
fn main()
{
Option<Box<Node>> list = None;
push_back(&mut list, 1);
push_back(&mut list, 2);
i64 sum = 0;
ref<Option<Box<Node>>, shared> cur = &list;
while (true)
{
match (cur)
{
Some(*b) : { sum += b.val; cur = &b.next; }, // b: the node in the box
None : { break; },
}
}
assert(sum == 3);
}Vec<T>for sequences,Option<T>for maybe-absent values,Result<T, E>for fallible calls,Box<T>for one value on the heap (a recursive type's link),Rc<T>when two owners are genuinely needed.- Library functions take
&vor&mut v; match the mode to what you need. - Hold element references briefly; any
pushorpopmay invalidate them (§10).
§22Surface syntax reference
spec/22-surface-syntax.mdTokens, declarations, statements and expressions on one page, with the tie-break rules a reader needs.
This section is the syntax in one place: the tokens, the declarations, the statements, the expressions, and the handful of places where the grammar needs a tie-break rule. It is meant for looking things up; the semantics are in the earlier sections.
Lexical structure
- Comments:
// to end of lineand/* block */(block comments do not nest). - Source text is UTF-8. The characters that reorder how text is displayed (U+202A–U+202E, U+2066–U+2069) are refused anywhere in it, so the order a reader sees is the order the compiler reads; in a string literal write them as
\u{202E}(spec/22[Bidi-Controls]). - Identifiers: ASCII letters, digits and
_, not starting with a digit. - Integer literals: decimal digits (two or more do not start with
0:0755is refused, as C would read it as octal), or hexadecimal, octal or binary after0x,0o,0b, optionally: type(255: u8,0xFF: u8). No sign:-is an operator. Float literals:1.5,0.25: f32,1.0e-7. Digit separators: a_between two digits is ignored (1_000_000,0xFFFF_0000). Booleans:true,false. Unit value:(). - String literals:
"…", typestr. Escapes\n \r \t \0 \\ \"and\u{hex}; any other source character stands for itself. A literal must close on its own line. Byte literals:b"…", typearray<u8, N>(a slice of static bytes where aslice<u8, shared>is declared); the same escapes except\xNNin place of\u{…}, ASCII characters only, at least one byte. Byte character literals:b'a', one ASCII character or escape: an unsigned integer literal,u8unless its context gives another unsigned type. No character literals (achartype). - Keywords:
fn struct bitstruct enum resource match if else while for foreach return auto const module import export unsafe extern break continue move mut true false as void(asis reserved and unused). - Reserved type names (cannot be identifiers):
i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 isize usize f32 f64 bool str ref rawptr array slice handle mutex guard. The wordssharedandexclusiveare ordinary identifiers that only have meaning insideref<…, …>. - Whitespace and newlines are insignificant between tokens; brace placement is a matter of style.
Types
| Type syntax | Meaning |
|---|---|
i32, u8, f64, bool, … | built-in scalars |
str | text value (§21) |
void | the unit type (its value is written ()) |
ref<T, shared>, ref<T, exclusive> | references |
rawptr<T> | raw pointer |
array<T, N> | fixed array, N a constant expression (§16) |
slice<T, shared>, slice<T, exclusive> | a borrowed run of elements (§16) |
fn(T1, T2) : R, fn(T1) | function type (result void if omitted) |
handle<T>, mutex<T>, guard<T> | concurrency types |
Name, Name<T1, T2>, mod::Name | a declared struct or enum, optionally instantiated |
Declarations
// Functions. `export` makes an item visible outside its module.
fn name(T1 p1, T2 p2) : R // return type after a colon
{
body
}
fn name(T1 p1) // no return type: returns void
{
body
}
export fn name<T, U>(T x) : U // generic, exported
{
body
}
fn Type::name(ref<Type, shared> self) // associated function, called as Type::name(...)
{
body
}
fn Type::drop(ref<Type, exclusive> self) // the destructor of Type
{
body
}
// Foreign functions: parameters and result must be scalars, void or rawptr.
unsafe extern fn name(rawptr<u8> buf, usize len) : isize;
// Structs and enums. `resource` marks a type that manages something.
struct Name<T>
{
T field; // fields end with ;
export i32 visible; // field visibility is per field
}
resource struct Name
{
i32 field;
}
enum Name<T>
{
Variant(T), // with a payload
Other // without
}
// Modules and imports.
module name
{
items
}
export module name
{
items
}
module name "./path/to/file.cb"; // the same, with that file's items as the body (§17);
// `export module name "…";` as for the inline form
import path::to::item;Statements and blocks
T x = e; // typed local
auto x = e; // inferred local
T x; // uninitialised local (must be assigned before use)
Name { f1, f2 } = e; // destructuring: every field
e; // expression statement
{ // a block; no ; needed after it
statements
}
if (c)
{
statements
}
else if (c2)
{
statements
}
else
{
statements
}
while (c)
{
statements
}
match (e) // a comma after each arm (optional after the last)
{
A(x) : e1,
B : e2,
_ : e3,
}
unsafe
{
statements
}A block is { statement* expr? }: zero or more statements, then an optional trailing
expression that is the block's value. if, while, match, unsafe and plain blocks may stand
as statements without a semicolon, and their value is discarded. When one appears as the initialiser
of a declaration or the right side of an assignment, the enclosing statement still ends with ;.
Expressions
| Form | Example |
|---|---|
| literals and names | 42, 3.5, true, (), x, mod::item |
| string and byte literals | "hello\n" (a str), b"\x00\xff" (an array<u8, 2>) |
| struct literal | Point { .x = 1, .y = 2 }, Box<i32> { .value = 5 } |
| array literal | [1, 2, 3], [0; 256] (256 copies of 0) |
| enum variant | Some(5), None, Shape::Dot |
| field, index, call | p.x, a[i], f(x, y), Vec::len(&v), identity<i64>(5) |
| borrow, deref | &x, &mut x, *r |
| operators | see the precedence table in §13 |
| propagate | e? |
| block, if, match, unsafe | as values: i32 x = if (c) { 1 } else { 2 }; |
| closure | [a, b](i32 x) { a + b + x }, move [v]() { Vec::len(&v) } |
| control | return e, return, break, continue |
Reading the grammar in tricky spots
- Declaration or expression? A statement that begins with a type name,
fn,auto, or the name of a struct or enum is a declaration; otherwise it is an expression.Point p = …declares;p.x = 1;assigns. [starts a closure or an array. It is a closure only if the closing]is immediately followed by( … ) {. Otherwise it is an array literal.- Generic call or comparison?
name<T>(…)with a type inside the angle brackets is always a generic instantiation. Comparisons are non-associative, soa < b > cis never a comparison. - Conditions are always parenthesised, which is why
if (Point { .x = 1 } == p) { … }needs no special rule. - A pattern as a condition.
if (Some(x) = e)andwhile (Some(x) = e)are read as a pattern followed by one=when the condition beginsName(,m::Nameor a literal;Some(x) == eis a comparison, andx = e(a bare name) the assignment it is everywhere, which is not abool. Name { f1, f2 } = e;(bare identifiers in braces) is destructuring;Name { .f = e }is a literal.bitstruct Name : u32 { f : 6; … }declares a struct of bit fields (§16): the widths fill the backing type exactly, low bit first.struct Name align(64) { … }raises a struct's alignment to a power of two up to 4096 (§16);alignis not reserved.&mutis two tokens, one operator.x = y = zassigns right to left.
Restrictions and deliberate absences
Things the grammar does not provide, each a considered decision recorded in the specification:
- no character literals (
b'x'is a byte: au8, or the unsigned type its context asks for), no indexing or slicing of astr; noswitch(amatchon an integer, §16, is the checked form); nogoto - no
import … asrenaming; no method-call syntax (v.push(x)— final,CHG-0132); no operator overloading - patterns in
matchare_, a name (a binder or a constant), a literal, a variant, a variant with a pattern for its payload, a struct pattern (P { a, .. }, which takes the value apart, §16), and a variant with fields (E::V { a, .. }, D-0324), nothing else (no ranges, alternatives or guards); destructuring takes a struct apart whole: every field named, or..for the rest (destroyed as usual), andfield : namerenames one - no partial initialisation of aggregates
- no lifetime annotations: a function returning a reference borrows from its one reference parameter, or, with several, from those its
fromclause names (§10); a result whose parts come from different arguments cannot be described - no user-declared bounds on generic type parameters: only the six built-in ones (
eq,ordered,number,integer,clone,plain), on a function's parameters; a struct or enum satisfiescloneby its fields, andeqandorderedwhen it is a key type (D-0271), nevernumberorinteger - no
mutqualifier on bindings (the keyword is reserved for&mut) - no moving a resource out of a field of a live struct; move the whole struct, or take it apart (a field of a temporary may be moved out; the rest ends with the statement)
- no spawning a closure that borrows; use
move
What an implementation must document
The width of isize/usize; byte order; enum discriminant width; struct padding; the
value of dangling<T>(); the encoding of function values; the address str_ptr gives for a
str's bytes and whether equal values share one; and the form in which faults and diagnostics are
reported. Everything else is fixed by the language.
PPerformance
Measured advice for fast compiled programs: what costs time in cobc's output, and how to write code the compiler can see through.
This chapter is about making compiled programs fast. Every piece of advice in it was
measured: a small program written two or more ways, each way built by cobc at its default -O2
under GCC and under Clang, and timed. The ratios quoted are from those runs, on the machine described
in bench/RESULTS.md. They describe cobc as it is today. The compiler proves more with each
release, so a gap measured here may close; where that is likely, the text says so.
A workflow by stage
| Stage | Command | What it costs and gives |
|---|---|---|
| Writing | cobc --check prog.cb or cobc --check src/ | Every check made before a program starts: syntax, names, types, ownership, exhaustive matches. Nothing runs and no C is compiled, so it takes seconds even for a large program, and a program that reads input, writes files or serves the network is checked without doing so. |
| Trying it | cobc --run -O0 prog.cb | -O0 makes the C compiler's work short, at the price of a slow program: right while you only care whether it behaves correctly. |
| Measuring and shipping | cobc -o prog prog.cb (-O2, the default) | What users run. Measure only this: -O0 keeps exactly the work -O2 removes, so a comparison made at -O0 says nothing about the real build. |
Beyond -O2: --cc clang and --cc gcc choose the C compiler, and neither wins everywhere
(bench/RESULTS.md has the comparison); -march=native lets the C compiler use every instruction
your processor has, at the cost of an executable that may not run on an older one. To see where the
time goes, perf stat ./prog counts instructions and perf record ./prog then perf report names
the functions; cobc --keep-c keeps the generated C, in which every run-time check is a visible
line ("Reading the C that cobc generates" in the Introduction).
Where the time goes
A compiled CobaltC program makes every check the specification requires, except those the compiler proves can never fail. Two kinds of check cost very differently:
- Cheap checks, a compare and a branch the processor predicts: an index against a length, an addition for overflow. In a tight loop they cost a few per cent to a few tens of per cent.
- Tracking, which the runtime library does for a value the compiler cannot reason about: it records each reference and access path as it is made, checks each access against the others (§08–§09), and retires them at the end of their statement or scope. This costs hundreds of nanoseconds per access, a hundred times a plain access or more.
So the advice that matters most is not about saving checks: it is about writing code whose values the compiler can see through, so that tracking is left out. The sections below are in order of how much they saved in the measurements.
A program none of whose conflicts are left to the run, because the compiler refutes or proves every
one of them before it runs, is decided, and cobc builds it with no tracking at all: no
record of references, nothing retired at the end of a statement (D-0284). The outcome is the one
the tracked build gives. A program stops being decided as soon as one function leaves a conflict to
the run: a reference whose origin the compiler cannot follow, an overlap that depends on values, a
Vec of views or a struct holding a reference that leaves the function that made it (passed on,
returned holding what is not a parameter's, stored where a parameter reaches), a thread whose
handle leaves the frame that lent it something. cobc -v
says which: "lowered pathless", or "kept paths" with the file and line of the first such conflict.
A decided program is also lowered a second time knowing it (D-0285): a view, or any value that only
holds references, is then plain data with no runtime record at all, and -v says "lowered pathless
and decided". There a value passed to a function or returned from one goes as its bytes, with no
runtime record of its own (D-0286), and a parameter or result the function only reads, borrows or
hands on is bound with none either. Since D-0294 the same holds for nearly every local of a decided
program: a value of a recursive type, a local that is assigned, matched, sliced or moved, a struct or
variant built as the result, a reference parameter -- none of them has a runtime object, and where
the generated C still asked for a record that nothing could read, the record is removed. The
self-hosted compiler, a decided program, runs in half the instructions it took before.
Since D-0315 a decided program keeps almost no cleanup bookkeeping either. A value whose end frees
memory alone goes from the call that makes it to the binding, argument or field that takes it with no
runtime object, and generated C frees it where its scope ends; the temporaries a statement borrows end
where the statement ends; a fn parameter the function only calls, and a local whose type has a
destructor of its own, are noted in a table the runtime reads only if a fault comes, so they end in the
order the rules give; and a statement stores its location for a fault only before a call that may read
it. The self-hosted compiler now runs in about a fifth of the instructions it took before D-0315, the
runtime about a tenth of its time.
Threads are decided too when what they are lent is held by a handle a binding of the lending frame
keeps until join (D-0289): no thread outlives the frame that holds its handle, so the compiler
checks the lender's accesses against the lend as it would any borrow, and a lock takes no record
either. A worker pool is decided too: a local Vec of handles holds what every thread pushed onto
it was lent (Vec::push(&mut hs, spawn(work, &shared))), and a handle taken out of it by foreach
or Vec::pop holds it as well, until it is joined (CHG-0384). A handle passed around while it lends,
a Vec of handles given to another function, or a thread that runs a fn value, leaves the program
to the run. Two ranges of one slice lent at once are told apart when their bounds are literals, or
when one range ends where the other starts at the same local (spawn(work, &mut s[0..mid], …) and
spawn(work, &mut s[mid..n], …)), a local declared once in the function, outside every loop and
closure, that nothing assigns, borrows or captures without move: it has one value in the frame, so
the two ranges share no element (report 311). Other computed bounds ([0..mid] beside [mid + 1..n],
or a mid the function writes) cannot be told apart: the function's accesses to s are checked as it
runs, and with threads each check is shared between them, which can make a recursive split far slower
than no threads at all. slice_parts(s, 2) gives disjoint parts as slices of their own in any case;
--report-tracking names such an access ("an access to s that only values decide").
A local that keeps references in data, such as the Vec<StringView> that StringView::split gives or
a struct of views built and read in one function, is checked the same way (D-0290): it holds what
was stored into it, and a view read out of it holds that, so writing the text while the Vec still
lives is refused, or left to the run when the Vec may hold nothing. A Vec holds what it keeps
until its scope ends; a struct that owns nothing, until its last use.
A call given such a local exclusively may store into it what its other arguments give. An argument
given shared gives itself and every reference the callee could form into a part of it (*slot =
&v[0] given &v). One given exclusively, such as the output in inflate_codes(&mut reader, out, …)
beside a reader that keeps a slice, gives its parts only when the callee's body may store one there.
The compiler keeps a summary of what each function stores, including through the functions it
calls (spec/14 §6, frame-held aggregates). A callee that stores nothing from the output adds
nothing to the reader, so clearing the output afterwards is still decided. When a callee does store
a part (*slot = &v[0] given &mut v), the caller is refused or left to the run when it changes v
while slot is still used. The run then faults as it does with --all-checks.
The same holds for a handle wrapped in the value a binding takes (Option<handle<T>> h = if (go) {
Some(spawn(…)) } else { None }), for a reference call(…)? gives, and for a slice lent whole to a
thread, such as the parts slice_parts gives (D-0291): each holds what it was formed from, and the
compiler checks the frame's accesses against it. When a reference or slice binding ends while a
thread or a closure still holds it, what they hold passes to what the binding referred to, so a
write to it after the loop that lent it is still checked. A copy of a lent slice, an element of
one, and a reborrow of one are left to the run while the lend lasts.
A program that is not decided no longer pays for every reference (D-0292). A function the
compiler decided forms its references with no record at all, in any program: &x, &s.f, &*p cost a
check against the references the run does record on that value, which is nothing when there are none,
and after that nothing — and since D-0293 the nothing is no call either: the generated C tests the
reference's kind, and an owner's binding a one-byte mark, before it would call the runtime. The record is kept only where it is needed: a reference stored into data
becomes a holder as it is stored, a reference arriving in a function that left a conflict to the run
is recorded as it arrives, an element reference is light too once the element's object persists
(D-0295), and slices, views, lock guards and what a thread is lent are recorded everywhere. So a program that keeps paths for one function pays for that function,
not for all of them.
To see where your own program still pays for tracking, run cobc --report-tracking prog.cb. It
compiles nothing: for a decided program it says so, and lists by line the frames, statement scopes
and objects its generated C still writes for an unwind (D-0315), for most decided programs none;
otherwise it names the first conflict left to
the run, then lists the lines whose generated C still calls the runtime's tracking, with the
kinds of call on each, lines inside a loop first. A line inside a loop is the one to look at; a
line that runs once (a binding, a move into a call) costs next to nothing. The sections below say
how to rewrite what it finds.
To see the decision itself, and keep it, run cobc --certificate cert.txt prog.cb (D-0299): the
file names each function body the static pass decided, each conflict it left to the run, the
checks made when a call is made, and the compiler's verdict for the program. It is the record of
what the compiler proved before it left checks out. For a program in the fragment the executable
model covers, cobmodel certify cert.txt prog.cb runs every interleaving with those bodies kept
unrecorded, as the compiler keeps them, and reports any alias or temporal fault the rules would
find there. spec/ASSURANCE.md says what each kind of evidence the project keeps establishes.
The other direction is cobc --all-checks prog.cb: it compiles the program with every proof about a function's reference parameters switched off, so every access through a parameter is checked where it is made. It is slower, and it exists for comparison: a program must behave the same both ways, and the project's test battery runs its whole file suite under it (D-0209).
Loop over a splitter's call
A Vec of views is still made: an allocation, and a view stored for each part. The
commonest text loop, foreach (l in StringView::lines(v)), would make one; written that way, with
the splitter's call as the loop's collection, it makes none: the loop walks the text and finds each
part as it reaches it, a view of the text like any other (D-0287). That covers split, lines,
split_whitespace and chars, of a StringView or a String (split with its separator written
as a literal; another separator, a StringView or &s, makes the Vec). The parts, their order and the
program's outcome are the Vec's; only the Vec is not made. Binding the result first
(Vec<StringView> words = StringView::split_whitespace(l);), to take its length or index it, keeps
the Vec and its cost. A word count over a 13.7 MB text (400,000 lines) took 9.8 s and 160 MB with
the Vecs, when they kept the program tracked (D-0287), and takes 0.47 s and 42 MB with the loops
over the calls.
import std;
fn main()
{
String text = "the quick fox\njumps over\n\nthe dog\n";
usize lines = 0;
usize words = 0;
usize longest = 0;
foreach (l in StringView::lines(&text))
{
lines += 1;
foreach (w in StringView::split_whitespace(l))
{
words += 1;
if (StringView::len(w) > longest)
{
longest = StringView::len(w);
}
}
}
printf("%v lines, %v words, longest %v\n", lines, words, longest);
}4 lines, 7 words, longest 5
Keep hot vectors confined
cobc proves a Vec confined when nothing but its own name can ever reach it.
A confined Vec's accesses compile to plain C with bounds and overflow checks and no tracking. A
local Vec, or one a function takes by value, stays confined when it is:
- made where it is declared (
Vec::new(), or a function's result), or received as a parameterVec<T> v; - used through
Vec::push,Vec::len,Vec::pop,Vec::reserve,Vec::swap,Vec::reverse,Vec::insert,Vec::remove,Vec::truncate,Vec::clear,Vec::sort,Vec::contains,Vec::index_of,Vec::binary_search, indexing (v[i],v[i] = x,v[i].f += x) andforeach, alsoforeach (p in &mut v)writingp.f; - passed as
&vor&mut vto functions that themselves use it only in those ways (the compiler checks each such function), and in no other argument of the same call; - at most moved out at the end: as the function's result (also inside a struct or
Ok(…)built as the result), or into a call as its last use, such asoverwrite(&mut h.v, v).
A shared reference to an element, held across the loop
(ref<i64, shared> first = &v[0];), leaves the loop's reads as fast as before: a read cannot clash
with a shared reference. Writes to the vector and pushes onto it are then checked, since one of
them could. What loses confinement altogether is an exclusive reference to an
element (&mut v[i] kept in a binding), &mut v handed to a function that may keep a path to it,
a closure that names v, or moving v to another binding; then every access in the loop is
tracked, about ten times the cost in a summing loop.
A vector that is a field of a local struct (h.v) is confined the same way while the function
uses it only by indexing (h.v[i], h.v[i] = x, h.v[i].f += x) and Vec::len(&h.v), and never
uses h whole (moving it, borrowing it, capturing it); the struct's other fields are used freely.
Where the function also pushes to h.v, borrows an element of it or hands it on, indexing it there
is tracked; then hand it to a helper (sum_helper(&h.v)), loop over it with
foreach (x in &h.v), or move it out for the loop and back (replace then overwrite), each of
which is as fast as a local. Confinement is decided per function: one function's use of a vector
does not slow another function down.
A function that takes a struct by reference and loops over the struct's
vectors (the shape of most programs: fn restock(ref<Inventory, exclusive> inv, …)) runs as plain
code too, wherever the struct lives, when that reference is the function's only one, its other
parameters are plain values, and it uses each such vector only in the ways listed above (no
&inv.counts handed to another function, no element borrowed and kept). The function then
checks once, as it starts, that no element of those vectors is borrowed elsewhere, and otherwise
runs its checked code, which faults where §08 says it must. Its other fields (inv.owner,
inv.total) are used freely. Over 1,000,000 elements through such a reference, a write
v[i] = v[i] + 1 went from 546 to 1.8 ns an element, pop from 280 to 8, push from 41 to 9:
the speed of a local.
import std;
struct Inventory
{
String owner;
Vec<i64> counts;
Vec<u8> flags;
i64 total;
}
// One reference, to a struct whose vectors it only indexes, pushes,
// swaps and measures: checked once as it starts, then plain code.
fn restock(ref<Inventory, exclusive> inv, i64 amount)
{
for (usize i = 0; i < Vec::len(&inv.counts); i += 1)
{
if (inv.counts[i] < 3)
{
inv.counts[i] += amount;
inv.flags[i] = 1;
}
inv.total += inv.counts[i];
}
Vec::push(&mut inv.counts, amount);
Vec::push(&mut inv.flags, 0);
Vec::swap(&mut inv.counts, 0, Vec::len(&inv.counts) - 1);
}
fn main()
{
Inventory inv = Inventory { .owner = "shop", .counts = Vec::new(), .flags = Vec::new(), .total = 0 };
foreach (i in 0..8: i64)
{
Vec::push(&mut inv.counts, i % 5);
Vec::push(&mut inv.flags, 0);
}
restock(&mut inv, 10);
printf("%s: %v items, total %v, first %v\n", &inv.owner, Vec::len(&inv.counts), inv.total, inv.counts[0]);
}shop: 9 items, total 73, first 10
| The same sum of 20,000,000 elements, ten times | Time, relative |
|---|---|
A local Vec, indexed | 1 |
The same Vec, passed as &v to a helper that indexes it | 1 |
A Vec field of a local struct, indexed in the loop (h.v[i]) | 1 |
A Vec field of a struct passed to that helper (sum_helper(&h.v)), or moved out for the loop and back | 1 |
A local Vec while a shared reference to one element is held | 1 |
A local Vec that is moved to another binding after the loop | 10 |
Predicates. Vec::retain, Vec::position and Vec::binary_search_by run
as plain loops when the function they are given is a closure literal written at the call, a named
function, or a fn value holding a named function, provided it only reads the elements it is
given (Vec::sort_by does so for a closure literal): 1,000,000 elements through retain took 3 to
9 ns each. A closure stored in a
variable first (fn(…) : bool p = [lim](…) { … };) is tested when the call starts: one that only
reads what it is given is called with bare element addresses, about 150 ns an element (the cost of
calling through the variable); one that may keep what it is given is lent each element through the
runtime, about a microsecond. Writing the closure at the call is fastest.
Updating elements
Every way of updating the elements of a Vec of structs compiles to the element's address
and a few plain instructions, as long as the vector is confined: v[i].x += v[i].vx,
foreach (p in &mut v) { p.x += p.vx; }, a call that receives one element, step(&mut v[i]), and
an element named for a block, ref<P, exclusive> p = &mut v[i]; (provided the rest of that block
uses p and not v). Over 100,000 elements updated 100 times, all four took the same time. Choose
whichever reads best:
import std;
struct Particle
{
i64 x;
i64 vx;
}
fn main()
{
Vec<Particle> ps = Vec::new();
foreach (k in 0..1000: i64)
{
Vec::push(&mut ps, Particle { .x = k, .vx = k % 7 - 3 });
}
foreach (t in 0..100)
{
foreach (p in &mut ps) // plain code: the loop holds ps for its length
{
p.x += p.vx;
if (p.x < 0 || p.x > 1000)
{
p.vx = -p.vx;
}
}
}
printf("%v %v\n", ps[0].x, ps[999].x);
}294 803
Functions that take references
A function that takes a reference (ref<T, …>) or a slice runs as plain code, with no
tracking inside it, when cobc can see that nothing else can clash with that reference while the
call runs. It can see it in three cases: the reference is the function's only one; all its
references are shared; or, the usual shape of code that builds something from its input, some
are exclusive and the rest shared and every one is to plain data. In the third case the function
checks once, as it starts, that its arguments do not overlap, and then runs unchecked; where they
do overlap (count(&mut c, &c.buf[0..4])), it runs the checked code instead, which faults where
§08 says it must. Plain data is numbers, bool and char, and arrays, structs and enums of them;
not a String, a Vec, a Box or a reference. And in every case the body must use each reference
only directly:
- through it: reads and writes of the value, its fields and its elements, and
slice_len; - never handed to another function, kept in a variable or a struct, or borrowed from (an only reference may still be handed whole to a function that returns plain data or nothing);
- beside parameters that are plain values, in the third case.
| 10,000,000 bytes summed into a struct of two counters | Time, relative |
|---|---|
fn feed(ref<Acc, exclusive> a, slice<u8, shared> data) | 1 |
fn feed(Acc a, slice<u8, shared> data) : Acc, the counters passed in and returned | 0.7 |
The first, each byte read through a helper, a.sum += byte_at(data, i) | 80 |
The first, with Acc also holding a Vec | 90 |
So keep the loop over the input in the function itself, and keep the state it updates in a
struct of plain fields. Where that state belongs to something larger (a struct that also holds a
String or a Vec), pass the plain part alone, as count(&mut r.counts, …) does here:
import std;
struct Counts
{
u64 bytes;
u64 newlines;
u64 sum;
}
struct Report
{
String name;
Counts counts;
}
// One exclusive reference to plain data beside a shared slice, each used
// only directly: checked once as the call starts, then plain code.
fn count(ref<Counts, exclusive> c, slice<u8, shared> data)
{
for (usize i = 0; i < slice_len(data); i += 1)
{
c.bytes += 1;
c.sum = wrapping_add(c.sum, widen<u64>(data[i]));
if (data[i] == 10)
{
c.newlines += 1;
}
}
}
fn main()
{
Vec<u8> data = Vec::new();
foreach (k in 0..1000)
{
Vec::push(&mut data, narrow_wrapping<u8>(k * 7));
}
Report r = Report { .name = "input", .counts = Counts { .bytes = 0, .newlines = 0, .sum = 0 } };
count(&mut r.counts, &data); // the struct holds a String: pass only its plain part
count(&mut r.counts, &data[0..10]);
printf("%v: %v bytes, %v newlines, sum %v\n", &r.name, r.counts.bytes, r.counts.newlines, r.counts.sum);
}input: 1010 bytes, 4 newlines, sum 126831
Tell the C compiler a slice's length
Every index is checked against its slice's length, and the C compiler removes a check it can
prove always passes. When a loop's bounds come from the slice itself (i < slice_len(s)) it can.
When they come from somewhere else, such as a constant, a grid's width and height or a row stride,
it cannot by itself: a slice parameter's length is a number it knows nothing about. In a loop that
reads several neighbours of each cell, those checks can be half the work.
So cobc tells it (D-0320). A loop whose bounds are known before the program runs, and which
indexes slices it never rebinds, is emitted twice: under a test of the slices' lengths
(if (src.len >= 65535 && dst.len >= 65279), one past the largest index the loop can form), the copy
in which the C compiler proves the checks and removes them; otherwise the same loop. Both copies keep
every check, so nothing the program does can change. Given a short slice it runs the loop as written
and faults at the first index out of range, as it always did.
| A 256 × 256 five-point blur over two slices, 1,000 passes | GCC | Clang |
|---|---|---|
| Slice parameters, before D-0320 | 31 instructions a cell | 38 |
| Slice parameters, now | 17 | 16 |
Now, with assert(slice_len(src) >= CELLS && slice_len(dst) >= CELLS) before the loop | 17 | 16 |
Now, with the same assert written with == | 17 | 28 |
ref<array<u32, CELLS>, …> parameters | 17 | 16 |
Slice parameters, the additions wrapping_add | 12 | 4.9 |
| The same loop written in C, which checks nothing and whose additions wrap | 12 | 4.9 |
- What the guard needs: the loops' bounds made from literals,
consts, locals bound to such values that nothing assigns, and the variables of the loops around them, through tests such asx < B,x <= Bandx + 1 < B; indices made from those with+,*, and-,/and%of constants; slices the loop does not write, borrow or declare again.simd_loadandsimd_storecount their lanes. cobc --report-guards prog.cblists each loop that indexes a slice: its guard, asslice_len(s) >= Ntests, or the index that has none and the name in it that is not kept below a value known before the run (first_row, where a loader stores rowsfirst_row + rowof a grid), and whether the guard is used (CHG-0449). A guard that asks for more than a slice has is never taken:at < WORDSwhere the loop readsnow[at + 1]asks forWORDS + 1.cobc --keep-cshows the test itself before each loop.- A loop whose bounds are known only when the program runs is not guarded. Where its bound is the slice's own length, say so: in
foreach (i in 0..slice_len(s))the C compiler provess[i]from the loop alone. - An
assertof the length is no longer needed for speed; it stays the way to stop early with a message of your own (assert(slice_len(s) >= n, "need %v cells", n)). If you write one, write>=: Clang draws nothing from==(28 instructions a cell against 16). - The rest of the difference from the C is the overflow checks on the additions, which C does not make. They are what
+means, so keep them unless wrapping is what you mean (§06). Withwrapping_addin their place, the build ran the same instructions as the C under both compilers. - Whether every check goes also depends on how the indices are written. An index the loop only adds to, and loop bounds as tight as the accesses (
p < LANES - 1where the body readsp + 1), are the forms the C compiler proves best.perf staton the build, orcobc --keep-cand the disassembly, shows whether it did.
import std;
const usize W = 16;
const usize H = 16;
const usize CELLS = W * H;
// The loops' bounds are constants: `cobc` tests the slices' lengths once,
// before the loop, and the C compiler removes every index check in the copy
// it then runs (D-0320). A short slice faults where it always would.
fn blur(slice<u32, shared> src, slice<u32, exclusive> dst)
{
for (usize y = 1; y < H - 1; y += 1)
{
for (usize x = 1; x < W - 1; x += 1)
{
usize i = y * W + x;
dst[i] = (src[i - W] + src[i - 1] + src[i] + src[i + 1] + src[i + W]) / 5;
}
}
}
fn main()
{
Vec<u32> a = Vec::filled(CELLS, 0);
Vec<u32> b = Vec::filled(CELLS, 0);
a[8 * W + 8] = 100000;
foreach (pass in 0..10)
{
blur(&a, &mut b);
blur(&b, &mut a);
}
printf("%v %v %v\n", a[8 * W + 8], a[8 * W + 12], a[2 * W + 2]);
}1947 733 15
Text in hot code
std takes text it only reads as a StringView (D-0134), and that is the right choice in hot
code too. A view made from a String (&s where a StringView is declared) for a function that only
reads it costs nothing to make: the function is given the text's address and length, and the view's checks
are decided before the run. For a function of your own that a hot loop calls millions of times:
| 1,000,000 calls of a function that reads a 60-byte text | Instructions per call, gcc | clang |
|---|---|---|
fn f(StringView s), one view made before the loop and passed each time | 4 | 0.3 |
fn f(StringView s), called f(&text), a view made at each call | 4 | 0.3 |
fn f(ref<String, shared> s), called f(&text) | 4 | 0.3 |
fn f(String s), called f(String::clone(&text)) | 148 | 147 |
- A function that only reads its
StringView(indexes it, takes its length, hands it tostd's readers) costs nothing to call, whether the view is made at the call or once before the loop: it is passed as its address and length. Copying the text to pass aStringcosts an allocation and a copy each time. - To process input line by line, use a
read_lineloop:read_allfollowed byStringView::splittook about six times as long over the same 200,000 lines, the price of keeping every line's view at once. - Calls to
stdthat take a view cost per call, not per byte (a 620-byte text cost the same as a 60-byte one).
Building and writing text
| Building one String from 2,000,000 numbers | Time, relative |
|---|---|
String::append(&mut out, i) then String::append(&mut out, ",") | 1 |
sprintf("%v,", i), then append that | 9 |
A Vec<String> of pieces (each made by sprintf), then String::join | 19 |
String::append formats a number or a bool straight into the String, with no
intermediate text, so build output with it; sprintf makes a new String each time, about
two-thirds of a microsecond a call. Standard output is buffered (§21), so printf per line is a
fast way to write many lines: 2,000,000 lines to a file took 0.35 s with one printf per line and
0.24 s building one String with String::append and printing it once. Printing as you go is
fast enough for most programs and keeps no text in memory; building one String saves a little
more where all the text fits.
Choose the collection by what you do most
| Operation | Fast | Slow | Measured |
|---|---|---|---|
| Take elements from the front, in order | Queue::pop_front, or Vec::reverse once then Vec::pop | Vec::remove(&mut v, 0), which moves every remaining element: the cost grows with the square of the length | 10,000 elements: 2.4 times; 100,000: 51 times |
| Test membership in a large set | Vec::sort once then Vec::binary_search, or HashSet::contains | Vec::contains, which compares element by element | 20,000 keys, 5,000 queries: binary_search 5 to 6 times as fast, HashSet 1.2 times, growing with the size |
Fill a Vec whose size you know | Vec::filled(n, x), then write the elements | pushing one by one (with or without Vec::reserve first, which no longer saves anything measurable) | 50,000,000 elements: 5 to 6 times |
| A fixed table a hot function consults | an array literal ([0, 1, 2, …]), which allocates nothing | a function that builds and returns a Vec (or a Vec of Vecs) each time it is called | a tic-tac-toe search calling it at every position: 13 times |
Counting with a HashMap<String, …>: *HashMap::entry(&mut counts, w, 0) += 1 looks the
word up by its view and makes a String only for a word it has not seen, so counting a text costs
one allocation per distinct word.
Threads
Each running thread keeps its own share of the compiled program's runtime checks, so threads doing their own work run in parallel (§19). Measured with four threads each counting the words of the same text: 0.30 s, against 0.16 s for one thread doing a quarter of the work, and 0.24 s for four separate programs. To keep a thread's work its own:
- Move what a thread works on into it (
spawn(count, chunk)withchunkaVecyou no longer need): it then belongs to the thread. A thread that reads the spawner's data through a reference shares it. Read it through a shared reference *parameter* the function never rebinds or borrows (fn band(ref<Vec<Row>, shared> rows, …)), and hand its fields and elements on only to functions that keep nothing of them:cobcthen reads through it with bounds checks alone, since nothing can change what it reaches while the call runs, and several threads read one structure at once (four threads aggregating 20,000 rows: 30 ms, against 48 ms for one). A reference kept past the call, or stored in a struct, is tracked as usual, and threads that form such references into one structure take turns on its records. - Hand results back as the thread's result, through
join, or through aChannel, rather than writing into a structure every thread locks. - Keep large shared data out of atomics: an
Atomicper cell of a 200 × 200 board made four threads barely faster than one, while private rows per thread with the edge rows exchanged under a mutex ran 13 times faster and scaled. Atomics are for counters and flags. - Keep a lock's block to reads and writes through its guard (
{ auto g = lock(&m); *g += 1; }): such a block is a lock and an unlock and no guard object. The lock is in the mutex itself: an uncontended lock and unlock are one atomic compare-and-swap each, about 30 ns with the thread's note of what it holds (C'spthread_mutex_lockand unlock, 11 ns on the same machine). Four threads counting keys in oneHashMapbehind a mutex, a million updates in all, took about 0.1 s; giving the guard to a function, or returning from inside the block, makes the guard an object, about 45 ns a lock. - A thread per connection is a sound design for a server. Each thread is an operating-system thread with a reserved, mostly uncommitted stack, and a finished thread is reused by the next
spawn. A test server held 10,000 connections at once, each its own supervised thread answering two queries, in 250 MB, about 25 kB per idle connection, with no failures, and a round trip cost the same 0.13–0.16 ms with 1,000 connections open as with 10,000. An idle connection costs nothing while it waits: on Linux its thread sleeps in the kernel until data arrives or it is cancelled.
Arithmetic and plain values
- Every
+,-and*on integers is checked for overflow (§06). Where wrapping around is what you mean (hashes, checksums, random number generators), say so withwrapping_add,wrapping_muland their relatives: a tight sum took a third less time, and Clang executed 40% of the instructions. Never use them to avoid a check on arithmetic that should not overflow: the check is what turns a wrong result into a diagnostic. - Pass a struct by whichever reads best. A 64-byte struct of eight
i64passed to a function that reads it took the same time copied as through aref<…, shared>.
When nothing else is enough
A kernel that must run at the speed of hand-written C can be hand-written C:
extern "./kernel.c"; links it and unsafe extern fn declares it (§20). That code is outside every
guarantee CobaltC makes: its memory safety, its aliasing and its arithmetic are yours to get right,
and its declaration is an unchecked claim. Measure first.
- Measure the
-O2build, never-O0. - Keep a hot
Veca local (or a parameter it owns) that only its own name reaches; across a loop, hold shared element references only, never an exclusive one. - Index a struct's
Vecfield (h.v[i]) where the function only indexes it; where it also pushes to it or hands it on, loop withforeachor a helper. - Give a function over a struct's vectors the struct as its only reference, and keep its uses of the vectors to indexing and the
Veccalls listed above. - In a function that takes references, use them only directly: loop over a slice in the function itself, and update plain state through one
exclusivereference (or pass it by value). - Give a hot loop over a slice bounds known before the run (literals,
consts) or the slice's own length, so that its index checks can be proved. - Make a
StringViewonce, outside a hot loop; passing it on is free. - Build text with
String::append;printfper line is fine. - Write a child process's input in large pieces (
ChildInput::write,Child::write_input): each write goes straight to the pipe and wakes the child, so a write per line of 100,000 short lines cost 11 s of system time, and 64 KB at a time 0.06 s. Nothing is buffered, so a program that writes a line and then waits for the child's answer works as written. - Never
Vec::remove(&mut v, 0)in a loop over a longVec; for membership in a large set, sort once andVec::binary_search, or use aHashSet. - Make a
Vecof a known size withVec::filled, then write its elements. - Say
wrapping_only where wrapping is the meaning.
RThe std reference
Every exported item of std: its declaration, its documentation and its examples, generated from the library's source.
Every item a program can use from std, module by module, with its declaration, what it does,
and for some an example. The text is the /// documentation in impl/std itself
(spec/22 §1), read by impl/tools/cobdoc.py when this page is built; each example is a unittest
block of std (cobc --unittest-std --run prog.cb runs them all), run here as a program's main.
The items the compiler builds in, which have no CobaltC body (printf, sqrt, exit, …), are documented by hand in
impl/std/builtins.md and shown here as built in. §21 says which module to look in;
spec/21 is the normative text.
799 of the 833 items are documented so far.
std::core, std::collections, std::text, std::io, std::fs, std::env, std::memory, std::sync, std::random, std::math, std::stats, std::time, std::process, std::net, std::crypto::digest, std::crypto::kdf, std::crypto::aead, std::crypto::pk, std::x509, std::tls, std::http, std::http::client, std::http::server, std::database, std::database::postgres, std::encoding::json, std::encoding::hex, std::encoding::base64, std::encoding::toml, std::compress, std::ffi
std::core impl/std/core.cb
Option enum
export enum Option<T>A value that may be absent: Some(T) holds one, None holds nothing.
In std after import std;, unqualified, as are its variants.
Option::unwrap_or fn
export fn Option::unwrap_or<T>(Option<T> o, T d) : TThe value in o, or d when o is None.
An unused d is destroyed at the call's end.
Option::ok_or fn
export fn Option::ok_or<T, E>(Option<T> o, E e) : Result<T, E>o as a Result: Ok of its value, or Err(e) when o is None, so ? applies.
e is evaluated before the call; unused, it ends with the statement.
None becomes Err of the given error; Some becomes OkrunsOption<i32> none = None;
Result<i32, u8> r = Option::ok_or(none, 7);
match (r)
{
Ok(_) : assert(false),
Err(e) : assert(e == 7),
}
assert(Result::is_ok(&Option::ok_or(Some(5), 7)));Option::unwrap fn
export fn Option::unwrap<T>(Option<T> o) : TThe value in o.
Faults (unwrap_failed) when o is None. Option::expect gives the fault a message of your own; Option::unwrap_or gives a default instead.
Option::expect fn
export fn Option::expect<T>(Option<T> o, str message) : TThe value in o, faulting with message when there is none.
Faults (unwrap_failed, showing message) when o is None.
Option::is_some fn
export fn Option::is_some<T>(ref<Option<T>, shared> o) : boolWhether o is Some, without consuming it.
Option::is_none fn
export fn Option::is_none<T>(ref<Option<T>, shared> o) : boolWhether o is None, without consuming it.
Result enum
export enum Result<T, E>The outcome of an operation that can fail: Ok(T) holds the value, Err(E) the error.
? on a Result returns an Err from the enclosing function. In std after import std;, unqualified, as are its variants.
Result::ok fn
export fn Result::ok<T, E>(Result<T, E> r) : Option<T>The value in r as an Option: Some of it, or None when r is Err.
The error, if any, is destroyed at the call's end.
Err becomes None and an Ok becomes SomerunsResult<i32, u8> bad = Err(4);
assert(Result::unwrap_or(bad, 0) == 0);
Result<i32, u8> good = Ok(9);
Option<i32> o = Result::ok(good);
assert(Option::is_some(&o) && Option::unwrap(o) == 9);Result::unwrap_or fn
export fn Result::unwrap_or<T, E>(Result<T, E> r, T d) : TThe value in r, or d when r is Err.
An unused d or error is destroyed at the call's end.
Result::unwrap fn
export fn Result::unwrap<T, E>(Result<T, E> r) : TThe value in r.
Faults (unwrap_failed) when r is Err, and the fault names the error: what %v prints of it (a number, bool, text, an enum's variant name, as "Result::unwrap found Err: NotFound"), else its type ("…: a ConfigError"); the error's payload is destroyed. Result::expect gives the fault a message of your own.
Result::expect fn
export fn Result::expect<T, E>(Result<T, E> r, str message) : TThe value in r, faulting with message when r is an error.
Faults (unwrap_failed, showing message and then the error as Result::unwrap names it) when r is Err; the error's payload is destroyed.
Result::is_ok fn
export fn Result::is_ok<T, E>(ref<Result<T, E>, shared> r) : boolWhether r is Ok, without consuming it.
Result::is_err fn
export fn Result::is_err<T, E>(ref<Result<T, E>, shared> r) : boolWhether r is Err, without consuming it.
Result::map_err built in fn
fn Result::map_err<T, E1, E2>(Result<T, E1> r, fn(E1) : E2 f) : Result<T, E2>Keeps an Ok as it is and maps an Err through f: match (r) { Ok(v) : Ok(v), Err(e) : Err(f(e)) }. It is the step that turns a library's error into a program's own before ? passes it on. r is consumed; f runs only for an Err.
AllocError struct
export struct AllocErrorThe error allocate returns when memory cannot be had; it carries nothing.
swap fn
export fn swap<T>(ref<T, exclusive> a, ref<T, exclusive> b)Exchanges the values behind a and b.
A program cannot move a value out of a place it reaches through a reference, so it cannot exchange two fields of a borrowed struct itself; this does. Nothing is copied or destroyed: a resource is now owned by the place it is in. Each place is written as *a = v would write it: a live reference that conflicts with either one, such as a shared reborrow of *a, makes the exchange fault. For two elements of one Vec or slice, use Vec::swap or slice_swap, which check the bounds and allow i == j.
replace fn
export fn replace<T>(ref<T, exclusive> r, T v) : TPuts v in *r and returns what was there.
swap with a fresh value. overwrite destroys the old value instead of returning it.
replace hands back the old value; swap exchanges two placesrunsi32 a = 1;
i32 old = replace(&mut a, 2);
assert(old == 1 && a == 2);
i32 b = 3;
swap(&mut a, &mut b);
assert(a == 3 && b == 2);overwrite fn
export fn overwrite<T>(ref<T, exclusive> r, T v)Puts v in *r and destroys what was there, at the call.
The way to assign over a place that holds a resource, which plain assignment refuses.
assert built in fn
fn assert(bool c), fn assert(bool c, str f, a1, …, an)Checks c and, if it is false, faults with diag.assert-failed, reporting the formatted message if one is given (spec/18 §1a, rule.fail.assert, D-0065). The message's arguments are evaluated only when the assertion fails. An assertion is part of the program's meaning: there is no build in which it is left out, and --check sees its format as it sees printf's. The fault unwinds like any other, so destructors run and a supervised task reports it to its parent.
std::collections impl/std/collections.cb
Vec struct
export resource struct Vec<T>A growable array of T, owning its elements.
v[i] reads or writes element i (index_out_of_bounds past the end), &v[lo..hi] is a slice of it, and foreach visits it by value, &v or &mut v. A reference to an element is stale after a push that reallocates. Dropping a Vec destroys its elements, first to last, then frees its buffer.
Vec::new fn
export fn Vec::new<T>() : Vec<T>A new, empty Vec; nothing is allocated until it first grows.
Vec::len fn
export fn Vec::len<T>(ref<Vec<T>, shared> v) : usizeThe number of elements in v.
Vec::push fn
export fn Vec::push<T>(ref<Vec<T>, exclusive> v, T x)Appends x to the end of v.
Amortised constant time: when the buffer is full it is reallocated at twice its capacity, and references to elements held across that are stale at their next use. Faults (alloc_failure) when memory runs out.
Vec::pop fn
export fn Vec::pop<T>(ref<Vec<T>, exclusive> v) : Option<T>Removes the last element of v and returns it; None when v is empty.
Vec::index_shared fn
export fn Vec::index_shared<T>(ref<Vec<T>, shared> v, usize i) : ref<T, shared>The element at index i of v, as a shared reference; what v[i] reads, so programs write v[i].
Faults (index_out_of_bounds) when i >= len.
Vec::index_exclusive fn
export fn Vec::index_exclusive<T>(ref<Vec<T>, exclusive> v, usize i) : ref<T, exclusive>The element at index i of v, as an exclusive reference; what v[i] is when it is written, so programs write v[i].
Faults (index_out_of_bounds) when i >= len. A live slice of v holding i conflicts with it.
Vec::reserve fn
export fn Vec::reserve<T>(ref<Vec<T>, exclusive> v, usize n)Makes room for n more elements: afterwards the capacity is at least len + n.
Grows at most once, to the larger of len + n and twice the capacity, so small reserves in a loop stay amortised; never shrinks and never changes the length or the elements. It changes only how fast a program runs. len + n overflowing is diag.arith-overflow, before anything is allocated.
Vec::drop fn
export fn Vec::drop<T>(ref<Vec<T>, exclusive> self)Destroys every element of self, first to last, then frees the buffer; the destructor run when a Vec goes out of scope, not called by programs.
Vec::sort_by fn
export fn Vec::sort_by<T>(ref<Vec<T>, exclusive> v, fn(ref<T, shared>, ref<T, shared>) : bool less)Sorts v by less, which is true when its first argument goes before its second.
Stable: equal elements (neither before the other) keep their order. Each element moves once. less must be a strict weak order (never less(a, a), transitive); with one that is not, the elements end as a permutation of what they were, in an unspecified order. For a key type Vec::sort needs no less.
less calls equal keep their orderrunsVec<i32> v = Vec::new();
Vec::push(&mut v, 13);
Vec::push(&mut v, 21);
Vec::push(&mut v, 12);
Vec::push(&mut v, 25);
Vec::sort_by(&mut v, [](ref<i32, shared> a, ref<i32, shared> b) : bool { *a / 10 < *b / 10 });
assert(v[0] == 13 && v[1] == 12 && v[2] == 21 && v[3] == 25);Vec::sort fn
export fn Vec::sort<T>(ref<Vec<T>, exclusive> v)Sorts v in its elements' own order, keeping equal elements in their order.
T must be a key type: integers by value, false before true, str and String by their bytes (a prefix first), a struct field by field, an enum by the order its variants are declared in, then by payload. f32 and f64 sort too ([Sort-Float]): by value, -0.0 and 0.0 as equal, every NaN after every other value. Any other T is rejected at compile time; use Vec::sort_by for those.
Vec::binary_search_by fn
export fn Vec::binary_search_by<T>(ref<Vec<T>, shared> v, ref<T, shared> key, fn(ref<T, shared>, ref<T, shared>) : bool less) : Result<usize, usize>Searches v, sorted by less, for key.
Returns Ok(i) with i the first position whose element is equal to key (neither goes before the other), or Err(i) with i the position where key would be inserted to keep v sorted. v must be sorted by the same less, or the result is unspecified.
Vec::binary_search fn
export fn Vec::binary_search<T>(ref<Vec<T>, shared> v, probe<T> key) : Result<usize, usize>Searches v, sorted in its elements' own order, for key.
T a key type or a float, as for Vec::sort. Ok(i) for the first position holding an element equal to key, otherwise Err(i), the position where key would go.
Ok gives the first equal element, Err the place a missing key would gorunsVec<i32> v = Vec::new();
Vec::push(&mut v, 10);
Vec::push(&mut v, 20);
Vec::push(&mut v, 20);
Vec::push(&mut v, 30);
i32 present = 20;
i32 absent = 25;
assert(Result::unwrap_or(Vec::binary_search(&v, present), 99) == 1);
match (Vec::binary_search(&v, absent))
{
Ok(_) : assert(false),
Err(i) : assert(i == 3),
}Vec::clear fn
export fn Vec::clear<T>(ref<Vec<T>, exclusive> v)Removes every element of v, destroying them first to last; the buffer is kept for reuse.
Vec::insert fn
export fn Vec::insert<T>(ref<Vec<T>, exclusive> v, usize i, T x)Inserts x at index i, moving the elements from i on up by one.
i may equal len, which appends. Faults (index_out_of_bounds) when i > len. Linear in the number of elements after i; no element is copied.
len appendsrunsVec<i32> v = Vec::new();
Vec::push(&mut v, 1);
Vec::push(&mut v, 3);
Vec::insert(&mut v, 1, 2);
Vec::insert(&mut v, 3, 4);
assert(Vec::len(&v) == 4);
assert(v[0] == 1 && v[1] == 2 && v[2] == 3 && v[3] == 4);Vec::remove fn
export fn Vec::remove<T>(ref<Vec<T>, exclusive> v, usize i) : TRemoves the element at index i and returns it, moving the elements after it down by one.
Keeps the order and takes time linear in the elements after i; Vec::swap_remove takes constant time but does not keep the order. Faults (index_out_of_bounds) when i >= len.
Vec::swap_remove fn
export fn Vec::swap_remove<T>(ref<Vec<T>, exclusive> v, usize i) : TRemoves the element at index i and returns it, moving the last element into its place.
Constant time, but the order is not kept; Vec::remove keeps it. Faults (index_out_of_bounds) when i >= len.
remove keeps the order; swap_remove moves the last element into the gaprunsVec<i32> a = Vec::new();
Vec::push(&mut a, 1);
Vec::push(&mut a, 2);
Vec::push(&mut a, 3);
Vec::push(&mut a, 4);
Vec<i32> b = Vec::clone(&a);
assert(Vec::remove(&mut a, 0) == 1);
assert(a[0] == 2 && a[1] == 3 && a[2] == 4);
assert(Vec::swap_remove(&mut b, 0) == 1);
assert(b[0] == 4 && b[1] == 2 && b[2] == 3);Vec::clone fn
export fn Vec::clone<T: clone>(ref<Vec<T>, shared> v) : Vec<T>A new Vec holding a copy of each element of v, in order.
T must be clone (owning nothing); for other element types use Vec::clone_by.
Vec::from_slice fn
export fn Vec::from_slice<T: clone>(slice<T, shared> s) : Vec<T>A new Vec holding a copy of each element of s, in order.
T must be clone. The buffer is allocated once, at the slice's length.
Vec::truncate fn
export fn Vec::truncate<T>(ref<Vec<T>, exclusive> v, usize n)Keeps the first n elements of v and destroys the rest, last first.
n at or beyond the length leaves v unchanged.
Vec unchangedrunsVec<i32> v = Vec::filled(3, 7);
Vec::truncate(&mut v, 10);
assert(Vec::len(&v) == 3);
Vec::truncate(&mut v, 1);
assert(Vec::len(&v) == 1);Vec::clone_by fn
export fn Vec::clone_by<T>(ref<Vec<T>, shared> v, fn(ref<T, shared>) : T copy) : Vec<T>A new Vec holding copy(&x) for each element x of v, in order.
For element types that are not clone; copy makes each new element.
Vec::filled fn
export fn Vec::filled<T: clone>(usize n, T x) : Vec<T>A new Vec of n copies of x.
T must be clone; Vec::from_fn builds elements that are not.
Vec::from_raw fn
export fn Vec::from_raw<T: plain>(rawptr<T> p, usize n) : Vec<T>n elements of plain data copied from C memory into a Vec: a buffer a C caller owns, taken as a value the checks then cover (D-0257). Called inside unsafe { } ([Trusted-Call]): the caller vouches that the n elements at p are readable and stay put for the call.
Vec::from_c_bytes fn
export fn Vec::from_c_bytes(rawptr<u8> p) : Vec<u8>A copy of the bytes C's text at p holds, up to and without its NUL.
Called only inside unsafe: p must point at readable bytes ending in a NUL, as a C function's char * result does. A null p faults (null_pointer); test with is_null first when C may return NULL. String::from_c also checks that the bytes are UTF-8.
Vec::from_fn fn
export fn Vec::from_fn<T>(usize n, fn(usize) : T f) : Vec<T>A new Vec of f(0), f(1), …, f(n - 1), called in that order.
Works for any T, including resources.
Vec from its indices, then keeping the even elementsrunsVec<i32> v = Vec::from_fn(6, [](usize i) : i32 { narrow<i32>(i) });
Vec::retain(&mut v, [](ref<i32, shared> x) : bool { *x % 2 == 0 });
assert(Vec::len(&v) == 3);
assert(v[0] == 0 && v[1] == 2 && v[2] == 4);Vec::append fn
export fn Vec::append<T>(ref<Vec<T>, exclusive> a, Vec<T> b)Moves every element of b onto the end of a, in order; b is consumed.
Vec::extend_from fn
export fn Vec::extend_from<T: clone>(ref<Vec<T>, exclusive> a, slice<T, shared> s)Appends a copy of each element of s to the end of a, in order.
T must be clone. A slice of a itself is rejected (diag.aliasing-conflict).
Vec::position fn
export fn Vec::position<T>(ref<Vec<T>, shared> v, fn(ref<T, shared>) : bool p) : Option<usize>The index of the first element for which p returns true; None when there is none.
p is called in index order and not past the first hit. Vec::index_of looks for an equal element.
position takes a predicate, index_of a value; both find the first matchrunsVec<i32> v = Vec::new();
Vec::push(&mut v, 4);
Vec::push(&mut v, 9);
Vec::push(&mut v, 6);
assert(Option::unwrap(Vec::position(&v, [](ref<i32, shared> x) : bool { *x > 5 })) == 1);
i32 six = 6;
assert(Option::unwrap(Vec::index_of(&v, six)) == 2);
assert(Option::is_none(&Vec::position(&v, [](ref<i32, shared> x) : bool { *x > 9 })));Vec::any fn
export fn Vec::any<T>(ref<Vec<T>, shared> v, fn(ref<T, shared>) : bool p) : boolWhether p returns true for some element; false for an empty Vec.
p is called in index order and not past the first element for which it returns true (D-0325).
Vec::all fn
export fn Vec::all<T>(ref<Vec<T>, shared> v, fn(ref<T, shared>) : bool p) : boolWhether p returns true for every element; true for an empty Vec.
p is called in index order and not past the first element for which it returns false (D-0325).
Vec::count fn
export fn Vec::count<T>(ref<Vec<T>, shared> v, fn(ref<T, shared>) : bool p) : usizeThe number of elements for which p returns true.
p is called once for each element, in index order (D-0325). Vec::len is the number of all of them.
any, all and count ask the same predicate three questionsrunsVec<i32> v = Vec::new();
Vec::push(&mut v, 4);
Vec::push(&mut v, 9);
Vec::push(&mut v, 6);
assert(Vec::any(&v, [](ref<i32, shared> x) : bool { *x > 5 }));
assert(!Vec::all(&v, [](ref<i32, shared> x) : bool { *x > 5 }));
assert(Vec::count(&v, [](ref<i32, shared> x) : bool { *x > 5 }) == 2);
Vec<i32> none = Vec::new();
assert(!Vec::any(&none, [](ref<i32, shared> x) : bool { *x > 5 }));
assert(Vec::all(&none, [](ref<i32, shared> x) : bool { *x > 5 }));
assert(Vec::count(&none, [](ref<i32, shared> x) : bool { *x > 5 }) == 0);Vec::index_of fn
export fn Vec::index_of<T: eq>(ref<Vec<T>, shared> v, probe<T> x) : Option<usize>The index of the first element equal to what x probes; None when there is none.
x is the element's probe (D-0312): a view for a Vec<String> (a literal, a str, a view or &s), the element itself for a number, bool or str, a reference for any other element type.
Vec::contains fn
export fn Vec::contains<T: eq>(ref<Vec<T>, shared> v, probe<T> x) : boolWhether v has an element equal to what x probes (as for Vec::index_of).
Vec::contains_ref fn
export fn Vec::contains_ref<T: eq>(ref<Vec<T>, shared> v, ref<T, shared> x) : boolWhether v has an element equal to *x, given a reference to an element rather than its probe (as HashMap::contains_ref, for generic code: fn unique<T: eq>(…)).
Vec::eq fn
export fn Vec::eq<T: eq>(ref<Vec<T>, shared> a, ref<Vec<T>, shared> b) : boolWhether a and b have the same length and equal elements in the same order.
Vec<u8> a = Vec::from_slice(&[1: u8, 2, 3][0..3]);
Vec<u8> b = Vec::from_slice(&[1: u8, 2, 3][0..3]);
Vec<u8> c = Vec::from_slice(&[1: u8, 3, 2][0..3]);
Vec<u8> d = Vec::from_slice(&[1: u8, 2][0..2]);
assert(Vec::eq(&a, &b));
assert(!Vec::eq(&a, &c));
assert(!Vec::eq(&a, &d));Vec::reverse fn
export fn Vec::reverse<T>(ref<Vec<T>, exclusive> v)Reverses the order of the elements of v in place; nothing is copied or destroyed.
Vec::retain fn
export fn Vec::retain<T>(ref<Vec<T>, exclusive> v, fn(ref<T, shared>) : bool keep)Keeps the elements for which keep returns true, in their order, and destroys the rest.
keep is called once per element, in index order, before any element is destroyed. The kept elements are moved down by Vec::swap, not copied, which leaves the removed ones at the end in an order of the swaps' making, not their original one; they are then destroyed as Vec::truncate destroys, from the last place. A program whose destructors must run in a set order removes the elements itself.
Vec::dedup fn
export fn Vec::dedup<T: eq>(ref<Vec<T>, exclusive> v)Removes every element equal to the one kept before it, keeping the first of each run.
Only adjacent duplicates are removed, so a sorted Vec is left with one of each value. The removed elements are destroyed as Vec::retain destroys its removed ones, in an order of their own.
Vec<i32> v = Vec::new();
Vec::push(&mut v, 1);
Vec::push(&mut v, 1);
Vec::push(&mut v, 2);
Vec::push(&mut v, 1);
Vec::dedup(&mut v);
assert(Vec::len(&v) == 3);
assert(v[0] == 1 && v[1] == 2 && v[2] == 1);Vec::swap fn
export fn Vec::swap<T>(ref<Vec<T>, exclusive> v, usize i, usize j)Exchanges elements i and j of v; nothing happens when i == j.
Use it rather than swap(&mut v[i], &mut v[j]), which is two exclusive borrows of one place when i == j. Faults (index_out_of_bounds) when either index is >= len.
Vec::push_le fn
export fn Vec::push_le<T: integer>(ref<Vec<u8>, exclusive> out, T x)Appends the sizeof<T>() bytes of x to out, least significant byte first (little-endian).
A signed x is written as its two's-complement image. read_le reads it back.
Vec::push_be fn
export fn Vec::push_be<T: integer>(ref<Vec<u8>, exclusive> out, T x)Appends the sizeof<T>() bytes of x to out, most significant byte first (big-endian, network order).
A signed x is written as its two's-complement image. read_be reads it back.
HashMap struct
export struct HashMap<K, V>A hash table mapping keys of type K to values of type V, kept in insertion order.
K must be a key type: an integer type, bool, str or String, or a struct or enum built only of key types (not f32/f64, not references). Entry i (key_at, value_at) is in insertion order, and foreach (k, v in m) visits the entries in that order; the order depends only on the calls, never on hash values. Replacing a value keeps its entry's place. Lookups take the key's probe (probe<K>, D-0312), so they copy nothing: for a HashMap<String, V> a view, so a literal, a str, a view or &s looks a key up without making a String; a number, bool or str key is passed itself (HashMap::get(&m, 7)); a struct or enum key by reference, &k. The map owns its keys and values and destroys them with itself.
HashMap::new fn
export fn HashMap::new<K, V>() : HashMap<K, V>A new, empty map.
HashMap::clone fn
export fn HashMap::clone<K: clone, V: clone>(ref<HashMap<K, V>, shared> m) : HashMap<K, V>A new map holding copies of the keys and values of m, in the same insertion order.
HashMap::clear fn
export fn HashMap::clear<K, V>(ref<HashMap<K, V>, exclusive> m)Removes every entry of m, destroying them first to last, each entry's key and then its value.
HashMap::len fn
export fn HashMap::len<K, V>(ref<HashMap<K, V>, shared> m) : usizeThe number of entries in m.
HashMap::key_at fn
export fn HashMap::key_at<K, V>(ref<HashMap<K, V>, shared> m, usize i) : ref<K, shared>The key of entry i, in insertion order.
Faults (index_out_of_bounds) when i >= len. Constant time, but logarithmic in the size of the map while places that HashMap::remove emptied are not yet closed up.
HashMap::value_at fn
export fn HashMap::value_at<K, V>(ref<HashMap<K, V>, shared> m, usize i) : ref<V, shared>The value of entry i, in insertion order.
Faults (index_out_of_bounds) when i >= len. Takes time as key_at does.
HashMap::insert fn
export fn HashMap::insert<K, V>(ref<HashMap<K, V>, exclusive> m, K k, V v) : Option<V>Adds key k with value v; returns the old value if k was already present, otherwise None.
A present key keeps its entry's place and its stored key; the k passed in is destroyed.
HashMap<i32, i32> m = HashMap::new();
HashMap::insert(&mut m, 5, 50);
HashMap::insert(&mut m, 7, 70);
assert(Option::unwrap(HashMap::insert(&mut m, 5, 55)) == 50);
assert(HashMap::len(&m) == 2);
assert(*HashMap::key_at(&m, 0) == 5 && *HashMap::value_at(&m, 0) == 55);HashMap::entry fn
export fn HashMap::entry<K, V>(ref<HashMap<K, V>, exclusive> m, probe<K> k, V fresh) : ref<V, exclusive>The value for the key k probes, as an exclusive reference, adding a copy of the key with the value fresh first if it is absent.
k is the key's probe, as for get: a view for a String key (a literal, a str, a view or &s), the key itself for a number, bool or str key, a reference for a struct or enum key. Only an absent key is copied, so counting the words of a text makes one String per distinct word. If the key is present, fresh is not needed and is destroyed. The usual way to count or to collect into a map: *HashMap::entry(&mut m, k, 0) += 1;.
entryrunsHashMap<i32, i32> counts = HashMap::new();
Vec<i32> words = Vec::new();
Vec::push(&mut words, 3);
Vec::push(&mut words, 1);
Vec::push(&mut words, 3);
foreach (w in &words)
{
*HashMap::entry(&mut counts, *w, 0) += 1;
}
i32 three = 3;
assert(*Option::unwrap(HashMap::get(&counts, three)) == 2);HashMap::get fn
export fn HashMap::get<K, V>(ref<HashMap<K, V>, shared> m, probe<K> k) : Option<ref<V, shared>> from mThe value for k, as a shared reference; None when k is absent.
HashMap::get_mut fn
export fn HashMap::get_mut<K, V>(ref<HashMap<K, V>, exclusive> m, probe<K> k) : Option<ref<V, exclusive>> from mThe value for k, as an exclusive reference; None when k is absent.
HashMap::contains fn
export fn HashMap::contains<K, V>(ref<HashMap<K, V>, shared> m, probe<K> k) : boolWhether m has an entry for k.
HashMap::contains_ref fn
export fn HashMap::contains_ref<K, V>(ref<HashMap<K, V>, shared> m, ref<K, shared> k) : boolWhether m has an entry for the key *k, given a reference to a key rather than its probe.
For generic code that holds its keys (fn f<K>(…, ref<K, shared> k)): a probe<K> is a view for a String key and the value for a number, so no one spelling of a lookup by probe fits every K (D-0336).
HashMap::get_ref fn
export fn HashMap::get_ref<K, V>(ref<HashMap<K, V>, shared> m, ref<K, shared> k) : Option<ref<V, shared>> from mThe value for the key *k, as a shared reference; None when it is absent. As HashMap::get, given a reference to a key (HashMap::contains_ref).
String key alikerunsHashMap<String, i32> m = HashMap::new();
HashMap::insert(&mut m, "a", 1);
String a = "a";
String b = "b";
assert(HashMap::contains_ref(&m, &a));
assert(!HashMap::contains_ref(&m, &b));
assert(*Option::unwrap(HashMap::get_ref(&m, &a)) == 1);
HashMap<u32, i32> n = HashMap::new();
HashMap::insert(&mut n, 7, 2);
u32 seven = 7;
assert(HashMap::contains_ref(&n, &seven));
u32 eight = 8;
assert(Option::is_none(&HashMap::get_ref(&n, &eight)));HashMap::entry_owned fn
export fn HashMap::entry_owned<K, V>(ref<HashMap<K, V>, exclusive> m, K k, V fresh) : ref<V, exclusive>As HashMap::entry, given the key itself rather than its probe: for generic code that holds its keys as K (HashMap::contains_ref), where a probe<K> has no one spelling for every key type. k is kept when it is absent, and k and fresh are destroyed when it is present.
HashMap::get_mut_ref fn
export fn HashMap::get_mut_ref<K, V>(ref<HashMap<K, V>, exclusive> m, ref<K, shared> k) : Option<ref<V, exclusive>> from mThe value for the key *k, as an exclusive reference; None when it is absent. As HashMap::get_mut, given a reference to a key (HashMap::contains_ref).
HashMap::remove_ref fn
export fn HashMap::remove_ref<K, V>(ref<HashMap<K, V>, exclusive> m, ref<K, shared> k) : Option<V>Removes the key *k and returns its value; None when it is absent. As HashMap::remove, given a reference to a key (HashMap::contains_ref).
entry_owned, get_mut_ref and remove_ref take a key held as K, for an integer
key and a String key alikerunsHashMap<String, usize> m = HashMap::new();
*HashMap::entry_owned(&mut m, String::copy("a"), 0) += 1;
*HashMap::entry_owned(&mut m, String::copy("a"), 0) += 1;
assert(*Option::unwrap(HashMap::get(&m, "a")) == 2);
String a = "a";
*Option::unwrap(HashMap::get_mut_ref(&mut m, &a)) += 1;
assert(Option::unwrap(HashMap::remove_ref(&mut m, &a)) == 3);
assert(HashMap::len(&m) == 0);
HashMap<u32, usize> n = HashMap::new();
u32 seven = 7;
*HashMap::entry_owned(&mut n, seven, 0) += 5;
assert(Option::is_some(&HashMap::get_mut_ref(&mut n, &seven)));
assert(Option::unwrap(HashMap::remove_ref(&mut n, &seven)) == 5);
assert(Option::is_none(&HashMap::remove_ref(&mut n, &seven)));HashMap::swap_remove fn
export fn HashMap::swap_remove<K, V>(ref<HashMap<K, V>, exclusive> m, probe<K> k) : Option<V>Removes k and returns its value, in constant time; None when k is absent.
The last entry moves into the removed one's place, so the insertion order is not kept; HashMap::remove keeps it. The removed key is destroyed.
HashMap::remove fn
export fn HashMap::remove<K, V>(ref<HashMap<K, V>, exclusive> m, probe<K> k) : Option<V>Removes k and returns its value; None when k is absent.
The other entries keep their order. The later entries are not moved at once: the emptied place is closed up with others after many removals, so a removal takes amortised logarithmic time in the size of the map, in any order. HashMap::swap_remove takes constant time but does not keep the order. The removed key is destroyed.
remove keeps the insertion order; swap_remove moves the last entryrunsHashMap<i32, bool> a = HashMap::new();
HashMap::insert(&mut a, 1, true);
HashMap::insert(&mut a, 2, true);
HashMap::insert(&mut a, 3, true);
HashMap<i32, bool> b = HashMap::clone(&a);
i32 one = 1;
HashMap::remove(&mut a, one);
assert(*HashMap::key_at(&a, 0) == 2 && *HashMap::key_at(&a, 1) == 3);
HashMap::swap_remove(&mut b, one);
assert(*HashMap::key_at(&b, 0) == 3 && *HashMap::key_at(&b, 1) == 2);key_at, foreach, a copy,
swap_remove and more insertionsrunsHashMap<i32, i32> m = HashMap::new();
i32 i = 0;
while (i < 10)
{
HashMap::insert(&mut m, i, i * 10);
i += 1;
}
i32 two = 2;
i32 zero = 0;
i32 five = 5;
i32 nine = 9;
assert(Option::unwrap(HashMap::remove(&mut m, two)) == 20);
assert(Option::unwrap(HashMap::remove(&mut m, zero)) == 0);
assert(Option::unwrap(HashMap::remove(&mut m, five)) == 50);
assert(HashMap::len(&m) == 7);
assert(*HashMap::key_at(&m, 0) == 1 && *HashMap::key_at(&m, 1) == 3 && *HashMap::value_at(&m, 3) == 60);
i32 sum = 0;
i32 pos = 0;
foreach (k, v in &m)
{
assert(*k == *HashMap::key_at(&m, narrow<usize>(pos)) && *v == *k * 10);
sum += *k;
pos += 1;
}
assert(sum == 1 + 3 + 4 + 6 + 7 + 8 + 9);
HashMap<i32, i32> c = HashMap::clone(&m);
assert(HashMap::len(&c) == 7 && *HashMap::key_at(&c, 2) == 4 && *Option::unwrap(HashMap::get(&c, nine)) == 90);
i32 one = 1;
HashMap::swap_remove(&mut m, one);
assert(*HashMap::key_at(&m, 0) == 9 && *HashMap::key_at(&m, 5) == 8 && HashMap::len(&m) == 6);
HashMap::insert(&mut m, 2, 22);
assert(*HashMap::key_at(&m, 6) == 2 && *Option::unwrap(HashMap::get(&m, two)) == 22);
i = 0;
while (i < 100)
{
HashMap::insert(&mut m, 100 + i, i);
i32 gone = 100 + i / 2;
HashMap::remove(&mut m, gone);
i += 1;
}
assert(HashMap::len(&m) == 57 && *HashMap::key_at(&m, 7) == 150 && *HashMap::key_at(&m, 56) == 199);HashMap::get_str fn
export fn HashMap::get_strRemoved (D-0303): write HashMap::get(…): a String key's probe is a view, so a literal, a str or a view looks it up (D-0312)
HashMap::get_mut_str fn
export fn HashMap::get_mut_strRemoved (D-0303): write HashMap::get_mut(…): a String key's probe is a view, so a literal, a str or a view looks it up (D-0312)
HashMap::contains_str fn
export fn HashMap::contains_strRemoved (D-0303): write HashMap::contains(…): a String key's probe is a view, so a literal, a str or a view looks it up (D-0312)
HashMap::remove_str fn
export fn HashMap::remove_strRemoved (D-0303): write HashMap::remove(…): a String key's probe is a view, so a literal, a str or a view looks it up (D-0312)
HashSet struct
export struct HashSet<K>A set of keys of type K, kept in insertion order.
K is a key type, as for HashMap. Key i (key_at) is in insertion order, and foreach (k in s) visits the keys in that order. The set owns its keys and destroys them with itself.
HashSet::new fn
export fn HashSet::new<K>() : HashSet<K>A new, empty set.
HashSet::len fn
export fn HashSet::len<K>(ref<HashSet<K>, shared> s) : usizeThe number of keys in s.
HashSet::insert fn
export fn HashSet::insert<K>(ref<HashSet<K>, exclusive> s, K k) : boolAdds k to s; returns true if it was not already present.
A key already present keeps its place, and the k passed in is destroyed.
HashSet<i32> s = HashSet::new();
assert(HashSet::insert(&mut s, 4));
assert(!HashSet::insert(&mut s, 4));
assert(HashSet::len(&s) == 1);HashSet::clone fn
export fn HashSet::clone<K: clone>(ref<HashSet<K>, shared> s) : HashSet<K>A new set holding copies of the keys of s, in the same order.
HashSet::union fn
export fn HashSet::union<K: clone>(ref<HashSet<K>, shared> a, ref<HashSet<K>, shared> b) : HashSet<K>A new set of the keys in a or b: a's keys in a's order, then b's keys not in a, in b's order.
The keys are copied with clone; a and b are left as they are.
HashSet<i32> a = HashSet::new();
HashSet<i32> b = HashSet::new();
HashSet::insert(&mut a, 3);
HashSet::insert(&mut a, 1);
HashSet::insert(&mut b, 2);
HashSet::insert(&mut b, 3);
HashSet<i32> u = HashSet::union(&a, &b);
assert(HashSet::len(&u) == 3);
assert(*HashSet::key_at(&u, 0) == 3 && *HashSet::key_at(&u, 1) == 1 && *HashSet::key_at(&u, 2) == 2);HashSet::intersection fn
export fn HashSet::intersection<K: clone>(ref<HashSet<K>, shared> a, ref<HashSet<K>, shared> b) : HashSet<K>A new set of the keys of a that are also in b, in a's order.
The keys are copied with clone; a and b are left as they are.
HashSet::difference fn
export fn HashSet::difference<K: clone>(ref<HashSet<K>, shared> a, ref<HashSet<K>, shared> b) : HashSet<K>A new set of the keys of a that are not in b, in a's order.
The keys are copied with clone; a and b are left as they are.
HashSet::contains fn
export fn HashSet::contains<K>(ref<HashSet<K>, shared> s, probe<K> k) : boolWhether s holds k.
HashSet::contains_ref fn
export fn HashSet::contains_ref<K>(ref<HashSet<K>, shared> s, ref<K, shared> k) : boolWhether s holds the key *k, given a reference to a key rather than its probe (as HashMap::contains_ref, for generic code).
HashSet::remove_ref fn
export fn HashSet::remove_ref<K>(ref<HashSet<K>, exclusive> s, ref<K, shared> k) : boolRemoves the key *k from s, keeping the order of the other keys; returns true if it was present. As HashSet::remove, given a reference to a key (HashSet::contains_ref, for generic code).
HashSet::swap_remove fn
export fn HashSet::swap_remove<K>(ref<HashSet<K>, exclusive> s, probe<K> k) : boolRemoves k from s in constant time; returns true if it was present.
As HashMap::swap_remove, the last key takes k's place, so the order is not kept; HashSet::remove keeps it.
HashSet::remove fn
export fn HashSet::remove<K>(ref<HashSet<K>, exclusive> s, probe<K> k) : boolRemoves k from s, keeping the order of the other keys; returns true if it was present.
Amortised logarithmic time, as HashMap::remove; HashSet::swap_remove is constant time.
HashSet::key_at fn
export fn HashSet::key_at<K>(ref<HashSet<K>, shared> s, usize i) : ref<K, shared>Key i of s, in insertion order.
Faults (index_out_of_bounds) when i >= len.
HashSet::clear fn
export fn HashSet::clear<K>(ref<HashSet<K>, exclusive> s)Removes every key of s, destroying them, as HashMap::clear does.
HashSet::contains_str fn
export fn HashSet::contains_strRemoved (D-0303): write HashSet::contains(…): a String key's probe is a view, so a literal, a str or a view looks it up (D-0312)
HashSet::remove_str fn
export fn HashSet::remove_strRemoved (D-0303): write HashSet::remove(…): a String key's probe is a view, so a literal, a str or a view looks it up (D-0312)
Queue struct
export resource struct Queue<T>A double-ended queue: elements are added and taken at either end in amortised constant time.
The queue owns its elements; dropping it destroys them front to back. There is no positional access, no foreach, no clone and no reserve; a Vec serves those needs.
Queue::new fn
export fn Queue::new<T>() : Queue<T>A new, empty queue.
Queue::len fn
export fn Queue::len<T>(ref<Queue<T>, shared> q) : usizeThe number of elements in q.
Queue::push_back fn
export fn Queue::push_back<T>(ref<Queue<T>, exclusive> q, T x)Adds x at the back of q.
Queue::push_front fn
export fn Queue::push_front<T>(ref<Queue<T>, exclusive> q, T x)Adds x at the front of q.
Queue::pop_front fn
export fn Queue::pop_front<T>(ref<Queue<T>, exclusive> q) : Option<T>Removes the front element of q and returns it; None when q is empty.
Queue::pop_back fn
export fn Queue::pop_back<T>(ref<Queue<T>, exclusive> q) : Option<T>Removes the back element of q and returns it; None when q is empty.
Queue::front fn
export fn Queue::front<T>(ref<Queue<T>, shared> q) : Option<ref<T, shared>>The front element of q, as a shared reference; None when q is empty.
The reference borrows the queue, which cannot change while it is in use.
Queue::back fn
export fn Queue::back<T>(ref<Queue<T>, shared> q) : Option<ref<T, shared>>The back element of q, as a shared reference; None when q is empty.
The reference borrows the queue, which cannot change while it is in use.
Queue<i32> q = Queue::new();
Queue::push_back(&mut q, 2);
Queue::push_back(&mut q, 3);
Queue::push_front(&mut q, 1);
assert(*Option::unwrap(Queue::front(&q)) == 1);
assert(*Option::unwrap(Queue::back(&q)) == 3);
assert(Option::unwrap(Queue::pop_back(&mut q)) == 3);
assert(Option::unwrap(Queue::pop_front(&mut q)) == 1);
assert(Queue::len(&q) == 1);Queue::clear fn
export fn Queue::clear<T>(ref<Queue<T>, exclusive> q)Removes every element of q, destroying them front to back; the buffers are kept.
Queue::drop fn
export fn Queue::drop<T>(ref<Queue<T>, exclusive> self)Destroys the elements of self, front to back; the destructor run when a Queue goes out of scope, not called by programs.
PriorityQueue struct
export struct PriorityQueue<T>A priority queue: it gives its elements back least first, in an order fixed when it is made.
PriorityQueue::new uses the key types' own order, PriorityQueue::new_by the caller's less. Elements the order calls equal come out first in, first out. A binary heap: push and pop take time in proportion to the logarithm of the length. The queue owns its elements. There is no peek_mut (pop, change and push instead), no foreach, no clone and no reserve.
PriorityQueue::new fn
export fn PriorityQueue::new<T>() : PriorityQueue<T>A new, empty priority queue in the key types' own order, smallest first (as Vec::sort orders).
T must be a key type or a float (in Vec::sort's order, a NaN last); for any other T use PriorityQueue::new_by.
PriorityQueue::new_by fn
export fn PriorityQueue::new_by<T>(fn(ref<T, shared>, ref<T, shared>) : bool less) : PriorityQueue<T>A new, empty priority queue in the order less gives: the element no other goes before comes out first.
less is true when its first argument goes before its second and must be a strict weak order, as for Vec::sort_by. A largest-first queue passes a less that answers "greater".
auto larger_tens = [](ref<i32, shared> a, ref<i32, shared> b) : bool { *a / 10 > *b / 10 };
PriorityQueue<i32> q = PriorityQueue::new_by(larger_tens);
PriorityQueue::push(&mut q, 15);
PriorityQueue::push(&mut q, 31);
PriorityQueue::push(&mut q, 12);
PriorityQueue::push(&mut q, 38);
assert(Option::unwrap(PriorityQueue::pop(&mut q)) == 31);
assert(Option::unwrap(PriorityQueue::pop(&mut q)) == 38);
assert(Option::unwrap(PriorityQueue::pop(&mut q)) == 15);
assert(Option::unwrap(PriorityQueue::pop(&mut q)) == 12);PriorityQueue::len fn
export fn PriorityQueue::len<T>(ref<PriorityQueue<T>, shared> q) : usizeThe number of elements in q.
PriorityQueue::push fn
export fn PriorityQueue::push<T>(ref<PriorityQueue<T>, exclusive> q, T x)Adds x to q; logarithmic in the length.
PriorityQueue::pop fn
export fn PriorityQueue::pop<T>(ref<PriorityQueue<T>, exclusive> q) : Option<T>Removes the element that comes out first and returns it; None when q is empty.
Among elements the order calls equal, the one pushed first comes out first. Logarithmic in the length.
PriorityQueue::peek fn
export fn PriorityQueue::peek<T>(ref<PriorityQueue<T>, shared> q) : Option<ref<T, shared>>The element pop would return next, as a shared reference; None when q is empty.
The reference borrows the queue.
PriorityQueue<i32> q = PriorityQueue::new();
PriorityQueue::push(&mut q, 5);
PriorityQueue::push(&mut q, 1);
PriorityQueue::push(&mut q, 3);
assert(*Option::unwrap(PriorityQueue::peek(&q)) == 1);
assert(Option::unwrap(PriorityQueue::pop(&mut q)) == 1);
assert(Option::unwrap(PriorityQueue::pop(&mut q)) == 3);
assert(Option::unwrap(PriorityQueue::pop(&mut q)) == 5);
assert(Option::is_none(&PriorityQueue::pop(&mut q)));PriorityQueue::clear fn
export fn PriorityQueue::clear<T>(ref<PriorityQueue<T>, exclusive> q)Removes every element of q, destroying them in the order the heap holds them (not priority order).
slice_eq fn
export fn slice_eq<T: eq>(slice<T, shared> a, slice<T, shared> b) : boolWhether a and b have the same length and equal elements in the same order.
Elements are compared with == in index order, stopping at the first difference. Slices have no == of their own; a Vec is passed as &v[0..$], an array as &a[0..$].
Vec and an array compare equal when their elements dorunsVec<u8> v = Vec::new();
Vec::push(&mut v, 1);
Vec::push(&mut v, 2);
array<u8, 2> a = [1, 2];
assert(slice_eq(&v, &a));
assert(!slice_eq(&v[0..1], &a));read_le fn
export fn read_le<T: integer>(slice<u8, shared> s, usize at) : TThe T whose sizeof<T>() bytes start at s[at], least significant byte first (little-endian).
The type is written at the call: read_le<u32>(&buf[0..$], 4). A signed T is read as two's complement. Faults (index_out_of_bounds) when fewer than sizeof<T>() bytes remain from at.
Vec<u8> out = Vec::new();
Vec::push_be(&mut out, 0x0102: u16);
Vec::push_le(&mut out, -2: i16);
assert(out[0] == 0x01 && out[1] == 0x02 && out[2] == 0xfe && out[3] == 0xff);
assert(read_be<u16>(&out, 0) == 0x0102);
assert(read_le<i16>(&out, 2) == -2);read_be fn
export fn read_be<T: integer>(slice<u8, shared> s, usize at) : TThe T whose sizeof<T>() bytes start at s[at], most significant byte first (big-endian).
The type is written at the call: read_be<u16>(&buf[0..$], 0). A signed T is read as two's complement. Faults (index_out_of_bounds) when fewer than sizeof<T>() bytes remain from at.
slice_parts fn
export fn slice_parts<T>(slice<T, exclusive> s, usize parts) : Vec<slice<T, exclusive>>Splits s into parts disjoint exclusive slices of consecutive elements, in order, as nearly equal in length as they can be.
With n elements, each part has n / parts elements and the first n % parts parts one more; some are empty when parts > n. The result is empty when parts is 0. The parts are disjoint, so each can be given to a thread of its own (spawn(work, part)) and written there without a lock; the borrow of s ends when the last part ends.
array<i32, 5> a = [1, 2, 3, 4, 5];
Vec<slice<i32, exclusive>> parts = slice_parts(&mut a, 2);
assert(Vec::len(&parts) == 2);
assert(slice_len(parts[0]) == 3 && slice_len(parts[1]) == 2);slice_swap fn
export fn slice_swap<T>(slice<T, exclusive> s, usize i, usize j)Exchanges elements i and j of s; nothing happens when i == j.
Faults (index_out_of_bounds) when either index is >= slice_len(s).
std::text impl/std/text.cb
Utf8Error struct
export struct Utf8ErrorThe error of bytes that are not well-formed UTF-8.
offset is where the first ill-formed sequence starts (one that is malformed or cut short), so bytes[0..offset] is well-formed UTF-8, as Python's start and Rust's valid_up_to give it.
Utf8Error::text fn
export fn Utf8Error::text(ref<Utf8Error, shared> e) : strA short description of the error for messages: "not UTF-8".
ParseError enum
export enum ParseErrorWhy text did not parse as a number, or as hexadecimal, base64 or JSON.
Empty: the text is empty (for JSON, it holds no value).Invalid(k): bytekis the first that cannot continue the text;kis the length when the text stops too early.OutOfRange: the text is well-formed, but its value does not fit the type (for JSON, also nesting deeper than 512).
ParseError::text fn
export fn ParseError::text(ref<ParseError, shared> e) : strA short description of the error for messages: "empty", "invalid syntax" or "out of range".
The same for every parser that gives a ParseError (numbers, JSON, TOML, dates, addresses, hexadecimal, base64). ParseError::describe adds where the error is in the text.
ParseError::describe fn
export fn ParseError::describe(ref<ParseError, shared> e, StringView text) : StringThe error with its place in text, the text that was parsed, for a message to a person.
For Invalid(k): line L, column C: unexpected 'x', the character at byte k (a space or a control character by its code, U+0009), or line L, column C: the text ends too early when k is its length. Lines and columns count from 1, columns in characters. Empty and OutOfRange give ParseError::text. For a Toml::parse error, Toml::describe_error adds TOML's reason (a key defined twice).
ParseError e = Invalid(9);
assert(ParseError::describe(&e, "{\"a\": 1,\n}") == "line 2, column 1: unexpected '}'");
ParseError f = Invalid(3);
assert(ParseError::describe(&f, "tru") == "line 1, column 4: the text ends too early");String struct
export struct StringOwned, growable text, always well-formed UTF-8.
Lengths, positions and ranges count bytes. A literal where a String is expected is made into one (String s = "text";), and &s[lo .. hi] is a StringView of part of it. ==, !=, <, <=, > and >= compare the bytes; a String also compares equal or not with a str or a StringView. Dropping a String frees its bytes.
String::from_utf8 fn
export fn String::from_utf8(Vec<u8> bytes) : Result<String, Utf8Error>Makes a String of bytes when they are well-formed UTF-8, without copying them.
Err(e) when they are not, with e.offset the position of the first byte that does not fit; the bytes are then dropped.
Vec<u8> b = Vec::new();
Vec::push(&mut b, b'o');
Vec::push(&mut b, b'k');
Vec::push(&mut b, 0xff: u8);
match (String::from_utf8(b))
{
Ok(_) : assert(false),
Err(e) : assert(e.offset == 2),
}String::from_c fn
export fn String::from_c(rawptr<u8> p) : Result<String, Utf8Error>A copy of C's text at p, up to and without its NUL, when it is UTF-8.
Called only inside unsafe: p must point at readable bytes ending in a NUL, as a C function's char * result does. A null p faults (null_pointer); test with is_null first when C may return NULL. Err(e) when the bytes are not UTF-8; Vec::from_c_bytes takes them as they are.
String::into_bytes fn
export fn String::into_bytes(String s) : Vec<u8>The bytes of s as a Vec<u8>, without copying them.
String::new fn
export fn String::new() : StringA new, empty String.
String::reserve fn
export fn String::reserve(ref<String, exclusive> s, usize n)Reserves room for n more bytes in s; the text is unchanged.
String::clone fn
export fn String::clone(ref<String, shared> s) : StringA new String with the same text as s.
String::push_ascii fn
export fn String::push_ascii(ref<String, exclusive> s, u8 b)Appends the ASCII byte b to s.
Faults (not_ascii) when b >= 128, since such a byte alone is not UTF-8. String::push_code_point appends any character; bytes of any kind are built in a Vec<u8> and checked by String::from_utf8.
String::clear fn
export fn String::clear(ref<String, exclusive> s)Empties s, keeping its buffer for reuse.
String::truncate fn
export fn String::truncate(ref<String, exclusive> s, usize n)Shortens s to its first n bytes; n at or beyond the length leaves s as it is.
Faults (not_char_boundary) when byte n is inside a character. To cut any text to at most n bytes, first take one off n while byte n is a continuation byte ((b & 0xC0) == 0x80).
String s = "caf\u{e9}";
String::truncate(&mut s, 3);
assert(s == "caf");
String t = "short";
String::truncate(&mut t, 80);
assert(t == "short");String::join fn
export fn String::join(slice<String, shared> parts, StringView sep) : StringThe texts of the Strings in parts, in order, with sep between each two, in a new String.
No parts give an empty String. StringView::join joins a slice of views.
String::copy fn
export fn String::copy(StringView v) : StringA new String holding a copy of the text of v: a view, a str, a literal, or &s of a String.
String::clone(&s) copies a whole String the same way.
String s = "h\u{e9}!";
assert(StringView::len(&s) == 4);
assert(StringView::char_count(&s) == 3);
Vec<StringView> cs = StringView::chars(&s);
assert(StringView::len(cs[1]) == 2);
assert(StringView::code_point(cs[1]) == Some(0xe9: u32));String::push_code_point fn
export fn String::push_code_point(ref<String, exclusive> s, u32 cp)Appends the character with code point cp to s, as one to four UTF-8 bytes.
A value that is no character (a surrogate, 0xD800 to 0xDFFF, or above 0x10FFFF) appends U+FFFD, the replacement character, so s stays UTF-8.
String s = String::new();
String::push_code_point(&mut s, 0x41);
String::push_code_point(&mut s, 0xD800);
assert(s == "A\u{fffd}");String::append fn
export fn String::append<T>(ref<String, exclusive> s, T x)Appends x to s as text: the bytes printf("%v", x) would write.
x is a str, a StringView, a ref<String, shared>, an integer, f32, f64 or bool; another type is rejected at the call. A float is written in the shortest digits that read back as the same value (1.0, 0.1). String::appendf appends formatted text.
printf writes themrunsString s = "x = ";
String::append(&mut s, 1.0);
String::append(&mut s, ", n = ");
String::append(&mut s, 42: u8);
assert(s == "x = 1.0, n = 42");String::from_view fn
export fn String::from_viewRemoved (D-0303): write String::copy(…): a copy of a view's text (D-0312)
String::to_ascii_lower fn
export fn String::to_ascii_lowerRemoved (D-0303): write StringView::to_ascii_lower(&s): it takes the text's view (D-0312)
String::to_ascii_upper fn
export fn String::to_ascii_upperRemoved (D-0303): write StringView::to_ascii_upper(&s): it takes the text's view (D-0312)
String::from_str fn
export fn String::from_strRemoved (D-0303): a literal is a String where one is declared; a str value, a view or a part is copied by String::copy; a whole String by String::clone
String::as_view fn
export fn String::as_viewRemoved (D-0303): &s is a view where a StringView is declared (D-0302); &s[0..$] elsewhere
String::find fn
export fn String::findRemoved (D-0303): write StringView::find(&s, …): &s is a view where a StringView is declared (D-0302)
String::starts_with fn
export fn String::starts_withRemoved (D-0303): write StringView::starts_with(&s, …): &s is a view where a StringView is declared (D-0302)
String::ends_with fn
export fn String::ends_withRemoved (D-0303): write StringView::ends_with(&s, …): &s is a view where a StringView is declared (D-0302)
String::trim fn
export fn String::trimRemoved (D-0303): write StringView::trim(&s): &s is a view where a StringView is declared (D-0302)
String::trim_start fn
export fn String::trim_startRemoved (D-0303): write StringView::trim_start(&s): &s is a view where a StringView is declared (D-0302)
String::trim_end fn
export fn String::trim_endRemoved (D-0303): write StringView::trim_end(&s): &s is a view where a StringView is declared (D-0302)
String::split fn
export fn String::splitRemoved (D-0303): write StringView::split(&s, …): &s is a view where a StringView is declared (D-0302)
String::contains fn
export fn String::containsRemoved (D-0303): write StringView::contains(&s, …): &s is a view where a StringView is declared (D-0302)
String::replace fn
export fn String::replaceRemoved (D-0303): write StringView::replace(&s, …): &s is a view where a StringView is declared (D-0302)
String::strip_prefix fn
export fn String::strip_prefixRemoved (D-0303): write StringView::strip_prefix(&s, …): &s is a view where a StringView is declared (D-0302)
String::strip_suffix fn
export fn String::strip_suffixRemoved (D-0303): write StringView::strip_suffix(&s, …): &s is a view where a StringView is declared (D-0302)
String::lines fn
export fn String::linesRemoved (D-0303): write StringView::lines(&s): &s is a view where a StringView is declared (D-0302)
String::split_whitespace fn
export fn String::split_whitespaceRemoved (D-0303): write StringView::split_whitespace(&s): &s is a view where a StringView is declared (D-0302)
String::len fn
export fn String::lenRemoved (D-0303): write StringView::len(&s): &s is a view where a StringView is declared (D-0302, D-0308)
String::char_count fn
export fn String::char_countRemoved (D-0303): write StringView::char_count(&s): &s is a view where a StringView is declared (D-0302, D-0308)
String::chars fn
export fn String::charsRemoved (D-0303): write StringView::chars(&s): &s is a view where a StringView is declared (D-0302, D-0308)
String::code_point fn
export fn String::code_pointRemoved (D-0303): write StringView::code_point(&s): &s is a view where a StringView is declared (D-0302, D-0308)
String::parse fn
export fn String::parseRemoved (D-0303): write StringView::parse<T>(&s): &s is a view where a StringView is declared (D-0302, D-0308)
String::eq_str fn
export fn String::eq_strRemoved (D-0303): write a == t (D-0164, D-0308)
String::eq_view fn
export fn String::eq_viewRemoved (D-0303): write a == v (D-0164, D-0308)
String::view fn
export fn String::viewRemoved (D-0303): write &s[lo..hi] (D-0308)
String::appendf built in fn
fn String::appendf(ref<String, exclusive> s, str f, a1, …, an)Appends to *s the text printf would write for the same arguments; String::append of sprintf's result, without the intermediate String. The common way to build a line piece by piece before printing or keeping it once.
StringView struct
export struct StringViewA borrowed, read-only view of part of some text, without a copy.
Made by &s[lo .. hi] from a String, re-sliced by &v[lo .. hi], and made from a str by StringView::of (a literal where a StringView is expected is one). Its bounds fall on character boundaries, so its bytes are UTF-8. A view is passed by value; while it lives, the String it views cannot be changed, and it cannot outlive that String. == and != compare its bytes with another view's, a str's or a String's.
String can be viewed again; positions are byte positionsrunsString s = "hello world";
StringView w = &s[6 .. $];
assert(w == "world");
StringView o = &w[0 .. 1];
assert(o == "w");StringView::from_utf8 fn
export fn StringView::from_utf8(slice<u8, shared> bytes) : Result<StringView, Utf8Error>Views bytes as text when they are well-formed UTF-8; nothing is copied.
Err(e) when they are not, with e.offset the position of the first byte that does not fit. The view borrows what bytes borrows.
StringView::to_ascii_lower fn
export fn StringView::to_ascii_lower(StringView v) : StringA copy of the text v views with its ASCII letters in lower case (D-0312: &s of a String is its view).
Other characters are unchanged: there is no case mapping beyond ASCII.
String s = "Hello, World 1";
String l = StringView::to_ascii_lower(&s);
assert(l == "hello, world 1");
assert(ascii_to_upper(b'q') == b'Q');
assert(!ascii_is_alpha(0xc3: u8));StringView::to_ascii_upper fn
export fn StringView::to_ascii_upper(StringView v) : StringA copy of the text v views with its ASCII letters in upper case.
Other characters are unchanged: there is no case mapping beyond ASCII.
StringView::of fn
export fn StringView::of(str s) : StringViewA view of the text of s, valid for the rest of the program.
A literal where a StringView is expected is this call, so programs usually write the literal.
StringView::len fn
export fn StringView::len(StringView v) : usizeThe length of v in bytes.
StringView::char_count counts characters.
StringView::as_bytes fn
export fn StringView::as_bytes(StringView v) : slice<u8, shared>The bytes of v as a slice, not a copy, valid as long as v is.
For what takes slice<u8, shared>: a hash, a MAC, a socket's write. A literal in its place is a view, and &s gives a String's where a StringView is declared (D-0302).
StringView::find fn
export fn StringView::find(StringView v, StringView t) : Option<usize>The byte position of the first occurrence of t in v, or None when it does not occur.
The empty text occurs at position 0.
StringView::rfind fn
export fn StringView::rfind(StringView v, StringView t) : Option<usize>The byte position of the last occurrence of t in v, or None when it does not occur.
The empty text occurs at the end, position StringView::len(v).
assert(StringView::rfind("abcabc", "bc") == Some(4: usize));
assert(StringView::rfind("abc", "d") == None);
assert(StringView::rfind("abc", "") == Some(3: usize));
assert(StringView::rfind("", "") == Some(0: usize));assert(StringView::contains("abc", ""));
assert(StringView::find("abcabc", "c") == Some(2: usize));
assert(StringView::find("abc", "d") == None);StringView::starts_with fn
export fn StringView::starts_with(StringView v, StringView t) : boolWhether v begins with t.
StringView::ends_with fn
export fn StringView::ends_with(StringView v, StringView t) : boolWhether v ends with t.
StringView::contains fn
export fn StringView::contains(StringView v, StringView t) : boolWhether t occurs in v.
The empty text is in every text.
StringView::trim_start fn
export fn StringView::trim_start(StringView v) : StringViewThe view v without the ASCII white space at its start.
White space is what ascii_is_space accepts.
StringView::trim_end fn
export fn StringView::trim_end(StringView v) : StringViewThe view v without the ASCII white space at its end.
White space is what ascii_is_space accepts.
StringView::trim fn
export fn StringView::trim(StringView v) : StringViewThe view v without the ASCII white space at either end.
White space is what ascii_is_space accepts; there is no Unicode white space.
StringView::split fn
export fn StringView::split(StringView v, StringView sep) : Vec<StringView> from vThe parts of v between occurrences of sep, in order, each a view of the same text.
Empty parts are kept: "a,,b" gives three parts, and empty text one empty part. An empty sep gives v whole. The parts are views of v alone (from v), so sep is any text. StringView::split_whitespace gives words without empty parts.
StringView line = "a,,b";
Vec<StringView> parts = StringView::split(line, ",");
assert(Vec::len(&parts) == 3);
assert(parts[1] == "");
assert(parts[2] == "b");StringView::char_count fn
export fn StringView::char_count(StringView v) : usizeThe number of characters (code points) in v.
StringView::len counts bytes; a character is one to four bytes. A character is a Unicode scalar value, so "e\u{301}" is two. Nothing is allocated.
StringView::chars fn
export fn StringView::chars(StringView v) : Vec<StringView>The characters of v, in order, each a view of that character's one to four bytes.
Empty text gives an empty Vec. The Vec is new (one allocation); the views borrow what v borrows. StringView::code_point reads a character's code point, and StringView::char_count counts without the Vec.
StringView::replace fn
export fn StringView::replace(StringView v, StringView from, StringView to) : StringA new String holding v with every occurrence of from replaced by to.
Occurrences are found left to right and do not overlap; an empty from occurs nowhere, so the result is then a copy of v.
from replaces nothingrunsString r = StringView::replace("aaa", "aa", "b");
assert(r == "ba");
String same = StringView::replace("abc", "", "x");
assert(same == "abc");StringView::join fn
export fn StringView::join(slice<StringView, shared> parts, StringView sep) : StringThe texts of parts, in order, with sep between each two, in a new String.
No parts give an empty String. String::join joins a slice of Strings.
Vec<StringView> parts = Vec::new();
Vec::push(&mut parts, StringView::of("a"));
Vec::push(&mut parts, StringView::of("b"));
Vec::push(&mut parts, StringView::of("c"));
String j = StringView::join(&parts, ", ");
assert(j == "a, b, c");StringView::strip_prefix fn
export fn StringView::strip_prefix(StringView v, StringView t) : Option<StringView> from vThe rest of v after t when v begins with t, else None.
It reads an option's value: StringView::strip_prefix(a, "--name=") gives the value, or None for another argument.
StringView a = "--name=value";
assert(Option::unwrap(StringView::strip_prefix(a, "--name=")) == "value");
assert(Option::is_none(&StringView::strip_prefix(a, "--other=")));StringView::strip_suffix fn
export fn StringView::strip_suffix(StringView v, StringView t) : Option<StringView> from vThe part of v before t when v ends with t, else None.
StringView::lines fn
export fn StringView::lines(StringView v) : Vec<StringView>The lines of v: the parts between \n bytes, each without a \r just before its \n.
There is no empty line after a final \n, so "a\nb\n" and "a\nb" both give a and b; "\n\n" gives two empty lines, and empty text none. A \r not followed by \n stays in its line.
StringView text = "one\r\ntwo\n\nthree\n";
Vec<StringView> ls = StringView::lines(text);
assert(Vec::len(&ls) == 4);
assert(ls[0] == "one");
assert(ls[2] == "");
assert(ls[3] == "three");StringView::split_whitespace fn
export fn StringView::split_whitespace(StringView v) : Vec<StringView>The words of v: the runs of bytes that are not ASCII white space, in order.
No word is empty, so leading, trailing and repeated white space make no difference. White space is what ascii_is_space accepts.
Vec<StringView> w = StringView::split_whitespace(" to be\tor ");
assert(Vec::len(&w) == 3);
assert(w[0] == "to");
assert(w[2] == "or");StringView::code_point fn
export fn StringView::code_point(StringView v) : Option<u32>The code point of the first character of v, or None when v is empty.
With StringView::chars, it reads every character of a text in turn.
StringView::parse fn
export fn StringView::parse<T>(StringView v) : Result<T, ParseError>The number the text of v holds, as a T: an integer type, f32 or f64.
Parsed in place, by the rules and with the errors of [Parse] (spec/21 §2d): the whole text or nothing, so white space around the number must be trimmed first.
StringView::parse_radix fn
export fn StringView::parse_radix<T: integer>(StringView v, u32 radix) : Result<T, ParseError>The integer the text of v writes in base radix (2 to 36), as a T.
Digits are 0-9 then a-z or A-Z, with no prefix such as 0x; a leading - for a signed T. The whole text or nothing, as StringView::parse: Err(Empty), Err(Invalid(position)) for a character that is no digit of the base, Err(OutOfRange) when the number does not fit. A radix outside 2 to 36 is a fault.
assert(StringView::parse_radix<u8>("ff", 16) == Ok(255));
assert(StringView::parse_radix<u8>("FF", 16) == Ok(255));
assert(StringView::parse_radix<u8>("100", 16) == Err(OutOfRange));
assert(StringView::parse_radix<i8>("-80", 16) == Ok(-128));
assert(StringView::parse_radix<i8>("80", 16) == Err(OutOfRange));
assert(StringView::parse_radix<u32>("777", 8) == Ok(511));
assert(StringView::parse_radix<u64>("1010", 2) == Ok(10));
assert(StringView::parse_radix<u32>("zz", 36) == Ok(1295));
assert(StringView::parse_radix<u32>("12g", 16) == Err(Invalid(2)));
assert(StringView::parse_radix<u32>("-1", 16) == Err(Invalid(0)));
assert(StringView::parse_radix<i32>("-", 10) == Err(Invalid(1)));
assert(StringView::parse_radix<u32>("", 10) == Err(Empty));StringView v = " 42 ";
assert(StringView::parse<u32>(v) == Err(Invalid(0)));
assert(StringView::parse<u32>(StringView::trim(v)) == Ok(42));StringView::eq_str fn
export fn StringView::eq_strRemoved (D-0303): write a == t (D-0308)
StringView::sub fn
export fn StringView::subRemoved (D-0303): write &v[lo..hi] (D-0308)
ascii_is_digit fn
export fn ascii_is_digit(u8 b) : boolWhether b is an ASCII digit, 0 to 9.
ascii_is_upper fn
export fn ascii_is_upper(u8 b) : boolWhether b is an ASCII upper-case letter, A to Z.
ascii_is_lower fn
export fn ascii_is_lower(u8 b) : boolWhether b is an ASCII lower-case letter, a to z.
ascii_is_alpha fn
export fn ascii_is_alpha(u8 b) : boolWhether b is an ASCII letter.
A byte of 128 or more is never a letter: std has no character classes beyond ASCII.
ascii_is_alnum fn
export fn ascii_is_alnum(u8 b) : boolWhether b is an ASCII letter or digit.
ascii_is_space fn
export fn ascii_is_space(u8 b) : boolWhether b is ASCII white space: space, tab, line feed, vertical tab, form feed or carriage return.
ascii_to_lower fn
export fn ascii_to_lower(u8 b) : u8The lower-case form of b when it is an ASCII upper-case letter, else b unchanged.
A byte of 128 or more is returned as it is, so lowering every byte of UTF-8 text keeps it UTF-8.
ascii_to_upper fn
export fn ascii_to_upper(u8 b) : u8The upper-case form of b when it is an ASCII lower-case letter, else b unchanged.
A byte of 128 or more is returned as it is, so raising every byte of UTF-8 text keeps it UTF-8.
sprintf built in fn
fn sprintf(str f, a1, …, an) : StringThe text printf would write for the same arguments, as a new String instead of output. The format is checked when the program is compiled, as printf's is.
std::io impl/std/io.cb
File::printf built in fn
fn File::printf(ref<File, exclusive> f, str format, a1, …, an) : Result<void, FileError>Writes the formatted text to the open file *f, as printf would to standard output (D-0059); the format is checked when the program is compiled. A write that fails is the Err, as for File::write. File itself is std::fs's type; this function is registered with the printf family in std::io, and import std; brings in both.
flush_stdout fn
export fn flush_stdout()Writes out what standard output still holds in its buffer.
Standard output is buffered; standard error is not. Reading standard input, writing to standard error, exit and the program's end write the buffer out themselves, so this is needed only when standard output is a pipe or a file that someone watches while the program runs (progress, a log), and before handing over to C code that writes through stdio.
read_line fn
export fn read_line() : Result<Option<String>, FileError>The next line of standard input, without its line ending, or Ok(None) at the end of the input.
- A line is every byte up to the next
\n, which is consumed and not included; a\rjust before it is consumed with it, so a Windows line ending reads as a Unix one. A last line with no\nis still a line, and keeps a final\r. Ok(None)when the input ended before the line's first byte, and on every call after that.Err(FileError::Utf8(e))when the line is not UTF-8,e.offsetcounted within the line; the line is consumed, so the next call reads the one after it.Err(FileError::Io)when standard input cannot be read (a directory given as standard input among such cases: the reason is not told apart); the bytes of the line read so far are lost.
read_all_bytes fn
export fn read_all_bytes() : Result<Vec<u8>, FileError>The rest of standard input, as bytes; empty when the input has already ended.
Err(FileError::Io) when standard input cannot be read. read_all takes it as text.
read_all fn
export fn read_all() : Result<String, FileError>The rest of standard input, as text.
Err(FileError::Utf8(e)) when it is not UTF-8, and Err(FileError::Io) when it cannot be read; read_all_bytes takes it as bytes.
printf built in fn
fn printf(str f, a1, …, an)Writes the arguments to standard output as the format f says (spec/21 §2f, rule.stdlib.format). f is a string literal, so the format and the arguments are checked when the program is compiled and nothing about it can fail at run time. The conversions are C's: %d for any integer type (there is no %ld), %u, %x, %X, %o, %b (binary) for an integer's bits in its own width, %f, %e, %g for f32 and f64, %s for a str, a StringView, a ref<String, shared> or a bool, and %v for any printable value or enum "as CobaltC writes it" (an enum's variant name; a float that reads back as the same value). Width and precision may be *, taking the next argument (a usize). A reference to a number, a bool or a str prints as what it refers to, so foreach (x in &v) { printf("%d\n", x); } prints the elements. Output is buffered (D-0178) and written out when the buffer fills, at flush_stdout(), and when the program ends.
eprintf built in fn
fn eprintf(str f, a1, …, an)Writes the arguments to standard error as the format f says, with printf's conversions. For messages that are not the program's output: errors, warnings, progress. Standard error is written at once, with nothing held back, so its text and standard output's interleave in the order the calls ran (after a flush_stdout(), exactly).
stdout_write extern fn
export unsafe extern fn stdout_write(rawptr<u8> buf, usize len) : isizeWrites the len bytes at buf to standard output: the primitive under printf.
Called inside unsafe, with buf pointing at len readable bytes; its result is a claim like any extern's. What it writes goes through the same buffer as printf (flush_stdout). Programs write with printf.
stdin_read extern fn
export unsafe extern fn stdin_read(rawptr<u8> buf, usize len) : isizeReads up to len bytes of standard input into buf: the primitive under read_all_bytes.
Called inside unsafe, with buf pointing at len writable bytes. Its result, a claim like any extern's, is the number of bytes read: 0 at the end of the input, negative when the input cannot be read. Programs read with read_line, read_all or read_all_bytes.
std::fs impl/std/fs.cb
FileError enum
export enum FileErrorThe error of every input and output operation of std, for files and standard input alike.
NotFound: no such file, or a directory on the path does not exist.Denied: the environment refuses the operation.IsDirectory: the path names a directory where a file is needed.NotDirectory: a part of the path that must be a directory is not one.NoSpace: the device (or the user's quota on it) is full.TooManyOpen: the program, or the system, has as many files open as it may.NotEmpty: a directory to remove still holds entries.LinkLoop: a chain of symbolic links on the path is too long, or loops back on itself.SameFile: a copy's target is its source (the same name written another way, or a link to it).CrossDevice: a rename to another file system, whichrenamecannot do (copy, then remove).NameTooLong: a name on the path, or the path, is longer than the system allows.InvalidName: the system refuses the name or the request as such (a name holding NUL, a directory renamed into itself).NotOpenForThat: the file is not open for the operation (a write to aFilefromFile::open).ArgsTooLong: aCommand's arguments and environment are more than the system takes.Io: any other failure (a device error, …).Utf8(e): the bytes read are not UTF-8;egives the offset of the first byte that is not.
FileError::text fn
export fn FileError::text(ref<FileError, shared> e) : strThe error as a short phrase for a person (not found, permission denied).
FileError e = FileError::NotFound;
assert(FileError::text(&e) == "not found");File struct
export resource struct FileAn open file, read and written in order from a position that seek moves.
Every File comes from File::open, create, append, open_rw or create_new. Positions are u64, so a file larger than the address space is still addressed. Reading and writing are buffered; the bytes written reach the file no later than the next operation on it, any other file-system operation of the program, the start of a child process, or the program's end.
Destroying a File closes it without making it durable and without reporting a failure; a program that must know its bytes were stored calls File::close.
File::open fn
export fn File::open(StringView path) : Result<File, FileError>Opens the existing file at path for reading, at position 0.
Err(NotFound) when there is no such file; Err(Denied) when the environment refuses; Err(IsDirectory) when the path names a directory; the other variants of FileError for the failures they name.
File::create fn
export fn File::create(StringView path) : Result<File, FileError>Opens the file at path for writing from empty, creating it or discarding its contents.
Err(NotFound) when a directory on the path does not exist; Err(Denied), Err(Io) as File::open's. Use File::create_new when an existing file must not be overwritten.
File::append fn
export fn File::append(StringView path) : Result<File, FileError>Opens the file at path for writing at its end, creating it if it does not exist.
Every write lands at the end of the file.
File::open_rw fn
export fn File::open_rw(StringView path) : Result<File, FileError>Opens the file at path for reading and writing, creating it if it does not exist, its contents kept.
The position starts at 0; a write lands at the position reading has reached.
File::read fn
export fn File::read(ref<File, exclusive> f, ref<Vec<u8>, exclusive> buf, usize max) : Result<usize, FileError>Appends up to max bytes from the file's position to the end of buf and returns how many.
At most a MiB is read at a time, whatever max is; fewer bytes come only at the end of the file, and Ok(0) (for a max above 0) means the end. Err(NotOpenForThat) on a file opened only for writing (Err(Denied) on Windows).
File::read_to_end fn
export fn File::read_to_end(ref<File, exclusive> f, ref<Vec<u8>, exclusive> buf) : Result<usize, FileError>Appends the rest of the file, from its position, to the end of buf and returns how many bytes.
File::read_line fn
export fn File::read_line(ref<File, exclusive> f) : Result<Option<String>, FileError>The next line of the file, without its final '\n' or one '\r' just before it.
Ok(None) at the end of the file. A last line with no '\n' is still a line. Err(Utf8(e)) when the line is not UTF-8, e's offset counted from the line's start; Err(NotOpenForThat) on a file opened only for writing (Err(Denied) on Windows). Lines end as read_line on standard input ends them. A program that must know whether the line ended (one following a file still being written) reads it with File::read_line_with_end.
File::read_line_with_end fn
export fn File::read_line_with_end(ref<File, exclusive> f) : Result<Option<String>, FileError>The next line of the file with its line end kept: it ends with '\n' unless the file ends first.
For a program that follows a file another one is still writing (a log), or reads a line-oriented protocol: a line that does not end with '\n' is the last one so far, cut short, and its position can be returned to with File::seek to read it again whole. '\r' is kept too. Otherwise as File::read_line.
String path = path_join(&temp_dir(), &sprintf("cb-line-end-%v.txt", process_id()));
_ = write_file(&path, "first\r\npart");
File f = Result::unwrap(File::open(&path));
assert(Option::unwrap(Result::unwrap(File::read_line_with_end(&mut f))) == "first\r\n");
assert(Option::unwrap(Result::unwrap(File::read_line_with_end(&mut f))) == "part");
assert(Option::is_none(&Result::unwrap(File::read_line_with_end(&mut f))));
_ = File::close(f);
_ = remove_file(&path);File::write fn
export fn File::write(ref<File, exclusive> f, slice<u8, shared> data) : Result<void, FileError>Writes all of data at the file's position, or at its end for a file opened by File::append.
The file grows as needed and the position moves past the bytes written. Writes are buffered (see File); a failure the environment reports late is reported by the file's next operation. Err(NotOpenForThat) on a file opened only for reading (Err(Denied) on Windows).
File::write_text fn
export fn File::write_text(ref<File, exclusive> f, StringView text) : Result<void, FileError>Writes the bytes of text at the file's position, as File::write does.
File::seek fn
export fn File::seek(ref<File, exclusive> f, u64 pos) : Result<void, FileError>Moves the file's position to byte pos from the start.
A position beyond the end is allowed: reading there gives 0 bytes, and writing there extends the file.
File::len fn
export fn File::len(ref<File, shared> f) : Result<u64, FileError>The file's length in bytes.
File::create_new fn
export fn File::create_new(StringView path) : Result<Option<File>, FileError>Opens a new file at path for writing, only if nothing is there yet.
Ok(None) when a file or a directory of that name already exists, and nothing is changed, so of two programs that race to make the same file exactly one wins: a lock file, a pid file, a file that must never be overwritten. Err(NotFound) when a directory above path does not exist; other errors as File::create's.
File::create_private fn
export fn File::create_private(StringView path) : Result<Option<File>, FileError>Opens a new file at path for writing that only its owner may read or write, only if nothing is there.
As File::create_new: Ok(None) when a file, a directory or a link of that name already exists, and nothing is changed. On Unix the file is made with the mode 0600 (read and write for its owner alone), whatever the umask; on Windows it takes its directory's access list, which in the user's profile and in temp_dir() admits the user alone. For a token, a key, a password or a session file; in a directory other users may write, make one with make_temp_dir first.
File::flush fn
export fn File::flush(ref<File, exclusive> f) : Result<void, FileError>Makes everything written to the file so far durable.
The bytes are handed to the operating system and by it to the device, and from then on survive a crash or a power loss; the write-then-rename pattern flushes before the rename. Err(Io) on a file open only for reading, or when the device fails.
File::position fn
export fn File::position(ref<File, shared> f) : Result<u64, FileError>The byte the next read or write starts at, counted from the start of the file.
It is 0 when the file is opened (for File::append, the length once something is written) and is moved by every read, read_line, write and seek.
File::close fn
export fn File::close(File f) : Result<void, FileError>Closes the file, first making a file open for writing durable, and reports any failure.
Err(e) when the environment reports a failure, including one for bytes written earlier; the file is closed all the same. Destroying a File closes it too, but reports nothing.
File::drop fn
export fn File::drop(ref<File, exclusive> self)Closes an open file when its File is destroyed, without making it durable or reporting a failure.
The destructor; programs do not call it, and call File::close to learn whether the bytes were stored.
PathKind enum
export enum PathKindWhat a path names, as path_kind and file_info report it.
File(n): a file ofnbytes.Dir: a directory.Other: something else, such as a device or a socket.
FileInfo struct
export struct FileInfoWhat file_info reports of a path.
kind: what the path names, aspath_kindgives it.len: the length in bytes.modified_unix: the last modification, in whole seconds since 1970-01-01T00:00:00Z (rounded down).readonly: whether the file is read-only.
read_file fn
export fn read_file(StringView path) : Result<String, FileError>The whole contents of the file at path, as text.
A relative path is resolved against the working directory. Err(Utf8(e)) when the bytes are not UTF-8, e giving the offset of the first that is not; Err(NotFound) when no such file exists; Err(Denied) when the environment refuses; Err(IsDirectory) for a directory; Err(Io) for another failure. Use read_bytes for bytes that need not be text, and File for a file too large to hold.
write_file fn
export fn write_file(StringView path, StringView text) : Result<void, FileError>Makes the file at path hold exactly text, creating it or replacing its contents.
Err(NotFound) when a directory on the path does not exist; Err(Denied) when the environment refuses the write; Err(Io) for any other failure.
read_bytes fn
export fn read_bytes(StringView path) : Result<Vec<u8>, FileError>The whole contents of the file at path, as bytes.
The errors are File::open's and File::read_to_end's. Use read_file for text.
write_bytes fn
export fn write_bytes(StringView path, slice<u8, shared> data) : Result<void, FileError>Makes the file at path hold exactly data, creating it or replacing its contents.
The errors are write_file's, and a failed write (a full disk, an exceeded quota) is one of them. Use write_file for text.
make_dir fn
export fn make_dir(StringView path) : Result<bool, FileError>Makes the directory path, whose parent must exist.
Ok(true) when it was made; Ok(false) when a directory was already there, so it is safe to call again. Err(NotFound) when the parent does not exist; Err(Io) when something that is not a directory is at path. Use make_dir_all to make the missing parents too.
remove_file fn
export fn remove_file(StringView path) : Result<void, FileError>Removes the file at path.
Err(NotFound) when there is none.
make_temp_dir fn
export fn make_temp_dir(StringView prefix) : Result<String, FileError>Makes a new, empty directory under temp_dir() that only its owner may use, and returns its path.
The name is prefix followed by a version 4 UUID (uuid_v4, from the operating system's secure source); the directory is made only if nothing was at that name (another is tried if something was), so a directory, a file or a link another user made first is never used. On Unix its mode is 0700; on Windows it takes the temporary directory's access list, which admits the user alone. Files made in it with File::create_new or write_file are then out of other users' reach. Remove it with remove_dir_all when done. Err(NotFound) when the temporary directory does not exist; faults (entropy_unavailable) when the system has no secure source.
String a = Result::unwrap(make_temp_dir("std-test-"));
String b = Result::unwrap(make_temp_dir("std-test-"));
assert(a != b);
assert(Vec::len(&Result::unwrap(list_dir(&a))) == 0);
assert(Result::is_ok(&remove_dir(&a)) && Result::is_ok(&remove_dir(&b)));remove_dir fn
export fn remove_dir(StringView path) : Result<void, FileError>Removes the empty directory at path.
Err(NotEmpty) when it is not empty; Err(NotFound) when there is none. Use remove_dir_all to remove a directory and everything in it.
rename fn
export fn rename(StringView from, StringView to) : Result<void, FileError>Renames (moves) what is at from to to, replacing a file at to.
Within one file system only: Err(CrossDevice) when to is on another (a move from /tmp often is); then copy_file and remove_file. Err(InvalidName) for a directory renamed into itself.
list_dir fn
export fn list_dir(StringView path) : Result<Vec<String>, FileError>The names of the entries of the directory path, sorted by their bytes.
The names are entry names, not paths (join them to path with path_join), and never . or ... Err(Utf8(e)) for a name that is not UTF-8; list_dir_bytes lists such a directory too.
list_dir_bytes fn
export fn list_dir_bytes(StringView path) : Result<Vec<Vec<u8>>, FileError>The names of the entries of the directory path as their bytes, sorted by them.
list_dir, for a directory that may hold a name that is not UTF-8 (one from another system or an old archive), which list_dir refuses for the whole directory: here every name is given, and String::from_utf8 tells the names a program can open from those it can only report (to_hex, or the valid part before Utf8Error::offset) or skip. On Windows a name is its WTF-8 bytes.
read_link fn
export fn read_link(StringView path) : Result<Option<String>, FileError>The target of the symbolic link at path, or None when what is at path is not a symbolic link.
The link itself is looked at, not followed, so a directory walker skips links with it (or follows them knowingly), and a link to itself or a missing target is no error. The target is the text the link holds, relative to the link's directory unless absolute; a byte sequence in it that is not UTF-8 is replaced with U+FFFD. On Windows a junction counts as a link. Err(NotFound) when nothing is at path.
path_kind fn
export fn path_kind(StringView path) : Result<PathKind, FileError>What path names: a file and its length, a directory, or something else.
A symbolic link is followed (read_link tells a link apart). Err(NotFound) when nothing is at path; Err(LinkLoop) when links on it lead round in a loop.
path_join fn
export fn path_join(StringView base, StringView tail) : StringThe path base followed by tail, with the platform's separator between them.
No separator is added after one base already ends with. An absolute tail is returned alone. Reads the text only, never the file system.
path_parent fn
export fn path_parent(StringView p) : Option<String>The path p without its last part.
None for a root or the empty path; the empty path for a single relative name. Reads the text only, never the file system; the grammar is the platform's (\ also separates parts on Windows).
assert(Option::unwrap(path_parent("notes.txt")) == "");
assert(Option::is_none(&path_parent("")));path_file_name fn
export fn path_file_name(StringView p) : Option<String>The last part of the path p.
None when the last part is .., or when there is none (/, the empty path). Reads the text only.
.. has no file namerunsassert(Option::unwrap(path_file_name("src/main.cb")) == "main.cb");
assert(Option::is_none(&path_file_name("src/..")));path_stem fn
export fn path_stem(StringView p) : Option<String>The file name of p without its extension (archive.tar of archive.tar.gz).
A name whose only dot is its first byte has no extension, so its stem is the whole name (.bashrc). Reads the text only.
assert(Option::unwrap(path_stem("archive.tar.gz")) == "archive.tar");
assert(Option::unwrap(path_stem(".bashrc")) == ".bashrc");path_extension fn
export fn path_extension(StringView p) : Option<String>The extension of the file name of p, without its dot (gz of archive.tar.gz).
None when there is none: a name with no dot, or whose only dot is its first byte. Reads the text only.
assert(Option::unwrap(path_extension("archive.tar.gz")) == "gz");
assert(Option::is_none(&path_extension(".bashrc")));
assert(Option::is_none(&path_extension("README")));path_is_absolute fn
export fn path_is_absolute(StringView p) : boolWhether p names a place without the working directory.
By the platform's grammar: a leading / on Unix; C:\ or \\server\share\ on Windows. Reads the text only.
path_normalize fn
export fn path_normalize(StringView p) : StringThe path p with every . part removed and every x/.. (x a name) resolved.
By the text alone: a link is not followed, so the result can name another place than p when x is a link. A leading .. stays, /.. is /, and a path with no part left is .. Use path_canonical to ask the file system.
. parts go, a name and its following .. cancel, and an empty result is .runsassert(path_normalize("a/./b/../c") == path_join("a", "c"));
assert(path_normalize("../x/..") == "..");
assert(path_normalize("a/..") == ".");path_canonical fn
export fn path_canonical(StringView p) : Result<String, FileError>The absolute path the operating system resolves p to, with every link followed.
p must exist: Err(NotFound) when nothing is at p; Err(Utf8(e)) when the result is not UTF-8.
file_info fn
export fn file_info(StringView path) : Result<FileInfo, FileError>The kind, length, modification time and read-only state of what is at path.
A symbolic link is followed, as path_kind follows it. Err(NotFound) when nothing is at path.
copy_file fn
export fn copy_file(StringView from, StringView to) : Result<u64, FileError>Copies the file from to to, replacing a file there, and returns the number of bytes copied.
Err(SameFile) when to is from itself (the same name written another way, or a link to it), and nothing is changed; Err(IsDirectory) when from is a directory. A source that is neither a file nor a directory (a pipe such as /dev/stdin or a shell's <(…), a device) is read to its end and written to to, as cp copies it; to then has the default permissions.
copy_permissions fn
export fn copy_permissions(StringView from, StringView to) : Result<void, FileError>Gives what is at to the permissions of what is at from: on Unix the mode bits, on Windows the read-only flag.
For the write-then-rename pattern: a file written beside the original and renamed over it keeps the original's permissions only when they are copied to it before the rename. Err(NotFound) when nothing is at from or at to.
String tmp = temp_dir();
String dir = path_join(&tmp, &sprintf("cb-perm-%v", process_id()));
_ = make_dir_all(&dir);
String a = path_join(&dir, "a.txt");
String b = path_join(&dir, "b.txt");
_ = write_file(&a, "a");
_ = write_file(&b, "b");
assert(Result::is_ok(©_permissions(&a, &b)));
bool ra = Result::unwrap(file_info(&a)).readonly;
bool rb = Result::unwrap(file_info(&b)).readonly;
assert(ra == rb);
String gone = path_join(&dir, "gone.txt");
assert(Result::is_err(©_permissions(&gone, &b)));
_ = remove_dir_all(&dir);make_dir_all fn
export fn make_dir_all(StringView path) : Result<void, FileError>Makes the directory path and every missing directory above it.
Ok(()) when they are all there already.
remove_dir_all fn
export fn remove_dir_all(StringView path) : Result<void, FileError>Removes the directory path and everything in it.
Err(NotFound) when nothing is at path.
std::env impl/std/env.cb
Args struct
export struct ArgsThe program's arguments, read as options and positional arguments.
Each Args::flag, Args::option or Args::options call names an option, takes its occurrences from the arguments and adds a line to Args::help; Args::finish then gives the arguments left and refuses any option nobody declared. --name, --name=value, --name value, -s and -s value are read; -- ends the options, and a lone - is an argument. A git-style program, whose command has options of its own, takes the command first with Args::command.
Args::new fn
export fn Args::new(StringView usage) : Result<Args, Utf8Error>The program's arguments, from arg(0) on, with the usage line that Args::help shows.
The usage line is the text after Usage: , such as prog [options] FILE.
Err(e) for the first argument that is not UTF-8.
Args::from fn
export fn Args::from(Vec<String> items, StringView usage) : ArgsThe arguments items, read as Args::new reads the program's own.
For arguments that come from elsewhere, or a test.
finish gives what is leftrunsVec<String> items = Vec::new();
Vec::push(&mut items, "-v");
Vec::push(&mut items, "--out=a.txt");
Vec::push(&mut items, "in.txt");
Args a = Args::from(items, "prog [options] FILE");
assert(Args::flag(&mut a, "verbose", "v", "say more"));
assert(Option::unwrap(Args::option(&mut a, "out", "o", "FILE", "where to write")) == "a.txt");
Vec<String> rest = Result::unwrap(Args::finish(&mut a));
assert(Vec::len(&rest) == 1 && rest[0] == "in.txt");Args::flag fn
export fn Args::flag(ref<Args, exclusive> a, str name, str short, str help) : boolWhether --name or -short is among the arguments before --.
short is one letter, or "" for none; help is the option's line in Args::help. Every occurrence is taken, so Args::finish does not see it. Faults (assert_failed) when an earlier declaration has the same name or the same letter (the first would take every occurrence).
--, an argument that looks like an option is a positional argumentrunsVec<String> items = Vec::new();
Vec::push(&mut items, "--");
Vec::push(&mut items, "-v");
Args a = Args::from(items, "prog [options] FILE");
assert(!Args::flag(&mut a, "verbose", "v", "say more"));
Vec<String> rest = Result::unwrap(Args::finish(&mut a));
assert(Vec::len(&rest) == 1 && rest[0] == "-v");Args::options fn
export fn Args::options(ref<Args, exclusive> a, str name, str short, str value_name, str help) : Vec<String>Every value given for the option --name or -short, in order.
A value is given as --name=value, --name value or -s value; each is taken, the value with it. value_name names the value in Args::help (FILE). A --name or -s that is the last argument, just before --, or followed by an argument an earlier declaration took (a flag's -v), has no value and is left for Args::finish to refuse. Faults (assert_failed) when an earlier declaration has the same name or the same letter.
Args::command fn
export fn Args::command(ref<Args, exclusive> a, str value_options) : Vec<String>Takes the command of a git-style program and the arguments after it: tool -v commit -m hi gives commit -m hi.
Called before the program's own options are declared. The command is the first argument (before --, or just after it) that does not start with - and is not the value of one of value_options, the options written there that take a value ("-C --config", as they are written before the command; "" for none). It and every argument after it are taken, so the declarations that follow read only the arguments before it and Args::finish gives none of them; the command's own options are read with Args::from(cmd, "tool commit [options]"), whose finish gives the command first. Empty when there is no command.
Args of its argumentsrunsVec<String> items = Vec::new();
Vec::push(&mut items, "-C");
Vec::push(&mut items, "dir");
Vec::push(&mut items, "-v");
Vec::push(&mut items, "commit");
Vec::push(&mut items, "-v");
Vec::push(&mut items, "-m");
Vec::push(&mut items, "hello");
Args a = Args::from(items, "tool [-v] [-C DIR] COMMAND");
Vec<String> cmd = Args::command(&mut a, "-C --dir");
bool verbose = Args::flag(&mut a, "verbose", "v", "say more");
Option<String> dir = Args::option(&mut a, "dir", "C", "DIR", "where to work");
assert(verbose && Option::unwrap(dir) == "dir");
assert(Vec::len(&Result::unwrap(Args::finish(&mut a))) == 0);
Args c = Args::from(cmd, "tool commit [-v] -m MSG");
bool cv = Args::flag(&mut c, "verbose", "v", "show the diff");
Option<String> msg = Args::option(&mut c, "message", "m", "MSG", "the message");
Vec<String> rest = Result::unwrap(Args::finish(&mut c));
assert(cv && Option::unwrap(msg) == "hello" && Vec::len(&rest) == 1 && rest[0] == "commit");Args::option fn
export fn Args::option(ref<Args, exclusive> a, str name, str short, str value_name, str help) : Option<String>The value of the option --name or -short, the last one when it is given more than once.
None when it is not given. Takes its arguments as Args::options does.
Args::finish fn
export fn Args::finish(ref<Args, exclusive> a) : Result<Vec<String>, String>The arguments no declaration took, in order, every argument after -- among them.
Err(message) for the first argument before -- that starts with - and is not a lone -: unknown option --x; missing a value for --x for a declared option given without its value; and for a declared option written in a form that is not read, the form to write: -I takes its value as a separate argument: -I inc for -Iinc, short options are written one at a time: -v -o for -vo, --verbose takes no value for --verbose=yes. The message is for the program to print, usually followed by Args::help.
Args::help fn
export fn Args::help(ref<Args, shared> a) : StringThe usage line and one aligned line per option declared so far, ready to print.
Args a = Args::from(Vec::new(), "prog FILE");
bool verbose = Args::flag(&mut a, "verbose", "v", "say more");
Option<String> out = Args::option(&mut a, "out", "", "FILE", "where to write");
String h = Args::help(&a);
assert(h == "Usage: prog FILE\n\nOptions:\n"
" -v, --verbose say more\n"
" --out FILE where to write\n");arg_count fn
export fn arg_count() : usizeThe number of the program's arguments, not counting the program's own name.
arg fn
export fn arg(usize i) : Result<String, Utf8Error>Argument i of the program, counted from 0 for the first after the program's own name.
Err(e) when the argument is not UTF-8, e.offset being the bad byte's offset within it; use arg_bytes for such an argument. Faults (index_out_of_bounds) when i >= arg_count().
env_var fn
export fn env_var(StringView name) : Result<Option<String>, Utf8Error>The value of the environment variable name.
Ok(None) when it is not set; Err(e) when its value is not UTF-8, e giving the offset of the first byte that is not.
current_dir fn
export fn current_dir() : Result<String, FileError>The working directory, against which a relative path is resolved.
Err(Utf8(e)) when its name is not UTF-8.
set_current_dir fn
export fn set_current_dir(StringView path) : Result<void, FileError>Makes path the working directory, against which relative paths are resolved from now on.
The change is seen by every thread of the program.
temp_dir fn
export fn temp_dir() : StringThe operating system's directory for temporary files.
A byte sequence in it that is not UTF-8 is replaced with U+FFFD.
home_dir fn
export fn home_dir() : Option<String>The user's home directory: the variable HOME, or USERPROFILE on Windows.
None when it is not set. A byte sequence that is not UTF-8 is replaced with U+FFFD.
current_exe fn
export fn current_exe() : Result<String, FileError>The path of the running program's own executable, absolute and with links followed.
A program finds the files installed beside it from here. Err(Utf8(e)) when the path is not UTF-8; Err(Io) when the operating system cannot say.
hostname fn
export fn hostname() : Result<String, FileError>The machine's host name, as the operating system knows it.
What a log line or a service's registration names the machine by. Err(Utf8(e)) when it is not UTF-8; Err(Io) when the operating system cannot say.
arg_bytes extern fn
export unsafe extern fn arg_bytes(usize i, rawptr<u8> buf, usize len) : isizeCopies at most len bytes of argument i to buf and returns the argument's whole length.
Returns -1, storing nothing, when there is no argument i; a call with len 0 only asks whether argument i exists and how long it is. Called inside unsafe: [buf, buf + len) must be storage outside every live object. For an argument's bytes whatever they are; arg is the safe way to read one.
std::memory impl/std/memory.cb
Rc struct
export resource struct Rc<T>A reference-counted handle to a value on the heap that several owners in one thread share.
Each Rc is one strong handle; the value is destroyed when the last strong handle is, and the memory is freed once no Weak handle remains either. The value is reached only as a shared reference (Rc::get), so changing it needs a mutex inside. A cycle of Rcs is never freed: a parent pointer, a cache or an observer list holds a Weak instead. Rc is not thread-safe (the count is not synchronised), so spawn refuses one, or a value holding or referring to one (diag.not-thread-safe), and an Rc or Weak used in a thread other than the one that made it (carried there by a closure the compiler could not see through) faults with the same diagnostic; share across threads with Arc<T> or ref<mutex<T>, shared>.
Rc::new fn
export fn Rc::new<T>(T v) : Rc<T>A new Rc holding v, the only strong handle to it.
Allocates; faults (alloc_failure) when memory cannot be had.
Rc::clone fn
export fn Rc::clone<T>(ref<Rc<T>, shared> r) : Rc<T>A second strong handle to the value r holds; nothing is copied.
What clone(&r) calls for an Rc. A reference into the value from Rc::get may stay live across it.
Rc::get fn
export fn Rc::get<T>(ref<Rc<T>, shared> r) : ref<T, shared>The value r holds, as a shared reference.
Rc::drop fn
export fn Rc::drop<T>(ref<Rc<T>, exclusive> self)Ends one strong handle; run when an Rc is destroyed, so programs write drop(r) or let it go.
When this was the last strong handle the value is destroyed now, and with no Weak handle left the memory is freed too.
Rc::downgrade fn
export fn Rc::downgrade<T>(ref<Rc<T>, shared> r) : Weak<T>A Weak handle to the value r holds.
Weak struct
export resource struct Weak<T>A handle to an Rc's value that does not keep the value alive.
It keeps only the memory: once the last Rc ends, the value is gone and Weak::upgrade gives None. Dropping the last handle of either kind frees the memory.
Weak::upgrade fn
export fn Weak::upgrade<T>(ref<Weak<T>, shared> w) : Option<Rc<T>>A new strong handle to the value, or None when the value has ended.
The value never comes back once ended: after the last Rc is destroyed every upgrade gives None.
Weak upgrades while any Rc remains and gives None after the last one endsrunsRc<String> a = Rc::new("shared");
Rc<String> b = Rc::clone(&a);
assert(StringView::len(Rc::get(&b)) == 6);
Weak<String> w = Rc::downgrade(&a);
drop(a);
assert(Option::is_some(&Weak::upgrade(&w)));
drop(b);
assert(Option::is_none(&Weak::upgrade(&w)));Weak::clone fn
export fn Weak::clone<T>(ref<Weak<T>, shared> w) : Weak<T>A second Weak handle to the same value; what clone(&w) calls for a Weak.
Weak::drop fn
export fn Weak::drop<T>(ref<Weak<T>, exclusive> self)Ends one weak handle; run when a Weak is destroyed.
When no strong or weak handle remains, the memory is freed.
Arc struct
export resource struct Arc<T>A reference-counted handle to a value that several threads share.
Rc for threads: each Arc is one strong handle, and handles may be cloned into other threads, moved and dropped there, so a thread owns its share of the value and may outlive the frame that made it, which a reference to the value does not allow. The counts are atomic, so clones and drops from several threads at once lose nothing; the value is destroyed, once, by whichever handle ends last. It is reached only as a shared reference (Arc::get), so changing it needs a mutex or an Atomic inside. An ArcWeak (Arc::downgrade) keeps the box but not the value, for a parent pointer or a cache.
Arc::new fn
export fn Arc::new<T>(T v) : Arc<T>A new Arc holding v, the only strong handle to it.
Allocates; faults (alloc_failure) when memory cannot be had.
Arc::clone fn
export fn Arc::clone<T>(ref<Arc<T>, shared> a) : Arc<T>A second strong handle to the value a holds; nothing is copied.
What clone(&a) calls for an Arc. The new handle may go to another thread.
Arc::get fn
export fn Arc::get<T>(ref<Arc<T>, shared> a) : ref<T, shared>The value a holds, as a shared reference.
Arc::drop fn
export fn Arc::drop<T>(ref<Arc<T>, exclusive> self)Ends one strong handle; run when an Arc is destroyed, so programs write drop(a) or let it go.
When this was the last strong handle, on whichever thread, the value is destroyed now, and with no ArcWeak handle left the memory is freed too.
Arc::downgrade fn
export fn Arc::downgrade<T>(ref<Arc<T>, shared> a) : ArcWeak<T>An ArcWeak handle to the value a holds.
ArcWeak struct
export resource struct ArcWeak<T>A handle that does not keep the value alive.
As Weak is to Rc: it keeps only the memory. Once the last Arc ends, the value is gone and ArcWeak::upgrade gives None. Dropping the last handle of either kind frees the memory.
ArcWeak::upgrade fn
export fn ArcWeak::upgrade<T>(ref<ArcWeak<T>, shared> w) : Option<Arc<T>>A new strong handle to the value, or None when the value has ended.
The value never comes back once ended: after the last Arc is destroyed every upgrade gives None.
ArcWeak::clone fn
export fn ArcWeak::clone<T>(ref<ArcWeak<T>, shared> w) : ArcWeak<T>A second ArcWeak handle to the same value; what clone(&w) calls for an ArcWeak.
ArcWeak::drop fn
export fn ArcWeak::drop<T>(ref<ArcWeak<T>, exclusive> self)Ends one weak handle; run when an ArcWeak is destroyed.
When no strong or weak handle remains, the memory is freed.
ArcWeak upgrades while any Arc remains and gives None after the last one endsrunsArc<String> a = Arc::new("shared");
Arc<String> b = clone(&a);
assert(StringView::len(Arc::get(&b)) == 6);
ArcWeak<String> w = Arc::downgrade(&a);
ArcWeak<String> w2 = clone(&w);
drop(a);
assert(Option::is_some(&ArcWeak::upgrade(&w)));
drop(b);
assert(Option::is_none(&ArcWeak::upgrade(&w)) && Option::is_none(&ArcWeak::upgrade(&w2)));Box struct
export resource struct Box<T>A value on the heap with one owner.
It gives recursive types their indirection (struct Node { i32 v; Option<Box<Node>> next; }) and moves a large value as a pointer. A Box is a resource: it moves, and destroying it destroys the value and frees the memory. It allocates sizeof<T>() bytes, or one for a zero-sized T. A Box is one pointer (D-0298): Box::new never gives the null pointer, so null marks a Box whose value into_inner took.
Box::new fn
export fn Box::new<T>(T v) : Box<T>A new Box holding v.
Allocates; faults (alloc_failure) when memory cannot be had.
Box::get fn
export fn Box::get<T>(ref<Box<T>, shared> b) : ref<T, shared>The value in b, as a shared reference.
Box::get_mut fn
export fn Box::get_mut<T>(ref<Box<T>, exclusive> b) : ref<T, exclusive>The value in b, as an exclusive reference.
Needs an exclusive borrow of the Box, as changing any value does.
Box::clone fn
export fn Box::clone<T: clone>(ref<Box<T>, shared> b) : Box<T>A new Box holding a copy of the value in b; what clone(&b) calls for a Box.
A chain of boxes, whose type links to one more of itself (Branch(Box<Tree>), a list of Option<Box<Node>>), is copied by its derived clone at any length: past a thousand links it copies the rest with a loop. So is a tree whose values have two or more such links (a struct's left and right, a variant's Add { Box<Expr> a; Box<Expr> b; }): past a thousand levels it copies the rest with a loop over a stack of its own. A type that links to itself only through another type (Node(Box<Pair>)), or one with a clone of its own, takes a call for each level, so millions of levels can exhaust the stack (diag.stack-exhausted).
Box::into_inner fn
export fn Box::into_inner<T>(Box<T> b) : TThe value in b, moved out; the Box's memory is freed.
Faults if another thread holds an exclusive path to the value.
Box, and taking the value back outrunsBox<i32> b = Box::new(5);
*Box::get_mut(&mut b) = 6;
assert(*Box::get(&b) == 6);
Box<i32> c = clone(&b);
assert(Box::into_inner(c) == 6);Box::drop fn
export fn Box::drop<T>(ref<Box<T>, exclusive> self)Destroys the value and frees the memory; run when a Box is destroyed.
std::sync impl/std/sync.cb
Channel struct
export resource struct Channel<T>A bounded first-in, first-out queue of values between threads.
Shared by reference, as a mutex is: every thread works on it through ref<Channel<T>, shared>. send waits while it is full and recv while it is empty; after close, send gives its value back and recv drains what is left, then gives None. Destroying the channel destroys the values still in it, oldest first.
Channel::new fn
export fn Channel::new<T>(usize cap) : Channel<T>An empty open channel holding at most cap values.
Faults (channel_zero_capacity) when cap is 0; 1 makes a hand-over.
Channel::send fn
export fn Channel::send<T>(ref<Channel<T>, shared> ch, T v) : Result<void, T>Puts v at the back of ch, waiting while the channel is full.
Err(v), the value handed back, once the channel is closed. Exclusive references inside v are lent to the receiving thread: the sender's own copies of them clash with them while they live.
Channel::recv fn
export fn Channel::recv<T>(ref<Channel<T>, shared> ch) : Option<T>Takes the value at the front of ch, waiting while the channel is empty.
None once the channel is closed and empty.
Channel::try_recv fn
export fn Channel::try_recv<T>(ref<Channel<T>, shared> ch) : Result<Option<T>, void>Takes the value at the front of ch if one is waiting, without waiting.
Ok(Some(v)) with the value; Ok(None) when the channel is empty; Err(()) once it is closed and empty, so a loop that also polls something else (a socket, interrupt_requested) knows when the senders are done.
Ok(None); closed and empty is ErrrunsChannel<i32> ch = Channel::new(1);
assert(Option::is_none(&Result::unwrap(Channel::try_recv(&ch))));
_ = Channel::send(&ch, 5);
Channel::close(&ch);
assert(Option::unwrap(Result::unwrap(Channel::try_recv(&ch))) == 5);
assert(Result::is_err(&Channel::try_recv(&ch)));Channel::recv_timeout_ms fn
export fn Channel::recv_timeout_ms<T>(ref<Channel<T>, shared> ch, u64 ms) : Result<Option<T>, void>Takes the value at the front of ch, waiting at most ms milliseconds for one.
Ok(Some(v)) with the value; Ok(None) when none arrived in time; Err(()) when the channel is closed and empty. The wait is a poll (every millisecond at first, then every five), so it ends at most a few milliseconds late.
Channel::close fn
export fn Channel::close<T>(ref<Channel<T>, shared> ch)Marks ch as taking no more values.
send fails from then on, and recv gives None once the values already in it are taken. Waiting senders and receivers wake. Closing a closed channel does nothing.
close, send hands its value back while recv still drains what was sentrunsChannel<i32> ch = Channel::new(2);
assert(Result::is_ok(&Channel::send(&ch, 1)));
assert(Result::is_ok(&Channel::send(&ch, 2)));
Channel::close(&ch);
assert(Result::is_err(&Channel::send(&ch, 3)));
assert(Option::unwrap(Channel::recv(&ch)) == 1);
assert(Option::unwrap(Channel::recv(&ch)) == 2);
assert(Option::is_none(&Channel::recv(&ch)));Channel::drop fn
export fn Channel::drop<T>(ref<Channel<T>, exclusive> self)Destroys the values still in the channel, oldest first; run when a Channel is destroyed.
ThreadFailure struct
export resource struct ThreadFailureA spawned thread's fault, contained and handed over by try_join instead of raised again.
Its text is kept by the runtime while the value lives, and freed when it is destroyed.
ThreadFailure::drop fn
export fn ThreadFailure::drop(ref<ThreadFailure, exclusive> self)Frees the runtime's record of the failure; run when a ThreadFailure is destroyed.
ThreadFailure::text fn
export fn ThreadFailure::text(ref<ThreadFailure, shared> f) : StringThe failure's report, as the program would have printed it had nothing taken the failure.
As a fault's report on standard error: its first line names the diagnostic, its second the location.
ThreadFailure::diagnostic fn
export fn ThreadFailure::diagnostic(ref<ThreadFailure, shared> f) : StringThe name of the failure's diagnostic alone, such as diag.index-out-of-bounds or diag.thread-cancelled.
ThreadFailure::is_cancelled fn
export fn ThreadFailure::is_cancelled(ref<ThreadFailure, shared> f) : boolWhether the thread ended because it was cancelled, rather than by a fault of its own.
Atomic struct
export resource struct Atomic<T>An integer that threads share and change without a lock.
Shared by reference, as a mutex is: every operation takes ref<Atomic<T>, shared>, and each one is indivisible and sequentially consistent, so all threads see all operations on all atomics in one order. T is an integer type of at most 64 bits. For a counter, a flag (an Atomic<u8>), a sequence number or a maximum kept by several threads; state of more than one integer belongs in a mutex.
Atomic::new fn
export fn Atomic::new<T: integer>(T v) : Atomic<T>A new atomic holding v.
T is an integer type of at most 64 bits: Atomic<u128> is rejected when the program is checked.
Atomic::load fn
export fn Atomic::load<T: integer>(ref<Atomic<T>, shared> a) : TThe value a holds.
Atomic::store fn
export fn Atomic::store<T: integer>(ref<Atomic<T>, shared> a, T v)Replaces the value a holds with v.
Atomic::swap fn
export fn Atomic::swap<T: integer>(ref<Atomic<T>, shared> a, T v) : TReplaces the value a holds with v, giving the value it held.
Atomic::compare_exchange fn
export fn Atomic::compare_exchange<T: integer>(ref<Atomic<T>, shared> a, T expected, T new) : Result<T, T>Replaces the value with new if it is expected, as one step.
Ok(expected) when it was replaced; Err(current) with the value found when it was not, and then nothing changed. The step under a lock-free update: read, compute, and try again from current when another thread got there first.
Atomic::fetch_add fn
export fn Atomic::fetch_add<T: integer>(ref<Atomic<T>, shared> a, T n) : TAdds n to the value a holds, giving the value it held.
Faults (arith_overflow) when the sum does not fit T, as + does, and then the value is unchanged. fetch_add_wrapping wraps instead.
Atomic::fetch_sub fn
export fn Atomic::fetch_sub<T: integer>(ref<Atomic<T>, shared> a, T n) : TSubtracts n from the value a holds, giving the value it held.
Faults (arith_overflow) when the difference does not fit T, as - does, and then the value is unchanged. fetch_sub_wrapping wraps instead.
Atomic::fetch_add_wrapping fn
export fn Atomic::fetch_add_wrapping<T: integer>(ref<Atomic<T>, shared> a, T n) : TAdds n to the value a holds modulo 2 to the width of T, giving the value it held.
Atomic::fetch_sub_wrapping fn
export fn Atomic::fetch_sub_wrapping<T: integer>(ref<Atomic<T>, shared> a, T n) : TSubtracts n from the value a holds modulo 2 to the width of T, giving the value it held.
Atomic::fetch_and fn
export fn Atomic::fetch_and<T: integer>(ref<Atomic<T>, shared> a, T n) : TReplaces the value a holds with its bitwise and with n, giving the value it held.
Atomic::fetch_or fn
export fn Atomic::fetch_or<T: integer>(ref<Atomic<T>, shared> a, T n) : TReplaces the value a holds with its bitwise or with n, giving the value it held.
Atomic::fetch_xor fn
export fn Atomic::fetch_xor<T: integer>(ref<Atomic<T>, shared> a, T n) : TReplaces the value a holds with its bitwise exclusive or with n, giving the value it held.
Atomic<u64> hits = Atomic::new(0: u64);
{
Vec<handle<u64>> hs = Vec::new();
foreach (k in 0..8)
{
Vec::push(&mut hs, spawn(Atomic::fetch_add<u64>, &hits, 5: u64));
}
while (Vec::len(&hs) > 0)
{
_ = join(Option::unwrap(Vec::pop(&mut hs)));
}
}
assert(Atomic::load(&hits) == 40);compare_exchange replaces only the value it expects, and reports the one it found otherwiserunsAtomic<i32> a = Atomic::new(5: i32);
assert(Result::unwrap(Atomic::compare_exchange(&a, 5, 9)) == 5);
match (Atomic::compare_exchange(&a, 5, 1))
{
Ok(_) : assert(false),
Err(now) : assert(now == 9),
}
assert(Atomic::swap(&a, 2) == 9);
Atomic::store(&a, 7);
assert(Atomic::load(&a) == 7);TrunsAtomic<u8> f = Atomic::new(0: u8);
_ = Atomic::fetch_or(&f, 0x05);
_ = Atomic::fetch_and(&f, 0x0c);
_ = Atomic::fetch_xor(&f, 0x0f);
assert(Atomic::load(&f) == 0x0b);
assert(Atomic::fetch_add_wrapping(&f, 250) == 0x0b);
assert(Atomic::load(&f) == 5);
assert(Atomic::fetch_sub_wrapping(&f, 6) == 5);
assert(Atomic::load(&f) == 255);Atomic::fetch_max fn
export fn Atomic::fetch_max<T: integer>(ref<Atomic<T>, shared> a, T v) : TReplaces the value a holds with the larger of it and v, giving the value it held.
A maximum kept by several threads: a high-water mark, the latest timestamp seen.
Atomic::fetch_min fn
export fn Atomic::fetch_min<T: integer>(ref<Atomic<T>, shared> a, T v) : TReplaces the value a holds with the smaller of it and v, giving the value it held.
Atomic::fetch_update fn
export fn Atomic::fetch_update<T: integer>(ref<Atomic<T>, shared> a, fn(T) : Option<T> f) : Result<T, T>Replaces the value a holds with f of it, retrying when another thread changed it meanwhile.
f is called with the value found and gives Some(new) to store or None to leave it. Ok(previous) when new was stored, Err(previous) when f gave None. f may be called more than once, so it should compute only from its argument.
Atomic::wait fn
export fn Atomic::wait<T: integer>(ref<Atomic<T>, shared> a, T expected)Blocks while a holds expected, until another thread changes it and calls notify_one or notify_all.
Returns at once if a does not hold expected, and otherwise only after it has seen another value, so a wake-up with the value unchanged waits again. The thread that changes the value calls notify_one or notify_all after the change. A wait no thread can end faults (deadlock).
Atomic::notify_one fn
export fn Atomic::notify_one<T: integer>(ref<Atomic<T>, shared> a)Wakes at least one thread waiting in Atomic::wait on a, if any waits.
Atomic::notify_all fn
export fn Atomic::notify_all<T: integer>(ref<Atomic<T>, shared> a)Wakes every thread waiting in Atomic::wait on a.
AtomicBool struct
export struct AtomicBoolA bool that threads share and change without a lock.
As Atomic, over a byte that holds 0 or 1: every operation takes ref<AtomicBool, shared> and is indivisible and sequentially consistent. For a stop flag, a "ready" flag, or a once-only claim (swap(&f, true) gives false to exactly one thread).
AtomicBool::new fn
export fn AtomicBool::new(bool v) : AtomicBoolA new atomic bool holding v.
AtomicBool::load fn
export fn AtomicBool::load(ref<AtomicBool, shared> f) : boolThe value f holds.
AtomicBool::store fn
export fn AtomicBool::store(ref<AtomicBool, shared> f, bool v)Replaces the value f holds with v.
AtomicBool::swap fn
export fn AtomicBool::swap(ref<AtomicBool, shared> f, bool v) : boolReplaces the value f holds with v, giving the value it held.
AtomicBool::compare_exchange fn
export fn AtomicBool::compare_exchange(ref<AtomicBool, shared> f, bool expected, bool new) : Result<bool, bool>Replaces the value with new if it is expected, as one step: Ok(expected), or Err(current).
AtomicBool::fetch_and fn
export fn AtomicBool::fetch_and(ref<AtomicBool, shared> f, bool v) : boolReplaces the value f holds with its and with v, giving the value it held.
AtomicBool::fetch_or fn
export fn AtomicBool::fetch_or(ref<AtomicBool, shared> f, bool v) : boolReplaces the value f holds with its or with v, giving the value it held.
AtomicBool::fetch_xor fn
export fn AtomicBool::fetch_xor(ref<AtomicBool, shared> f, bool v) : boolReplaces the value f holds with its exclusive or with v, giving the value it held.
AtomicBool::wait fn
export fn AtomicBool::wait(ref<AtomicBool, shared> f, bool expected)Blocks while f holds expected, as Atomic::wait.
AtomicBool::notify_one fn
export fn AtomicBool::notify_one(ref<AtomicBool, shared> f)Wakes at least one thread waiting in AtomicBool::wait on f, if any waits.
AtomicBool::notify_all fn
export fn AtomicBool::notify_all(ref<AtomicBool, shared> f)Wakes every thread waiting in AtomicBool::wait on f.
AtomicPtr struct
export resource struct AtomicPtr<T>A raw pointer that threads share and change without a lock.
As Atomic: shared by reference, every operation indivisible and sequentially consistent. Taking and storing addresses is safe; reading or writing through one is unsafe, as for any rawptr. For lock-free lists and stacks whose nodes come from allocate.
AtomicPtr::new fn
export fn AtomicPtr::new<T>(rawptr<T> p) : AtomicPtr<T>A new atomic pointer holding p; null_rawptr<T>() for none.
AtomicPtr::load fn
export fn AtomicPtr::load<T>(ref<AtomicPtr<T>, shared> a) : rawptr<T>The address a holds.
AtomicPtr::store fn
export fn AtomicPtr::store<T>(ref<AtomicPtr<T>, shared> a, rawptr<T> p)Replaces the address a holds with p.
AtomicPtr::swap fn
export fn AtomicPtr::swap<T>(ref<AtomicPtr<T>, shared> a, rawptr<T> p) : rawptr<T>Replaces the address a holds with p, giving the address it held.
AtomicPtr::compare_exchange fn
export fn AtomicPtr::compare_exchange<T>(ref<AtomicPtr<T>, shared> a, rawptr<T> expected, rawptr<T> new) : Result<rawptr<T>, rawptr<T>>Replaces the address with new if it is expected, as one step: Ok(expected), or Err(current).
Barrier struct
export struct BarrierA meeting point for a fixed number of threads.
Shared by reference, as a mutex is. Barrier::wait blocks until parties threads have called it, then releases them all together and is ready for the next round: the phases of a parallel algorithm, where every thread must finish one before any starts the next.
Barrier::new fn
export fn Barrier::new(usize parties) : BarrierA barrier for parties threads.
Faults (barrier_zero_parties) when parties is 0.
Barrier::wait fn
export fn Barrier::wait(ref<Barrier, shared> b) : boolWaits until parties threads have called it, then lets them all go on.
true for the last thread to arrive, the one that released the others, and false for the rest, so one thread of each round can do something once. A wait that fewer threads than parties can ever reach faults (deadlock). A thread cancelled while it waits (cancel) takes its arrival back, so the round still waits for parties threads that meet it.
Barrier b = Barrier::new(4);
Atomic<u32> leaders = Atomic::new(0: u32);
Atomic<u32> seen = Atomic::new(0: u32);
Vec<handle<void>> hs = Vec::new();
for (u32 i = 0; i < 4; i += 1)
{
Vec::push(&mut hs, spawn(move [](
ref<Barrier, shared> b,
ref<Atomic<u32>, shared> leaders,
ref<Atomic<u32>, shared> seen,
u32 id,
)
{
for (u32 round = 0; round < 3; round += 1)
{
_ = Atomic::fetch_add(seen, 1);
if (Barrier::wait(b))
{
_ = Atomic::fetch_add(leaders, 1);
assert(Atomic::load(seen) == 4 * (round + 1)); // everyone wrote before anyone read
}
_ = Barrier::wait(b); // the read phase ends together too
}
}, &b, &leaders, &seen, i));
}
foreach (h in hs)
{
join(h);
}
assert(Atomic::load(&leaders) == 3 && Atomic::load(&seen) == 12);Semaphore struct
export struct SemaphoreA count of permits that threads take and give back.
Shared by reference, as a mutex is. acquire takes one permit, waiting while there is none; release gives one back, or adds one. It bounds how many threads do something at once (connections open, workers busy); made with 0 permits, it hands events from one thread to another, each release letting one acquire through.
Semaphore::new fn
export fn Semaphore::new(usize permits) : SemaphoreA semaphore with permits permits; 0 is allowed.
Semaphore::acquire fn
export fn Semaphore::acquire(ref<Semaphore, shared> s)Takes one permit, waiting while there is none.
Permits are not handed out in arrival order. A wait no thread can end faults (deadlock).
Semaphore::try_acquire fn
export fn Semaphore::try_acquire(ref<Semaphore, shared> s) : boolTakes one permit if one is free, without waiting: true when it did.
Semaphore::release fn
export fn Semaphore::release(ref<Semaphore, shared> s)Gives one permit back, or adds one; a thread waiting in acquire wakes.
Faults (arith_overflow) when the permits would exceed what usize counts.
Semaphore::available fn
export fn Semaphore::available(ref<Semaphore, shared> s) : usizeHow many permits are free now: a snapshot another thread may change at once.
Semaphore limit = Semaphore::new(2);
Atomic<u32> active = Atomic::new(0: u32);
Atomic<u32> peak = Atomic::new(0: u32);
Vec<handle<void>> hs = Vec::new();
for (u32 i = 0; i < 6; i += 1)
{
Vec::push(&mut hs, spawn(move [](
ref<Semaphore, shared> limit,
ref<Atomic<u32>, shared> active,
ref<Atomic<u32>, shared> peak,
)
{
Semaphore::acquire(limit);
_ = Atomic::fetch_max(peak, Atomic::fetch_add(active, 1) + 1);
_ = Atomic::fetch_sub(active, 1);
Semaphore::release(limit);
}, &limit, &active, &peak));
}
foreach (h in hs)
{
join(h);
}
assert(Atomic::load(&peak) <= 2 && Semaphore::available(&limit) == 2);
assert(Semaphore::try_acquire(&limit) && Semaphore::try_acquire(&limit) && !Semaphore::try_acquire(&limit));
Semaphore events = Semaphore::new(0);
handle<u32> h = spawn(move [](ref<Semaphore, shared> e) : u32
{
Semaphore::acquire(e);
Semaphore::acquire(e);
Semaphore::acquire(e);
3
}, &events);
Semaphore::release(&events);
Semaphore::release(&events);
Semaphore::release(&events);
assert(join(h) == 3 && Semaphore::available(&events) == 0);Once struct
export struct OnceSomething done once, by whichever thread gets there first.
Shared by reference, as a mutex is. Once::call(&o, f) runs f the first time any thread calls it; every other call, on any thread, returns once that run has finished, without running f: initialising what several threads share, lazily and exactly once. Should f fault, the Once is as before, and the next caller runs f afresh.
Once::new fn
export fn Once::new() : OnceA Once whose f has not run.
Once::call fn
export fn Once::call(ref<Once, shared> o, fn() f)Runs f if no call has run it yet; otherwise waits until the call that is running it has finished.
f runs on the calling thread. After call returns, on any thread, f has run to its end exactly once (unless it faulted, and then the next caller runs it again).
Once::is_done fn
export fn Once::is_done(ref<Once, shared> o) : boolWhether f has run to its end.
Once o = Once::new();
Atomic<u32> runs = Atomic::new(0: u32);
Vec<handle<bool>> hs = Vec::new();
for (u32 i = 0; i < 4; i += 1)
{
Vec::push(&mut hs, spawn(move [](ref<Once, shared> o, ref<Atomic<u32>, shared> runs) : bool
{
Once::call(o, [runs]() { _ = Atomic::fetch_add(runs, 1); });
Once::is_done(o)
}, &o, &runs));
}
foreach (h in hs)
{
assert(join(h));
}
assert(Atomic::load(&runs) == 1 && Once::is_done(&o));cpu_count fn
export fn cpu_count() : usizeHow many threads the machine runs at once, at least 1: the size of a worker pool.
The processors, or what this program may use of them.
try_join fn
export fn try_join<R>(handle<R> h) : Result<R, ThreadFailure>Waits for the thread h and gives its result, or its failure as a value instead of raising it again.
Ok of the thread's result; Err(ThreadFailure) when the thread faulted or was cancelled, and the failure is then taken, so nothing is raised. How a supervisor keeps going when a worker has a bug; join raises the failure instead.
Err, and the fault goes no furtherrunsOption<i32> none = None;
auto h = spawn(Option::unwrap<i32>, none);
match (try_join(h))
{
Ok(_) : assert(false),
Err(f) :
{
String d = ThreadFailure::diagnostic(&f);
assert(d == "diag.unwrap-failed");
assert(!ThreadFailure::is_cancelled(&f));
},
}is_finished fn
export fn is_finished<R>(ref<handle<R>, shared> h) : boolWhether the thread h has ended, its result or failure waiting for join or try_join.
Never waits and takes nothing: how a supervisor finds which of its threads to take.
atomic_fence fn
export fn atomic_fence()A full memory fence: every memory access before it, in this thread, is ordered before every one after it, as seen by any other thread or device.
CobaltC's own operations are already sequentially consistent, so a program that stays within them never needs this. It is for raw and volatile accesses and C code, which are outside that guarantee: the equivalent of C's atomic_thread_fence(memory_order_seq_cst).
spin_hint fn
export fn spin_hint()Tells the processor that this thread is spinning, waiting for another thread to change something.
The CPU's pause instruction: it saves power and lets the other hardware thread of the core run. Call it in the body of a loop that polls an atomic; Atomic::wait blocks instead, for waits that may be long.
fetch_max and fetch_min keep the extremes; fetch_update stores what its function givesrunsAtomic<i32> a = Atomic::new(10: i32);
assert(Atomic::fetch_max(&a, 4) == 10);
assert(Atomic::fetch_max(&a, 25) == 10);
assert(Atomic::fetch_min(&a, 30) == 25);
assert(Atomic::fetch_min(&a, -3) == 25);
assert(Atomic::load(&a) == -3);
assert(Result::unwrap(Atomic::fetch_update(&a, [](i32 x) : Option<i32> { Some(x * 2) })) == -3);
match (Atomic::fetch_update(&a, [](i32 x) : Option<i32> { None }))
{
Ok(_) : assert(false),
Err(v) : assert(v == -6),
}wait until another stores a new value and notifiesrunsAtomicBool done = AtomicBool::new(false);
{
handle<void> h = spawn(move [](ref<AtomicBool, shared> d)
{
AtomicBool::store(d, true);
AtomicBool::notify_all(d);
}, &done);
AtomicBool::wait(&done, false);
join(h);
}
assert(AtomicBool::load(&done));
assert(AtomicBool::swap(&done, false));std::random impl/std/random.cb
Rng struct
export struct RngA general-purpose pseudo-random generator: xoshiro256** seeded through splitmix64.
The same seed gives the same sequence in every implementation, so a run can be reproduced. Not suitable for cryptographic purposes: its state is recoverable from its output, so it must not produce keys, tokens or nonces; use os_random_bytes for those.
Rng::new fn
export fn Rng::new(u64 seed) : RngA generator seeded from seed; equal seeds give equal sequences.
Rng::from_os seeds one unpredictably instead.
Rng::next_u64 fn
export fn Rng::next_u64(ref<Rng, exclusive> r) : u64The next 64 pseudo-random bits from r.
Rng::below fn
export fn Rng::below(ref<Rng, exclusive> r, u64 n) : u64A pseudo-random number from 0 up to, not including, n, each value equally likely.
Unbiased: a draw that would favour some values is rejected and drawn again. Faults (div_by_zero) when n is 0.
Rng::unit_f64 fn
export fn Rng::unit_f64(ref<Rng, exclusive> r) : f64A pseudo-random f64 with 0.0 <= x < 1.0, from the top 53 bits of one draw.
below and unit_f64 stay in their rangesrunsRng a = Rng::new(42);
Rng b = Rng::new(42);
assert(Rng::next_u64(&mut a) == Rng::next_u64(&mut b));
for (usize i = 0; i < 100; i += 1)
{
assert(Rng::below(&mut a, 6) < 6);
f64 x = Rng::unit_f64(&mut a);
assert(x >= 0.0 && x < 1.0);
}Rng::from_os fn
export fn Rng::from_os() : RngA generator seeded from the operating system's secure source, so each run draws a different sequence.
The sequence itself is still Rng's, so it is still not for cryptographic purposes.
Rng::shuffle fn
export fn Rng::shuffle<T>(ref<Rng, exclusive> r, slice<T, exclusive> s)Puts the elements of s in a uniformly random order drawn from r.
Fisher-Yates over Rng::below; elements are exchanged, never copied. The same seed gives the same order in every implementation.
Vec through a slice of it keeps every elementrunsRng r = Rng::new(7);
Vec<i32> v = Vec::new();
for (i32 i = 1; i <= 5; i += 1)
{
Vec::push(&mut v, i);
}
Rng::shuffle(&mut r, &mut v);
assert(Vec::len(&v) == 5 && Vec::contains(&v, 3));os_random_bytes fn
export fn os_random_bytes(slice<u8, exclusive> out)Fills out with bytes from the operating system's cryptographically secure source.
Suitable for keys, tokens and nonces, and for seeding Rng. Faults (entropy_unavailable) when the system has no such source.
os_random_u64 fn
export fn os_random_u64() : u64A u64 from the operating system's cryptographically secure source.
Faults (entropy_unavailable) when the system has no such source.
uuid_v4 fn
export fn uuid_v4() : StringA version 4 UUID (RFC 9562) from the operating system's secure source, as 36 lowercase characters.
The form is xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx, with y one of 8, 9, a, b. Faults (entropy_unavailable) when the system has no secure source.
4 stands at position 14, after the second hyphenrunsString id = uuid_v4();
assert(StringView::len(&id) == 36);
assert(&id[8..9] == "-");
assert(&id[14..15] == "4");std::math impl/std/math.cb
BigUint struct
export struct BigUintAn unsigned integer of any size, for public-key arithmetic and numbers too large for u128.
Each operation gives the exact integer result. The time an operation takes depends on its operands' values, so a BigUint is for public values only, never a private key or anything secret. It owns its digits, so a program reassigns one with overwrite.
BigUint::zero fn
export fn BigUint::zero() : BigUintThe number 0.
BigUint::from_u64 fn
export fn BigUint::from_u64(u64 x) : BigUintThe number x.
BigUint::from_bytes_be fn
export fn BigUint::from_bytes_be(slice<u8, shared> bytes) : BigUintThe number whose big-endian bytes are bytes; leading zero bytes are allowed, and no bytes give 0.
BigUint::to_bytes_be fn
export fn BigUint::to_bytes_be(ref<BigUint, shared> a) : Vec<u8>The big-endian bytes of a, with no leading zero byte; none for zero.
BigUint::to_bytes_be_padded gives a fixed width instead.
BigUint::to_bytes_be_padded fn
export fn BigUint::to_bytes_be_padded(ref<BigUint, shared> a, usize width) : Vec<u8>The big-endian bytes of a in exactly width bytes, zeros in front.
Faults (arith_overflow) when a needs more than width bytes.
BigUint x = BigUint::from_bytes_be(b"\x00\x01\x02");
Vec<u8> min = BigUint::to_bytes_be(&x);
assert(Vec::len(&min) == 2 && min[0] == 1);
Vec<u8> wide = BigUint::to_bytes_be_padded(&x, 4);
assert(Vec::len(&wide) == 4 && wide[0] == 0 && wide[3] == 2);
assert(Vec::len(&BigUint::to_bytes_be(&BigUint::zero())) == 0);BigUint::is_zero fn
export fn BigUint::is_zero(ref<BigUint, shared> a) : boolWhether a is 0.
BigUint::bit_len fn
export fn BigUint::bit_len(ref<BigUint, shared> a) : usizeThe number of bits needed to write a; 0 for zero.
BigUint::bit fn
export fn BigUint::bit(ref<BigUint, shared> a, usize i) : boolWhether bit i of a is set, bit 0 being the least significant; false beyond bit_len.
BigUint::eq fn
export fn BigUint::eq(ref<BigUint, shared> a, ref<BigUint, shared> b) : boolWhether a and b are the same number.
BigUint::less fn
export fn BigUint::less(ref<BigUint, shared> a, ref<BigUint, shared> b) : boolWhether a is less than b; fits Vec::sort_by.
BigUint::add fn
export fn BigUint::add(ref<BigUint, shared> a, ref<BigUint, shared> b) : BigUintThe sum a + b.
BigUint::sub fn
export fn BigUint::sub(ref<BigUint, shared> a, ref<BigUint, shared> b) : BigUintThe difference a - b.
Faults (arith_overflow) when b is greater than a, as for any unsigned subtraction.
BigUint::mul fn
export fn BigUint::mul(ref<BigUint, shared> a, ref<BigUint, shared> b) : BigUintThe product a * b.
BigUint::shift_right fn
export fn BigUint::shift_right(ref<BigUint, shared> a, usize k) : BigUinta divided by 2 to the power k, rounded down.
BigUint::shift_left fn
export fn BigUint::shift_left(ref<BigUint, shared> a, usize k) : BigUinta times 2 to the power k.
BigUint::div_rem fn
export fn BigUint::div_rem(ref<BigUint, shared> a, ref<BigUint, shared> b) : BigDivisionThe quotient of a by b, rounded down, and the remainder, together.
Faults (div_by_zero) when b is 0. BigUint::rem gives only the remainder.
BigDivision is taken apart by destructuringrunsBigUint a = BigUint::from_u64(100);
BigUint b = BigUint::from_u64(7);
BigDivision { quotient, remainder } = BigUint::div_rem(&a, &b);
assert(BigUint::eq("ient, &BigUint::from_u64(14)));
assert(BigUint::eq(&remainder, &BigUint::from_u64(2)));BigUint::rem fn
export fn BigUint::rem(ref<BigUint, shared> a, ref<BigUint, shared> m) : BigUinta modulo m.
Faults (div_by_zero) when m is 0.
BigUint::mod_pow fn
export fn BigUint::mod_pow(ref<BigUint, shared> base, ref<BigUint, shared> exp, ref<BigUint, shared> m) : BigUintbase raised to the power exp, modulo m.
By squaring and multiplying, reducing at each step. Faults (div_by_zero) when m is 0; anything modulo 1 is 0.
BigUint::clone fn
export fn BigUint::clone(ref<BigUint, shared> a) : BigUintA copy of a; what clone(&a) calls for a BigUint.
BigUint::mod_inverse fn
export fn BigUint::mod_inverse(ref<BigUint, shared> a, ref<BigUint, shared> m) : Option<BigUint>The inverse of a modulo m: the number below m whose product with a is 1 modulo m.
None when a and m share a factor above 1, or when m is below 2. Its time depends on the values, as every BigUint operation's does: for public numbers and one-time blinding factors, not a private key.
BigUint m = BigUint::from_u64(11);
match (BigUint::mod_inverse(&BigUint::from_u64(3), &m))
{
Some(x) : assert(BigUint::eq(&x, &BigUint::from_u64(4))),
None : assert(false),
}
assert(Option::is_none(&BigUint::mod_inverse(&BigUint::from_u64(6), &BigUint::from_u64(9))));
BigUint p = BigUint::mod_pow(&BigUint::from_u64(3), &BigUint::from_u64(10), &m);
assert(BigUint::eq(&p, &BigUint::from_u64(1)));BigUint::text fn
export fn BigUint::text(ref<BigUint, shared> a) : Stringa in decimal digits, with no leading zero.
BigUint big = BigUint::shift_left(&BigUint::from_u64(1), 100);
assert(BigUint::bit_len(&big) == 101);
String t = BigUint::text(&big);
assert(t == "1267650600228229401496703205376");
BigUint back = Result::unwrap(BigUint::parse(&t));
assert(BigUint::eq(&back, &big));BigUint::parse fn
export fn BigUint::parse(StringView text) : Result<BigUint, ParseError>The number written in decimal digits in text.
Err(Empty) when text is empty; Err(Invalid(i)) at the first byte i that is not a digit (a sign is not accepted).
BigDivision struct
export struct BigDivisionThe quotient and remainder that BigUint::div_rem gives.
Taken apart by destructuring: BigDivision { quotient, remainder } = BigUint::div_rem(&a, &b);.
min fn
export fn min<T: ordered>(T a, T b) : TThe smaller of a and b; a when they are equal.
max fn
export fn max<T: ordered>(T a, T b) : TThe larger of a and b; a when they are equal.
abs fn
export fn abs<T: number>(T x) : TThe magnitude of x.
Checked: faults (arith_overflow) for a signed type's minimum, whose magnitude does not fit. abs(-0.0) is 0.0, and a NaN stays a NaN.
pow fn
export fn pow<T: number>(T base, u32 exp) : Tbase raised to the power exp, by repeated squaring; pow(x, 0) is 1.
For an integer type the result is exact, and checked: faults (arith_overflow) only when it does not fit in T. For a float base each multiplication rounds, so a large exp can be off by several units in the last place (pow(1.01, 500)); powf is within one unit, and takes a floating-point exponent.
clamp fn
export fn clamp<T: ordered>(T x, T lo, T hi) : Tx held within lo ..= hi: lo when x is below it, hi when above, else x.
Faults (assert_failed) when lo is above hi.
is_nan fn
export fn is_nan<T: number>(T x) : boolWhether x is a NaN, the one value not equal to itself; false for every integer.
is_finite fn
export fn is_finite<T: number>(T x) : boolWhether x is neither a NaN nor an infinity; true for every integer.
gcd fn
export fn gcd<T: integer>(T a, T b) : TThe greatest common divisor of a and b, never negative; gcd(0, 0) is 0.
Euclid's algorithm over the magnitudes, so a signed type's minimum faults (arith_overflow) as in abs.
assert(gcd(-12, 18) == 6);
assert(gcd(0, 0) == 0);
assert(clamp(15, 0, 10) == 10 && clamp(-3, 0, 10) == 0);
assert(pow(3, 4) == 81 && pow(7, 0) == 1);
assert(abs(-0.0) == 0.0 && is_nan(0.0 / 0.0) && !is_finite(1.0 / 0.0));sqrt built in fn
fn sqrt(T x) : TThe square root of x, correctly rounded ([Float-Fn], spec/21 §3d, D-0091): every conforming implementation gives the same bits. A NaN for a negative x; -0.0 for -0.0; a NaN in gives a NaN out.
floor built in fn
fn floor(T x) : Tx rounded to an integral value toward negative infinity, exactly ([Float-Fn]). A NaN or an infinity is returned as it is.
ceil built in fn
fn ceil(T x) : Tx rounded to an integral value toward positive infinity, exactly ([Float-Fn]).
round built in fn
fn round(T x) : Tx rounded to the nearest integral value, halfway cases away from zero (2.5 to 3.0, -2.5 to -3.0), exactly ([Float-Fn]). Convert the result with rule.arith.convert when an integer is wanted.
trunc built in fn
fn trunc(T x) : Tx rounded to an integral value toward zero, exactly ([Float-Fn]): the fractional part dropped.
ln built in fn
fn ln(T x) : TThe natural logarithm of x, within one unit in the last place of the mathematical value ([Float-Transcendental], D-0101): the platform's C library computes it, so the result is the same on one platform and may differ in the last bit between platforms. A NaN for a negative x; negative infinity for ±0.
exp built in fn
fn exp(T x) : Te to the power x, within one unit in the last place ([Float-Transcendental]). Overflows to infinity as IEEE-754 says.
log2 built in fn
fn log2(T x) : TThe base-2 logarithm of x, within one unit in the last place ([Float-Transcendental]); a NaN for a negative x, negative infinity for ±0. For an integer's bit length, integer arithmetic is exact and cheaper.
log10 built in fn
fn log10(T x) : TThe base-10 logarithm of x, within one unit in the last place ([Float-Transcendental]); a NaN for a negative x, negative infinity for ±0.
sin built in fn
fn sin(T x) : TThe sine of x, an angle in radians, within one unit in the last place ([Float-Transcendental]).
cos built in fn
fn cos(T x) : TThe cosine of x, an angle in radians, within one unit in the last place ([Float-Transcendental]).
tan built in fn
fn tan(T x) : TThe tangent of x, an angle in radians, within one unit in the last place ([Float-Transcendental]).
asin built in fn
fn asin(T x) : TThe arc sine of x, in radians in [-π/2, π/2], within one unit in the last place ([Float-Transcendental], D-0181); a NaN for x outside [-1, 1].
acos built in fn
fn acos(T x) : TThe arc cosine of x, in radians in [0, π], within one unit in the last place ([Float-Transcendental], D-0181); a NaN for x outside [-1, 1].
atan built in fn
fn atan(T x) : TThe arc tangent of x, in radians in (-π/2, π/2), within one unit in the last place ([Float-Transcendental], D-0181). For an angle from two coordinates use atan2, which knows the quadrant.
atan2 built in fn
fn atan2(T y, T x) : TThe angle of the point (x, y) from the positive x axis, in radians in (-π, π], within one unit in the last place ([Float-Transcendental-2]); C's atan2. Both operands have the same type.
powf built in fn
fn powf(T x, T y) : Tx to the power y for floating-point operands, within one unit in the last place ([Float-Transcendental-2]); C's pow. pow (an ordinary std::math function, u32 exponent) is exact and checked for overflow for an integer type; for a float base it multiplies by repeated squaring and loses a little at each step, so powf is the more accurate one (powf(1.01, 500.0)).
std::stats impl/std/stats.cb
Summary struct
export struct SummaryWhat describe gives: the count of the values and their minimum, maximum, mean, population standard deviation and median.
sum fn
export fn sum<T: number>(slice<T, shared> data) : TThe sum of data's values in their own type; 0 for an empty slice.
Added left to right with +, so an integer sum that does not fit in T faults (arith_overflow), as + does. For the sum as an f64 whatever T is, multiply mean by the count.
array<i32, 4> a = [3, -1, 4, 1];
assert(sum(&a) == 7);
assert(sum(&a[0..0]) == 0);
array<f64, 3> f = [0.5, 0.25, 2.0];
assert(sum(&f) == 2.75);mean fn
export fn mean<T: number>(slice<T, shared> data) : Option<f64>The arithmetic mean of data's values; None for an empty slice.
Each value is converted to f64 with to_float and the values added left to right, then divided by the count. A NaN among the values makes the mean a NaN.
variance fn
export fn variance<T: number>(slice<T, shared> data) : Option<f64>The population variance of data's values, the mean of the squared deviations from their mean; None for an empty slice.
Two passes: the mean first, then the sum of (x - mean)² left to right, divided by the count. For the variance of a sample drawn from a larger population, use sample_variance.
stddev fn
export fn stddev<T: number>(slice<T, shared> data) : Option<f64>The population standard deviation of data's values, the square root of variance; None for an empty slice.
sample_variance fn
export fn sample_variance<T: number>(slice<T, shared> data) : Option<f64>The sample variance of data's values, the squared deviations from their mean divided by one less than the count (Bessel's correction); None for fewer than two values.
For values that are the whole population, use variance.
sample_stddev fn
export fn sample_stddev<T: number>(slice<T, shared> data) : Option<f64>The sample standard deviation of data's values, the square root of sample_variance; None for fewer than two values.
array<u32, 8> a = [2, 4, 4, 4, 5, 5, 7, 9];
assert(Option::unwrap(variance(&a)) == 4.0);
assert(Option::unwrap(stddev(&a)) == 2.0);
assert(Option::unwrap(sample_variance(&a)) == 32.0 / 7.0);
assert(Option::is_none(&variance(&a[0..0])));
assert(Option::unwrap(variance(&a[0..1])) == 0.0);
assert(Option::is_none(&sample_variance(&a[0..1])));median fn
export fn median<T: number>(slice<T, shared> data) : Option<f64>The median of data's values: the middle one of them sorted, or the mean of the two middle ones when the count is even; None for an empty slice.
The values are copied, converted to f64 and sorted; data is not changed. A NaN is passed over, as minimum and maximum pass it over: the median is that of the other values, and a NaN only when every value is one.
percentile fn
export fn percentile<T: number>(slice<T, shared> data, f64 p) : Option<f64>The pth percentile of data's values, p from 0 to 100, with linear interpolation between the two sorted values it falls between; None for an empty slice.
The position is (count - 1) · p / 100 in the sorted values (R's type 7, the default of spreadsheets and NumPy): percentile(data, 0.0) is the minimum, percentile(data, 100.0) the maximum, and percentile(data, 50.0) the median. A NaN among the values is passed over, as those three pass it over (the result is a NaN only when every value is one). Faults (assert_failed) when p is below 0, above 100 or a NaN.
array<i64, 5> a = [15, 20, 35, 40, 50];
assert(Option::unwrap(percentile(&a, 25.0)) == 20.0);
assert(Option::unwrap(percentile(&a, 40.0)) == 29.0);
assert(Option::unwrap(percentile(&a, 50.0)) == 35.0);
assert(Option::unwrap(median(&a)) == 35.0);
assert(Option::unwrap(median(&a[0..4])) == 27.5);
assert(Option::unwrap(percentile(&a, 0.0)) == 15.0);
assert(Option::unwrap(percentile(&a, 100.0)) == 50.0);
assert(Option::is_none(&median(&a[0..0])));percentile 0 and 100 agree with minimum and maximumrunsf64 nan = 0.0 / 0.0;
array<f64, 4> d = [3.0, nan, 1.0, 2.0];
assert(Option::unwrap(percentile(&d, 100.0)) == 3.0);
assert(Option::unwrap(percentile(&d, 0.0)) == 1.0);
assert(Option::unwrap(median(&d)) == 2.0);
array<f64, 2> all = [nan, nan];
f64 m = Option::unwrap(median(&all));
assert(m != m);minimum fn
export fn minimum<T: number>(slice<T, shared> data) : Option<f64>The smallest of data's values as an f64; None for an empty slice.
A NaN is passed over: the result is a NaN only when every value is one.
maximum fn
export fn maximum<T: number>(slice<T, shared> data) : Option<f64>The largest of data's values as an f64; None for an empty slice.
A NaN is passed over: the result is a NaN only when every value is one.
array<i16, 4> a = [7, -3, 12, 0];
assert(Option::unwrap(minimum(&a)) == -3.0);
assert(Option::unwrap(maximum(&a)) == 12.0);
f64 nan = 0.0 / 0.0;
array<f64, 3> f = [nan, 2.5, 1.5];
assert(Option::unwrap(minimum(&f)) == 1.5);
assert(Option::unwrap(maximum(&f)) == 2.5);
assert(Option::is_none(&minimum(&f[0..0])));describe fn
export fn describe<T: number>(slice<T, shared> data) : Option<Summary>The count, minimum, maximum, mean, stddev and median of data's values as one Summary; None for an empty slice.
array<u32, 6> ms = [12, 15, 11, 40, 13, 14];
Summary s = Option::unwrap(describe(&ms));
assert(s.count == 6 && s.minimum == 11.0 && s.maximum == 40.0);
assert(s.mean == 17.5 && s.median == 13.5);
assert(s.stddev == sqrt(Option::unwrap(variance(&ms))));
assert(Option::is_none(&describe(&ms[0..0])));std::time impl/std/time.cb
DateTime struct
export struct DateTimeA moment in UTC: a date of the proleptic Gregorian calendar and a time of day to the second.
year 0 is 1 BC and -1 is 2 BC; there are no leap seconds, so every day has 86,400 seconds. Any field values can be written in a struct literal: DateTime::new checks them, and DateTime::to_unix faults on a value that names no moment. Keep moments in UTC and convert with DateTime::to_local only for display.
DateTime t = DateTime { .year = -1, .month = 3, .day = 1, .hour = 9, .minute = 5, .second = 0 };
String s = DateTime::to_iso(&t);
assert(s == "-0001-03-01T09:05:00Z");DateTime::from_unix fn
export fn DateTime::from_unix(i64 s) : DateTimeThe moment s seconds after 1970-01-01T00:00:00Z, or before it when s is negative.
Every i64 names a moment, so this never fails.
to_unix gives the count backrunsDateTime t = DateTime::from_unix(-1);
assert(t.year == 1969 && t.month == 12 && t.day == 31);
assert(t.hour == 23 && t.minute == 59 && t.second == 59);
assert(DateTime::to_unix(&t) == -1);DateTime::now fn
export fn DateTime::now() : DateTimeThe moment now by the wall clock, to the second: DateTime::from_unix(unix_seconds()).
DateTime::new fn
export fn DateTime::new(i64 year, u8 month, u8 day, u8 hour, u8 minute, u8 second) : Option<DateTime>The DateTime with these fields, or None when they name no moment.
None for a month 13, a 30 February, a 29 February in a common year, an hour 24 or a second 60. A leap year is divisible by 4 and not by 100, or by 400.
Option<DateTime> leap = DateTime::new(2024, 2, 29, 0, 0, 0);
Option<DateTime> common = DateTime::new(2023, 2, 29, 0, 0, 0);
assert(Option::is_some(&leap));
assert(Option::is_none(&common));DateTime::to_unix fn
export fn DateTime::to_unix(ref<DateTime, shared> t) : i64The seconds from 1970-01-01T00:00:00Z to the moment t, negative before it; the inverse of from_unix.
Faults (invalid_datetime) when the fields of t name no moment, or when the count does not fit in an i64.
DateTime::weekday fn
export fn DateTime::weekday(ref<DateTime, shared> t) : WeekdayThe day of the week of the date of t.
Defined for every valid t, however far from 1970. Faults (invalid_datetime) when the date of t names no day.
DateTime t = DateTime::from_unix(0);
Weekday w = DateTime::weekday(&t);
assert(Weekday::text(&w) == "Thursday");DateTime::to_iso fn
export fn DateTime::to_iso(ref<DateTime, shared> t) : StringThe moment in ISO 8601 form in UTC, such as 2026-10-03T10:17:00Z.
Each field is zero-padded to its width. A year outside 0 ..= 9999 is written with its sign and at least four digits (-0001, +10000). Use iso_from_unix_ms for a timestamp with milliseconds.
DateTime::from_iso fn
export fn DateTime::from_iso(StringView text) : Result<DateTime, ParseError>Reads a moment in ISO 8601 / RFC 3339 form (to_iso's, to_iso_local's), or a date alone (YYYY-MM-DD) as its midnight.
The year is four digits, or a sign and four or more. The date and the time are parted by T (or t, or a space, as PostgreSQL writes them), and the time is HH:MM:SS. The seconds may carry a fraction (:37.25Z), which is dropped; unix_ms_from_iso keeps it to the millisecond. The zone is Z (or z), an offset from UTC, +HH:MM, -HH:MM, +HH or +HHMM, by which the moment is converted to UTC (2024-03-10T03:30:00-04:00 is 2024-03-10T07:30:00Z), or nothing: a time without a zone is read as its fields as written (a DateTime knows no zone; std::time takes it as UTC). No other form is read.
Err(Empty)for the empty text.Err(Invalid(i)): byteiis the first that does not fit the form (the length when the text stops short).Err(OutOfRange): the fields name no moment (a month 13, a 29 February in a common year, a second 60, an offset of 24 hours or more or with a minute past 59), or the moment is too far from 1970 forto_unix(its seconds do not fit in ani64), so aDateTimeread here can always be converted.
Invalid at its endrunsmatch (DateTime::from_iso("2026-10-03"))
{
Ok(t) : assert(t.day == 3 && t.hour == 0),
Err(_) : assert(false),
}
match (DateTime::from_iso("2026-10-03T10:17"))
{
Err(Invalid(i)) : assert(i == 16),
_ : assert(false),
}timestamptz text readsrunsString z = DateTime::to_iso(&Result::unwrap(DateTime::from_iso("2024-03-10T03:30:00-04:00")));
assert(z == "2024-03-10T07:30:00Z");
z = DateTime::to_iso(&Result::unwrap(DateTime::from_iso("2023-11-15 09:13:20+11")));
assert(z == "2023-11-14T22:13:20Z");
z = DateTime::to_iso(&Result::unwrap(DateTime::from_iso("2023-11-14 22:13:20")));
assert(z == "2023-11-14T22:13:20Z");
z = DateTime::to_iso(&Result::unwrap(DateTime::from_iso("2020-01-01T00:10:00+0530")));
assert(z == "2019-12-31T18:40:00Z");
assert(unix_ms_from_iso("2023-11-14 22:13:20.5+00") == Ok(1700000000500));
match (DateTime::from_iso("2024-03-10T03:30:00+24:00"))
{
Err(OutOfRange) : {},
_ : assert(false),
}
match (DateTime::from_iso("2024-03-10T03:30:00+4"))
{
Err(Invalid(i)) : assert(i == 21),
_ : assert(false),
}DateTime::eq fn
export fn DateTime::eq(ref<DateTime, shared> a, ref<DateTime, shared> b) : boolWhether a and b are the same moment, every field equal.
DateTime::less fn
export fn DateTime::less(ref<DateTime, shared> a, ref<DateTime, shared> b) : boolWhether a is earlier than b, comparing the fields in order of significance.
For valid values this is the order of to_unix. It fits Vec::sort_by.
less orders moments by time, and eq tells them apartrunsDateTime a = DateTime::from_unix(100);
DateTime b = DateTime::from_unix(160);
assert(DateTime::less(&a, &b));
assert(!DateTime::less(&b, &a));
assert(!DateTime::eq(&a, &b));DateTime::to_local fn
export fn DateTime::to_local(ref<DateTime, shared> t) : DateTimeThe moment t, given in UTC, written in the machine's local time.
The result is a DateTime like any other and knows nothing of its zone: print its fields, not to_iso (which writes Z; DateTime::to_iso_local writes a local time with its offset), and keep the UTC value for arithmetic, since to_unix of the result is the moment plus the offset. Faults (invalid_datetime) when t names no moment, or when the moment is within a day of an i64 limit.
DateTime::to_iso_local fn
export fn DateTime::to_iso_local(ref<DateTime, shared> t) : StringThe moment t, given in UTC, in ISO 8601 form in the machine's local time with its offset from UTC.
Such as 2024-03-10T03:30:00-04:00 for 2024-03-10T07:30:00Z in New York; +00:00 where local time is UTC. The text names the same moment as to_iso's, so DateTime::from_iso and any other reader of ISO 8601 get t back (an offset that is not a whole number of minutes, which no zone has used since 1972, is cut to the minute, and the time with it). The offset is local_offset_seconds's at that moment. Faults as DateTime::to_local.
DateTime::to_http_date fn
export fn DateTime::to_http_date(ref<DateTime, shared> t) : StringThe moment in HTTP's date form, such as Sun, 06 Nov 1994 08:49:37 GMT.
The form (RFC 9110 §5.6.7, the IMF-fixdate) is what the Date, Last-Modified and Expires headers carry. Faults (invalid_datetime) for a year outside 0 ..= 9999, or fields that name no moment.
DateTime t = DateTime::from_unix(784111777);
assert(DateTime::to_http_date(&t) == "Sun, 06 Nov 1994 08:49:37 GMT");DateTime::from_http_date fn
export fn DateTime::from_http_date(StringView text) : Result<DateTime, ParseError>Reads an HTTP date in any of the three forms a recipient must accept (RFC 9110 §5.6.7).
The forms are Sun, 06 Nov 1994 08:49:37 GMT (the one to send), the obsolete RFC 850 Sunday, 06-Nov-94 08:49:37 GMT (a two-digit year: 70 to 99 are 1970 to 1999, 00 to 69 are 2000 to 2069) and asctime's Sun Nov 6 08:49:37 1994. The words are separated by ASCII whitespace; the weekday is not checked against the date.
Err(Empty)when the text has no words.Err(Invalid(i)):iis the start of the first word that does not fit (a zone other thanGMT, a word after the last), or the text's length when it stops short.Err(OutOfRange): the fields name no moment.
match (DateTime::from_http_date("Sunday, 06-Nov-94 08:49:37 GMT"))
{
Ok(t) : assert(t.year == 1994 && t.month == 11 && t.day == 6),
Err(_) : assert(false),
}Weekday enum
export enum WeekdayA day of the week, Monday to Sunday.
Weekday::text fn
export fn Weekday::text(ref<Weekday, shared> w) : strThe day's English name (Monday).
unix_ms fn
export fn unix_ms() : i64The wall clock in milliseconds since 1970-01-01T00:00:00Z, rounded down.
unix_ms() / 1000 is unix_seconds() when read together. The wall clock may be changed while the program runs; measure elapsed time with monotonic_ns.
local_offset_seconds fn
export fn local_offset_seconds(i64 unix) : i64How many seconds the machine's local time is ahead of UTC at the moment unix seconds after 1970.
Negative when local time is behind UTC; daylight saving included, by the operating system's rule for the zone the program runs in. Between -64800 and 64800. For a moment the system has no rule for, the offset now. It differs between machines, and on one machine between moments.
monotonic_ns fn
export fn monotonic_ns() : u64Nanoseconds on a monotonic clock, from a start fixed for the whole program.
The clock never goes backwards, so the difference of two readings measures how long something took. Its values mean nothing else; use unix_ms for the time of day.
unix_seconds fn
export fn unix_seconds() : i64The wall clock: whole seconds since 1970-01-01T00:00:00Z.
The wall clock may be changed while the program runs; measure elapsed time with monotonic_ns.
sleep_ms fn
export fn sleep_ms(u64 ms)Makes the calling thread do nothing for at least ms milliseconds; other threads run meanwhile.
iso_from_unix_ms fn
export fn iso_from_unix_ms(i64 ms) : StringThe moment ms milliseconds after 1970-01-01T00:00:00Z in to_iso's form, with milliseconds.
The form is 2026-10-07T12:34:56.789Z, a log line's or a JSON document's timestamp. A negative ms is before 1970, the milliseconds still counted forward within their second.
assert(iso_from_unix_ms(-1) == "1969-12-31T23:59:59.999Z");unix_ms_from_iso fn
export fn unix_ms_from_iso(StringView text) : Result<i64, ParseError>The milliseconds since 1970-01-01T00:00:00Z of a moment in DateTime::from_iso's form.
A fraction of the seconds is kept to the millisecond: its first three digits, fewer filled with zeros, further digits ignored (.5 is 500, .1234 is 123). The errors are from_iso's; Err(OutOfRange) also when the milliseconds do not fit in an i64.
assert(unix_ms_from_iso("1970-01-01T00:00:01.5Z") == Ok(1500));
assert(unix_ms_from_iso("1970-01-01T00:00:00.1239Z") == Ok(123));std::process impl/std/process.cb
Command struct
export struct CommandA program to run: its name or path, its arguments, its working directory and its environment.
Made by Command::new, changed by arg, current_dir, env and clear_env, and run by output, output_with_input, status or spawn, any number of times. No shell is involved: each argument reaches the program exactly as given, with no splitting, quoting or expansion; a program that wants a shell runs one by name (/bin/sh with -c).
Running fails with Err(NotFound) when there is no such program or no such working directory, Err(Denied) when it may not be run, and Err(Io) for any other failure to start it.
Command::new fn
export fn Command::new(StringView program) : CommandA command running program with no arguments, in this program's working directory and environment.
A name without a separator is looked for on PATH, as the system does.
Command::arg fn
export fn Command::arg(ref<Command, exclusive> c, StringView a)Appends one argument, passed to the program exactly as given.
Command::current_dir fn
export fn Command::current_dir(ref<Command, exclusive> c, StringView dir)Sets the working directory the program starts in.
A directory that does not exist makes the run fail with Err(NotFound), as a missing program does.
Command::env fn
export fn Command::env(ref<Command, exclusive> c, StringView name, StringView value)Sets the environment variable name to value for the program.
The variables set this way go on top of the inherited environment, or of an empty one after Command::clear_env. A name that is empty or holds =, or a NUL in the name or the value, makes a run fail with Err(Io): such a name would set another variable in the child.
Command::clear_env fn
export fn Command::clear_env(ref<Command, exclusive> c)Makes the program start with no environment variables but those Command::env sets.
Command::output fn
export fn Command::output(ref<Command, shared> c) : Result<Output, FileError>Runs the program to its end with an empty standard input, and gives its status and everything it wrote.
Both streams are read at once, so neither pipe fills and stops the program.
Command::output_with_input fn
export fn Command::output_with_input(ref<Command, shared> c, slice<u8, shared> input) : Result<Output, FileError>Runs the program to its end with input as its standard input, as Command::output does.
Command::status fn
export fn Command::status(ref<Command, shared> c) : Result<i32, FileError>Runs the program to its end with this program's standard input, output and error, and gives its status.
The status is Output::status's: the exit code, or on Unix minus the signal that ended it.
Command::spawn fn
export fn Command::spawn(ref<Command, shared> c) : Result<Child, FileError>Starts the program and returns at once, its three streams pipes to this program.
A pipe holds only so much (64 KiB on Linux): a child that writes more stops until this program reads it, so read its output (Child::read_output, read_output_line, or Child::take_output in another thread) before Child::wait, or use Command::output, which reads both streams while it waits.
Output struct
export struct OutputHow a run of Command::output ended, and everything the program wrote.
status: the exit code, or on Unix minus the number of the signal that ended it (-9for SIGKILL).stdout: every byte the program wrote to its standard output.stderr: every byte the program wrote to its standard error.
Child struct
export resource struct ChildA running child process, its standard input, output and error each a pipe to this program.
Made by Command::spawn. Destroying a Child closes its pipes but does not end it: a running child runs on. On Unix a destroyed child is still reaped, at once when it was killed and otherwise once it has ended (by the next start or destruction of a child), so it leaves no zombie. A child that fills a pipe nobody reads stops until it is read, so read its output before Child::wait, or use Command::output. Child::take_input and Child::take_output move its pipes out, for use from other threads.
Child::id fn
export fn Child::id(ref<Child, shared> ch) : u64The operating system's number for the child (its process id).
Child::write_input fn
export fn Child::write_input(ref<Child, exclusive> ch, slice<u8, shared> data) : Result<void, FileError>Writes all of data to the child's standard input.
Err(Io) when the child has ended or closed its input; it never ends this program. Does nothing once Child::take_input has taken the input.
Child::close_input fn
export fn Child::close_input(ref<Child, exclusive> ch)Closes the child's standard input, so that the child reads its end.
Does nothing once Child::take_input has taken the input.
Child::read_output fn
export fn Child::read_output(ref<Child, exclusive> ch, ref<Vec<u8>, exclusive> buf, usize max) : Result<usize, FileError>Appends to buf what has arrived on the child's standard output, up to max bytes, and returns how many.
Waits for at least one byte; at most a MiB is read at a time. Ok(0) (for a max above 0) means the end of the output.
Child::read_output_line fn
export fn Child::read_output_line(ref<Child, exclusive> ch) : Result<Option<String>, FileError>The next line of the child's standard output, without its '\n' or a '\r' just before it.
Ok(None) at the end of the output; Err(Utf8(e)) for a line that is not UTF-8.
Child::read_error fn
export fn Child::read_error(ref<Child, exclusive> ch, ref<Vec<u8>, exclusive> buf, usize max) : Result<usize, FileError>Appends to buf what has arrived on the child's standard error, as Child::read_output does.
What Child::read_error_line has read ahead comes first.
Child::read_error_line fn
export fn Child::read_error_line(ref<Child, exclusive> ch) : Result<Option<String>, FileError>The next line of the child's standard error, as Child::read_output_line reads standard output.
Each stream is read ahead on its own.
Child::wait fn
export fn Child::wait(ref<Child, exclusive> ch) : Result<i32, FileError>Closes the child's standard input, waits for the child to end and gives its status.
The status is Output::status's. Asked again, it gives the same status. It does not read the child's output: a child that fills its output pipe before it ends waits for a reader, and then wait never returns. Read the output to its end first, or use Command::output.
Child::try_wait fn
export fn Child::try_wait(ref<Child, exclusive> ch) : Result<Option<i32>, FileError>The child's status if it has ended, without waiting.
Ok(None) while it runs.
Child::kill fn
export fn Child::kill(ref<Child, exclusive> ch) : Result<void, FileError>Ends the child at once (SIGKILL on Unix, TerminateProcess on Windows).
Child::wait then gives its status. Nothing happens to a child that has already ended. Use Child::terminate to let the child stop cleanly, and Child::kill_tree to end the processes it started too.
Child::kill_tree fn
export fn Child::kill_tree(ref<Child, exclusive> ch) : Result<void, FileError>Ends the child and every process it started, and theirs in turn.
On Linux the processes are found from /proc; on Windows by taskkill /T; elsewhere only the child is ended, as Child::kill ends it. Child::wait then gives its status. A process that has left the tree before the call is not reached: one that forked twice to become a daemon now has init as its parent, and nothing links it to the child.
Child::terminate fn
export fn Child::terminate(ref<Child, exclusive> ch) : Result<void, FileError>Asks the child to end: SIGTERM on Unix, which a program may catch to stop cleanly.
On Windows it ends the child as Child::kill does. On Unix the status Child::wait then gives is -15, unless the child handles the signal. Nothing happens, and Ok(()) is returned, for a child that has already ended.
Child::drop fn
export fn Child::drop(ref<Child, exclusive> self)Closes the child's pipes when its Child is destroyed, leaving the child running.
The destructor; programs do not call it. On Unix the process is reaped all the same: at once when it was killed (Child::kill, kill_tree), otherwise once it has ended, when the next child is started or destroyed, so it leaves no zombie.
Child::take_input fn
export fn Child::take_input(ref<Child, exclusive> ch) : Option<ChildInput>The child's standard input, moved out of the Child.
Child::write_input and Child::close_input then do nothing. None when the input was taken or closed already.
Child::take_output fn
export fn Child::take_output(ref<Child, exclusive> ch) : Option<ChildOutput>The child's standard output, moved out of the Child with whatever was read ahead.
Child::read_output then finds the end. None when the output was taken already.
ChildInput struct
export resource struct ChildInputA child's standard input as a value of its own, taken out of its Child by Child::take_input.
It is independent of the Child and of the child's output, and outlives the Child, so one thread can write a child's input while another reads its output (or one child's output can feed another's input). Destroying it closes the pipe, and the child reading its input then finds its end.
ChildInput::write fn
export fn ChildInput::write(ref<ChildInput, exclusive> p, slice<u8, shared> data) : Result<void, FileError>Writes all of data to the child's standard input, as Child::write_input does.
ChildInput::drop fn
export fn ChildInput::drop(ref<ChildInput, exclusive> self)Closes the pipe when its ChildInput is destroyed, so the child reads the end of its input.
The destructor; programs do not call it.
ChildOutput struct
export resource struct ChildOutputA child's standard output as a value of its own, taken out of its Child by Child::take_output.
It is independent of the Child and of the child's input, and outlives the Child. Destroying it closes the pipe.
ChildOutput::read fn
export fn ChildOutput::read(ref<ChildOutput, exclusive> p, ref<Vec<u8>, exclusive> buf, usize max) : Result<usize, FileError>Appends to buf what has arrived on the child's standard output, up to max bytes, and returns how many.
As Child::read_output: at most a MiB at a time, and Ok(0) (for a max above 0) only at the end.
ChildOutput::read_line fn
export fn ChildOutput::read_line(ref<ChildOutput, exclusive> p) : Result<Option<String>, FileError>The next line of the child's standard output, as Child::read_output_line reads it.
ChildOutput::drop fn
export fn ChildOutput::drop(ref<ChildOutput, exclusive> self)Closes the pipe when its ChildOutput is destroyed.
The destructor; programs do not call it.
process_id fn
export fn process_id() : u64The operating system's number for this program (its process id), as a pid file records it.
watch_interrupts fn
export fn watch_interrupts()From now on, makes an interrupt set the flag interrupt_requested reads instead of ending the program.
An interrupt is SIGINT or SIGTERM on Unix; Ctrl-C, Ctrl-Break or closing the console on Windows. A blocking socket call returns early on an interrupt the program has not seen yet, one that arrives while it waits or since the program last called interrupt_requested (accept and a socket's read give Err(TimedOut)), so a long-running loop checks the flag and stops cleanly. Once the program has seen the flag set, its later calls wait as usual, so a clean shutdown can finish its exchanges, until another interrupt arrives. A socket call already waiting when an interrupt arrives returns early even if another thread has seen the flag since. An interrupt that arrives while the previous one is still unseen (the program has not called interrupt_requested since) ends the program as without watch_interrupts: pressing Ctrl-C twice stops a program blocked in read_line or a long computation. There is no callback.
interrupt_requested fn
export fn interrupt_requested() : boolWhether an interrupt has arrived since watch_interrupts was called.
exit built in fn
fn exit(u8 status) : neverEnds the program with exit status status ([Exit], spec/21 §2k, D-0150). The calling thread unwinds first, so its destructors run and standard output is written out; other threads are not waited for. The result type is never, so a branch that calls exit needs no value of its own. fn main() : u8's return value is the ordinary way to set the status; exit is for deep inside a program.
std::net impl/std/net.cb
IpAddr enum
export enum IpAddrAn IP address: IPv4 (V4, four bytes) or IPv6 (V6, sixteen bytes).
The bytes are in the order the text writes them: 127.0.0.1 is V4([127, 0, 0, 1]).
IpAddr::localhost_v4 fn
export fn IpAddr::localhost_v4() : IpAddrThe IPv4 loopback address, 127.0.0.1.
IpAddr::unspecified_v4 fn
export fn IpAddr::unspecified_v4() : IpAddrThe IPv4 unspecified address, 0.0.0.0.
A listener bound to it accepts connections to any of the machine's IPv4 addresses.
IpAddr::localhost_v6 fn
export fn IpAddr::localhost_v6() : IpAddrThe IPv6 loopback address, ::1.
IpAddr::unspecified_v6 fn
export fn IpAddr::unspecified_v6() : IpAddrThe IPv6 unspecified address, ::.
IpAddr::parse fn
export fn IpAddr::parse(StringView text) : Result<IpAddr, ParseError>Reads an IP address from its text, as the platform's library does.
Accepts dotted decimal (127.0.0.1) and RFC 4291 IPv6 with :: (::1, 2001:db8::8a2e:370:7334, ::ffff:192.0.2.1), without brackets or a port. Err(Empty) for "", Err(Invalid(0)) for any other text that is not an address.
IpAddr::text fn
export fn IpAddr::text(ref<IpAddr, shared> ip) : StringThe address as text: dotted decimal, or IPv6 in RFC 5952's shortest form (::1).
IpAddr ip = Result::unwrap(IpAddr::parse("2001:db8:0:0:0:0:0:1"));
assert(IpAddr::text(&ip) == "2001:db8::1");
assert(IpAddr::text(&IpAddr::localhost_v4()) == "127.0.0.1");
assert(Result::is_err(&IpAddr::parse("256.0.0.1")));SocketAddr struct
export struct SocketAddrAn IP address and a port: where a socket is bound or connected.
SocketAddr::new fn
export fn SocketAddr::new(IpAddr ip, u16 port) : SocketAddrThe socket address of ip and port.
SocketAddr::parse fn
export fn SocketAddr::parse(StringView text) : Result<SocketAddr, ParseError>Reads an address and a port written a.b.c.d:port or [v6]:port.
Err(Empty)for "".Err(Invalid(i))at the first byte that does not fit;iis the address's first byte when the address is not one (an IPv6 address must be in brackets, an IPv4 address must not).Err(OutOfRange)for a port above 65535.
: is where the text stops fittingrunsSocketAddr a = Result::unwrap(SocketAddr::parse("[::1]:8080"));
assert(a.port == 8080);
assert(SocketAddr::text(&a) == "[::1]:8080");
match (SocketAddr::parse("::1:8080"))
{
Err(Invalid(i)) : assert(i == 0),
_ : assert(false),
}
assert(Result::is_err(&SocketAddr::parse("127.0.0.1:70000")));SocketAddr::text fn
export fn SocketAddr::text(ref<SocketAddr, shared> a) : StringThe address and port as text, in the forms SocketAddr::parse reads: 127.0.0.1:8080, [::1]:8080.
NetError enum
export enum NetErrorWhy a socket operation failed.
Refused: nothing listens at the address connected to.Reset: the peer reset the connection.TimedOut: the socket's timeout passed; the socket is still usable.Unreachable: the address cannot be reached.AddrInUse: the address to bind is already in use.AddrNotAvailable: the address to bind cannot be used on this machine.UnknownHost: the name resolves to nothing or cannot be resolved.NotPermitted: the system denied permission.Closed: the peer has gone while writing, or aread_exactwas cut short.NoDescriptors: the program, or the system, has as many files and sockets open as it may.MessageTooLong: a datagram is larger than the socket can send.Failed: any other failure.NotUtf8(e): a lineread_lineread is not UTF-8.
No variant shares a name with FileError's, so either may be written unqualified.
NetError::text fn
export fn NetError::text(ref<NetError, shared> e) : strA short description of the error, in lower case, for messages.
TcpListener struct
export resource struct TcpListenerA socket that listens for TCP connections; accept gives each one as a TcpStream.
Dropping it closes the socket.
TcpListener::bind fn
export fn TcpListener::bind(SocketAddr a) : Result<TcpListener, NetError>Listens for TCP connections at a.
Port 0 asks the system for a free port, which local_addr names. Err(AddrInUse), Err(AddrNotAvailable) or Err(NotPermitted) when the address cannot be bound.
TcpListener::local_addr fn
export fn TcpListener::local_addr(ref<TcpListener, shared> l) : SocketAddrThe address the listener is bound to, with the port the system chose when bind asked for port 0.
TcpListener::set_accept_timeout_ms fn
export fn TcpListener::set_accept_timeout_ms(ref<TcpListener, exclusive> l, u64 ms)Sets how long accept waits for a connection, in milliseconds; 0 waits for ever.
After the timeout accept gives Err(TimedOut) and the listener is still usable. A server loop that checks interrupt_requested() sets one.
TcpListener::accept fn
export fn TcpListener::accept(ref<TcpListener, exclusive> l) : Result<TcpStream, NetError>Waits for the next connection made to the listener and gives its stream.
Err(TimedOut) when the accept timeout (set_accept_timeout_ms) passes first.
TcpListener::drop fn
export fn TcpListener::drop(ref<TcpListener, exclusive> self)Closes the listening socket; run when a TcpListener is dropped.
TcpStream struct
export resource struct TcpStreamA TCP connection: a stream of bytes each way.
The bytes on the wire are exactly those written, in order, with no framing or encoding added, and a read gives whatever part of them has arrived. Calls block until they complete or the stream's timeout passes (set_read_timeout_ms, set_write_timeout_ms). Dropping the stream closes it; the connection closes when the last stream on it (try_clone) is dropped. Formatted text is sent with TcpStream::printf(s, format, …), as File::printf writes to a file.
TcpStream::connect fn
export fn TcpStream::connect(SocketAddr a) : Result<TcpStream, NetError>Connects to a, waiting as long as the system does.
Err(Refused) when nothing listens there, Err(TimedOut), Err(Unreachable). connect_timeout bounds the wait.
TcpStream::connect_timeout fn
export fn TcpStream::connect_timeout(SocketAddr a, u64 ms) : Result<TcpStream, NetError>Connects to a, waiting at most ms milliseconds.
Err(TimedOut) when the time passes first; an ms of 0 is taken as 1. Other errors as connect's.
TcpStream::peer_addr fn
export fn TcpStream::peer_addr(ref<TcpStream, shared> s) : SocketAddrThe address of the other end of the connection.
TcpStream::local_addr fn
export fn TcpStream::local_addr(ref<TcpStream, shared> s) : SocketAddrThe local address of the connection.
TcpStream::set_read_timeout_ms fn
export fn TcpStream::set_read_timeout_ms(ref<TcpStream, exclusive> s, u64 ms)Sets how long a read waits for data, in milliseconds; 0 waits for ever.
A read, read_exact or read_line that waits longer gives Err(TimedOut), and the stream stays usable.
TcpStream::set_write_timeout_ms fn
export fn TcpStream::set_write_timeout_ms(ref<TcpStream, exclusive> s, u64 ms)Sets how long a write may wait to go on, in milliseconds; 0 waits for ever.
A write that cannot go on for that long gives Err(TimedOut), and the stream stays usable.
TcpStream::set_nodelay fn
export fn TcpStream::set_nodelay(ref<TcpStream, exclusive> s, bool on)Sets whether small writes are sent at once (true) or gathered for a moment into fewer packets.
Gathering (false) is the default.
TcpStream::read fn
export fn TcpStream::read(ref<TcpStream, exclusive> s, ref<Vec<u8>, exclusive> buf, usize max) : Result<usize, NetError>Appends up to max bytes of what has arrived to buf, and gives how many.
Waits until at least one byte has arrived, and reads at most a MiB in one call. With max > 0 it gives 0 exactly when the peer has closed its sending side.
TcpStream::read_exact fn
export fn TcpStream::read_exact(ref<TcpStream, exclusive> s, ref<Vec<u8>, exclusive> buf, usize n) : Result<void, NetError>Appends exactly n bytes to buf, reading until they have all arrived.
Err(Closed) when the peer closes first; what arrived before that stays in buf.
TcpStream::read_line fn
export fn TcpStream::read_line(ref<TcpStream, exclusive> s) : Result<Option<String>, NetError>The next line from the connection, without its \n (nor a \r before it).
Ok(None) when the peer has closed its side; Err(NotUtf8(e)) for a line that is not UTF-8. Reads as File::read_line does.
TcpStream::write fn
export fn TcpStream::write(ref<TcpStream, exclusive> s, slice<u8, shared> data) : Result<void, NetError>Sends all of data.
Err(Closed) or Err(Reset) when the peer has gone; Err(TimedOut) after the write timeout.
TcpStream::write_text fn
export fn TcpStream::write_text(ref<TcpStream, exclusive> s, StringView text) : Result<void, NetError>Sends the bytes of text, as write does.
TcpStream::shutdown_write fn
export fn TcpStream::shutdown_write(ref<TcpStream, exclusive> s) : Result<void, NetError>Closes the sending side of the connection; this side can still read.
The peer reads the end (0) after what was sent. Through any stream of a try_cloned pair it ends sending for all of them.
TcpStream::drop fn
export fn TcpStream::drop(ref<TcpStream, exclusive> self)Closes this stream, and the connection when no other stream (try_clone) is on it.
Run when a TcpStream is dropped.
TcpStream::set_keepalive fn
export fn TcpStream::set_keepalive(ref<TcpStream, exclusive> s, bool on)Turns TCP keepalive on or off for the connection.
With it on, the system probes an idle connection by its own schedule (after a couple of hours, by default), so a peer or a path that has silently gone makes a later read fail rather than wait for ever.
TcpStream::try_clone fn
export fn TcpStream::try_clone(ref<TcpStream, shared> s) : Result<TcpStream, NetError>A second TcpStream on the same connection, for reading in one thread while another writes.
Each thread takes its own stream by move. Bytes read through one are not seen by the other, and each has its own timeouts; shutdown_write through either ends sending for both, and the connection closes when the last of them is dropped.
TcpStream::printf built in fn
fn TcpStream::printf(ref<TcpStream, exclusive> s, str format, a1, …, an) : Result<void, NetError>Writes the formatted text to the connected stream *s, as File::printf does to a file; the whole text is written or the Err says why ([Stream-Write]). A line protocol's reply in one call: TcpStream::printf(&mut c, "%d %s\r\n", code, text)?.
UdpSocket struct
export resource struct UdpSocketA UDP socket: it sends and receives datagrams of up to about 64 KiB, each delivered whole or not at all.
The network may lose, duplicate or reorder datagrams; on loopback it does not. Dropping the socket closes it.
UdpSocket::bind fn
export fn UdpSocket::bind(SocketAddr a) : Result<UdpSocket, NetError>Opens a UDP socket bound to a; port 0 asks the system for a free port.
Errors as TcpListener::bind's.
UdpSocket::try_clone fn
export fn UdpSocket::try_clone(ref<UdpSocket, shared> u) : Result<UdpSocket, NetError>A second handle on the same socket, as TcpStream::try_clone gives one.
A thread can wait for datagrams on one handle while others send on another.
UdpSocket::local_addr fn
export fn UdpSocket::local_addr(ref<UdpSocket, shared> u) : SocketAddrThe address the socket is bound to, with the port the system chose for port 0.
UdpSocket::set_read_timeout_ms fn
export fn UdpSocket::set_read_timeout_ms(ref<UdpSocket, exclusive> u, u64 ms)Sets how long recv_from and recv wait for a datagram, in milliseconds; 0 waits for ever.
After the timeout they give Err(TimedOut), and the socket stays usable.
UdpSocket::send_to fn
export fn UdpSocket::send_to(ref<UdpSocket, exclusive> u, slice<u8, shared> data, SocketAddr to) : Result<usize, NetError>Sends data as one datagram to to, and gives the number of bytes sent.
UdpSocket::recv_from fn
export fn UdpSocket::recv_from(ref<UdpSocket, exclusive> u, usize max) : Result<Datagram, NetError>Waits for the next datagram and gives its first max bytes and its sender.
The rest of a datagram longer than max is lost. Err(TimedOut) after the read timeout.
UdpSocket::drop fn
export fn UdpSocket::drop(ref<UdpSocket, exclusive> self)Closes the socket; run when a UdpSocket is dropped.
UdpSocket::connect fn
export fn UdpSocket::connect(ref<UdpSocket, exclusive> u, SocketAddr to) : Result<void, NetError>Fixes the peer that send sends to and recv receives from.
A datagram from any other address is then dropped. send_to and recv_from still work.
UdpSocket::send fn
export fn UdpSocket::send(ref<UdpSocket, exclusive> u, slice<u8, shared> data) : Result<usize, NetError>Sends data as one datagram to the connected peer, and gives the number of bytes sent.
Err(Failed) on a socket that is not connected (connect).
UdpSocket::recv fn
export fn UdpSocket::recv(ref<UdpSocket, exclusive> u, usize max) : Result<Vec<u8>, NetError>Waits for the next datagram from the connected peer and gives its first max bytes.
The rest of a longer datagram is lost. Err(Failed) on a socket that is not connected (connect).
Datagram struct
export struct DatagramA datagram received: its bytes (data) and its sender (from).
resolve fn
export fn resolve(StringView host, u16 port) : Result<Vec<SocketAddr>, NetError>The socket addresses host names, each with port, through the system's resolver.
The resolver reads its hosts file, then DNS, and the addresses come in its order; "localhost" resolves without a network. Err(UnknownHost) when the name resolves to nothing or cannot be resolved. The call blocks until the resolver answers.
std::crypto::digest impl/std/crypto/digest.cb
Sha256 struct
export struct Sha256A SHA-256 computation in progress (FIPS 180-4).
Make one with Sha256::new, give it the message with Sha256::update as the message arrives, and take the 32-byte digest with Sha256::finish; the digest is the same however the message is cut. A Sha256 is a plain value, so a copy continues on its own: copy one to hash two continuations of one prefix.
Not independently audited: std::crypto is implemented to the standards its documentation names, tested against their vectors and against OpenSSL, and fuzzed continuously, but it has not been independently audited.
Sha256 s = Sha256::new();
Sha256::update(&mut s, b"ab");
Sha256 copy = s;
Sha256::update(&mut s, b"c");
Sha256::update(&mut copy, b"d");
array<u8, 32> abc = Sha256::finish(s);
array<u8, 32> abd = Sha256::finish(copy);
assert(digest_eq(&abc, &sha256(b"abc")));
assert(digest_eq(&abd, &sha256(b"abd")));Sha256::new fn
export fn Sha256::new() : Sha256A SHA-256 computation that has been given nothing yet.
Sha256::update fn
export fn Sha256::update(ref<Sha256, exclusive> s, slice<u8, shared> data)Adds data to the message being hashed.
Call it as often as the message arrives; the pieces are hashed as their concatenation.
Sha256::finish fn
export fn Sha256::finish(Sha256 s) : array<u8, 32>The 32-byte SHA-256 digest of everything given to s.
s is consumed; copy it first to go on hashing.
Sha512 struct
export struct Sha512A SHA-512 computation in progress (FIPS 180-4).
Used as Sha256 is: Sha512::new, Sha512::update as often as needed, then Sha512::finish for the 64-byte digest. A plain value: a copy continues on its own.
Sha512::new fn
export fn Sha512::new() : Sha512A SHA-512 computation that has been given nothing yet.
Sha512::update fn
export fn Sha512::update(ref<Sha512, exclusive> s, slice<u8, shared> data)Adds data to the message being hashed.
Sha512::finish fn
export fn Sha512::finish(Sha512 s) : array<u8, 64>The 64-byte SHA-512 digest of everything given to s.
Sha384 struct
export struct Sha384A SHA-384 computation in progress (FIPS 180-4).
SHA-512 with its own initial values and the digest cut to 48 bytes; used as Sha256 is. A plain value: a copy continues on its own.
Sha384::new fn
export fn Sha384::new() : Sha384A SHA-384 computation that has been given nothing yet.
Sha384::update fn
export fn Sha384::update(ref<Sha384, exclusive> s, slice<u8, shared> data)Adds data to the message being hashed.
Sha384::finish fn
export fn Sha384::finish(Sha384 s) : array<u8, 48>The 48-byte SHA-384 digest of everything given to s.
Sha1 struct
export struct Sha1A SHA-1 computation in progress (FIPS 180-4), for legacy protocols only.
Used as Sha256 is, with a 20-byte digest. It is here for what older protocols still require (HMAC-SHA-1 in RFC 6238's TOTP, git's object names, old signatures to check), never for a new signature or anything whose collision resistance matters: SHA-1 collisions have been made.
Sha1::new fn
export fn Sha1::new() : Sha1A SHA-1 computation that has been given nothing yet.
Sha1::update fn
export fn Sha1::update(ref<Sha1, exclusive> s, slice<u8, shared> data)Adds data to the message being hashed.
Sha1::finish fn
export fn Sha1::finish(Sha1 s) : array<u8, 20>The 20-byte SHA-1 digest of everything given to s.
HashKind enum
export enum HashKindA hash chosen at run time: SHA-1, SHA-256, SHA-384 or SHA-512.
Sha1: SHA-1, a 20-byte digest and a 64-byte block; legacy only, asSha1says.Sha2_256: SHA-256, a 32-byte digest and a 64-byte block.Sha2_384: SHA-384, a 48-byte digest and a 128-byte block.Sha2_512: SHA-512, a 64-byte digest and a 128-byte block.
It names the hash in hash, Hasher, Hmac, hmac, pbkdf2, the HKDF _with forms, the RSA signature functions and SignatureScheme.
Hasher struct
export struct HasherA hash computation whose HashKind is chosen at run time.
Used as Sha256 is: Hasher::new(kind), Hasher::update as often as needed, then Hasher::finish, which gives hash(kind, d) of the concatenation d of everything given. A plain value: a copy continues on its own.
hash gives for the wholerunsHasher h = Hasher::new(Sha2_384);
Hasher::update(&mut h, b"ab");
Hasher::update(&mut h, b"c");
Vec<u8> d = Hasher::finish(h);
assert(Vec::len(&d) == 48);
assert(digest_eq(&d, &hash(Sha2_384, b"abc")));Hasher::new fn
export fn Hasher::new(HashKind kind) : HasherA computation of the hash kind that has been given nothing yet.
Hasher::update fn
export fn Hasher::update(ref<Hasher, exclusive> h, slice<u8, shared> data)Adds data to the message being hashed.
Hasher::finish fn
export fn Hasher::finish(Hasher h) : Vec<u8>The digest of everything given to h: 20, 32, 48 or 64 bytes.
As long as the digest of its kind: SHA-1, SHA-256, SHA-384 or SHA-512.
Blake2b struct
export struct Blake2bA BLAKE2b computation in progress (RFC 7693), plain or keyed.
Make one with Blake2b::new or Blake2b::new_keyed, give it the message with Blake2b::update, and take the digest with Blake2b::finish. The digest's length, 1 to 64 bytes, is chosen when it is made. A plain value: a copy continues on its own.
Blake2b::new_keyed fn
export fn Blake2b::new_keyed(slice<u8, shared> key, usize out_len) : Blake2bA keyed BLAKE2b computation (RFC 7693 §2.1) with a digest of out_len bytes.
key is up to 64 bytes; an empty key gives the plain hash. Faults (crypto_length) when out_len is 0 or above 64, or key is longer than 64 bytes.
Blake2b::new fn
export fn Blake2b::new(usize out_len) : Blake2bA plain BLAKE2b computation with a digest of out_len bytes.
The same as Blake2b::new_keyed with an empty key. Faults (crypto_length) when out_len is 0 or above 64.
Blake2b::update fn
export fn Blake2b::update(ref<Blake2b, exclusive> s, slice<u8, shared> data)Adds data to the message being hashed.
Blake2b::finish fn
export fn Blake2b::finish(Blake2b s) : Vec<u8>The digest of everything given to s, of the length chosen when it was made.
sha256 fn
export fn sha256(slice<u8, shared> data) : array<u8, 32>The SHA-256 digest of data, 32 bytes.
The same as Sha256::new, one Sha256::update and Sha256::finish. to_hex prints it.
abc is the FIPS 180-4 example'srunsarray<u8, 32> d = sha256(b"abc");
String hex = to_hex(&d);
assert(hex == "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad");sha512 fn
export fn sha512(slice<u8, shared> data) : array<u8, 64>The SHA-512 digest of data, 64 bytes.
abc is the FIPS 180-4 example'srunsarray<u8, 64> d = sha512(b"abc");
String want = "ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a";
String::append(&mut want, "2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f");
assert((to_hex(&d) == want));sha384 fn
export fn sha384(slice<u8, shared> data) : array<u8, 48>The SHA-384 digest of data, 48 bytes.
sha1 fn
export fn sha1(slice<u8, shared> data) : array<u8, 20>The SHA-1 digest of data, 20 bytes; legacy, as Sha1 says.
abc is the FIPS 180-4 example'srunsarray<u8, 20> d = sha1(b"abc");
assert(to_hex(&d) == "a9993e364706816aba3e25717850c26c9cd0d89d");hash fn
export fn hash(HashKind kind, slice<u8, shared> data) : Vec<u8>The digest of data by the hash kind: 20, 32, 48 or 64 bytes.
sha1, sha256, sha384 or sha512 of data, as a Vec<u8>.
blake2b fn
export fn blake2b(slice<u8, shared> data, usize out_len) : Vec<u8>The BLAKE2b digest of data, out_len bytes long (64 for BLAKE2b-512).
Faults (crypto_length) when out_len is 0 or above 64.
abc is RFC 7693's examplerunsVec<u8> d = blake2b(b"abc", 64);
String want = "ba80a53f981c4d0d6a2797b69f12f6e94c212f14685ac4b74b12bb6fdbffa2d1";
String::append(&mut want, "7d87c5392aab792dc252d5de4533cc9518d38aa8dbf1925ab92386edd4009923");
assert((to_hex(&d) == want));crc32 fn
export fn crc32(slice<u8, shared> data) : u32The CRC-32 checksum of data, as zlib, PNG, gzip and Ethernet compute it.
CRC-32/IEEE: polynomial 0x04C11DB7 (reflected 0xEDB88320), initial value and final exclusive or 0xFFFFFFFF, input and output reflected; computed eight bytes at a time from tables.
It is not cryptographic: it detects accidental corruption, and anyone can make data with any CRC they choose. To detect tampering, use a hash or a MAC.
123456789 is CRC-32's published check valuerunsassert(crc32(b"123456789") == 0xCBF43926);digest_eq fn
export fn digest_eq(slice<u8, shared> a, slice<u8, shared> b) : boolWhether a and b have the same length and the same bytes, in a time that depends on the lengths alone.
Every byte is compared, however early they differ, so a sender guessing a MAC learns nothing from how long the check took. A program that checks a MAC or a digest it received compares with this, never ==. Slices of different lengths are false.
array<u8, 3> a = [1, 2, 3];
array<u8, 4> b = [1, 2, 3, 0];
assert(digest_eq(&a, &b[0..3]));
assert(!digest_eq(&a, &b));std::crypto::kdf impl/std/crypto/kdf.cb
HmacSha256 struct
export struct HmacSha256An HMAC-SHA-256 computation in progress (RFC 2104).
Make one with HmacSha256::new(key), give it the message with HmacSha256::update, and take the 32-byte MAC with HmacSha256::finish. A plain value: a copy of a keyed HmacSha256 continues on its own, so one key setup serves many messages.
HmacSha256::new fn
export fn HmacSha256::new(slice<u8, shared> key) : HmacSha256An HMAC-SHA-256 computation under key that has been given no message yet.
key may be of any length: one longer than 64 bytes is replaced by its SHA-256 digest, then the key is padded with zero bytes to 64.
HmacSha256::update fn
export fn HmacSha256::update(ref<HmacSha256, exclusive> m, slice<u8, shared> data)Adds data to the message being authenticated.
HmacSha256::finish fn
export fn HmacSha256::finish(HmacSha256 m) : array<u8, 32>The 32-byte MAC of everything given to m.
Hmac struct
export struct HmacAn HMAC computation in progress (RFC 2104) over a hash chosen at run time.
Used as HmacSha256 is: Hmac::new(kind, key), Hmac::update, then Hmac::finish. A plain value: a copy of a keyed Hmac continues on its own, which is how pbkdf2 reuses one key setup for every iteration.
Hmac::new fn
export fn Hmac::new(HashKind kind, slice<u8, shared> key) : HmacAn HMAC computation over the hash kind under key that has been given no message yet.
A key longer than the hash's block (64 bytes for SHA-1 and SHA-256, 128 for SHA-384 and SHA-512) is replaced by its digest, then padded with zero bytes to the block.
Hmac::update fn
export fn Hmac::update(ref<Hmac, exclusive> m, slice<u8, shared> data)Adds data to the message being authenticated.
Hmac::finish fn
export fn Hmac::finish(Hmac m) : Vec<u8>The MAC of everything given to m, as long as its hash's digest.
hmac_sha256 fn
export fn hmac_sha256(slice<u8, shared> key, slice<u8, shared> data) : array<u8, 32>The HMAC-SHA-256 of data under key (RFC 2104), 32 bytes.
Check a MAC that arrived with digest_eq, never ==.
array<u8, 32> mac = hmac_sha256(b"Jefe", b"what do ya want for nothing?");
String hex = to_hex(&mac);
assert(hex == "5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843");hkdf_extract fn
export fn hkdf_extract(slice<u8, shared> salt, slice<u8, shared> ikm) : array<u8, 32>The 32-byte HKDF-SHA-256 pseudorandom key of ikm under salt (RFC 5869).
HMAC-SHA-256 of ikm with salt as the key; an empty salt stands for 32 zero bytes.
hkdf_expand fn
export fn hkdf_expand(slice<u8, shared> prk, slice<u8, shared> info, usize len) : Vec<u8>The first len bytes of HKDF-SHA-256 output keying material from prk and info (RFC 5869).
Block i is HMAC-SHA-256(prk, block i-1 ‖ info ‖ i), block 0 being empty and i one byte counted from 1. Faults (hkdf_length) when len is above 8160 (255 blocks).
hkdf_sha256 fn
export fn hkdf_sha256(slice<u8, shared> salt, slice<u8, shared> ikm, slice<u8, shared> info, usize len) : Vec<u8>HKDF-SHA-256 in one call: len bytes derived from ikm with salt and info.
The same as hkdf_expand of hkdf_extract(salt, ikm), info and len. Faults (hkdf_length) when len is above 8160.
Vec<u8> ikm = Vec::filled(22, 0x0b: u8);
Vec<u8> none = Vec::new();
Vec<u8> okm = hkdf_sha256(&none, &ikm, &none, 42);
String want = "8da4e775a563c18f715f802a063c5a31b8a11f5c5ee1879ec345";
String::append(&mut want, "4e5f3c738d2d9d201395faa4b61a96c8");
assert((to_hex(&okm) == want));hkdf_expand_label fn
export fn hkdf_expand_label(slice<u8, shared> secret, StringView label, slice<u8, shared> context, usize len) : Vec<u8>TLS 1.3's HKDF-Expand-Label (RFC 8446 §7.1): len bytes from secret, label and context.
hkdf_expand of secret with the info len in two bytes ‖ the length of "tls13 " ‖ label in one byte ‖ "tls13 " ‖ label ‖ the length of context in one byte ‖ context. The key schedules of TLS 1.3, QUIC and DTLS 1.3 are built from it.
Faults (hkdf_length) when len is above 8160; a label longer than 249 bytes or a context longer than 255 faults (narrowing_overflow) while the info is built.
hmac fn
export fn hmac(HashKind kind, slice<u8, shared> key, slice<u8, shared> data) : Vec<u8>The HMAC of data under key over the hash kind, as long as that hash's digest.
hmac(Sha2_256, key, data) gives the same bytes as hmac_sha256(key, data).
Vec<u8> mac = hmac(Sha2_512, b"Jefe", b"what do ya want for nothing?");
String want = "164b7a7bfcf819e2e395fbe73b56e0a387bd64222e831fd610270cd7ea250554";
String::append(&mut want, "9758bf75c05a994a6d034f65f8f0e6fdcaeab1a34d4a6b4b636e070a38bce737");
assert((to_hex(&mac) == want));hkdf_extract_with fn
export fn hkdf_extract_with(HashKind kind, slice<u8, shared> salt, slice<u8, shared> ikm) : Vec<u8>The HKDF pseudorandom key of ikm under salt over the hash kind (RFC 5869).
As hkdf_extract, with kind's digest length in place of 32: an empty salt stands for that many zero bytes, and the key is that long.
hkdf_expand_with fn
export fn hkdf_expand_with(HashKind kind, slice<u8, shared> prk, slice<u8, shared> info, usize len) : Vec<u8>The first len bytes of HKDF output keying material from prk and info over the hash kind.
As hkdf_expand, with HMAC over kind. Faults (hkdf_length) when len is above 255 of kind's digests.
hkdf_with fn
export fn hkdf_with(HashKind kind, slice<u8, shared> salt, slice<u8, shared> ikm, slice<u8, shared> info, usize len) : Vec<u8>HKDF over the hash kind in one call: len bytes derived from ikm with salt and info.
The same as hkdf_expand_with of hkdf_extract_with(kind, salt, ikm), info and len.
hkdf_expand_label_with fn
export fn hkdf_expand_label_with(HashKind kind, slice<u8, shared> secret, StringView label, slice<u8, shared> context, usize len) : Vec<u8>TLS 1.3's HKDF-Expand-Label over the hash kind, as the SHA-384 cipher suites use it.
As hkdf_expand_label, with hkdf_expand_with over kind: len above 255 of kind's digests faults (hkdf_length).
pbkdf2 fn
export fn pbkdf2(HashKind kind, slice<u8, shared> password, slice<u8, shared> salt, usize iterations, usize len) : Vec<u8>PBKDF2 (RFC 8018 §5.2) over HMAC of kind: len bytes derived from password and salt.
Each block of the result costs iterations HMACs. It is here for the formats that still use it (SCRAM among them); to store a password, use hash_password. Faults (kdf_parameters) when iterations is 0.
Vec<u8> dk = pbkdf2(Sha1, b"password", b"salt", 2, 20);
assert(to_hex(&dk) == "ea6c014dc72d6f8ccd1ed92ace1d41f0d8de8957");argon2id fn
export fn argon2id(slice<u8, shared> password, slice<u8, shared> salt, usize iterations, usize memory_kib, usize parallelism, usize len) : Vec<u8>The Argon2id tag (RFC 9106, version 0x13) of len bytes from password and salt.
iterations passes over memory_kib kibibytes, rounded down to a multiple of 4 × parallelism, in parallelism lanes, computed one after another; no secret key and no associated data. The first two slices of the first pass address memory independently of the password and the rest depend on it, as Argon2id prescribes; that addressing is outside std::crypto's constant-time guarantee.
Faults (kdf_parameters) when iterations is 0, parallelism is 0 or above 255, memory_kib is below 8 × parallelism, salt is shorter than 8 bytes or len is below 4, or when iterations, memory_kib or len is above 2^32 − 1 (RFC 9106's bounds).
Cost: time grows with iterations × memory_kib, and memory_kib KiB are allocated. To store a password, hash_password chooses the parameters.
hash_password fn
export fn hash_password(slice<u8, shared> password) : Stringpassword hashed for storage: an Argon2id PHC string with a fresh random salt.
The text $argon2id$v=19$m=19456,t=2,p=1$S$H, S the unpadded base64 of 16 bytes of os_random_bytes and H that of argon2id(password, salt, 2, 19456, 1, 32): 19 MiB, two passes and one lane, the OWASP recommendation. verify_password and every password library read it.
Slow by design, so that guessing stays expensive.
verify_password fn
export fn verify_password(StringView stored, slice<u8, shared> password) : boolWhether password is the one the Argon2id PHC string stored was made from.
stored is a hash written by hash_password or by any Argon2id implementation ($argon2id$v=19$m=M,t=T,p=P$salt$hash); its parameters are taken from it, and the result is compared with digest_eq. false when stored does not have that shape, its parameters are outside the bounds argon2id accepts (so it never faults on them), or its memory m is above 1,048,576 KiB (1 GiB, libsodium's largest preset), so a hostile stored hash cannot make one call allocate more. Cost: one argon2id with the stored parameters.
std::crypto::aead impl/std/crypto/aead.cb
chacha20 fn
export fn chacha20(slice<u8, shared> key, slice<u8, shared> nonce, u32 counter, slice<u8, shared> data) : Vec<u8>data exclusive-ored with the ChaCha20 keystream (RFC 8439 §2.4) for key and nonce, from block counter.
Encryption and decryption are the same operation. key is 32 bytes and nonce 12. The stream cipher alone hides the data but does not protect it from change; use chacha20_poly1305_seal for that. Constant-time: the steps taken depend on the lengths of the arguments only.
Faults (crypto_length) for another key or nonce length, or when data would need a block counter past 2^32 - 1.
array<u8, 32> key = [9; 32];
array<u8, 12> nonce = [0; 12];
Vec<u8> hidden = chacha20(&key, &nonce, 1, b"attack at dawn");
Vec<u8> back = chacha20(&key, &nonce, 1, &hidden);
assert(slice_eq(&back, b"attack at dawn"));poly1305 fn
export fn poly1305(slice<u8, shared> key, slice<u8, shared> message) : array<u8, 16>The 16-byte Poly1305 tag of message under the one-time 32-byte key (RFC 8439 §2.5).
A key must never authenticate two messages; chacha20_poly1305_seal derives a fresh one for each nonce. Constant-time: the steps taken depend on the lengths of the arguments only. Faults (crypto_length) when key is not 32 bytes.
StringView k = "85d6be7857556d337f4452fe42d506a80103808afb0db2fd4abff6af4149f51b";
Vec<u8> key = Result::unwrap(from_hex(k));
array<u8, 16> tag = poly1305(&key, b"Cryptographic Forum Research Group");
assert(to_hex(&tag) == "a8061dc1305136c6c22b8baf0c0127a9");chacha20_poly1305_seal fn
export fn chacha20_poly1305_seal(slice<u8, shared> key, slice<u8, shared> nonce, slice<u8, shared> aad, slice<u8, shared> plaintext) : Vec<u8>Encrypts and authenticates plaintext with ChaCha20-Poly1305 (RFC 8439 §2.8).
The result is the ciphertext, as long as plaintext, followed by a 16-byte tag over it and over aad, data sent in the clear but protected from change. key is 32 bytes and nonce 12; a nonce must never be used twice with one key. Constant-time: the steps taken depend on the lengths of the arguments only. Faults (crypto_length) for another key or nonce length.
array<u8, 32> key = [7; 32];
array<u8, 12> nonce = [1; 12];
array<u8, 2> ad = [0xa1, 0xa2];
Vec<u8> sealed = chacha20_poly1305_seal(&key, &nonce, &ad, b"hello");
assert(Vec::len(&sealed) == 5 + 16);
Option<Vec<u8>> opened = chacha20_poly1305_open(&key, &nonce, &ad, &sealed);
assert(slice_eq(&Option::unwrap(opened), b"hello"));
sealed[0] = sealed[0] ^ 1;
assert(Option::is_none(&chacha20_poly1305_open(&key, &nonce, &ad, &sealed)));chacha20_poly1305_open fn
export fn chacha20_poly1305_open(slice<u8, shared> key, slice<u8, shared> nonce, slice<u8, shared> aad, slice<u8, shared> sealed) : Option<Vec<u8>>Checks and decrypts what chacha20_poly1305_seal gave, under the same key, nonce and aad.
Some(plaintext) when the tag matches; None when anything was changed, the key, nonce or aad differ, or sealed is shorter than the 16-byte tag. The tag is checked with digest_eq, and nothing of a refused message is returned. Faults (crypto_length) for a key that is not 32 bytes or a nonce that is not 12.
aes_encrypt_block fn
export fn aes_encrypt_block(slice<u8, shared> key, array<u8, 16> block) : array<u8, 16>One 16-byte block encrypted with AES (FIPS 197) under key.
key is 16, 24 or 32 bytes, for AES-128, AES-192 or AES-256. The bare block cipher, for building other modes; to encrypt data, use aes_gcm_seal. Constant-time: the steps taken depend on the lengths of the arguments only. Faults (crypto_length) for another key length.
Vec<u8> key = Result::unwrap(from_hex("000102030405060708090a0b0c0d0e0f"));
Vec<u8> b = Result::unwrap(from_hex("00112233445566778899aabbccddeeff"));
array<u8, 16> block = [0; 16];
for (usize i = 0; i < 16; i += 1)
{
block[i] = b[i];
}
array<u8, 16> out = aes_encrypt_block(&key, block);
assert(to_hex(&out) == "69c4e0d86a7b0430d8cdb78070b4c55a");aes_gcm_seal fn
export fn aes_gcm_seal(slice<u8, shared> key, slice<u8, shared> nonce, slice<u8, shared> aad, slice<u8, shared> plaintext) : Vec<u8>Encrypts and authenticates plaintext with AES-GCM (NIST SP 800-38D) under key and nonce.
The result is the ciphertext, as long as plaintext, followed by a 16-byte tag over it and over aad. key is 16, 24 or 32 bytes (AES-128, AES-192 or AES-256) and nonce 12; a nonce must never be used twice with one key. Constant-time: the steps taken depend on the lengths of the arguments only. Faults (crypto_length) for another key or nonce length.
array<u8, 16> key = [0; 16];
array<u8, 12> nonce = [0; 12];
array<u8, 16> plain = [0; 16];
Vec<u8> none = Vec::new();
Vec<u8> sealed = aes_gcm_seal(&key, &nonce, &none, &plain);
String want = "0388dace60b6a392f328c2b971b2fe78";
String::append(&mut want, "ab6e47d42cec13bdf53a67b21257bddf");
assert((to_hex(&sealed) == want));
Vec<u8> opened = Option::unwrap(aes_gcm_open(&key, &nonce, &none, &sealed));
assert(slice_eq(&opened, &plain));
assert(Option::is_none(&aes_gcm_open(&key, &nonce, b"aad", &sealed)));aes_gcm_open fn
export fn aes_gcm_open(slice<u8, shared> key, slice<u8, shared> nonce, slice<u8, shared> aad, slice<u8, shared> sealed) : Option<Vec<u8>>Checks and decrypts what aes_gcm_seal gave, under the same key, nonce and aad.
Some(plaintext) when the tag matches; None when anything was changed, the key, nonce or aad differ, or sealed is shorter than the 16-byte tag. The tag is checked with digest_eq, and nothing of a refused message is returned. Faults (crypto_length) for a key that is not 16, 24 or 32 bytes or a nonce that is not 12.
std::crypto::pk impl/std/crypto/pk.cb
RsaPublicKey struct
export struct RsaPublicKeyAn RSA public key: the modulus n and the public exponent e.
EcCurve enum
export enum EcCurveAn elliptic curve for ECDH and ECDSA.
P256: NIST P-256 (secp256r1): private keys and shared secrets of 32 bytes, public keys of 65.P384: NIST P-384 (secp384r1): private keys and shared secrets of 48 bytes, public keys of 97.
RsaPrivateKey struct
export struct RsaPrivateKeyAn RSA private key: the modulus n, the public exponent e, the private exponent d and the primes p and q.
Made by RsaPrivateKey::new, rsa_generate_key or PrivateKey::from_der; it also holds the Chinese-remainder values the private operation uses. Signing computes m^d mod n modulo p and q with a constant-time exponentiation and checks the result with e.
RsaPrivateKey::new fn
export fn RsaPrivateKey::new(BigUint n, BigUint e, BigUint d, BigUint p, BigUint q) : Option<RsaPrivateKey>The private key with these parts, or None when they do not fit together.
They fit when p and q are odd and above 2, p·q = n, and e·d ≡ 1 modulo p - 1 and modulo q - 1.
BigUint n = BigUint::from_u64(3233);
BigUint e = BigUint::from_u64(17);
BigUint p = BigUint::from_u64(61);
BigUint q = BigUint::from_u64(53);
Option<RsaPrivateKey> good = RsaPrivateKey::new(n, e, BigUint::from_u64(2753), p, q);
assert(Option::is_some(&good));
Option<RsaPrivateKey> bad = RsaPrivateKey::new(
BigUint::from_u64(3233),
BigUint::from_u64(17),
BigUint::from_u64(2754),
BigUint::from_u64(61),
BigUint::from_u64(53),
);
assert(Option::is_none(&bad));RsaPrivateKey::public_key fn
export fn RsaPrivateKey::public_key(ref<RsaPrivateKey, shared> key) : RsaPublicKeyThe public half of key: its modulus and public exponent.
x25519 fn
export fn x25519(slice<u8, shared> private_key, slice<u8, shared> public_key) : Option<array<u8, 32>>The X25519 shared secret (RFC 7748) of private_key and the other side's public_key.
Both are 32 bytes; the result is the clamped private key times the point with u-coordinate public_key on Curve25519. None when the result is all zeros, which a public key of small order gives and which must never be used as a secret (TLS 1.3 requires the check). Constant-time, the check for zero included. Faults (crypto_length) when either is not 32 bytes.
x25519_public_key fn
export fn x25519_public_key(slice<u8, shared> private_key) : array<u8, 32>The X25519 public key of the 32-byte private_key: the private key times the base point u = 9.
Constant-time. Faults (crypto_length) when private_key is not 32 bytes.
x25519_private_key fn
export fn x25519_private_key() : array<u8, 32>A new X25519 private key: 32 bytes of os_random_bytes.
From the operating system's secure source, never from Rng.
rsa_verify_pkcs1v15 fn
export fn rsa_verify_pkcs1v15(ref<RsaPublicKey, shared> key, HashKind kind, slice<u8, shared> digest, slice<u8, shared> signature) : boolWhether signature is key's RSASSA-PKCS1-v1_5 signature (RFC 8017 §8.2.2) of a message whose kind digest is digest.
digest is the hash of the message, not the message. True exactly when signature is as long as the modulus, below it, and signature^e mod n is 00 01 FF…FF 00 ‖ the DigestInfo of kind ‖ digest with at least eight FF bytes; the block is rebuilt and compared whole, so no part of it is parsed. A malformed key or signature gives false, never a fault. Not constant-time, and need not be: it uses public values only.
rsa_verify_pss fn
export fn rsa_verify_pss(ref<RsaPublicKey, shared> key, HashKind kind, slice<u8, shared> digest, slice<u8, shared> signature) : boolWhether signature is key's RSASSA-PSS signature (RFC 8017 §8.1.2) of a message whose kind digest is digest.
With MGF1 over the same hash and a salt as long as the digest, as TLS 1.3 and most X.509 use. A malformed key or signature gives false, never a fault. Not constant-time, and need not be: it uses public values only.
ecdsa_verify fn
export fn ecdsa_verify(EcCurve curve, slice<u8, shared> public_key, slice<u8, shared> digest, slice<u8, shared> signature) : boolWhether signature is an ECDSA signature (FIPS 186-4 §6.4.2) on curve by the holder of public_key of a message whose digest is digest.
public_key is an uncompressed point (0x04 ‖ x ‖ y) on the curve, and signature the strict DER SEQUENCE { r INTEGER, s INTEGER } of X.509 and TLS, with r and s in [1, n-1]. The digest's leftmost bits are used when it is longer than the curve's order. A malformed key or signature gives false, never a fault. Not constant-time, and need not be: it uses public values only.
ec_private_key fn
export fn ec_private_key(EcCurve curve) : Vec<u8>A new private key for curve: 32 (P-256) or 48 (P-384) bytes of os_random_bytes.
The bytes name a number in [1, n-1]; they are drawn again in the rare case they do not.
ec_public_key fn
export fn ec_public_key(EcCurve curve, slice<u8, shared> private_key) : Option<Vec<u8>>The public key of private_key on curve: 0x04 ‖ x ‖ y of the private key times the base point.
65 bytes on P-256, 97 on P-384; None when private_key does not name a number in [1, n-1]. Constant-time. Faults (crypto_length) when private_key is not 32 bytes (P-256) or 48 (P-384).
array<u8, 32> zero = [0; 32];
assert(Option::is_none(&ec_public_key(P256, &zero)));
array<u8, 32> above = [0xff; 32];
assert(Option::is_none(&ec_public_key(P256, &above)));ecdh fn
export fn ecdh(EcCurve curve, slice<u8, shared> private_key, slice<u8, shared> public_key) : Option<Vec<u8>>The ECDH shared secret (SEC 1 §3.3.1) of private_key and the peer's public_key on curve.
The x-coordinate of their product: 32 bytes on P-256, 48 on P-384. None when private_key does not name a number in [1, n-1], or public_key is not an uncompressed point on the curve (a point off the curve could leak the key it is multiplied by). Constant-time. Faults (crypto_length) for a private key of the wrong length.
p256_private_key fn
export fn p256_private_key() : array<u8, 32>A new P-256 private key: ec_private_key(P256) as a 32-byte array.
p256_public_key fn
export fn p256_public_key(slice<u8, shared> private_key) : Option<array<u8, 65>>The P-256 public key of private_key, as a 65-byte array.
ec_public_key(P256, private_key), with its None and its fault.
p256_ecdh fn
export fn p256_ecdh(slice<u8, shared> private_key, slice<u8, shared> public_key) : Option<array<u8, 32>>The P-256 shared secret of private_key and public_key, as a 32-byte array.
ecdh(P256, private_key, public_key), with its None and its fault.
ecdsa_sign fn
export fn ecdsa_sign(EcCurve curve, slice<u8, shared> private_key, slice<u8, shared> digest) : Option<Vec<u8>>The ECDSA signature (FIPS 186-4 §6.4.1) by private_key on curve of a message whose digest is digest.
The strict DER SEQUENCE { r, s } that ecdsa_verify checks, or None when private_key does not name a number in [1, n-1]. The nonce is RFC 6979's, derived from the key and the digest with HMAC-SHA-256 (P-256) or HMAC-SHA-384 (P-384), so the same message signs the same way every time and no random number can repeat. Constant-time but for one branch, on whether a candidate nonce is below n. Faults (crypto_length) for a private key of the wrong length.
ed25519_private_key fn
export fn ed25519_private_key() : array<u8, 32>A new Ed25519 private key: 32 bytes of os_random_bytes.
ed25519_public_key fn
export fn ed25519_public_key(slice<u8, shared> private_key) : array<u8, 32>The Ed25519 public key (RFC 8032 §5.1.5) of the 32-byte private_key.
The encoding of s·B, s the clamped first half of SHA-512(private_key). Constant-time. Faults (crypto_length) when private_key is not 32 bytes.
ed25519_sign fn
export fn ed25519_sign(slice<u8, shared> private_key, slice<u8, shared> message) : array<u8, 64>The Ed25519 signature (RFC 8032 §5.1.6) of message by private_key: R ‖ S, 64 bytes.
message is signed whole, not a digest of it. The signature is the same for the same key and message every time, with no random number to repeat. Constant-time. Faults (crypto_length) when private_key is not 32 bytes.
ed25519_verify fn
export fn ed25519_verify(slice<u8, shared> public_key, slice<u8, shared> message, slice<u8, shared> signature) : boolWhether signature is public_key's Ed25519 signature (RFC 8032 §5.1.7) of message.
True exactly when public_key and signature are 32 and 64 bytes, the key and R (the signature's first 32 bytes) are canonical point encodings, S (the rest, little-endian) is below L, and S·B = R + k·A with k = SHA-512(R ‖ A ‖ message) mod L. Anything else, a wrong length included, is false. Not constant-time, and need not be: it uses public values only.
rsa_sign_pkcs1v15 fn
export fn rsa_sign_pkcs1v15(ref<RsaPrivateKey, shared> key, HashKind kind, slice<u8, shared> digest) : Vec<u8>key's RSASSA-PKCS1-v1_5 signature (RFC 8017 §8.2.1) of a message whose kind digest is digest.
As many bytes as the modulus, and the same every time; rsa_verify_pkcs1v15 with the key's public half accepts it. Faults (crypto_length) when digest is not as long as kind's digests, or the modulus is shorter than the encoding plus 11 bytes.
rsa_sign_pss fn
export fn rsa_sign_pss(ref<RsaPrivateKey, shared> key, HashKind kind, slice<u8, shared> digest) : Vec<u8>key's RSASSA-PSS signature (RFC 8017 §8.1.1) of a message whose kind digest is digest.
With MGF1 over the same hash and a salt of os_random_bytes as long as the digest: a different signature every time, each accepted by rsa_verify_pss. Faults (crypto_length) when digest is not as long as kind's digests, or the modulus is too short for two digests and two bytes.
rsa_generate_key fn
export fn rsa_generate_key(usize bits) : RsaPrivateKeyA new RSA private key of bits bits, with the public exponent 65537.
n = p·q has exactly bits bits; p and q are distinct primes of bits/2 bits from os_random_bytes, found by trial division by the primes below 1000 and five rounds of Miller–Rabin with random bases (FIPS 186-4 B.3.3), with p - 1 and q - 1 prime to e. Faults (crypto_length) when bits is below 1024, above 8192 or not a multiple of 64. Slow, as every key generation is: it searches for primes.
std::x509 impl/std/x509.cb
CertError enum
export enum CertErrorWhy a certificate, a chain or a key was refused.
BadEncoding: the DER or PEM is malformed, or is not what was asked for.Expired: a certificate's validity ended before the time checked.NotYetValid: a certificate's validity begins after the time checked.UnknownAuthority: no chain from the leaf reaches a trusted root.HostMismatch: the leaf certificate is not for the host.BadSignature: a certificate's signature does not verify under its issuer's key.NotAuthority: an issuer is not a CA allowed to sign certificates, its path length is exceeded, or a name below it is outside its name constraints.UnsupportedAlgorithm: a key or signature algorithmstddoes not handle, or an encrypted private key.UnhandledCritical: a certificate has a critical extensionstddoes not handle.WrongUsage: the leaf's extended key usage, or an issuer's, does not allow a TLS server.ChainTooLong: no root was reached within 10 certificates.
CertError::text fn
export fn CertError::text(ref<CertError, shared> e) : strA short English description of e, such as "certificate expired", for a message.
Der struct
export struct DerOne DER element (ITU-T X.690), as der_read reads it: its tag and where its contents lie.
tag: the tag byte.start,end: the contents arebuf[start..end]of the buffer it was read from.next: where the next element begins, the same asend.
EcPublicKey struct
export struct EcPublicKeyAn elliptic-curve public key: the curve and the uncompressed point (0x04 ‖ x ‖ y).
CertKey enum
export enum CertKeyA public key, as a certificate or a SubjectPublicKeyInfo carries it.
RsaKey: an RSA key.EcKey: a P-256 or P-384 key.Ed25519Key: an Ed25519 key, 32 bytes.UnsupportedKey: a key of another algorithm; a certificate with one parses, but no signature verifies under it.
CertKey::to_der fn
export fn CertKey::to_der(ref<CertKey, shared> key) : Option<Vec<u8>>The DER SubjectPublicKeyInfo of key, or None for UnsupportedKey.
CertKey::from_der reads it back.
CertKey::from_der fn
export fn CertKey::from_der(slice<u8, shared> der) : Result<CertKey, CertError>The public key of the DER SubjectPublicKeyInfo der.
Err(BadEncoding) when der is not exactly one SubjectPublicKeyInfo; Err(UnsupportedAlgorithm) when its algorithm is not RSA, P-256, P-384 or Ed25519.
CertKey::from_pem fn
export fn CertKey::from_pem(StringView text) : Result<CertKey, CertError>The public key of the first -----BEGIN PUBLIC KEY----- block in text (RFC 7468).
The block's DER is read as CertKey::from_der reads it; Err(BadEncoding) when there is no such block, or its base64 does not decode.
CertKey::to_pem fn
export fn CertKey::to_pem(ref<CertKey, shared> key) : Option<String>key as a PEM PUBLIC KEY block of 64-character lines, or None for UnsupportedKey.
CertKey key = Ed25519Key([0x42; 32]);
String pem = Option::unwrap(CertKey::to_pem(&key));
assert(StringView::starts_with(&pem, "-----BEGIN PUBLIC KEY-----\n"));
match (CertKey::from_pem(&pem))
{
Ok(Ed25519Key(k)) : assert(k[0] == 0x42 && k[31] == 0x42),
_ : assert(false),
}SignatureScheme enum
export enum SignatureSchemeA signature algorithm with its hash, as certificates and TLS name them.
RsaPkcs1(h): RSASSA-PKCS1-v1_5 over the hashh.RsaPss(h): RSASSA-PSS overh, with MGF1 overhand a salt as long as its digest.Ecdsa(h): ECDSA overh.Ed25519: Ed25519, over the message itself.UnsupportedSignature: another algorithm; nothing verifies or signs with it.
Certificate struct
export struct CertificateA parsed X.509 certificate (RFC 5280), v3 or older.
der: the whole certificate;tbs: the signed part;signature: the signature overtbs, made withscheme.issuer,subject: the names' DER, compared whole.common_name: the subject's last common name, empty when there is none; host matching does not consult it.not_before,not_after: the validity.dns_names,ip_addresses: the subject alternative names' DNS names and IP addresses.is_ca,max_path_len: the basic constraints;max_path_lenis -1 when there is no limit.can_sign_certificates: key usage's keyCertSign,truewhen there is no key usage.server_auth: extended key usage allows server authentication or any use,truewhen there is no extended key usage.unhandled_critical: a critical extension other than certificate policies was not understood, or critical name constraints hold a subtree of a form other thandNSNameandiPAddress, so the certificate is not usable. ThedNSNameandiPAddressname constraints are kept forverify_chain.key: the subject's public key.
Not independently audited: std::x509 is implemented to the standards its documentation names, tested against OpenSSL, and fuzzed continuously, but it has not been independently audited.
Certificate::parse fn
export fn Certificate::parse(slice<u8, shared> der) : Result<Certificate, CertError>The certificate whose DER is der (RFC 5280 §4.1), or Err(BadEncoding).
der must be exactly one certificate, with its inner and outer signature algorithms equal. UTCTime years 50 to 99 are read as 19xx. An unknown key or signature algorithm still parses, as UnsupportedKey or UnsupportedSignature; an unknown critical extension sets unhandled_critical. An Ed25519 key or signature algorithm (OID 1.3.101.112) is Ed25519Key or Ed25519.
Certificate::matches_host fn
export fn Certificate::matches_host(ref<Certificate, shared> c, StringView host) : boolWhether c is for host (RFC 6125 §6.4).
An IP address literal is compared with the certificate's IP addresses. A name is compared with its DNS names, ignoring ASCII case and one final dot on host; a leading *. in a DNS name stands for exactly one whole label, and only where at least two labels follow it (so *.com matches nothing). The common name is not consulted.
TrustStore struct
export struct TrustStoreThe root certificates a chain may end at, for verify_chain.
roots may be read and changed directly; TrustStore::system reads the operating system's.
TrustStore::new fn
export fn TrustStore::new() : TrustStoreA store with no roots.
TrustStore::add fn
export fn TrustStore::add(ref<TrustStore, exclusive> t, Certificate root)Adds root to the roots of t.
TrustStore::from_pem_file fn
export fn TrustStore::from_pem_file(StringView path) : Result<TrustStore, FileError>The roots in the PEM file at path, such as /etc/ssl/certs/ca-certificates.crt.
Its certificates are read as certificates_from_pem reads them. Err with the FileError when the file cannot be read.
TrustStore::system fn
export fn TrustStore::system() : Result<TrustStore, FileError>The operating system's roots, from the first of the usual bundle files that holds a certificate.
The files tried, in order: /etc/ssl/certs/ca-certificates.crt (Debian, Ubuntu), /etc/pki/tls/certs/ca-bundle.crt (Fedora, RHEL), /etc/ssl/ca-bundle.pem, /etc/ssl/cert.pem (Alpine) and /usr/local/etc/openssl/cert.pem (macOS with a package manager's OpenSSL). Err(NotFound) where none does, as on Windows: a program there passes a bundle to TrustStore::from_pem_file.
EcPrivateKey struct
export struct EcPrivateKeyAn elliptic-curve private key: the curve and the scalar, 32 bytes for P-256 or 48 for P-384.
PrivateKey enum
export enum PrivateKeyA private key of one of the algorithms std signs with.
RsaPrivate: an RSA key.EcPrivate: a P-256 or P-384 key.Ed25519Private: an Ed25519 key, its 32-byte private key (the seed).
PrivateKey::public_key fn
export fn PrivateKey::public_key(ref<PrivateKey, shared> key) : CertKeyThe public key that matches key.
An EC key whose scalar does not name a number in [1, n-1], which PrivateKey::from_der never gives, gets an empty point; a scalar of the wrong length faults (crypto_length).
PrivateKey::from_der fn
export fn PrivateKey::from_der(slice<u8, shared> der) : Result<PrivateKey, CertError>The private key of the DER der: a PKCS #8 PrivateKeyInfo (RFC 5958), PKCS #1 RSAPrivateKey or SEC 1 ECPrivateKey.
The three are told apart by their first fields; a SEC 1 key's curve comes from its own parameters. The numbers are checked as RsaPrivateKey::new and ec_public_key check them. Err(BadEncoding) when der is none of these or its numbers do not fit together; Err(UnsupportedAlgorithm) for an algorithm or curve std does not sign with.
PrivateKey::to_der fn
export fn PrivateKey::to_der(ref<PrivateKey, shared> key) : Vec<u8>key as DER PKCS #8 (version 0), which PrivateKey::from_der reads back.
An RSA key with its Chinese-remainder values, an EC key with its public key, an Ed25519 key as its seed.
PrivateKey::from_pem fn
export fn PrivateKey::from_pem(StringView text) : Result<PrivateKey, CertError>The private key of a PRIVATE KEY, RSA PRIVATE KEY or EC PRIVATE KEY block in text.
The block's DER is read as PrivateKey::from_der reads it. The labels are looked for in that order, so a PRIVATE KEY block is taken even when a block of the other kinds comes before it. An ENCRYPTED PRIVATE KEY block alone is Err(UnsupportedAlgorithm); no block, or base64 that does not decode, is Err(BadEncoding).
StringView text = "-----BEGIN ENCRYPTED PRIVATE KEY-----\nAAAA\n-----END ENCRYPTED PRIVATE KEY-----\n";
match (PrivateKey::from_pem(text))
{
Err(UnsupportedAlgorithm) : assert(true),
_ : assert(false),
}PrivateKey::to_pem fn
export fn PrivateKey::to_pem(ref<PrivateKey, shared> key) : Stringkey as a PEM PRIVATE KEY block (PKCS #8) of 64-character lines.
der_read fn
export fn der_read(slice<u8, shared> buf, usize at) : Option<Der>The DER element at at in buf, or None when it is not well-formed.
Well-formed means a single-byte tag, the shortest length form, at most four length bytes, no indefinite length, and contents inside buf. Read an element's first child by calling it again at start, and the element after it at next.
array<u8, 5> der = [0x30, 0x03, 0x02, 0x01, 0x05];
Der seq = Option::unwrap(der_read(&der, 0));
assert(seq.tag == 0x30 && seq.start == 2 && seq.end == 5 && seq.next == 5);
Der int = Option::unwrap(der_read(&der, seq.start));
assert(int.tag == 0x02 && der[int.start] == 5);
array<u8, 4> long_form = [0x04, 0x81, 0x01, 0x00];
assert(Option::is_none(&der_read(&long_form, 0)));certificates_from_pem fn
export fn certificates_from_pem(StringView text) : Vec<Certificate>Every certificate in the PEM text, in order: its -----BEGIN CERTIFICATE----- blocks (RFC 7468).
Text between blocks is ignored. A block whose base64 does not decode, that holds a byte that is not ASCII, or that is not a certificate, is skipped.
StringView text = "junk\n-----BEGIN CERTIFICATE-----\nnot base64!\n-----END CERTIFICATE-----\n";
Vec<Certificate> certs = certificates_from_pem(text);
assert(Vec::len(&certs) == 0);verify_signature fn
export fn verify_signature(ref<CertKey, shared> key, ref<SignatureScheme, shared> scheme, slice<u8, shared> message, slice<u8, shared> signature) : boolWhether signature over message verifies under key with scheme.
The RSA and ECDSA schemes hash message with the scheme's hash first; Ed25519 checks message itself. A key of another kind than the scheme, UnsupportedKey, UnsupportedSignature or a malformed signature gives false. Not constant-time, and need not be: it uses public values only.
verify_chain fn
export fn verify_chain(ref<Certificate, shared> leaf, slice<Certificate, shared> intermediates, ref<TrustStore, shared> roots, StringView host, ref<DateTime, shared> now) : Result<void, CertError>Verifies a TLS server's certificate chain from leaf to one of roots, for host at the time now.
Ok(()) when the leaf matches host (Certificate::matches_host), may serve TLS, is in date and usable, and a chain of at most 10 certificates below the root exists (RFC 5280 §6, as a client needs it) in which:
- each certificate is signed by the next, found by issuer name and signature among
intermediates, in any order, or among the roots; - every issuer, the root included, is a CA allowed to sign certificates, allowed by its extended key usage (when it has one) to serve TLS servers, in date and usable, and within its path length;
- every DNS name and IP address of each certificate below an issuer, and
host, is within the issuer's name constraints (its permitted and excludeddNSNameandiPAddresssubtrees, a wildcard name read as written; a critical name constraint of another form makes the issuerUnhandledCritical); - the last is one of the roots.
When several certificates could issue the same one (an expired and a renewed intermediate, a cross sign), each is tried in turn until a chain verifies, within 100 signature checks in all.
Otherwise Err: HostMismatch, then WrongUsage, then NotYetValid, Expired or UnhandledCritical for the leaf; then the reason the last candidate issuer tried failed (UnknownAuthority when there was none, BadSignature, NotAuthority for an issuer that is not a CA, is beyond its path length or whose name constraints exclude a name, WrongUsage, NotYetValid, Expired, UnhandledCritical or ChainTooLong).
sign fn
export fn sign(ref<PrivateKey, shared> key, ref<SignatureScheme, shared> scheme, slice<u8, shared> message) : Option<Vec<u8>>key's signature of message under scheme, which verify_signature accepts with the matching public key.
The RSA PKCS #1 v1.5, RSA-PSS and ECDSA schemes sign the scheme's hash of message; Ed25519 signs message whole. None when key is not of the scheme's kind, the scheme is UnsupportedSignature, or an EC key's scalar is not in [1, n-1]. An RSA modulus too short for the scheme's hash faults (crypto_length).
PrivateKey key = Ed25519Private([1; 32]);
SignatureScheme scheme = RsaPss(Sha2_256);
assert(Option::is_none(&sign(&key, &scheme, b"message")));std::tls impl/std/tls.cb
TlsError enum
export enum TlsErrorWhy a TLS connection failed.
TlsNetFailure(e): the socket failed asesays; also a lineread_lineread that is not UTF-8 (NotUtf8), and aread_exactcut short (Closed).CertRejected(e): the server's certificate chain did not verify, asesays.HandshakeFailed: a negotiation this side cannot complete.ProtocolError: the peer sent a malformed message.PeerAlert(code): the peer sent an alert with this description code (40 handshake_failure, 70 protocol_version, and so on).RecordRejected: a record did not authenticate.
TlsError::text fn
export fn TlsError::text(ref<TlsError, shared> e) : strA one-line description of the error, for messages; the common alert codes are named.
NetError'srunsTlsError e = PeerAlert(70);
assert(TlsError::text(&e) == "the peer does not speak TLS 1.3 (alert 70)");
TlsError n = TlsNetFailure(Refused);
assert(TlsError::text(&n) == "connection refused");TlsStream struct
export resource struct TlsStreamA TLS 1.3 connection over a TcpStream, as a client (client, connect) or as a server (server).
It speaks the cipher suites TLS_CHACHA20_POLY1305_SHA256, TLS_AES_128_GCM_SHA256 and TLS_AES_256_GCM_SHA384, the key exchanges X25519, P-256 and P-384, and ECDSA, RSA-PSS and Ed25519 signatures. No TLS 1.2, no session resumption, no early data, no client certificates: a client asked for one answers with none, as RFC 8446 §4.4.2 allows, and a server that requires one then refuses with alert 116 (PeerAlert(116)). Dropping the stream closes the connection without close_notify; close sends it first.
Implemented to RFC 8446, tested against its vectors and against OpenSSL on loopback, and fuzzed continuously; not independently audited.
TlsStream::peer_certificate fn
export fn TlsStream::peer_certificate(ref<TlsStream, shared> s) : Option<ref<Certificate, shared>>The peer's certificate that the handshake verified: on a client's stream, the server's leaf.
None on a server's stream, since clients send none. A program that pins a key or a certificate compares it here.
TlsStream::peer_addr fn
export fn TlsStream::peer_addr(ref<TlsStream, shared> s) : SocketAddrThe address of the other end of the connection.
TlsStream::local_addr fn
export fn TlsStream::local_addr(ref<TlsStream, shared> s) : SocketAddrThe local address of the connection.
TlsStream::set_read_timeout_ms fn
export fn TlsStream::set_read_timeout_ms(ref<TlsStream, exclusive> s, u64 ms)Sets how long a read waits for data, in milliseconds, as TcpStream::set_read_timeout_ms does on the stream's socket; 0 waits for ever.
A read that times out between records leaves the stream usable; one that times out inside a record leaves it unusable (the next record does not authenticate, Err(RecordRejected)).
TlsStream::set_write_timeout_ms fn
export fn TlsStream::set_write_timeout_ms(ref<TlsStream, exclusive> s, u64 ms)Sets how long a write waits, in milliseconds, as TcpStream::set_write_timeout_ms does on the stream's socket; 0 waits for ever.
TlsStream::client fn
export fn TlsStream::client(TcpStream tcp, StringView server_name, ref<TrustStore, shared> roots) : Result<TlsStream, TlsError>Performs the TLS 1.3 handshake as a client over the connected tcp, and gives the stream.
server_name is a DNS name, sent as SNI and checked against the certificate, or an IP address literal, checked against its IP addresses. The server's chain is verified against roots at the current time. The timeouts set on tcp apply to every read and write. Err(CertRejected(e)) for a chain that does not verify, Err(HandshakeFailed) for a negotiation this client cannot complete, Err(PeerAlert(code)) when the server refuses.
TlsStream::connect fn
export fn TlsStream::connect(SocketAddr addr, StringView server_name, ref<TrustStore, shared> roots) : Result<TlsStream, TlsError>Connects to addr with TcpStream::connect and performs the handshake as client does.
A failure to connect is Err(TlsNetFailure(e)). For a bounded wait, connect with TcpStream::connect_timeout and call client.
TlsStream::write fn
export fn TlsStream::write(ref<TlsStream, exclusive> s, slice<u8, shared> data) : Result<void, TlsError>Sends all of data, encrypted, in records of at most 16 KiB.
TlsStream::write_text fn
export fn TlsStream::write_text(ref<TlsStream, exclusive> s, StringView text) : Result<void, TlsError>Sends the bytes of text, as write does.
TlsStream::read fn
export fn TlsStream::read(ref<TlsStream, exclusive> s, ref<Vec<u8>, exclusive> buf, usize max) : Result<usize, TlsError>Appends up to max bytes of the peer's data to buf, waiting for some, and gives how many.
0 when the peer has closed the connection with close_notify (or when max is 0). Key updates and session tickets the peer sends are handled on the way. Err(RecordRejected) for a record that does not authenticate, Err(PeerAlert(code)) for an alert.
TlsStream::read_exact fn
export fn TlsStream::read_exact(ref<TlsStream, exclusive> s, ref<Vec<u8>, exclusive> buf, usize n) : Result<void, TlsError>Appends exactly n bytes of the peer's data to buf, reading until they have all arrived.
Err(TlsNetFailure(Closed)) when the peer closes first; what arrived before that stays in buf.
TlsStream::read_line fn
export fn TlsStream::read_line(ref<TlsStream, exclusive> s) : Result<Option<String>, TlsError>The next line the peer sent, without its \n (nor a \r before it).
Ok(None) when the peer has closed (close_notify) before any byte; a last line without \n is given as it is. Err(TlsNetFailure(NotUtf8(e))) for a line that is not UTF-8.
TlsStream::close fn
export fn TlsStream::close(ref<TlsStream, exclusive> s) : Result<void, TlsError>Sends close_notify, telling the peer that no more data follows.
The peer may still send what it had in flight, and read still reads it. Dropping a TlsStream without close just closes the connection.
TlsStream::server fn
export fn TlsStream::server(TcpStream tcp, ref<PrivateKey, shared> key, slice<Certificate, shared> chain) : Result<TlsStream, TlsError>Performs the TLS 1.3 handshake as a server over the accepted tcp, and gives the stream.
key is the server's private key and chain its certificate first, then its issuers up to, but not including, the root. The suite and the group are chosen in the client's order of preference. A client that does not speak TLS 1.3, or offers no suite, group or signature scheme in common, is sent an alert and the result is Err(HandshakeFailed), as it is for an empty chain; so is one whose key share does not have its group's length (illegal_parameter). The timeouts set on tcp apply to every read and write.
std::http impl/std/http.cb
HttpError enum
export enum HttpErrorWhy an HTTP request or connection failed.
HttpNetFailure(e): the network failed, asesays.HttpTlsFailure(e): the TLS connection failed, asesays.BadUrl: the URL is malformed (Url::parse).UnsupportedScheme: the URL's scheme is neitherhttpnorhttps.NoRoots: an https request needed the system's trusted roots andTrustStore::systemfailed.BadMessage: an HTTP message received is malformed; or one to be sent would be: a header whose name is not a token or whose value holds a control byte other than the tab (a CR or LF would start a header or a body of its own), a method that is not a token, or a status outside 100 to 599; or a server's response with no request waiting for one (HttpConnection::respondcalled twice).TooLarge: a message's head is over 65536 bytes, or its body over the limit.TooManyRedirects: a response asked for one redirect more than the client'smax_redirects.ConnectionClosed: the connection ended inside a message.
HttpError::text fn
export fn HttpError::text(ref<HttpError, shared> e) : strA one-line description of the error, for messages.
Url struct
export struct UrlA parsed absolute URL, scheme://host[:port]/path?query.
scheme: lower-cased.host: lower-cased; an IPv6 host keeps its brackets ([::1]).port: the number after the host's:, or the scheme's default: 443 forhttps, 80 otherwise.path: "/" when the text has none.query: the text after?, without it; empty when there is none.
The fragment (#…), which never reaches a server, is dropped.
Url::parse fn
export fn Url::parse(StringView text) : Result<Url, HttpError>Parses an absolute URL.
Err(BadUrl) for text without ://; with an empty host, whether or not a port follows; with a host that is neither a name of RFC 3986's reg-name characters (letters, digits, -._~!$&'()*+,;= and %) nor a bracketed IPv6 address; with user information (user@); with a port that is not 1 to 5 decimal digits up to 65535 (no sign); or with a space, a control byte or DEL anywhere in the text, which a request line or Host header would otherwise carry into the request (a space in a path is written %20). The scheme is not checked here: HttpClient::send gives Err(UnsupportedScheme) for one that is neither http nor https.
Url u = Result::unwrap(Url::parse("HTTPS://Example.com/a/b?x=1#top"));
assert(u.scheme == "https" && u.host == "example.com" && u.port == 443);
assert(u.path == "/a/b" && u.query == "x=1");
assert(Url::target(&u) == "/a/b?x=1");
Url v = Result::unwrap(Url::parse("http://[::1]:8080"));
assert(v.host == "[::1]" && v.path == "/");
assert(Url::text(&v) == "http://[::1]:8080/");
assert(Result::is_err(&Url::parse("http://user@example.com/")));reg-name are refusedrunsassert(Result::is_err(&Url::parse("http://:8080/x")));
assert(Result::is_err(&Url::parse("http://host:+80/")));
assert(Result::is_err(&Url::parse("http://example.com/a b")));
assert(Result::is_err(&Url::parse("http://example.com/x\r\nX-Evil: 1")));
assert(Result::is_err(&Url::parse("http://exa mple.com/")));
assert(Result::is_err(&Url::parse("http://exa\"mple.com/")));
assert(Result::is_err(&Url::parse("http://[::1/")));
assert(Result::unwrap(Url::parse("http://127.0.0.1:65535/a%20b")).port == 65535);Url::target fn
export fn Url::target(ref<Url, shared> u) : StringThe request target: the path, then ? and the query when the query is not empty.
Url::text fn
export fn Url::text(ref<Url, shared> u) : StringThe URL as text again, with the port only when it is not the scheme's default.
The fragment, dropped by Url::parse, does not come back.
Url::query_pairs fn
export fn Url::query_pairs(ref<Url, shared> u) : Vec<Param>The parameters of the URL's query, as form_decode reads them.
Param struct
export struct ParamOne name and value of a query string or an application/x-www-form-urlencoded body.
Names compare exactly (find_param), unlike a header's.
Param::new fn
export fn Param::new(StringView name, StringView value) : ParamA parameter with a copy of name and of value.
Header struct
export struct HeaderOne header field: a name and a value.
Names compare without regard to ASCII case (find_header).
Header::new fn
export fn Header::new(StringView name, StringView value) : HeaderA header with a copy of name and of value.
Request struct
export struct RequestAn HTTP request: the method, the URL, the headers and the body.
For the client, url is absolute (https://…); for a request a server received, it is the target as sent (/path?query). A server's request has the body decoded if it came chunked.
Request::new fn
export fn Request::new(StringView method, StringView url) : RequestA request with method and url, no headers and an empty body.
Request::header fn
export fn Request::header(ref<Request, shared> r, StringView name) : Option<StringView> from rThe value of the request's first header named name, ignoring ASCII case.
Request r = Request::new("POST", "https://example.com/upload");
Vec::push(&mut r.headers, Header::new("Content-Type", "text/plain"));
assert(Option::unwrap(Request::header(&r, "content-type")) == "text/plain");
assert(Option::is_none(&Request::header(&r, "accept")));Response struct
export struct ResponseAn HTTP response: the status, its reason phrase, the headers and the whole body.
The client gives the body decoded if it came chunked, and decompressed if it came with Content-Encoding: gzip or deflate (that header and Content-Length are then dropped).
Response::header fn
export fn Response::header(ref<Response, shared> r, StringView name) : Option<StringView> from rThe value of the response's first header named name, ignoring ASCII case.
Response::text fn
export fn Response::text(ref<Response, shared> r) : Result<String, Utf8Error>The body as text: a copy of its bytes, which must be UTF-8.
Err(e) when they are not.
percent_encode fn
export fn percent_encode(slice<u8, shared> bytes) : StringPercent-encodes bytes as RFC 3986 does: unreserved bytes as they are, every other as %XX.
The unreserved bytes are ASCII letters and digits, -, ., _ and ~; the hex digits are upper case. A space becomes %20; form_encode writes it as +.
percent_decode fn
export fn percent_decode(StringView text) : Option<Vec<u8>>The bytes text percent-encodes, each %XX decoded.
None for a % not followed by two hex digits; hex digits of either case are read. A + stays a +; form_decode reads it as a space.
assert(percent_encode(StringView::as_bytes("a b/ü")) == "a%20b%2F%C3%BC");
Vec<u8> back = Option::unwrap(percent_decode("a%20b%2f"));
assert(Result::unwrap(String::from_utf8(back)) == "a b/");
assert(Option::is_none(&percent_decode("100%")));find_param fn
export fn find_param(slice<Param, shared> params, StringView name) : Option<StringView> from paramsThe value of the first parameter named exactly name, or None when there is none.
The comparison is case-sensitive, unlike find_header's.
form_decode fn
export fn form_decode(StringView text) : Vec<Param>The parameters of a query string (without its ?) or of an application/x-www-form-urlencoded body.
The text is split into name=value pairs at & only, and empty pairs are skipped; a ; is part of a name or value, as the WHATWG URL standard reads it (splitting at ; too would let a cache or proxy that splits at & see other parameters than the program does). A pair without = has an empty value. Each name and value is read with + as a space and then percent-decoded; one that is not UTF-8 after decoding, or holds a bad escape, is kept as given, so nothing is lost.
; separates nothingrunsVec<Param> ps = form_decode("q=red+fish&flag&&n=%41&x=%zz;role=admin");
assert(Vec::len(&ps) == 4);
assert(Option::unwrap(find_param(&ps, "q")) == "red fish");
assert(Option::unwrap(find_param(&ps, "flag")) == "");
assert(Option::unwrap(find_param(&ps, "n")) == "A");
assert(Option::unwrap(find_param(&ps, "x")) == "%zz;role=admin");
assert(Option::is_none(&find_param(&ps, "role")));
assert(Option::is_none(&find_param(&ps, "Q")));form_encode fn
export fn form_encode(slice<Param, shared> params) : StringEncodes params as a query string or form body that form_decode reads back.
The pairs are name=value, joined by &, each name and value percent-encoded with a space as +. There is no leading ?.
+ and a reserved byte an escape, so the value comes back intactrunsVec<Param> ps = Vec::new();
Vec::push(&mut ps, Param::new("q", "a b&c"));
Vec::push(&mut ps, Param::new("lang", "en"));
String body = form_encode(&ps);
assert(body == "q=a+b%26c&lang=en");
Vec<Param> back = form_decode(&body);
assert(back[0].value == "a b&c");find_header fn
export fn find_header(slice<Header, shared> headers, StringView name) : Option<StringView> from headersThe value of the first header named name, ignoring ASCII case, or None when there is none.
reason_phrase fn
export fn reason_phrase(u16 status) : strThe reason phrase RFC 9110 gives a status code, such as "Not Found" for 404.
"" for a status it does not list here.
assert(reason_phrase(404) == "Not Found");
assert(reason_phrase(422) == "Unprocessable Content");
assert(reason_phrase(410) == "Gone");
assert(reason_phrase(299) == "");std::http::client impl/std/http/client.cb
HttpClient struct
export struct HttpClientAn HTTP/1.1 client: the settings and the state it carries from request to request.
roots: the trusted roots https verifies servers against;Noneuntil the first https request loads the system's (TrustStore::system), or a store the program puts there.timeout_ms: the timeout for connecting and for each read and write, in milliseconds.max_redirects: how many redirectssendfollows; 0 follows none, andsendgives the 3xx response itself (itsLocationandSet-Cookiethere to read).max_body: the most bytes a response body may have, after decompression too (TooLargebeyond).headers: sent with every request; a request's own header of the same name replaces one.keep_alive: when set, the last connection is kept open while the server allows, and the next request to the same origin goes on it; when not (the default), each request has its own connection.
A program that makes several https requests keeps one client, so the roots are loaded once.
HttpClient::new fn
export fn HttpClient::new() : HttpClientA client with the default settings.
No roots loaded yet, a 30 s timeout, up to 10 redirects, a 16 MiB body limit, keep_alive off, and the headers User-Agent and Accept-Encoding: gzip, deflate.
HttpClient c = HttpClient::new();
assert(c.timeout_ms == 30000 && c.max_redirects == 10 && !c.keep_alive);
assert(Option::is_none(&c.roots));
assert(Option::is_some(&find_header(&c.headers, "user-agent")));
c.max_body = 1_048_576;HttpClient::send fn
export fn HttpClient::send(ref<HttpClient, exclusive> c, ref<Request, shared> req) : Result<Response, HttpError>Sends req and gives the final response, following redirects.
req.urlis absolute; a scheme other thanhttporhttpsisErr(UnsupportedScheme). The host's addresses are tried in turn.- The request carries
Host, the client's headers and then the request's own (Host,Content-Length,ConnectionandTransfer-Encoding, the client's or the request's, are ignored:sendframes the body itself),Content-Lengthwhen the body is not empty or the method is POST, PUT or PATCH, andConnection: closeunlesskeep_aliveis set. - A method that is not a token, or a header (the client's or the request's) whose name is not a token or whose value holds a control byte other than the tab, is
Err(BadMessage)before anything is sent: a CR LF taken from data would otherwise end the line and inject headers or a second request. - Interim responses (status 1xx) are read past, up to 16 of them; one more is
Err(BadMessage). A body sent withContent-Encoding: gzipordeflatearrives decoded. - A 301, 302 or 303 with a
Locationis followed by GET without the body (HEAD stays HEAD), a 307 or 308 with the method and body kept; a redirect withoutLocationis given as it is.Locationis a URI reference resolved against the request's URL as RFC 3986 §5 resolves one (an absolute URL,//and a host, an absolute path,?and a query, or a path relative to the current one, with.and..segments removed); its fragment is dropped. Withmax_redirects0 no redirect is followed and the 3xx response is given; otherwise one redirect more thanmax_redirectsisErr(TooManyRedirects). Once a redirect leaves the request's origin (scheme, host and port),Authorization,Proxy-AuthorizationandCookie, the client's and the request's, are not sent again. - On a kept connection that proves closed before any of the response arrives, an idempotent request (GET, HEAD, PUT, DELETE, OPTIONS, TRACE) is sent again on a fresh connection; another is
Err(ConnectionClosed), since the server may have acted on it. - Network and TLS failures are
Err(HttpNetFailure(e))andErr(HttpTlsFailure(e)); seeHttpErrorfor the rest.
http_get fn
export fn http_get(StringView url) : Result<Response, HttpError>Sends a GET of url with a fresh HttpClient::new() and gives the response.
For https each call loads the system's roots again; a program that makes several requests keeps an HttpClient.
http_post fn
export fn http_post(StringView url, StringView content_type, slice<u8, shared> body) : Result<Response, HttpError>Sends a POST of body to url, with Content-Type: content_type, from a fresh default client.
As http_get, a program that makes several requests keeps an HttpClient.
std::http::server impl/std/http/server.cb
HttpServer struct
export resource struct HttpServerA listening HTTP/1.1 server: accept gives each client's connection.
max_body: the most bytes a request body may have (TooLargebeyond); 16 MiB frombind.timeout_ms: the timeout for each read and write on the connections it accepts, in milliseconds; 30 s frombind. A request's head (its request line and headers) must also arrive whole within it, from its first byte: a client that sends it a byte at a time cannot hold a connection longer.
The limits apply to every connection accepted after they are set. A server program handles each connection in a thread of its own (spawn). Dropping the server closes its listening socket.
HttpServer::bind fn
export fn HttpServer::bind(SocketAddr a) : Result<HttpServer, NetError>An HTTP server listening at a, with a 16 MiB body limit and a 30 s timeout per read and write.
Port 0 asks the system for a free port (local_addr names it). Errors as TcpListener::bind's.
HttpServer::bind_tls fn
export fn HttpServer::bind_tls(SocketAddr a, PrivateKey key, Vec<Certificate> chain) : Result<HttpServer, NetError>An HTTPS server listening at a: each connection it accepts first completes a TLS 1.3 handshake.
key is the server's private key and chain its certificate first, then its issuers, as TlsStream::server takes them; each connection gets its own copy. The handshake is done by the connection's first request or respond, on the thread that handles it, not by accept. Otherwise as bind.
HttpServer::local_addr fn
export fn HttpServer::local_addr(ref<HttpServer, shared> s) : SocketAddrThe address the server listens at, with the port the system chose for port 0.
HttpServer::accept fn
export fn HttpServer::accept(ref<HttpServer, exclusive> s) : Result<HttpConnection, HttpError>Waits for the next client and gives its connection, with the server's limits and timeouts.
A failure of the listener is Err(HttpNetFailure(e)). For an https server the TLS handshake is not done here: the connection's first request (or respond) does it, on the thread that handles the connection, so a client that connects and never completes the handshake holds up only its own connection, not accept and the clients after it. A client that fails the handshake is then Err(HttpTlsFailure(e)) from that call, and the connection is closed.
HttpConnection struct
export resource struct HttpConnectionOne client's connection to an HttpServer: request, then respond, repeated while it stays open.
The connection stays open for the next request when the request is HTTP/1.1 without close among its Connection options, or HTTP/1.0 with keep-alive among them and without close. Dropping it closes the socket; close ends it cleanly first.
HttpConnection::peer_addr fn
export fn HttpConnection::peer_addr(ref<HttpConnection, shared> c) : SocketAddrThe client's address.
HttpConnection::request fn
export fn HttpConnection::request(ref<HttpConnection, exclusive> c) : Result<Option<Request>, HttpError>Reads the client's next request, or gives None when there is none to read.
Ok(Some(r)):r.urlis the target as sent (/path?query); the body is read byContent-Lengthor chunked encoding, and there is none without them. When an HTTP/1.1 request expects100-continue, theHTTP/1.1 100 Continueis sent before the body is read, unless itsContent-Lengthis overmax_body(thenErr(TooLarge)at once, before the client sends the body); an HTTP/1.0 request's expectation is ignored.Ok(None): the client closed before a request, the server's read timeout (timeout_ms) passed before any byte of a next request came (an idle keep-alive connection; the connection then closes), or the last response ended the connection.Err(BadMessage): a malformed request line (a method that is not a token, a control byte in the target), header or body, an HTTP/1.1 request withoutHost, a request with twoHostfields or one whose value is not a host and an optional port,Content-Lengthfields that disagree, an HTTP/1.0 request withTransfer-Encoding, or chunked framing that is not exact (a line not ended by CR LF, a size that is not hex digits from the line's first byte, a control byte in a chunk extension, a trailer line that is not a header field);Err(TooLarge): a head, or the trailers, over 65536 bytes, or a body overmax_body. The caller answers 400 or 413 if it wishes, and the connection then closes.Err(HttpNetFailure(e)): the connection failed, or the timeout passed in the middle of a request (TimedOut); there is no request to answer, and the connection closes.- On an https connection the first call does the TLS handshake; a client that fails it is
Err(HttpTlsFailure(e)), and the connection is closed.
HttpConnection::respond fn
export fn HttpConnection::respond(ref<HttpConnection, exclusive> c, u16 status, slice<Header, shared> headers, slice<u8, shared> body) : Result<void, HttpError>Writes a response with status, headers and body.
The status line carries reason_phrase(status). Content-Length, Transfer-Encoding and Connection among headers are dropped, since respond frames the body itself: Content-Length is written from body (not for 1xx, 204 or 304), Connection as negotiated, and Date (the time now) unless headers has one. The body is left out after a HEAD request and for a status that has none. After a response that ends the connection, the connection is closed and request gives None.
Err(BadMessage), with nothing written, for a status outside 100 to 599, or a header whose name is not a token or whose value holds a control byte other than the tab: a CR or LF in a value taken from the request (a redirect's Location, a file name) would otherwise end the header and let the client write headers and a body of its own (response splitting). Err(BadMessage) too, with nothing written, when no request is waiting for a response: respond answers what the last request read (a request, or one it found malformed), once.
HttpConnection::close fn
export fn HttpConnection::close(ref<HttpConnection, exclusive> c)Ends the connection: closes its sending side, or sends TLS's close_notify on an https connection.
Does nothing on a connection already closed.
std::database impl/std/database.cb
Scram struct
export struct ScramThe client's side of one SCRAM-SHA-256 exchange (RFC 5802, RFC 7677), without channel binding.
The steps in order: Scram::start, send Scram::client_first, answer the server's first message with Scram::respond, then check the server's final message with Scram::verify. The PostgreSQL client uses it; it is exported so a program can speak the exchange to another server.
Scram::start fn
export fn Scram::start(StringView user, StringView client_nonce) : ScramA new exchange for user with the client's nonce client_nonce.
, and = in user are escaped as =2C and =3D. The nonce should be fresh random text for each exchange, such as the base64 of bytes from os_random_bytes. PostgreSQL ignores the user, and its client sends "".
Scram::client_first fn
export fn Scram::client_first(ref<Scram, shared> s) : StringThe client's first message, n,,n=USER,r=NONCE: no channel binding.
Scram::respond fn
export fn Scram::respond(ref<Scram, exclusive> s, StringView server_first, StringView password) : Result<String, PgError>The client's final message, carrying the proof of password, for the server's first message.
server_first is the server's r=…,s=…,i=…. Remembers the signature Scram::verify then expects. Err(AuthFailed) when the server's nonce does not begin with the client's and add to it; Err(ProtocolViolation) when the message is malformed, asks for an extension (m=), gives an iteration count of 0 or a salt that is not base64.
Scram::verify fn
export fn Scram::verify(ref<Scram, shared> s, StringView server_final) : boolWhether the server's final message (v=…) carries the signature this exchange expects.
false for anything else, an e= error among them, and false before Scram::respond has succeeded (there is no signature to expect yet).
Scram s = Scram::start("user", "rOprNGfwEbeRWgbNEkqO");
assert(Scram::client_first(&s) == "n,,n=user,r=rOprNGfwEbeRWgbNEkqO");
String first = "r=rOprNGfwEbeRWgbNEkqO%hvYDpWUa2RaTCAfuxFIlj)hNlF$k0,";
String::append(&mut first, "s=W22ZaJ0SNY7soEsUEjb6gQ==,i=4");
String reply = Result::unwrap(Scram::respond(&mut s, &first, "pencil"));
assert(StringView::ends_with(&reply, ",p=0ByS2g6XZEtov8MR140MFRsEfy8/X+bacfpPofVtKjE="));
assert(Scram::verify(&s, "v=ITrN4zX09+hsD398Qk6ol73eg0shWPnOWwnwS83jitc="));
assert(!Scram::verify(&s, "e=invalid-proof"));scram_salted_password fn
export fn scram_salted_password(StringView password, slice<u8, shared> salt, usize iterations) : Vec<u8>The SCRAM-SHA-256 salted password: PBKDF2 over HMAC-SHA-256 of password and salt, 32 bytes.
iterations is the server's count. The password is used as given: RFC 5802 prepares it with SASLprep first (saslprep), as the PostgreSQL client does before Scram::respond.
saslprep fn
export fn saslprep(StringView text) : Option<String>text prepared by SASLprep (RFC 4013), as PostgreSQL prepares the passwords it stores and libpq the password it sends; None when the result is prohibited.
The steps of stringprep (RFC 3454) with the SASLprep profile, over Unicode 3.2, in the order and on the text PostgreSQL's own SASLprep uses: ASCII text comes back unchanged, controls included; otherwise the non-ASCII spaces of table C.1.2 (no-break space, U+200B zero width space and the others) become U+0020 and the characters of table B.1 (soft hyphen, zero-width joiners, variation selectors) are removed; None when nothing is left; then None when the mapped text holds a character of the prohibited tables (C.1.2, C.2.1, C.2.2, C.3 to C.9: controls, private use, non-characters, surrogates, tagging and the bidirectional controls) or a code point Unicode 3.2 leaves unassigned (table A.1, the rule for stored strings), or breaks the bidirectional rule (text with a right-to-left character holds no left-to-right one and begins and ends with a right-to-left one); these checks read the mapped text before normalisation, as PostgreSQL's do. The result is the mapped text normalised to NFKC (with Corrigendum #4, as every Unicode version after 3.2). A client that gets None uses the password as given, as libpq does.
assert(Option::unwrap(saslprep("I\u{AD}X")) == "IX");
assert(Option::unwrap(saslprep("user")) == "user");
assert(Option::unwrap(saslprep("USER")) == "USER");
assert(Option::unwrap(saslprep("\u{AA}")) == "a");
assert(Option::unwrap(saslprep("\u{2168}")) == "IX");
assert(Option::unwrap(saslprep("\u{7}")) == "\u{7}");
assert(Option::is_none(&saslprep("\u{627}1")));
assert(Option::unwrap(saslprep("a\u{A0}b")) == "a b");
assert(Option::unwrap(saslprep("\u{D55C}")) == "\u{D55C}");
assert(Option::unwrap(saslprep("e\u{301}")) == "\u{E9}");
assert(Option::is_none(&saslprep("\u{221}\u{A0}x")));assert(Option::unwrap(saslprep("x\u{200B}z")) == "x z");
assert(Option::is_none(&saslprep("\u{AD}\u{200D}")));
assert(Option::is_none(&saslprep("e\u{340}")));
assert(Option::unwrap(saslprep("\u{5D0}\u{2122}\u{5D0}")) == "\u{5D0}TM\u{5D0}");
assert(Option::unwrap(saslprep("\u{2F868}")) == "\u{36FC}");std::database::postgres impl/std/database/postgres.cb
PgError enum
export enum PgErrorWhy a PostgreSQL connection or statement failed.
PgNetFailure(e): connecting, reading or writing failed;esays how.PgTlsFailure(e): the TLS handshake or the encrypted stream failed.TlsRefused: the server does not accept TLS, and the URL asks forverify-full.NoTrustedRoots: the system's trusted roots could not be loaded.BadConnectionUrl: the URL is malformed (PgUrl::parse).UnsupportedAuth: the server asks for a method other than SCRAM-SHA-256 or a password over TLS.AuthRefused: the server asks for the password in clear over an unencrypted connection.AuthFailed: the server refused the credentials, or failed to prove it knows them.Server(e): the server reported an error; the connection stays usable, unless the server ended the session with it (aFATALerror, such as57P01when an administrator terminated the session).ProtocolViolation: a message from the server is malformed or not allowed at that point.ResultTooLarge: the rows exceedmax_result, or more than 65 535 parameters were given.Disconnected: the stream ended, or the connection was closed or broken by an earlier failure.Unsupported(what): the statement needs what this client does not do, aswhatsays:COPY(the connection stays usable), or aclient_encodingother thanUTF8(the connection is closed, since text sent and received would no longer be UTF-8).
PgError::text fn
export fn PgError::text(ref<PgError, shared> e) : Stringe as text for a message; a server error as severity: message (code).
PgServerError struct
export struct PgServerErrorAn error or notice the server reported.
severity is ERROR, FATAL, NOTICE and so on; code the five-character SQLSTATE; message the text; detail, hint and position (a character position from 1 into the statement) when the server gave them.
PgSslMode enum
export enum PgSslModeWhether a connection is encrypted.
Disable: not encrypted.VerifyFull: TLS, with the server's certificate verified for the host name against the trusted roots.
An unverified TLS connection is not offered.
PgUrl struct
export struct PgUrlA parsed connection URL, postgres://user[:password]@host[:port]/database[?sslmode=MODE].
user, password and database are percent-decoded; host is a name, an IPv4 literal or an IPv6 literal without its brackets.
PgUrl::parse fn
export fn PgUrl::parse(StringView text) : Result<PgUrl, PgError>The connection URL text taken apart.
The scheme is postgres or postgresql. The port defaults to 5432, the database to the user, sslmode to verify-full; the only query key is sslmode, disable or verify-full. Err(BadConnectionUrl) for another scheme, no user, no host, a port that is not a number, another query key or mode, a bad percent-encoding, or a %00 in the user, the password or the database (it would end the startup message's string and let the text add parameters of its own).
PgUrl u = Result::unwrap(PgUrl::parse("postgres://app:p%40ss@[::1]/?sslmode=disable"));
assert(u.host == "::1" && u.port == 5432);
assert(u.database == "app");
match (&u.password)
{
Some(p) : assert(*p == "p@ss"),
None : assert(false),
}
Result<PgUrl, PgError> no_user = PgUrl::parse("postgres://db.example/shop");
assert(Result::is_err(&no_user));
assert(Result::is_err(&PgUrl::parse("postgres://me@h/db%00options%00-c%20x=y")));
assert(Result::is_err(&PgUrl::parse("postgres://me%00x@h/db")));PgValue enum
export enum PgValueA statement parameter, sent in the text form the server reads for it.
The server infers each parameter's type from the statement. PgValue::text gives the text each variant is sent as.
PgValue::text fn
export fn PgValue::text(ref<PgValue, shared> value) : Option<String>The text value is sent as; None for Null.
An integer and a float as decimal text: a float that is a whole number within 2^53 without a fraction (2, not 2.0, so it can go into an integer column as well as a float or numeric one, as a whole Json number does; a fraction into an integer column is still refused), one that is not finite as Infinity, -Infinity or NaN; a bool as t or f, bytes as bytea's hex form (\x and the hex digits).
assert(Option::unwrap(PgValue::text(&Bool(true))) == "t");
assert(Option::unwrap(PgValue::text(&Bytes(Vec::filled(2, 0xAB: u8)))) == "\\xabab");
assert(Option::unwrap(PgValue::text(&Float(1.0 / 0.0))) == "Infinity");
assert(Option::unwrap(PgValue::text(&Float(2.0))) == "2");
assert(Option::unwrap(PgValue::text(&Float(-0.0))) == "-0");
assert(Option::unwrap(PgValue::text(&Float(2.5))) == "2.5");
assert(Option::is_none(&PgValue::text(&Null)));PgColumn struct
export struct PgColumnOne column of a result: its name and the OID of its type (23 for int4, 25 for text, 16 for bool).
PgRow struct
export struct PgRowOne row of a result: a cell per column, NULL as None, every other value as the server's text form.
PgRow::get fn
export fn PgRow::get(ref<PgRow, shared> r, usize i) : Option<StringView>The text of the cell at column i of r; None for NULL or past the last column.
PgRow::get_i64 fn
export fn PgRow::get_i64(ref<PgRow, shared> r, usize i) : Option<i64>The cell at column i of r read as an i64.
None for NULL, past the last column, or for text that is not an integer; PgRow::get still gives the text.
PgRow::get_f64 fn
export fn PgRow::get_f64(ref<PgRow, shared> r, usize i) : Option<f64>The cell at column i of r read as an f64, NaN, Infinity and -Infinity included.
None for NULL, past the last column, or for text that is not a number.
PgRow::get_bool fn
export fn PgRow::get_bool(ref<PgRow, shared> r, usize i) : Option<bool>The cell at column i of r read as a bool: t is true, f is false.
None for NULL, past the last column, or for any other text.
PgRow::get_bytes fn
export fn PgRow::get_bytes(ref<PgRow, shared> r, usize i) : Option<Vec<u8>>The cell at column i of r read as bytes from bytea's hex form (\x and hex digits).
None for NULL, past the last column, or for text of another form.
PgRow::get_datetime fn
export fn PgRow::get_datetime(ref<PgRow, shared> r, usize i) : Option<DateTime>The cell at column i of r read as a moment by DateTime::from_iso.
That reads PostgreSQL's text for a timestamptz (2023-11-15 09:13:20+11, converted to UTC), a timestamp (2023-11-14 22:13:20, no zone: the fields as written) and a date (its midnight), as the server writes them in its default DateStyle, ISO. A fraction of the seconds is dropped; for milliseconds read the text with unix_ms_from_iso(Option::unwrap(PgRow::get(&row, i))). None for NULL, past the last column, or text of another form (infinity, a year BC, another DateStyle).
None for text of another form, as for NULL and past the last columnrunsVec<Option<String>> cells = Vec::new();
Vec::push(&mut cells, Some("42"));
Vec::push(&mut cells, Some("t"));
Vec::push(&mut cells, None);
Vec::push(&mut cells, Some("2023-11-15 09:13:20.25+11"));
PgRow row = PgRow { .cells = cells };
assert(DateTime::to_iso(&Option::unwrap(PgRow::get_datetime(&row, 3))) == "2023-11-14T22:13:20Z");
assert(Option::is_none(&PgRow::get_datetime(&row, 0)));
assert(Option::unwrap(PgRow::get_i64(&row, 0)) == 42);
assert(Option::unwrap(PgRow::get_bool(&row, 1)));
assert(Option::is_none(&PgRow::get_bool(&row, 0)));
assert(Option::is_none(&PgRow::get(&row, 2)) && Option::is_none(&PgRow::get(&row, 9)));PgResult struct
export struct PgResultWhat a statement gave: its columns and rows, the count of rows affected, and the command tag.
columns and rows are empty for a statement without a result set. affected is the number the tag ends with, 0 when it has none; tag is the tag itself (SELECT 3, INSERT 0 1, CREATE TABLE).
PgResult::column fn
export fn PgResult::column(ref<PgResult, shared> res, StringView name) : Option<usize>The index of the first column named exactly name; None when there is none.
PgConnection struct
export resource struct PgConnectionAn open connection to a PostgreSQL server.
Not independently audited: this client is implemented to PostgreSQL's wire protocol and RFC 5802 and RFC 7677, tested against their vectors and against a PostgreSQL server on loopback, and fuzzed continuously; it has not been independently audited.
One statement runs at a time, its parameters bound (never spliced into the SQL text), and rows come back as text. A connection is one thread's: a program that queries from several threads keeps a connection per thread. notices holds the notices received so far, for the program to read and clear; max_result is the most a statement's rows may take in bytes (16 MiB). Dropping a connection without PgConnection::close closes the socket without telling the server. Text is UTF-8: a SET client_encoding to another encoding ends the connection (Unsupported). No binary rows, cursors, COPY (Unsupported), LISTEN/NOTIFY or channel binding; a statement is cancelled only when its reply times out (PgConnection::query).
PgConnection::connect fn
export fn PgConnection::connect(StringView url) : Result<PgConnection, PgError>Connects to the server url names, with the system's trusted roots and a 30-second timeout for connecting and for each read and write.
The timeout bounds each wait for a statement's reply too; PgConnection::set_timeout_ms changes it (0 waits for ever), for statements that take longer. The roots are loaded only for verify-full: Err(NoTrustedRoots) when they cannot be. Otherwise as PgConnection::connect_with.
PgConnection::connect_with fn
export fn PgConnection::connect_with(StringView url, ref<TrustStore, shared> roots, u64 timeout_ms) : Result<PgConnection, PgError>Connects to the server url names, verifying its certificate against roots.
roots is unused for sslmode=disable. timeout_ms bounds connecting to each of the host's addresses in turn and then every read and write, the wait for each statement's reply included (see PgConnection::query for a reply that takes longer; PgConnection::set_timeout_ms changes it). Authenticates by SCRAM-SHA-256, or by the password over TLS only. Its errors include BadConnectionUrl, PgNetFailure when no address connects, TlsRefused, PgTlsFailure, UnsupportedAuth, AuthRefused, AuthFailed, Server and ProtocolViolation.
PgConnection::parameter fn
export fn PgConnection::parameter(ref<PgConnection, shared> c, StringView name) : Option<StringView> from cThe value the server reported for the run-time parameter name at startup; None when it gave none.
Such as server_version, server_encoding or TimeZone.
PgConnection::set_timeout_ms fn
export fn PgConnection::set_timeout_ms(ref<PgConnection, exclusive> c, u64 ms)Sets the timeout, in milliseconds, for each read and write on the connection from now on, the wait for a statement's reply included; 0 waits for ever.
A statement that may run longer than the timeout connect or connect_with set (a report, a migration, CREATE INDEX) is run after a larger one, or 0.
PgConnection::query fn
export fn PgConnection::query(ref<PgConnection, exclusive> c, StringView sql, slice<PgValue, shared> params) : Result<PgResult, PgError>Runs one statement with $1, $2, ... bound to params, and gives its result.
A server error is Err(Server(e)) once the server is ready again, and the connection stays usable (unless the server ended the session: a FATAL error is given as Server(e) too, and the connection is then closed); Err(ResultTooLarge) when the rows exceed max_result, also leaving it usable. A COPY is Err(Unsupported(_)), the connection usable. A network or protocol failure closes the connection, and every later call gives Err(Disconnected). Transactions are statements: BEGIN, COMMIT, ROLLBACK.
When the reply does not come within the connection's timeout, the statement is cancelled (a CancelRequest, as libpq's PQcancel sends) and the reply waited for once more: what is given is then what the server did, a cancelled statement's Err(Server(e)) (SQLSTATE 57014) or the result of a statement that completed first, and the connection stays usable. Only when that wait times out as well is the connection closed with Err(PgNetFailure(TimedOut)), and the statement may then have completed or not. PgConnection::set_timeout_ms sets a longer timeout, or none. A statement without parameters takes an empty slice: array<PgValue, 0> none = []; and &none (a bare &[] is an array<i32, 0>).
PgConnection::execute fn
export fn PgConnection::execute(ref<PgConnection, exclusive> c, StringView sql, slice<PgValue, shared> params) : Result<u64, PgError>Runs a statement without rows, as PgConnection::query does, and gives the count of rows it affected. Without parameters it takes an empty slice, array<PgValue, 0> none = []; and &none.
PgConnection::run_script fn
export fn PgConnection::run_script(ref<PgConnection, exclusive> c, StringView sql) : Result<void, PgError>Runs sql as a script of statements separated by ;, without parameters, discarding every result.
The first server error is Err(Server(e)); a timed-out reply, a COPY, a FATAL error and a changed client_encoding are as for PgConnection::query. Err(Disconnected) on a closed connection.
PgConnection::close fn
export fn PgConnection::close(ref<PgConnection, exclusive> c)Tells the server the session is over and closes the connection; nothing when it is already closed.
std::encoding::json impl/std/encoding/json.cb
Json enum
export enum JsonA JSON value: null, a boolean, a number, a string, an array or an object.
JsonNull,JsonBool(b):null,trueandfalse.JsonNumber(x): every number is anf64, so an integer beyond 2^53 loses precision.JsonText(s): a string, its escapes decoded.JsonArray(items): the elements, in order.JsonObject(members): the members in the order read or added; duplicate keys are kept as read.
The variant names carry Json so that none clashes with another std enum's. Dropping a Json frees the whole tree.
Json::parse fn
export fn Json::parse(StringView text) : Result<Json, ParseError>The JSON value text holds, with any white space around it.
Err(Empty)when the text holds no value at all.Err(Invalid(i))at the first byte that does not fit, or the length when the text stops short.Err(OutOfRange)for a number beyondf64, or arrays and objects nested deeper than 512.
In a string, a surrogate pair written as two \u escapes is joined, and a lone surrogate becomes U+FFFD.
match (Json::parse("[1, 2"))
{
Err(Invalid(i)) : assert(i == 5),
_ : assert(false),
}
match (Json::parse("[1] x"))
{
Err(Invalid(i)) : assert(i == 4),
_ : assert(false),
}Json::text fn
export fn Json::text(ref<Json, shared> j) : StringThe value j as compact JSON text: no white space, members and elements in order.
A whole number within 2^53 is written without a fraction (a negative zero as -0.0, keeping its sign), any other in the shortest digits that read back as it, and a NaN or an infinity, which JSON cannot write, as null. Strings escape ", \ and the control characters; other characters, non-ASCII included, are written as they are. Apart from a NaN or an infinity, Json::parse of the text gives j back.
Json::pretty fn
export fn Json::pretty(ref<Json, shared> j) : StringThe value j as JSON text for people: one element or member per line, two spaces per level.
A key is followed by : , an empty array or object stays [] or {}, and there is no newline at the end. Numbers and strings are written as Json::text writes them.
Json a = JsonArray(Vec::new());
Json::push(&mut a, JsonNull);
Json::push(&mut a, JsonText("x"));
String p = Json::pretty(&a);
assert(p == "[\n null,\n \"x\"\n]");Json::get fn
export fn Json::get(ref<Json, shared> j, StringView key) : Option<ref<Json, shared>> from jThe value of the first member named key when j is an object, else None.
None also when there is no such member. The members are searched in order; for many lookups in a large object make an index once with Json::key_index.
get, at and the as_ functionsrunsJson doc = Result::unwrap(Json::parse("{\"name\": \"ok\", \"n\": [1, 2.5]}"));
assert(Option::unwrap(Json::as_text(Option::unwrap(Json::get(&doc, "name")))) == "ok");
auto n = Option::unwrap(Json::get(&doc, "n"));
assert(Json::as_i64(Option::unwrap(Json::at(n, 0))) == Some(1: i64));
assert(Json::as_i64(Option::unwrap(Json::at(n, 1))) == None);
assert(Option::is_none(&Json::get(&doc, "missing")));Json::at fn
export fn Json::at(ref<Json, shared> j, usize i) : Option<ref<Json, shared>>Element i of j when j is an array, else None.
None also when i is past the end.
Json::lookup fn
export fn Json::lookup(ref<Json, shared> j, StringView path) : Option<ref<Json, shared>> from jThe value at the dotted path below j: Json::lookup(&doc, "servers.0.host").
Each part of the path names a member of an object, or, where the value reached is an array, an element by its index written in decimal. None when any part is not there. A key that itself contains a dot is reached with Json::get.
NonerunsJson doc = Result::unwrap(Json::parse("{\"servers\": [{\"host\": \"a\"}, {\"host\": \"b\"}], \"n\": 1}"));
assert(Option::unwrap(Json::as_text(Option::unwrap(Json::lookup(&doc, "servers.1.host")))) == "b");
assert(Json::as_i64(Option::unwrap(Json::lookup(&doc, "n"))) == Some(1: i64));
assert(Option::is_none(&Json::lookup(&doc, "servers.2.host")));
assert(Option::is_none(&Json::lookup(&doc, "servers.x")));Json::is_null fn
export fn Json::is_null(ref<Json, shared> j) : boolWhether j is JsonNull.
Json::as_bool fn
export fn Json::as_bool(ref<Json, shared> j) : Option<bool>The boolean j holds, or None when j is not JsonBool.
Json::as_f64 fn
export fn Json::as_f64(ref<Json, shared> j) : Option<f64>The number j holds, or None when j is not JsonNumber.
Json::as_i64 fn
export fn Json::as_i64(ref<Json, shared> j) : Option<i64>The number j holds as an integer, or None when it is not a number, not whole, or outside i64.
Json::as_text fn
export fn Json::as_text(ref<Json, shared> j) : Option<StringView>A view of the string j holds, or None when j is not JsonText.
Json::as_array fn
export fn Json::as_array(ref<Json, shared> j) : Option<ref<Vec<Json>, shared>>The elements of j when it is an array, or None for another kind of value.
Json::as_object fn
export fn Json::as_object(ref<Json, shared> j) : Option<ref<Vec<JsonMember>, shared>>The members of j, in order, when it is an object, or None for another kind of value.
Json::set fn
export fn Json::set(ref<Json, exclusive> j, StringView key, Json v)Sets member key of the object j to v.
The first member of that name is replaced, or else a new member appended. Faults (diag.assert-failed) when j is not an object. The members are searched in order, so building an object of many thousands of keys this way takes time growing with the square of their count: append keys known to be new with Json::push_member.
Json::push_member fn
export fn Json::push_member(ref<Json, exclusive> j, StringView key, Json v)Appends the member key: v to the object j, without looking for one of that name first.
For building a large object whose keys are known to be distinct (from a HashMap, a database's rows): each call takes the same time, where Json::set searches the members. A key already there is kept twice, as JSON allows (Json::get gives the first). Faults (diag.assert-failed) when j is not an object.
Json::key_index fn
export fn Json::key_index(ref<Json, shared> j) : HashMap<String, usize>Where each key of the object j is first among its members: members[at].key == key.
For many lookups in a large object, where each Json::get searches the members: make the index once, then HashMap::get(&at, key) gives the member's position in Json::as_object(&j). Empty when j is not an object. The index does not follow later changes to j.
push_member and read through key_indexrunsJson o = JsonObject(Vec::new());
for (usize i = 0; i < 1000; i += 1)
{
Json::push_member(&mut o, &sprintf("k%v", i), JsonNumber(to_float<f64>(i)));
}
HashMap<String, usize> at = Json::key_index(&o);
ref<Vec<JsonMember>, shared> members = Option::unwrap(Json::as_object(&o));
usize k = *Option::unwrap(HashMap::get(&at, "k777"));
assert(Json::as_f64(&members[k].value) == Some(777.0));Json doc = JsonObject(Vec::new());
Json::set(&mut doc, "a", JsonNumber(1.0));
Json::set(&mut doc, "b", JsonArray(Vec::new()));
Json::set(&mut doc, "a", JsonBool(true));
String t = Json::text(&doc);
assert(t == "{\"a\":true,\"b\":[]}");Json::push fn
export fn Json::push(ref<Json, exclusive> j, Json v)Appends v to the array j.
Faults (diag.assert-failed) when j is not an array.
JsonMember struct
export struct JsonMemberOne member of a JSON object: its key and its value.
key: the member's name, its escapes decoded.value: its value.
std::encoding::hex impl/std/encoding/hex.cb
to_hex fn
export fn to_hex(slice<u8, shared> bytes) : StringThe bytes as lowercase hexadecimal text, two digits each.
from_hex fn
export fn from_hex(StringView text) : Result<Vec<u8>, ParseError>The bytes the hexadecimal text spells, two digits a byte, in either case.
The empty text is no bytes, so from_hex(to_hex(b)) gives b back for every b, the empty one too (as base64_decode does).
Err(Invalid(i))at the first byte that is not a hexadecimal digit.Err(Invalid(len))when the digits are odd in number.
Vec<u8> b = Result::unwrap(from_hex("00FFa0"));
assert(Vec::len(&b) == 3);
assert(b[1] == 255);
String h = to_hex(&b);
assert(h == "00ffa0");
match (from_hex("abc"))
{
Err(Invalid(i)) : assert(i == 3),
_ : assert(false),
}
// Report 287: no bytes round-trip.
assert(Vec::len(&Result::unwrap(from_hex(""))) == 0);std::encoding::base64 impl/std/encoding/base64.cb
base64_encode fn
export fn base64_encode(slice<u8, shared> bytes) : StringThe bytes in base64 (RFC 4648 §4), padded with = to a multiple of four characters.
The alphabet is the standard one: A-Z, a-z, 0-9, + and /.
base64_decode fn
export fn base64_decode(StringView text) : Result<Vec<u8>, ParseError>The bytes the base64 text spells, read as base64_encode writes it.
Padding is required. Empty text gives no bytes.
Err(Invalid(len))when the length is not a multiple of four.Err(Invalid(i))at the first byte that is not a base64 character; a=before the final one or two is such a byte.Err(Invalid(i))at the last character before the padding when it leaves bits over that are not zero:"QR=="is refused, sincebase64_encodewrites"A"as"QQ==". Each byte string has one text.
= inside it is an error, and so are bits it leaves over that are not zerorunsStringView text = "hi!?";
String e = base64_encode(StringView::as_bytes(text));
assert(e == "aGkhPw==");
Vec<u8> d = Result::unwrap(base64_decode(&e));
assert(Vec::len(&d) == 4);
match (base64_decode("aG=hPw=="))
{
Err(Invalid(i)) : assert(i == 2),
_ : assert(false),
}
match (base64_decode("QR=="))
{
Err(Invalid(i)) : assert(i == 1),
_ : assert(false),
}std::encoding::toml impl/std/encoding/toml.cb
Toml enum
export enum TomlA TOML value: a string, an integer, a float, a boolean, a date-time, an array or a table.
TomlString(s): a string, its escapes decoded.TomlInteger(i): an integer, exact ini64.TomlFloat(x): a float,infandnanincluded.TomlBool(b):trueorfalse.TomlDateTime(d): one of the four date-time forms (seeTomlDateTime).TomlArray(items): the elements, in order; elements may be of different kinds.TomlTable(members): the members in the order read or added; a key occurs once.
The variant names carry Toml so that none clashes with another std enum's. Dropping a Toml frees the whole tree.
Toml::parse fn
export fn Toml::parse(StringView text) : Result<Toml, ParseError>The TOML document text holds, as a table.
The whole of TOML 1.0: tables and arrays of tables under headers, dotted keys, inline tables, the four string forms with every escape, integers in decimal, hexadecimal, octal and binary with underscores, floats with inf and nan, and the four date-time forms. An empty document is an empty table.
Err(Invalid(i))at the first byte that does not fit; at a key or a table header's name that is defined twice or would add to a table the format has closed (one defined by an earlier header, or an inline table); or at a date or time with a field beyond its range (a month 13, a 30 February, an hour 24).Toml::describe_errorsays which, for a message:line 3, column 1: name is defined twice.Err(OutOfRange)for an integer beyondi64, a float beyondf64, or tables and arrays nested deeper than 512: each array and inline table is one level, and so is each part of a header or a dotted key ([a.b]anda.b = 1are two).
Err(Empty) never occurs: a document with no key is an empty table.
Toml::describe_error fn
export fn Toml::describe_error(ref<ParseError, shared> e, StringView text) : StringThe error Toml::parse(text) gave, as a message for a person: ParseError::describe's, with TOML's reason.
line 3, column 1: name is defined twice for a key or a table defined twice (or added to a table the format has closed); line 1, column 7: 2026-13-01 is not a date or time (a field beyond its range) for a month 13; otherwise ParseError::describe(e, text). e is the error Toml::parse gave for text.
Toml::text fn
export fn Toml::text(ref<Toml, shared> t) : StringThe value t as TOML text.
A table is written as a document: its plain members as key = value lines, then each member that is a table under a [header], and each non-empty array of tables under [[headers]], in order, recursively; a key is bare when it can be and quoted otherwise. Strings are basic strings with ", \ and the control characters escaped; a float is written in the shortest digits that read back as it, with inf and nan; a date-time as TomlDateTime::text writes it. A value that is not a table is written in the form it takes after =: arrays as [a, b], inline tables as { k = v }. Comments are not kept. Toml::parse of the text gives t back, the plain members of each table before its sub-tables.
Toml doc = Result::unwrap(Toml::parse("[server]\nhost = \"example.org\"\nports = [80, 443]\n[server.tls]\ncert = 'a b'\n[[users]]\nname = \"ann\"\n[[users]]\nname = \"bob\"\n"));
String t = Toml::text(&doc);
assert(t == "[server]\nhost = \"example.org\"\nports = [80, 443]\n\n[server.tls]\ncert = \"a b\"\n\n[[users]]\nname = \"ann\"\n\n[[users]]\nname = \"bob\"\n");
assert(Toml::text(&Result::unwrap(Toml::parse(&t))) == t);Toml::get fn
export fn Toml::get(ref<Toml, shared> t, StringView key) : Option<ref<Toml, shared>> from tThe value of the member named key when t is a table, else None.
None also when there is no such member.
Toml::at fn
export fn Toml::at(ref<Toml, shared> t, usize i) : Option<ref<Toml, shared>>Element i of t when t is an array, else None.
None also when i is past the end.
Toml::lookup fn
export fn Toml::lookup(ref<Toml, shared> t, StringView path) : Option<ref<Toml, shared>> from tThe value at the dotted path below t: Toml::lookup(&doc, "database.ports.0").
Each part of the path names a member of a table, or, where the value reached is an array, an element by its index written in decimal. None when any part is not there. A key that itself contains a dot is reached with Toml::get.
Toml::as_text fn
export fn Toml::as_text(ref<Toml, shared> t) : Option<StringView>The string t holds as a view, or None when t is not TomlString.
Toml::as_i64 fn
export fn Toml::as_i64(ref<Toml, shared> t) : Option<i64>The integer t holds, or None when t is not TomlInteger.
Toml::as_f64 fn
export fn Toml::as_f64(ref<Toml, shared> t) : Option<f64>The float t holds, or None when t is not TomlFloat; an integer is not converted.
Toml::as_bool fn
export fn Toml::as_bool(ref<Toml, shared> t) : Option<bool>The boolean t holds, or None when t is not TomlBool.
Toml::as_datetime fn
export fn Toml::as_datetime(ref<Toml, shared> t) : Option<TomlDateTime>The date-time t holds, or None when t is not TomlDateTime.
Toml::as_array fn
export fn Toml::as_array(ref<Toml, shared> t) : Option<ref<Vec<Toml>, shared>>The elements of t when it is an array, or None for another kind of value.
Toml::as_table fn
export fn Toml::as_table(ref<Toml, shared> t) : Option<ref<Vec<TomlMember>, shared>>The members of t, in order, when it is a table, or None for another kind of value.
Toml::set fn
export fn Toml::set(ref<Toml, exclusive> t, StringView key, Toml v)Sets member key of the table t to v.
The member of that name is replaced, or else a new member appended. Faults (diag.assert-failed) when t is not a table.
Toml::push fn
export fn Toml::push(ref<Toml, exclusive> t, Toml v)Appends v to the array t.
Faults (diag.assert-failed) when t is not an array.
Toml doc = TomlTable(Vec::new());
Toml::set(&mut doc, "name", TomlString("demo"));
Toml ports = TomlArray(Vec::new());
Toml::push(&mut ports, TomlInteger(8080));
Toml::push(&mut ports, TomlInteger(8081));
Toml server = TomlTable(Vec::new());
Toml::set(&mut server, "ports", ports);
Toml::set(&mut server, "debug", TomlBool(false));
Toml::set(&mut doc, "server", server);
Toml::set(&mut doc, "name", TomlString("demo 2"));
assert(Toml::text(&doc) == "name = \"demo 2\"\n\n[server]\nports = [8080, 8081]\ndebug = false\n");TomlMember struct
export struct TomlMemberOne member of a TOML table: its key and its value.
key: the member's name, one key part (a dotted keya.bis a memberaholding a table with a memberb).value: its value.
TomlDateKind enum
export enum TomlDateKindWhich of the four date-time forms a TomlDateTime is.
TomlOffsetDateTime: a date, a time and an offset from UTC:1979-05-27T07:32:00Z,…-08:00.TomlLocalDateTime: a date and a time with no offset:1979-05-27T07:32:00.TomlLocalDate: a date alone:1979-05-27.TomlLocalTime: a time alone:07:32:00.
TomlDateTime struct
export struct TomlDateTimeA TOML date-time: the fields of RFC 3339's form, and kind, which of the four forms it is.
kind: the form; the fields a form does not have are 0.year,month,day: the date (month1 to 12,day1 to the month's length).hour,minute,second: the time (secondup to 60 for a leap second).nanoseconds: the fraction of the second, 0 to 999 999 999; digits beyond nine are dropped when read.offset_minutes: the offset from UTC in minutes,-1439to1439; 0 for every other form.
A plain struct, assigned by copying. TomlDateTime::text writes it as the format does.
TomlDateTime::text fn
export fn TomlDateTime::text(ref<TomlDateTime, shared> d) : StringThe date-time as TOML (and RFC 3339) writes it: the date, T, the time, its fraction when there is one, and the offset as Z or ±HH:MM; a local form leaves out what it does not have.
String text = "a = 1979-05-27T07:32:00.999999Z\nb = 1979-05-27T00:32:00.5-07:00\nc = 1979-05-27T07:32:00\nd = 1979-05-27\ne = 07:32:00\n";
Toml doc = Result::unwrap(Toml::parse(&text));
assert(Toml::text(&doc) == text);
TomlDateTime b = Option::unwrap(Toml::as_datetime(Option::unwrap(Toml::get(&doc, "b"))));
assert(b.nanoseconds == 500000000 && b.offset_minutes == -420 && TomlDateTime::text(&b) == "1979-05-27T00:32:00.5-07:00");std::compress impl/std/compress.cb
CompressError enum
export enum CompressErrorWhy a stream could not be decompressed.
Corrupt(i): the stream is not DEFLATE (or not the wrapper asked for), or its checksum does not match, first seen at bytei.Truncated: the stream ends before its last block or its trailer.Oversize: the output would exceed themaxgiven.
CompressError::text fn
export fn CompressError::text(ref<CompressError, shared> e) : strA short description of e for a message, such as corrupt compressed data.
inflate fn
export fn inflate(slice<u8, shared> data, usize max) : Result<Vec<u8>, CompressError>The bytes a raw DEFLATE stream (RFC 1951, no header or checksum) encodes, at most max of them.
Err(Oversize) as soon as the output would exceed max: a limit against a small stream that expands without bound. Err(Truncated) when data ends inside a block; Err(Corrupt(i)) at byte i for a malformed block. Bytes after the final block are ignored. Reads stored, fixed and dynamic Huffman blocks.
deflate fn
export fn deflate(slice<u8, shared> data) : Vec<u8>data compressed as a raw DEFLATE stream (RFC 1951, no header or checksum).
One fixed strategy, so every implementation writes the same bytes: LZ77 over a 32 KiB window, each block stored, fixed or dynamic Huffman, whichever is shortest. Empty data is one empty block (03 00).
Wikipedia is fixed by RFC 1950runsVec<u8> nothing = Vec::new();
Vec<u8> empty = deflate(¬hing);
assert(Vec::len(&empty) == 2 && empty[0] == 0x03 && empty[1] == 0x00);
assert(Vec::len(&Result::unwrap(inflate(&empty, 0))) == 0);
assert(adler32(b"Wikipedia") == 300286872);
assert(adler32(¬hing) == 1);adler32 fn
export fn adler32(slice<u8, shared> data) : u32The Adler-32 checksum of data (RFC 1950), zlib's checksum; 1 for no bytes.
For CRC-32, gzip's checksum, use crc32 in std::crypto.
zlib_deflate fn
export fn zlib_deflate(slice<u8, shared> data) : Vec<u8>data compressed as a zlib stream (RFC 1950): a two-byte header, the DEFLATE stream, the Adler-32.
zlib_inflate fn
export fn zlib_inflate(slice<u8, shared> data, usize max) : Result<Vec<u8>, CompressError>The bytes a zlib stream encodes, at most max of them, its header checked and its checksum verified.
Err(Corrupt(0)) for a header that is not DEFLATE without a preset dictionary; Err(Corrupt(i)) at the trailer when the Adler-32 does not match; Err(Truncated) for fewer than 6 bytes or a missing trailer; otherwise as inflate, Err(Oversize) included.
Corrupt at the trailer, the last four bytesrunsVec<u8> z = zlib_deflate(b"hello hello hello");
usize last = Vec::len(&z) - 1;
z[last] = z[last] ^ 1;
match (zlib_inflate(&z, 100))
{
Err(Corrupt(at)) : assert(at == last - 3),
_ : assert(false),
}gzip fn
export fn gzip(slice<u8, shared> data) : Vec<u8>data compressed as a gzip file (RFC 1952), with no name, time or extra fields in its header.
The trailer holds the CRC-32 and the length of data modulo 2 to the power 32.
gunzip fn
export fn gunzip(slice<u8, shared> data, usize max) : Result<Vec<u8>, CompressError>The bytes a gzip file encodes, every member in turn, at most max of them.
Each header's optional fields are skipped, and zero bytes after the last member (a tape's or a device's padding) are the end. Each member is decoded apart, as gzip does: a distance into an earlier member's output is Corrupt. Err(Corrupt(i)) at a header that is not gzip's, or at a trailer whose CRC-32 or length does not match; Err(Truncated) for a member cut short; otherwise as inflate, Err(Oversize) included.
Oversize when max is one byte short of the outputrunsVec<u8> data = Vec::filled(1000, b'a');
Vec<u8> packed = gzip(&data);
assert(Vec::len(&packed) < 100);
Vec<u8> back = Result::unwrap(gunzip(&packed, 1000));
assert(Vec::len(&back) == 1000 && back[999] == b'a');
match (gunzip(&packed, 999))
{
Err(Oversize) : {},
_ : assert(false),
}std::ffi impl/std/ffi.cb
NulError struct
export struct NulErrorThe error of text that holds a NUL byte, which C would take as its end.
offset is the position of the first NUL.
NulError::text fn
export fn NulError::text(ref<NulError, shared> e) : strA short description of the error for messages: "holds a NUL byte".
CString struct
export struct CStringText followed by one NUL byte, for a C function that takes const char *.
Made by CString::new or CString::from_bytes, which refuse text that already holds a NUL. CString::ptr is the address to pass; it stays valid while the CString lives, even if the CString itself is moved, and dropping the CString frees the bytes. The C function must not write through the address or keep it.
CString::from_bytes fn
export fn CString::from_bytes(slice<u8, shared> b) : Result<CString, NulError>b with a NUL byte after it, or Err with the position of the first NUL already in b.
The bytes need not be UTF-8: a path or a name from another system is often not.
CString::new fn
export fn CString::new(StringView s) : Result<CString, NulError>s with a NUL byte after it, or Err with the position of the first NUL already in s.
A literal where a StringView is expected is made into one: CString::new("HOME").
CString::ptr fn
export fn CString::ptr(ref<CString, shared> c) : rawptr<u8>The address of the first byte, to pass to C as a const char *.
Taking the address is safe; the call that uses it is inside unsafe. The address is valid until the CString is dropped.
CString::len fn
export fn CString::len(ref<CString, shared> c) : usizeThe length of the text, without the NUL.
CString::as_bytes fn
export fn CString::as_bytes(ref<CString, shared> c) : slice<u8, shared>The text without the NUL, as bytes.
copy_to_raw fn
export fn copy_to_raw<T: plain>(slice<T, shared> s, rawptr<T> p)The elements of s, plain data, copied to C memory at p: an output buffer a C caller owns (D-0257). Called inside unsafe { } ([Trusted-Call]): the caller vouches that p has room for them and that nothing else uses that memory for the call.
is_null fn
export fn is_null<T>(rawptr<T> p) : boolWhether p is C's NULL, the address null_rawptr<T>().
C functions return NULL for "none": getenv of a name that is not set, fopen of a file that cannot be opened. Testing for it is safe; reading through p is not.
AAppendix: diagnostics
Every named diagnostic, what it means, and the usual fix.
Every diagnostic has a stable name. Static means the program is rejected before it runs; dynamic means a checked fault terminates the program; both means the same rule is applied statically where the checker can see the problem and dynamically otherwise.
| Diagnostic | Phase | Meaning | Usual fix |
|---|---|---|---|
diag.syntax-error | static | the text is not a CobaltC program by the grammar | correct the text there; the message names what was expected and what was found |
diag.unbound-name | static | a name resolves to nothing | declare it, fix the spelling, or import it |
diag.ambiguous-name | static | two imports or two enums supply the same name | qualify it |
diag.name-not-visible | static | the item is private to another module | mark it export or move the use |
diag.module-file-not-found | static | module m "…"; names no readable file | fix the path (relative to the declaring file) or create the file |
diag.module-cycle | static | a file's module body loads itself again, directly or through other files | move the shared items into a third file both name |
diag.module-file-duplicate | static | one file is named by two module declarations | declare it once; reach it by qualified path or import |
diag.const-not-constant | static | a const's initializer is not a constant expression, or a constant depends on itself | use only constants in it (a local const helps), or compute the value in a function |
diag.static-assert-failed | static | a static_assert condition is false, for the program or for one instantiation | fix what the assertion guards, or the assertion |
diag.static-assert-not-constant | static | a static_assert condition (or message argument) is not a bool constant expression | check run-time values with assert; name compile-time values with const |
diag.duplicate-item | static | two declarations add the same qualified name, or an entry point (extern fn with a body) takes a name C, its library or the runtime has | rename one, or move it into a module; rename the entry point (a module does not change its C name) |
diag.instantiation-unbounded | static | a generic function's instantiations do not end: a type argument nested over 64 deep or of over 4,096 parts, or a generic type whose fields hold it at a larger argument (spec/16 [Type-Recursion-Expanding]) | pass the larger value as a type the function already has (a Vec, a Box of one type) |
diag.duplicate-local | static | a name declared twice in one block (a function's parameters and a loop's or pattern's names count as declared in the block they govern) | assign to the existing variable, or choose another name; an inner block may shadow it |
diag.foreign-associated-fn | static | fn T::name in a module that does not declare T (for example fn Vec::first_or outside std) | declare a plain function, or put it in T's module |
diag.no-main | static | no fn main() at the root module (a main inside a module is just m::main) | declare fn main() at the root, or run the file that has one |
diag.div-overflow | both | min / -1 or min % -1 for a signed type | checked_div, or widen first |
diag.transfer-without-authority | both | a move from a binding that no longer holds its resource (already moved or destroyed) | move from the current holder |
diag.type-mismatch | static | an operand or argument has the wrong type | convert explicitly; fix the types |
diag.unbounded-type-parameter | static | arithmetic, comparison, field access or a call on a bare T | use a concrete type |
diag.cannot-infer-type-parameter | static | a generic argument is fixed by nothing | write name<T>(…) or declare the variable's type |
diag.break-outside-loop, diag.return-outside-fn | static | misplaced control statement | move it |
diag.capture-list-mismatch | static | the closure's […] does not equal its free variables | add or remove names |
diag.stale-binding | both | use of a moved-from, dropped, or dead binding or reference | use the current owner; re-fetch after a move or reallocation |
diag.use-of-uninitialized | static | a read on a path with no prior write | initialise on every path; initialise aggregates whole |
diag.reference-escapes-scope | static | a reference stored or returned beyond its referent's block | return an owned value |
diag.lifetime-elision-ambiguous | static | a reference or view returned from a function with no reference parameter; or a reference, a view or a value holding them (Option<ref<T, shared>>, Vec<StringView>) returned from one with two or more and no from clause | with several, name the parameters it may come from (from a, from a, b) or take the others by value; with none, return an owned value |
diag.result-source-invalid | static | a from clause naming something other than a reference parameter, or one twice, or on a result holding no reference | name once each reference parameter the result may come from, or drop the clause |
diag.result-source-kept | static | a reference parameter the from clause does not name, kept rather than probed | only compare, measure or search it; or name it in the clause |
diag.aliasing-conflict | both | a read or write while a conflicting reference is live; a closure argument that captures what another argument writes | end the earlier borrow first; pass the captured value as the closure's parameter |
diag.borrow-exceeds-source | static | &mut taken through a shared reference | take ref<T, exclusive> |
diag.write-through-shared | static | assignment through a shared reference | as above |
diag.destroy-while-aliased | both | drop or scope exit while a reference or guard is live; a reference through a guard kept past the guard | let the reference's holder end first; bind the guard as long as the reference is needed |
diag.move-while-aliased | both | a move while a reference is live | end the reference before moving |
diag.move-out-of-field | static | moving a resource out of a live struct's field or through a reference | move the whole container, or match a reference (match (&e)) |
diag.borrow-of-non-place, diag.borrow-of-temporary | static | & applied to a value or temporary | bind it first |
diag.no-destroy-authority, diag.transfer-without-authority | both | destroying or moving something this thread does not own | destroy in the owning thread, once |
diag.overwrite-of-live-resource | both | assigning over a resource that is still owned and is not quiet (its end runs a destructor or releases something) | overwrite(&mut x, v), or drop first |
diag.unwrap-failed | dynamic | unwrap or expect of a None or an Err | match, or unwrap_or with a default |
diag.assert-failed | dynamic | an assert condition is false (the formatted message, if any, is shown) | the condition names what was assumed; find why it did not hold |
diag.read-of-resource | static | a resource used where a copy would be made (==, a value read) | move it or take a reference |
diag.text-join | static | + with a text operand: + does not join text | String::append(&mut s, t), String::appendf, or sprintf("%s%s", a, b) |
diag.bad-destructor-signature, diag.direct-destructor-call | static | drop declared wrongly or called by hand | fn T::drop(ref<T, exclusive> self); use drop(x) |
diag.destructor-on-plain-type | static | T::drop declared for a type that is not a resource | declare the type resource struct T; an enum has no destructor, so wrap it in a resource struct |
diag.arith-overflow | both | + - * or negation left the type's range | widen, or use wrapping_/saturating_/checked_ |
diag.div-by-zero, diag.div-overflow | both | division by zero; MIN / -1 | test first or checked_div |
diag.shift-amount-out-of-range | both | shift by the bit width or more | mask the amount |
diag.narrowing-overflow | both | narrow or to_int of a value that does not fit, or a value too wide for a bitstruct field | checked_narrow or narrow_wrapping, or a wider target, for an integer; for a float (to_int), test its range first |
diag.result-discarded | both | an expression statement whose value is a Result, so its error would vanish; a handle<Result<…>> that may end unjoined; at run time, one in a container that ended unjoined after Err | handle it (?, match, unwrap), or write _ = e; to ignore it on purpose |
diag.literal-out-of-range | static | a literal that does not fit its type | fix the literal or its type |
diag.recursive-type | static | a struct or enum contains itself by value | put the recursive part behind Box<T>, Rc<T> or Vec<T> |
diag.index-out-of-bounds | both | array or Vec index, or str_byte position, at or past the length | check the index first |
diag.not-ascii | dynamic | String::push_ascii given a byte of 128 or more | build the bytes in a Vec<u8> and check them with String::from_utf8 |
diag.not-char-boundary | dynamic | a StringView bound inside a character's UTF-8 encoding | move the bound to a character's start, e.g. with StringView::find |
diag.non-exhaustive-match | static | a variant with no arm and no _ | add arms |
diag.unreachable-arm | static | an arm whose every value an earlier arm already takes (arms are tried in order) | remove it, or move it before the arm that shadows it |
diag.propagate-outside-fallible-context | static | ? in a function whose return type is not Result<_, E> with the same E | change the return type or map_err |
diag.format-invalid | static | a printf-family format that is not a string literal, or a malformed % specifier | fix the specifier; write %% for a literal % |
diag.spawn-borrow-closure | static | spawn given a closure that borrows | add move |
diag.not-thread-safe | both | spawn given an Rc or Weak, or a value that holds or reaches one; at run time, an Rc or Weak used in a thread other than its maker's | share an Arc, or make the Rc inside the thread |
diag.mutex-reentrant-lock | dynamic | locking a mutex this thread already holds | release the guard first |
diag.channel-zero-capacity | dynamic | Channel::new given a capacity of 0 | give the number of values it may hold; 1 for a hand-over |
diag.channel-deadlock | dynamic | the program's only running thread waits on a full or empty channel that is not closed | send or receive from another thread, or close the channel first |
diag.stack-exhausted | dynamic | calls nested deeper than the stack the implementation provides | recurse less deeply: a loop, or an explicit stack in a Vec |
diag.trusted-outside-unsafe | static | a raw or extern operation outside unsafe | wrap it in unsafe after checking the precondition |
diag.extern-non-ffi-type | static | an unsafe extern fn with a non-FFI parameter or result | pass scalars or rawptr |
diag.alloc-failure | dynamic | Vec or Rc could not allocate | call allocate yourself if you need to recover |
diag.slice-of-whole | warning | a warning of --check: &x[0..$] (or &mut x[0..$]) at a position whose declared type is a slice or a StringView, where [Coerce-Slice] or [Coerce-Text] makes the plain borrow, the view, the slice or the reference the same thing | write &x (&mut x); a view, a slice, a str or a reference as it is |
diag.text-copy-literal | warning | a warning of --check: String::copy("…") where a String is declared | write the literal |
diag.text-copy-whole | warning | a warning of --check: String::copy(&s) of a whole String | write String::clone(&s), which says a whole String is copied |
diag.handle-discarded | warning | a warning: _ = spawn(…); or a spawn(…); statement, whose handle ends at once and so waits for the thread on that line | keep the handle (or push it onto a Vec of handles) and join it later |
diag.extern-variadic-without-ellipsis | static | a C library function that takes a variable argument list (snprintf, open, ioctl, …) declared without ... ([Extern-Variadic-Without-Ellipsis]) | declare its fixed parameters and then ..., as C does |
diag.static-assigned | static | a static assigned (S = …) or destroyed (drop(S)); it lives as long as the program ([Static-Not-Assigned]) | change it through what it holds: Atomic::store(&S, x) |
diag.type-annotation-needed | static | cobc cannot take a generic call's or variant's type arguments from what is written (u8 x = Result::unwrap_or(Ok(5), 7);: nothing fixes the error type, [Lower-Uninferable]) | write the type where the value is declared, or on the call or variant (Ok<u8, str>(…)) |
diag.thread-affine-moved | static | a guard passed to spawn or captured by a spawned closure ([Thread-Confined], D-0340) | pass &m and call lock(m) in the thread |
diag.never-returns | static | a function declared : never that can return ([T-Never-Fn], D-0340) | end every path with exit(…) or another : never call |
diag.no-effect | warning | a warning: a statement whose value is its only effect, such as count == count + 1; or x; | assign with =, or discard a value on purpose with _ = …; |
diag.reference-identity | warning | a warning: x == v of two references to a T: eq compares where they refer, not the values | *x == *v for the values |
diag.comparison-constant | warning | a warning: an unsigned value compared with 0 so that the result is always the same (i >= 0) | count down with while (i > 0) { i -= 1; … } |
diag.match-arm-break | warning | a warning: break; ending, after its work, the block of a match arm for a literal value inside a loop, which leaves the loop (C's switch habit) | delete it (an arm never runs on into the next); to leave the loop, write break without ; as the block's value |
diag.deprecated-use | static | this item is deprecated | write what the message says instead; meanwhile --allow-deprecated accepts the program and reports each use as a warning |
diag.removed-use | static | this item was removed | write what the message says instead; no flag accepts a removed name |
diag.unittest-name | static | this test's name cannot be used | name each test of a module differently, say what it checks, or leave the name out |
diag.precondition-failed | both | a requirement of the called function does not hold | establish the condition before the call, or test it and take another path |
diag.requires-misplaced | static | this function cannot have a requires block | check the condition in the body with assert, or in the caller |
diag.invalid-datetime | dynamic | this date and time do not exist | make it with DateTime::new, which returns None for such fields, or with DateTime::from_unix/from_iso |
diag.entropy-unavailable | dynamic | the operating system gave no secure random bytes | run where the system provides secure randomness; never substitute a clock or a fixed seed for keys |
diag.hkdf-length | dynamic | HKDF cannot produce more than 8160 bytes | derive at most 8160 bytes from one pseudorandom key; derive more keys with different info |
diag.crypto-length | dynamic | a key, nonce or digest of the wrong length | pass keys and nonces of the algorithm's sizes (a key from hkdf_expand with len 32, a nonce of 12 bytes, a digest from hash of the HashKind named) |
diag.kdf-parameters | dynamic | the key-derivation parameters are out of range | pass the parameters the standard allows; hash_password chooses them itself |
diag.null-pointer | dynamic | C's NULL where an address was required | test with is_null first; C functions return NULL for "none" |
diag.barrier-zero-parties | dynamic | a barrier needs at least one party | give the number of threads that meet at the barrier |
diag.thread-cancelled | dynamic | this thread was cancelled | none is needed when the stop was meant: the thread's failure is contained, and its joiner or handle sees it; to let a thread finish, do not cancel it |
diag.mutex-poisoned | dynamic | a thread failed while holding this lock | find that fault (try_join gives it); keep a lock's block short, so that little can fail inside it |
diag.deadlock | dynamic | these threads would wait for each other forever | take locks in one order; send before waiting to receive; store and notify before waiting on an atomic another thread waits to see change; join a thread only after giving it what it waits for |
BAppendix: the runtime interface
How compiled CobaltC uses cbrt, the runtime: what it holds, every call the generated C makes, and why.
A compiled CobaltC program is two things linked together: the C that cobc wrote for the
program, compiled by the system's C compiler, and cbrt, the CobaltC runtime, a static library
(libcbrt.a). This appendix describes the line between them: what the runtime holds, what the
generated C asks of it and when, and what the generated C does on its own. It is a reference for
reading generated C (cobc --keep-c), for reading a profile that names a cb_ function, and for
working on the compiler or the runtime. Nothing in it is needed to write CobaltC programs, and
nothing in it is a rule of the language: the interface belongs to this implementation and changes
with it. The section on where the time goes gives the same picture from
the side of a program's speed.
Why there is a runtime
CobaltC's safety rules are checked in two places. The static pass proves what it can before the program runs. What depends on values, such as whether two indexes name the same element, whether a reference kept in a data structure is still alive when it is used, or whether a binding still owns its resource on this path, the specification leaves to the run, and says exactly which checks those are (the diagnostics marked dynamic or both in appendix A). Those checks are made over state that only exists while the program runs: which objects are alive, which references reach them and in which mode, which frame owns what. Something has to hold that state and make the checks, and that is the runtime. A conforming compiler is native code for the program plus a runtime holding the dynamic part of the specification's state.
The runtime also does what any language's runtime does: it starts the program, ends it, runs destructors when a fault unwinds the stack, starts threads, and carries the standard library's calls to the operating system (files, sockets, processes, clocks, random bytes).
The runtime is written in C, not in CobaltC (D-0326). Every other tool is CobaltC. Three things a runtime needs are not in the language:
- Code that calls no runtime. Compiled CobaltC asks the runtime to record its objects and check its accesses. A runtime written in CobaltC would ask itself: the function that checks a read would need its own reads checked. That takes a way of compiling with no runtime calls at all, which does not exist (D-0256 set a freestanding mode aside for the same reason).
- Mutable statics. The runtime's state is global: its tables, its allocator's lists, its lock. CobaltC has static atomics, and no general mutable
static. - Thread-local storage. Each thread has a stack of frames and scopes of its own, and the language has no way to declare one.
C costs nothing extra here: C is what CobaltC compiles to, so a C compiler is already needed, and the runtime is not a second toolchain.
The shape of a compiled program
cobc prog.cb checks the program, writes one C file in a directory of its own, and runs the C
compiler on it. --keep-c keeps that file beside the executable (prog.c), writing over a file there
only when cobc wrote it, and no output ever replaces one of the program's own files (its source, its
modules, a C file it names with extern); --emit-c writes it and compiles nothing,
--no-line-directives leaves out the #line lines so that the C reads straight through, and -v
prints the C compiler's command and which form the program was lowered in. The file has these parts,
in this order:
- The form's macros, when the program is lowered in a form that needs them:
CB_PATHLESS,CB_DECIDED,CB_QUIET_CELLS(see the forms). - The whole text of
cbrt.h, copied in, so the file includes nothing but the C library's headers. Everything the generated C may say to the runtime is declared there, and nothing else is exported by the library. - The program's types as C structs, each with a
_Static_asserton its size and alignment against the layout the specification gives. - String literals as byte arrays (
cb_s_…). - Prototypes, then the call thunks for
fnvalues and the thread bodies for eachspawn. - The type descriptors:
cb_types[], onecb_typefor each type the runtime may have to end or copy without seeing its source, andcb_type_ids[], each one's 32-bit identifier. A call that names a type (cb_new(addr, ty, …)) passes that identifier. - One C function for each function the program reaches, generic ones once for each set of types (
f_name, and for a function with reference parameters sometimes two bodies and a dispatcher:f_name__dir,f_name__chk). - The start-up text: two thread-locals the runtime reads through functions the program defines (
cb_at_pos, the statement now executing, andcb_stack_floor), thencb_programand C'smain.
static void cb_program(void)
{
cb_init(cb_files, 1, cb_types, 4, cb_type_ids);
cb_frame_push();
void (*volatile cb_main_fn)(void) = f_main;
cb_main_fn();
cb_frame_pop();
cb_terminate_ok(0);
}
int main(int argc, char **argv)
{
cb_set_args(argc, argv);
cb_run_main(cb_program);
}
cb_run_main moves the program onto a large stack of its own, whose limit every function's
cb_stack_check tests, and calls cb_program. cb_init hands the runtime the file names, for
reports, and the type descriptors. main runs inside an outermost frame, and cb_terminate_ok
writes out what is still buffered and ends the process with main's value.
The link line is cc … prog.c -L DIR -lcbrt -lpthread -ldl -lm -Wl,--gc-sections, where DIR
is where cobc itself is. The library is one relocatable object whose only global names are the
interface's (impl/cbrt/tools/exports.txt), so the runtime's own names never meet a program's C at
link time; it is compiled with a section for each function, so a program links only the parts it
reaches. cobc refuses a libcbrt.a built from other sources than the ones it was built with: the
library carries a stamp, a hash of its sources, and the compiler knows its own.
What the runtime holds
The runtime's state is the dynamic part of the state the specification describes, kept over
real addresses. The generated C owns the storage: a local is a C local, a Vec's buffer is a block
the program allocated. The runtime never holds a value, only records about values.
| Record | What it says | Made by | Ended by |
|---|---|---|---|
| Object | A value at an address: its type, whether it is initialised, whether it is a resource, and what holds it: a frame (a binding), a statement scope (a temporary), nothing (in flight across a call, or lying over raw storage). Named by a 64-bit id. | cb_new, cb_new_uninit, cb_reclaim | its frame's or scope's end, cb_destroy, cb_consume, cb_absorb, cb_release |
| Access path | One way of reaching an object: the object, the steps from it (a field, an index, an enum's payload, a range), shared or exclusive, whether it is still valid, the paths it was formed from, and how many places hold it. A reference's identity. Named by a 64-bit token. | cb_bind (an object's root path), cb_borrow and its relatives, cb_lock | the end of what holds it; a conflicting access makes it invalid |
| Frame | An entry on the thread's stack: the objects it owns, in the order they were bound, and the paths it holds. | cb_frame_push and its relatives | cb_frame_pop: its objects end last bound first, destructors run |
| Statement scope | An entry on the same stack for one statement: its temporaries and the paths formed in it that nothing has taken. | cb_stmt_push | cb_stmt_pop |
| Reference slot | For a memory cell that holds a reference: the token of the reference stored there. In memory a reference is its 8-byte address alone; the token is kept here, keyed by the cell's address. | cb_store_ref, cb_hold_ref, cb_copy_datum | the end of the object the cell lies in; cb_deallocate |
| In flight | A queue for each thread of what is between a caller and a callee: objects, references, values holding references, in argument order. | cb_send and its relatives | cb_recv and its relatives |
| Objects over raw cells | Objects that lie in storage the program allocated (a Vec's elements, a Box's contents), found by address, with a count for each page so that the usual answer, none here, costs a load. | cb_reclaim, cb_elem_borrow | cb_release, cb_deallocate |
| Threads and locks | Each thread's state and result, each mutex's holder, what a thread was lent, and under --explore whose turn it is. | cb_spawn, cb_lock | cb_join, the guard's end |
| Noted locals | For a function whose locals have no object: a table of their addresses and types, read only if a fault unwinds through the function, to run their destructors in order. | cb_notes_push | cb_notes_pop |
Each running thread has a heap of records of its own, so two threads that share nothing do not wait for each other; an id carries its heap's number. A program's first thread, while no other has been started, takes none of the runtime's locks. Once threads run, every access to memory two threads can reach is checked under the runtime's lock before it is made.
References and tokens
A reference in a register, as a parameter, a result or a temporary, is a cb_ref: the address
and the token of its path. Stored into memory it is the address alone, and cb_store_ref and
cb_load_ref keep and find its token by the cell's address. That keeps a reference 8 bytes wide in
every struct and array, as the specification's layout says, while every access still knows which
path it is made through. A token is one of four things:
| Token | Meaning | What a check through it costs |
|---|---|---|
0 | No record. Every token of a program lowered without paths; also a reference the compiler proved needs none. | nothing: the entries are macros that expand to nothing |
CB_LIGHT | CB_ROOT | obj | The owner's own binding of object obj. | one byte read (cb_marks): no call while no recorded path is on the object |
CB_LIGHT | obj | A light reference: formed in a function the static pass decided, recorded nowhere. | a test of the token's bits, no call |
| anything else | The id of a recorded path. | a call into the runtime |
The test is cb_vouched, inline in the header: cb_read, cb_write, cb_borrow and their
relatives are macros over inline functions (cb_read_i, …) that call the runtime only for a token
that is not vouched for. A light reference becomes a recorded one where the record is needed: when
it is stored into data (cb_hold_ref) or arrives in a function that left a conflict to the run
(cb_rec_ref).
What the generated C does itself
Most of what a program does never reaches the runtime:
- Loads and stores.
cb_readandcb_writecheck that an access may be made; the C statement after them reads or writes the value. The runtime never touches the program's values on an access. - Arithmetic. A checked
+is__builtin_add_overflowand a branch; division tests for zero and forMIN / -1; a shift tests its amount. Only the failing branch calls the runtime (cb_fault). - Bounds. An index is compared with the length in line (
cb_index_check, or the comparison written out), so the C compiler can drop the test where a loop's condition already proves it. - Layout. Field offsets, enum tags, array elements and conversions are plain C.
- The stack limit.
cb_stack_checkcompares the frame's address with a thread-local. - Where the program is.
cb_at(file, line)is a store to a thread-local, read by the runtime only when a fault needs a location that was not passed to it. - Small allocations. A block of up to 1,024 bytes is popped from, and pushed onto, a list for its size class in line (
cb_bins), while the program has one thread. - Formatting and text helpers. A literal format's common specifiers, byte comparison, hashing, searching, bit counts and rotations are inline functions of the header.
One function, three forms
The clearest way to see the interface is to read what cobc writes for a small program. This
one makes a struct, passes an exclusive reference to it, and reads a field through a shared
reference:
import std;
struct Point
{
i32 x;
i32 y;
}
fn bump(ref<Point, exclusive> p)
{
p.x = p.x + 1;
}
fn main()
{
Point pt = Point { .x = 1, .y = 2 };
bump(&mut pt);
ref<Point, shared> r = &pt;
printf("%v\n", r.x);
}2
cobc --bootstrap-form writes the general form, with every record made and every check
asked for. It is what the rules say, statement by statement, and the other forms are this one with
parts proved away. Here is bump, and the first three statements of main:
void f_bump(cb_ref p_p)
{
cb_stack_check();
cb_frame_push_rec();
p_p.tok = cb_rec_ref(p_p.tok, p_p.p, 3936939825u, CB_EXCLUSIVE, 1u, CB_NOLOC, 0);
void *l_p_p = p_p.p;
uint64_t o1 = cb_new(&l_p_p, 1886034091u, CB_NOLOC, 0);
cb_hold_ref(&l_p_p, p_p.tok, p_p.p, 3936939825u, CB_EXCLUSIVE, CB_NOLOC, 0);
uint64_t root2 = cb_bind(o1);
cb_at(0u, 11u);
uint64_t tk3 = cb_load_ref(&l_p_p);
uint64_t tk4 = cb_load_ref(&l_p_p);
cb_read(tk4, (cb_proj[]){ { CB_FIELD, 0u } }, 1, 0u, 11u);
int32_t t5 = (*(struct s_Point *)l_p_p).x;
int32_t t6 = ((int32_t)1ULL);
int32_t t7 = ({ int32_t _r; if (__builtin_add_overflow(t5, t6, &_r)) cb_fault("diag.arith-overflow", 0u, 11u); _r; });
cb_write(tk3, (cb_proj[]){ { CB_FIELD, 0u } }, 1, 0u, 0u, 11u);
(*(struct s_Point *)l_p_p).x = t7;
cb_frame_pop();
return;
}
void f_main(void)
{
cb_stack_check();
cb_frame_push_rec();
cb_at(0u, 16u);
cb_stmt_push_at(0u, 16u);
int32_t t2 = ((int32_t)1ULL);
int32_t t3 = ((int32_t)2ULL);
struct s_Point st4;
st4.x = t2;
st4.y = t3;
struct s_Point l_pt_1;
l_pt_1 = st4;
uint64_t o5 = cb_new(&l_pt_1, 3936939825u, 0u, 16u);
uint64_t root6 = cb_bind(o5);
cb_stmt_pop();
cb_at(0u, 17u);
cb_stmt_push_at(0u, 17u);
uint64_t tok7 = cb_borrow(root6, NULL, 0, CB_EXCLUSIVE, 0u, 17u);
cb_ref r8 = ((cb_ref){ (void *)&(l_pt_1), tok7 });
f_bump(r8);
cb_stmt_pop();
cb_at(0u, 18u);
cb_stmt_push_at(0u, 18u);
uint64_t tok10 = cb_borrow(root6, NULL, 0, CB_SHARED, 0u, 18u);
cb_ref r11 = ((cb_ref){ (void *)&(l_pt_1), tok10 });
void * l_r_9;
l_r_9 = (r11).p;
cb_hold_ref(&l_r_9, (r11).tok, (r11).p, 3936939825u, CB_SHARED, CB_NOLOC, 0);
uint64_t o12 = cb_new(&l_r_9, 3175594122u, 0u, 18u);
uint64_t root13 = cb_bind(o12);
cb_stmt_pop();
…
cb_frame_pop();
return;
}
Read with the table of records beside it:
- Line 16,
Point pt = …. The C builds the struct in a C local.cb_newtells the runtime an object of typePointnow lies at&l_pt_1, as a temporary of this statement;cb_bindmakes the frame adopt it and returns its root path's token,root6, through which every later access toptis made.cb_stmt_popends the statement's scope, which by then holds nothing. - Line 17,
bump(&mut pt).cb_borrowchecks that an exclusive reference may be formed fromptnow (no other live path conflicts) and mints a path; the token and the address make thecb_refpassed tof_bump. The path is held by the statement, andcb_stmt_popends it when the call has returned. - Inside
bump.cb_frame_push_recopens a frame that records the references arriving in it, andcb_rec_refrecords the parameter. The parameter is itself a local that holds a reference: an object (cb_new,cb_bind) whose one cell holds the token (cb_hold_ref).p.x + 1loads the token back (cb_load_ref), askscb_readwhether field 0 may be read through it, and then reads it with a C expression. The sum is checked in line.cb_writeasks whether field 0 may be written, and a C assignment writes it.cb_frame_popends the parameter's object and what the frame held. - Line 18,
ref<Point, shared> r = &pt. A shared borrow, stored into the localr: the cell gets the address, the runtime gets the token for that cell, andris an object the frame owns.
Without the option, cobc first asks whether the static pass decided the program: whether
every conflict between references that could arise was proved or refuted before the run. This
program is decided, and cobc -v says "lowered pathless and decided". All of the above is then
proved unnecessary, and the same two functions are:
CB_SMALL void f_bump__dir(cb_ref p_p)
{
enum { cb_lf = 1 };
void *l_p_p = p_p.p;
int32_t t1 = (*(struct s_Point *)l_p_p).x;
int32_t t2 = ((int32_t)1ULL);
int32_t t3 = ({ int32_t _r; if (__builtin_add_overflow(t1, t2, &_r)) cb_fault("diag.arith-overflow", 0u, 11u); _r; });
(*(struct s_Point *)l_p_p).x = t3;
return;
}
void f_main(void)
{
enum { cb_lf = 1 };
int32_t t2 = ((int32_t)1ULL);
int32_t t3 = ((int32_t)2ULL);
struct s_Point st4;
st4.x = t2;
st4.y = t3;
struct s_Point l_pt_1;
l_pt_1 = st4;
cb_at(0u, 17u);
void *ad5 = (void *)&(l_pt_1);
f_bump__dir(((cb_ref){ ad5, 0 }));
cb_at(0u, 18u);
cb_ref r7 = ((cb_ref){ (void *)&(l_pt_1), 0 });
void * l_r_6;
cb_ref r8 = r7;
l_r_6 = (r8).p;
uint64_t tk9 = (r8).tok;
cb_frame_hold(tk9);
cb_at(0u, 19u);
cb_str t10 = ((cb_str){ cb_s_f788bc38, 3u });
uint64_t tk11 = tk9;
cb_read(tk11, (cb_proj[]){ { CB_FIELD, 0u } }, 1, 0u, 19u);
int32_t t12 = (*(struct s_Point *)l_r_6).x;
…
return;
}
No frame, no scope, no object, no path. Every token is 0, and the three entries still
written, cb_frame_hold, cb_read and (in other programs) cb_write, are macros that expand to
nothing when CB_PATHLESS is defined, so the C compiler sees a function that reads a field, adds
with an overflow test and writes the field. What is left of the runtime in this program is the
start-up text, cb_at's store before a call that may fault, the overflow test's cb_fault, and
cb_write_out under printf. The executable is 54 KB; in the bootstrap form it is 225 KB, because
it links the object and path machinery it calls.
A program the static pass does not decide keeps its paths, but only where they are needed. This one stores a reference to a local through a parameter, so the local's end leaves a dead reference behind, which only the run can find:
import std;
struct Holder
{
ref<i32, shared> r;
}
fn stash(ref<Holder, exclusive> h)
{
i32 local = 5;
h.r = &local;
}
fn main()
{
i32 outer = 0;
auto held = Holder { .r = &outer };
stash(&mut held);
printf("%v\n", *held.r); // ✗ diag.stale-binding (dynamic)
}cobc -v says why the record is kept: "kept paths: stash, stash.cb:11: a reference is
stored where this frame does not hold it (D-0290); lowered with holders (D-0292)". The function
that left the conflict, and the statement of main that reads the reference back:
static void f_stash(cb_ref p_h)
{
cb_frame_push_rec();
void *l_p_h = p_h.p;
p_h.tok = cb_rec_ref(p_h.tok, p_h.p, 458631599u, CB_EXCLUSIVE, 1u, CB_NOLOC, 0);
cb_at(0u, 10u);
cb_stmt_push_at(0u, 10u);
int32_t l_local_1;
l_local_1 = ((int32_t)5ULL);
uint64_t o2 = cb_new(&l_local_1, 3400004773u, 0u, 10u);
uint64_t root3 = cb_bind(o2);
cb_stmt_pop();
cb_at(0u, 11u);
cb_stmt_push_at(0u, 11u);
uint64_t tk4 = p_h.tok;
uint64_t tok5 = cb_borrow(root3, NULL, 0, CB_SHARED, 0u, 11u);
cb_ref r6 = ((cb_ref){ (void *)&(l_local_1), tok5 });
cb_write(tk4, (cb_proj[]){ { CB_FIELD, 0u } }, 1, 0u, 0u, 11u);
(*(struct s_Holder *)l_p_h).r = (r6).p;
cb_hold_ref(&(*(struct s_Holder *)l_p_h).r, (r6).tok, (r6).p, 3400004773u, CB_SHARED, CB_NOLOC, 0);
cb_stmt_pop();
cb_frame_pop();
return;
}
/* in f_main, line 19 */
cb_read(root10, (cb_proj[]){ { CB_FIELD, 0u } }, 1, 0u, 19u);
cb_ref r14 = ((cb_ref){ l_held_4.r, cb_load_ref(&l_held_4.r) });
cb_read(r14.tok, NULL, 0, 0u, 19u);
int32_t t15 = (*(int32_t *)r14.p);
cb_hold_ref records that the cell held.r now holds the path to local. cb_frame_pop
ends local, and with it every path to it: the path is marked invalid, and the token in the cell
stays. Back in main, cb_load_ref finds that token, and cb_read finds its path invalid and
calls cb_fault. The address in the cell is never followed:
fault[diag.stale-binding]: this value is no longer valid
--> stash.cb:19:5
|
19 | printf("%v\n", *held.r); // ✗ diag.stale-binding (dynamic)
| ^^^^^^
= repair: use the current holder after a move, or give the binding a new value first (`x = e`, `spec/11` `[Assign-Reestablish]`); do not keep a reference past its referent's or its holder's scope; re-index after a `Vec` reallocation
cobc --report-tracking stash.cb lists these calls by source line without compiling, which is
the quick way to see what a program of your own still asks of the runtime.
The forms a program is lowered in
The same program can be written as C in five ways. All of them behave the same: the same output, the same fault at the same place. They differ in how much the runtime is asked, and the project's tests run the suites in several of them and compare.
| Form | Chosen when | cobc -v says | What reaches the runtime |
|---|---|---|---|
| Pathless and decided | the static pass left no conflict to the run (the default for such a program) | lowered pathless and decided | CB_PATHLESS and CB_DECIDED are defined: the path entries are constants, a value holding references is plain data, most locals have no object, and a function has a frame or a table of noted locals only where an unwind would need one. Bounds, arithmetic and the other value checks stay. |
| Pathless | the same program with COBALTC_DECIDED=0 in the compiler's environment | lowered pathless | CB_PATHLESS alone: no paths, but objects, frames, statement scopes and values in flight as in the general form. |
| Kept paths, with holders | some function left a conflict to the run (the default for such a program) | kept paths: the first conflict, with its file and line; lowered with holders | A function the static pass decided opens cb_frame_push_fn and forms light references (enum { cb_lf = 1 }; at its start says so to the header's inline tests). A function that left a conflict opens cb_frame_push_rec and records what arrives (cb_rec_ref). A reference stored into data is recorded where it is stored (cb_hold_ref). |
| Every check | cobc --all-checks | kept paths: every check was asked for | No proof about a function's reference parameters is used: every function records, and every access through a parameter is checked where it is made. |
| Bootstrap form | cobc --bootstrap-form | kept paths: every check was asked for | The general form with no elision: every local an object, every stored reference a slot, a stack check in every function. The reference the code generator is held to; much slower. |
CB_QUIET_CELLS is defined as well, in any form, when no call in the program can put an
object over raw storage or start a second thread: the tests for an object over a Vec's elements
are then constants.
The header is how the forms differ without the generated C differing much. Under
CB_PATHLESS the entries cb_borrow, cb_read, cb_valid, cb_store_ref, cb_load_ref,
cb_frame_hold and their relatives are redefined as macros that evaluate their token argument and
give 0 or nothing; cb_write becomes cb_write_pathless, which keeps the one check a decided
program still needs at a write through a reference (the target is a resource that still owns
something: diag.overwrite-of-live-resource). Under CB_DECIDED the entries for references and
reference data in flight are nothing too, and cb_init first calls cb_set_decided. The C
compiler then deletes the calls and whatever was computed only for them.
A function with reference parameters is sometimes written twice, when whether its checks
are needed depends on its arguments: f__dir, the direct body, with no check on its parameters, and
f__chk, the checked one. A small dispatcher chooses: the direct body when the program has one
thread, or the tokens are 0, or cb_direct_ok vouches for the paths (valid, and over fresh storage). cb_paths_disjoint, cb_paths_arrive and cb_frozen_ok are the same kind of
question for other shapes of parameter.
The interface, name by name
Every name cbrt.h declares is below, grouped by what it is for. "The runtime" in the third
column means code in libcbrt.a; a name marked inline is defined in the header and compiled
into the program, and calls the library only where its row says so. The words in square brackets
are the specification's rules, as the header's own comments cite them. Arguments named file and
line are the source location a fault there is reported at (CB_NOLOC for none); ty is a type's
identifier; obj an object's id; tok, root and base are tokens.
Types, constants and shared variables
| Name | What it is |
|---|---|
cb_str | A str: a pointer and a length, 16 bytes. |
cb_unit | The empty value (): an empty struct. |
cb_i128, cb_u128 | The 128-bit integers, as the C compiler's __int128. |
cb_ref | A reference outside memory: { void *p; uint64_t tok; }. |
cb_proj | One step of a place from its base: CB_FIELD i, CB_INDEX i or CB_PAYLOAD. &s.f[i] passes an array of two. |
cb_type, cb_field | A type descriptor and one of its fields: name, size, kind (CB_K_SCALAR, CB_K_STRUCT, CB_K_ENUM, CB_K_ARRAY, CB_K_REF, CB_K_FN, CB_K_HANDLE, CB_K_GUARD, CB_K_OTHER), whether it is a resource, whether it holds references, its destructor's address, its fields or variants or element. |
cb_fnbox | What a fn value's 8-byte handle points at: the code, and for a closure the object holding its captures. |
cb_fmt_arg | One argument of a printf-family call that the general formatter (cb_format) handles. |
struct cb_pos, cb_at_pos | The statement now executing, a thread-local the generated program defines. |
struct cb_note | One entry of a function's table of noted locals: address, moved flag, type, whether bound now. |
CB_SHARED, CB_EXCLUSIVE | A borrow's mode. |
CB_LIGHT, CB_ROOT, cb_lf | A token's kind bits; cb_lf is 0 in the header and shadowed by 1 at the start of a decided body, where a borrow from a vouched token is light. |
cb_marks, cb_inline_off | For each heap one byte for each object, nonzero while a recorded path is on it; and a flag that sends every entry to the runtime (set under COBALTC_RECORD). |
cb_live_threads, cb_threaded, cb_sched_flag | How many threads run (1: this one is alone); whether a thread was ever started; whether a schedule runs the threads (--explore). |
cb_reclaimed_entries, cb_reclaimed_pages | The count of objects over raw cells, in all and by page: the gates of the element fast paths. |
cb_slots_used | 1 once any reference was stored into data: until then no cell holds one, and a copy or a deallocation has no slot to look for. |
cb_bins, cb_alloc_gate, cb_alloc_traced | The free lists of small blocks by size class; the flag that closes the inline allocation paths (a thread was started, an over-aligned block was made, a sanitizer is on, a trace records allocations); whether the replay trace records each allocation. |
cb_stack_floor | This thread's stack limit, a thread-local the generated program defines. |
CB_SMALL, CB_NOTYPE, CB_NOLOC, CB_OWN_STACK, CB_SANITIZED | A small function's linkage; no type; no location; whether the program runs on a stack of its own (not under a sanitizer); whether the C is compiled under a sanitizer, in which case every block is malloc's so that the sanitizer sees it. |
Starting, ending, faulting
| Name | When the generated C uses it | What it does |
|---|---|---|
cb_set_args | first thing in C's main | keeps argc and argv for arg, arg_count and Args |
cb_run_main (inline), cb_run_program | C's main | runs cb_program on a large stack of its own, or on a thread under a sanitizer; does not return |
cb_init, cb_set_decided | start of cb_program | [Program]: takes the file names and type descriptors and sets up the state; cb_set_decided first, in a decided program |
cb_terminate_ok | end of cb_program | writes out buffered output and ends the process with main's value |
cb_exit | std::exit | unwinds this thread as a fault does, reports nothing, ends with the status |
cb_unittest_runner | cobc --unittest's runner, before its first test | an exit reached during a test then reports the test FAILED and ends the run with status 1 (report 374) |
cb_fault, cb_fault_msg, cb_fault_index, cb_fault_range, cb_fault_arith, cb_fault_arith_r, cb_fault_arith_c, cb_fault_op, cb_fault_narrow, cb_fault_to_int | a check written in line has failed (overflow, bounds, unwrap, assert) | [Fault-Unwind]: see a fault from call to exit; cb_fault_msg carries assert's formatted message; the others the values the check compared: the index and the length, the range and the length, the operands and the type (of + - *, of -a, of a division and of a shift), the value and the type it does not fit |
cb_at (inline) | before a statement that may fault without a location of its own | stores the file and line in cb_at_pos |
cb_where, cb_set_where, cb_set_stack_floor | defined by the generated program, called by the runtime | read and set the two thread-locals, which live in the program so that its stores to them are plain |
cb_stack_check (inline), cb_stack_exhausted | a function's entry | [Call]'s stack limit: below the floor is diag.stack-exhausted, raised as a fault |
cb_index_check (inline) | an index into an array, slice or Vec | the comparison, and cb_fault("diag.index-out-of-bounds") |
Frames and statement scopes
| Name | When the generated C uses it | What it does |
|---|---|---|
cb_frame_push, cb_frame_push_at | a block or a function body begins | [Block-Enter], [Call]: pushes a frame; _at keeps the block's location for a fault in a destructor at its end |
cb_frame_push_fn | a decided function's body, in a program that keeps paths | a frame whose references are light |
cb_frame_push_rec | a body the static pass left a conflict in | a frame that records every reference formed or arriving in it |
cb_frame_pop | the block or body ends, on every way out | [Block-Exit]: ends the frame's objects last bound first ([Destroy] for a resource: its destructor, then its parts; [Object-End] for the rest) and drops the paths it held |
cb_stmt_push, cb_stmt_push_at | a statement that makes temporaries or paths begins | [Stmt-Enter]: a scope for them |
cb_stmt_pop | the statement ends | [Stmt-Exit]: ends the scope's temporaries and the paths nothing took |
cb_frame_here | a binding that may be given a new value after a move | the current frame's id, kept for cb_rebind |
cb_frame_hold, cb_frame_unhold | a reference local that has no object of its own is bound, or ends early at its last use | the frame holds the path until [Block-Exit], or stops holding it ([Ref-Binding-Last-Use]) |
Objects
| Name | When the generated C uses it | What it does |
|---|---|---|
cb_new | a value now lies in a C local or temporary | [Object-Establish]: an initialised object at that address, a temporary of this statement; returns its id |
cb_new_uninit | T x; with no value | [Let-Uninit]: the same, not yet initialised |
cb_bind | a temporary becomes a binding | [Binding-Form]: the current frame adopts it; returns the root path's token |
cb_rebind | x = e after x was moved from | a new object at the address, bound in the binding's own frame |
cb_move_to | the C copied a value's bytes to another local | the record follows: the same object, now at the new address |
cb_temp_path | a temporary closure is called | [Temp-Root]: an owner's path to a temporary |
cb_take | a binding is moved from | [Authority-Transfer]: checks that nothing else reaches it and that the binding still owns it; the root path ends and the object is in flight |
cb_absorb, cb_absorb_refs | a value is moved into a struct, an enum or a container | [Relocate-In]: its record ends without destruction, since it is now part of the container; _refs for plain data holding references, whose slots stay |
cb_result | a block's or statement's value leaves it | [Stmt-Exit]'s re-stamp: the object now belongs to the enclosing scope |
cb_destroy, cb_destroy_via | drop(x), drop(*r) | [Destroy]: valid, nothing else reaching it, authority held; then the destructor, the parts, the object's end |
cb_consume | a temporary is destroyed now, not at the statement's end | [Destroy] of the temporary |
cb_end_moved_out | a value was taken apart by a pattern | [Relocate-Out]: the container ends without destroying the parts that moved out |
cb_end_binding | a reference binding's last use | [Ref-Binding-Last-Use]: its object and path end there |
cb_forget_obj | a callee keeps a received value in a local with no object | the record ends, the value stays with the C |
cb_drop_local, cb_drop_value | a local with no object ends; a plain temporary holding fn values ends | destroys the value there as its binding's end would, from its type descriptor |
cb_owns | an assignment over a place whose type may own something | whether the value at the address owns a resource now, for [Write]'s test |
Access paths and checked accesses
| Name | When the generated C uses it | What it does |
|---|---|---|
cb_borrow | &x, &mut x, &s.f, &a[i] | [Borrow]: the source is valid, the mode is no stronger than the source's, no live path conflicts, the thread may reach it; mints a path held by this statement and returns its token |
cb_borrow_range | &a[lo..hi] | [Slice-Form]: a borrow whose last step is a range |
cb_borrow_unstamped, cb_call_self, cb_call_self_fn, cb_call_done | a call through a closure | a borrow in no statement scope: the closure's self for the call (shared for a closure whose copies share its box), ended by cb_call_done when nothing took it |
cb_borrow_unminted, cb_borrow_range_unminted, cb_borrow_check | a reference passed straight to a parameter the callee only uses directly, or &v straight into Vec::index | [Borrow]'s checks without minting a path |
cb_read | before a load from a place that a path reaches | [Read]'s premises: valid, no conflicting exclusive path, the thread may reach it. The C does the load. |
cb_write | before a store to such a place | [Write]'s premises: valid, exclusive, no conflicting path, and no live resource overwritten when the target is one. The C does the store. |
cb_write_quiet | a store over a value whose end only frees memory | [Write-Quiet-Replace]: destroys the old value, then allows the write |
cb_point_check | a call whose callee is known to access something the caller also lent | the access the callee's summary declares, checked at the call, with the call's argument paths counted as held |
cb_valid | swap of two places | [Swap-Places]: valid, with no conflict check |
cb_vouched, cb_read_i, cb_write_i, cb_borrow_i, cb_borrow_unstamped_i, cb_borrow_check_i, cb_borrow_unminted_i, cb_borrow_range_unminted_i (all inline) | every use of the entries above, which are macros over these | the token's kind tested in line; the runtime is called only for a recorded path, a marked owner, or under COBALTC_RECORD |
cb_write_pathless (inline) | cb_write in a pathless program | the live-resource test alone |
cb_direct_ok, cb_paths_disjoint, cb_paths_arrive, cb_frozen_ok, cb_peek_datum_tok | a dispatcher choosing between a function's direct and checked bodies | whether the arguments' paths are valid, pairwise disjoint and free of conflict as they arrive, so that the direct body may run; cb_peek_datum_tok reads the token of a value in flight without taking it |
References kept in memory
| Name | When the generated C uses it | What it does |
|---|---|---|
cb_store_ref | a reference is stored into a cell | [Write] of a reference value: the cell's slot gets the token, and the path gains a holder |
cb_hold_ref | the same, where the compiler knows the referent's place | a light reference becomes a recorded path as it is stored; a recorded one is stored as cb_store_ref stores it |
cb_rec_ref | a reference arrives in a recording function, as a parameter or a call's result | a light token becomes a recorded path, held by the frame or the statement; a recorded one is returned as it is |
cb_load_ref | a reference is read out of a cell | the token the cell's slot holds |
cb_copy_datum | a value that holds references is copied | copies each slot's hold with the bytes |
cb_lend, cb_lend_fn | spawn with reference arguments, or a closure with reference captures | [Thread-Lend]: every exclusive path in the argument block is lent to the thread that receives it |
Across a call
A C call passes the bytes. The records of what is passed travel beside them, in the thread's queue of what is in flight, in argument order: the caller sends, the callee receives, and the same for a result on the way back.
| Name | When the generated C uses it | What it does |
|---|---|---|
cb_send, cb_recv | a resource or other object passed or returned by value | [Call]: the object is in flight; the receiver gets it, now at its own address, and binds it |
cb_send_ref, cb_recv_ref | a reference argument | the path is pending until the callee binds it, so it is not ended by the caller's statement |
cb_result_ref | a statement's or call's reference result | re-stamps the path into the enclosing scope |
cb_send_datum, cb_recv_datum | a value holding references (a view, an Option of a reference, a struct of them) | its slots' holds move with it |
cb_recv_datum_tok, cb_send_tok_datum, cb_send_datum_none | a native body that returns one reference as data, or None, and its caller | the token of such a value, taken or sent without a slot |
fn values and closures
| Name | When the generated C uses it | What it does |
|---|---|---|
cb_fn_item, cb_fn_item_pure | a function's name used as a value | the one box kept for that function; _pure when its reference parameters are only used directly |
cb_fn_box | a closure expression | a heap box that owns the closure's object of captures |
cb_fn_pure, cb_fn_mark_pure | a native body deciding whether it may pass element references with no path | whether the fn value keeps nothing of its arguments; marks a closure's code as such |
cb_fn_copy, cb_fn_read, cb_fn_split, cb_fn_moved_out | a fn value is read from a place | [Read]: copies the handle, cloning a closure's box (or sharing it, for a closure no copy can tell apart); or moves it out when the closure owns a resource, for one slot or for each fn slot of a value; cb_fn_moved_out empties the fn slots a raw read moved out |
cb_fn_moved | a call through a slot that was emptied | the fault for it |
cb_fn_shared, cb_fn_shared_value | a fn value read through a shared reference | checks that it holds no exclusive capture |
cb_drop_fn | a fn value ends | [Destroy] of a closure's box and the object it owns |
Raw storage, allocation and container elements
Vec, Box, String and the other containers are written in CobaltC, in std, over raw
storage (§20). Their elements are not objects while nobody refers to them: an element becomes an
object when it is reclaimed, usually because a reference to it is formed, and stops being one when
it is released. So the common case, an element read or written at once, is checked with a load of
a counter and nothing more. The specification lets an implementation realise a library function
natively (spec/21 §0), and for some std functions that hot loops call (Vec's element access,
its length and its end, sorts and searches over slices) the compiler writes the body directly as C
in place of compiling the CobaltC one: a native body. It makes only the checks that can
fail there, and takes the general path when an object lies over the cells it would touch.
| Name | When the generated C uses it | What it does |
|---|---|---|
cb_allocate, cb_allocate_at_once (inline) | allocate, a container growing | [Allocate]: a small block from its class's list in line, else the runtime; 0 on failure |
cb_deallocate, cb_deallocate_at_once (inline), cb_deallocate_plain, cb_deallocate_plain_at_once (inline) | deallocate, a container's end | [Deallocate]: releases the objects over the cells and their slots, then frees the block; _plain for cells that never held a reference; in line when there is nothing to release |
cb_reallocate_plain, cb_reallocate_plain_fast (inline) | a Vec of plain elements grows | allocate, copy, deallocate as one step: realloc, or nothing when both sizes are of one class |
cb_free_block, cb_block_free (inline) | the last step of a deallocation | hands the block back, to its class's list in line when small |
cb_drop_plain_buf (inline) | a String or Vec of plain elements with no object ends | frees its buffer at once when no object lies over it, else cb_drop_local |
cb_vec_drop_plain | Vec::drop for plain elements | ends every element object still over the buffer |
cb_copy_raw, cb_copy_raw_at_once (inline) | copy_raw | [Copy-Raw]: memmove, and the slots of any references among the bytes move with them |
cb_reclaim | reclaim | [Reclaim]: an object over the raw cells at an address; its root token |
cb_release, cb_release_plain | release | [Release]: ends the reclaimed objects that start in the range |
cb_raw_move_in, cb_raw_move_out | *p = v and a read of *p where the value is a resource | [Rawptr-Move-In], [Rawptr-Move-Out]: the object's record goes into, or comes out of, raw storage |
cb_elem_borrow, cb_elem_borrow_here, cb_elem_borrow_datum | Vec::index and its relatives return a reference to an element | [Reclaim] and [Borrow] together: an object over the element and a path to it, in flight, recorded in the current scope, or sent as reference data |
cb_elem_access (inline), cb_elem_access_if (inline), cb_elem_access_slow | v[i] read or written at once | nothing while no object lies near the element (cb_reclaimed_any, cb_reclaimed_near); otherwise [Read]'s or [Write]'s premises on the object there |
cb_reclaimed_any, cb_reclaimed_near, cb_cells_busy (all inline), cb_cells_held | the gates of the paths above | whether any object lies over raw cells at all, on these pages, over exactly these cells |
cb_live_at, cb_live_in, cb_live_in2, cb_live_in_q (inline), cb_live_in2_q (inline) | the entry of a native body | whether a live object lies over the cells: if so the body takes its general, checked path |
cb_gate, cb_slots, cb_blocks_from_malloc | inside the inline paths above | read cb_alloc_gate and cb_slots_used (atomically under a sanitizer); cb_blocks_from_malloc is a constructor that closes the gate in a sanitized build |
Locals with no object
In a decided program most locals have no object, so cb_frame_pop has nothing to end, and
the generated C ends each local itself where its scope ends. If a fault unwinds through the
function, those C statements never run, so a function whose locals have destructors, or are freed,
notes them in a table on its C stack.
| Name | When the generated C uses it | What it does |
|---|---|---|
cb_notes_push | such a function is entered, or binds such a local | registers the table for the unwind |
cb_notes_pop, cb_notes_drop | the function returns; one temporary with a destructor ends | the table, or the one entry, leaves |
Threads, mutexes and atomics
| Name | When the generated C uses it | What it does |
|---|---|---|
cb_env_alloc, cb_hold | spawn(f, a, b): the arguments are put in a block | storage for the block, outside every object; a resource argument waits in it until the new thread binds it |
cb_spawn | spawn | [Spawn]: starts a thread on the body the compiler wrote for this spawn; the thread's id, which is the handle's value |
cb_thread_jmp, cb_thread_start, cb_thread_done, cb_env_forget | that body, in the new thread | sets where a contained fault's unwind ends; registers the thread and binds its parameters from the block; [Thread-Body-Done]: the result is in the block; the block's reference cells stop counting as holders |
cb_thread_failed, cb_thread_lent | the body after a contained fault; a thread lent an exclusive reference | records the failure ([Fault-Contain]); marks the thread as one whose fault is never contained |
cb_join, cb_join_plain | join(h) | [Join]: waits, copies the result out, and returns its object (_plain: a result with no object) |
cb_join_status, cb_cancel, cb_task_op | std::try_join, is_finished, cancel, a failure's text | the supervision operations of §19 |
cb_lock, cb_lock_pathless | lock(&m) | [Lock]: waits for the mutex (diag.mutex-reentrant-lock if this thread holds it) and returns the lock path's token, which the guard holds; _pathless in a program with no paths |
cb_lock_bare, cb_unlock_bare, cb_unlock_signal | std's own bodies, which lock with no guard object | lock and unlock; _signal wakes waiters and unlocks in one step |
cb_event_op | Channel's waits and wake-ups | an event's count: read, wait for a change, signal |
cb_atomic_wait, cb_atomic_point, cb_spin_hint | Atomic's wait and notify; any atomic operation under a schedule; a spin loop | [Atomic-Wait], [Atomic-Notify]; a point where --explore may pass the turn; the processor's pause |
Library mode
cobc --lib builds the program's extern fn definitions as a C library (§20). There is no
main: each entry point is a stub that makes sure the runtime is running and that the calling C
thread is known to it.
| Name | When the generated C uses it | What it does |
|---|---|---|
cb_lib_enter, cb_lib_leave | each entry point's stub | starts the runtime once and registers the calling thread; writes out what the call printed |
cb_lib_jmp, cb_lib_fault_code, cb_lib_last_fault | an entry point's _try form | [Fault-Contain]: a fault inside the call unwinds to the stub, which returns its status; the report is kept for cobalt_last_fault |
cb_lib_shutdown | cobalt_shutdown | ends the runtime |
A program with a main may have entry points too, and its own C may call them from threads it
started. Its main makes the runtime ready for such threads before it runs anything, and each entry
point's stub registers a thread the runtime does not know on its first call.
| Name | When the generated C uses it | What it does |
|---|---|---|
cb_entries_on | main, in a program with entry points | each thread allocates from its own heap and locking stays on for the whole run, so a thread can arrive at any moment |
cb_entry_enter | each entry point's stub | a thread the runtime did not start is registered on its first call and released when it ends; any other goes on |
The standard library's way out
std is CobaltC. Where it needs the operating system or a routine better written in C, it
declares an unsafe extern fn (stdout_write, sleep_ns, …), and the compiler calls the runtime's
function for it. None of these touches the records above: they take addresses and lengths and
return a count or an error code.
| Name | When the generated C uses it | What it does |
|---|---|---|
cb_write_out, cb_write_err, cb_flush_out | printf, print, eprintf, flush_stdout | buffered standard output, standard error |
cb_read_in, cb_read_line_in, cb_arg_bytes | read, read_line, arg | standard input; the program's arguments |
cb_print_int, cb_print_f64, cb_print_f32, cb_print_bool | print of a number or a bool | writes its text |
cb_text_int, cb_text_f64, cb_text_f32, cb_text_bool | String::append of a number | its text into a buffer |
cb_parse_int, cb_parse_int_q (inline), cb_parse_float, cb_parse_bool | parse | the value, or which byte stopped it; an integer of up to 64 bits and 19 digits is parsed in line |
cb_format, cb_fmt_space, cb_fmt_u64, cb_fmt_i64, cb_fmt_hex, cb_fmt_pad (the last four inline) | printf, sprintf | a literal format of the common specifiers is written in place by the generated C into cb_fmt_space's buffer; anything else goes to cb_format |
cb_file_read, cb_file_write, cb_file_op, cb_file_at | read_file, write_file, File | whole files; an open file's read, write, close, seek and length |
cb_fs_op, cb_fs_query, cb_path_op | the filesystem and path functions (make_dir, list_dir, path_canonical, …) | the filesystem |
cb_proc_op, cb_net_op | Command, TcpStream, UdpSocket, resolve | processes and sockets |
cb_thread_id (inline), cb_thread_here | Rc and Weak (thread_id) | the running thread's number (1 for the main thread), one load while no thread has been spawned; the box of an Rc records its maker's, and a use from another thread is diag.not-thread-safe |
cb_clock_read, cb_tz_offset, cb_sleep_ns, cb_os_random | monotonic_ns, unix_ms, local time, sleep_ms, os_random_bytes | clocks, the time zone, sleeping, the system's random bytes |
cb_sort_plain, cb_sort_text, cb_bytes_less | Vec::sort of integers, bools or text | a native sort; text in byte order |
Inline helpers with no state
| Name | What it computes |
|---|---|
cb_popcount64, cb_popcount128, cb_clz, cb_clz128, cb_ctz, cb_ctz128 | the bit-counting built-ins, at a given width |
cb_rotl, cb_rotr, cb_rotl128, cb_rotr128, and cb_rotl8 to cb_rotr64 | rotations: at a width passed as an argument, and at each fixed width in the form a C compiler turns into one instruction |
cb_round, cb_roundf | round, half away from zero, computed from trunc so that it is the same on every C library |
cb_str_eq, cb_bytes_eq, cb_bytes_cmp, cb_bytes_lt | equality and byte order of text |
cb_hash_fold | one step of HashMap's hash: two 64-bit words multiplied to 128 bits, and the halves of the product exclusive-ored |
cb_find_bytes, cb_char_boundary | StringView::find; whether a position is on a UTF-8 character's first byte |
The hash tables' hash
HashMap and HashSet are written in CobaltC, in the standard library; the one thing they ask of
the runtime is the hash of a key's bytes. It starts from a seed that the runtime draws once in each run, from
the system's randomness, the first time a program hashes a key: a program with no hash table draws nothing. No
program can read a hash, and a map keeps its entries in the order they were added, so the seed changes nothing
a program computes; it keeps someone who chooses a program's keys from choosing keys that all share a hash.
| Name | When the generated C uses it, and what it does |
|---|---|
cb_hash_bytes | The hash of an integer, bool, str or String key: the seed, the key's length, then its bytes eight at a time (cb_hash_more). Inline; one multiplication for a u64 key. |
cb_hash_more | The hash so far, taken over more bytes: the parts of a struct or enum key go through it one after another, in the function the compiler writes for that key type. |
cb_hash_bytes_drawn | cb_hash_bytes with the seed as it stands, with no test of it: the hash in the bodies the compiler writes itself for HashMap's lookups, insertions and removals with integer, bool and String keys. The ones that place an entry (insert, entry) call cb_hash_start first; a lookup or a removal does not, because until the seed is drawn no map in the program has an entry, and an empty table gives the same answer for any hash. |
cb_hash_start | The seed, where a struct or enum key's hash starts, and what a compiler-written insert or entry calls before it hashes. Inline: it loads cb_hash_seed_cell, and calls cb_hash_seed_make only while that is still zero. |
cb_hash_seed_cell | The seed: zero until the first hash of the run. |
cb_hash_seed_make | Draws the seed and stores it, once for all threads: from COBALTC_HASH_SEED when that is set, else eight bytes from the system (as os_random_bytes gets them), else, on a system with none, from the clock and an address. |
A fault, from call to exit
Every failed check ends in cb_fault(diag, file, line), whether the generated C found it
(an overflow, an index) or the runtime did (a stale path inside cb_read). The generated C never
longjmps and has no cleanup code of its own for this: the runtime holds the stack of frames and
scopes, so it can do what the rules say.
- The location is the one passed, or the one
cb_atlast stored when none was (a fault found while a frame was ending, or in a destructor). - [Fault-Unwind]: every open statement scope and frame of this thread is ended, innermost first, exactly as
cb_stmt_popandcb_frame_popwould end them. Destructors run: the runtime calls back into the program through each type descriptor'sdrop. Noted locals are ended from their tables at the depth they were registered. - The report is written to standard error:
fault[diag.name]: message, the file, line and column, the source line, and the registry's repair advice. WithCOBALTC_EXPLAIN=1in the environment the registry's whole entry follows. - Buffered output is written out and the process ends with status 1.
Three things change the last step. In a thread started with the supervision operations, the
unwind ends at the setjmp in the thread's body (cb_thread_jmp), the thread is recorded as
failed, and try_join gives the failure to whoever joins it. In a library entry point's _try
form it ends at the stub's setjmp and the stub returns the status to its C caller. And a
thread that was lent an exclusive reference is never contained: its fault ends the program.
A state the runtime's own tables should never reach is not a fault of the program: the
runtime prints cbrt: internal: … and exits with status 4, as cobc does for an error of its
own.
What the runtime calls in the program
The calls go the other way in four places only:
- Destructors. A
cb_typewith a userdrop, or generated drop glue, carries its address.cb_frame_pop,cb_stmt_pop,cb_destroy,cb_drop_localand the unwind call it with acb_refto the value. - Thread bodies.
cb_spawnis given the function the compiler wrote for thatspawn, which unpacks the argument block and calls the program's function. cb_program. Given tocb_run_main, or the initialiser given tocb_lib_enter.cb_where,cb_set_where,cb_set_stack_floor. The accessors of the two thread-locals the program defines.
The runtime never reads the program's source, its names or its values except through these and through the type descriptors: what it knows about a type is its size, its fields' offsets and types, where its references are, and how to end it.
What the runtime reads from the environment
A compiled program checks these variables when it starts. They change how the run is observed, never what the program computes.
| Variable | Effect |
|---|---|
COBALTC_EXPLAIN=1 | A fault's report is followed by the diagnostic's whole registry entry, as cobc --explain --run shows it. |
COBALTC_SCHEDULE_SEED=S | The threads run one at a time, in the order seed S gives, as cobc --explore ran them: a run that ended differently can be replayed. |
COBALTC_VERIFY=1 (or =N) | At every statement's end (or every Nth), the runtime re-derives that its object and path tables agree with each other, and stops naming the defect if they do not. A violation is a defect of the tool, never of the program. |
COBALTC_TRACE_EVENTS=1 | One EV line on standard error for each event the compiler's elisions must not disturb: each user destructor run, the fault, an exit, the end. |
COBALTC_RECORD=full or check | Every entry goes to the runtime (cb_inline_off): full keeps the full record of references, for comparison with the light one; check stops where a light reference reaches something that should have recorded it. |
COBALTC_REPLAY_TRACE=FILE | Writes the run's steps in the format of the proved machine in proofs/, for replaying against it. |
COBALTC_RT_STATS=1 | A test hook: counts of what the runtime recorded, and what it still holds when the program ends. |
COBALTC_HASH_SEED=N | Read at the first hash rather than at the start: the hash tables' seed is made from the number N, not drawn from the system, so two runs place their entries alike and execute the same instructions. For measuring. |
Without COBALTC_HASH_SEED, the instructions a program with a hash table executes differ a little
from run to run: its output does not.
Where to read further
| File | What is there |
|---|---|
impl/cbrt/include/cbrt.h | the interface itself; each declaration's comment names the rule it implements |
impl/cbrt/src/rt.h | the runtime's data structures, with the design in its first comment |
impl/cbrt/src/rt_objs.c | objects, frames and statement scopes, destruction |
impl/cbrt/src/rt_refs.c | borrows, checked reads and writes, reference slots, values in flight, fn values, raw storage, noted locals |
impl/cbrt/src/rt_tables.c | the tables: slots by address, an object's paths, projections and their comparison, the marks, objects over raw cells |
impl/cbrt/src/rt_threads.c, rt_lock.c | threads, the schedule, mutexes and the runtime's lock |
impl/cbrt/src/rt_init.c, rt_alloc.c, diagnostics.c | start-up, ending and faults; the allocator; the reports |
impl/cbrt/src/plat_posix.c, plat_win.c | everything that differs between Linux and Windows |
impl/COBC-PLAN.md | the compiler's plan and its history: why the interface has the shape it has, and each step that made it cheaper, with measurements |
spec/04, spec/08, spec/10, spec/14 | the state, aliasing, temporal validity and the scopes the records above implement |
spec/ASSURANCE.md | what is proved, checked and tested about the runtime |