LEVIATHAN v962456e · 962456eee1

leviathan-lang.com / docs / library

Standard Library

Every type and function of the standard library, with signatures, examples and Run it links.

The standard library: the types and functions every Leviathan program can use without installing anything.

Almost all of it lives in one namespace, std, which every program sees automatically, so Array, Map, console and File are used by their plain names. A few areas that hold many functions have a namespace of their own that you reach with ::, for example math::sin, json::parse, regex::compile, datetime::parseIso8601 and env::args.

The core of the library is the built-in types and the collections built on them. The primitives are bool, int, float, char and string, together with the sized numbers from byte to float32 and Block, a fixed buffer of bytes. Array, Map, Set, Pair and Triple hold values, Range is what a..b produces, and a lazy Seq pipeline (map, where, take and the rest) works over any of them. Errors are objects too: Exception and its subclasses, such as RuntimeException, are what throw and catch carry. For text there are StringBuilder, the Regex type, and the encoding and digest namespaces for base64, hexadecimal, percent escapes and hashes.

Asynchronous work uses Promise with await, and Timer, Channel, TaskGroup and Worker build on it. Everything that crosses the process boundary is a stream: console writes to standard output, InStream and OutStream carry values between a producer and a consumer, and files, sockets, HTTP, child processes, the terminal and operating-system signals are reached through File, TcpStream, HttpClient, Process, term and signal. The capability interfaces IEnv, IConsole, IClock, IFileSystem and INet let a program ask for these facilities by interface so that a test can substitute its own. Data formats are covered by json, csv and datetime, and meta is what rules read at compile time.

