std reference
The std package: std.arena, std.compress, std.crypto, std.csv, std.deque, std.doc and more.
std.arena
class Arena
offer class ArenaChunks of storage and a cursor into them.
Take never moves what it already gave out: a run stays where it is
until Reset or the arena's own drop, so a view of one is safe to keep
for that long. deinit gives every chunk back.
field chunks
var chunks: List<[]mut u8>field chunk_size
var chunk_size: intfield current
var current: intfield used
var used: intmethod deinit
deinitmethod Take
fun Take(count: int) -> []mut u8 uses unsafeA run of count bytes, a multiple of eight apart from the last one.
What comes back is whatever the chunk held: fresh chunks are zero, but
a run handed out again after Reset still has its old bytes.
method Reset
fun Reset()Hands the whole arena out again from the start, keeping its chunks.
Every view taken before is dead: the next Take writes over it.
method Capacity
fun Capacity() -> intHow many bytes the arena holds, used or not.
function ArenaNew
offer fun ArenaNew(chunk_size: int) -> Arena uses unsafeAn arena that asks for storage chunk_size bytes at a time.
A run bigger than a chunk gets a chunk of its own.
std.compress
error Malformed
offer error MalformedWhat a stream that is not one answers with.
function Inflate
offer fun Inflate(bytes: []u8) -> []mut u8!Malformed uses unsafeReads a deflate stream. There is no cap on the output, so a hostile
stream can expand about a thousandfold; use InflateLimited on anything
that came from outside (D227).
function InflateLimited
offer fun InflateLimited(bytes: []u8, most: int) -> []mut u8!Malformed uses unsafeReads a deflate stream, failing with Malformed once the output would
pass most bytes -- the guard against a decompression bomb (D227).
function Deflate
offer fun Deflate(bytes: []u8) -> []mut u8 uses unsafeCompresses with fixed Huffman codes and a window of matches.
One block, fixed codes: a dynamic block saves a few more percent and costs a Huffman tree builder, which is worth having and is not what a program reaching for this needs first (D177).
function Gzip
offer fun Gzip(bytes: []u8) -> []mut u8 uses unsafeWraps deflated bytes in a gzip container, which is what a .gz is.
function Gunzip
offer fun Gunzip(bytes: []u8) -> []mut u8!Malformed uses unsafeReads a gzip container. Unlimited output; see GunzipLimited (D227).
function GunzipLimited
offer fun GunzipLimited(bytes: []u8, most: int) -> []mut u8!Malformed uses unsafeReads a gzip container, failing with Malformed once the output would
pass most bytes (D227).
function Crc32
offer fun Crc32(bytes: []u8) -> u32The CRC-32 a gzip container carries, which is how a reader knows the bytes arrived whole.
std.crypto
function Sha256
offer fun Sha256(bytes: []u8) -> []u8 uses unsafeSHA-256 of bytes, as 32 bytes.
function Sha256Of
offer fun Sha256Of(value: text) -> []u8 uses unsafeThe same, over text.
function Hex
offer fun Hex(digest: []u8) -> text uses unsafeA digest as lowercase hexadecimal, which is how one is written down.
function Hmac
offer fun Hmac(key: []u8, message: []u8) -> []u8 uses unsafeHMAC-SHA-256 of message with key, as 32 bytes.
What signs a cookie, a webhook or a token: a hash of the message and the key together, arranged so that knowing the hash of one message does not let someone sign another.
function SameDigest
offer fun SameDigest(left: []u8, right: []u8) -> boolWhether two digests are the same, in time that does not depend on where they differ.
A comparison that stops at the first difference tells an attacker how much of a signature they got right, which is enough to find the rest one byte at a time.
function RandomBytes
offer fun RandomBytes(count: int) -> []mut u8 uses rand, unsafecount bytes from the system's own source.
Not std.random: that is a sequence, and a token made from a
sequence is a token someone can continue (D170).
function Token
offer fun Token(bytes: int) -> text uses rand, unsafeA token of bytes random bytes, as hexadecimal.
function Uuid
offer fun Uuid() -> text uses rand, unsafeA version 4 UUID: random, in the shape everything expects.
function UuidAt
offer fun UuidAt(millis: s64) -> text uses rand, unsafeA version 7 UUID: the time first, then randomness.
Two of them made a millisecond apart sort in the order they were made, which is what a database index wants and what version 4 does not give.
function ToBase32
offer fun ToBase32(bytes: []u8) -> text uses unsafeBase32 as RFC 4648 writes it: what a one-time password secret and a case-insensitive identifier are written in.
function FromBase32
offer fun FromBase32(value: text) -> []u8 uses unsafeThe bytes a base32 string spells. Anything that is not a digit of the alphabet is skipped, which is what makes a written-down secret with spaces in it work.
std.csv
function Rows
offer fun Rows(input: text, separator: u8) -> List<List<text>> uses unsafeEvery row of input, split on separator.
function Read
offer fun Read(input: text) -> List<List<text>> uses unsafeThe same, with a comma.
function Named
offer fun Named(input: text, separator: u8) -> List<Value> uses unsafeRows as tables, taking the first row as the names.
What a file with a header line is for: Get(row, "price") rather
than row[3] and a comment saying which column that is.
function Write
offer fun Write(rows: &List<List<text>>, separator: u8) -> text uses unsafeRows as CSV.
A field is quoted when it has to be -- a separator, a quote or a line break in it -- and not otherwise, which is what keeps a written file readable.
function Field
offer fun Field(value: text, separator: u8) -> text uses unsafeOne field, quoted if it has to be.
std.deque
class Deque
offer class Deque<T>field items
var items: []mut Tfield first
var first: int = 0Where the first element is.
field count
var count: int = 0method deinit
deinitmethod Len
fun Len() -> intmethod IsEmpty
fun IsEmpty() -> boolmethod Iterate
fun Iterate() -> DequeWalk<T>What for x in deque walks: front to back.
method Slot
fun Slot(index: int) -> intWhere element index is in the storage.
method At
fun At(index: int) -> TThe indexth from the front.
method Set
fun Set(index: int, value: T)method Push
fun Push(value: T) uses unsafeAdds to the back.
method PushFront
fun PushFront(value: T) uses unsafeAdds to the front.
method Pop
fun Pop() -> TTakes from the front. The caller checks Len first: a queue with
nothing in it has nothing to give, and an optional of T would be
a second shape to lay out for every T.
method PopBack
fun PopBack() -> TTakes from the back.
method Front
fun Front() -> Tmethod Back
fun Back() -> Tmethod Clear
fun Clear()method Reserve
fun Reserve(wanted: int) uses unsafeMakes room for wanted elements.
Growing a ring means laying it out straight again: the elements are
copied in order, so first is zero afterwards and the arithmetic
above stays the same.
class DequeWalk
offer class DequeWalk<T>Walks a deque from front to back.
field over
var over: Deque<T>field at
var at: int = -1method Next
fun Next() -> boolmethod Value
fun Value() -> Tfunction DequeNew
offer fun DequeNew<T>() -> Deque<T> uses unsafestd.doc
enum Value
offer enum ValueOne of the six things a document value can be.
method Null
Nullmethod Bool
Bool(value: bool)method Number
Number(value: float)method Text
Text(value: text)method Array
Array(items: List<Value>)method Object
Object(fields: List<Field>)struct Field
offer struct FieldA member of a table: its name and its value.
field name
var name: textfield value
var value: Valuefunction Kind
offer fun Kind(value: Value) -> intWhich of the six a value is, as a number: 0 null, 1 bool, 2
number, 3 text, 4 array, 5 object.
For a program that switches on the shape of a document it did not write, which is most of what reading one is.
function Member
offer fun Member(value: Value, name: text) -> Value? uses unsafeThe member of a table called name, or nothing.
function At
offer fun At(value: Value, at: int) -> Value? uses unsafeElement at of a list, or nothing.
function Get
offer fun Get(value: Value, path: text) -> Value? uses unsafeWhat path names, or nothing.
"server.ports.0": a name walks into a table and a number walks into
a list. What reading configuration actually looks like, written once
here rather than as four lines at every call.
function Len
offer fun Len(value: Value) -> int uses unsafeHow many elements a list has, or how many members a table has.
function NameAt
offer fun NameAt(value: Value, at: int) -> text uses unsafeThe name of member at of a table, or "".
function ValueAt
offer fun ValueAt(value: Value, at: int) -> Value uses unsafeThe value of member at of a table.
function AsNumber
offer fun AsNumber(value: Value, fallback: float) -> floatThe number this is, or fallback.
function AsInt
offer fun AsInt(value: Value, fallback: int) -> intThe whole number this is, or fallback.
function AsText
offer fun AsText(value: Value, fallback: text) -> textThe text this is, or fallback.
function AsBool
offer fun AsBool(value: Value, fallback: bool) -> boolThe truth this is, or fallback.
function IsNull
offer fun IsNull(value: Value) -> boolfunction Object
offer fun Object() -> Value uses unsafeAn empty table, to put members in.
function Array
offer fun Array() -> Value uses unsafeAn empty list, to put values in.
function Put
offer fun Put(object: Value, name: text, value: Value) -> Value uses unsafePuts a member in a table. The table is what it answers with, so calls
chain: Put(Put(Object(), "a", ..), "b", ..).
function Push
offer fun Push(array: Value, value: Value) -> Value uses unsafeAdds a value to a list.
function Number
offer fun Number(value: float) -> Value =>function OfInt
offer fun OfInt(value: int) -> Value =>function OfText
offer fun OfText(value: text) -> Value =>function OfBool
offer fun OfBool(value: bool) -> Value =>function Null
offer fun Null() -> Value =>std.encoding
function ToBase64
offer fun ToBase64(bytes: []u8) -> text uses unsafebytes as base64, padded with =.
function TextToBase64
offer fun TextToBase64(value: text) -> text uses unsafeA string as base64.
function FromBase64
offer fun FromBase64(value: text) -> text? uses unsafeWhat value holds as base64, or nothing when it is not base64.
An optional, because a token that arrived over a wire is exactly the place where "this is not valid" has to be an answer rather than a trap.
function ToHex
offer fun ToHex(bytes: []u8) -> text uses unsafebytes as lowercase hexadecimal.
function FromHex
offer fun FromHex(value: text) -> text? uses unsafeWhat a hexadecimal string holds, or nothing.
function ToUrl
offer fun ToUrl(value: text) -> text uses unsafevalue with everything a URL cannot carry written as %XX.
function FromUrl
offer fun FromUrl(value: text) -> text uses unsafevalue with %XX and + read back.
std.env
function System
offer fun System() -> text uses io, unsafeWhich system this is running on: "linux", "macos" or "windows".
function ArgCount
offer fun ArgCount() -> int uses io, unsafeHow many arguments the program was given.
function ArgAt
offer fun ArgAt(index: int) -> text uses io, unsafeArgument index, counting from zero, or "".
function Lookup
offer fun Lookup(name: text) -> text? uses io, unsafeThe environment variable called name, or nothing.
An optional rather than "" because a variable set to nothing and one that is not there mean different things to a program reading configuration.
function Get
offer fun Get(name: text, fallback: text) -> text uses io, unsafeThe environment variable called name, or fallback.
function Set
offer fun Set(name: text, value: text) -> bool uses io, unsafeSets one, for this program and whatever it starts. True on success.
std.fmt
function Int
offer fun Int(value: int) -> textvalue in base ten.
function IntWidth
offer fun IntWidth(value: int, width: int) -> text uses unsafevalue in base ten, right-aligned in width with spaces.
function IntZeros
offer fun IntZeros(value: int, width: int) -> text uses unsafevalue in base ten, right-aligned in width with zeros.
The sign stays in front of the zeros, which is what a reader of a timestamp or an identifier expects.
function Radix
offer fun Radix(value: int, base: int) -> text uses unsafevalue in base base, from 2 to 16.
function Hex
offer fun Hex(value: int) -> text uses unsafevalue in hexadecimal, with no prefix.
function HexWidth
offer fun HexWidth(value: int, width: int) -> text uses unsafevalue in hexadecimal, width digits wide.
function Binary
offer fun Binary(value: int) -> text uses unsafevalue in binary.
function Float
offer fun Float(value: float, decimals: int) -> text uses unsafevalue with decimals digits after the point.
Rounded half away from zero, which is what a person reading a price expects -- and said here because the other roundings are defensible too.
function Percent
offer fun Percent(value: float, decimals: int) -> text uses unsafevalue as a percentage with decimals digits: 0.256 is 25.6%.
function Bytes
offer fun Bytes(count: int) -> text uses unsafeA count of bytes as a person would read it: 1536 is 1.5 KiB.
function Duration
offer fun Duration(nanos: s64) -> text uses unsafeA duration in nanoseconds as a person would read it.
function Left
offer fun Left(value: text, width: int) -> text uses unsafevalue padded on the left to width.
function Right
offer fun Right(value: text, width: int) -> text uses unsafevalue padded on the right to width.
function Centre
offer fun Centre(value: text, width: int) -> text uses unsafevalue centred in width.
std.fs
class File
offer class FileAn open file. Closing it is deinit's job, so a handle that goes out
of scope leaves no descriptor behind.
field fd
var fd: s32 = -1method deinit
deinitmethod IsOpen
fun IsOpen() -> boolmethod Close
fun Close() uses unsafemethod Read
fun Read(buffer: []mut u8) -> int uses unsafeFills buffer and says how many bytes arrived: zero at the end of
the file, negative when the system refused.
method Write
fun Write(bytes: []u8) -> int uses unsafefunction Open
offer fun Open(path: text) -> File uses io, unsafeOpens path for reading. The handle is closed when it goes away.
function Create
offer fun Create(path: text) -> File uses io, unsafeOpens path for writing, making it or emptying it first.
function ReadAll
offer fun ReadAll(path: text, limit: int) -> []u8 uses io, unsafeReads the whole of path into fresh storage.
The caller owns what comes back and gives it to Free -- which is
what a []u8 is: a view of bytes that are somewhere, and here the
somewhere is an allocation.
function WriteAll
offer fun WriteAll(path: text, bytes: []u8) -> bool uses io, unsafeWrites bytes to path, replacing what was there.
enum Kind
offer enum KindWhat a path is.
method Missing
Missingmethod File
Filemethod Directory
Directorymethod Other
Otherfunction KindOf
offer fun KindOf(path: text) -> Kind uses io, unsafeWhether path is a file, a directory, something else, or nothing.
function Exists
offer fun Exists(path: text) -> bool uses io, unsafeWhether there is anything at path.
function IsFile
offer fun IsFile(path: text) -> bool uses io, unsafefunction IsDirectory
offer fun IsDirectory(path: text) -> bool uses io, unsafefunction SizeOf
offer fun SizeOf(path: text) -> int uses io, unsafeHow many bytes the file holds, or -1.
function ChangedAt
offer fun ChangedAt(path: text) -> s64 uses io, unsafeWhen it last changed, as seconds since the epoch, or -1.
function Remove
offer fun Remove(path: text) -> bool uses io, unsafeTakes path away: a file, or a directory with nothing in it. True
when it is gone afterwards.
function Rename
offer fun Rename(from: text, to: text) -> bool uses io, unsafeMoves from to to, which is also how a file is replaced atomically:
write beside it, then rename over it.
function MakeDirectory
offer fun MakeDirectory(path: text, parents: bool) -> bool uses io, unsafeMakes a directory. With parents, every one above it too.
function List
offer fun List(path: text) -> text uses io, unsafeWhat is in path, as names separated by line breaks.
Names rather than paths, and one string rather than a list: the
caller splits it with std.text.Pieces, which is what it would do
with a list anyway -- and this way the whole listing is one
allocation and one call.
function Current
offer fun Current() -> text uses io, unsafeThe directory the program is running in.
function SetCurrent
offer fun SetCurrent(path: text) -> bool uses io, unsafeMoves the program to path. False when it is not a directory.
function Home
offer fun Home() -> text uses io, unsafeThe person's home directory, or "".
function TempDirectory
offer fun TempDirectory() -> text uses io, unsafeWhere temporary things belong on this machine.
function TempName
offer fun TempName(prefix: text) -> text uses io, unsafeA path in the temporary directory that nothing else has.
The name, not the file: a caller that wants it to exist writes to
it, and one that wants a directory calls MakeDirectory.
function Absolute
offer fun Absolute(path: text) -> text uses io, unsafepath with . and .. worked out, whether or not it is there yet.
function Copy
offer fun Copy(from: text, to: text, over: bool) -> bool uses io, unsafeCopies a file. over says whether an existing one may be replaced.
function RemoveTree
offer fun RemoveTree(path: text) -> bool uses io, unsafeTakes a directory and everything in it away.
A separate verb from Remove, which takes away one file or one
empty directory: deleting a tree is something a program should have
to say it means.
function Walk
offer fun Walk(path: text) -> text uses io, unsafeEvery path under path, one per line, as List answers for one
directory.
function Append
offer fun Append(path: text, value: text) -> bool uses io, unsafeAdds to the end of a file, making it when it is not there.
function ReadText
offer fun ReadText(path: text, limit: int) -> text uses io, unsafeThe whole of a text file.
function WriteText
offer fun WriteText(path: text, value: text) -> bool uses io, unsafeWrites text to a file, replacing what was there.
std.hash
function OfBytes
offer fun OfBytes(bytes: []u8) -> u64The hash of bytes.
function OfText
offer fun OfText(value: text) -> u64 uses unsafeThe hash of a string's bytes.
function OfInt
offer fun OfInt(value: int) -> u64The hash of a whole number.
Mixed rather than taken as it is: a map that takes the low bits of a key as its slot puts every multiple of its table size in one place, and sequential identifiers are the common case.
function Combine
offer fun Combine(left: u64, right: u64) -> u64Two hashes joined, for a key made of several parts.
function Slot
offer fun Slot(hash: u64, slots: int) -> intThe hash as a map wants it: a number from zero to slots.
function TextHash
offer fun TextHash(value: text) -> int uses unsafeWhat std.map wants for a text key: a hash as an int.
function TextEquals
offer fun TextEquals(left: text, right: text) -> bool uses unsafeWhat std.map wants for a text key: equality.
std.heap
class Heap
offer class Heap<T>field items
var items: []mut Tfield count
var count: int = 0field before
var before: fun(T, T) -> boolWhether the first argument comes out before the second.
method deinit
deinitmethod Len
fun Len() -> intmethod IsEmpty
fun IsEmpty() -> boolmethod Peek
fun Peek() -> TWhat comes out next, without taking it.
method Push
fun Push(value: T) uses unsafeAdds value, then moves it up until the order holds.
method Pop
fun Pop() -> TTakes the next one out. The caller checks Len first, for the same
reason a deque's Pop does.
method Clear
fun Clear()method Reserve
fun Reserve(wanted: int) uses unsafefunction HeapNew
offer fun HeapNew<T>(before: keep fun(T, T) -> bool) -> Heap<T> uses unsafestd.ini
error Malformed
offer error MalformedWhat a document that is not one answers with.
function Parse
offer fun Parse(input: text) -> Value!Malformed uses unsafeReads a document. Every value is text.
function Write
offer fun Write(value: Value) -> text uses unsafeA value as INI.
Members that are tables become sections and everything else becomes a pair at the top, which is the only arrangement INI has.
std.io
function Write
offer fun Write(message: text) uses io, unsafeWrites text to standard output, with no line break.
function Print
offer fun Print(message: text) uses ioWrites text and a line break.
function Warn
offer fun Warn(message: text) uses io, unsafeWrites message to standard error, with a line break.
Its own call rather than a flag on Print: a program that mixes the
two wants them to go to different places, and "which stream" is not
something a caller should have to pass every time.
function WriteError
offer fun WriteError(message: text) uses io, unsafeWrites message to standard error with no line break.
function ReadAll
offer fun ReadAll(limit: int) -> text uses io, unsafeReads up to limit bytes of standard input.
Answers what arrived, which may be less: a pipe hands over what it has. The bytes are a fresh allocation the caller owns.
function ReadLine
offer fun ReadLine() -> text? uses io, unsafeReads one line of standard input, without the line break.
Answers nothing at the end of input, which is what tells a loop reading commands to stop -- and what "" cannot say, because an empty line is a line.
class Out
offer class OutCollects output and writes it in blocks.
field held
var held: Builderfield fd
var fd: s32 = 1field most
var most: int = 65536How much to collect before writing by itself.
method deinit
deinitmethod Write
fun Write(message: text) uses io, unsafeAdds message, writing if there is enough to be worth it.
method Line
fun Line(message: text) uses io, unsafeAdds message and a line break.
method Flush
fun Flush() uses io, unsafeWrites what has been collected, if anything.
function OutNew
offer fun OutNew() -> Out uses unsafeA writer for standard output.
function ErrNew
offer fun ErrNew() -> Out uses unsafeA writer for standard error.
function OutTo
offer fun OutTo(fd: s32) -> Out uses unsafeA writer for an open file descriptor.
std.iter
ability Iterator
offer ability IteratorSomething that hands out values one at a time.
method Item
type Itemmethod Next
fun Next() -> boolMoves to the next value. False when there is none.
method Value
fun Value() -> ItemThe value Next moved to.
ability Iterable
offer ability IterableSomething that can be walked: it hands out an Iterator.
method Walker
type Walker: Iteratormethod Iterate
fun Iterate() -> Walkerfunction Count
offer fun Count<C: Iterable>(items: C) -> intHow many values items has, by walking them.
function Collect
offer fun Collect<C: Iterable>(items: C) -> List<C.Walker.Item> uses unsafeEvery value of items, in a list.
std.json
error Malformed
offer error Malformed(line: int, column: int)What a document that is not one answers with, and where: the line and the column, both counted from one (D235).
function Parse
offer fun Parse(input: text) -> Value!Malformed uses unsafeReads one value from input.
function Write
offer fun Write(value: Value) -> text uses unsafevalue as JSON text.
std.list
class List
offer class List<T>A sequence that grows.
Doubling, and never shrinking: an append is amortised constant and a
list that was big once stays ready to be big again, which is what a
frame loop wants. deinit gives the storage back, so a list that goes
out of scope leaves nothing behind.
field items
var items: []mut Tfield count
var count: int = 0method deinit
deinitmethod Len
fun Len() -> intmethod Iterate
fun Iterate() -> ListWalk<T>What for value in list walks with.
method Items
fun Items() -> []mut T uses unsafeThe elements, as a slice of exactly what is in the list.
A view, not a copy: writing through it writes the list. What every
function taking []T wants, which is most of them. The language
has no slicing syntax yet, so this is a view built from where the
storage is and how much of it is in use.
The view is valid only until the list next grows: Push or Reserve
past the capacity moves the storage and leaves the view pointing at
freed memory, and so does the list dying. Take it after the last
mutation and use it before the next (D227).
method Capacity
fun Capacity() -> intmethod At
fun At(index: int) -> TThe element at index, or the first one when the index is outside
the list. Reading past the end is a mistake the bounds check would
catch; this is the total function the library offers instead.
method Set
fun Set(index: int, value: T)method Push
fun Push(value: T) uses unsafeAdds value to the end, growing the storage when it is full.
method Pop
fun Pop() -> TDrops the last element and gives it back, or the first one when the list is empty.
method Clear
fun Clear()method Reserve
fun Reserve(wanted: int) uses unsafeMakes room for at least wanted elements.
Doubling rather than growing by one: a push that copies every time turns a loop into quadratic work, and the whole reason to have a list is that it does not.
class ListWalk
offer class ListWalk<T>Walks a list from front to back.
Next moves and says whether there is anything there; Value is what
it is standing on. Three names and no ability, because an ability that
said "what I walk over" needs an associated type the language does not
have yet (D96).
field over
var over: List<T>field at
var at: int = -1method Next
fun Next() -> boolmethod Value
fun Value() -> Tfunction ListNew
offer fun ListNew<T>() -> List<T> uses unsafeAn empty list, with no storage until something is pushed.
function Any
offer fun Any<T>(items: []T, holds: fun(T) -> bool) -> boolWhether anything in items satisfies holds.
function All
offer fun All<T>(items: []T, holds: fun(T) -> bool) -> boolWhether everything in items does.
function Count
offer fun Count<T>(items: []T, holds: fun(T) -> bool) -> intHow many satisfy holds.
function Find
offer fun Find<T>(items: []T, holds: fun(T) -> bool) -> intWhere the first one that satisfies holds is, or -1.
The index rather than the value: a caller that wants the value has the slice, and one that wants to write it back needs the index.
function Each
offer fun Each<T>(items: []T, body: fun(T))Runs body on each element.
function Fold
offer fun Fold<T, A>(items: []T, start: A, join: fun(A, T) -> A) -> AFolds items into one value, left to right.
function MapInPlace
offer fun MapInPlace<T>(items: []mut T, change: fun(T) -> T)Replaces each element with what change makes of it, in place.
In place rather than into a new list: a list that owns its storage is something to free, and a caller that wants both keeps a copy.
function Keep
offer fun Keep<T>(items: []mut T, holds: fun(T) -> bool) -> intMoves everything that satisfies holds to the front, and answers how
many there are.
What filtering is without allocating: the caller takes the first n
elements, and what was dropped is past them.
std.log
enum Level
offer enum LevelHow much to say.
method Trace
Tracemethod Debug
Debugmethod Info
Infomethod Warning
Warningmethod Error
Errormethod Silent
Silentfunction SetLevel
offer fun SetLevel(level: Level)Says nothing below level from here on.
function Enabled
offer fun Enabled(level: Level) -> boolWhether level would be written. For a caller whose message costs
something to build: the check is cheaper than the string.
function SetTimestamps
offer fun SetTimestamps(on: bool)Turns the timestamp off, for a program whose output is compared.
function At
offer fun At(level: Level, message: text) uses io, time, unsafeWrites one line at level.
function Trace
offer fun Trace(message: text) uses io, time, unsafefunction Debug
offer fun Debug(message: text) uses io, time, unsafefunction Info
offer fun Info(message: text) uses io, time, unsafefunction Warning
offer fun Warning(message: text) uses io, time, unsafefunction Error
offer fun Error(message: text) uses io, time, unsafestd.map
class Map
offer class Map<K, V>A map from K to V.
Open addressing with linear probing and a load factor of a half: one
allocation per table rather than one per entry, which is what makes a
lookup a couple of cache lines instead of a pointer chase. deinit
gives the three arrays back.
field keys
var keys: []mut Kfield values
var values: []mut Vfield filled
var filled: []mut boolfield count
var count: int = 0field hash
var hash: fun(K) -> intfield equals
var equals: fun(K, K) -> boolmethod deinit
deinitmethod Len
fun Len() -> intmethod Iterate
fun Iterate() -> MapWalk<K, V>What for key in map walks with: the keys, and Get for the rest.
method Slot
fun Slot(key: K) -> intWhere key is, or where it would go. -1 when there is no room,
which cannot happen while the load factor is kept under one.
method Has
fun Has(key: K) -> boolmethod Get
fun Get(key: K, fallback: V) -> VThe value for key, or fallback when it is not there. A total
function rather than an optional, because V may be anything and an
optional of it would be a second allocation shape to lay out.
method Put
fun Put(key: K, value: V) uses unsafemethod Remove
fun Remove(key: K) -> boolTakes key out. Answers whether it was there.
By shifting the run that follows back rather than by leaving a tombstone: a probe stops at the first empty slot, so a hole in the middle of a run would hide everything after it. Shifting keeps the invariant that every key is reachable from where it hashes to, which is what makes a lookup a walk and not a search.
method Reserve
fun Reserve(wanted: int) uses unsafeMakes room for wanted entries, keeping the table at most half
full: linear probing degrades sharply past that, and the whole
reason to probe rather than chain is that it does not chase
pointers.
class MapWalk
offer class MapWalk<K, V>Walks the entries of a map, in whatever order the table holds them.
A map is a table with holes, so walking it means skipping them: that is why this is a class with a position rather than an index into anything the caller can see.
field over
var over: Map<K, V>field at
var at: int = -1method Next
fun Next() -> boolmethod Value
fun Value() -> Kfunction MapNew
offer fun MapNew<K, V>(hash: keep fun(K) -> int, equals: keep fun(K, K) -> bool) -> Map<K, V> uses unsafefunction IntHash
offer fun IntHash(key: int) -> intHashing and comparing for int keys, which is most of them.
function IntEquals
offer fun IntEquals(left: int, right: int) -> boolfunction IntMapNew
offer fun IntMapNew<V>() -> Map<int, V> uses unsafeA map keyed by int, with the hashing already chosen.
function TextMapNew
offer fun TextMapNew<V>() -> Map<text, V> uses unsafeA map keyed by text: what a symbol table is (D250).
std.math
constant Pi
offer const Pi: float = 3.141592653589793The ratio of a circle's circumference to its diameter.
constant Tau
offer const Tau: float = 6.283185307179586A whole turn, which is the one that comes up in gameplay code.
function Sqrt
offer fun Sqrt(x: float) -> float uses unsafefunction Sin
offer fun Sin(x: float) -> float uses unsafefunction Cos
offer fun Cos(x: float) -> float uses unsafefunction Tan
offer fun Tan(x: float) -> float uses unsafefunction Atan2
offer fun Atan2(y: float, x: float) -> float uses unsafeThe angle of the vector (x, y), in radians.
function Pow
offer fun Pow(x: float, y: float) -> float uses unsafefunction Exp
offer fun Exp(x: float) -> float uses unsafefunction Log
offer fun Log(x: float) -> float uses unsafeThe natural logarithm.
function Floor
offer fun Floor(x: float) -> float uses unsafefunction Ceil
offer fun Ceil(x: float) -> float uses unsafefunction Round
offer fun Round(x: float) -> float uses unsafefunction Mod
offer fun Mod(x: float, y: float) -> float uses unsafeThe remainder of x / y, keeping x's sign.
function AbsFloat
offer fun AbsFloat(x: float) -> floatfunction Abs
offer fun Abs(x: int) -> intfunction Min
offer fun Min(a: int, b: int) -> intfunction Max
offer fun Max(a: int, b: int) -> intfunction MinFloat
offer fun MinFloat(a: float, b: float) -> floatfunction MaxFloat
offer fun MaxFloat(a: float, b: float) -> floatfunction Clamp
offer fun Clamp(value: int, low: int, high: int) -> intvalue, kept between low and high.
function ClampFloat
offer fun ClampFloat(value: float, low: float, high: float) -> floatfunction Lerp
offer fun Lerp(a: float, b: float, t: float) -> floata and b mixed by t, which is the one every gameplay curve is
made of.
function Near
offer fun Near(a: float, b: float, tolerance: float) -> boolWhether two floats are within tolerance of each other.
Comparing floats with == is almost always a bug; this is what the
comparison usually meant.
function WrappingAdd
offer fun WrappingAdd(a: u64, b: u64) -> u64a + b, keeping the low bits instead of trapping.
Everything else in this language traps on overflow, which is right for a program counting damage and wrong for one hashing a key or stepping a generator (D107). These three have no body: what they stand for is the instruction the compiler already writes for its own arithmetic.
function WrappingSub
offer fun WrappingSub(a: u64, b: u64) -> u64a - b, keeping the low bits.
function WrappingMul
offer fun WrappingMul(a: u64, b: u64) -> u64a * b, keeping the low bits.
std.mem
function BytesFromRaw
offer unsafe fun BytesFromRaw(data: *u8, length: int) -> []mut u8A view of length bytes at data.
unsafe because nothing here can check that there are that many, or
that they stay there. The caller promises both.
function SoaNew
offer unsafe fun SoaNew<T>(count: int) -> soa []mut TStorage for count records, laid out as one array per field.
soa []T is the same record with a different layout: a walk over one
field touches every value in a cache line instead of every seventh.
Which is the whole point, and why this is a layout rather than a type.
Like BytesFromRaw, it has no body: how big the storage is, is a
question only a tier can answer, so the compiler answers it at the call.
function ArrayNew
offer unsafe fun ArrayNew<T>(count: int) -> []mut TStorage for count records, one after another.
The same records as SoaNew and a different layout: this is the one
that reads well when a pass touches most of a record, and the other is
the one that reads well when it touches one field of it.
function Free
offer unsafe fun Free<T>(items: []T)Gives back storage ArrayNew or SoaNew handed out.
unsafe because nothing here can check that the view is the whole
allocation, or that nothing else is still looking at it. A collection
that owns its storage calls this from its deinit, which is where
those two promises are easy to keep.
Like the two above, it has no body: what a view's storage is depends on how the tier laid it out, so the compiler answers at the call.
function ViewFromRaw
offer unsafe fun ViewFromRaw<T>(data: *u8, count: int) -> []mut TA view of count values of T at data.
BytesFromRaw with an element type: the same pair, and the same
reason for having no body. unsafe because nothing here can check
that there are that many values there, or that they stay.
function Prefix
offer unsafe fun Prefix<T>(items: []T, count: int) -> []TThe first count elements of items, as a view.
A view and not a copy: writing through it writes the storage. What a
container with room to spare hands out -- List.Items() is this with
the count filled in -- and the one place that knows a slice is a
pointer and a length (D138).
function PrefixMut
offer unsafe fun PrefixMut<T>(items: []mut T, count: int) -> []mut TPrefix of a view that may be written, as a view that may be written
(D251). The same instruction: only what the caller is promised differs.
function Copy
offer unsafe fun Copy(to: []mut u8, at: int, from: []u8, count: int)Copies the first count bytes of from into to, starting at at.
One call where a loop would make one per byte: a builder that appends
a text, or a buffer that grows, is a copy and nothing else (D284). The
runs must not overlap, and to must have room, which unsafe is for.
function SizeOf
offer fun SizeOf<T>(value: T) -> intHow many bytes a value of value's type takes.
The value is not read -- what is wanted is its type, which is why this is spelled with an argument. How big a value is depends on how the tier laid it out, so the compiler answers at the call (D100).
function Suffix
offer unsafe fun Suffix<T>(items: []T, at: int) -> []TThe elements of items from at onwards, as a view.
The other half of Prefix, and an intrinsic for the same reason: a
view is a pointer and a length, and only the tiers know how far
along an element is. Between them a caller can name any run inside a
view without copying it (D177).
std.net
class Socket
offer class SocketOne connection, open until it is closed.
field fd
var fd: s32 = -1method IsOpen
fun IsOpen() -> boolmethod Send
fun Send(message: text) -> bool uses unsafeSends everything in message. False when the other end went away.
method Receive
fun Receive(limit: int) -> text uses unsafeReads up to limit bytes. "" when the other end closed.
method ReceiveAll
fun ReceiveAll(limit: int) -> text uses unsafeReads until the other end closes or limit bytes have arrived.
method Close
fun Close() uses unsafemethod SetNoDelay
fun SetNoDelay(on: bool) uses unsafeWhether small writes go out at once rather than waiting for more. What a server turns off, because a reply held back is latency nobody asked for.
method SetBlocking
fun SetBlocking(on: bool) uses unsafeWhether a call that would wait answers instead.
function ParseAddress
offer fun ParseAddress(host: text) -> s64? uses unsafeThe number a dotted address spells, or nothing.
No name lookup: a resolver is a protocol of its own, and a program that needs one should say so rather than have it happen inside a connect.
function Resolve
offer fun Resolve(host: text) -> s64? uses net, unsafeThe address host names, whether it is written as numbers or as a
name.
A dotted address is read here; a name goes to the system's resolver, because that is what every other program on the machine uses (D148).
function Connect
offer fun Connect(host: text, port: int) -> Socket uses net, unsafeConnects to host on port. A closed socket when it fails.
function Listen
offer fun Listen(port: int, backlog: int) -> Socket uses net, unsafeA socket listening on port, or a closed one.
function Accept
offer fun Accept(listener: Socket) -> Socket uses net, unsafeWaits for a connection on a listening socket.
struct Datagram
offer struct DatagramOne datagram received: how many bytes landed in the caller's buffer, who sent it, and whether it was longer than the buffer (then the rest is gone, as UDP has no way to ask for it again).
field count
var count: intfield address
var address: s64field port
var port: intfield truncated
var truncated: boolclass UdpSocket
offer class UdpSocketAn unconnected datagram socket (D244). Its fd can be given to a
poller like any other descriptor.
field fd
var fd: s32 = -1method IsOpen
fun IsOpen() -> boolmethod LocalPort
fun LocalPort() -> int uses net, unsafeThe port the socket is bound to; how port 0 says which was picked. -1 when closed.
method SendTo
fun SendTo(address: s64, port: int, bytes: []u8) -> int uses net, unsafeSends bytes as one datagram to address (see Resolve) and
port. The bytes sent, or -1: closed socket, no bytes, or more than
65507 (the most a datagram carries).
method SendTextTo
fun SendTextTo(address: s64, port: int, message: text) -> int uses net, unsafeSends the bytes of message; see SendTo.
method ReceiveFrom
fun ReceiveFrom(buffer: []mut u8) -> Datagram? uses net, unsafeTakes one datagram into buffer, never writing past its length. Null
when a non-blocking socket has nothing yet, or on an error; a
datagram longer than the buffer comes with truncated set.
method SetNonBlocking
fun SetNonBlocking(on: bool) uses net, unsafeWhether ReceiveFrom answers null at once (true) or waits (the
default).
method SetBroadcast
fun SetBroadcast(on: bool) -> bool uses net, unsafeWhether datagrams may be sent to the broadcast address.
method Close
fun Close() uses net, unsafefunction BindUdp
offer fun BindUdp(port: int) -> UdpSocket uses net, unsafeA UDP socket bound to port on every interface (0 picks a free one;
ask LocalPort), or a closed one.
function BindUdpOn
offer fun BindUdpOn(address: s64, port: int) -> UdpSocket uses net, unsafeLike BindUdp but on one local address (e.g. 127.0.0.1 from
ParseAddress), so a test or a LAN-only game stays off other
interfaces.
std.ops
ability Add
@Operator
offer ability Adda + b and a += b.
method Plus
fun Plus(other: Self) -> Selfability Sub
@Operator
offer ability Suba - b and a -= b.
method Minus
fun Minus(other: Self) -> Selfability Mul
@Operator
offer ability Mula * b and a *= b.
method Times
fun Times(other: Self) -> Selfability Div
@Operator
offer ability Diva / b and a /= b.
method Divide
fun Divide(other: Self) -> Selfability Neg
@Operator
offer ability Neg-a.
method Negate
fun Negate() -> Selfability Eq
@Operator
offer ability Eqa == b and a != b. The other side is borrowed, so comparing two
counted values neither copies nor frees either.
method Equals
fun Equals(other: &Self) -> boolability Ord
@Operator
offer ability Orda < b, a <= b, a > b and a >= b: Compare answers a negative
number, zero or a positive one for less, equal and greater.
method Compare
fun Compare(other: &Self) -> intability Hash
offer ability HashA number a table can file the value under. Not an operator: it is what
std.map and std.set ask of a key that is not a number or text.
method Hash
fun Hash() -> intfunction Max
offer fun Max<T: Ord>(a: T, b: T) -> TThe greater of two, by Ord.
function Min
offer fun Min<T: Ord>(a: T, b: T) -> TThe lesser of two, by Ord.
std.own
class Owned
offer class Owned<T>One value on the heap, owned by one name.
Moving it hands the value over; the name it was moved out of no longer
holds one, which the checker enforces (E0122). What it holds is
freed when it goes out of scope.
field at
var at: *mut u8field live
var live: bool = truemethod deinit
deinitmethod Get
fun Get() -> T uses unsafeWhat it holds.
method Set
fun Set(value: T) uses unsafeReplaces what it holds.
method Release
fun Release() -> *mut u8 uses unsafeGives up ownership without freeing, and answers where the value is.
unsafe because nothing here can promise that something else will
free it. For handing a value to C, which then owns it.
function OwnedNew
offer fun OwnedNew<T>(value: T) -> Owned<T> uses unsafevalue, moved onto the heap.
class Shared
offer class Shared<T>One value on the heap with several handles on it.
Clone takes another handle and the last one out frees the value.
There is no implicit copy: a type with a destructor is moved rather
than copied, so taking another handle is something the program says.
field at
var at: *mut u8field live
var live: bool = truemethod deinit
deinitmethod Get
fun Get() -> T uses unsafeWhat it holds.
method Set
fun Set(value: T) uses unsafeReplaces what it holds. Every handle sees the new value, which is what sharing means.
method Clone
fun Clone() -> Shared<T> uses unsafeAnother handle on the same value.
method Count
fun Count() -> int uses unsafeHow many handles there are on the value.
function SharedNew
offer fun SharedNew<T>(value: T) -> Shared<T> uses unsafevalue, moved onto the heap with one handle on it.
std.path
function IsAbsolute
offer fun IsAbsolute(path: text) -> bool uses unsafeWhether path starts from the root.
function Name
offer fun Name(path: text) -> text uses unsafeThe last part of path: a/b/c.wo is c.wo.
function Parent
offer fun Parent(path: text) -> text uses unsafeEverything before the last separator: a/b/c.wo is a/b.
"" for a name with no separator in it, and "/" for a path directly under the root -- both of which a caller joining onto the answer wants.
function Extension
offer fun Extension(path: text) -> text uses unsafeThe extension of the last part, without the dot: c.wo is wo.
"" when there is none, and "" for a name that is only a dot -- a leading dot is a hidden file rather than an extension.
function Stem
offer fun Stem(path: text) -> text uses unsafeThe last part without its extension: a/b/c.wo is c.
function Join
offer fun Join(left: text, right: text) -> text uses unsafeleft and right with one separator between them.
An absolute right wins, which is what every path library does and
what a caller joining a configured directory with a configured file
depends on.
function Normalize
offer fun Normalize(path: text) -> text uses unsafepath with . and .. worked out, and double separators removed.
Textual: it never looks at the filesystem, so a .. after a symbolic
link means what the text says rather than what the disk says.
A path with more than 64 parts left after the dots are worked out answers "" -- the one thing Normalize otherwise never returns -- rather than dropping the rest, which would turn a deep path into a different, shallower one (D223).
function IsInside
offer fun IsInside(path: text, directory: text) -> bool uses unsafeWhether path is inside directory, textually.
function WithExtension
offer fun WithExtension(path: text, extension: text) -> text uses unsafepath with a different extension. An empty extension removes it.
std.process
function Exit
offer fun Exit(code: int) uses io, unsafeStops the program with code. Nothing after this runs.
Destructors do not run: a program that has to tidy up should return
from main instead, and this is for the case where there is nothing
left to tidy.
function Id
offer fun Id() -> int uses io, unsafeThis program's identifier.
function Run
offer fun Run(command: text) -> int uses io, unsafeRuns command through the system shell and answers its exit code.
unsafe because the command is a string: what is in it is the
caller's responsibility, and a command built from input a program did
not choose is the oldest hole there is.
function Sleep
offer fun Sleep(millis: int) uses time, unsafeSleeps for millis milliseconds.
struct Said
offer struct SaidWhat another program did.
field code
var code: int = -1Its exit code, or a negative number when the system stopped it or it could not be started at all.
field out
var out: text = ""field errors
var errors: text = ""constant kMostOutput
offer const kMostOutput: int = 1048576How much of each stream to keep. A program that says more than this has the rest dropped, which beats a tool that grows without bound.
function Start
offer fun Start(command: text) -> Said uses io, unsafeRuns command and collects what it said.
No shell: the command is split on blanks with quoted runs kept
whole, and the program is started directly. Which is the difference
between running git and running whatever a ; in an argument says
(D153).
function StartWith
offer fun StartWith(command: text, input: text) -> Said uses io, unsafeThe same, with input written to the program's standard input.
function Works
offer fun Works(command: text) -> bool uses io, unsafeWhether command exists and ran without complaint.
struct Command
offer struct CommandEverything a caller may say about how a program runs.
Built up and handed to StartCommand, the way an HTTP call is
built up and handed to Perform (D151):
the command, what to write to it, where to run it, and what to add
to its environment.
field command
var command: text = ""field input
var input: text = ""field directory
var directory: text = ""field environment
var environment: text = ""NAME=value lines, added to what this process has rather than
replacing it -- a child with no PATH cannot find anything.
function CommandNew
offer fun CommandNew(command: text) -> Commandfunction WithInput
offer fun WithInput(run: Command, input: text) -> Commandfunction WithDirectory
offer fun WithDirectory(run: Command, directory: text) -> Commandfunction WithVariable
offer fun WithVariable(run: Command, name: text, value: text) -> Command uses unsafeOne more NAME=value for the child.
function StartCommand
offer fun StartCommand(run: Command) -> Said uses io, unsafeRuns what the Command describes.
std.random
class Random
offer class RandomA generator. Two words of state, held by value.
field low
var low: u64 = 0field high
var high: u64 = 0method Next
fun Next() -> u64 uses unsafeThe next 64 bits.
method Below
fun Below(limit: int) -> int uses unsafeA number in 0 .. limit, with limit itself excluded.
Zero when the limit is not positive, which is the answer that keeps a caller's loop from running forever.
method Between
fun Between(from: int, to: int) -> int uses unsafeA number from low to high, both included.
method Unit
fun Unit() -> float uses unsafeA float in 0.0 .. 1.0.
method Range
fun Range(from: float, to: float) -> float uses unsafeA float from from to to.
method Chance
fun Chance(chance: float) -> bool uses unsafeTrue with probability chance.
function RandomNew
offer fun RandomNew(seed: u64) -> Random uses unsafeA generator from a seed. The same seed gives the same sequence, which is what makes a bug in a procedural level reproducible.
function RandomFromClock
offer fun RandomFromClock() -> Random uses time, unsafeA generator seeded from the clock.
std.regex
error BadPattern
offer error BadPatternWhat a pattern that is not one answers with.
class Regex
offer class RegexA compiled pattern.
field steps
var steps: List<Step>field groups
var groups: int = 0field fold
var fold: bool = falsefield dot_all
var dot_all: bool = falsemethod Groups
fun Groups() -> intstruct Match
offer struct MatchWhere a match is: the whole of it, and each group.
start and end are byte offsets; a group that did not take part
has -1 for both.
field start
var start: int = -1field end
var end: int = -1field starts
var starts: [20]intfield ends
var ends: [20]intfield ok
var ok: bool = falsefunction MatchNone
offer fun MatchNone() -> Matchfunction Whole
offer fun Whole(input: text, found: &Match) -> text uses unsafeThe text a match covers.
function Group
offer fun Group(input: text, found: &Match, index: int) -> text uses unsafeThe text group index covers, or "" when it took no part. Group 1 is
the first (.
function Compile
offer fun Compile(pattern: text, flags: text) -> Regex!BadPattern uses unsafeCompiles pattern. flags holds i and s.
function Find
offer fun Find(pattern: &Regex, input: text) -> Match uses unsafeWhere pattern first matches in input, or a match that is not one.
function FindFrom
offer fun FindFrom(pattern: &Regex, input: text, from: int) -> Match uses unsafeThe same, starting at from.
function Matches
offer fun Matches(pattern: &Regex, input: text) -> bool uses unsafeWhether pattern matches anywhere in input.
function FindAll
offer fun FindAll(pattern: &Regex, input: text) -> List<Match> uses unsafeEvery match, left to right, without overlapping.
function ReplaceAll
offer fun ReplaceAll(pattern: &Regex, input: text, with: text) -> text uses unsafeinput with every match replaced by with.
$1 in with is the first group, $0 the whole match, and $$ a
dollar sign.
function Split
offer fun Split(pattern: &Regex, input: text) -> List<text> uses unsafeinput split on every match.
std.save
error Corrupt
offer error CorruptThe bytes are not a save of this class: they end early, name a class the program does not have, or are not a save at all.
struct Shape
offer struct Shape<T>What the compiler knows about T that the runtime needs: a description of
its saved fields, and the numbers only the tier running the program can
give, such as where a field sits.
field schema
var schema: textfield offsets
var offsets: u64function ShapeOf
offer fun ShapeOf<T>() -> Shape<T>The shape of T. Answered by the compiler, so it has no body.
function HandleOf
offer fun HandleOf<T>(value: T) -> u64An object as the word the runtime takes. Answered by the compiler.
function FromHandle
offer fun FromHandle<T>(word: u64) -> TThe object a word the runtime gave back stands for, with one reference for the caller. Answered by the compiler.
function Save
offer fun Save<T>(value: T) -> []mut u8 uses unsafeThe saved fields of value and of every object they reach, as bytes. Give
them back with Free when done. Empty when T cannot be saved.
function Load
offer fun Load<T>(data: []u8) -> T!Corrupt uses unsafeThe object data holds, with every object it reached.
std.set
class Set
offer class Set<T>A set of T, with the hash and the equality the caller gives.
field held
var held: Map<T, bool>method Len
fun Len() -> intHow many values it holds.
method Add
fun Add(value: T) -> bool uses unsafePuts value in. Answers whether it was new.
method Has
fun Has(value: T) -> bool uses unsafeWhether value is in it.
method Remove
fun Remove(value: T) -> bool uses unsafeTakes value out. Answers whether it was there.
function SetNew
offer fun SetNew<T>(hash: keep fun(T) -> int, equals: keep fun(T, T) -> bool) -> Set<T> uses unsafestd.sort
function Sort
offer fun Sort<T>(items: []mut T, before: fun(T, T) -> bool)Sorts items in place, with before(a, b) saying whether a comes
first.
The comparison has to be a strict order: before(a, a) false, and
before(a, b) and before(b, a) never both true. A comparison that
is not one leaves the elements in some order rather than looping.
function SortBy
offer fun SortBy<T: Ord>(items: []mut T)Sorts items in place by their own order, the one < gives them
(D239): Sort with the comparison already written.
function LowerBound
offer fun LowerBound<T>(items: []T, value: T, before: fun(T, T) -> bool) -> intWhere value is in a sorted slice, or where it would go.
The answer is an index between zero and items.len, which is what
makes it useful for inserting as well as for finding.
function Contains
offer fun Contains<T>(items: []T, value: T, before: fun(T, T) -> bool) -> boolWhether a sorted slice holds value.
std.tasks
function Yield
offer task fun Yield()Gives the scheduler a chance to run something else.
function Run
offer fun Run() -> s64 uses unsafeRuns every spawned task until none can make progress. Returns how many steps that took.
This is where the effect row stops being able to help: what Run does
is whatever the tasks do, and the row cannot say so. Keep the spawning
close to the running and the question stays answerable by reading.
function Done
offer fun Done(handle: s32) -> bool uses unsafeWhether the task behind handle has finished.
function Pending
offer fun Pending() -> s32 uses unsafeHow many spawned tasks have not finished.
function Join
offer fun Join(handle: s32) -> s64 uses unsafeRuns until the task behind handle has finished.
Not a task itself, and that is a limitation rather than a design: a
wait on a task from another module needs the frame layout that module
computed (E0305), so joining is done by running the scheduler rather
than by suspending. Inside a task, prefer wait on something in your
own module and keep Join for the top level.
function Wait
offer task fun Wait(seconds: f64)Suspends for seconds of the caller's clock, which moves only when the
caller calls Tick: pausing is not ticking and slow motion is a smaller
step, so a game needs no hook for its own time (D267). A wait of nothing
finishes at once. Like Yield it has no body, and for the same reason: the
compiler writes its machine, so wait Wait(2.0) works from any module.
function Tick
offer fun Tick(dt: f64) -> s64 uses unsafeHands the scheduler dt seconds of the caller's clock and gives every task
that was ready one step. A task that is not finished comes back next tick
and one spawned during this tick starts on the next. Returns how many steps
were taken.
function Now
offer fun Now() -> f64 uses unsafeThe sum of every dt given to Tick.
class Event
offer class EventSomething a task can wait for. A task waits on one by looking at it each
turn, while !event.raised { wait Yield() }, which keeps the waiting in
the module that knows what the event means.
field raised
var raised: bool = falsemethod Raise
fun Raise()Lets whoever is waiting go on.
method Clear
fun Clear()Makes it something to wait for again.
std.text
function Length
offer fun Length(value: text) -> intHow many bytes a piece of text is. Not how many characters: UTF-8 is bytes, and the two numbers differ exactly where it matters.
function IsEmpty
offer fun IsEmpty(value: text) -> boolfunction Bytes
offer fun Bytes(value: text) -> []u8 uses unsafeThe bytes of value, as a view. Nothing is copied. The view is
read-only: it is of text that may be a literal, and []u8 cannot be
written through (D251).
function Equals
offer fun Equals(left: text, right: text) -> bool uses unsafeWhether the two hold the same bytes.
function StartsWith
offer fun StartsWith(value: text, prefix: text) -> bool uses unsafeWhether value starts with prefix.
function IndexOf
offer fun IndexOf(value: text, needle: text) -> int uses unsafeWhere needle first appears in value, or -1.
class Builder
offer class BuilderText that owns its bytes.
Appending copies into storage the builder grew, so what comes out of
Text() stays valid until the builder goes away -- which is what a
destructor is for, and why this is a class and not a function.
field bytes
var bytes: []mut u8field count
var count: int = 0method deinit
deinitmethod Len
fun Len() -> intmethod Text
fun Text() -> text uses unsafeWhat has been built, as a view of the builder's own bytes.
The view is valid only until the next Append, Reserve or Clear
(they may move or rewrite the bytes) and until the builder dies (its
destructor frees them). Returning it from the function that owns the
builder, or keeping it after, dangles. A string that has to outlive
the builder is Release, the owning one (D227).
method Release
fun Release() -> text uses unsafeWhat has been built, as bytes that outlive the builder.
The storage goes with the string and the builder starts again empty
-- which is what a function that returns what it built needs, and
what Text cannot give. Nothing frees the bytes yet: the same
latitude every string that is built takes today (D67).
method Clear
fun Clear()method Append
fun Append(value: text) uses unsafemethod AppendLine
fun AppendLine(value: text) uses unsafevalue and a newline: what a printer that builds a dump line by line writes (D250).
method AppendByte
fun AppendByte(value: u8) uses unsafemethod Reserve
fun Reserve(wanted: int) uses unsafefunction BuilderNew
offer fun BuilderNew() -> Builder uses unsafefunction TextFromRaw
offer unsafe fun TextFromRaw(data: *u8, length: int) -> textfunction EndsWith
offer fun EndsWith(value: text, suffix: text) -> bool uses unsafeWhether value ends with suffix.
function Contains
offer fun Contains(value: text, needle: text) -> bool uses unsafeWhether needle is anywhere in value.
function LastIndexOf
offer fun LastIndexOf(value: text, needle: text) -> int uses unsafeWhere the last needle is, or -1.
function Substring
offer fun Substring(value: text, from: int, to: int) -> text uses unsafeThe bytes from from up to to, as a view: nothing is copied, and
the result lasts as long as value does.
Out-of-range bounds are clamped rather than trapped: a slice of a string is almost always computed from a search, and a search that found nothing should give an empty string rather than stop the program.
function After
offer fun After(value: text, needle: text) -> text uses unsafeEverything after the first needle, or "" when there is none.
function Before
offer fun Before(value: text, needle: text) -> text uses unsafeEverything before the first needle, or the whole string.
function Trim
offer fun Trim(value: text) -> text uses unsafevalue without the spaces at either end, as a view.
function TrimStart
offer fun TrimStart(value: text) -> text uses unsafefunction TrimEnd
offer fun TrimEnd(value: text) -> text uses unsafeclass Split
offer class SplitThe pieces of a string, between one separator and the next.
A walk rather than a list: each piece is a view into the string, so
for piece in Pieces(line, ",") costs one allocation less than
nothing -- and the protocol is the one every type that says how to be
walked uses (D96).
field value
var value: textfield separator
var separator: textfield at
var at: int = 0field piece
var piece: text = ""field done
var done: bool = falsemethod Iterate
fun Iterate() -> Splitmethod Next
fun Next() -> bool uses unsafemethod Value
fun Value() -> textfunction Pieces
offer fun Pieces(value: text, separator: text) -> SplitThe pieces of value separated by separator.
An empty separator gives the whole string as one piece, and a string with nothing in it gives one empty piece -- which is what every splitter does and what a caller counting fields expects.
function CountPieces
offer fun CountPieces(value: text, separator: text) -> int uses unsafeHow many pieces there are.
function PieceAt
offer fun PieceAt(value: text, separator: text, which: int) -> text uses unsafeThe whichth piece, counting from zero, or "".
function Join
offer fun Join(pieces: Split, separator: text) -> text uses unsafeThe pieces of value joined with separator between them.
Allocates: the answer is a new string, because the pieces are not next to each other in memory.
function Replace
offer fun Replace(value: text, needle: text, with: text) -> text uses unsafevalue with every needle replaced by with. Allocates.
function Upper
offer fun Upper(value: text) -> text uses unsafevalue in upper case, for the ASCII letters. Allocates.
function Lower
offer fun Lower(value: text) -> text uses unsafevalue in lower case, for the ASCII letters. Allocates.
function Repeat
offer fun Repeat(value: text, times: int) -> text uses unsafevalue repeated times over. Allocates.
function PadStart
offer fun PadStart(value: text, width: int, pad: text) -> text uses unsafevalue with pad added on the left until it is width long.
function PadEnd
offer fun PadEnd(value: text, width: int, pad: text) -> text uses unsafefunction ParseInt
offer fun ParseInt(value: text) -> int? uses unsafeThe whole number value spells, or nothing when it does not spell
one.
An optional rather than a fallback, because "this is not a number" and "this is zero" are different answers and a program reading a configuration file has to tell them apart.
function ParseFloat
offer fun ParseFloat(value: text) -> float? uses unsafeThe number value spells, or nothing.
std.thread
class Thread
offer class ThreadOne running thread.
field handle
var handle: u64 = 0method IsRunning
fun IsRunning() -> boolmethod Join
fun Join() -> bool uses unsafeWaits for it to finish. False when there was nothing to wait for.
function Spawn
@Thread
offer fun Spawn(body: fun()) -> Thread uses unsafeRuns body alongside the caller.
The body takes nothing and gives nothing back: what a thread works on
is what it can reach, which in this language means a module-level
var or something behind a lock. A parameter would be a pointer whose
lifetime nobody checks.
function Parallelism
offer fun Parallelism() -> int uses unsafeHow many threads this machine will really run at once.
class Mutex
offer class MutexA lock. deinit gives it back, so one that goes out of scope leaves
nothing behind.
field handle
var handle: u64 = 0method deinit
deinitmethod Lock
fun Lock() uses unsafemethod Unlock
fun Unlock() uses unsafefunction MutexNew
offer fun MutexNew() -> Mutex uses unsafefunction AtomicAdd
offer unsafe fun AtomicAdd(counter: *mut s64, delta: s64) -> s64Adds delta to the number at counter and gives back what was there
before, with no other thread able to see a half-done sum.
function ParallelFor
@Thread(captures)
offer unsafe fun ParallelFor(count: int, threads: int, body: fun(int, int))Runs body over [0, count) on threads threads, in chunks.
Each call gets a range to itself -- body(begin, end) -- so the body
is an ordinary loop and the work is split without any locking. Zero
threads means one per core, and the calling thread takes the last
chunk, so a one-thread loop spawns nothing (D147).
The body may be a closure, which is the point: ParallelFor(n, 0, |from, to| ...) takes what it needs with it. What it may not do is
write to what it captured -- a capture is a copy, and here there is
one copy per thread -- so a result comes back through storage the
body was given, by index.
Declared with no body: what the runtime needs is the two halves of the body's function value, and lowering is the only place that can take a function value apart (D147).
std.time
struct Instant
offer struct InstantA point in time, as the two numbers every system reports it as.
field seconds
var seconds: s64 = 0field nanos
var nanos: s64 = 0function Now
offer fun Now() -> Instant uses time, unsafeHow long the machine has been up, as seconds and nanoseconds.
Monotonic: the difference between two of these is a duration, and it is never negative no matter what happens to the system clock.
function WallClock
offer fun WallClock() -> Instant uses time, unsafeWhat the system thinks the time is, as seconds since the epoch.
function Elapsed
offer fun Elapsed(from: Instant, to: Instant) -> s64How many nanoseconds there are between from and to.
function ElapsedMillis
offer fun ElapsedMillis(from: Instant, to: Instant) -> s64The same, in milliseconds, which is what a frame budget is written in.
struct DateTime
offer struct DateTimeA moment taken apart, in UTC.
No time zones: they are a database that changes four times a year, and a program that needs one should read that database rather than have this guess. UTC is what a log line and a wire format want anyway.
field year
var year: int = 1970field month
var month: int = 1field day
var day: int = 1field hour
var hour: int = 0field minute
var minute: int = 0field second
var second: int = 0field weekday
var weekday: int = 4field yearday
var yearday: int = 1function Civil
offer fun Civil(seconds: s64) -> DateTimeseconds since the epoch, taken apart.
The civil-from-days algorithm: it shifts the year to start in March so that the leap day lands at the end, which is what removes every special case from the month arithmetic.
function YearDay
offer fun YearDay(year: int, month: int, day: int) -> intWhich day of the year a date is, from one.
function IsLeapYear
offer fun IsLeapYear(year: int) -> boolWhether year has a 29th of February.
function Epoch
offer fun Epoch(moment: DateTime) -> s64Seconds since the epoch for a date in UTC.
function Iso
offer fun Iso(moment: DateTime) -> text uses unsafe2026-10-15T14:03:07Z, which sorts as text and parses everywhere.
function Clock
offer fun Clock(moment: DateTime, millis: int) -> text uses unsafe14:03:07.123, which is what a log line wants.
function WeekdayName
offer fun WeekdayName(weekday: int) -> textThe three-letter name of a weekday, from Sunday.
function MonthName
offer fun MonthName(month: int) -> textThe three-letter name of a month, from one.
function HttpDate
offer fun HttpDate(seconds: s64) -> text uses unsafeWed, 15 Oct 2026 14:03:07 GMT: the date format HTTP uses.
function ZoneOffset
offer fun ZoneOffset(seconds: s64, zone: text) -> int uses time, unsafeHow many seconds zone is ahead of UTC at that moment.
The moment matters: half the world moves its clocks twice a year.
An empty zone is the machine's own. "Europe/Kyiv", "UTC",
"America/New_York" -- whatever the system's database holds.
function ZoneName
offer fun ZoneName(seconds: s64, zone: text) -> text uses time, unsafeWhat the zone is called at that moment: CET, PDT, EEST.
function CivilIn
offer fun CivilIn(seconds: s64, zone: text) -> DateTime uses time, unsafeThe same moment, as the wall clock reads in zone.
What a program shows a person: the moment is the same, the numbers are theirs.
function EpochIn
offer fun EpochIn(moment: DateTime, zone: text) -> s64 uses time, unsafeThe moment a wall clock in zone was showing.
Two passes: the offset depends on the moment, and the moment is what is being worked out. The second pass is what gets the hour after a clock change right.
function ParseIso
offer fun ParseIso(value: text) -> s64? uses unsafeReads 2026-10-15T18:09:23Z and the shapes around it.
What it takes: a date, optionally a time after T or a blank,
optionally a fraction, optionally Z or +02:00. What it answers:
seconds since the epoch, or nothing when the text is not a moment.
The one format worth having built in, because it is the one every
machine writes (D176).
function IsoInstant
offer fun IsoInstant(seconds: s64) -> text uses unsafe2026-10-15T18:09:23Z from a moment, which is what ParseIso reads
back. Iso is the same thing from a DateTime.
function Ago
offer fun Ago(seconds: s64, now: s64) -> text uses unsafeHow long ago, in words a person reads: just now, 3 minutes ago,
2 days ago. What a listing shows instead of a timestamp.
std.toml
error Malformed
offer error Malformed(line: int, column: int)What a document that is not one answers with, and where: the line and the column, both counted from one (D235).
function Parse
offer fun Parse(input: text) -> Value!Malformed uses unsafeReads a document.
function NumberOf
offer fun NumberOf(spelled: text) -> float? uses unsafeThe number spelled is, in any of TOML's four bases, or nothing.
function Write
offer fun Write(value: Value) -> text uses unsafeA value as TOML.
Tables are written as headers and arrays of tables as double headers, which is what a person writing a manifest by hand would have written.
std.utf8
function Width
offer fun Width(first: u8) -> intHow many bytes the code point starting at first takes.
Zero for a byte that cannot start one, which is what tells a walk to stop rather than to loop.
function Count
offer fun Count(value: text) -> int uses unsafeHow many code points value holds.
function IsValid
offer fun IsValid(value: text) -> bool uses unsafeWhether value is valid UTF-8 throughout.
struct Char
offer struct CharOne code point and where the next one starts.
field code
var code: intfield at
var at: intfield width
var width: intfunction CharAt
offer fun CharAt(value: text, at: int) -> Char uses unsafeThe code point starting at byte at.
class Chars
offer class CharsA walk over the code points of a string.
field value
var value: textfield at
var at: int = 0field current
var current: Char = Char(0, 0, 0)method Iterate
fun Iterate() -> Charsmethod Next
fun Next() -> bool uses unsafemethod Value
fun Value() -> intfunction Walk
offer fun Walk(value: text) -> CharsThe code points of value, for for code in Walk(value).
function Encode
offer fun Encode(code: int) -> text uses unsafeOne code point as text. Allocates.
function AppendTo
offer fun AppendTo(builder: &mut Builder, code: int) uses unsafeWrites one code point into a builder.
std.yaml
error Malformed
offer error Malformed(line: int, column: int)What a document that is not one answers with, and the line it went wrong on and a column in it, both counted from one (D235).
function Parse
offer fun Parse(input: text) -> Value!Malformed uses unsafeReads the first document of input.
function ParseAll
offer fun ParseAll(input: text) -> List<Value>!Malformed uses unsafeEvery document in a stream, which is what --- separates.
function ReadScalar
offer fun ReadScalar(value: text) -> Step uses unsafeWhat a scalar on one line is, with the core schema applied.
function Resolve
offer fun Resolve(held: text) -> Value uses unsafeA plain scalar, as the core schema reads it.
function NumberOf
offer fun NumberOf(spelled: text) -> float? uses unsafeThe number spelled is, in any base YAML allows, or nothing.
function Write
offer fun Write(value: Value) -> text uses unsafeA value as YAML.
Block style, two spaces an indent, which is what a person writing it by hand would have written.