Table of Contents

Appendix B: Standard library modules

Nyx ships with 37 standard library modules. Import them with import "std/module_name".

Core

Module Description
std/prelude Auto-loaded. Defines Option, Result, operator traits (Add, Sub, Mul, Eq, Ord, Display), and default implementations. You never need to import this — it is always available.
std/math Mathematical functions: abs, min, max, pow, sqrt, floor, ceil, round, log, sin, cos, tan, PI, E.
std/math_ext Extended math: gcd, lcm, factorial, fibonacci, is_prime, clamp, lerp, matrix operations.
std/array Array utilities: map, filter, reduce, zip, enumerate, flatten, chunk, take, skip, find, any, all, sort_by, group_by, unique.
std/map Map utilities: map_from_arrays, map_merge, map_filter, map_map_values, map_invert.
std/io I/O utilities: read_line (stdin), print_err, format.

Data structures

Module Description
std/collections Set (backed by Map), Deque (double-ended queue), PriorityQueue (min-heap).
std/btreemap Balanced binary search tree map. Ordered keys, O(log n) operations.
std/linkedlist Doubly-linked list. O(1) insert/remove at head/tail.
std/graph Graph data structure with BFS, DFS, Dijkstra's shortest path, topological sort.
std/matrix Matrix operations: create, multiply, transpose, determinant, identity.

Data formats

Module Description
std/json JSON parser and serializer. json_parse(str) -> Map, json_stringify(map) -> String. Handles nested objects, arrays, strings, numbers, booleans, null.
std/toml TOML parser. toml_parse(str) -> Map. Supports tables, arrays, strings, integers, booleans.
std/csv CSV reader/writer. csv_parse(str) -> Array, csv_stringify(rows) -> String. Handles quoted fields and escaping.
std/msgpack MessagePack binary serialization. msgpack_encode(value) -> String, msgpack_decode(bytes) -> value. Compact binary format.

File and I/O

Module Description
std/file File operations: read_file(path) -> String, write_file(path, content), file_exists(path) -> bool, file_size(path) -> int, list_dir(path) -> Array, delete_file(path), rename_file(old, new).
std/compress zlib compression: deflate(data) -> String, inflate(data) -> String.

Networking

Module Description
std/http HTTP server and client. Server: http_serve(port, handler), http_serve_mt(port, workers, handler). Client: http_get(url), http_post(url, body). Handles requests as [id, method, path, headers, body].
std/web Web framework: App/Request/Response structs, routing (app_get, app_post, app_put, app_delete), middleware chain (app_use, mw_logging, mw_cors), JSON APIs (req_json, response_json_map), static file serving, query/form parsing.
std/http2 HTTP/2 server (h2c cleartext). h2_serve(port, workers, callback) — callback receives (method, path, headers, body) and returns [status, headers, body]. Binary framing, HPACK header compression, stream multiplexing. Runtime frame I/O in C (runtime/http2.c).
std/session Cookie-backed sessions stored in nyx-kv via RESP. session_configure(host, port, ttl), session_start(req, resp), session_get(req, key), session_set(req, key, value), session_destroy(req, resp).
std/url URL encoding/decoding: url_encode(str) -> String, url_decode(str) -> String, url_parse(str) -> Map.
std/websocket WebSocket RFC 6455: handshake, frame encoding/decoding, ws_send, ws_recv.
std/proxy Reverse proxy utilities: backend selection, round-robin, health checking, header forwarding.

Concurrency

Module Description
std/sync Synchronization primitives: WaitGroup (wait for N tasks), Semaphore (limit concurrency), Once (run exactly once), AtomicCounter (thread-safe counter), Barrier (synchronize N threads).

Database

Module Description
std/sqlite SQLite3 bindings (via dlopen): db_open(path), db_exec(db, sql), db_query(db, sql) -> Array, db_close(db). Supports transactions, prepared statements, migrations.
std/pool Connection pool: pool_new(factory, size), pool_acquire(pool), pool_release(pool, conn). Generic — works with any resource.

Security

Module Description
std/regex POSIX regular expressions: regex_match(pattern, text) -> bool, regex_find(pattern, text) -> Array, regex_replace(pattern, text, replacement) -> String.
std/random Random number generation (xorshift64): random_int(min, max), random_float(), random_choice(array), random_shuffle(array).
std/uuid UUID generation: uuid_v4() -> String.

Text and encoding