std

  • Array — An ordered sequence of values of one type, Array<T>, with value semantics.
  • Block — A fixed-length, mutable buffer of bytes.
  • bool — The boolean type: a value is either true or false.
  • byte — An unsigned 8-bit integer: a byte holds 0 to 255 and is stored unboxed.
  • CancelledException — The error delivered to a task that has been cancelled.
  • Channel — A queue that carries values from one worker to another.
  • char — A single Unicode character, stored as one code point.
  • ChunkedDecoder — Decodes an HTTP body sent with chunked transfer coding.
  • ChunkedSink — The writer for a streaming HTTP response body.
  • Console — The program's standard output as an object.
  • CsvRows — The sequence of rows read from a CSV file.
  • DateTime — A point in time, held as milliseconds since 1970-01-01T00:00:00Z.
  • DomEvent — A DOM event delivered to a handler, as a typed handle.
  • DomNode — A handle to one node in the browser page.
  • Duration — A length of time, stored as a whole number of milliseconds.
  • Exception — The base class of the standard exceptions, holding a message.
  • File — An open file.
  • FileException — The error thrown when a file operation fails.
  • FileInStream — A stream that reads text from a file descriptor.
  • FileOutStream — A stream that writes text to a file descriptor.
  • float — A 64-bit IEEE 754 floating-point number (binary64).
  • float16 — A 16-bit floating-point number in the IEEE 754 binary16 format: 1 sign bit, 5 exponent bits and 10 mantissa bits.
  • float32 — A 32-bit floating-point number in the IEEE 754 binary32 format: 1 sign bit, 8 exponent bits and 23 mantissa bits.
  • float8 — An 8-bit floating-point number in the OCP E4M3 format: 1 sign bit, 4 exponent bits and 3 mantissa bits.
  • Group — One capture group of a match: whether it took part, and where and what it matched.
  • Header — One HTTP header line: a name and its value.
  • HeaderMap — An ordered collection of HTTP headers whose names are matched without regard to letter case.
  • HttpClient — A simple HTTP client that sends one request per connection and delivers the response to a callback.
  • HttpConnection — One client connection served by an HttpServer.
  • HttpRequest — An HTTP request as seen by a server: the request line, the headers and the body.
  • HttpResponse — An HTTP response: a status code, headers and a body.
  • HttpResponseReader — Collects a client's incoming bytes and turns them into an HttpResponse.
  • HttpServer — A web server that listens on a port and answers each request with a handler function.
  • ICancelledException — The interface of the error that reports that a task was cancelled.
  • IClock — What a program may know about the time.
  • IConsole — What a program may say to the terminal.
  • IDisposable — The interface of an object that must be cleaned up when its work is finished.
  • IEnv — What a program may learn from the process environment: its arguments and its variables.
  • IException — The interface that every thrown value must implement.
  • IFileException — The interface of every error that comes from working with files.
  • IFileSystem — What a program may do with the file system: open files and check whether a path exists.
  • IIterable — A source of values that can be walked with for.
  • IIterator — The pull protocol for walking a sequence one value at a time.
  • ILogicException — The interface of errors that come from a mistake in how the program was written, such as calling something in the wrong state.
  • INet — What a program may do with the network: open connections and listen for them.
  • InStream — The reading end of a stream: a queue of values of type T that something else produces.
  • int — The signed 64-bit integer type, the default type of whole numbers.
  • int16 — A signed 16-bit integer: an int16 holds -32768 to 32767 and is stored unboxed.
  • int32 — A signed 32-bit integer: an int32 holds -2147483648 to 2147483647 and is stored unboxed.
  • int8 — A signed 8-bit integer: an int8 holds -128 to 127 and is stored unboxed.
  • IOStream — A stream that can be both read and written, with both ends over one queue.
  • IRuntimeException — The interface of errors that arise while a program runs, such as a bad argument or a failed operation.
  • JsonValue — A JSON value: null, a boolean, a number, a string, an array or an object.
  • LogicException — An error that signals a mistake in the program's own logic, such as using an object in the wrong state.
  • Map — An associative collection from keys of type K to values of type V, with value semantics.
  • Match — A successful match: where it is, what it matched, and its capture groups.
  • OpenMode — A set of flags that says how a file is opened.
  • OrderedArray — An array that has been sorted by one or more keys, produced by Array.orderBy and thenBy.
  • OutStream — The writing end of a stream: you push values of type T in, and a reader takes them out.
  • Pair — A pair of two values, possibly of different types.
  • Process — Runs another program as a child process and gives you its standard input, standard output and standard error as streams.
  • Promise — A value that arrives later.
  • Pty — Runs another program on a pseudo-terminal, so the child believes it is talking to a real terminal.
  • Range — A run of consecutive integers written a..b, including both ends.
  • Regex — A compiled regular expression.
  • RegexException — The exception thrown for a malformed pattern, and for a malformed or out-of-range reference in a replacement string.
  • RegexOptions — Options that change how a pattern is interpreted: ASCII case folding, line anchors and whether . crosses line breaks.
  • RuntimeException — The error the standard library throws when an operation fails at run time.
  • Seq — A lazy sequence: a pipeline of steps that does no work until its result is requested.
  • Set — A collection of distinct values of type T, with value semantics.
  • string — An immutable sequence of text, stored as UTF-8.
  • StringBuilder — A mutable accumulator for building a string from many pieces.
  • SystemClock — The real clock behind the IClock interface.
  • SystemConsole — The real console behind the IConsole interface: it prints to standard output.
  • SystemEnv — The real process environment behind the IEnv interface.
  • SystemFileSystem — The real file system behind the IFileSystem interface.
  • SystemNet — The real network behind the INet interface.
  • TaskGroup — A set of tasks that live and end together.
  • TcpListener — A listening socket that delivers each incoming connection as a TcpStream.
  • TcpStream — A connected network socket that reads and writes text.
  • Timer — A source of ticks on the event loop.
  • TlsAccept — Accepts a TLS client on a server socket, with a deadline.
  • TlsDrive — Drives a TLS handshake to completion on the event loop.
  • Triple — A group of three values, possibly of different types.
  • uint — An unsigned 32-bit integer: a uint holds 0 to 4294967295 and is stored unboxed.
  • Worker — The handle to a value that another worker is computing.

expr

The expression-reification tree: runtime, walkable descriptions of lambda bodies.

  • Assign — A field assignment, u.field = value, which is the whole body of a "set" lambda.
  • Bin — A binary operation: l op r.
  • Bind — A captured value, referred to by its position in the binds array of the enclosing expr::Expr.
  • Call — A method call on a receiver, such as u.name.like("A%").
  • Expr — A lambda together with a walkable description of its body.
  • Field — A member access rooted at a lambda parameter, such as u.address.city.
  • Lit — A literal value in the expression: a string, an integer, a float, a boolean, or None.
  • Node — The base class of every node in the reification tree.
  • Un — A unary operation: !e or -e.

