Standard library
import std/file
import std/http
import std/http/websocket
import std/io
import std/net
fn handle(req: http.Request) -> http.Response {
if req.path == "/chat" {
using ws = websocket.accept(req) catch {
_ => return http.response(400, "")
}
let m = websocket.receive(ws) catch {
_ => return http.upgraded()
}
websocket.send_text(ws, str(m.data)) catch {
_ => {}
}
return http.upgraded()
}
http.response(200, file.read_text("index.html") catch "missing")
}
fn main() ! io.Error {
let client = http.client().with_bearer_token("token").with_timeout(5000).build()
let page = client.get("https://example.com/") catch {
_ => return
}
using l = net.listen("", 8080)?
http.serve(l, handle)?
}
import std/<name> loads a standard library module. The library is compiled into low, and the project root is not searched for it.
Every module except std/math and std/sql/sqlite talks to the kernel through raw syscalls. std/math calls libm and std/sql/sqlite calls libsqlite3 through extern blocks. A library is linked only when reachable code calls it, so a program stays static unless it calls one of their C functions.
| Module | Contents |
|---|---|
std/io | Error, the error type shared by the I/O, codec and protocol modules. Stream, a copyable struct of read, write and close closures that views a resource. Guard and Lease (guard, enter, retire), the shared state that makes a closed descriptor fail with NotConnected instead of reaching a reused descriptor. A buffered Reader over a stream or, with bytes_reader, over a buffer, with read_line, read_exact, read_some, read_byte, buffered and fill. write_all, read_all, buffer(n), copy, and big- and little-endian byte helpers. |
std/file | Opening: open, create, append and update return a droppable File whose handle is a copyable FileHandle. On a File: read, write, write_all, seek, sync, truncate, close, info and stat. On a FileHandle: read_on, write_on, write_all_on, close_on and stream_on. Whole files and directories: exists, read_file, read_text, write_file, write_text, remove, remove_dir, rename, mkdir, mkdir_all, list and stream. read_file sizes its buffer from the file's size; a file that reports no size, such as one under /proc, is read into a 64 KB buffer that doubles when full. Permission bits: create_mode, write_file_mode, write_text_mode, mkdir_mode and mkdir_all_mode take them, the other creators use 0o644 for files and 0o755 for directories, all are filtered by the process umask, and chmod is not. Locks: try_lock and unlock are advisory flock locks that report a held lock as false instead of waiting. remove_all removes a tree without following symbolic links. temp_dir creates a private directory under /tmp. Info also carries regular, link, accessed, uid, gid, device and inode. Further functions: lstat, is_dir, is_file, is_symlink, symlink, link, readlink, realpath, chown, lchown, set_times, disk_usage and read_dir_info. walk is a sorted depth-first walk that uses lstat, never descends into symbolic links and lets its callback return Continue, Skip or Stop. glob matches each segment with path.matches and supports **. copy and copy_dir keep file modes and recreate symbolic links. temp_file(dir, pattern) creates a uniquely named file with O_EXCL and mode 0600 and returns a droppable TempFile that closes and removes it unless keep is called. temp_dir_pattern makes a 0700 directory the same way. |
std/file/watch | inotify. watch and watch_with take paths and Options (recursive, access) and return a droppable Watcher with a copyable WatcherHandle. On a watcher: add, remove, next, events and stop. next parks the green thread until an Event (watched, name, path, kind, dir, cookie) arrives. events is a chan[Event] fed by a forwarding green thread. Kind is Created, Modified, Deleted, MovedFrom, MovedTo, Attrib, Closed, ClosedUnmodified, Opened, Accessed, SelfDeleted, SelfMoved or Overflow. |
std/net | Addresses: IPv4 and IPv6 Addr, parse_ip, format_ip, parse_addr, format, in_network (tests an address against a CIDR prefix) and is_global (false for addresses the IANA special-purpose registries mark as not globally reachable, and for multicast). Types: the droppable Listener, Conn and Socket, each with a copyable ListenerHandle, ConnHandle or SocketHandle in its handle field; adopt and detach convert between a ConnHandle and a Conn. TCP: listen, accept, accept_handle (returns the connection's view for a green thread to adopt), connect, dial and their _within forms with a connect timeout, connect_through (binds the socket to a network interface first), connect_first (tries a list of addresses in order through an optional interface) and interface_index. Connection I/O: read, write, write_all, close, shutdown_write, set_nodelay, read and write timeouts and stream, with read_on, write_on, write_all_on, close_on and stream_on on the view. UDP: bind_udp, send_to, receive_from and close_socket. lookup tries an IP literal, then /etc/hosts, then A and AAAA queries to each /etc/resolv.conf nameserver. An Addr with an empty ip is a Unix address: listen_unix, connect_unix, connect_unix_within and socketpair return the same Listener and Conn, abstract names start with @ or NUL, and a listener unlinks its pathname when closed. peer_credentials returns the peer's credentials. listen_with and bind_udp_with take ListenOptions (reuse_addr, reuse_port, backlog). Socket options: set_keepalive and set_buffer_sizes. UDP multicast: join_group, leave_group, set_multicast_ttl, set_multicast_loop and set_multicast_interface. Dialer is a function value that makes a connection; direct_dialer is the plain one. |
std/socks | SOCKS5 (RFC 1928, with RFC 1929 username and password) and SOCKS4a clients: dial, dial4a, tunnel and tunnel4a over an existing connection, and dialer and dialer4a, which return a net.Dialer. The proxy resolves the target name. |
std/pipe | Pipelines. A Pipe owns a Reader and a Writer, each droppable so that releasing it completes it, with copyable ReaderHandle and WriterHandle views for green threads (adopt_reader, adopt_writer and the _on operations). Also segmented buffers, backpressure, Sequence and SequenceReader, and adapters between pipes and streams. |
std/cancel | Token with token, child, cancel, cancelled, check and done (a channel that closes on cancellation, for select). on_cancel returns a droppable Registration that releases its callback; release, on_cancel_handle and release_on work on the copyable RegistrationHandle. pause is a sleep that ends early on cancellation. |
std/http | Server types: Request, Response, Header, header helpers and parse_url. Request.token is cancelled when the client goes away and when the handler returns. Request.remote is the client's IP address for connections served by serve, serve_tls and serve_conn. Serving: serve, serve_tls, serve_conn and serve_stream; the _on forms (serve_on, serve_tls_on, serve_conn_on) take the listener's or connection's view. Client: a pooled client configured through client() and with_* builders, per-request builders, send, stream_to and download. with_interface binds every connection to a network interface. with_resolver substitutes for net.lookup on host names; TLS keeps the host name for SNI and certificate checks. with_cancel makes a request fail with Cancelled once its token is cancelled. URLs: parsing, resolution and encoding. connect returns a droppable Connection that closes its stream when released; detach hands the stream on. Proxies: with_proxy, with_http_proxy, with_https_proxy, with_no_proxy, with_proxy_from_environment and with_dialer send requests through an http:// proxy (absolute-form for http targets, CONNECT for https targets) or a socks5://, socks5h://, socks4:// or socks4a:// proxy. no_proxy follows Go's matching rules. CookieJar is a shared RFC 6265 jar (cookie_jar, with_cookie_jar, jar_set, jar_header, jar_cookies, jar_clear) that enforces the Secure rules and the __Secure- and __Host- prefixes and has no public-suffix check. A Response whose stream is a chan[[]u8] is written as it is produced, chunked on HTTP/1.1 and as DATA frames on HTTP/2, until the handler closes the channel. |
std/http/websocket | accept and dial over ws and wss return a droppable Socket that sends a normal close when released. Operations: receive, send_text, send_binary, ping and close, with _on forms, and adopt and detach on the *SocketHandle. |
std/http/sse | Server-sent events. Shared: Event (id, event, data, retry), format, comment and keepalive. Server: stream, stream_with, serve_events, serve_events_with, Emitter and last_event_id. Client: parser, feed, parse and listen, which reads a text/event-stream response with any chunking and CR, LF or CRLF line ends. |
std/http/files | serve_file and serve_file_with answer a request from a file. Content type comes from the extension, then sniffing. Weak ETag and Last-Modified work with If-None-Match and If-Modified-Since. A single Range is answered as 206 or 416, with If-Range. HEAD is supported and the body is streamed. |
std/web | A router with groups, middleware and typed JSON endpoints, problem details (RFC 9457), an OpenAPI 3.1 document built from the types, cookie sessions, CSRF protection, API key, Basic and bearer authentication, CORS and response compression. static and static_with serve a directory. events and event_stream serve server-sent events. |
std/tls | TLS 1.2 and 1.3 clients and servers. client, server and dial return a droppable Session that sends close_notify and closes the stream beneath it when released. Its handle is the shared *SessionHandle holding protocol, version, group, suite, cipher_suite and peer_certificates. client_handle and server_handle return the view alone, and read_on, write_on, close_on and stream_on operate on it. |
std/serde | The Writer and Reader protocols, write[T], read[T] and schema[T] (which the compiler derives for every type), and Field[T, F]. |
std/json | A reader and writer over UTF-8 bytes, the Value document model, equal (compares numbers numerically and objects without regard to member order), and serialize[T] and deserialize[T] with naming policies. |
std/json/pointer | RFC 6901 pointers: escape, unescape, parse, format, get, has, set, add, replace, remove and relative pointers. Edits return a new document. |
std/json/patch | RFC 6902 apply (atomic, failing with the operation's index) and diff; RFC 7396 merge_patch and merge_diff. |
std/json/path | RFC 9535 JSONPath: compile, query, find, values and paths, with slices, filters, match, search, length, count and value, normalised paths, and syntax errors at a byte offset. |
std/json/schema | JSON Schema 2020-12. compile and compile_with check the schema, resolve $ref, $anchor, $dynamicRef and registered resources, and precompile patterns. validate returns Violations with the instance pointer, the keyword pointer and a message. unevaluatedProperties and unevaluatedItems use annotations from the branches that passed. format annotates or asserts. |
std/cbor | CBOR (RFC 8949): the Value model, a decoder with depth and length limits, a deterministic encoder, diagnostic notation, and serialize[T] and deserialize[T]. |
std/webauthn | A WebAuthn relying party: registration and authentication options as JSON, registration and authentication verification for ES256, EdDSA and RS256 credentials, and COSE key parsing. |
std/sql | The driver contract: Connection, the droppable owner that closes the driver connection when released; ConnectionHandle, the copyable view of closures that std/orm and closures use (handle makes it from an owner, adopt the other way); Value, Rows, Error, Options and dialect helpers. |
std/sql/postgres | A PostgreSQL driver over protocol 3.0, plain or over TLS. |
std/sql/sqlserver | A Microsoft SQL Server driver over TDS 7.4, plain or over TLS. |
std/sql/sqlite | SQLite through libsqlite3, linked only when a program calls it. open and open_with (read-only, create, busy timeout). exec runs scripts. query, each and execute take ? or ?N parameters over cached prepared statements. Also last_insert_id, begin, begin_immediate, commit and rollback, and backup to a file through the online backup API. close and close_on are idempotent; a closed Database fails with sql.Error.Closed. connection and connect present a database as an sql.Connection: the one connection returns leaves closing to the Database, the one connect returns closes it. Calls block their OS thread. |
std/sql/pool | A pool of connections made by an opener. open takes a Config (max, max_idle, idle_timeout, max_lifetime, wait_timeout, ping_after, ping, clock). acquire and acquire_until (with a cancel token) park in first-in first-out order while every connection is in use. A droppable Lease returns its connection on release. Also with, discard, prune, stats and shutdown. |
std/sql/migrate | Ordered migrations recorded in a schema_migrations table with a SHA-256 checksum: plan, with_table, status, up, up_to and down, each migration in its own transaction under a lock. from_text and load_dir read -- +up and -- +down files named NNN_name.sql. |
std/toml | TOML 1.0.0: a table tree, an encoder, and serde binding. |
std/yaml | YAML 1.2.2: events, a node tree, an encoder, and serde binding. |
std/otel | OpenTelemetry traces, metrics and logs with W3C propagation, OTLP/HTTP protobuf and JSON, OTLP/gRPC and console exporters, and the instrumentation used by std/http, std/web, std/sql/postgres, std/sql/sqlserver and std/orm. |
std/protobuf | The protobuf wire format: an encoder with nested messages and packed fields, and a field decoder. |
std/xml | XML 1.0 with namespaces: a pull reader, a tree, a writer, and serde binding. |
std/orm | Typed queries over field references, row mapping, inserts, updates and deletes, tables created from types, and raw queries mapped onto structs, over an sql.ConnectionHandle. |
std/compress/deflate | DEFLATE, zlib and gzip. |
std/compress/xz | xz with LZMA2, and .lzma. |
std/compress/zstd | Zstandard (RFC 8878). |
std/compress/lz4 | LZ4 frames. |
std/compress/brotli | Brotli (RFC 7932). |
std/compress/bzip2 | compress(data, level), decompress(data, limit), a streaming decode and an Encoder. The decoder reads multiple streams and blocks and checks both CRCs. Randomised blocks fail with Unsupported. |
std/compress/snappy | Raw blocks (compress_block, decompress_block, decoded_length) and the framing format with masked CRC-32C (compress, decompress, decode, Encoder). |
std/hash | One-shot and incremental forms of CRC-32, CRC-32C, Adler-32, CRC-64 and xxHash32/64. Also FNV-1 and FNV-1a in 32 and 64 bits; SipHash-2-4 and SipHash-1-3 with a 16-byte key in 64- and 128-bit forms; MurmurHash3 (murmur3_32, murmur3_128); wyhash final 4.2; jump consistent hashing; and rendezvous hashing. |
std/bits | Dense bitsets. |
std/bits/roaring | Roaring bitmaps with the portable serialization format. |
std/image | Bitmaps, pixel operations and resizing, with PNG, JPEG, GIF, BMP, QOI and lossless WebP codecs. |
std/crypto | sha1, and random, which reads getrandom. |
std/crypto/hash | Algorithm and cloneable Digest, SHA-256, SHA-384 and SHA-512, HMAC, HKDF and constant-time equal. |
std/crypto/sha3 | SHA3-256, SHA3-384, SHA3-512, SHAKE128 and SHAKE256. |
std/crypto/aead | Aead values for AES-128-GCM, AES-256-GCM, ChaCha20-Poly1305 and XChaCha20-Poly1305 (xchacha20_poly1305, 24-byte nonce). The AES block functions for 128-, 192- and 256-bit keys (aes_key, encrypt_block_into, decrypt_block, decrypt_block_into). The ChaCha20 functions chacha20_xor (takes the RFC 8439 block counter) and hchacha20. |
std/crypto/md5 | MD5 as a hash.Algorithm, so HMAC, HKDF and PBKDF2 work over it, and sum. For interop and checksums, not security. |
std/crypto/cipher | AES in CBC, raw (cbc_encrypt, cbc_decrypt) or with PKCS#7 padding (cbc_seal, cbc_open, pkcs7_pad, pkcs7_unpad); in CTR with a 128-bit big-endian counter (ctr); and in XTS with ciphertext stealing (xts, xts_encrypt, xts_decrypt). There is no ECB, and CBC provides no integrity: use an Aead. |
std/crypto/x25519, std/crypto/ed25519 | X25519 key agreement (RFC 7748) and Ed25519 signatures (RFC 8032), over std/crypto/curve25519. |
std/crypto/ecdsa | ECDH and ECDSA on P-256 and P-384, with RFC 6979 nonces and SEC1 private keys. |
std/crypto/rsa | RSA PKCS#1 v1.5 and PSS signing and verification, and PKCS#1 keys. |
std/crypto/blake3 | BLAKE3: sum, xof, keyed_hash, derive_key, an incremental Hasher with finalize and seekable finalize_at, and algorithm(), a hash.Algorithm for HMAC. |
std/crypto/otp | HOTP (RFC 4226) and TOTP (RFC 6238) over SHA-1, SHA-256 and SHA-512: hotp, totp, verify_totp with a window, verify_hotp, generate_secret, base32 secrets, and otpauth:// uri and parse_uri. |
std/crypto/mlkem | ML-KEM-512, -768 and -1024 (FIPS 203). |
std/crypto/jose | JSON Web Tokens: compact JWS with HS256/384/512, RS256/384/512, PS256/384/512, ES256, ES384 and EdDSA, JWK sets, and claim checks. |
std/crypto/password | Password hashes in PHC strings: Argon2id, scrypt (RFC 7914, with a memory limit checked before allocating) and PBKDF2. bcrypt ($2b$; passwords over 72 bytes are rejected). verify handles all of them and $2a$ and $2y$ bcrypt strings. BLAKE2b. |
std/crypto/x509 | DER, PEM, certificates, PKCS#8 private keys, the system roots, chain validation and TLS signature schemes. |
std/time | now (Unix seconds), now_millis and now_nanos (the wall clock at finer resolution), monotonic (nanoseconds), sleep_for (rounds up to whole milliseconds), after, Timer and Ticker (their channels work in select), and Stopwatch. Calendar and zone types live in the submodules below, one module per type, so d.plus(span.days(3)) resolves to date.plus. |
std/time/fault | Fault (OutOfRange, Invalid, Syntax(at), Overflow, UnknownZone, Malformed, Unsupported, Skipped, Ambiguous, OffsetConflict), the error every fallible time function returns, and to_string. |
std/time/duration | Duration, an exact signed elapsed time with private seconds and nanoseconds. Constructors from nanoseconds to hours, and from_seconds_f64. Arithmetic: plus, minus, times, divide, ratio, negate, abs, with try_ forms returning an optional. Plain forms panic on overflow. Also round and truncate with a Rounding, comparison, to_string (ISO 8601 PT1H30M), friendly (1h 30m) and parse, which reads both forms and fails at the offset of the first bad character. |
std/time/timestamp | Timestamp, a point on the UTC timeline from 0001-01-01 to 9999-12-31 with nanosecond precision: now, from_unix in seconds, milliseconds or nanoseconds, plus and minus by Duration, until and since, round, truncate, RFC 3339 to_string and parse (offset required, :60 read as :59), and to_http_date and parse_http_date (IMF-fixdate, RFC 850 and asctime). |
std/time/clock | Clock, a pair of closures for the wall and monotonic readings, with system, fixed and manual. A Manual clock moves with advance and set, so code that asks for the time is tested without sleeping. |
std/time/span | Span, a calendar amount of years, months, weeks, days and time units with one sign. Unit, Diff (largest, smallest, increment, mode), to_duration and from_duration, ISO 8601 to_string (P1Y2M3DT4H), friendly and parse. |
std/time/rounding | Rounding (Trunc, Ceil, Floor, Expand and the five Half modes) and the helpers the other time modules share. |
std/time/date | Date with private fields and validated constructors (of, clamped, from_epoch_days, from_ordinal, from_iso_week, from_weekday_in_month). Month, Weekday and IsoWeek. plus and minus by Span with month-end clamping, until and since with a Diff, next_weekday and on_or_next, and range. ISO 8601 to_string and parse (calendar, ordinal and week dates). format and parse_with over a pattern. |
std/time/timeofday | TimeOfDay to the nanosecond. plus fails past midnight and plus_wrapping wraps. Also until, round, truncate, to_string, parse, and pattern format and parse_with. |
std/time/datetime | DateTime, a civil date and time of day with no zone: plus by Span or Duration, until and since with a Diff, round, truncate, to_string, parse (an offset is rejected), and pattern format and parse_with. |
std/time/offset | Offset, a UTC offset in whole seconds within ±25:59:59, with utc, hours, hm, to_string, to_string_z and parse. |
std/time/zone | IANA zones. Zone is a shared value decoded once, from named (the host database, honouring ZONEINFO), load_from (any fn(str) -> []u8?), local (TZ, /etc/localtime, /etc/timezone, then UTC), from_posix, decode, utc or fixed. Queries: info_at, candidates (One, Overlap, Gap for a civil time), next_transition, previous_transition and transitions. |
std/time/tzdata | An embedded copy of the database for hosts without one: source (for zone.load_from), names and version. The data is linked only when source or names is reachable. |
std/time/zoned | Zoned, a Timestamp seen through a Zone whose offset is always the zone's own. Built from a civil time with a Disambiguation (Compatible, Earlier, Later, Reject) or strict. plus by Span moves calendar units on civil dates and time units by elapsed time; plus_duration is exact. Also until and since with a Diff, start_of_day, hours_in_day, series and round. RFC 9557 to_string (2026-11-11T10:00:00+00:00[Europe/London]), to_rfc3339, to_rfc2822, and parse with an OffsetPolicy for a written offset that disagrees with the zone. Pattern format and parse_with. |
std/time/pattern | Compiled strftime and strptime patterns shared by the types above: compile, Names for other languages, render and scan. Verbs: %Y %y %C %m %d %e %j %b %B %a %A %u %w %U %W %V %G %H %I %M %S %f %N %p %P %z %:z %::z %Z %s %F %T %R %D %% %n %t. Flags: -, _, 0 and ^. Parsing is strict, and every error carries a byte offset. |
std/time/humanize | ago, relative, in_words, compact and round_to over a Words value; English by default. |
std/simd | Vector reads and writes, splat, mask, blend, min, max, lane access, byte shuffles, bit counting and find_byte. |
std/text | Parsing and formatting: integer parsing in any base from 2 to 36; correctly rounded float parsing, which allocates only to expand a decimal when digits beyond the 19th decide the rounding; parse_bool, radix, hex and hex encoding; fixed(x, places), which rounds half to even on the exact binary value. Trimming and splitting: trim and its start, end, prefix and suffix forms; split on a byte; split_str on a string (an empty separator splits into code points); fields; lines (drops a final empty line and \r before \n); chars; join. Searching: index, last_index, contains, count, starts_with, ends_with. Rewriting: repeat, replace, ASCII upper and lower (return their argument when no byte changes), and case-insensitive equal_fold and starts_with_fold (allocate nothing). Widths: char_count, from_char, and pad_left and pad_right to a width in code points. append and append_char onto a []u8. Comma-separated token lists. cut and last_cut return a Cut of before, after and found. strip_prefix and strip_suffix return str?. Also split_n, title, quote and unquote (backslash, \x, \u and \U escapes, failing with QuoteError), edit_distance over code points, wrap to a width, is_ascii and reverse. |
std/text/diff | Myers line diff: diff, lines, stats, distance, similarity, GNU-compatible unified and hunks, patch and patch_within over a unified diff, and word and character level inline, inline_chars and inline_markup. |
std/text/table | Table with per-column Align, width limits, truncation and wrapping, and Border styles None, Ascii, Unicode, Markdown and Tabs. Widths use unicode.text_width and ignore ANSI sequences. align and align_tabbed align tab-separated cells like Go's tabwriter. |
std/text/naming | words, snake, kebab, dotted, screaming_snake, camel, pascal, title, sentence, the matching is_ predicates, and slug and slug_with (transliterate Latin letters and cut at a word boundary). |
std/text/number | format_bytes and parse_bytes in decimal and binary units, grouped, ordinal, percent, compact, si, English words, and roman with parse_roman. Arithmetic is exact. |
std/builder | A Builder over a growing byte buffer, appended in place through mut: write, write_bytes, write_byte, write_char, write_i64, write_f64, write_line, write_repeat, write_join, len, capacity, reserve, truncate, reset, to_str and to_bytes. |
std/regex | Linear-time regular expressions in the RE2 style: compile and compile_with with Flags, generated (a pattern compiled into specialised code at build time), is_match, find, full_match, find_all, replace_all (with a closure receiving each Match), split and split_n. A match offers start, end, text, group and span, with byte offsets. |
std/unicode | Normalization (Unicode 16.0.0): nfd, nfkd, nfc and nfkc; combining_class; full case folding with casefold; search_key, which case-folds, applies NFKD and drops combining marks in one pass. Properties: category, is_letter, is_upper, is_lower, is_digit, is_space, is_punct, is_identifier_start and the other predicates; east_asian_width, display_width and text_width; script. Case mapping: to_upper, to_lower and to_title, and upper and lower with SpecialCasing but without final-sigma or locale rules. Segmentation: UAX #29 graphemes, grapheme_count and grapheme_end. UTF-8 helpers: decode_rune, encode_rune, utf8_valid, utf8_to_valid. Category, width and identifier data are Unicode 16.0.0; script, grapheme break and case data come from 17.0.0 restricted to characters assigned in 16.0.0. The tables are generated by cmd/tablegen and linked only when a function that reads them is reachable. |
std/unicode/utf16, std/unicode/utf32 | Encoding and decoding of code points, []u16 and []u32, and byte forms in either order with BOM handling, strict or lossy, with surrogate validation. |
std/charset | decode, decode_lossy, encode, encode_replace, canonical (WHATWG labels) and detect_bom for UTF-8, UTF-16, UTF-32, ISO-8859-1, -2 and -15, windows-1250, -1251 and -1252, KOI8-R, IBM437 and IBM850. The CJK encodings are not provided. |
std/html | An HTML tokenizer: a pull Tokenizer returning StartTag, EndTag, Text, Comment, Doctype and End tokens, attribute lookup and unescape for character references. |
std/math | libm's trigonometric, hyperbolic, exponential and rounding functions, pi, tau, e, infinity, nan, is_nan, is_inf, generic abs, min, max and clamp, and integer ipow and gcd. |
std/slices | Queries and transforms: contains, index, clone, concat, reverse, map, filter, fold, any, all, sum, min and max (as optionals), sorted. Sorting: sort and sort_by are unstable and in place, a quicksort with median-of-three pivots that recurses into the smaller side and finishes runs of 16 or fewer with insertion sort. sort_stable and sort_stable_by are a top-down merge sort; sort_by_key is stable. Also reduce, count, find, find_index, first, last, equal, compare, starts_with, ends_with, unique (adjacent duplicates), flat_map, flatten, repeat, lower_bound, binary_search (the first match) and binary_search_by. take, skip, chunks and windows share the source's elements. partition and zip work over Pair[A, B]. fill, swap, rotate, insert and remove are in place. Slices are not named types, so these are called with a pipe: xs |> slices.sort(). |
std/maps | keys, values, sorted_keys, entries, from_pairs, clone, merge (the right map wins), filter, map_values, has, get_or, invert, count_by and group_by. |
std/os | Process state: args and environment (from the argument and environment vectors the program started with), env as str?, umask (sets the creation mask and returns the previous one), pid and exit. Queries: getcwd, chdir, hostname, uid, gid, euid, egid, ppid, executable, uptime, cpu_count, and lookup_user and user_name from /etc/passwd. set_env and unset_env are seen by env, environment, process.find and the environment process.run passes on. Directories: home_dir, cache_dir, config_dir, data_dir and state_dir (XDG variables when absolute, otherwise under $HOME), and temp_dir_path. |
std/os/signal | Signal (Hangup, Interrupt, Quit, Abort, Kill, User1, User2, Pipe, Alarm, Terminate, Child, Continue, Stop, TerminalStop, WindowChange) with number, name, from_number and catchable. notify returns a droppable Watch (copyable WatchHandle) whose signals channel delivers the caught signals, with wait_for, wait_timeout, wait_any and stop. Also ignore, reset, send and raise. Kill and Stop cannot be caught and fail with Invalid. |
std/process | Command with arguments, an optional replacement environment, a working directory, Inherit, Piped or Null for each standard stream, and an optional new process group. start returns a droppable Child that kills and reaps an unwaited process and closes its pipes when released. start_handle, adopt, wait, kill, and wait_on and kill_on on the shared ChildHandle. run feeds input and collects both outputs. find searches PATH. success. |
std/cdp | The Chrome DevTools Protocol. launch starts a headless Chromium with a disposable profile, connects to it and returns a droppable Browser that shuts it down when released. Its handle is the shared *BrowserHandle; launch_handle, adopt, shutdown_on and open_page_on take it. call sends a command to the browser or a session, and events delivers everything else. open_page opens a page in its own browser context whose every request, including those of cross-site frames and workers, passes through Handlers. Also navigate and shutdown. |
std/path | Slash-separated path manipulation: clean (lexical, resolving . and ..), join, base, dir, ext, stem and is_absolute. matches matches shell globs with *, ?, [...] classes (ranges, ! or ^ negation) and \ escapes; no wildcard crosses a /. |
std/sync | Mutex with lock, try_lock, unlock and locked. WaitGroup with add, done and wait. Once with run. RwLock, first in first out and writer-fair, with read_lock, read_unlock, write_lock, write_unlock, try_read_lock, try_write_lock, reading and writing. Semaphore with acquire, try_acquire, release and available. Cond with wait_cond, signal and broadcast. Barrier with wait_barrier. OnceValue[T]. ErrorGroup[E], whose go blocks while limit tasks run and whose join returns the first error. All are built on channels, so a waiting green thread parks instead of spinning. |
std/retry | Policy with attempts, base, multiplier, maximum delay, Jitter (None, Full, Equal, Decorrelated), a deadline, a seeded Rng and a cancel token. delay; a loop driver start with next and at_least; run over a Step (Done, Retry, RetryAfter, Fatal) giving an Outcome. |
std/ratelimit | Bucket (token bucket in exact nanosecond units) with allow, allow_n, reserve, wait and set_rate. Window, a sliding log. Keyed, a bounded per-key set of buckets with idle eviction. All take a clock.Clock. |
std/singleflight | Group[K, V] with do, do_shared, forget and in_flight, which run one call per key while the others wait for its result. Expiring[V], a value refreshed at most once per interval. |
std/atomic | Int, Bool and Flag built on compare-and-swap, with load_int, store_int, add_int, swap_int, compare_and_swap_int and update_int, and the same forms for Bool. Every load is a locked operation, so a loop cannot hoist it. Value[T] swaps a heap pointer under a lock: load_value, store_value, swap_value, update_value, snapshot_value and compare_and_swap_value (compares pointer identity). |
std/rand | A seedable, non-cryptographic xoshiro256** generator: seeded, rng (all 256 bits of state from std/crypto), next, unbiased below and between, float, chance, shuffle and pick. pcg32, pcg64 and chacha (seeded from 32 bytes; chacha_rng seeds from entropy) produce an Rng that every function accepts, and next32 draws 32 bits. Distributions: normal, exponential, gamma, beta, poisson, binomial, geometric, zipf, weighted_pick, cumulative with pick_cumulative, sample and permutation. Use std/crypto for secrets. |
std/uuid | Random v4 and time-ordered v7 UUIDs, format, parse (reports the offset of the first bad character), version, timestamp for v7, equal and nil. |
std/csv | RFC 4180 records with quoted fields, doubled quotes, embedded newlines and CRLF or LF line ends. parse and parse_with a separator fail with the line of an unterminated or bare quote. format, format_with and append_record quote only fields that need it. |
std/dotenv | .env files. parse and read return a map from NAME=value lines. They allow export, blank lines, # comments (inline after whitespace in unquoted values), single quotes taken literally, and double quotes with \n, \t and \r escapes that may span lines. Errors carry the line. |
std/flag | Command-line flags from Specs with help text, booleans and defaults: --name value, --name=value, single-dash forms and --. get, enabled, number, the remaining arguments, and usage. |
std/log | Leveled line logging (debug, info, warn, error) to a descriptor (stderr by default) as level prefix: message, without timestamps so journald and other collectors add their own. with_prefix nests a prefix. A Logger also carries attributes (str_attr, int_attr, float_attr, bool_attr, with_attrs, and the _with level forms), a Format of Text (key=value, quoting what needs it) or Json (one object per line), a Sink (a descriptor, an io.Stream, a line closure or a Record handler), optional RFC 3339 timestamps, and a level from parse_level or the LOG_LEVEL variable. Each record is one write, so lines from green threads do not interleave. |
std/term | is_tty, size and set_size. enter_raw returns a droppable Raw that restores the terminal when released. Key, read_key (a lone escape resolves after 50 ms) and parse_keys. ANSI helpers: fg, bg with 16, 256 and RGB colours, bold, dim, underline, cursor movement, clear_screen, the alternate screen, strip and visible_width. colour_enabled honours NO_COLOR, CLICOLOR_FORCE and TERM=dumb. open_pty. |
std/mime | Media types by file extension and back (by_extension, extension) for web, image, font, archive, audio, video and subtitle formats. sniff recognises content by its magic bytes or its leading text and falls back to plain text or application/octet-stream. |
std/semver | Semantic Versioning 2.0.0: parse (with an optional v, failing at the offset of the first bad part), format, and compare and less with prerelease precedence, ignoring build metadata. |
std/container/heap | A binary Heap[T] ordered by a less function: insert, pop, peek and size. |
std/container/lru | A least-recently-used Cache[K, V] of fixed capacity: get (refreshes the entry), put (returns the evicted key), contains, size and keys from most to least recent. All run in constant time over index-linked entries. |
std/container/deque | A ring-buffer Deque[T]: push_front, push_back, pop_front, pop_back, front, back, at and size, doubling when full. |
std/container/set | Set[T] over a map, in insertion order: set, from_slice, add and remove (both return whether the set changed), has, size, items, union, intersection, difference and is_subset. |
std/container/ordered | An AVL Tree[K, V] for ordered keys: tree, put, get, remove, contains, size, height, is_valid, first, last, floor_entry, ceiling_entry, each, each_range, keys, values, entries and the half-open range(lo, hi). |
std/container/sorted | Sorted[T], an ordered set over ordered.Tree: sorted, from_slice, add, remove, has, size, items, first, last, floor_item, ceiling_item and range. |
std/archive | The filesystem layer shared by std/archive/tar and std/archive/zip. Names are cleaned and rejected when absolute, containing .. or NUL, or passing through a symbolic link below the destination. Files are created exclusively without following links. |
std/archive/tar | ustar, GNU and pax archives. A streaming Reader (next, read_body, read_entry, list) with limits on header, entry and total size. A Writer (add_file, add_dir, add_symlink, add_hardlink, finish) that uses pax records for long or non-ASCII names. gzip through read_gzip and write_gzip. extract, extract_gzip, create and create_gzip over the filesystem strip setuid, setgid and sticky bits. |
std/archive/cpio | newc, CRC and odc archives, detected per entry on read: a Reader, a Writer (add_file, add_dir, add_symlink, add_links, finish), and extract and create over the filesystem with the safe extraction of std/archive. Hard links store their data with the last link in newc and CRC. The binary format fails with Unsupported. |
std/archive/zip | Zip archives read through the central directory, with zip64, stored and deflate entries, CRC-32 checks and limits on entries, sizes and compression ratio. Written with add_file, add_dir, add_symlink and finish, which emits zip64 records when a count or size needs them. extract works over the filesystem. Encrypted entries and other methods fail with Unsupported. |
std/testing | T, passed to a test fn(*T), with log, error, fatal, skip, require and sub. Assertions equal, not_equal, equal_slice, is_true, is_false, is_some, is_none, contains, contains_item, close_to, unexpected, must and expect_error render values of any type. table and table_of. run and run_with run each test on its own green thread with a timeout, filter with -run, print with -v and exit with status 1 on failure. bench, bench_for and blackhole. golden rewrites its file when UPDATE_GOLDEN is set. check_property, check_shrunk and check_ints print the seed and shrink integers. |
std/base32 | RFC 4648 base32 with the standard and extended-hex alphabets: encode, encode_unpadded, decode (case-insensitive, padding optional, failing at the first bad character or on an impossible length), encode_hex and decode_hex. |
std/base58 | The Bitcoin alphabet (encode, decode), the Flickr alphabet (encode_flickr, decode_flickr) and Base58Check (encode_check, decode_check), failing at the first bad character. |
std/ascii85 | encode, encode_adobe (with <~ ~>), decode, and Z85 (encode_z85, decode_z85). |
std/msgpack | MessagePack: the Value model with timestamps and extensions, a decoder with depth and length limits that reports the offset of an error, the smallest-form encode, and serialize[T] and deserialize[T]. |
std/bson | BSON documents as []Field with ObjectId, datetime, binary, regex, int32, int64, double and Decimal128 (as bytes): decode, encode, get, diagnostic, new_object_id and parse_object_id. |
std/ini | INI files with sections, = or :, ; and # comments, quoted values, continuations and duplicate keys (last wins, or all with collect): parse, get, get_all, sections, set, format. |
std/properties | Java .properties: parse, get, set, format, with \u escapes and surrogate pairs. |
std/big | Int over 32-bit limbs. Parsing and printing in bases 2 to 36 (printing divides the limbs, packed into 64-bit words, by the largest power of the base below 2^64 with a precomputed reciprocal). add, sub, mul (Karatsuba), divmod, divmod_floor, divmod_euclid, pow, modpow (Montgomery for odd moduli), mod_inverse, gcd, lcm, isqrt. Shifts and bitwise operators with two's complement semantics. is_probable_prime, next_prime, random_below, to_f64, from_bytes and to_bytes. Division by zero is an error. Not constant time. |
std/big/rat | Normalised rationals over big.Int: ratio, parse (a/b, decimals, exponents), the four operations, inv, cmp, to_fixed, to_f64. |
std/big/decimal | A coefficient and an i32 exponent: exact add, sub and mul, and div and rescale with HalfEven, HalfUp, Down, Up, Floor or Ceiling rounding to a target exponent. |
std/redis | RESP2 and RESP3 over TCP or TLS: a droppable Client with a ClientHandle, connect with AUTH, SELECT and HELLO 3, command, typed helpers for strings, hashes, lists, sets, sorted sets and publish, pipelining, transaction, pub/sub through a channel usable in select, command timeouts, and limits on bulk size and nesting. |
std/smtp | An SMTP client: connect, connect_starttls and connect_tls, EHLO extensions, AUTH PLAIN, LOGIN, XOAUTH2 and CRAM-MD5 (plaintext authentication is refused unless insecure_auth), send with per-recipient results, dot-stuffing, pipelining when advertised, and errors separating 4xx from 5xx. |
std/mail | Message building: Message with text and HTML alternatives and attachments, RFC 2047 encoded words, quoted-printable, base64 wrapped at 76, RFC 5322 dates, and rejection of CR and LF in any header. |
std/template | A text template engine over a Data model (to_data[T] through serde): {{ expr }}, if, for, include, block and extends, let, trim markers, filters (built in and registered), HTML autoescaping, depth and output limits, and errors with line and column. A Set is read-only while rendering, so green threads share it. |
std/multipart | multipart parsing and writing (RFC 7578, RFC 2046): a streaming Reader with limits and a spill sink for large parts, RFC 2231 and 5987 parameters, Writer, Form, and request_form for an http.Request. |
std/base64 | encode and decode, and encode_url and decode_url for the URL-safe alphabet without padding (RFC 4648 §5). The URL-safe decoder rejects padding, other alphabets and non-zero trailing bits. |
Resource ownership
Every standard library resource that must be disposed of is a droppable owner bound with using. defer is for work that is not disposal: unlocking a lock, signalling a channel, restoring ambient state and logging.
- An owner keeps the resource's name (
file.File,net.Conn,net.Listener,net.Socket,tls.Session,http.Connection,websocket.Socket,process.Child,cancel.Registration,pipe.Reader,pipe.Writer,sqlite.Database,sql.Connection,cdp.Browser,otel.Sdk) and holds its view in a publichandlefield. Itsdropcloses through the handle. - A view is named
<Owner>Handle:FileHandle,ConnHandle,ListenerHandle,SocketHandle,SessionHandle,ChildHandle,RegistrationHandle,ReaderHandle,WriterHandle,DatabaseHandle,ConnectionHandle,BrowserHandleandSdkHandle.SocketHandlenames the view in bothnetandwebsocket. A view is a copyable struct, or a pointer to the shared state when that state is mutable, so closures capture it, slices, channels, optionals and pointer-held structs store it, andspawntakes it. A view never closes anything on its own. - Operations a caller uses directly take the owner and borrow it:
net.read(c, buf). Operations that run after ownership has moved elsewhere (green threads,io.Streamclosures, pools, callbacks) take the view and end in_on:net.read_on(h, buf),net.stream_on(h),net.close_on(h). A function that returns a view without an owner ends in_handle:net.accept_handle,tls.client_handle,cdp.launch_handle.adopt(h)makes an owner from a view.detach(mut owner)gives up an owner's responsibility so a function that opened a resource and wrapped it can return the wrapper. - Closing is explicit and idempotent from the owner, the view and the stream, and the drop after an explicit close does nothing. The closed state lives in the shared view. Descriptor-based views share an
io.Guard: every operation enters it,retiremarks it closed and wakes blocked operations, and the last operation to leave closes the descriptors. A view used after its owner closed fails withNotConnectedand never reaches a reused descriptor. The SQL drivers fail withsql.Error.Closedand cdp withcdp.Error.Closed. io.Streamis a view whoseclosecloses everything beneath it. Intls.client(net.stream(c), config), closing the session closes the connection, and the connection's own drop does nothing.- A droppable cannot be stored in a pointer, slice, map, channel, optional or enum variant, captured by a closure or passed to
spawn, so long-lived and shared state holds views. The HTTP client's idle connections, its HTTP/2 connections and the reaper's deadlines holdConnHandleandio.Streamviews and close them explicitly with the_onoperations. A green thread that should own a resource receives its view and binds the owner itself:http.serveaccepts withnet.accept_handle, and each spawned connection thread runsusing c = net.adopt(h). Pump threads that only use a resource take its view and leave it to its owner. A scope that opens a resource for a wrapper it returns binds it withusing varand callsdetach, astls.dialdoes. - A
process.Childthat was not waited for is killed and reaped when released. Apipe.Readerorpipe.Writercompletes when released, so a peer never waits on an abandoned end.
Networking
- Sockets are non-blocking. An operation that would block waits with
wait_readableorwait_writable, so a green thread waiting on the network never holds an OS thread the collector must wait for. Every connection holds a duplicate descriptor for its write side, so one green thread can read while another writes. - A timeout spawns a green thread that sleeps and shuts the socket down if the operation is still waiting. The waiting operation then fails with
TimedOut. - A connection counts the reads and writes in progress. Closing it shuts it down, which wakes any green thread still waiting while the descriptor stays registered. The last operation to finish closes the descriptors, so a descriptor number is never reused under a waiting operation. Reads and writes after
closefail withNotConnected, and closing twice does nothing. serveruns each connection on its own green thread.- Cancellation is cooperative. A token runs its callbacks and closes its channel once, so code stops blocking work by closing what it waits on:
net.closewakes a waiting read or write,process.killends a child, andselecttakes<-cancel.done(t). - An HTTP/1.1 handler without an
Upgradeheader runs on the connection's green thread while one spawned watcher reads ahead into the request reader. End of input or a read error cancels the request's token, and the response is still written. Requests read ahead are served in order afterwards. An HTTP/2 stream's token is cancelled when the client resets it or the connection ends. Every request's token is cancelled once its handler returns. - A client request with a token arms its deadline even without a timeout. Cancelling the token fires the deadline, which shuts down the connection the request is using and wakes the request from waiting on a pooled connection or an HTTP/2 stream.
- A server speaks HTTP/1.1 and HTTP/2 on the same port. A connection that opens with the HTTP/2 preface is served as HTTP/2; any other is HTTP/1.1 with keep-alive, pipelining, chunked bodies and
Expect: 100-continue. Over TLS, ALPN offersh2andhttp/1.1and the same detection applies. Theh2cupgrade from HTTP/1.1, deprecated by RFC 9113, is not offered. - HTTP/2 covers framing, HPACK with its dynamic table and Huffman decoding, stream multiplexing, flow control in both directions, SETTINGS, PING, RST_STREAM, GOAWAY and CONTINUATION, and the request validation of RFC 9113 section 8. A reader green thread feeds frames to the connection, each request's handler runs on its own green thread, and the connection selects over frames and finished responses, so every write happens on one green thread. The encoder uses the static table and literals without Huffman coding. It passes h2spec except the test sending a garbage preface, which the shared port reads as an HTTP/1.1 request. A handler's
Response.trailersare sent as a final HEADERS frame over HTTP/2; HTTP/1.1 responses carry none. - A handler that returns status 101 owns the connection: the server writes nothing more and closes it once the handler returns.
http.upgraded()is that response, returned after a WebSocket session. Request.connectionis the buffered reader of an HTTP/1.1 connection.websocket.acceptwrites the handshake to it and reads frames from it. A WebSocket server requires masked client frames, answers pings, reassembles fragments, checks UTF-8 in text messages, limits messages to 16 MB and echoes a close frame.http.client()returns aBuilder[Client]value whosewith_*functions return updated copies.buildmakes a*Clientthat any number of green threads share.c.request(method, url)copies the client's settings into aBuilder[Response], so headers, authentication, timeouts, redirects, retries, version and decompression can be overridden per request. The type parameter only selects whetherbuildorsendapplies.- HTTP/1.1 client connections: a request takes an idle keep-alive connection from a pool keyed by scheme, host and port, dials a new one while the host is under its limit, or queues for one. A sweeper green thread expires idle connections. A pooled connection that fails before any response byte is retried once on a fresh one.
- HTTP/2 client connections: over TLS the client offers
h2andhttp/1.1by ALPN and keeps one HTTP/2 connection per host. A reader green thread decodes frames into per-stream queues, request green threads wait on their stream, flow control credits windows as bodies are consumed, and SETTINGS, PING, RST_STREAM, GOAWAY and the peer's stream limit are honoured.with_prior_knowledge(true)speaks HTTP/2 tohttp://URLs without negotiation (h2c), keeping one connection per host as over TLS. - One reaper green thread per client enforces whole-request deadlines by shutting down an expired HTTP/1.1 exchange. HTTP/2 waits select on the deadline and reset the stream.
- Redirects switch 301, 302 and 303 to GET without a body, keep the method and body on 307 and 308, resolve relative locations and drop
AuthorizationandCookieacross origins. - Responses are decoded from gzip, deflate (zlib or raw), Brotli and Zstandard as they stream, and chunked bodies are read and sent. An optional RFC 6265 cookie jar is shared by the client.
- Retries apply to connection failures and, for idempotent methods, to transport errors and 429, 502, 503 and 504, with exponential backoff that respects
Retry-After. - Servers set
TCP_NODELAYso separate HEADERS and DATA writes are not held back by delayed acknowledgements. Response.trailersholds the trailer fields of chunked HTTP/1.1 bodies and of HTTP/2 responses.- Request and response bodies are limited to 64 MB.
Processes
process.startbuilds the path, arguments, environment and pipes beforefork, so the child runs only straight-line syscalls:setpgidfor a new group,dup2onto descriptors 0 to 2,chdirandexecve. Every descriptor the standard library opens is close-on-exec, so the child inherits only its three streams. A child's pipes are streams over guarded descriptors, so closing one twice or using it after it closed fails withNotConnectedand never reaches a reused descriptor.- A failed
chdirorexecvewrites its errno to a close-on-exec pipe, which the parent reads before returning. The read sees end of file onceexecvesucceeds; otherwise the parent reaps the child and fails with that errno. - The parent's pipe ends are non-blocking and wait through the scheduler, as sockets do; the child's ends stay blocking.
waitwaits for the process's pidfd to become readable, then reaps it withwaitidand remembers the result.killsignals through the pidfd, or the whole group when the command asked for one. signal.notifyinstalls a handler withrt_sigaction. The handler is a short block of machine code in a mapped page: it writes the signal number to a non-blocking pipe and returns throughrt_sigreturn. The runtime gives every OS thread an alternate signal stack, so the handler runs on whichever thread receives the signal. A forwarding green thread reads the pipe withwait_readableand sends to thesignalschannel, which holds 16 and drops repeats while full. Anothernotifyfor the same signal replaces the handler. Dropping aWatchrestores the saved dispositions and unmaps the page.raisesignals the calling thread, so its handler has run whenraisereturns;sendis process-directed and unordered against other threads.watch.nextreads every event an inotify read returns and queues them. Withrecursiveset, new and moved-in directories are watched before the batch that reports them is returned.stopwakes a parkednextby adding and removing a watch on/, which makes the descriptor readable. The kernel merges identical consecutive events it has not yet delivered.
Resilience
retry.delayis the capped exponential backoff andjitteredapplies the chosen jitter to it.nextcalls the observer, waits through the policy's sleeper orsleep, and stops at the attempt limit, the deadline or a cancelled token.- A
Bucketkeeps its balance as an integer in units of one token overpernanoseconds, so refills are exact and a wait is the ceiling of the deficit over the rate.reserveconsumes and returns the wait.waitsleeps that long and refunds if cancelled. Group.doruns the function outside its lock, removes the key and stores the result before waking the waiters. It matches the key by call identity, so aforgetfollowed by a new call is not disturbed.
Text
diff.unifiedmerges hunks whose gap is at most twice the context, omits a count of 1 in a hunk header and writes\ No newline at end of file, as GNUdiff -udoes. The edit script is minimal.number.format_bytesshows one decimal below 10 and rounds half to even on exact integers.parse_bytesreadskandkbas 1000 andkiandkibas 1024, and fails withOutOfRangeon overflow orTooPrecisebeyond 18 fraction digits.sirounds on the exact decimal expansion of thef64.naming.wordssplits at case, acronym and digit boundaries and keeps combining marks attached to their letter, soHTTPServerID2ishttp server id 2.
Time
- Each concept is its own type:
Timestampis a point on the UTC timeline;Date,TimeOfDayandDateTimeare civil values with no zone;Zonedis a timestamp seen through a zone;Durationis exact elapsed time;Spanis a calendar amount. Types never convert silently. - Fields are private and constructors validate, so a
Datecannot hold February 30. Months are 1 to 12, andMonthandWeekdayare enums. Nothing rolls over:date.of(2026, 2, 30)fails withInvalid, and the clamping forms are named (clamped,plus_months). - Calendar arithmetic and elapsed arithmetic are separate. A
Durationmoves aTimestamporZonedby elapsed time. ASpanmoves aDate,DateTimeorZonedby calendar units: a month after January 31 is the last day of February, and a day after a spring-forward midnight is the next civil day although it is 23 hours long.untilandsincetake aDiff, add whole years, then months, to the start without passing the end, then count the rest. - Only
zone.localreads the host zone. A civil time in a daylight saving gap or overlap needs aDisambiguation. In an overlap,CompatibleandEarlierpick the first occurrence andLaterthe second. In a gap,CompatibleandLatermove forward by the gap andEarlierback.Rejectfails withSkippedorAmbiguous.zoned.start_of_dayis the first instant of the civil day, correct where midnight does not exist. - Zones come from TZif versions 1 to 4, using the 64-bit body from version 2, with the footer's POSIX TZ rule applying after the last transition. Before the first transition the first standard-time type applies. The rules cover
Jn, zero-basednandMm.w.ddays and transition times from -167 to 167 hours, so negative daylight saving (Dublin, Casablanca), half-hour shifts (Lord Howe) and skipped days (Apia) work. - Parsing is strict ISO 8601, RFC 3339 and RFC 9557:
T,tor a space separates date and time, a fraction has 1 to 9 digits,:60reads as:59, and a civil type rejects an offset. A written offset that disagrees with a bracketed zone isOffsetConflictunless anOffsetPolicysays which wins. Every parse error isSyntax(at)with the byte offset of the first bad character, or a value error naming the field. - The supported range is 0001-01-01 to 9999-12-31 for a
Timestampand years -9999 to 9999 for aDate. Leap seconds are not modelled. Plain arithmetic panics on overflow; thetry_forms return an optional. - Month and weekday names are English.
pattern.Namesandhumanize.Wordscarry other languages.
Browser automation
cdp.launchfindschromium,chromium-browser,google-chrome-stableorgoogle-chromeonPATHunless given an executable, and creates a profile withfile.temp_dir. It starts the browser headless in its own process group with--remote-debugging-port=0, standard input and output discarded and standard error piped. A green thread reads standard error until theDevTools listening online, which gives the WebSocket address, and keeps draining it so the browser never blocks on a full pipe.shutdowncloses the WebSocket, kills the process group, reaps the browser and removes the profile.- Commands carry an id and, for a session, its
sessionId. A pump green thread routes replies to the waiting call and sends every other message to the events channel. Sends are serialised and a call waits at most 30 seconds. Once the socket closes, every waiting call fails withClosedand the events channel closes. open_pagecreates a browser context that is disposed on detach, denies downloads in it, and turns on auto-attach withwaitForDebuggerOnStartand flat sessions, so every page, frame and worker target pauses on creation. The first page in the context is the opened page; any other page in it, such as a popup, is closed before it runs. Every other target in the context getsFetch.enablefor all URLs,Network.enable, auto-attach for its own children and, for pages,Network.setBypassServiceWorker, and only then resumes, so no request escapes interception. Each paused request is passed toHandlers.requeston its own green thread and continued or failed with its verdict. Responses and failed loads are reported with their URL.- Cancellation is the caller's:
let h = b.handleandcancel.on_cancel(t, fn() { cdp.shutdown_on(h) })end everything the browser was doing.
TLS
- TLS 1.3 (RFC 8446) and TLS 1.2 (RFC 5246), client and server.
Config.min_versionandConfig.max_version, written withtls12()andtls13(), bound the versions and default to 1.2 through 1.3. A client offers its range throughsupported_versions, and a server answers with the highest version both support.Session.handle.versionholds the result. - Downgrade protection: a server that supports 1.3 ends a 1.2 ServerHello random with the RFC 8446 downgrade sentinel; a client that offered 1.3 aborts with
illegal_parameterwhen it sees either sentinel; a server refusesTLS_FALLBACK_SCSVbelow its highest version withinappropriate_fallback. Config.cipher_suiteslists suites in preference order, and a server takes the first of its own list that the client offers.Session.handle.cipher_suiteholds the IANA code andSession.handle.suitethe AEAD and hash.- TLS 1.3 has TLS_AES_128_GCM_SHA256, TLS_CHACHA20_POLY1305_SHA256 and TLS_AES_256_GCM_SHA384. TLS 1.2 has ECDHE with ECDSA or RSA authentication and AES-128-GCM with SHA-256, ChaCha20-Poly1305 with SHA-256 or AES-256-GCM with SHA-384, AEAD only: GCM records carry the 64-bit sequence number as their explicit nonce, and ChaCha20-Poly1305 records use the RFC 7905 nonce.
- TLS 1.3 key exchange offers the hybrid post-quantum group X25519MLKEM768 first, then X25519, P-256 and P-384. A client sends key shares for X25519MLKEM768 and X25519. A server picks the first group of its own order that the client supports, answering with a HelloRetryRequest when the client sent no share for it, so a client that supports X25519MLKEM768 always gets it. TLS 1.2 uses the first of X25519, P-256 and P-384 in the server's order that the client lists, and a server with an ECDSA certificate also requires the client to list the certificate's curve (RFC 8422).
- Servers sign with ECDSA P-256 or P-384, RSA-PSS, RSA PKCS#1 v1.5 in TLS 1.2, or Ed25519, with keys loaded from PEM (
load_certificates,load_key). TLS 1.2 ECDSA signature schemes name only the hash, so either curve signs with SHA-256 or SHA-384. Clients verify the chain againstConfig.roots, or the system roots when that is empty, and check the host name against the certificate's subject alternative names. They verify CertificateVerify or ServerKeyExchange with any offered scheme the certificate allows and, in TLS 1.2, the suite's authentication. - TLS 1.2 requires the extended master secret (RFC 7627) on both sides. A client requires the secure renegotiation indication (RFC 5746), a server echoes it when the client sends it, and both refuse renegotiation with a
no_renegotiationwarning. - ALPN, SNI, KeyUpdate in TLS 1.3 and
close_notifyare supported. Session tickets are ignored, so there is no resumption or 0-RTT. Servers do not request client certificates; a client answers a CertificateRequest with an empty Certificate. - Records hold at most 2^14 bytes of plaintext, and a peer's ciphertext may add 256 bytes in TLS 1.3 or 2048 in TLS 1.2. A record or handshake error sends its fatal alert, such as
bad_record_mac,record_overflow,unexpected_messageordecode_error, and leaves the session unusable. - A session's read and write sides are independent, with a write lock, so different green threads can read and write it.
Derived serialization
std/serde defines a Writer and a Reader, structs of closures through which values are written and read. For every concrete type the compiler derives a function that writes a value to a Writer, a function that reads it from a Reader, and a Schema describing it:
- Booleans, integers, floats and strings map to their primitives;
[]u8to binary; slices to sequences; maps to maps with keys written as text; optionals to null or the value; pointers to their target. - A struct is a map from field names to values, and every field takes part, private ones included. Reading skips unknown keys, uses a field's default when its key is missing, treats a missing optional field as
none, and fails withMissingotherwise. - An enum variant without fields is its name. One with labelled fields is a single-key map from its name to a map of its fields, and one with positional fields maps its name to a sequence.
- A schema records each type's kind, name, fields with whether they are required, and variants. A struct or enum reached again through a pointer while it is being described becomes a
Refto its name.
std/json, std/orm and std/web are built on these. T.field, where T is a struct type, is a serde.Field[T, F] holding the field's name and index, so a function can take a field of a given struct with a given type.
Data
json.Readertokenizes UTF-8 bytes like .NET'sUtf8JsonReader, strictly per RFC 8259, with a depth limit of 64. It returns strings without copying unless they contain escapes. Numbers are parsed as integers or correctly rounded floats.json.serialize_withandjson.deserialize_withtakeOptionsfor indentation, naming (Unchanged,CamelCase,SnakeCase,PascalCase), maximum depth andomit_none. Naming applies to field names and to variant names in both directions; a variant name read back is matched in PascalCase. Withomit_none, a field whose value isnoneis left out instead of written asnull. Binary data is base64; non-finite floats are written asnull.std/cbordecodes RFC 8949 items intoValues: every major type, indefinite-length strings, arrays and maps, tags, simple values, and half, single and double floats, which becomef64. Indefinite-length items arrive as their definite equivalents. Text must be valid UTF-8 and map keys must be distinct. These fail withMalformed: truncated input, reserved additional information, a stray break, indefinite integers or tags, mixed or nested string chunks, a two-byte simple value below 32, data after the item, and a declared length that exceeds the remaining input (checked before anything is allocated). Nesting deeper thanOptions.max_depth, or a string, array or map longer thanmax_length, fails withTooLarge.decode_firstreturns the first item and its length so a caller can continue after it.encodewrites the deterministic encoding of §4.2.1: shortest heads, definite lengths, map entries sorted by the bytes of their encoded keys, and floats in the shortest of half, single or double that keeps the value, with NaN asf97e00.diagnosticwrites the notation of §8.serializeanddeserializebind types through serde with[]u8as byte strings, structs and variants as maps with text keys, andnoneas null; reading looks through tags and accepts integer map keys as their decimal text.std/webauthnproduces options JSON in the shape py_webauthn'soptions_to_jsonwrites, with base64url challenges, user ids and credential ids,pubKeyCredParamsdefaulting to EdDSA, ES256 and RS256, and attestationnone.verify_registrationtakes the credential JSON a browser'sPublicKeyCredentialgives in base64url, with or without padding. It checks thatidis the base64url ofrawId, thattypeispublic-key, that clientDataJSON has typewebauthn.create, the expected challenge (compared in constant time) and the origin. It then decodes the attestation object and checks the RP ID hash, user presence, user verification when required, and attested credential data. It parses the COSE key, accepts only thenoneformat with an empty statement, and rejects a backup state without backup eligibility. It returns the credential id, the COSE key bytes exactly as the authenticator wrote them, and the sign count.verify_authenticationmakes the same client data and authenticator data checks forwebauthn.get. It rejects a sign count that is not greater than the stored one unless both are zero. It verifies the signature over authenticatorData followed by SHA-256 of clientDataJSON with the stored key: ES256 as DER ECDSA on P-256, EdDSA as Ed25519 and RS256 as PKCS#1 v1.5 with SHA-256.- Each failure is its own
Errorvariant.
std/ormbuilds queries from conditions over field references, such asorm.filter(orm.from(users), orm.ge(User.age, 18)), and type-checks them against the field. It renders them for Postgres or SQL Server, maps rows onto structs, stores nested values as JSON columns, creates tables from types with an identity key namedid, and returns generated keys from inserts.sql.Valueholds dates as days since 1970-01-01, times as microseconds since midnight, timestamps as microseconds since 1970-01-01 UTC, infinite dates and timestamps as thei64maximum and minimum, and UUIDs as 16 bytes. A connection serves one green thread at a time; a call made while another is running fails withBusy.orm.transactionrolls back on any error from its body and fails with that error.std/sql/postgresauthenticates with SCRAM-SHA-256, MD5 or cleartext. It uses the simple protocol for statements without parameters and the extended protocol with a 64-entry prepared statement cache otherwise, streamseachin batches of 512 rows, reads results as text decoded by type OID, and keeps a connection usable after a server error. A timeout sends a CancelRequest and closes the connection.connect_tlsupgrades with SSLRequest andstd/tls.std/sql/sqlserverspeaks TDS 7.4 with SQL authentication.- Prelogin offers no encryption to
connectand full encryption toconnect_tls.connect_tlsruns thestd/tlshandshake inside PRELOGIN packets and unwraps the packets the server keeps sending around TLS records. LOGIN7 announces UTF-8 support. - Statements without parameters go as SQL batches. With parameters they go to
sp_executesqlas@p1..@pNdeclared asbigint,float,bit,decimal(38, s),nvarchar,varbinary,uniqueidentifier,date,time(7),datetime2(7)ordatetimeoffset(7), with NULL sent asnvarchar(4000). Every request carries the transaction descriptor, andbegin,commitandrollbackuse transaction manager requests. - Results decode every fixed, nullable, decimal, money, date and time, GUID, character, binary, long-value, text, image, XML,
sql_variantand user-defined type. GUIDs become RFC 4122 byte order. Single-byte text decodes through its collation's UTF-8 flag or as Windows-1252. Row counts sum the DONE and DONEINPROC counts. eachstreams rows as they arrive, and stopping early sends an ATTENTION and reads until the server acknowledges it. A server error below severity 20 leaves the connection usable. A per-connection watchdog sends an ATTENTION and closes the stream when one read waits longer than the timeout, and the call fails withTimeout.
- Prelogin offers no encryption to
std/tomlparses into ordered tables and applies every rule of TOML 1.0.0, including the restrictions on redefining tables through headers, dotted keys, inline tables and arrays of tables. It agrees with Python'stomllibon the toml-test suite. Errors carry a line and column.encodewrites plain values first and then[table]and[[array]]sections.serializeanddeserializebind types through serde, reading date-times as RFC 3339 text.std/yamlparses YAML 1.2.2 into ordered node trees and agrees with the yaml-test-suite on every case's event stream and JSON equivalent.- A scanner modelled on libyaml tokenizes the whole stream, tracking indentation, implicit keys, JSON-like adjacent values and the YAML 1.2 tab rules, with 32-byte vector scans over plain scalars and
simd.find_byte_strfor comment and line ends. Token text is a view into the source. - A recursive-descent parser turns tokens into
Events with resolved tags, and a composer buildsNodes carrying line, column, tag, anchor and style. - Plain scalars resolve with the core schema.
!!str,!!int,!!float,!!bool,!!nulland!!binaryare checked against their content; other tags stay on the node. Aliases share their anchored node.Options.max_nodesbounds the tree with every alias expanded, failing withTooManyNodes, andmax_depthbounds nesting. Duplicate scalar keys are an error. encodewrites block style, quotes a scalar only when it would read back differently (including YAML 1.1 booleans, numbers and dates), writes multi-line text as literal blocks, and anchors any node reached more than once.serializeanddeserializebind types through serde, with[]u8as!!binary.
- A scanner modelled on libyaml tokenizes the whole stream, tracking indentation, implicit keys, JSON-like adjacent values and the YAML 1.2 tab rules, with 32-byte vector scans over plain scalars and
std/otelkeeps the provider in the green thread's context slot as an immutableContextof the active span, baggage, a suppression flag and the SDK.spawncopies the slot, so a child green thread's spans parent to the spawning span.installandsetup_from_envreturn a droppableSdkthat shuts down when released and put theSdkHandleinto the calling green thread's slot, reaching the green threads it spawns afterwards. Programs install at the top ofmain. Every API call checks the slot first and returns a no-op value without allocating when no SDK is present.- Timestamps and durations come from
time.now_nanosandtime.monotonic. Span and trace ids come from astd/randgenerator behind a lock. Samplers are always on, always off, trace-id ratio on the low 63 bits, and parent-based. - Batch processors for spans and logs queue to a bounded channel with a non-blocking send that counts drops. A worker green thread exports when a batch fills, when the delay passes, and on flush or shutdown.
- Metric instruments aggregate per attribute set, keyed by a canonical encoding of the sorted attributes, in one stream per reader, capped at 2000 series plus an
otel.metric.overflowseries. Readers collect cumulatively or as deltas, periodically or on demand. - Exporters encode OTLP once through a writer that emits protobuf through
std/protobufor the OTLP JSON mapping, and send with the context suppressed. - OTLP/HTTP posts, optionally gzipped, retrying 429, 502, 503 and 504 with jittered exponential backoff and
Retry-After. - OTLP/gRPC makes unary
Exportcalls onopentelemetry.proto.collector.{trace,metrics,logs}.v1over the pooled client's HTTP/2 connection, with h2c prior knowledge forhttp://. The message carries the 5-byte gRPC prefix, optionally gzipped undergrpc-encoding, withte: trailersandgrpc-timeout. The result isgrpc-statusfrom the trailers or, in a trailers-only response, the headers. CANCELLED, DEADLINE_EXCEEDED, ABORTED, OUT_OF_RANGE, UNAVAILABLE and DATA_LOSS are retried. RESOURCE_EXHAUSTED is retried only whengrpc-status-details-bincarries a RetryInfo, whose delay replaces the backoff. setup_from_envreads the standardOTEL_*variables.OTEL_EXPORTER_OTLP_PROTOCOL=grpcselects gRPC, defaulting tohttp://localhost:4317.
std/httpsits belowstd/otelin the import graph, so the hook runs through the context slot.otel.Contextdeclares anhttp.Ambientas its first field, andstd/httpreads the slot as*http.Ambient, which relies on struct fields being laid out in declaration order.installsets the ambientObserverandsuppressedclears it;std/httpdoes nothing when it is absent.http.serveandserve_tlsopen a server span per request over HTTP/1.1 and HTTP/2, with the parent extracted fromtraceparentandclient.addressfromRequest.remote, and recordhttp.server.request.duration.std/webadopts that span, addshttp.routeand renames it to the method and route; it opens its own span only when its handler runs outsidehttp.serve.- The client opens a CLIENT span named after the method for each attempt sent, redirects and retries included. Each span is under the caller's span, with
http.request.resend_countfrom the second attempt. The client injectstraceparent,tracestateandbaggageinto that attempt, setsurl.fullwithout userinfo, and ends the span when the body is delivered or the attempt fails, witherror.typethe status from 400 or thehttp.Errorvariant. It recordshttp.client.request.duration. std/sql/postgresandstd/sql/sqlserverwrap their connections withinstrument_sql.std/ormopens client spans with the operation and table; a nested database span merges into the outer one, so an ORM query produces one span.
std/protobufwrites and reads the protobuf wire format without code generation. AnEncoderappends into a buffer that doubles as needed. Signed integers sign-extend to ten bytes andsint64zigzag-encodes.begin_messagereturns a mark andend_messagemeasures the body, shifts it right by the size of its length varint and writes the length, so nested messages need neither a second buffer nor padded lengths. Output matchesprotoc --encodebyte for byte. ADecoderwalks fields in order as number, wire type, integer value and a view of the payload. It rejects truncated or overlong varints, lengths past the end, field 0 and wire types 6 and 7 withMalformed, and groups withUnsupported. Theas_*readers check the wire type and theunpack_*readers accept packed and single encodings.std/xmlreads XML 1.0 (fifth edition) with Namespaces from UTF-8, UTF-16 with a byte order mark, ISO-8859-1 or US-ASCII, converting to UTF-8 and normalising line endings first.xml.Readeris a pull reader:nextreturns one token andpositionits line and column. Names arrive with namespaces resolved and are interned in a per-reader table. Text, CDATA, comments and attribute values are views into the input unless a reference or normalisation forces a copy, and 32-byte vector scans find the bytes that end them. The reader enforces well-formedness and the namespace constraints and agrees with libxml2 on what it accepts.- The internal subset is parsed. General entities expand, including markup, with recursion detection, a nesting limit of 40 and a total of 1 MiB plus eight times the input. Attribute-list declarations supply defaults and normalise tokenised types. External entities are never fetched and parameter entities are not expanded.
xml.parsebuilds anElementtree of owned strings withattribute,child,children,textandfind.xml.Writerescapes text and attributes, splits CDATA around]]>, writes namespace declarations and indents element-only content.serialize_valueanddeserializebind types through serde, mapping fields to attributes or child elements by local name, repeated elements to slices, andxsi:niltonone.
- Pipes block through channels. A writer flushing more than the pause threshold waits until the reader brings the unconsumed bytes below the resume threshold, or until the reader itself waits for more data, so a message larger than the thresholds cannot deadlock the pipe.
pool.openstoresConnectionHandleviews, so one connection serves a lease at a time and the pool, not the owner, closes it. Idle and lifetime limits are checked on acquire, release andpruneagainstclock.monotonic, and a release hands the connection to the oldest waiter. A lease marks its connection broken onConnect,Authentication,Closed,TimeoutorProtocolerrors, and the pool closes it. A transaction left open at release is rolled back.migrate.uprefuses any applied migration whose checksum differs (Drift), a pending version below the highest applied one (OutOfOrder) and duplicate or non-ascending versions. The lock isBEGIN IMMEDIATEon SQLite,pg_advisory_lockon PostgreSQL andsp_getapplockon SQL Server, and each migration re-checks inside its transaction that it is not yet recorded. In a text migration a statement ends at a line ending in;, and-- +beginto-- +endkeeps a block with several;as one statement.
Unicode
std/unicodereads tables generated bycmd/tablegen unicodefrom UnicodeData.txt, CaseFolding.txt and DerivedNormalizationProps.txt of Unicode 16.0.0, the version Python'sunicodedatareports, and agrees with it on every code point.- The tables are
embedded binary files. A two-level trie of 64-entry blocks covers code points below U+2FA40 and gives 0 above. It maps each code point to a 16-bit record id. Each record holds the canonical combining class and 16-bit offsets and lengths into a pool ofu32code points for the full canonical decomposition, the full compatibility decomposition and the C and F case folding. - Hangul syllables decompose and compose algorithmically. Decomposition is followed by a stable canonical reordering by combining class. Composition binary-searches a sorted table of primary composites, leaving out Full_Composition_Exclusion. ASCII input returns at once, or lowercased by
casefoldandsearch_key. search_key(s)equals Python's''.join(c for c in unicodedata.normalize('NFKD', s.casefold()) if not unicodedata.combining(c)). It skips reordering, since every reordered character is dropped.
HTML
std/htmltokenizes UTF-8 HTML following the WHATWG tokenization states. It builds no tree and never fails. Tag and attribute names are lowercased in ASCII, attribute values may be double-quoted, single-quoted or unquoted, a repeated attribute keeps its first value, and a tag cut off by the end of input is dropped.- A start tag for
script,style,xmp,iframe,noembedornoframesswitches to raw text, and one fortitleortextareato escapable raw text, until the matching end tag in any case.plaintexttakes the rest of the input. The script-data double-escape states are not implemented, andnoscriptis tokenized as when scripting is disabled. - Comments end at
-->or--!>, with<!-->and<!--->empty.<?...>,<!...>other than comments and doctypes,<![CDATA[...]]>and</followed by a non-letter become comments, and</>is skipped.Doctypecarries the lowercased name and the optional public and system identifiers. - Character references are decoded in text, escapable raw text and attribute values. Named references match the longest name against the full WHATWG table of 2,231 names, generated by
cmd/tablegen entitiesandembedded, including the names valid without a semicolon. Decimal and hexadecimal references work with or without a semicolon. Zero, surrogates and values above U+10FFFF become U+FFFD, and 0x80 to 0x9F map through Windows-1252. Inside an attribute, a match without a semicolon that is followed by=or a letter or digit stays literal. Text without references is a view into the input. - The tokens match Python's
html.parserexcept where it departs from WHATWG: duplicate attributes, processing instructions and CDATA as comments, raw text after<script/>, and control-character references.
Regular expressions
std/regexcompiles a pattern once into a program for a Pike VM, a Thompson NFA simulation that carries capture slots per thread, so matching takes time linear in the input times the program size and never backtracks.- A
Regexkeeps two pools of idle machines: one without capture slots foris_match, one with them forfind,full_matchand the scans. Each machine owns its thread queues, capture slots and scratch. A call takes an idle machine under a lock, builds one when none is idle, and puts it back when it finishes. A compiled value is therefore shared freely between green threads, and a callback that matches with the sameRegexduringreplace_allgets its own machine. AMatchcopies its slots out of the machine. - Syntax: literals; escapes
\n \t \r \f \v \a,\xhh,\uhhhh,\Uhhhhhhhhand escaped punctuation;.; classes with ranges, negation and\d \w \s \D \W \Sinside;\d \w \s \D \W \S \b \B \A \Z \z;^and$; capturing groups,(?:...), inline flags(?i),(?m),(?s),(?-i)and scoped(?i:...); alternation;*,+,?,{m},{m,},{,n}and{m,n}with lazy forms. A{that does not form a valid count is a literal. Inline flags apply to the rest of the enclosing group. - Input is UTF-8 matched by code point; offsets are bytes.
\d,\w,\s,\band case folding are ASCII..excludes only\nunlessdot_allis set. Withoutmultiline,$matches at the end or before a final\n; with it,^and$match at every line boundary. - Matching is leftmost-first, as in Python and RE2, and results agree with Python's
reunderre.ASCII.find_all,replace_allandsplitfollow Python 3.7: an empty match is allowed right after a non-empty one, and after an empty match the next one may start at the same offset only if it is not empty.splitdoes not include group text.split_nsplits at mostmaxtimes; a negativemaxsplits everywhere. - Repeat counts are limited to 10000 and programs to 100,000 instructions. Invalid patterns fail with
Invalid(at, message), at the byte offset Python reports. Backreferences, lookaround, named groups and possessive quantifiers are rejected. regex.generated("pattern")is aRegexbuilt at compile time, like .NET's[GeneratedRegex]. The pattern must be a string literal; flags are written inline. An invalid pattern is a compile error at the literal,invalid regex at byte N: message, with the offset and messagecompilewould fail with. The result is used through the same functions as a compiledRegexand matches identically.internal/regexholds a Go copy of the parser and assembler, held to the Low one by running thestd_regex_errorsfixture's patterns through it. The checker turns each distinct literal into Low functions named__regex_and the FNV-1a hash of the pattern, parsed with the prelude's privileges and added tostd/regex, so they reach its private types.- A
Regexcarries anEngineof thread-start, step and skip functions with the queue size.compilefills it with the Pike VM. The generated engine keeps the VM's queues, priorities and capture slots but replaces interpretation with code per instruction:- One function per instruction that starts a thread, follows a consumed character or joins two epsilon paths, each guarded by the queue's sparse set. The remaining jumps, splits, saves and assertions are inlined into it.
- Characters and classes of up to four ranges compare inline in the step, which dispatches on the program counter by binary search. Larger classes get a binary-search function.
- When no empty match is possible from the start, a skip function moves past ASCII bytes that cannot begin a match before a thread starts.
- Programs over 2000 instructions are compiled at run time by
compileinstead, so call depth stays bounded.
Compression
- DEFLATE, zlib and gzip decode stored, fixed and dynamic blocks with two-level lookup tables, check Adler-32, CRC-32, ISIZE and the gzip header CRC, and read concatenated gzip members. The encoder uses greedy matching at levels 1 to 3 and lazy matching at 4 to 9 over a hash chain on a 32 KB window, choosing dynamic, fixed or stored encoding per block.
flushemits a sync flush so streamed output is decodable as it arrives. - xz decodes multiple blocks and streams, the none, CRC32, CRC64 and SHA-256 checks, LZMA2 chunks with their resets, and the delta filter; other filters fail with
Unsupported. The encoder writes LZMA2 with a hash-chain match finder and lazy parsing, a dictionary from 256 KiB to 64 MiB by level, and raw chunks where compression does not pay. std/compress/zstdandstd/compress/lz4each offercompress(data, level),decompress(data, limit), a streamingdecode(reader, sink, limit)that passes output to the sink one block at a time, and a streamingEncoderwithencode,flushandfinish.- The zstd decoder handles every block and literal type, 1- and 4-stream Huffman literals, all four FSE table modes, repeat offsets, skippable and concatenated frames, and the content checksum. Its history grows with real output up to the smaller of the window and the remaining limit, so large windows never allocate what the header claims up front.
- The zstd encoder finds matches with two hash chains keyed on 8-byte and 4- or 5-byte prefixes, with depth and lazy evaluation set by the level. It Huffman-codes literals, picks predefined, RLE or custom FSE tables per block by estimated cost, and falls back to raw or RLE blocks.
- The LZ4 decoder accepts linked and independent blocks, block and content checksums, content sizes and skippable frames. The encoder writes linked 64 KB blocks with a content checksum.
- Dictionaries and LZ4 frames with magic number
0x184C2102fail withUnsupported.
std/compress/brotlihas the same API as zstd and LZ4.- The decoder handles compressed, uncompressed and metadata meta-blocks, block switching for literals, commands and distances, all four literal context modes, context maps with run-length coding and inverse move-to-front, distance postfix and direct parameters, the static dictionary with all 121 transforms, and windows of 10 to 24 bits. Output collects in a ring buffer that starts at 64 KB and doubles up to the window, and reaches the sink at the end of each meta-block, when the ring wraps, and before each blocking read. The 122,784-byte dictionary is
embedded fromdictionary.bin. - The encoder writes uncompressed meta-blocks at level 0. Levels 1 to 11 run hash chains of depth 2^(level-1) with lazy matching from level 4 and checks against the four recent distances and their neighbours, writing 256 KB meta-blocks with Huffman-coded commands and distances. From level 5 they model literals in UTF-8 context mode with up to 3·level-11 clustered trees. A block that would grow is stored.
flushends the meta-block and pads with an empty metadata block so everything sent decodes.
- The decoder handles compressed, uncompressed and metadata meta-blocks, block switching for literals, commands and distances, all four literal context modes, context maps with run-length coding and inverse move-to-front, distance postfix and direct parameters, the static dictionary with all 121 transforms, and windows of 10 to 24 bits. Output collects in a ring buffer that starts at 64 KB and doubles up to the window, and reaches the sink at the end of each meta-block, when the ring wraps, and before each blocking read. The 122,784-byte dictionary is
std/bitsholds a growableSetover[]u64words. Counts use a SWAR popcount, and scans (next_set,next_clear,min,max,rank,select_at,members) step a word at a time.std/bits/roaringholdsRoaring, a set ofu32split into 65536-value chunks keyed by the high 16 bits. Each chunk is a sorted[]u16array of up to 4096 values, a 1024-word bitmap, or a list of runs. Arrays and bitmaps convert at 4096 values; ranges create runs, and unions and intersections of runs stay runs. Every container tracks its cardinality, socardinalityis constant time. Set operations come as new-set and in-place_withforms, working word by word on bitmaps and by galloping merge on arrays.run_optimizepicks the smallest form per container by the Go library's rule.serializeanddeserializeimplement the portable Roaring format byte for byte as Goroaring/v2writes it, rejecting any inconsistent length, ordering or cardinality withMalformed.std/imageholds anImageof width, height,Format(Gray8,GrayAlpha8,Rgb8,Rgba8,Gray16,Rgba16, 16-bit samples big-endian), stride and pixel bytes.- Pixels read and write as 8-bit
Rgba, with operations converting through 16-bit intermediates.getoutside the image is transparent black andsetthere does nothing. Operations convert formats, crop, flip, rotate, apply EXIF orientation, fill rectangles, composite straight alpha, premultiply and unpremultiply, and resize separably on premultiplied values with nearest, bilinear, Catmull-Rom bicubic or Lanczos-3 filters. decodepicks a codec by signature and rejects images over 2^26 pixels;decode_limitedtakes another limit.- PNG decodes every colour type, bit depth and Adam7, checks every CRC, and encodes with per-row adaptive filtering.
- JPEG decodes baseline and progressive scans with restart markers, any sampling, grayscale and Adobe CMYK/YCCK, with libjpeg's integer IDCT and fancy upsampling, so output matches libjpeg byte for byte. It encodes baseline 4:2:0 with the standard tables scaled by quality.
- GIF decodes 87a and 89a and composites every frame by disposal method in
decode_gif_frames. It encodes one frame with a given or median-cut palette. - BMP covers 1 to 32 bits, RLE, bitfields and every header version, and encodes 24 or 32 bits.
- QOI decodes and encodes.
- WebP decodes lossless VP8L with every transform, the colour cache and meta prefix codes. Lossy VP8, alpha chunks and animation fail with
Unsupported.
- Pixels read and write as 8-bit
- Every codec has buffer functions, a streaming decoder that pulls from an
io.Reader, pushes output to a sink and fails withTooLargepast a caller's limit, and a streaming encoder.
Web
web.app()holds routes and middleware.get,post,put,patch,delandrouteadd handlers for paths with:nameparameters and a trailing*.groupmakes a sub-application with a prefix and more middleware, andmountadds its routes back. An unknown path is a 404 and a known path with another method a 405 withAllow.endpoint[Req, Res]andquery_endpoint[Res]read a JSON body intoReq, call a handler returningRes ! web.Problem, and write the result as JSON or the problem asapplication/problem+json. Their schemas describe the operation in the OpenAPI document thatopenapiserves, along with path parameters and each route's security schemes.- Middleware is a struct of a
runclosure and an optional security scheme.api_key,basicandbearerauthenticate requests and setContext.user.sessionskeeps a map in a cookie sealed with AES-256-GCM, with the cookie name as associated data and an expiry inside.csrfrequires the session's token inX-CSRF-Tokenon unsafe methods.require_session,cors,loggerandcompresscomplete the set;compresspicks Zstandard, Brotli or gzip, in that order, from whatAccept-Encodingallows. jwtverifies bearer tokens against a key set withstd/crypto/jose.oidcdoes the same for an OpenID Connect issuer: it reads the discovery document and the JWKS, refreshes them hourly, and refreshes early, at most once a minute, when a token names a key it does not know.oidc_loginadds a sign-in route that redirects to the issuer withstate,nonceand a PKCE S256 challenge kept in the session, and a callback route that checks the state, exchanges the code, verifies the ID token and its nonce, and hands the claims to the application.- A handler streams a body by returning a
Responsewithstreamset to achan[[]u8]and closing it at the end. The server writes each chunk as it arrives, cancelsreq.tokenwhen the stream ends, the client disconnects or a write fails, and drops the stream forHEADand bodiless statuses. Response compression skips streamed responses. sse.streamsetstext/event-stream,no-cacheandx-accel-buffering: no, flushes every event, sends a: keepalivecomment every 15 seconds unlesskeepaliveis 0, and stops whenreq.tokenis cancelled.Emitter.sendreturns false after the client has gone.sse.formatremoves CR and LF fromidandeventand NUL fromid.web.staticdecodes each path segment and answers 400 for.., an embedded separator, NUL or a bad escape, and 404 for dotfiles, non-regular files and any file whose real path leaves the root. A directory without a trailing slash is redirected, and a directory servesindex.htmlor an optional listing.precompressedpicks.brthen.gzbyAccept-Encoding. A multi-range or malformedRangegives the whole file. Files stream in 64 KiB chunks.