Module Description
std/semver Semantic versioning: semver_parse(str) -> Map, semver_compare(a, b) -> int, semver_satisfies(version, range) -> bool.
std/base64 Base64 and Base64URL encoding/decoding: base64_encode(str) -> String, base64_decode(str) -> String, base64url_encode(str) -> String, base64url_decode(str) -> String.

Patterns and architecture

Module Description
std/events Event bus / observable pattern: event_bus_new(), on(bus, event, handler), emit(bus, event, data). Decoupled pub/sub communication.
std/statemachine Generic finite state machine: fsm_new(states, transitions), fsm_transition(fsm, event), fsm_current(fsm).
std/owned Ownership wrappers: Box (unique ownership), Rc (reference counted), MoveOnly (non-copyable). Convention-based, not compiler-enforced.
std/proptest Property-based testing (QuickCheck-style): prop_check(name, generator, property), random input generation, shrinking on failure.

System

Module Description
std/log Logging: log_info(msg), log_warn(msg), log_error(msg), log_debug(msg). Configurable log level and output.
std/args Command-line argument parsing: args_parse(spec) -> Map. Supports flags, options with values, positional arguments, help generation.

Runtime builtins (added in v0.12.0)

These functions are implemented in the C runtime and available without imports:

Function Description
hmac_sha256(key, data) HMAC-SHA256 message authentication code. Returns hex string.
getenv_default(name, default) Read environment variable with fallback value.
crc32_bytes(data, len) CRC32 checksum for binary data.
string_from_bytes(ptr, len) Create a Nyx string from a raw byte pointer and length.
rename_file(old, new) Atomically rename a file.
tcp_read_exact(fd, n) Read exactly n bytes from a TCP socket. Blocks until all bytes arrive.
setup_shutdown_handler(callback) Register a callback for SIGTERM/SIGINT signals.

Terminal I/O builtins (added in v0.12.0)

These functions provide raw terminal access for building interactive TUI applications:

Function Description
raw_mode_enter() Set terminal to raw mode (no echo, no line buffering). Use with defer { raw_mode_exit() } for safe cleanup.
raw_mode_exit() Restore terminal to normal (cooked) mode.
read_byte() Read a single byte from stdin. Returns int (0-255), or -1 on EOF.
chr(code) Convert an ASCII code (int) to a single-character String. Example: chr(65) returns "A".
term_cols() Return terminal width in columns (default 80 if unavailable).
term_rows() Return terminal height in rows (default 24 if unavailable).

Array insert/remove (added in v0.12.0)

Arrays now support inserting and removing at arbitrary positions:

Method Description
arr.insert(index, value) Insert value at index, shifting subsequent elements right. O(n) time.
arr.remove(index) Remove and return element at index, shifting subsequent elements left. O(n) time.

Process control builtins (added in v0.12.0)

POSIX process control primitives for building shells, pipelines, and process managers:

Function Description
fork()Fork process. Returns 0 in child, pid in parent, -1 on error.
execvp(program, args)Replace process image with program. args is an Array of Strings.
waitpid(pid, opts)Wait for child. opts: 0=block, 1=WNOHANG. Returns exit status.
dup2(old_fd, new_fd)Redirect file descriptor new_fd to refer to old_fd.
pipe_new()Create a pipe. Returns [read_fd, write_fd].
close_fd(fd)Close a raw file descriptor.
open_fd(path, mode)Open file returning raw fd. mode: 0=read, 1=write(trunc), 2=append.
getcwd()Return current working directory as String.
chdir(path)Change working directory. Returns 0 on success.
stat(path)File info: [size, mode, mtime, is_dir, is_file].
isatty(fd)Returns 1 if fd is a terminal, 0 otherwise.
getpid()Return current process ID.
kill_process(pid, sig)Send signal to process (e.g. 15=SIGTERM, 9=SIGKILL).

GC safety: After fork(), the child must call execvp() immediately without allocating GC memory.

Example usage

import "std/json"
import "std/http"
import "std/file"

fn main() {
    // Read and parse a config file
    let config_text: String = read_file("config.json")
    let config: Map = json_parse(config_text)

    let port: int = string_to_int(config.get("port"))

    // Start a web server
    http_serve_mt(port, 4, fn(req: Array) -> String {
        return http_response(200, "Hello from Nyx!")
    })
}

← Back to Table of Contents

← Previous: Appendix A: Syntax quick reference Next: Appendix C: Common error messages →