meta

The compile-time view of a program that rules and macros read.

  • Attr — An attribute written on a field or method, with the values of its arguments.
  • AttrArg — One argument of an attribute, with a slot for every primitive form.
  • Class — A class that a rule has matched, as a rule sees it.
  • Field — A field of a class, as a rule sees it.
  • Method — A method of a class, as a rule sees it.
  • Param — One parameter of a method, as a rule sees it.

term

Control of the terminal the program runs in: raw input mode and the window size.

  • WinSize — The size of a terminal window in character cells.

Constants and globals

append

since 0.1.0-alpha.1linuxwindowswasm

const OpenMode append = OpenMode(4)

Open a file for adding to the end, creating it if it is missing.

Existing contents are kept and every write goes after them.

See also: OpenMode, write

binary

since 0.1.0-alpha.1linuxwindowswasm

const OpenMode binary = OpenMode(8)

Marks a file as binary.

It is accepted so that code can state its intent, but has no effect yet: files are read and written as text.

See also: OpenMode

console

since 0.1.0-alpha.1linuxwindowswasm

const Console console = Console()

The process console: the one Console every program can print to.

See also: Console

read

since 0.1.0-alpha.1linuxwindowswasm

const OpenMode read = OpenMode(1)

Open a file for reading. The file must already exist.

Combined with std::write it opens for reading and writing, creating the file if it is missing and keeping its contents.

See also: OpenMode

write

since 0.1.0-alpha.1linuxwindowswasm

const OpenMode write = OpenMode(2)

Open a file for writing, creating it if it is missing and emptying it if it exists.

Combine with std::read to read as well and keep the existing contents.

See also: OpenMode, append

Functions

after

since 0.1.0-alpha.1linuxwindows

after(int ms) -> Timer

Start a timer that fires once.

The single tick comes after ms milliseconds, and the timer then releases itself.

Parameters

ms
The delay before the tick, in milliseconds.

Returns

The running timer.

Examples

std::after(10).subscribe((n) => { console.writeln("ten milliseconds later"); });
std::after(5).subscribe((n) => { console.writeln("five milliseconds later"); });
console.writeln("waiting");
waiting
five milliseconds later
ten milliseconds later

See also: every

average

since 0.1.0-alpha.1linuxwindowswasm

average(Array<int> a) -> float

Compute the arithmetic mean of an integer array.

The mean is always a float, even for an integer array, so [1, 2] averages to 1.5. The mean of an empty array is not a number (NaN), because it divides zero by zero. The same name is overloaded for Array<float>.

Parameters

a
The numbers to average.

Returns

The sum of the elements divided by their count.

Examples

Array<int> a = [4, 8, 15, 16, 23, 42];
console.writeln(std::average(a));
console.writeln(std::average([1, 2]));
console.writeln(std::average([1.0, 2.0, 6.0]));
18.000000
1.500000
3.000000
average(Array<float> a) -> float

Compute the arithmetic mean of a float array.

Same as the Array<int> overload, but for floats. The mean of an empty array is not a number (NaN).

Parameters

a
The numbers to average.

Returns

The sum of the elements divided by their count.

awaitTimeout

since 0.1.0-alpha.1linuxwindows

awaitTimeout<T>(Promise<T> work, int ms) -> T | None

Wait for a promise, but give up after a time limit.

If work settles first, the result is its value. If ms milliseconds pass first, the result is None: a timeout is an outcome here, not an error. Giving up only stops the waiting; it does not cancel whatever is producing work, and a Worker is never stopped by a timeout. To stop the producers as well, combine the call with cancelAll on the group that runs them. If work has already failed, the failure is rethrown.

Parameters

work
The promise to wait for.
ms
The longest time to wait, in milliseconds.

Returns

The promise's value, or None when the time limit passed first.

Throws

CancelledException
when the waiting task is cancelled while it waits.

Examples

