Skip to content

Standard library

Built-in modules are imported by name (import json). fs, os, io, net, hash, gzip, sqlite and random wrap C (gzip and sqlite link the system’s zlib and SQLite); json, path, time, http, regex, glob, cli, encoding, csv and template are written in Brass, as is the prelude.

  • Starting programs and using the network need a permission: a value of type os.Processes or net.Access. Only the program’s main file can make one (os.processes(), net.access(); anywhere else, and in plugins, the call is a compile error), and it is handed to the code that may use it. A library cannot reach the network or start programs unless its caller gave it the permission, and a caller can narrow it first: procs.only(&["git"]), access.only(&["api.example.com"]), and access.public_only(), which refuses this machine, private networks and link-local addresses (checked on the address actually connected to, so a name cannot be pointed inside later).
  • Files work the same way, except that a script’s main file may call fs.read, fs.write and the rest directly. Every other module (and every plugin) is handed an fs.Files permission, made by fs.files() in the main file, and calls files.read(&path) and so on. files.within(&dir) limits it to one folder: paths are made absolute, and .. and symbolic links are resolved before the check, so neither can lead out. (A link swapped in between the check and the use is not caught; the check guards against mistakes and hostile names, not against another program racing this one.)
  • procs.run(&cmd), procs.run_output(&cmd) (status, and what the program printed as Untrusted out and err) and procs.spawn(&cmd). A spawned Process has write, close_input, and read_line, read, read_all giving Untrusted text, and must end with wait() (the exit code) or kill(): it is a Finish type, so forgetting is a compile error. If a try or return leaves early, it is killed. os.utc_offset(t) gives the local zone.
  • access.connect(&host, port) and access.listen(&host, port) (port 0 picks one; l.port() tells which) give TCP Sockets with write, read_line, read_line_max, read, read_exact, read_all, read_all_max, close_write, set_timeout(Some(time.seconds(5))) and peer. Every read returns ! NetError: a timeout, a broken connection or a TLS failure is an error that must be handled, never an early “end”. Sockets and listeners can be moved into thread.join/thread.each.
  • access.connect_tls(&host, port) speaks TLS 1.2 or later; the certificate must chain to the system’s trusted roots and name host, and there is no switch to turn that off. access.open(&host, port, &net.Options { transport: .Tls(try net.ca_file(&files, &path)), timeout: Some(d) }) trusts only that CA instead. Transport (Plain, Tls(Trust)) is an enum, so contradictory settings cannot be written, and a Trust comes from net.system_roots() or net.ca_file, which needs file permission like every other file read. A timeout below one millisecond counts as one millisecond, never as “no timeout”. What sockets read is Untrusted<Str>. OpenSSL is loaded when TLS is first used. access.listen_tls(&host, port, &files, &cert_file, &key_file) makes a server: every accept does the handshake (with a 10 second limit, so a silent client cannot hold the server) and returns a TLS Socket. With a timeout set, looking up a host name gives up in time too (the lookup runs on its own thread, since it cannot be interrupted).
  • http.get(&access, &url), http.post and http.send speak HTTP/1.1 over http:// and https:// with the default client and return an http.Reply, whose reason, header values and body are Untrusted. http.client(&access) makes one to adjust with with_timeout, with_deadline, with_trust, with_max_body, with_max_redirects (defaults: 30 s per wait, 5 minutes per request, system roots, 64 MB, 5 redirects, never from https to http). The deadline caps the whole request (for get, with all its redirects), so a server sending one byte now and then cannot stretch it. A header sent more than once is joined in headers, and kept apart in header_values(&name) (for Set-Cookie). Header names and values with line breaks, URLs with spaces or control characters, Host, Content-Length and Transfer-Encoding set by the caller, and a message with both a length and chunking are refused: no header injection or request smuggling through this API. Servers use http.read_request(&mut socket, &http.limits()), http.write_response, http.response(200, body) and http.handle(&mut socket, &handler) (or handle_with and your own limits), which answers bad or oversized requests with 400/413, an invalid response from the handler with 500, HEAD without the body, and drops idle clients. set_header replaces a header in any spelling and add_header repeats one; 1xx, 204 and 304 answers carry no body. A Request’s path, query, header values and body are Untrusted.
  • Untrusted<T> (in the prelude) holds data from outside. Any T can be wrapped (Untrusted.new(v)) and taken out with checked(fn(v) => ...) or the visible unchecked() / into_unchecked(). Untrusted<Str>, which the library hands out for request data, replies and program output, has the text checks: it turns into a Str through path_inside(&root) (after %-decoding; None if it would leave root), html_escaped(), as_name() (letters, digits, _-.), only(&allowed_bytes), to_i64(), checked(fn(s) => ...), or unchecked(), which is easy to search for in a review. is(&"/x"), starts_with and len compare without converting.
  • hash.sha256(&data) and hash.hmac_sha256(&key, &data) give lowercase hex; hash.equal_secret(&a, &b) compares in constant time. encoding.base64/from_base64 (standard or URL-safe input) and encoding.hex/from_hex.
  • csv.parse(&text) (RFC 4180: quoted fields with commas, doubled quotes and line breaks; parse_with for another separator; blank lines are skipped) and csv.text(&rows) (\n line ends; text_with(&rows, sep, &"\r\n") for another separator or Excel’s \r\n).
  • yaml.parse(&text) and toml.parse(&text) read into a json.Json, and yaml.text/toml.text write one, so the three formats convert into each other. xml.parse(&text) gives an Element tree (attr, child, children_named, text; element, add, set_attr, pretty to build and write), and ini.parse(&text) sections of text values (get, set, entries, to_str). Duplicate keys are errors in every format, nesting is limited to 256 levels, and the features that let a small file expand without limit or reach outside it are refused: YAML anchors, aliases and tags, and XML DOCTYPEs (so no entity expansion or XXE).
  • gzip.compress(&data) and gzip.decompress(&data) (gzip or zlib, via the system’s zlib); decompressing stops with an error past 256 MB, or past the limit given to decompress_limited, so a “zip bomb” cannot fill memory.
  • sqlite.open(&files, &path) (the file permission decides which paths; ":memory:" is always allowed) gives a Db with exec(&sql) for plain SQL, query(&sql, &values) and run(&sql, &values) for one statement with ? placeholders. Values (.Null, .Int, .Real, .Text, .Blob) are always bound, never pasted into the SQL, and a query holding a second statement is refused, so data cannot become SQL. Rows read with text, int, real, blob, get. db.transaction(&fn(tx) ...) commits when the function succeeds and rolls back when it fails, so a transaction cannot be left open. A locked database is waited for up to 5 seconds (set_busy_timeout).
  • template.compile(&text) understands {{name}}, {{#if name}}..{{else}}.. {{/if}} and {{#each name}}..{{/each}}; render(&values) escapes every Text value for HTML, template.untrusted(&u) turns Untrusted text into one, and only Html(...) goes in as written. (Escaping covers text and quoted attributes; a URL in href still needs its own check.)
  • regex.compile(&pattern) gives a Regex with is_match, find, find_at, find_all, replace (the first match), replace_all ($0..$9, ${n}) and split. Syntax: . [a-z] [^x] \d \w \s (and capitals), ^ $ \b \B, ( ), (?: ), |, * + ? {m} {m,} {m,n} and lazy *? etc., with (?i) at the start for either case. \d, \w, \s and \b follow Unicode (letters and digits of every script). It runs as a Pike VM, so matching time is linear in the text; there are no backreferences.
  • Str.to_upper() and to_lower() use Unicode’s full case mappings ("straße".to_upper() is "STRASSE").
  • glob.matches(&"src/**/*.brass", &path) and glob.find(&files, &pattern): * and ? stay within a name, [a-z]/[!x] match one character, ** spans folders, and names starting with . (files or folders, also under **) need a pattern that names them. find lists links but never follows them, so a link cannot send it in circles.
  • cli.parser(&name, &about) declares flag, option (with a default), positional, optional and rest, then parse(&os.args()) returns Args or a cli.CliError (Help with the help text, or UsageError). -abc, -ofile, --name=value and -- work as usual, negative numbers are arguments, args.given(&name) tells a given option from its default, and args.all(&name) collects a repeated one.
  • time.now(), time.now_local(), time.from_unix(seconds, offset) and time.parse_datetime(&"2026-11-26T14:05:09Z") give a DateTime with format(&"%Y-%m-%d %H:%M") (strftime codes), unix(), add_seconds and with_offset; Date.format too. A Date is always a real date: its fields are private, read with year(), month(), day().
  • time.Duration, made with time.milliseconds(n), time.seconds(n) or time.minutes(n) or time.hours(n) (never negative), is what every timeout takes, so units cannot be mixed up; it adds, subtracts, scales (times) and compares (+, -, <), with as_milliseconds() and time.sleep(&d). time.start() gives a Timer whose elapsed() is a Duration from a clock that only moves forward.
  • Option.unwrap_or(default) gives the value or the default. Vec.sort_by_key(fn(x) => key) sorts stably by a number or Str key, and Map.get_or_insert(k, default) returns the value for k, inserting default first if needed: *counts.get_or_insert(word, 0) += 1. A compound assignment evaluates its target once, so a call in it runs once.