MIMIC

Standard library

These are visible in every file without an import. The string, list and map functions are runtime intrinsics: they are implemented in Mimic's C runtime (runtime/mimic_std.c) and declared in the prelude with extern "mimic". They are memory safe and need no unsafe, and they have no side effects, so code that uses them stays parallel.

Strings

Function Result
split(s, sep) [str]. split(s, "") splits into characters.
join(parts, sep) str
lines(s), chars(s) [str] (UTF-8 characters stay whole)
trim(s), trim_start(s), trim_end(s) str
contains(s, part) bool. It also works on lists: contains([1 2 3], 2).
starts_with(s, p), ends_with(s, p) bool
find(s, part) Some(byte index) or None
replace(s, from, to) str (every occurrence)
upper(s), lower(s) str (ASCII letters)
repeat(s, n) str
string(x) Any value as text, the way print shows it
parse_int(s), parse_float(s) Some(number) or None
parse_int(s, base) In base 2 to 36: parse_int("ff", 16) is Some(255). A 0x, 0o or 0b that matches the base may come first.
char_code(s), char_of(n) The code point of the first character (char_code("A") is 65), and the character of a code point (char_of(233) is "é")
pad_start(s, width, fill), pad_end(s, width, fill) s widened to width characters with fill (default " ") before or after: pad_start("7", 3, "0") is "007"
words(s) [str]: split on runs of spaces, tabs and newlines
slice(s, from, to) The bytes from to to (excluded), as find and ≢ count them; negative positions count from the end. A position inside a multi-byte character moves to its edge.
format(x, spec) x as text by a format spec; the same as "{x:spec}" (below)
a + b Joins two strings.
a == b Compares two whole strings.
≢ s, s ↑ n, s ↓ n, ⌽ s Length, take, drop and reverse, as for any array.

Formats in interpolation

A float with no spec, "{x}" (and print(x)), is the shortest text that reads back as the same number: parse_float("{x}") is Some(x) for every finite x, as in Rust, Go, JavaScript and Python. So 0.1 + 0.2 shows as 0.30000000000000004; a spec such as .2 rounds for display. To save floats exactly in binary, see math::to_bits and bytes::of_f64s.