A value that arrives in time, and one that does not

Promise<int> fast = Promise();
std::sysTimerStart(5, 0, (n) => { fast.resolve(7); });
int? a = std::awaitTimeout(fast, 2000);
console.writeln(a ?? -1);
Promise<int> never = Promise();
int? b = std::awaitTimeout(never, 20);
console.writeln(b == None);
7
true

See also: TaskGroup

bodyLenOf

since 0.1.0-alpha.1linuxwindowswasm

bodyLenOf(HeaderMap hm) -> int

Reads the Content-Length header as a number.

Parameters

hm
The headers to look in.

Returns

The length, or -1 when the header is missing, empty, or contains anything other than digits.

Examples

HeaderMap present = std::parseHeaderLines("Content-Length: 42");
HeaderMap absent = std::parseHeaderLines("Host: example.com");
HeaderMap invalid = std::parseHeaderLines("Content-Length: abc");
console.writeln(std::bodyLenOf(present));
console.writeln(std::bodyLenOf(absent));
console.writeln(std::bodyLenOf(invalid));
42
-1
-1

byteToString

since 0.1.0-alpha.1linuxwindowswasm

byteToString(int b) -> string

Make a one-byte string from a byte value.

The result has length 1 and holds the single byte b. Use it to assemble strings from raw byte values, for example when building a binary protocol frame. For a character given as a Unicode code point use charFromCode.

Parameters

b
The byte value, from 0 to 255 inclusive.

Returns

A string of length 1 containing that byte.

Throws

RuntimeException
when b is outside 0..255.

Examples

console.writeln(std::byteToString(104) + std::byteToString(105));
console.writeln(std::byteToString(255).length());
try {
    std::byteToString(300);
} catch (RuntimeException e) {
    console.writeln("caught: ${e.message}");
}
hi
1
caught: byte value 300 out of range 0..255

See also: charFromCode

charFromCode

since 0.1.0-alpha.1linuxwindowswasm

charFromCode(int code) -> char

Make a char from a Unicode code point.

Valid code points run from 0 to 0x10FFFF, excluding the surrogate range 0xD800 to 0xDFFF. A char holds one code point, so the result can be any character, not just ASCII.

Parameters

code
The Unicode code point.

Returns

The char with that code point.

Throws

RuntimeException
when code is negative, above 0x10FFFF, or a surrogate.

Examples

char lambda = std::charFromCode(955);
console.writeln(lambda);
console.writeln(std::charFromCode(65));
console.writeln(lambda.code());
λ
A
955

See also: byteToString

chunkEncode

since 0.1.0-alpha.1linuxwindowswasm

chunkEncode(string data) -> string

Wraps text as one chunk of a chunked HTTP body.

The result is the length in hexadecimal, a carriage return and newline, the text, and another carriage return and newline. Finish the body with chunkEnd.

Parameters

data
The text to send as one chunk.

Returns

The framed chunk.

Examples

string framed = std::chunkEncode("hello");
console.writeln(framed.replace("\r\n", "|"));
console.writeln(std::chunkEncode("0123456789abcdef").replace("\r\n", "|"));
5|hello|
10|0123456789abcdef|

See also: chunkEnd, ChunkedDecoder

chunkEnd

since 0.1.0-alpha.1linuxwindowswasm

chunkEnd() -> string

Returns the zero-size chunk that ends a chunked HTTP body.

Returns

The terminating chunk, including the final blank line.

Examples

string body = std::chunkEncode("hi") + std::chunkEnd();
console.writeln(body.replace("\r\n", "|"));
2|hi|0||

See also: chunkEncode

connectTimeout

since 0.1.0-alpha.1linux

connectTimeout(string host, int port, int ms, (int) => void cb) -> void

Connect to a TCP server, giving up after a time limit.

The callback is called exactly once. On success it receives the descriptor of the connected, non-blocking socket, ready to wrap in a TcpStream. It receives -1 when the connection is refused, the host cannot be reached or looked up, the address is not valid, or ms milliseconds pass first. A descriptor that failed to connect is closed before the callback runs. A host name is looked up through the system resolver; an address containing : is read as IPv6.

Parameters

