KonLang Tiếng Việt

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): String

The literal as an owned String.

empty(): String

Empty text.

copy(value: view String): String

A 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): String

A whole number as text.

fromInt(value: i64): String

A 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): bool

Whether two texts are the same.

isText(value: view String, literal: str): bool

Whether the text is exactly this literal.

compare(first: view String, second: view String): i32

Below zero, zero or above zero, comparing bytes, which is code point order.

startsWith(value: view String, needle: view String): bool

Whether it begins with needle.

endsWith(value: view String, needle: view String): bool

Whether 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): bool

Whether 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): String

Without 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): String

The pieces with the separator between them.

replace(value: view String, old: view String, replacement: view String): String

Every occurrence of old changed to replacement. An empty old changes nothing.

toLowerAscii(value: view String): String

A to Z only: other letters, such as Vietnamese ones, stay as they are.

toUpperAscii(value: view String): String

a 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): bool

Creates or replaces a file. It appears complete or not at all.

appendFile(path: str, value: view String): bool

Adds 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): bool

writeFile 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): bool

Whether 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 Document

Every value of one JSON document.

isValid(view self): bool

Whether parsing succeeded. A failed document has no values, and errorText says why.

errorText(view self, source: view String): String

Like "line 3, column 5: expected , or ] in a list". Empty if there is no error.

root(view self): u64

The top value.

exists(view self, value: u64): bool

Whether this value exists.

isNull(view self, value: u64): bool

Whether it is null.

isBool(view self, value: u64): bool

Whether it is true or false.

isNumber(view self, value: u64): bool

Whether it is a number.

isText(view self, value: u64): bool

Whether it is text.

isArray(view self, value: u64): bool

Whether it is a list.

isObject(view self, value: u64): bool

Whether it is an object.

numberOr(view self, value: u64, fallback: f64): f64

The number, or the fallback.

intOr(view self, value: u64, fallback: i64): i64

The number if it is whole and fits, otherwise the fallback.

boolOr(view self, value: u64, fallback: bool): bool

The true or false, or the fallback.

textOr(view self, value: u64, fallback: str): String

A copy of the text, or the fallback.

count(view self, value: u64): u64

How many items a list or members an object has.

first(view self, value: u64): u64

The first value of a list or object, for walking through it. 0 means there is none.

next(view self, value: u64): u64

The value after this one. 0 means the end.

item(view self, value: u64, index: u64): u64

An 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): String

The key of an object's member, or empty text.

get(view self, value: u64, key: str): u64

A 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): u64

get with a key built at run time.

newNull(edit self): u64

Makes a null value.

newBool(edit self, value: bool): u64

Makes true or false.

newNumber(edit self, value: f64): u64

Makes a number.

newText(edit self, value: str): u64

Makes text from a literal.

newTextOf(edit self, value: view String): u64

Makes text from a String.

newArray(edit self): u64

Makes an empty list.

newObject(edit self): u64

Makes an empty object.

setRoot(edit self, value: u64)

Chooses the top value.

push(edit self, list_: u64, value: u64): bool

Adds 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): bool

Sets 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): bool

set 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): bool

Writes the root to a file, indented. It appears complete or not at all.

document(): Document

A new document with no values and no root yet.

parse(source: view String): Document

Reads JSON text. Check isValid on the result.

load(path: str): Document

Reads 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(): String

What the last failed call ran into, in a sentence.

struct Address

An address and port.

toText(view self): String

As 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 TcpStream

A TCP connection. A read that reaches the other end's close gives nothing more.

read(edit self, out: edit List<u8>): i64

Adds 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>): bool

Sends everything, waiting as needed. False on failure or timeout.

writeText(edit self, value: view String): bool

Sends text.

writeLine(edit self, value: view String): bool

Sends text followed by a line end.

setTimeout(edit self, millis: u32): bool

How long a read or write may wait, in milliseconds. 0 means no limit.

setNonBlocking(edit self, nonBlocking: bool): bool

Whether calls return at once instead of waiting.

shutdownWrite(edit self): bool

Tells 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): bool

Closes 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 TcpListener

