Files
std/README.md
T
2026-12-06 13:12:06 -06:00

16 KiB

std

The Sakura programming language's standard library: what programs build on beyond core, which ships with the compiler, sakurac, and system, the layer beneath std that talks to the operating system, a package of its own that std requires. Each module is a library of its own, in the folder of its name, which reads core and the modules it lists, system among them:

Module Folder Holds
std::containers containers/ dict, hashset, deque, list, chain, heap, queue, stack, groups, runs, and interner, beside core's vector; and rc and arc, owners shared by every copy, beside core's box
std::allocators allocators/ arena and pool
std::io io/ The console, files, directories, paths, and pipes; the streams' traits, readable, writable, and flushable, and the streams reader, writer, and byte_writer; and globs, as std::io::glob, in io/glob/
std::process process/ Running other programs
std::thread thread/ Threads, and what guards what they share: mutexes, conditions, channels, and once
std::time time/ Lengths of time, the clocks, the calendar, time zones, and RFC 3339 text
std::math math/ The functions of real numbers and their constants, and the operations of integers the operators don't give
std::serial serial/ Writing and reading typed values by their @serial marks, in any format
std::testing testing/ Tests found by reflection
std::text text/ Regular expressions
std::net net/ URIs, and the file URIs of paths
std::semver semver/ Semantic versions
std::json json/ JSON, read and written strictly, as RFC 8259 writes it
std::yaml yaml/ YAML 1.2.2, read and written by its core schema
std::xml xml/ XML 1.0, read strictly, with its namespaces and its document type's internal subset
std::args args/ A program's arguments, read into a struct by its marks, and the help they write

std is built on core and system alone, declares no intrinsic, and holds nothing the compiler names, so it changes as a library does, versioned apart from the compiler and from system.

Using it

Require it in your blossomfile, and name among a target's deps the modules it reads:

requires:
- https://git.malunal.studio/sakura/std@v1.0.0

targets:
- name: app
  type: program
  deps: [std.io, std.time]

blossom gives each with --lib, as --lib std::io=DIR. A program built without blossom reads the standard library the compiler finds:

  • the folder --lib std=DIR names, as this repository checked out;
  • or else a std folder beside the sakurac executable or in the nearest folder above it, as a copy of this repository;
  • or else its libraries in the share/sakura folder nearest above the executable, as share/sakura/std.io for std::io, where blossom install puts them.

blossom reads system with std, since std requires it. Without blossom, sakurac finds it as it finds std: by --lib system=DIR, beside or above the executable, or in share/sakura.

Installed with blossom install --prefix ~/.local, it's found by a sakurac in ~/.local/bin.

There is no module std itself: a file imports the modules it uses.

The modules

Files: std::io takes paths, and gives what can fail inside a result with an io_error:

val dir := path::parse("build") else (_) { return; };
io::create_directories(dir) else (e) { println($"cannot make it: {e}"); return; };
val notes := dir.join("notes.txt");
io::write_file(notes, "first\n") else (e) { return; };
val text := io::read_file(notes) else (e) { return; };
var listing := io::directory::open(dir) else (_) { return; };
for entry in listing { println($"{entry.name} {entry.kind}"); }   # notes.txt regular

On Windows, paths are UTF-8 to the program, as arguments and variables are, and UTF-16 to the system. Windows keeps only whether a file is read only, so setting permissions looks only at whether the owner may write, and they read as everyone reading the file, writing it unless it is read only, and running it where it is a directory or its name ends in .exe, .com, .bat, or .cmd.

Streams: anything bytes are read from is readable, and anything they're written to is writable, so one function serves files, the console, and strings. A string is writable, and a strview readable, where a file imports std::io, which declares their write and read. io::reader_of and io::writer_of buffer any stream, byte_writer writes to memory, laying words out one after another as a binary format wants them, and io::read_line() reads the standard input.

Programs:

var git := process::command::new("git");
git.arguments(["rev-parse", "HEAD"]);
val head := git.capture() else (e) { return; };   # head.output, head.error, head.status

A name without a / is looked for in the PATH the child will have. On Windows, a \ or a drive, as C:, also makes a name a path, PATH is split at ;, a name ending in none of the endings PATHEXT lists is tried with each of them, and variables are the same whatever their case, as Path is PATH. A batch file is run by cmd.exe, which can't be given an argument holding a ", a %, or a new line unchanged, so one with such an argument fails with invalid rather than start.

Typed values are written and read by their marks:

@serial struct position { @serial var line: u32; @serial{ name = "char" } var column: u32; }