host
The host name or address to connect to.
port
The port number.
ms
The longest time to wait for the connection, in milliseconds.
cb
The function called with the connected descriptor, or -1 on failure.

Examples

std::connectTimeout("192.0.2.10", 8080, 2000, (fd) => {
    if (fd < 0) {
        console.writeln("connection failed or timed out");
    } else {
        console.writeln("connected");
        TcpStream(fd).close();
    }
});
not run — needs a network connection to a server

See also: TcpStream

cpuCount

since 0.1.0-alpha.1linuxwindowswasm

cpuCount() -> int

Count the logical processors that are online.

Use it to size a pool of workers. The result is at least 1.

Returns

The number of online logical processors.

Examples

int n = std::cpuCount();
console.writeln(n >= 1);
true

See also: spawn

every

since 0.1.0-alpha.1linuxwindows

every(int ms) -> Timer

Start a repeating timer.

The first tick comes after ms milliseconds and so does every later one, until the timer is cancelled.

Parameters

ms
The interval between ticks, in milliseconds.

Returns

The running timer.

Examples

Timer t = std::every(5);
t.subscribe((n) => {
    console.writeln("tick ${n}");
    if (n == 3) { t.cancel(); }
});
tick 1
tick 2
tick 3

See also: after

fileExists

since 0.1.0-alpha.1linux

fileExists(string path) -> bool

Tells whether a file or directory exists at a path, without opening it.

Parameters

path
The path to check.

Returns

true when something exists at path.

Examples

console.writeln(std::fileExists("/dev/null"));
console.writeln(std::fileExists("/no/such/path"));
true
false

See also: isDir

fileModified

since 0.1.0-alpha.1linux

fileModified(string path) -> int

Returns the time a file was last changed, as seconds since 1 January 1970.

Parameters

path
The path to check.

Returns

The modification time in whole seconds, or -1 when nothing exists at path.

Examples

console.writeln(std::fileModified("/dev/null") > 0);
console.writeln(std::fileModified("/no/such/path"));
true
-1

fileSize

since 0.1.0-alpha.1linux

fileSize(string path) -> int

Returns the size in bytes of the file at a path, without opening it.

Parameters

path
The path to check.

Returns

The size in bytes, or -1 when nothing exists at path.

Examples

console.writeln(std::fileSize("/dev/null"));
console.writeln(std::fileSize("/no/such/path"));
0
-1

import

since 0.1.0-alpha.1linuxwindowswasm

import(string path) -> string

Read a file at compile time and return its content as a string.

import only does its job during compilation: a call such as comptime string page = import("views/index.html"); is replaced by the content of that file, and the file becomes a declared input of the build. In a project the file must be listed in the manifest's assets; a program compiled as a single file looks next to its own source file. The path is project-relative and /-separated, with no leading /, no \ and no . or .. segment.

Called while the program is running, import throws, because there is nothing left to read the file at that point.

Parameters

path
The project-relative path of the file to include.

Returns

The content of the file as a string.

Throws

RuntimeException
when called at run time instead of at compile time.

Examples

Calling it at run time fails loudly

try {
    string text = std::import("notes.txt");
    console.writeln(text);
} catch (RuntimeException e) {
    console.writeln("import is a compile-time construct");
}
import is a compile-time construct

isDir

since 0.1.0-alpha.1linux

isDir(string path) -> bool

Tells whether a path is a directory.

Parameters

path
The path to check.

Returns

true when path is a directory; false for a file, or when nothing exists there.

Examples

console.writeln(std::isDir("/"));
console.writeln(std::isDir("/dev/null"));
console.writeln(std::isDir("/no/such/path"));
true
false
false

See also: fileExists

max

since 0.1.0-alpha.1linuxwindowswasm

max(Array<int> a) -> int | None

Find the largest element of an integer array.

The result is optional: an empty array has no largest element, so it gives None. Use ?? to supply a fallback. The same name is overloaded for Array<float>.

Parameters

a
The numbers to search.

Returns

The largest element, or None when the array is empty.

Examples

