Library reference
Every public name in the library, with signatures taken from its source. For an overview with examples, see Library.
view means the function only reads, edit means it changes the value, and a type with neither means the value is handed over. A temporary cannot be passed to view yet, so bind it to a name first.
std/text Text
Numbers to text and back, searching, splitting, replacing, and whole text files. Text is UTF-8 and positions count bytes.
import "std/text.kon" as text
of(literal: str): StringThe literal as an owned String.
empty(): StringEmpty text.
copy(value: view String): StringA separate copy.
fromBytes(bytes: view List<u8>): Option<String>Text from bytes, or none if they are not valid UTF-8.
toBytes(value: view String): List<u8>The text as a list of bytes.
fromUint(value: u64): StringA whole number as text.
fromInt(value: i64): StringA whole number as text.
fromFloat(value: f64, decimals: u32): Option<String>Fixed decimals, up to 9, rounded half up. None for NaN, infinities, 1e15 and above, or too many decimals.
parseUint(value: view String): Option<u64>Digits only. None for anything else, for no digits, or for too large a value.
parseInt(value: view String): Option<i64>An optional sign, then digits. None otherwise, or if too large.
parseFloat(value: view String): Option<f64>Like 12, -1.5, .25 or 2.5e3, rounded correctly. None for anything else, including inf, nan and values too large for f64.
fromFloatShortest(value: f64): Option<String>The shortest text that reads back as exactly this value, as 0.1 or 1e+300. None for NaN and infinities.
equal(first: view String, second: view String): boolWhether two texts are the same.
isText(value: view String, literal: str): boolWhether the text is exactly this literal.
compare(first: view String, second: view String): i32Below zero, zero or above zero, comparing bytes, which is code point order.
startsWith(value: view String, needle: view String): boolWhether it begins with needle.
endsWith(value: view String, needle: view String): boolWhether it ends with needle.
findFrom(value: view String, needle: view String, start: u64): Option<u64>The first position at or after start, if any. An empty needle is found at start.
find(value: view String, needle: view String): Option<u64>The first position, if any.
contains(value: view String, needle: view String): boolWhether needle appears anywhere.
substring(value: view String, start: u64, end: u64): Option<String>The bytes from start up to end. None if out of range or if that would cut a character in two.
trim(value: view String): StringWithout spaces, tabs and line ends at either end.
split(value: view String, separator: view String): List<String>The pieces between separators, keeping empty ones. An empty separator gives the whole text as one piece.
lines(value: view String): List<String>One piece per line, for \n and \r\n endings. A final line end does not add an empty line.
join(pieces: view List<String>, separator: view String): StringThe pieces with the separator between them.
replace(value: view String, old: view String, replacement: view String): StringEvery occurrence of old changed to replacement. An empty old changes nothing.
toLowerAscii(value: view String): StringA to Z only: other letters, such as Vietnamese ones, stay as they are.
toUpperAscii(value: view String): Stringa to z only.
readFile(path: str): Option<String>The whole file. None if it cannot be read or is not valid UTF-8.
writeFile(path: str, value: view String): boolCreates or replaces a file. It appears complete or not at all.
appendFile(path: str, value: view String): boolAdds to the end of a file.
readFileAt(path: view String): Option<String>readFile with a path built at run time.
writeFileAt(path: view String, value: view String): boolwriteFile with a path built at run time.
argument(index: i32): Option<String>A program argument; number 0 is the program itself.
listDirectory(path: str): Option<List<String>>The names in a folder in sorted order. None if it cannot be read.
listDirectoryAt(path: view String): Option<List<String>>listDirectory with a path built at run time.
isDirectoryAt(path: view String): boolWhether this path is a folder.
std/json JSON
Read, change and write JSON, strictly by RFC 8259. A value is its number in the document, and a value that does not exist is 0, so lookups chain without checks.
import "std/json.kon" as json
struct DocumentEvery value of one JSON document.
isValid(view self): boolWhether parsing succeeded. A failed document has no values, and errorText says why.
errorText(view self, source: view String): StringLike "line 3, column 5: expected , or ] in a list". Empty if there is no error.
root(view self): u64The top value.
exists(view self, value: u64): boolWhether this value exists.
isNull(view self, value: u64): boolWhether it is null.
isBool(view self, value: u64): boolWhether it is true or false.
isNumber(view self, value: u64): boolWhether it is a number.
isText(view self, value: u64): boolWhether it is text.
isArray(view self, value: u64): boolWhether it is a list.
isObject(view self, value: u64): boolWhether it is an object.
numberOr(view self, value: u64, fallback: f64): f64The number, or the fallback.
intOr(view self, value: u64, fallback: i64): i64The number if it is whole and fits, otherwise the fallback.
boolOr(view self, value: u64, fallback: bool): boolThe true or false, or the fallback.
textOr(view self, value: u64, fallback: str): StringA copy of the text, or the fallback.
count(view self, value: u64): u64How many items a list or members an object has.
first(view self, value: u64): u64The first value of a list or object, for walking through it. 0 means there is none.
next(view self, value: u64): u64The value after this one. 0 means the end.
item(view self, value: u64, index: u64): u64An item of a list by position. This walks the list, so use first and next to go through all of them.
keyOf(view self, value: u64): StringThe key of an object's member, or empty text.
get(view self, value: u64, key: str): u64A member of an object. If a file repeats a key, the last one counts, as in JavaScript.
getAt(view self, value: u64, key: view String): u64get with a key built at run time.
newNull(edit self): u64Makes a null value.
newBool(edit self, value: bool): u64Makes true or false.
newNumber(edit self, value: f64): u64Makes a number.
newText(edit self, value: str): u64Makes text from a literal.
newTextOf(edit self, value: view String): u64Makes text from a String.
newArray(edit self): u64Makes an empty list.
newObject(edit self): u64Makes an empty object.
setRoot(edit self, value: u64)Chooses the top value.
push(edit self, list_: u64, value: u64): boolAdds to the end of a list. False if value already has a parent, or if this would put a value inside itself.
set(edit self, object: u64, key: str, value: u64): boolSets a member of an object, replacing one with the same key. False as for push.
setAt(edit self, object: u64, key: view String, value: u64): boolset with a key built at run time.
toText(view self, pretty: bool): Option<String>The root as JSON text, indented if pretty. None if there is no root, or it is nested over 1000 levels deep.
save(view self, path: str): boolWrites the root to a file, indented. It appears complete or not at all.
document(): DocumentA new document with no values and no root yet.
parse(source: view String): DocumentReads JSON text. Check isValid on the result.
load(path: str): DocumentReads a file. If it cannot be read, or its JSON is wrong, the document is not valid.
std/net Networking
TCP, UDP, host lookup, and a line-based server that handles many clients in one thread. Calls that can fail give none or false, and lastError says why. Sockets are closed with close, because Kon has no destructors yet.
import "std/net.kon" as net
lastError(): StringWhat the last failed call ran into, in a sentence.
struct AddressAn address and port.
toText(view self): StringAs text, like 127.0.0.1:80. An IPv6 address goes in brackets.
resolve(host: str): Option<List<String>>Every address of a host, numeric addresses and localhost included. None if it cannot be found.
struct TcpStreamA TCP connection. A read that reaches the other end's close gives nothing more.
read(edit self, out: edit List<u8>): i64Adds what is available to out, waiting for at least one byte unless the socket is non-blocking. The number of bytes; 0 at the end; -2 if none yet on a non-blocking socket; -1 on failure or timeout.
readToEnd(edit self): Option<List<u8>>Everything until the other end closes. None on failure or timeout.
readLine(edit self): Option<String>The next line without its line end. At the end, a last line with no line end, then none. None too on failure, timeout, text that is not UTF-8, or a line past one million bytes.
writeAll(edit self, bytes: view List<u8>): boolSends everything, waiting as needed. False on failure or timeout.
writeText(edit self, value: view String): boolSends text.
writeLine(edit self, value: view String): boolSends text followed by a line end.
setTimeout(edit self, millis: u32): boolHow long a read or write may wait, in milliseconds. 0 means no limit.
setNonBlocking(edit self, nonBlocking: bool): boolWhether calls return at once instead of waiting.
shutdownWrite(edit self): boolTells the other end nothing more is coming. Reading still works.
peerAddress(view self): Option<Address>The other end's address.
localAddress(view self): Option<Address>This end's address.
close(edit self): boolCloses it. False if it was already closed.
connect(host: str, port: u16): Option<TcpStream>Connects to a host name or address, trying each address it has. None on failure.
connectWithin(host: str, port: u16, timeoutMs: i32): Option<TcpStream>connect, giving up after this many milliseconds on each address.
connectAt(host: view String, port: u16): Option<TcpStream>connect with a host built at run time.
struct TcpListenerWaits for connections.
accept(edit self): Option<TcpStream>The next connection, waiting for one unless the listener is non-blocking. None on failure, or if none is waiting.
setNonBlocking(edit self, nonBlocking: bool): boolWhether accept returns at once instead of waiting.
localAddress(view self): Option<Address>Where it listens, including the port the system picked.
close(edit self): boolStops listening.
listen(address: str, port: u16): Option<TcpListener>Listens on an address: 127.0.0.1 for this machine only, 0.0.0.0 for all of them. Port 0 lets the system pick.
struct DatagramA datagram received: its bytes and where it came from.
textOf(view self): Option<String>Its bytes as text, or none if they are not UTF-8.
size(view self): u64How many bytes.
senderText(view self): StringWho sent it, as text.
senderPort(view self): u16The sender's port.
struct UdpSocketA UDP socket. Datagrams can be lost, repeated or arrive out of order.
sendTo(edit self, bytes: view List<u8>, address: str, port: u16): boolSends one datagram. False on failure; true does not mean it arrived.
receive(edit self): Option<Datagram>The next datagram, up to 65536 bytes. None on failure, on timeout, or if none is waiting on a non-blocking socket.
setTimeout(edit self, millis: u32): boolHow long receive may wait, in milliseconds. 0 means no limit.
setNonBlocking(edit self, nonBlocking: bool): boolWhether receive returns at once instead of waiting.
localAddress(view self): Option<Address>Where it is bound, including the port the system picked.
close(edit self): boolCloses it.
bindUdp(address: str, port: u16): Option<UdpSocket>Opens a UDP socket on an address. Port 0 lets the system pick.
waitReadable(stream: view TcpStream, millis: i32): boolWaits until a stream has data, up to this many milliseconds. False after the time, or on failure.
struct EventSomething that happened on a Server.
isConnected(view self): boolA client connected.
isLine(view self): boolA client sent a line.
isDisconnected(view self): boolA client is gone.
clientId(view self): u64Which client, a number that is never reused.
lineText(view self): StringThe line received, without its line end. Empty for other events.
struct ServerA server for line-based protocols: many clients in one thread, none able to hold up the others.
clientCount(view self): u64How many clients are connected.
localAddress(view self): Option<Address>Where it listens, including the port the system picked.
setIdleTimeout(edit self, millis: i64)Disconnects a client that sends nothing for this long, counted while poll waits. 0, the default, never does.
setMaxLine(edit self, bytes: u64)Disconnects a client whose line passes this many bytes, 65536 by default.
sendLine(edit self, client: u64, line: view String): boolQueues a line for a client. False if there is no such client.
broadcast(edit self, line: view String, except: u64): u64Queues a line for every client but one; pass 0 to leave nobody out. How many it was queued for.
disconnect(edit self, client: u64): boolDisconnects a client once what is queued for it has gone. False if there is no such client.
clientAddress(view self, client: u64): Option<String>The other end's address, as text.
poll(edit self, timeoutMs: i32): List<Event>Does what can be done now, waiting up to this many milliseconds, and says what happened. A negative wait has no limit. Call it in a loop.
close(edit self)Closes every client and the listener.
serve(address: str, port: u16): Option<Server>Starts a line-based server. Port 0 lets the system pick.
std/hash Hashing
SHA-256, for telling whether content has changed. A match says the bytes are the same, nothing about whether they can be trusted.
import "std/hash.kon" as hash
sha256(bytes: view List<u8>): StringThe SHA-256 of the bytes, as 64 lowercase hex digits.
sha256Text(value: view String): StringThe SHA-256 of a text's UTF-8 bytes.
std/sys System
Files as bytes, folders, clocks and program arguments. Most programs want std/text on top of it.
import "std/sys.kon" as sys
readFile(path: str, out: edit List<u8>): boolReplaces out with the file's bytes. False if it cannot be read, leaving out empty.
writeFile(path: str, data: view List<u8>): boolCreates or replaces a file. It appears complete or not at all, so a crash cannot leave half a save.
appendFile(path: str, data: view List<u8>): boolAdds to the end of a file.
exists(path: str): boolWhether something is at this path.
removeFile(path: str): boolDeletes a file.
makeDirectory(path: str): boolCreates a folder; true if it already exists. The parent must exist.
makeDirectoryAt(path: view List<u8>): boolmakeDirectory with a path built at run time.
removeDirectoryAt(path: view List<u8>): boolRemoves an empty folder.
removeFileAt(path: view List<u8>): boolremoveFile with a path built at run time.
readFileAt(path: view List<u8>, out: edit List<u8>): boolreadFile with a path built at run time, as UTF-8 bytes.
writeFileAt(path: view List<u8>, data: view List<u8>): boolwriteFile with a path built at run time.
existsAt(path: view List<u8>): boolexists with a path built at run time.
isDirectory(path: str): boolWhether this path is a folder.
isDirectoryAt(path: view List<u8>): boolisDirectory with a path built at run time.
listDirectory(path: str): i32Reads a folder's names, sorted and without . and .., for entryName and entryIsDirectory. The number of names, or -1 if it cannot be read. The next listing replaces them.
listDirectoryAt(path: view List<u8>): i32listDirectory with a path built at run time.
entryName(index: i32, out: edit List<u8>): boolReplaces out with a name's UTF-8 bytes. False if there is no such entry.
entryIsDirectory(index: i32): boolWhether that entry is a folder.
isWindows(): boolWhether the program is running on Windows.
commandBegin()Starts a new command for runCommand.
commandArgument(value: view List<u8>)Adds one argument; the first is the program. A zero byte makes the command impossible to start.
runCommand(keep: bool, output: edit List<u8>): boolRuns the command and waits. False if it could not start. With keep, its output and errors go into output together.
commandExitCode(): i32The exit code of the last command that ran.
addFloat(out: edit List<u8>, value: f64)Adds the shortest decimal text that reads back as exactly this finite value.
readFloat(number: view List<u8>): f64The value of a plain decimal number such as -1.5e3, rounded correctly. A number too large for f64 is infinite.
addText(out: edit List<u8>, text: str)Adds a literal's bytes to a list, for building paths and file contents.
monotonicMillis(): i64Milliseconds on a clock that never goes backward; only differences mean anything.
unixMillis(): i64Milliseconds since 1970 by the system clock, which can jump.
sleepMillis(milliseconds: i32)Waits this long.
argumentCount(): i32How many program arguments there are; number 0 is the program itself.
argument(index: i32, out: edit List<u8>): boolReplaces out with an argument's UTF-8 bytes. False if there is no such argument.
std/path Paths
File paths as text. Both / and \ separate on Windows, and only / elsewhere. Only walk touches the disk, and nothing resolves . or ..
import "std/path.kon" as paths
isAbsolute(value: view String): boolWhether the path starts from a root.
join(first: view String, second: view String): StringThe second path under the first, unless the second is absolute or has a drive, which replaces the first.
baseName(value: view String): StringThe last name: game.kon from a/b/game.kon, and b from a/b/.
parent(value: view String): StringThe folder above: a/b from a/b/game.kon. Empty if there is none written. A root is its own parent.
extension(value: view String): StringThe extension with its dot: .gz from a.tar.gz, and empty text if there is none.
stem(value: view String): StringThe last name without its extension: a.tar from a.tar.gz.
walk(folder: view String): Option<List<String>>Every file under a folder and the folders inside it, in sorted order. None if a folder cannot be read or the tree is over 64 levels deep.
std/args Command line
The command line. --name is a flag, --name=value carries a value, and anything else is a plain word, kept in order. After -- everything is a plain word.
import "std/args.kon" as args
struct ArgumentsA parsed command line.
has(view self, name: str): boolWhether this flag was given.
valueOr(view self, name: str, fallback: str): StringThe value of --name=value, or the fallback if it is absent or has no value.
count(view self): u64How many plain words there are.
positional(view self, index: u64): Option<String>A plain word by position, or none.
parse(list_: view List<String>): ArgumentsReads a list of arguments, without the program's own name.
read(): ArgumentsThe arguments this program was started with.
std/process Processes
Run another program and wait for it. No shell is involved, so spaces and symbols in an argument reach the program as they are.
import "std/process.kon" as process
struct FinishedWhat happened to a program that was run.
didStart(view self): boolWhether the program could be started at all.
succeeded(view self): boolWhether it started and exited with 0.
exitCode(view self): i32Its exit code, or -1 if it did not start.
outputText(view self): StringWhat it printed, output and errors together, when run by runKept. Empty text if that is not valid UTF-8.
outputBytes(view self): List<u8>The same as raw bytes.
command(program: str): List<String>A command list with the program first. Add arguments to it. A name without a folder is looked for on PATH.
run(parts: view List<String>): FinishedRuns it with its output going to this program's, and waits.
runKept(parts: view List<String>): FinishedRuns it with its output kept in the result, and waits.
std/map Generic table
A generic hash table. No iteration order is promised. Keys from untrusted sources need a hash that resists attack.
import "std/map.kon" as map
struct MapA table from K to V.
count(view self): u64Number of entries.
get(view self, wanted: view K): Option<view V> from selfA view of the value for this key, or none.
insert(edit self, ownedKey: K, value: V): Option<V>Sets the key to the value, and returns the value it replaced, if any.
remove(edit self, wanted: view K): Option<V>Removes the key, and returns its value, if it was present.
map<K, V>(): Map<K, V> where K: key.Hash + key.EqualA new empty table.
std/interfaces Map keys
What a type implements to be a Map key.
import "std/interfaces.kon" as interfaces
interface HashA type that gives a hash: func hash(view self): u64
interface EqualA type that can be compared: func equals(view self, other: view Self): bool
std/intmap Integer table
A hash table from i64 to i64, with open addressing.
import "std/intmap.kon" as intmap
struct IntMapThe table.
count(view self): u64Number of entries.
contains(view self, key: i64): boolWhether the key is present.
get(view self, key: i64): Option<i64>The value for key, or none.
insert(edit self, key: i64, value: i64): Option<i64>Sets key to value, and returns the value it replaced, if any.
remove(edit self, key: i64): Option<i64>Removes key, and returns its value, if it was present.
intMap(): IntMapA new empty table.
std/intset Integer set
A set of i64, built on IntMap.
import "std/intset.kon" as intset
struct IntSetThe set.
count(view self): u64Number of values.
contains(view self, value: i64): boolWhether the value is present.
add(edit self, value: i64): boolAdds value, and returns whether it was new.
remove(edit self, value: i64): boolRemoves value, and returns whether it was present.
intSet(): IntSetA new empty set.
std/deque Queue
A queue of i64 with fast adds and removals at both ends.
import "std/deque.kon" as deque
struct IntDequeThe queue.
count(view self): u64Number of items.
pushBack(edit self, value: i64)Adds at the back.
pushFront(edit self, value: i64)Adds at the front.
popFront(edit self): Option<i64>Removes from the front, or none if empty.
popBack(edit self): Option<i64>Removes from the back, or none if empty.
get(view self, index: u64): Option<i64>The item at a position counted from the front, or none.
intDeque(): IntDequeA new empty queue.
std/heap Priority queue
A priority queue. Items are i64 values with an i64 priority, and the lowest priority comes out first.
import "std/heap.kon" as heap
struct MinHeapThe queue.
count(view self): u64Number of items.
push(edit self, priority: i64, value: i64)Adds a value with its priority.
pop(edit self): Option<i64>The value with the lowest priority, removed from the heap, or none.
minHeap(): MinHeapA new empty queue.
std/grid Grid
A 2D map of i64 cells with shortest paths, for tile maps, boards and mazes.
import "std/grid.kon" as grid
struct GridThe map.
gridWidth(view self): i64Its width.
gridHeight(view self): i64Its height.
inside(view self, x: i64, y: i64): boolWhether a cell is on the map.
get(view self, x: i64, y: i64, fallback: i64): i64The cell's value; outside the grid, the given fallback.
set(edit self, x: i64, y: i64, value: i64)Sets a cell. Writing outside the grid is ignored.
fill(edit self, value: i64)Sets every cell.
findPath(edit self, startX: i64, startY: i64, goalX: i64, goalY: i64, open: i64): i64Finds a shortest path over cells equal to open, moving up, down, left and right. Its steps are then in routeX and routeY.
routeLength(view self): u64Steps in the last path.
routeX(view self, step: u64): i64X of a step of the last path, numbered from the start.
routeY(view self, step: u64): i64Y of a step of the last path.
grid(width: i64, height: i64, value: i64): GridA new map with every cell set to value.
std/sort Sorting
Sorting lists in place.
import "std/sort.kon" as sort
sortI64(values: edit List<i64>)Sorts ascending, O(n log n) in the worst case.
isSorted(values: view List<i64>): boolWhether the list is in ascending order.
std/math Integer math
Integer math, including sine and cosine scaled to integers.
import "std/math.kon" as math
minI64(a: i64, b: i64): i64The smaller one.
maxI64(a: i64, b: i64): i64The larger one.
clampI64(value: i64, low: i64, high: i64): i64Value kept between low and high.
absI64(value: i64): i64Without its sign.
gcd(first: u64, second: u64): u64Greatest common divisor; gcd(0, 0) is 0.
isqrt(value: u64): u64The largest r with r * r <= value.
powI64(base: i64, exponent: u64): i64Integer power. Overflow wraps, like other integer arithmetic.
sinDegrees(angle: i64): i64Sine of an angle in degrees, scaled so 1000 means 1.0, accurate to about 0.2%.
cosDegrees(angle: i64): i64Cosine, scaled the same way.
std/fixed Fixed point
Fixed-point numbers: an i64 holding a value times 65536, so fractions work without floats. Add and subtract with plain + and -.
import "std/fixed.kon" as fixed
one(): i64The value 1.
fromInt(value: i64): i64A whole number as fixed-point.
toInt(value: i64): i64To a whole number, rounding toward negative infinity.
fromRatio(numerator: i64, denominator: i64): i64numerator / denominator; fromRatio(3, 2) is 1.5.
mul(a: i64, b: i64): i64Multiplies.
div(a: i64, b: i64): i64Divides.
sqrt(value: i64): i64Square root; a negative value gives 0.
lerp(a: i64, b: i64, t: i64): i64The value part way from a to b; t runs from 0 to one().
sinDegrees(angle: i64): i64Sine of an angle in whole degrees.
cosDegrees(angle: i64): i64Cosine of an angle in whole degrees.
length(x: i64, y: i64): i64The length of the vector (x, y).
std/random Random numbers
A small, fast, repeatable generator. Good for games and simulation, not for security.
import "std/random.kon" as random
struct RandomThe generator.
next(edit self): u64The next value over all of u64.
below(edit self, limit: u64): u64A value from 0 up to, but not including, limit. A limit of 0 gives 0.
between(edit self, low: i64, high: i64): i64A value from low up to and including high.
chance(edit self, percent: u64): boolTrue with a chance of percent in 100.
random(seed: u64): RandomThe same seed gives the same sequence.