"{x:spec}" formats a value by a spec after a single :, the grammar Python and Rust use: [[fill]align][sign][#][0][width][,][.precision][type].

Spec Example Text
.2 "{3.14159:.2}" 3.14
>8, <8, ^8 "{42:>8}" 42 (right, left, centre)
*^9 "{"mid":*^9}" ***mid*** (a fill character before the alignment)
06 "{42:06}" 000042 (zeros after the sign)
+ "{42:+}" +42
, / _ "{1234567:,}" 1,234,567
x X o b, with # "{255:#x}" 0xff
e, f, % "{0.256:.1%}" 25.6%
.5 on text "{"truncated":.5}" trunc

A spec that is not one is a compile error (E0213).

Lists

Function Result
push(xs, x) A new list with x appended
put(xs, i, x) A new list with element i replaced by x (for maps: a new map with key i set)
concat(xs, ys) xs followed by ys
sort(xs) Ascending, stable; numbers or strings. ⌽ sort(xs) for descending.
sort_by(xs, key, descending: false) Ordered by key(x); equal keys keep their order
contains(xs, x) bool
unique(xs) The distinct elements, in order of first appearance
zip(a, b) [(a0, b0) (a1, b1) …], as long as the shorter list
enumerate(xs) [(0, x0) (1, x1) …]
any(mask), all(mask) Is any (every) element of a list of bools true: any(xs > 2)
count(xs, f) How many elements f says yes to
group_by(xs, f) A map from each f(x) to its elements, in order
flatten(xss) One list from a list of lists
min_by(xs, f), max_by(xs, f) Option: the element with the smallest (largest) f(x)
clamp(x, lo, hi) x kept between lo and hi; elementwise on lists
to_map(pairs) A map from [(key, value) …]; a later key wins
assert(ok, message) Stops the program with message (default "assertion failed") unless ok
panic(message) Stops the program with message (exit status 101)

Lists are values. push and concat return new lists and leave the original unchanged.

Sets: set

A set is a map from each element to true, so lookups are fast and the order of first appearance is kept.

Function Result
set::of(xs) A set of the elements of xs
set::has(s, x), set::size(s), set::items(s) Membership, the number of elements, the elements as a list
set::add(s, x), set::remove(s, x) A new set with x added or removed
set::union(a, b), set::intersection(a, b), set::difference(a, b) New sets

Maps

let born = ["ada": 1815, "alan": 1912]     // a map literal; [:] is empty
born["alan"]                               // 1912 (missing keys stop the program)
get(born, "linus")                         // None (Option)
has(born, "ada")                           // true
≢ born                                     // 2
keys(born), values(born)                   // in insertion order
let mut m = born
m["linus"] = 1969                          // copy-on-write: born is unchanged
put(born, "grace", 1906)                   // a new map with one more key
map_of(["x" "y"], [1 2])                   // ["x": 1, "y": 2]: a map from keys and values
remove(born, "ada")                        // a new map without it

What a key can be: numbers, bools, characters or strings.

How maps behave:

  • Order. Entries keep their insertion order, which is the order you see when printing and in keys and values.
  • Speed. Lookups go through a hash index.
  • Updates. m[k] = v on a let mut map changes it in place when nothing else shares it, and copies it first otherwise.

math: numbers (pure)

math::sqrt(2.0)                    // 1.4142135623731
math::atan2(1.0, 1.0) * 4.0        // π
[1.0 4.0 9.0] ¨ math::sqrt         // [1.0 2.0 3.0]
Function Result
math::sqrt(x), math::pow(x, y), math::hypot(x, y) square root, power, √(x² + y²)
math::sin(x), math::cos(x), math::tan(x) trigonometry, in radians
math::asin(x), math::acos(x), math::atan(x), math::atan2(y, x) inverse trigonometry
math::exp(x), math::ln(x), math::log2(x), math::log10(x) exponential and logarithms
math::tanh(x), math::sinh(x), math::cosh(x) hyperbolic functions
math::log1p(x), math::expm1(x) ln(1 + x) and eˣ − 1, exact near zero (stable losses)
math::sigmoid(x) the logistic function 1 / (1 + e⁻ˣ), without overflow for large negative x
math::floor(x), math::ceil(x), math::round(x) rounding (to an f64)
math::to_bits(x), math::from_bits(b) a float's 64 bits as an i64, and back, exactly (NaNs and -0.0 included); math::to_bits32, math::from_bits32 for f32 (its bits as 0 … 4294967295)
math::to_int(x) the integer part as an i64, towards zero: math::to_int(¯2.7) is -2; math::to_int(math::round(x)) rounds. NaN, or a number no i64 holds, stops the program. (An integer becomes a float with n * 1.0.)
math::pi(), math::e() the constants

All take and return f64 (integers are converted). On numbers the compiler knows, each is one machine instruction or one call to the system's math library, so it costs what it does in C and runs inside parallel array kernels. Any function of a standard module can be passed as a value: xs ¨ math::sqrt.

On whole numbers (i64 in, i64 or bool out):

Function Result
math::gcd(a, b), math::lcm(a, b) greatest common divisor and least common multiple, never negative (gcd(0, 0) and an lcm with 0 are 0)
math::powmod(b, e, m), math::mulmod(a, b, m) b to the power e, and a × b, modulo m (m > 0, e ≥ 0), exact for any numbers an i64 holds (products in 128 bits); the result is in 0 … m − 1
math::is_prime(n) whether n is prime: Miller-Rabin with the bases 2 … 37, which decide every i64 exactly
math::primes(n) the primes below n, in order (a sieve of Eratosthenes)
math::totient(n) Euler's φ: how many of 1 … n share no factor with n (n ≥ 1)

Standard modules

Everything with effects lives in a module, used by path from any file with no import: fs::read(p), time::now(). use fs::read brings in a short name.

Your own names come first. A program (or one of its modules) called json hides the standard json module. The compiler says so when that is the problem. Then std::json::encode still reaches the standard one, as std:: names every standard module. The global names are only print, Option/Result and the string, list and map functions above.

Functions with effects are known to the compiler for what they are (see ffi.md):

  • concurrent: may overlap; let x = … starts an implicit future, and ¨ runs them in parallel.
  • ordered: in program order.
  • sync: pending futures finish first.

Failures come back as values, never as crashes. Error messages name the operation, the path and the system's reason: cannot read data.csv: No such file or directory.

fs: files and directories

Function Result Effect
fs::read(path) Result[str, str] concurrent
fs::read_bytes(path) Result[[u8], str] concurrent
fs::size(path) Result[i64, str] concurrent
fs::list_dir(path) Result[[str], str]: sorted names, without . and .. concurrent
fs::walk(path) Result[[str], str]: every file below path, its subdirectories too, as sorted paths relative to it with / concurrent
fs::modified(path) Result[i64, str]: when the file last changed, in ns since 1970 (like time::now()) concurrent
fs::exists(path), fs::is_file(path), fs::is_dir(path) bool concurrent
fs::current_dir(), fs::temp_dir() str (the temporary directory: TMPDIR or /tmp; on Windows the user's, from TMP/TEMP) concurrent
fs::write(path, text), fs::append(path, text) Result[i64, str]: bytes written sync
fs::write_bytes(path, data) Result[i64, str] sync
fs::copy(from, to) Result[i64, str] sync
fs::rename(from, to), fs::remove(path) Result[bool, str]; remove also removes empty directories sync
fs::make_dir(path) Result[bool, str]: creates missing parents too; fine if it exists sync

The error text of the fs functions already names the path and the reason, cannot read data.csv: No such file or directory: show it as it is rather than adding the path again.

chan: channels between tasks (concurrent)

let (tx, rx) = chan::new[str]()            // a channel of str
let worker = consume(rx)                   // a task: an implicit future
chan::send(tx, "job 1")                    // never waits
chan::close(tx)                            // no more values
fn consume(rx: chan::Receiver[str]) -> i64 {
    match chan::receive(rx) {              // waits; None once closed and drained
        Some(job) => 1 + consume(rx),
        None => 0,
    }
}
Function Result
chan::new[T]() (chan::Sender[T], chan::Receiver[T]): an unbounded channel
chan::bounded[T](capacity) The same, holding at most capacity values
chan::send(tx, value) bool: false when the channel is closed. On a full bounded channel it waits for room
chan::receive(rx) Option[T]: waits for a value; None once closed and empty
chan::try_receive(rx) Option[T] without waiting
chan::close(tx) No more values; receivers get what is left, then None

How channels behave:

  • Unbounded or bounded. chan::new makes an unbounded queue, so send never waits. chan::bounded holds a fixed number of values, and send waits while it is full. That is backpressure: a fast producer cannot run ahead of a slow consumer and fill memory.
  • Safe to share. Values can be handed between tasks safely because they are immutable.
  • Ends are ordinary values. A Sender or Receiver can be stored in a list, sent through another channel or captured by a closure.
  • Tasks. A task is any let of a function whose effects may overlap, which channel operations are, and ws::serve/http::serve handlers run as tasks too.
  • Waiting is cheap. On the event loop a receive that waits parks only its own task, not a thread.
  • Without threads (WebAssembly), tasks are deferred. A receive that would wait first runs deferred tasks, so producer/consumer code still works. A deferred task cannot stop half-way, so a full bounded channel grows there instead of waiting.

bytes: binary data (pure)

[u8] is an array of bytes: one byte per element, so it is compact, and each element reads as an i64. Arithmetic on bytes gives i64 results instead of silently wrapping at 256. Storing a value outside 0 … 255 into a [u8] stops the program. push, concat, ↑, ↓, ⌽ and indexing keep bytes as bytes.

Function Result
bytes::from(xs) [u8] from a list of integers 0 … 255
bytes::of_text(s) the UTF-8 bytes of a string
bytes::to_text(b) Result[str, str]: Err unless the bytes are valid UTF-8
bytes::hex(b), bytes::from_hex(s) "486921" ↔ bytes; from_hex returns a Result
bytes::base64(b), bytes::from_base64(s) standard base64 ↔ bytes; from_base64 returns a Result
bytes::of_f64s(xs), bytes::to_f64s(b) floats as 8 bytes each (little-endian) ↔ bytes, exactly: model weights saved and read back bit for bit (to_f64s stops the program unless the length is a multiple of 8)

fs::read_bytes/fs::write_bytes and tcp::send_bytes/tcp::receive_bytes read and write bytes. A [u8] parameter accepts only bytes; passing a list of i64 is a compile error.

text: text algorithms (pure)

Function Result
text::distance(a, b) The Levenshtein distance: the fewest insertions, deletions and substitutions of characters (UTF-8 characters count as one) that turn a into b
text::find_all(s, part) [i64]: every byte position where part occurs (the positions find and slice use), overlapping ones included, by Knuth-Morris-Pratt; [] for an empty part
text::soundex(name) The American Soundex code: "R163" for both "Robert" and "Rupert"; letters other than A-Z are skipped
text::wrap(s, width) [str]: the words of s in lines of at most width characters, filled greedily (a longer word gets a line of its own), as Python's textwrap.wrap does with break_long_words=False

compress: compression and compact encodings (pure)

Function Result
compress::rle(b), compress::unrle(b) Run-length encoding: each run as two bytes, its length (1 … 255; longer runs take several pairs) and the byte. unrle returns a Result: Err for an odd length or a zero length
compress::lzw(b), compress::unlzw(codes) LZW with 12-bit codes (0 … 255 the bytes, new strings 256 … 4,095, then the dictionary stays): the codes as [i64]. unlzw returns a Result: Err for a code it could not have made
compress::varints(xs), compress::unvarints(b) Numbers as zigzag LEB128: each the difference from the one before, zigzag-mapped, 7 bits a byte, so small steps take one byte. unvarints returns a Result: Err when the bytes end inside a number or one runs past 10 bytes

graph: graph algorithms (pure)

Nodes are numbered 0 … n - 1; edge e goes from from[e] to to[e], with weight w[e] where one is needed. Each function is checked against networkx.

Function Result
graph::bfs(n, from, to, start) [i64]: the number of edges from start to each node along directed edges (breadth-first search); ¯1 where it cannot be reached
graph::shortest(n, from, to, w, start) [i64]: the length of the shortest path from start to each node along directed edges of weights w (none negative), by Dijkstra's algorithm with a binary heap; ¯1 where it cannot be reached
graph::components(n, a, b) [i64]: the connected components of the undirected graph, each node labelled with the smallest node of its component (union-find)
graph::topo(n, from, to) Option[[i64]]: an order in which every edge goes forwards (Kahn's algorithm, first come first served from the smallest node), or None if the edges make a cycle
graph::mst(n, a, b, w) [i64]: the edges of a minimum spanning forest of the undirected graph, by number (Kruskal's algorithm; equal weights by their place in the lists)

order: searching sorted lists (pure)

Function Result
order::lower_bound(xs, x), order::upper_bound(xs, x) In the sorted list xs, the first place whose value is not below x, and the first whose value is above it (binary search); their difference counts the xs
order::select(xs, k) The k-th smallest value (from 0), as sort(xs)[k] without sorting all of it (quickselect)
order::merge(a, b) Two sorted lists as one sorted list (equal values from a first)
order::is_sorted(xs) Whether xs never goes down

The module is called order because sort is the global function.

parse: common text formats (pure)

Function Result
parse::csv(text) [[str]]: the rows of a CSV text as Python's csv reads it (RFC 4180): fields apart by commas, rows by \n or \r\n, a field in double quotes may hold commas, newlines and doubled quotes; a blank line is a row of no fields
parse::url(s) A parse::Url record { scheme, user, password, host, port, path, query, fragment }, as Python's urllib.parse.urlsplit reads it: absent parts are "", an absent port ¯1, the scheme and host in lower case, an IPv6 host without its brackets
parse::semver(s) Option[parse::Version]: { major, minor, patch, pre, build } by Semantic Versioning 2.0.0, or None
parse::semver_compare(a, b) ¯1, 0 or 1 by Semantic Versioning precedence (a pre-release before its release; build metadata ignored)

hash: checksums and hashes (pure)

Each function is the standard algorithm on [u8], checked against the usual references (Python's zlib, hashlib, xxhash and mmh3, and the published test vectors), and is the same code the benchmark corpus measures. None of them is for passwords or signatures; md5 and sha1 are broken for security and are here for old formats.

Function Result
hash::crc32(b), hash::crc64(b) CRC-32 (as zlib and PNG compute it), CRC-64/XZ
hash::adler32(b) Adler-32 (as zlib computes it)
hash::fnv1a32(b), hash::fnv1a64(b) FNV-1a
hash::murmur3(b, seed = 0) MurmurHash3 x86_32
hash::xxhash32(b, seed = 0), hash::xxhash64(b, seed = 0) xxHash
hash::siphash(b, k0, k1) SipHash-2-4 with a 128-bit key, for hash tables facing chosen keys
hash::md5(b), hash::sha1(b), hash::sha256(b) the digest as bytes (16, 20 and 32 of them): bytes::hex(hash::sha256(b))

The 32-bit results are from 0 to 2^32 - 1; the 64-bit ones use every bit, so as an i64 they may be negative. To hash text, hash its bytes: hash::crc32(bytes::of_text(s)).

path: paths as text (pure)

Function Example
path::join(a, b) path::join("logs", "today.txt") → "logs/today.txt"; an absolute b replaces a
path::file_name(p) "a/b/c.tar.gz" → "c.tar.gz"
path::extension(p) "a/b/c.tar.gz" → "gz"
path::stem(p) "a/report.pdf" → "report"
path::parent(p) "a/b/c.txt" → "a/b"; "c.txt" → ""

io: standard input and error (ordered)

Function Result
io::read_line() Option[str]: the next line without its newline; None at the end
io::read_input() str: everything left on standard input
io::eprint(x) Print to standard error
io::write(x) Like print, without the newline; shown at once on a terminal
io::flush() Send what was written so far (to a file or pipe)
io::read_char() Option[str]: the next character of standard input
io::read_bytes(n) [u8]: up to n bytes (fewer only at the end of input)

term: the terminal (ordered)

Function Result
term::raw(on) Result[bool, str]. Raw mode: keys arrive one at a time, without echo or line editing. \n still starts a new line, and Ctrl-C still stops the program (or calls os::on_interrupt). The terminal is restored when the program ends.
term::read_key() Option[str]: one key, as a word ("up", "down", "left", "right", "enter", "tab", "backspace", "escape", "delete", "home", "end", "page_up", "page_down", "insert", "f1"… "f12", "ctrl-a"… "ctrl-z") or the character typed. It reads the keyboard directly, so do not mix it with io::read_line on the same input.
term::size() Option[term::Size]: { columns, rows }, or None without a terminal
term::is_terminal(stream) bool: 0 standard input, 1 standard output, 2 standard error
term::clear(), term::move_to(column, row) Clear the screen; move the cursor (from 0, top left)
term::show_cursor(on), term::alternate_screen(on) Hide the cursor; draw on a separate screen that disappears at the end, as full-screen programs do. Both are undone when the program ends.

Colours and other effects are ANSI codes in strings: "\x1b[1;32mgreen\x1b[0m". They work on Windows too.

os: the program and other programs

Function Result Effect
os::args() [str]: the command-line arguments, without the program name (mimic run file.mim -- a b) concurrent
os::env(name) Option[str] concurrent
os::env_all() Every environment variable: a map from name to value, sorted by name concurrent
os::pid() This process's id concurrent
os::set_env(name, value) Result[bool, str] sync
os::run(program, arguments) Result[os::Output, str]: program is looked up through PATH; Output { status, stdout, stderr } holds the exit status (128 + n when killed by signal n) and both outputs, captured completely sync
os::on_interrupt(f) Ctrl-C calls f (on a thread of its own) instead of stopping the program; f decides, for example with os::exit(0) sync
os::run_in(dir, program, arguments) os::run with dir as the program's working directory (a relative program path, such as ./tool, is found from there); Err when dir is not a folder sync
os::shell(command) the command line through the system shell: /bin/sh -c (on Windows cmd.exe /c) sync
os::exit(code) Leave the program now with that exit status ordered

The child's standard input is empty. WebAssembly (WASI), tvOS and watchOS have no child processes, so there os::run returns Err.

time: clocks and dates

Instants and durations are both i64 nanoseconds, so duration literals mix freely: time::now() + 90min, took < 2s.

Function Result Effect
time::now() Wall-clock time: nanoseconds since 1970-01-01 00:00 UTC concurrent
time::clock() A monotonic clock in nanoseconds, for measuring how long something takes (never jumps) concurrent
time::sleep(d) Pause, e.g. time::sleep(250ms) concurrent
time::local(t) time::DateTime in this machine's time zone concurrent
time::utc(t) time::DateTime { year, month, day, hour, minute, second, nanosecond, weekday, utc_offset }; weekday 1 = Monday … 7 = Sunday pure
time::timestamp(y, mo, d, h, mi, s) The instant of a UTC date and time pure
time::format(t) ISO 8601 / RFC 3339 in UTC: 2026-11-12T14:30:05Z, with .250 milliseconds when present pure
time::format(t, pattern) By a pattern, in UTC: %Y %m %d %H %M %S, %f milliseconds, %j day of the year, %a/%A weekday, %b/%B month, %y, %I and %p (12-hour clock), %%. time::format(t, "%d %b %Y") is 14 Nov 2026. pure

The calendar is the proleptic Gregorian one, correct for any year, before 1970 included.

random: random numbers (ordered)

Function Result
random::float() A float in [0, 1)
random::int(lo, hi) An integer in [lo, hi), without bias
random::seed(n) Make the sequence repeatable (per thread)
random::choice(xs) Option: one element at random, None for no elements
random::shuffle(xs) The elements in a random order

The generator is xoshiro256**, seeded from the operating system's entropy. Each thread has its own. Drawing a number changes the generator's state, so random draws run in order and never in parallel. It is not for cryptography.

lines(s) (global) splits at newlines and drops a \r before each one. A final newline ends the last line instead of starting an empty one, so lines(fs::read(…)) gives exactly the file's lines.

json: JSON text ↔ values (pure)

type User = { name: str, age: i64, tags: [str], email: Option[str] }

json::encode(user)                       // {"name":"Ada","age":36,"tags":["math"],"email":null}
json::encode_pretty(user)                // the same, indented
let u = json::decode[User](text) else { return }      // Result[User, str]
let v = json::parse(text) else { return }             // Result[json::Value, str]
match v { json::Object(m) => …, json::List(xs) => …, _ => … }
Function Result
json::encode(x), json::encode_pretty(x) str
json::decode[T](text) Result[T, str]: T given explicitly in […]
json::parse(text) Result[json::Value, str]
json::Value Null | Bool(bool) | Number(f64) | Text(str) | List([Value]) | Object([str: Value])

How values map to JSON:

Mimic JSON
i64, f64 numbers (floats keep a .0; NaN and infinity become null)
bool, str true/false, strings
lists, matrices arrays (nested, row by row, for matrices)
maps objects (non-string keys are written as text)
records objects with the field names
tuples arrays
Some(x) / None x / null
Ok(x) / Err(e) {"ok": x} / {"error": e}
other variants "Name", {"Name": x}, {"Name": [x, y]}

Decoding into T follows T's fields and types:

  • Extra fields in the JSON are ignored.
  • Missing fields are None when their type is an Option, and an error otherwise.
  • Integers must be whole numbers.
  • Errors name where the problem is: json: expected an integer at users[2].age, found a string or invalid JSON at line 3, column 7: expected ','.
  • What can be decoded: records (generic ones too, like Page[User]), lists, maps ([str: i64]), Option, numbers, bools and strings. Unions other than Option cannot be decoded yet.

Raw strings make JSON literals easy: '{"name": "Ada"}' uses single quotes, has no interpolation and no escapes.

Networking: the http, ws, tcp and udp modules

Networking lives in standard modules, used by path from any file with no import: http::fetch, ws::connect, tcp::connect, udp::bind. (use http::fetch works too.) Your own modules come first: a project or module called http hides the standard one.

http

let r = http::fetch("http://example.com/") else { return }   // Result[http::Response, str]
print((r.status, get(r.headers, "content-type")))
http::request("POST", url, ["content-type": "application/json"], body)

fn handle(req: http::Request) -> http::Response {
    match (req.method, req.path) {
        ("GET", "/") => http::ok("hello"),
        ("GET", "/users/{id: i64}") => http::ok("user #{id}"),
        _ => http::not_found(),
    }
}
http::serve(8080, handle)                                     // runs until the program ends
Function / type Meaning
http::fetch(url) Result[Response, str]: a GET request
http::request(method, url, headers, body) Any method, with [str: str] headers and a body
http::serve(port, handler) An HTTP/1.1 server; handler is a fn(http::Request) -> http::Response
http::serve_requests(port, handler, n) The same, stopping after n requests; Ok(n)
http::serve_tls(port, handler, identity), http::serve_tls_requests(port, handler, identity, n) The same over HTTPS, with a tls::Identity (see tls)
http::Request { method, path, query, headers, body }: header names are lower case, query is the part after ?
http::Response { status, headers, body }
http::ok(body), http::respond(status, body), http::not_found() Responses (text/plain unless the headers say otherwise)
http::json(value) A 200 response with value encoded as JSON (application/json)

How the client and server behave:

  • Requests overlap. let a = http::fetch(u1) and let b = http::fetch(u2) are in flight at the same time (implicit futures).
  • Redirects are followed (301, 302, 303, 307, 308; up to 10), with two limits: never from https to http (an Err), and to another server (another scheme, host or port) without Authorization, Cookie and Proxy-Authorization.
  • The server runs a pure or overlapping handler in parallel, one task per connection on the event loop (see the event loop). A handler that prints or writes files takes turns: one request at a time. Requests are still read side by side, so an idle client never holds up the others.
  • The server keeps connections open (HTTP/1.1 keep-alive): a client sends request after request on one connection, and pipelined requests are answered in order, their answers sent together. A connection closes when the client asks (Connection: close, or HTTP/1.0), after a chunked request body, or after 30 seconds without a request. serve_requests and serve_tls_requests answer one request per connection, so their count is exact.
  • The client sends one request per connection (Connection: close). Bodies use Content-Length; chunked responses are decoded.
  • https:// uses the operating system's TLS, loaded when first needed: the Security framework on Apple platforms, Schannel on Windows, OpenSSL 3 (libssl.so.3) on Linux. Certificates and host names are checked against the system's trusted certificates, so an expired, self-signed or wrong-host certificate is an Err ("TLS with example.com failed: …"). Statically linked Linux programs (--target x86_64-linux, …) cannot load OpenSSL; they carry Mbed TLS instead, built into the program, and trust the system's CA bundle (/etc/ssl/certs/ca-certificates.crt and the other usual places, or the file SSL_CERT_FILE names). Serving HTTPS: see tls.
  • Redirects are followed (301, 302, 303, 307, 308), up to 10. A 303, or a 301/302 after a non-GET, continues as a GET; 307 and 308 keep the method and body.
  • WebAssembly has no sockets, so there every network function returns Err.

The event loop

Every connection of http::serve and ws::serve runs as a task, and so does every implicit future started by such a task. A task is a coroutine with its own small stack, not an operating-system thread. When a task would wait it parks, and its thread runs other tasks meanwhile. A task waits when it receives from a socket, sends to a full one, connects, accepts, sleeps (time::sleep), receives from an empty channel or awaits another task. A few scheduler threads (one per core) run all the tasks. One poller thread watches the waiting sockets (kqueue on Apple systems, epoll on Linux) and the timers.

You never write async or await, and nothing changes in your code. The difference shows at scale: a WebSocket echo server holds 3000 open connections with 14 threads, where one thread per connection would need 3000. A task always stays on the same thread, so pure work inside a handler still uses the parallel array kernels as usual.

Details:

  • Where it runs. On Apple systems, Linux and Windows, on arm64 and x86-64 (on Windows the coroutines are fibers and sockets are watched through IOCP). Elsewhere (WebAssembly, other CPUs) tasks are threads or deferred calls, as before.
  • Switching it off. Set the environment variable MIMIC_NO_EVENT_LOOP=1 to run each connection on its own thread instead.
  • Finding a hang. With MIMIC_DEBUG_WATCHDOG=10, a program still running after 10 seconds prints every task and what it waits for (a channel, a join, a socket read or write, a timer), the event loop's queues, and the threads blocked in joins or channel receives, on standard error. A task shown as running for that long is blocking its thread instead of waiting on the event loop.
  • Calls that still block their thread for a moment: looking up a host name, TLS handshakes on Linux, file I/O, os::run and io::read_line. Other tasks on the same thread wait meanwhile. Tasks on other threads keep running.
  • Timeouts still apply. A task's socket wait ends at the same timeout a thread's would: 60 seconds for an HTTP response, 30 seconds for a request a server is reading.
  • ¨ over a function that waits (its effects may overlap: network calls, sleeping) runs every element as a task of its own on the event loop, so urls ¨ fetch or 3000 WebSocket clients all wait at once instead of a core's worth at a time. A pure function under ¨ is spread over the cores as before. A test runs 3000 clients, each holding its connection for half a second, against one server in about a second, on macOS, Linux and Windows.
  • Open files. A program raises its own limit on open files to what the system allows (macOS starts at 256), so thousands of connections need no ulimit.
  • Futures started outside a task, from main for example, still get a thread each. That is cheap, because there are few of them.

ws: WebSockets

fn echo(sock: ws::Socket) {                       // one call per connection
    match ws::receive(sock) {
        Ok(ws::Text(t)) => { ws::send(sock, upper(t)); echo(sock) }
        _ => {}
    }
}
ws::serve(8080, echo)

let sock = ws::connect("wss://example.com/live") else { return }
ws::send(sock, "hello")
let reply = ws::receive(sock)                     // Ok(ws::Text("…")) / Ok(ws::Binary(bytes)) / Ok(ws::Closed)
ws::close(sock)
Function / type Meaning
ws::connect(url) Result[ws::Socket, str] for ws:// and wss:// (TLS as for https://)
ws::send(socket, text), ws::send_bytes(socket, data) Result[i64, str]
ws::receive(socket) Result[ws::Message, str]: Text(str), Binary([u8]) or Closed
ws::close(socket) Close (with the closing handshake)
ws::serve(port, handler) Call handler(socket) for each connection; the socket closes when it returns
ws::serve_connections(port, handler, n) The same, stopping after n connections
ws::serve_tls(port, handler, identity), ws::serve_tls_connections(port, handler, identity, n) The same over TLS (wss://)

How WebSockets behave:

  • Protocol. RFC 6455: fragmented messages are joined, pings are answered automatically, and messages may be up to 64 MB.
  • Sending. Sends on one socket from different tasks never interleave.
  • Connections run in parallel when the handler's effects may overlap, the same rule as http::serve.
  • Connections talk through channels (chan): see the chat room in tutorial chapter 19.

tcp

Function Result
tcp::connect(host, port) Result[tcp::Socket, str]
tcp::listen(port) Result[tcp::Listener, str]; port 0 picks a free port, see .port
tcp::accept(listener) Result[tcp::Socket, str]
tcp::send(socket, text) Result[i64, str]: everything is sent
tcp::receive(socket, limit) Result[str, str]: up to limit bytes; "" when the other side closed
tcp::send_bytes(socket, data), tcp::receive_bytes(socket, limit) The same with [u8]
tcp::close(socket) Close a socket or listener

TCP calls happen in program order.

tls: encryption

// a server: a certificate and its key, as PEM text
let cert = fs::read("cert.pem") else { return }
let key = fs::read("key.pem") else { return }
let id = tls::identity(cert, key) else { return }
http::serve_tls(8443, handle, id)                      // https://…:8443
ws::serve_tls(8444, chat, id)                          // wss://…:8444

// encrypted TCP, for protocols of your own
let s = tls::connect("example.com", 443) else { return }
tls::send(s, "…")
let reply = tls::receive(s, 4096)
Function / type Result
tls::identity(cert, key) Result[tls::Identity, str]: a server's certificate (chain) and private key, both PEM text
tls::self_signed(host) Result[(str, str), str]: a new certificate and key (PEM) for host, for development
tls::connect(host, port) Result[tls::Stream, str]: an encrypted connection, checked against the system's trusted certificates
tls::connect_trusting(host, port, cert) The same, but trusting exactly the certificate(s) in cert (PEM) instead
tls::accept(listener, identity) Result[tls::Stream, str]: the next connection on a tcp::Listener, encrypted
tls::send(stream, text), tls::send_bytes(stream, data) Result[i64, str]
tls::receive(stream, limit), tls::receive_bytes(stream, limit) Result[str, str] / Result[[u8], str]: up to limit bytes; "" when the other side closed
tls::close(stream) Close it

How TLS behaves:

  • The system's own TLS. Mimic uses the Security framework on Apple systems, Schannel on Windows and OpenSSL 3 on Linux, loaded when first used, as for https://. Statically linked Linux programs use the Mbed TLS built into them, as for https://.
  • Certificates are PEM text, the usual -----BEGIN CERTIFICATE----- files. Read them with fs::read, or take them from the environment. Keys may be PKCS#8 (BEGIN PRIVATE KEY), EC or RSA, unencrypted. An identity is loaded once and shared by every connection.
  • Clients check certificates. tls::connect, http::fetch and ws::connect accept only certificates your system trusts, and only for the host name you asked for. tls::connect_trusting replaces the system's list with the certificate you give, which is how you talk to your own servers during development.
  • tls::self_signed(host) makes a P-256 key and a certificate valid for 90 days, for host (and for 127.0.0.1 and ::1 when host is "localhost"). Browsers warn about it. Use a certificate from a certificate authority, such as Let's Encrypt, in production.
  • Apple's limits. On Apple systems Mimic speaks TLS 1.2, and certificates must follow Apple's rules. For example, Apple rejects server certificates that are valid for more than 825 days.
  • On the event loop, handshakes and reads park only their task on Apple systems. On Linux the handshake blocks its thread briefly.

udp

let sock = udp::bind(0) else { return }                 // port 0: any free port, see sock.port
udp::send(sock, "127.0.0.1", 9999, "ping")
match udp::receive_within(sock, 2s) {
    Ok(p) => print("{p.text} from {p.host}:{p.port}"),
    Err(e) => print(e),                                  // "timed out"
}
Function / type Result
udp::bind(port) Result[udp::Socket, str]: a socket on every interface; .port is the port it got
udp::send(socket, host, port, text) Result[i64, str]: one packet
udp::send_bytes(socket, host, port, data) The same with [u8]
udp::receive(socket) Result[udp::Packet, str]: waits for one packet
udp::receive_within(socket, timeout) The same, or Err("timed out") after timeout (a duration such as 500ms)
udp::close(socket) Close it
udp::Packet { data: [u8], text: str, host: str, port: i64 }: the bytes, the same bytes as text, and the sender

How UDP behaves:

  • Packets, not streams. Each send is one packet, at most about 64 KB. Packets can be lost, duplicated or arrive out of order. UDP never tells you, so use receive_within and retry when an answer matters.
  • IPv4 only, for now. Broadcast addresses are allowed.
  • Tasks. UDP calls may overlap, like WebSockets. A function that only uses UDP can run as a task (let s = serve_udp(sock)), and on the event loop a waiting receive parks only its task.

Interfaces: the ui module

A screen is a value of type ui::Node[Msg], built by view(state). Events become messages, update(state, message) makes the next state, and the browser shows the result. The design is in ui.md, and tutorial chapter 20 walks through an app.

fn view(s: State) -> ui::Node[Msg] {
    ui::column(gap: 12, [
        ui::text("Count: {s.count}", size: 24),
        ui::row([ui::button("-", on_click: Dec), ui::button("+", on_click: Inc)]),
    ])
}
ui::run(State { count: 0 }, view, update)               // http://localhost:8080/
Element Settings (named, all optional)
ui::column(children), ui::row(children) gap, padding, align, background, grow
ui::grid(children) columns, gap
ui::text(content) size, weight, color, strike
ui::button(label, on_click: message)
ui::input(value, on_input: fn(str) -> Msg) placeholder
ui::checkbox(checked, on_change: fn(bool) -> Msg)
ui::form(children, on_submit: message), ui::submit(label) gap (Enter in an input submits)
ui::link(label, url), ui::image(url) width, height, alt (image)
ui::spacer(), ui::divider()
ui::keyed(key, node) node, known by key among its siblings (see below)
Function Result
ui::run(init, view, update) Show the interface until the program is stopped. Settings: show ("browser", "terminal" or "window"; by default the MIMIC_UI environment variable, else the browser), port (8080), title ("Mimic"), connections (stop after that many, for tests; 0 = never)
ui::run_live(init, view, update) The same, with an update that returns a ui::Step (jobs), and subscriptions: [ui::Sub[Msg]]
ui::stay(state) A ui::Step with nothing else to do
ui::then(state, job), ui::also(step, job) A step with a job: job() runs as a task of its own, and the message it returns is handled when it is done
ui::every(interval, message) A subscription: message every interval (a duration such as 1s)
ui::listen(receiver) A subscription: each value that comes through a chan::Receiver[Msg]
ui::html(node) The screen as HTML
ui::diff(a, b, "0") The changes ([ui::Patch]) that turn screen a into screen b
ui::message(node, event) The message a browser event (JSON) stands for, if any
ui::terminal_text(node, focus, title), ui::plain(text) The screen as terminal text (with styles), and text without them
ui::focusables(node, "0"), ui::key_message(node, focus, key) The elements a key can reach, and the message a key stands for on one

How it works:

  • Each browser tab is a task with its own state. The first page is complete HTML. After that, events travel to the program over a WebSocket, and only the changed parts travel back.
  • view and update are pure. Lists of children built with ¨ are built in parallel, and so is the comparison of the old and new screens. Different tabs run in parallel too.
  • Functions inside a screen must be pure (on_input: Typed or t => Typed(trim(t))). Printing or other effects there is error E0605. Effects belong in jobs.
  • Jobs keep the page responsive. A job (fetching, saving, a slow computation) runs on its own, while the tab keeps handling clicks. Its result arrives as an ordinary message. Several jobs run at the same time.
  • Each tab handles one message at a time, in order. Tabs run side by side, even when update or a job has effects.
  • Built-in theme: readable defaults with light and dark modes.
  • Lists change cheaply. A list that grows or shrinks at the end sends only the new rows, or only a removal. Give rows keys with ui::keyed("{todo.id}", row), and inserting or removing anywhere sends only that row. Reordered rows re-send the list. Adding or removing a row sends a few hundred bytes.
  • Unchanged rows are not built again. In xs ¨ row, where row makes a screen part from one element and captures nothing, an element that is the very same value as at the last screen gets its old row back, and ui::diff skips it. Values never change, so nothing can be stale. With 10 000 rows and one changed, a new screen and its changes take about 15 ms on one core of an M3 Pro (170 ms when every row was built). Write the rows as todos ¨ row (not ⍳ ≢ todos ¨ (i => row(todos[i]))) to get this.
  • As a web page. mimic build --web (or mimic run --web) turns a ui program into a page that runs entirely in the browser, as WebAssembly with no server. The same view, update and subscriptions work there. The differences: jobs run right after the message that started them, time::sleep returns at once, there is no networking, and print goes to the browser's console.
  • In a terminal. mimic run --terminal (or show: "terminal") draws the same screens as text. Tab and the arrow keys move the focus, Enter or Space presses buttons and ticks boxes, typing edits the focused text box, Enter in a text box submits its form, and Esc or Ctrl-C quits (ui::run then returns Ok(messages handled)). Timers and jobs work as in the browser. Layout follows the elements: rows side by side, columns one below the other, and gap and padding become spaces and blank lines.
  • In a native window (macOS, Windows, Linux). mimic run --window (or show: "window") shows the screens with the system's own controls: AppKit on macOS, Win32 controls on Windows, GTK 3 on Linux. Columns, rows and forms become boxes, text becomes labels, buttons, check boxes and text boxes are the native ones, grids line their columns up, and links open in the browser. The tab's loop runs as a task, so timers and jobs never freeze the window. Closing the window makes ui::run return. Call ui::run from main, because macOS needs windows on the main thread. Nothing is linked in for this: AppKit and GTK are loaded when the first window opens, so a program runs on machines without them until it opens one. On Linux that needs GTK 3 (libgtk-3-0, installed on most desktops) and a display; without them ui::run returns an Err that says so. Static Linux programs (--target x86_64-linux) cannot load GTK. Images show on macOS and Linux; on Windows an image is a placeholder for now. Setting MIMIC_UI_TEST to a file of steps (click PATH, type PATH TEXT, enter PATH, wait MS, dump, close) drives the window through its real controls and prints the views, which is how window tests are written.
  • Not yet: native windows on Windows and Linux.

From docs/std.md in the Mimic repository.