Array<int> a = [4, 8, 15, 16, 23, 42];
console.writeln(std::max(a) ?? -1);
Array<int> empty = [];
int? none = std::max(empty);
console.writeln(none == None);
console.writeln(std::max([2.5, 1.5]) ?? 0.0);
42
true
2.500000
max(Array<float> a) -> float | None

Find the largest element of a float array.

Same as the Array<int> overload, but for floats. An empty array gives None.

Parameters

a
The numbers to search.

Returns

The largest element, or None when the array is empty.

See also: min

min

since 0.1.0-alpha.1linuxwindowswasm

min(Array<int> a) -> int | None

Find the smallest element of an integer array.

The result is optional: an empty array has no smallest element, so it gives None. Use ?? to supply a fallback. The same name is overloaded for Array<float>.

Parameters

a
The numbers to search.

Returns

The smallest element, or None when the array is empty.

Examples

Array<int> a = [4, 8, 15, 16, 23, 42];
console.writeln(std::min(a) ?? -1);
Array<int> empty = [];
int? none = std::min(empty);
console.writeln(none == None);
console.writeln(std::min([2.5, 1.5]) ?? 0.0);
4
true
1.500000
min(Array<float> a) -> float | None

Find the smallest element of a float array.

Same as the Array<int> overload, but for floats. An empty array gives None.

Parameters

a
The numbers to search.

Returns

The smallest element, or None when the array is empty.

See also: max

overflowBlock

since 0.1.0-alpha.1linuxwindowswasm

overflowBlock() -> int

The overflow policy that makes a full channel hold the sender back.

A channel is created with a capacity and a policy for what happens when it is full. With this policy the sender waits until the receiver makes room, which is backpressure. Pass the result as the second argument of the Channel constructor.

Returns

The policy value to pass to Channel.

Examples

A producer held back by a small channel

Channel<int> ch = Channel(2, std::overflowBlock());
Worker<int> producer = std::spawn(() => {
    for (int i in 1..5) ch.send(i * 10);
    ch.close();
    return 5;
});
int? item = await ch.receive();
while (item != None) {
    console.writeln("received ${item}");
    item = await ch.receive();
}
console.writeln("producer sent ${await producer}");
received 10
received 20
received 30
received 40
received 50
producer sent 5

See also: Channel

overflowDrop

since 0.1.0-alpha.1linuxwindowswasm

overflowDrop() -> int

The overflow policy that discards new values when a channel is full.

The value being sent is dropped silently, and the values already queued are kept. Pass the result as the second argument of the Channel constructor.

Returns

The policy value to pass to Channel.

Examples

Channel<int> ch = Channel(2, std::overflowDrop());
ch.send(1);
ch.send(2);
ch.send(3);
ch.close();
int? x = await ch.receive();
while (x != None) {
    console.writeln("kept ${x}");
    x = await ch.receive();
}
kept 1
kept 2

See also: Channel

overflowError

since 0.1.0-alpha.1linuxwindowswasm

overflowError() -> int

The overflow policy that makes sending to a full channel throw.

Pass the result as the second argument of the Channel constructor.

Returns

The policy value to pass to Channel.

Examples

Channel<int> ch = Channel(1, std::overflowError());
ch.send(10);
try {
    ch.send(11);
} catch (RuntimeException e) {
    console.writeln("caught: ${e.message}");
}
caught: channel overflow

See also: Channel

parseHeaderLines

since 0.1.0-alpha.1linuxwindowswasm

parseHeaderLines(string block) -> HeaderMap

Reads a block of Name: value lines into a HeaderMap.

Lines are separated by a carriage return and a newline. A line without a colon, or with an empty name, is skipped, and names and values are trimmed of surrounding spaces. Repeated names are all kept.

Parameters

block
The header lines, without the start line and without the blank line that ends the headers.

Returns

A map holding the headers in the order they appeared.

Examples

string block = "Host: example.com\r\nAccept:  text/html \r\nnot a header\r\nSet-Cookie: a=1\r\nset-cookie: b=2";
HeaderMap headers = std::parseHeaderLines(block);
console.writeln(headers.length());
console.writeln(headers.first("accept"));
console.writeln(headers.all("Set-Cookie").length());
4
text/html
2

See also: HeaderMap

spawn

since 0.1.0-alpha.1linux