Waits 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): bool

Whether accept returns at once instead of waiting.

localAddress(view self): Option<Address>

Where it listens, including the port the system picked.

close(edit self): bool

Stops 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 Datagram

A 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): u64

How many bytes.

senderText(view self): String

Who sent it, as text.

senderPort(view self): u16

The sender's port.

struct UdpSocket

A UDP socket. Datagrams can be lost, repeated or arrive out of order.

sendTo(edit self, bytes: view List<u8>, address: str, port: u16): bool

Sends 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): bool

How long receive may wait, in milliseconds. 0 means no limit.

setNonBlocking(edit self, nonBlocking: bool): bool

Whether 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): bool

Closes 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): bool

Waits until a stream has data, up to this many milliseconds. False after the time, or on failure.

struct Event

Something that happened on a Server.

isConnected(view self): bool

A client connected.

isLine(view self): bool

A client sent a line.

isDisconnected(view self): bool

A client is gone.

clientId(view self): u64

Which client, a number that is never reused.

lineText(view self): String

The line received, without its line end. Empty for other events.

struct Server

A server for line-based protocols: many clients in one thread, none able to hold up the others.

clientCount(view self): u64

How 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): bool

Queues a line for a client. False if there is no such client.

broadcast(edit self, line: view String, except: u64): u64

Queues a line for every client but one; pass 0 to leave nobody out. How many it was queued for.

disconnect(edit self, client: u64): bool

Disconnects 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>): String

The SHA-256 of the bytes, as 64 lowercase hex digits.

sha256Text(value: view String): String

The 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>): bool

Replaces out with the file's bytes. False if it cannot be read, leaving out empty.

writeFile(path: str, data: view List<u8>): bool

Creates 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>): bool

Adds to the end of a file.

exists(path: str): bool

Whether something is at this path.

removeFile(path: str): bool

Deletes a file.

makeDirectory(path: str): bool

Creates a folder; true if it already exists. The parent must exist.

makeDirectoryAt(path: view List<u8>): bool

makeDirectory with a path built at run time.

removeDirectoryAt(path: view List<u8>): bool

Removes an empty folder.

removeFileAt(path: view List<u8>): bool

removeFile with a path built at run time.

readFileAt(path: view List<u8>, out: edit List<u8>): bool

readFile with a path built at run time, as UTF-8 bytes.

writeFileAt(path: view List<u8>, data: view List<u8>): bool

writeFile with a path built at run time.

existsAt(path: view List<u8>): bool

exists with a path built at run time.

isDirectory(path: str): bool

Whether this path is a folder.

isDirectoryAt(path: view List<u8>): bool

isDirectory with a path built at run time.

listDirectory(path: str): i32

Reads 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>): i32

listDirectory with a path built at run time.

entryName(index: i32, out: edit List<u8>): bool

Replaces out with a name's UTF-8 bytes. False if there is no such entry.

entryIsDirectory(index: i32): bool

Whether that entry is a folder.

isWindows(): bool

Whether 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>): bool

Runs the command and waits. False if it could not start. With keep, its output and errors go into output together.

commandExitCode(): i32

The 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>): f64

The 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(): i64

Milliseconds on a clock that never goes backward; only differences mean anything.

unixMillis(): i64

Milliseconds since 1970 by the system clock, which can jump.

sleepMillis(milliseconds: i32)

Waits this long.

argumentCount(): i32

How many program arguments there are; number 0 is the program itself.

argument(index: i32, out: edit List<u8>): bool

Replaces 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): bool

Whether the path starts from a root.

join(first: view String, second: view String): String

The second path under the first, unless the second is absolute or has a drive, which replaces the first.

baseName(value: view String): String

The last name: game.kon from a/b/game.kon, and b from a/b/.

parent(value: view String): String

The 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): String

The extension with its dot: .gz from a.tar.gz, and empty text if there is none.

stem(value: view String): String

The 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 Arguments

A parsed command line.

has(view self, name: str): bool

Whether this flag was given.

valueOr(view self, name: str, fallback: str): String

The value of --name=value, or the fallback if it is absent or has no value.