val text := json::to_text(&position{ line = 3, column = 7 }) else (_) { return; };   # {"line":3,"char":7}
val back := json::from_text::<position>(text.span) else (e) { return; };

Arguments are read into a struct the program marks, whose marks also write the help text, by std::args, whose README says what it reads and how:

@command{ name = "greet", help = "Greets people.", version = "1.0" }
struct greet {
  @option{ short = 'n', value = "N", help = "How many times." } var times: u32 = 1;
  @option{ short = 'l', help = "Says it loudly." }             var loud: bool;
  @argument{ value = "NAME", help = "Whom to greet." }          var names: vector<strview>;
}

def main(args: span<strview>): void {
  val given := args::parse_or_exit::<greet>(args);   # greet -l -n2 Ann Bo, or greet --help
  for &name in given.names {
    for _ in 0..given.times { println(given.loud ? $"HELLO, {name}!" : $"Hello, {name}!"); }
  }
}

Time: std::time has lengths of time, moments of two clocks, and the calendar in any zone:

import std::time;

val began := instant::now();                               # the steady clock, for measuring
build();
println($"built in {began.elapsed().describe()}");         # built in 2.31s

val now := timestamp::now();                               # the wall clock, in UTC
println(now.rfc3339());                                    # 2026-10-07T12:42:03.451Z
println(now.at(zone::local()).rfc3339());                  # 2026-10-07T07:42:03.451-05:00

val due := date::of(2026, month::october, 31) else (e) { return; };
println(due.plus_months(1).iso());                         # 2026-11-30
  • Arithmetic is operators. Durations add, subtract, and negate, scale by a count, and divide into a ratio: seconds(90) + milliseconds(500), timeout * 2, done / total. A moment moves by a duration, and one less another is the duration between them: deadline - instant::now().
  • Durations are made by nanoseconds, microseconds, milliseconds, seconds, minutes, and hours, and read by in_nanoseconds and in_seconds.
  • The range: moments and durations count nanoseconds in an i64, so a timestamp reaches from 1677 to 2262. Arithmetic past that stops a checked program, as indexing past an end does.
  • Two clocks: an instant never goes back, and means nothing but against another. A timestamp says when, and the system may set its clock back.
  • The calendar is the Gregorian one, without leap seconds. date has weekday, day_of_year, plus_days, plus_months, days_since, and iso.
  • Zones: zone::utc(), zone::fixed(offset), zone::named("Asia/Tokyo") from the system's database, and zone::local(). Windows keeps no database, so there zone::named reads the directory TZDIR names, and finds no zone without it, and zone::local() is the rule the system's setting keeps the clocks by now, which says nothing of the years before that rule. timestamp::at gives the date_time a zone's clocks show, and zone::resolve the moment they show a date and time: one they skip is taken that long after the change, and one they show twice at its first.
  • Text: rfc3339 writes a moment, and parse_rfc3339 and parse_date read one, giving a time::error for text that is none.
  • Waiting: time::sleep(milliseconds(50)). A signal the program handles ends the wait, as it ends every wait.

Math: std::math has the functions of real numbers, for f32 and f64 alike, and the operations of integers that the operators don't give:

import std::math;

val length := math::sqrt(x * x + y * y);              # an f64, as x and y are
val angle: f32 = math::atan2(dy, dx);                  # an f32, as dy and dx are
val half := math::sin(math::pi / 6);                   # 0.49999999999999994, not 0.5
val wrapped := math::div_floor(-7, 2);                 # -4, where -7 / 2 is -3
val sum := math::checked_add(a, b) else { return; };   # nothing where it overflows
  • Functions of any T that is real: sqrt, cbrt, hypot, exp, exp2, expm1, log, log2, log10, log1p, pow, sin, cos, tan, asin, acos, atan, atan2, sinh, cosh, tanh, asinh, acosh, and atanh, all in radians.
  • Exact operations: floor, ceil, trunc, round, which takes halves away from zero, round_even, copysign, and fma, which rounds once. abs, min, max, and clamp take any ordered type, as integers and durations. Of reals, min and max give NaN where either is NaN, and put -0 below 0.
  • The same bits everywhere: the functions are std's own Sakura, ported from musl, so they give the same results in the VM, in executables, and in constants. sqrt is the machine's, correctly rounded. Results are within an ulp of the true value, but for atan2, sinh, tanh, asinh, acosh, and atanh, which are within 2, as musl's are. An f32 is worked in f64 and rounded, which is almost always the nearest f32.
  • Nothing stops the program: a result outside a function's domain is NaN, and one too large is infinity, as IEEE 754 says.
  • Constants: pi, tau, e, sqrt_2, ln_2, and ln_10 are f64s, which as f32 rounds for floats. largest, smallest, epsilon, infinity, and nan are per type, as math::infinity::<f32>().
  • Classifying: is_nan, is_infinite, is_finite, is_subnormal, and sign_bit, and a real's bits, bits_of and real_of_bits.
  • Integers, of every integer type: rotate_left and rotate_right. count_ones, leading_zeros, trailing_zeros, and swap_bytes are core's, with no import. checked_add, checked_sub, checked_mul, and checked_pow give nothing where the result overflows, and the saturating_ ones hold it at the type's limit. Also int_pow, gcd, lcm, isqrt, div_floor, and rem_floor.
  • An element read by indexing is a reference, which is not real, so give the type: math::sqrt::<f64>(xs[i]).