spawn<T>(() => T body) -> Worker<T>

Run a function as a worker and return a handle to its result.

The body's captured variables are copied when spawn is called, so changing the originals afterwards does not affect the worker. The result is copied back when the worker is awaited. If the body throws, the worker fails and await rethrows the failure as a RuntimeException carrying the message. Pass a closure; anything else makes spawn itself throw.

On Linux the body runs on a separate operating-system thread. Do not print from inside the body; return the result and print it after the join.

Parameters

body
The function the worker runs.

Returns

A Worker that settles with the body's result.

Examples

Joining a failing worker

Worker<int> bad = std::spawn(() => {
    throw RuntimeException("worker failed");
    return 0;
});
try {
    int r = await bad;
} catch (RuntimeException e) {
    console.writeln("caught: ${e.message}");
}
Worker<int> good = std::spawn(() => 6 * 7);
console.writeln(await good);
caught: worker failed
42

See also: Worker

sum

since 0.1.0-alpha.1linuxwindowswasm

sum(Array<int> a) -> int

Add up the elements of an integer array.

The sum of an empty array is 0. The same name is overloaded for Array<float>; the overload is chosen by the element type.

Parameters

a
The numbers to add.

Returns

The sum of all elements.

Examples

Array<int> a = [4, 8, 15, 16, 23, 42];
console.writeln(std::sum(a));
Array<int> none = [];
console.writeln(std::sum(none));
console.writeln(std::sum([0.5, 0.25]));
108
0
0.750000
sum(Array<float> a) -> float

Add up the elements of a float array.

Same as the Array<int> overload, but the result is a float. The sum of an empty array is 0.0.

Parameters

a
The numbers to add.

Returns

The sum of all elements.

sysReadLine

since 0.1.0-alpha.1linuxwindows

sysReadLine(int fd) -> string

Read one line of text from a file descriptor, without its trailing newline.

The newline that ends the line is consumed and not included in the result. A last line that has no newline is returned as it is. At end of input the result is the empty string, which is also what an empty line gives, so loop until you have what you need rather than treating "" as the only sign of the end. Most programs read standard input through this function.

Parameters

fd
The descriptor to read from; 0 is standard input.

Returns

The next line, or "" at end of input.

Examples

Echoing every line in upper case

string line = std::sysReadLine(0);
while (line != "") {
    console.writeln(line.toUpper());
    line = std::sysReadLine(0);
}
console.writeln("end of input");
alpha
beta
ALPHA
BETA
end of input

sysTimerStart

since 0.1.0-alpha.1linuxwindows

sysTimerStart(int delayMs, int intervalMs, (int) => void cb) -> int

Schedule a callback on the event loop, once or repeatedly.

The callback runs after delayMs milliseconds. When intervalMs is greater than zero it then runs again every intervalMs milliseconds until the timer is cancelled; with 0 the timer fires once and releases itself. The callback receives the tick number, which counts from 1. The program does not exit while a timer is pending. Timers that are due run in order of their due time, and timers due at the same moment run in the order they were created, so the order of output below does not depend on how busy the machine is.

Most programs use the Timer class with after and every instead of calling this function.

Parameters

delayMs
Milliseconds until the first call.
intervalMs
Milliseconds between later calls; 0 for a one-shot timer.
cb
The callback; it receives the tick number, starting at 1.

Returns

A timer id that identifies the timer for cancelling.

Examples

Timers fire in the order they are due

std::sysTimerStart(30, 0, (n) => { console.writeln("third"); });
std::sysTimerStart(10, 0, (n) => { console.writeln("first"); });
std::sysTimerStart(20, 0, (n) => { console.writeln("second"); });
console.writeln("registered");
registered
first
second
third

See also: Timer

tlsAccept

since 0.1.0-alpha.1linux

tlsAccept(int fd, string cert, string key, string alpn, int deadlineMs, (int) => void cb) -> void

Secure an accepted client connection with TLS, with a deadline.

This is the function form of TlsAccept. The callback is called once: with the descriptor when the handshake completes, or with -1 when it fails, the certificate or key cannot be used, or the deadline passes. In the failure cases the descriptor is closed. It never throws.