count(view self): u64

How many plain words there are.

positional(view self, index: u64): Option<String>

A plain word by position, or none.

parse(list_: view List<String>): Arguments

Reads a list of arguments, without the program's own name.

read(): Arguments

The 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 Finished

What happened to a program that was run.

didStart(view self): bool

Whether the program could be started at all.

succeeded(view self): bool

Whether it started and exited with 0.

exitCode(view self): i32

Its exit code, or -1 if it did not start.

outputText(view self): String

What 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>): Finished

Runs it with its output going to this program's, and waits.

runKept(parts: view List<String>): Finished

Runs 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 Map

A table from K to V.

count(view self): u64

Number of entries.

get(view self, wanted: view K): Option<view V> from self

A 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.Equal

A new empty table.

std/interfaces Map keys

What a type implements to be a Map key.

import "std/interfaces.kon" as interfaces
interface Hash

A type that gives a hash: func hash(view self): u64

interface Equal

A 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 IntMap

The table.

count(view self): u64

Number of entries.

contains(view self, key: i64): bool

Whether 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(): IntMap

A new empty table.

std/intset Integer set

A set of i64, built on IntMap.

import "std/intset.kon" as intset
struct IntSet

The set.

count(view self): u64

Number of values.

contains(view self, value: i64): bool

Whether the value is present.

add(edit self, value: i64): bool

Adds value, and returns whether it was new.

remove(edit self, value: i64): bool

Removes value, and returns whether it was present.

intSet(): IntSet

A 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 IntDeque

The queue.

count(view self): u64

Number 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(): IntDeque

A 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 MinHeap

The queue.

count(view self): u64

Number 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(): MinHeap

A 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 Grid

The map.

gridWidth(view self): i64

Its width.

gridHeight(view self): i64

Its height.

inside(view self, x: i64, y: i64): bool

Whether a cell is on the map.

get(view self, x: i64, y: i64, fallback: i64): i64

The 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): i64

Finds 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): u64

Steps in the last path.

routeX(view self, step: u64): i64

X of a step of the last path, numbered from the start.

routeY(view self, step: u64): i64

Y of a step of the last path.

grid(width: i64, height: i64, value: i64): Grid

A 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>): bool

Whether 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): i64

The smaller one.

maxI64(a: i64, b: i64): i64

The larger one.

clampI64(value: i64, low: i64, high: i64): i64

Value kept between low and high.

absI64(value: i64): i64

Without its sign.

gcd(first: u64, second: u64): u64

Greatest common divisor; gcd(0, 0) is 0.

isqrt(value: u64): u64

The largest r with r * r <= value.

powI64(base: i64, exponent: u64): i64

Integer power. Overflow wraps, like other integer arithmetic.

sinDegrees(angle: i64): i64

Sine of an angle in degrees, scaled so 1000 means 1.0, accurate to about 0.2%.

cosDegrees(angle: i64): i64

Cosine, 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(): i64

The value 1.

fromInt(value: i64): i64

A whole number as fixed-point.

toInt(value: i64): i64

To a whole number, rounding toward negative infinity.

fromRatio(numerator: i64, denominator: i64): i64

numerator / denominator; fromRatio(3, 2) is 1.5.

mul(a: i64, b: i64): i64

Multiplies.

div(a: i64, b: i64): i64

Divides.

sqrt(value: i64): i64

Square root; a negative value gives 0.

lerp(a: i64, b: i64, t: i64): i64

The value part way from a to b; t runs from 0 to one().

sinDegrees(angle: i64): i64

Sine of an angle in whole degrees.

cosDegrees(angle: i64): i64

Cosine of an angle in whole degrees.

length(x: i64, y: i64): i64

The 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 Random

The generator.

next(edit self): u64

The next value over all of u64.

below(edit self, limit: u64): u64

A value from 0 up to, but not including, limit. A limit of 0 gives 0.

between(edit self, low: i64, high: i64): i64

A value from low up to and including high.

chance(edit self, percent: u64): bool

True with a chance of percent in 100.

random(seed: u64): Random

The same seed gives the same sequence.