Threads run functions at the same time, sharing the program's memory. A thread's handle is owning, and closing it waits for the thread, so a thread started in a scope ends before the scope does:

import std::thread;

var total := thread::mutex::<u64>::new(0);
{
  var workers := vector::<thread::handle<void>>::new();
  for part in 0..thread::cpu_count() {
    var started := thread::spawn(def() {
      val sum := add_up(part);
      var held := total.lock();             # unlocks where `held` closes
      held.value() += sum;
    }) else (e) { return; };
    workers.append(move(started));
  }
}                                           # closing `workers` joins every thread

var parsed := thread::spawn(def(): u64 { return parse_all(); }) else (e) { return; };
println($"{parsed.join()}");                # what the function gave

var jobs := thread::channel::<job>::new(64);   # at most 64 waiting; 0 for no bound
var worker := thread::spawn(def() { while jobs.receive() is some(next) { run(next); } }) else (e) { return; };
jobs.send(make_job()) else (j) { ... };
  • Starting one: spawn takes a function, and join gives back what it gave, void where it gives nothing. spawn_with(f, move(x)) gives the function a value the thread then owns alone, and closes where it ends. A closure refers to the locals it uses, as every closure does, so a thread may use the locals of the scope starting it while its handle is open, since closing the handle waits for the thread; a loop's variable, which changes, is given with spawn_with.
  • Guarding what's shared: a mutex<T> owns its value, and lock gives a @nodiscard guard lending it, which unlocks where it closes; try_lock doesn't wait. A condition's wait lets go of a mutex until notified, and wait_for until a time passes too. A channel<T> hands each value sent to one receiver, in the order one sender sent them; close wakes every waiter, gives back what's sent after, and closes what it held. once runs a function once however many threads ask. Atomics are the rest.
  • A race is the program's mistake: two threads touching the same memory that isn't atomic or guarded, at least one writing, with neither happening before the other. What either then reads isn't defined. Containers take no lock; share one through a mutex. print and println hold the standard output for each call, so lines from two threads never mix, and io::output_locked() holds it across several.
  • Stopping: a fault in any thread stops the program with that thread's trace, and system::exit from any thread stops them all. Signal handlers run in the thread the program began with. A program forks before it starts threads, as std::testing does for each test on Linux.
  • In the VM, threads take turns running bytecode, one at a time, letting the next run as they wait and every few thousand steps; executables run them in parallel. A program right in one is right in the other. No thread starts while compiling.
  • Also: thread::sleep, thread::id(), thread::cpu_count(), and in system, futex_wait and futex_wake, which the rest is built on.

Tests are functions marked @test, each run in a copy of the program, so one that faults fails alone:

import system;
import std::testing;

@test def adds(t: &mut tester): void { t.expects(1 + 1 == 2); }

def main(args: span<strview>): void { exit(tester::run(args)); }

t.expects(cond) reports a failed condition as written, with its operands' values. A test may take a fixture, and --only TEXT runs the tests whose names hold the text.

Windows can't fork, and system::fork gives unsupported there, so each copy is the program started again, with the same command line and SAKURA_TEST_ONE naming the one test it runs. What the program does before tester::run, each copy does again.

Testing

From the repository's root, blossom test runs each module's tests as a test of its own, built and run as an executable, or, for those of std::io:

sakurac run --lib std=. tests/main.sakura tests/io/*.sakura tests/io/glob/*.sakura

The tests of std::serial write and read through JSON and YAML. JSON's and YAML's conformance suites are in tests/json/parsing and tests/yaml/suite, under their licenses, and are found from the root.

License

MIT. See LICENSE.