Parameters

fd
The descriptor of an accepted client connection.
cert
The path of the server's certificate file in PEM format.
key
The path of the server's private key file in PEM format.
alpn
The application protocols to accept, comma separated; "" for none.
deadlineMs
The longest time the client may take to finish the handshake, in milliseconds.
cb
The function called with the descriptor on success, or with -1 when the client is dropped.

Examples

A descriptor that is not connected is dropped

std::tlsAccept(-1, "server.pem", "server.key", "", 1000, (r) => {
    console.writeln("accept result ${r}");
});
console.writeln("after tlsAccept");
accept result -1
after tlsAccept

See also: TlsAccept

tlsConnect

since 0.1.0-alpha.1linux

tlsConnect(int fd, string host, string alpn, string caFile, int verifyMode, (int) => void cb) -> void

Start TLS on a connected client socket and wait for the handshake to finish.

The call arms TLS on the socket, drives the handshake, and then calls cb with the descriptor, after which the same descriptor carries encrypted traffic, so a TcpStream over it needs no other change. The server's certificate is checked before any protocol data is exchanged. A failure to set up the session throws a RuntimeException whose message starts with TLS handshake: and names the reason, the host and the descriptor. A handshake that fails later, for example because the certificate does not verify or does not match host, throws the same exception when the handshake ends.

verifyMode chooses how much is checked: 0 verifies the certificate chain and the host name, 1 verifies the chain only, and 2 encrypts without verifying anything, which should only be used on purpose and never as a default.

Parameters

fd
The descriptor of a connected socket.
host
The host name to verify the certificate against and to send as the server name.
alpn
The application protocols to offer, comma separated, such as "h2,http/1.1"; "" offers none.
caFile
A file of additional trusted certificates; "" uses only the system's trusted roots.
verifyMode
0 to verify chain and host name, 1 for chain only, 2 for no verification.
cb
The function called with the descriptor once the handshake has completed.

Throws

RuntimeException
when TLS cannot be set up on the descriptor or the handshake fails.

Examples

A descriptor that is not connected is refused

try {
    std::tlsConnect(-1, "example.com", "", "", 0, (fd) => { console.writeln("connected"); });
} catch (RuntimeException e) {
    console.writeln(e.message.startsWith("TLS handshake:"));
}
true

See also: TlsDrive

tlsDrive

since 0.1.0-alpha.1linux

tlsDrive(int fd, (int) => void cb) -> void

Drive the TLS handshake of a descriptor that is already armed.

This is the function form of TlsDrive. The callback is called once, with the descriptor when the handshake completes and with -1 when it fails. It does not throw.

Parameters

fd
The descriptor of a socket that was already armed for TLS.
cb
The function called with the descriptor on success, or with -1 on failure.

Examples

A descriptor that is not connected fails the handshake

std::tlsDrive(-1, (r) => { console.writeln("handshake result ${r}"); });
console.writeln("after tlsDrive");
handshake result -1
after tlsDrive

See also: TlsDrive

Bindings

IClock

since 0.1.0-alpha.1linuxwindowswasm

bind IClock

The default binding for IClock: a new SystemClock for each injection.

It is inert until a program names the interface with use std::IClock;; the default is never active just because the name is visible.

IConsole

since 0.1.0-alpha.1linuxwindowswasm

The default binding for IConsole: a new SystemConsole for each injection.

It is inert until a program names the interface with use std::IConsole;; the default is never active just because the name is visible.

IEnv

since 0.1.0-alpha.1linuxwindowswasm

bind IEnv

The default binding for IEnv: a new SystemEnv for each injection.

It is inert until a program names the interface with use std::IEnv;; the default is never active just because the name is visible.

IFileSystem

since 0.1.0-alpha.1linuxwindowswasm

The default binding for IFileSystem: a new SystemFileSystem for each injection.

It is inert until a program names the interface with use std::IFileSystem;; the default is never active just because the name is visible.

INet

since 0.1.0-alpha.1linuxwindowswasm

bind INet

The default binding for INet: a new SystemNet for each injection.

It is inert until a program names the interface with use std::INet;; the default is never active just because the name is visible.