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.Processesornet.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"]), andaccess.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.writeand the rest directly. Every other module (and every plugin) is handed anfs.Filespermission, made byfs.files()in the main file, and callsfiles.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 asUntrustedoutanderr) andprocs.spawn(&cmd). A spawnedProcesshaswrite,close_input, andread_line,read,read_allgivingUntrustedtext, and must end withwait()(the exit code) orkill(): it is aFinishtype, so forgetting is a compile error. If atryorreturnleaves early, it is killed.os.utc_offset(t)gives the local zone.access.connect(&host, port)andaccess.listen(&host, port)(port 0 picks one;l.port()tells which) give TCPSockets withwrite,read_line,read_line_max,read,read_exact,read_all,read_all_max,close_write,set_timeout(Some(time.seconds(5)))andpeer. 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 intothread.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 namehost, 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 aTrustcomes fromnet.system_roots()ornet.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 isUntrusted<Str>. OpenSSL is loaded when TLS is first used.access.listen_tls(&host, port, &files, &cert_file, &key_file)makes a server: everyacceptdoes the handshake (with a 10 second limit, so a silent client cannot hold the server) and returns a TLSSocket. 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.postandhttp.sendspeak HTTP/1.1 overhttp://andhttps://with the default client and return anhttp.Reply, whose reason, header values and body areUntrusted.http.client(&access)makes one to adjust withwith_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 (forget, with all its redirects), so a server sending one byte now and then cannot stretch it. A header sent more than once is joined inheaders, and kept apart inheader_values(&name)(forSet-Cookie). Header names and values with line breaks, URLs with spaces or control characters,Host,Content-LengthandTransfer-Encodingset by the caller, and a message with both a length and chunking are refused: no header injection or request smuggling through this API. Servers usehttp.read_request(&mut socket, &http.limits()),http.write_response,http.response(200, body)andhttp.handle(&mut socket, &handler)(orhandle_withand your own limits), which answers bad or oversized requests with 400/413, an invalid response from the handler with 500,HEADwithout the body, and drops idle clients.set_headerreplaces a header in any spelling andadd_headerrepeats one;1xx,204and304answers carry no body. ARequest’s path, query, header values and body areUntrusted.Untrusted<T>(in the prelude) holds data from outside. AnyTcan be wrapped (Untrusted.new(v)) and taken out withchecked(fn(v) => ...)or the visibleunchecked()/into_unchecked().Untrusted<Str>, which the library hands out for request data, replies and program output, has the text checks: it turns into aStrthroughpath_inside(&root)(after %-decoding; None if it would leave root),html_escaped(),as_name()(letters, digits,_-.),only(&allowed_bytes),to_i64(),checked(fn(s) => ...), orunchecked(), which is easy to search for in a review.is(&"/x"),starts_withandlencompare without converting.hash.sha256(&data)andhash.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) andencoding.hex/from_hex.csv.parse(&text)(RFC 4180: quoted fields with commas, doubled quotes and line breaks;parse_withfor another separator; blank lines are skipped) andcsv.text(&rows)(\nline ends;text_with(&rows, sep, &"\r\n")for another separator or Excel’s\r\n).yaml.parse(&text)andtoml.parse(&text)read into ajson.Json, andyaml.text/toml.textwrite one, so the three formats convert into each other.xml.parse(&text)gives anElementtree (attr,child,children_named,text;element,add,set_attr,prettyto build and write), andini.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)andgzip.decompress(&data)(gzip or zlib, via the system’s zlib); decompressing stops with an error past 256 MB, or past the limit given todecompress_limited, so a “zip bomb” cannot fill memory.sqlite.open(&files, &path)(the file permission decides which paths;":memory:"is always allowed) gives aDbwithexec(&sql)for plain SQL,query(&sql, &values)andrun(&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 withtext,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 everyTextvalue for HTML,template.untrusted(&u)turnsUntrustedtext into one, and onlyHtml(...)goes in as written. (Escaping covers text and quoted attributes; a URL inhrefstill needs its own check.)regex.compile(&pattern)gives aRegexwithis_match,find,find_at,find_all,replace(the first match),replace_all($0..$9,${n}) andsplit. 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,\sand\bfollow 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()andto_lower()use Unicode’s full case mappings ("straße".to_upper()is"STRASSE").glob.matches(&"src/**/*.brass", &path)andglob.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.findlists links but never follows them, so a link cannot send it in circles.cli.parser(&name, &about)declaresflag,option(with a default),positional,optionalandrest, thenparse(&os.args())returnsArgsor acli.CliError(Helpwith the help text, orUsageError).-abc,-ofile,--name=valueand--work as usual, negative numbers are arguments,args.given(&name)tells a given option from its default, andargs.all(&name)collects a repeated one.time.now(),time.now_local(),time.from_unix(seconds, offset)andtime.parse_datetime(&"2026-11-26T14:05:09Z")give aDateTimewithformat(&"%Y-%m-%d %H:%M")(strftime codes),unix(),add_secondsandwith_offset;Date.formattoo. ADateis always a real date: its fields are private, read withyear(),month(),day().time.Duration, made withtime.milliseconds(n),time.seconds(n)ortime.minutes(n)ortime.hours(n)(never negative), is what every timeout takes, so units cannot be mixed up; it adds, subtracts, scales (times) and compares (+,-,<), withas_milliseconds()andtime.sleep(&d).time.start()gives aTimerwhoseelapsed()is aDurationfrom 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 orStrkey, andMap.get_or_insert(k, default)returns the value fork, insertingdefaultfirst if needed:*counts.get_or_insert(word, 0) += 1. A compound assignment evaluates its target once, so a call in it runs once.