std
The Sakura programming language's standard library: what programs build on beyond core and system, which ship with the compiler, sakurac. Each module is a library of its own, in the folder of its name, which reads core, system, and the modules it lists:
| 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.
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=DIRnames, as this repository checked out; - or else a
stdfolder beside thesakuracexecutable or in the nearest folder above it, as a copy of this repository; - or else its libraries in the
share/sakurafolder nearest above the executable, asshare/sakura/std.ioforstd::io, whereblossom installputs them.
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.view()) 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, andhours, and read byin_nanosecondsandin_seconds. - The range: moments and durations count nanoseconds in an
i64, so atimestampreaches from 1677 to 2262. Arithmetic past that stops the program, as indexing past an end does. - Two clocks: an
instantnever goes back, and means nothing but against another. Atimestampsays when, and the system may set its clock back. - The calendar is the Gregorian one, without leap seconds.
datehasweekday,day_of_year,plus_days,plus_months,days_since, andiso. - Zones:
zone::utc(),zone::fixed(offset),zone::named("Asia/Tokyo")from the system's database, andzone::local(). Windows keeps no database, so therezone::namedreads the directoryTZDIRnames, and finds no zone without it, andzone::local()is the rule the system's setting keeps the clocks by now, which says nothing of the years before that rule.timestamp::atgives thedate_timea zone's clocks show, andzone::resolvethe 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:
rfc3339writes a moment, andparse_rfc3339andparse_dateread one, giving atime::errorfor 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
Tthat isreal:sqrt,cbrt,hypot,exp,exp2,expm1,log,log2,log10,log1p,pow,sin,cos,tan,asin,acos,atan,atan2,sinh,cosh,tanh,asinh,acosh, andatanh, all in radians. - Exact operations:
floor,ceil,trunc,round, which takes halves away from zero,round_even,copysign, andfma, which rounds once.abs,min,max, andclamptake any ordered type, as integers anddurations. Of reals,minandmaxgive NaN where either is NaN, and put-0below0. - 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.
sqrtis the machine's, correctly rounded. Results are within an ulp of the true value, but foratan2,sinh,tanh,asinh,acosh, andatanh, which are within 2, as musl's are. Anf32is worked inf64and rounded, which is almost always the nearestf32. - 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, andln_10aref64s, whichas f32rounds for floats.largest,smallest,epsilon,infinity, andnanare per type, asmath::infinity::<f32>(). - Classifying:
is_nan,is_infinite,is_finite,is_subnormal, andsign_bit, and a real's bits,bits_ofandreal_of_bits. - Integers, of every integer type:
rotate_leftandrotate_right.count_ones,leading_zeros,trailing_zeros, andswap_bytesarecore's, with no import.checked_add,checked_sub,checked_mul, andchecked_powgivenothingwhere the result overflows, and thesaturating_ones hold it at the type's limit. Alsoint_pow,gcd,lcm,isqrt,div_floor, andrem_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:
spawntakes a function, andjoingives back what it gave,voidwhere 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 withspawn_with. - Guarding what's shared: a
mutex<T>owns its value, andlockgives a@nodiscardguard lending it, which unlocks where it closes;try_lockdoesn't wait. Acondition'swaitlets go of a mutex until notified, andwait_foruntil a time passes too. Achannel<T>hands each value sent to one receiver, in the order one sender sent them;closewakes every waiter, gives back what's sent after, and closes what it held.onceruns 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.printandprintlnhold the standard output for each call, so lines from two threads never mix, andio::output_locked()holds it across several. - Stopping: a fault in any thread stops the program with that thread's trace, and
system::exitfrom any thread stops them all. Signal handlers run in the thread the program began with. A program forks before it starts threads, asstd::testingdoes 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 insystem,futex_waitandfutex_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.