Docs / Standard Library

10. Standard Library Reference

The Dryad Standard Library (STDLIB) provides a comprehensive set of modules for file I/O, networking, JSON processing, cryptography, mathematics, date/time operations, operating system interaction, debugging, and data structure collections. Every module is implemented in 100% pure Dryad atop the ~50 intrinsic syscalls exposed by the minimal C++ runtime. Native modules are loaded via #module directives and their functions become available in the global scope. The STDLIB follows consistent naming conventions (snake_case functions, PascalCase types) and error handling across all modules.

ModuleNamespaceCategoryError Range
io#ioFile I/O5000-5099
fs#fsFile System5100-5199
net#netNetworking6000-6099
http#httpHTTP6100-6199
json#jsonJSON6200-6249
crypto#cryptoCryptography6250-6299
math#mathMathematics
time#timeDate/Time
os#osOperating System6300-6399
debug#debugDebugging
collectionsbuilt-inData Structures
Module Overview
 1 // ── Dryad Standard Library — Module Index ──────────────────────
 2 //
 3 // Module     | Namespace    | Description
 4 // ───────────┼──────────────┼──────────────────────────────────────────
 5 // io         | #io          | File I/O: read, write, list, delete, temp
 6 // fs         | #fs          | High-level FS: copy, move, watch, stat
 7 // net        | #net         | TCP networking: connect, listen, sockets
 8 // http       | #http        | HTTP client: GET, POST, request
 9 // json       | #json        | JSON parse and stringify
10 // crypto     | #crypto      | Hash, random bytes, UUID, encrypt/decrypt
11 // math       | #math        | Math functions, constants, RNG
12 // time       | #time        | Date/time: now, sleep, format, parse
13 // os         | #os          | OS: platform, env, args, exit
14 // debug      | #debug       | Assert, log, trace, benchmark
15 // collections| built-in     | List, Map, Set data structures

All modules are loaded via #module directives. Collections are built-in types available without import.

io — File I/O
 1 // ── io Module ──────────────────────────────────────────────
 2 // File and directory operations. Error codes: 5000-5099.
 3 
 4 // Read entire file as string
 5 function io_read_file(path: string): string
 6 
 7 // Write string to file (overwrites existing)
 8 function io_write_file(path: string, content: string): void
 9 
10 // Append string to end of file
11 function io_append_file(path: string, content: string): void
12 
13 // Check if file exists at path
14 function io_file_exists(path: string): bool
15 
16 // Get file size in bytes
17 function io_file_size(path: string): number
18 
19 // Delete file at path
20 function io_delete_file(path: string): void
21 
22 // Create directory (including parents)
23 function io_create_dir(path: string): void
24 
25 // Remove empty directory
26 function io_remove_dir(path: string): void
27 
28 // List directory entries
29 function io_list_dir(path: string): string[]
30 
31 // Get system temporary directory path
32 function io_temp_dir(): string
33 
34 // Read one line from stdin
35 function io_stdin(): string
36 
37 // Print string to stdout
38 function io_print(value: any): void
39 
40 // Print string to stdout with newline
41 function io_println(value: any): void

The io module provides low-level file and directory operations. All paths use UTF-8 encoding. Functions throw I/O Error (5000-5099) on failure with the specific OS error code.

fs — High-Level File System
 1 // ── fs Module ───────────────────────────────────────────────
 2 // High-level file system operations. Error codes: 5100-5199.
 3 
 4 // Read file as Buffer
 5 function fs_read(path: string): Buffer
 6 
 7 // Write Buffer to file (overwrites)
 8 function fs_write(path: string, data: Buffer): void
 9 
10 // Copy file from src to dst
11 function fs_copy(src: string, dst: string): void
12 
13 // Move/rename file from src to dst
14 function fs_move(src: string, dst: string): void
15 
16 // Get file metadata
17 function fs_stat(path: string): FileStat
18 
19 // FileStat properties
20 //   .size: number       — file size in bytes
21 //   .created: number    — creation timestamp (ms since epoch)
22 //   .modified: number   — last modification timestamp
23 //   .is_dir: bool       — true if path is a directory
24 //   .permissions: number — POSIX-style permission bits
25 
26 // Watch file/directory for changes (calls callback on change)
27 function fs_watch(path: string, callback: fn(string)): Watcher
28 
29 // Watcher methods
30 //   watcher.close(): void  — stop watching

The fs module builds on io with higher-level abstractions. Buffer-based operations enable zero-copy I/O. The watch function uses the OS-native file notification system (inotify on Linux, FSEvents on macOS, ReadDirectoryChanges on Windows).

net — TCP Networking
 1 // ── net Module ──────────────────────────────────────────────
 2 // TCP networking operations. Error codes: 6000-6099.
 3 
 4 // Connect to TCP server
 5 function net_connect(host: string, port: number): TcpSocket
 6 
 7 // Start TCP listener on address
 8 function net_listen(host: string, port: number): TcpListener
 9 
10 // ── TcpSocket ──────────────────────────────────────
11 // Represents an active TCP connection.
12 
13 // Read available data from socket (blocks until data arrives)
14 //   socket.read(): Buffer
15 // Read up to n bytes from socket
16 //   socket.read(n: number): Buffer
17 // Write data to socket
18 //   socket.write(data: Buffer): void
19 // Write string to socket
20 //   socket.writeString(data: string): void
21 // Close the connection
22 //   socket.close(): void
23 // Check if socket is still connected
24 //   socket.isConnected(): bool
25 // Set read timeout in milliseconds (0 = no timeout)
26 //   socket.setTimeout(ms: number): void
27 
28 // ── TcpListener ────────────────────────────────────
29 // Listens for incoming TCP connections.
30 
31 // Accept next incoming connection (blocks until one arrives)
32 //   listener.accept(): TcpSocket
33 // Close the listener
34 //   listener.close(): void
35 // Get the bound port number
36 //   listener.port(): number
37 
38 // ── DNS ────────────────────────────────────────────
39 // Resolve hostname to IPv4 address string
40 function dns_resolve(hostname: string): string

The net module provides blocking TCP sockets. The async/await execution model enables concurrent connection handling without threads. All socket operations are non-blocking at the kernel level when used with the event loop.

http — HTTP Client
 1 // ── http Module ─────────────────────────────────────────────
 2 // HTTP client operations. Error codes: 6100-6199.
 3 
 4 // Perform HTTP GET request
 5 function http_get(url: string): HttpResponse
 6 
 7 // Perform HTTP GET with custom headers
 8 function http_get(url: string, headers: Map): HttpResponse
 9 
10 // Perform HTTP POST with body
11 function http_post(url: string, body: string): HttpResponse
12 
13 // Perform HTTP POST with JSON body
14 function http_post(url: string, body: any): HttpResponse
15 
16 // Perform arbitrary HTTP request
17 function http_request(method: string, url: string, options: HttpOptions): HttpResponse
18 
19 // ── HttpResponse ───────────────────────────────────
20 //   .status: number        — HTTP status code (200, 404, etc.)
21 //   .headers: Map          — Response headers
22 //   .body: string          — Response body as string
23 //   .bodyBuffer: Buffer    — Response body as Buffer
24 //   .json(): any           — Parse body as JSON
25 
26 // ── HttpOptions ────────────────────────────────────
27 //   .headers: Map          — Request headers
28 //   .body: string|Buffer   — Request body
29 //   .timeout: number       — Request timeout in ms
30 //   .followRedirects: bool — Auto-follow redirects (default: true)

The http module wraps net sockets with HTTP protocol handling. JSON body support enables convenient API client usage. Response bodies are available as both string and Buffer.

json — JSON Processing
 1 // ── json Module ─────────────────────────────────────────────
 2 // JSON parsing and serialization. Error codes: 6200-6249.
 3 
 4 // Parse JSON string into Dryad value
 5 function json_parse(text: string): any
 6 
 7 // Serialize Dryad value to JSON string
 8 function json_stringify(value: any): string
 9 
10 // Serialize with pretty-print (indented)
11 function json_stringify(value: any, pretty: bool): string
12 
13 // Read JSON file and parse
14 function json_parse_file(path: string): any
15 
16 // Serialize value and write to file
17 function json_write_file(path: string, value: any): void
18 
19 // Validate JSON string (returns true if valid)
20 function json_is_valid(text: string): bool

JSON parsing supports all standard JSON types: objects, arrays, strings, numbers, booleans, and null. Circular references in stringify throw an error. File operations use the io module underneath.

crypto — Cryptography
 1 // ── crypto Module ──────────────────────────────────────────
 2 // Cryptographic operations. Error codes: 6250-6299.
 3 
 4 // Hash data with specified algorithm
 5 function crypto_hash(algorithm: string, data: Buffer): Buffer
 6 function crypto_hash(algorithm: string, data: string): string
 7 
 8 // Supported algorithms: "sha256", "sha512", "md5", "blake2b"
 9 
10 // Generate cryptographically secure random bytes
11 function crypto_random_bytes(n: number): Buffer
12 
13 // Generate a random UUID v4 string
14 function crypto_random_uuid(): string
15 
16 // Encrypt data with symmetric key
17 function crypto_encrypt(algorithm: string, key: Buffer, data: Buffer): Buffer
18 
19 // Decrypt data with symmetric key
20 function crypto_decrypt(algorithm: string, key: Buffer, data: Buffer): Buffer
21 
22 // Supported encryption: "aes-256-gcm", "chacha20-poly1305"
23 
24 // Generate cryptographically secure random number in range [min, max]
25 function crypto_random_int(min: number, max: number): number

The crypto module wraps system-level cryptographic providers (OpenSSL on Linux, CNG on Windows, Security Framework on macOS). The hash and encrypt/decrypt functions accept both string and Buffer inputs.

math — Mathematics
 1 // ── math Module ─────────────────────────────────────────────
 2 // Mathematical functions and constants.
 3 
 4 // ── Constants ──────────────────────────────────────
 5 //   math.pi: number  — π (3.14159...)
 6 //   math.e: number   — Euler's number (2.71828...)
 7 //   math.tau: number — τ = 2π (6.28318...)
 8 //   math.inf: number — Positive infinity
 9 //   math.nan: number — Not-a-Number (NaN)
10 
11 // ── Basic Functions ────────────────────────────────
12 function math_abs(x: number): number
13 function math_floor(x: number): number
14 function math_ceil(x: number): number
15 function math_round(x: number): number
16 function math_trunc(x: number): number          // integer truncation
17 function math_min(a: number, b: number): number
18 function math_max(a: number, b: number): number
19 function math_clamp(x: number, lo: number, hi: number): number
20 function math_sign(x: number): number            // -1, 0, or 1
21 
22 // ── Power and Root ────────────────────────────────
23 function math_sqrt(x: number): number
24 function math_cbrt(x: number): number
25 function math_pow(base: number, exp: number): number
26 function math_exp(x: number): number              // e^x
27 function math_log(x: number): number              // natural log
28 function math_log10(x: number): number
29 function math_log2(x: number): number
30 
31 // ── Trigonometric ─────────────────────────────────
32 function math_sin(x: number): number
33 function math_cos(x: number): number
34 function math_tan(x: number): number
35 function math_asin(x: number): number
36 function math_acos(x: number): number
37 function math_atan(x: number): number
38 function math_atan2(y: number, x: number): number
39 
40 // ── Random Numbers ────────────────────────────────
41 function math_random(): number                    // [0.0, 1.0)
42 function math_random_int(min: number, max: number): number

All trigonometric functions operate in radians. The default RNG is a xoshiro256** PRNG seeded at program start from OS entropy. For cryptographic randomness, use crypto_random_bytes instead.

time — Date and Time
 1 // ── time Module ─────────────────────────────────────────────
 2 // Date and time operations.
 3 
 4 // Get current date/time
 5 function time_now(): DateTime
 6 
 7 // Sleep for specified milliseconds (blocks thread)
 8 function time_sleep(ms: number): void
 9 
10 // Format DateTime to string using format specifier
11 function time_format(dt: DateTime, format: string): string
12 
13 // Parse string to DateTime using format specifier
14 function time_parse(format: string, text: string): DateTime
15 
16 // Get current Unix timestamp (ms since epoch)
17 function time_timestamp(): number
18 
19 // Measure elapsed time in ms since start
20 function time_elapsed(start: number): number
21 
22 // ── DateTime ───────────────────────────────────────
23 // Properties:
24 //   dt.year: number      — 4-digit year
25 //   dt.month: number     — 1-12
26 //   dt.day: number       — 1-31
27 //   dt.hour: number      — 0-23
28 //   dt.minute: number    — 0-59
29 //   dt.second: number    — 0-59
30 //   dt.millisecond: number — 0-999
31 //   dt.timestamp: number — Unix timestamp in ms
32 //   dt.weekday: number   — 0=Sunday, 6=Saturday
33 //   dt.timezone: string  — e.g. "UTC", "America/New_York"
34 
35 // Methods:
36 //   dt.addDays(n: number): DateTime
37 //   dt.addHours(n: number): DateTime
38 //   dt.addMinutes(n: number): DateTime
39 //   dt.addSeconds(n: number): DateTime
40 //   dt.toISOString(): string   — ISO 8601 format
41 //   dt.toDateString(): string  — locale date
42 //   dt.toTimeString(): string  — locale time
43 
44 // Common format specifiers (strftime-style):
45 //   %Y — 4-digit year    %m — month (01-12)
46 //   %d — day (01-31)     %H — hour (00-23)
47 //   %M — minute (00-59)  %S — second (00-59)

The time module provides platform-level date/time support. DateTime objects are immutable — all add* methods return a new instance. Format strings follow strftime conventions.

os — Operating System
 1 // ── os Module ───────────────────────────────────────────────
 2 // Operating system interface.
 3 
 4 // Get platform identifier
 5 function os_platform(): string
 6 // Returns: "linux", "macos", "windows", "freebsd", etc.
 7 
 8 // Get CPU architecture
 9 function os_arch(): string
10 // Returns: "x86_64", "aarch64", "arm64", etc.
11 
12 // Get number of logical CPUs
13 function os_cpus(): number
14 
15 // Get total and available system memory (bytes)
16 function os_memory(): MemoryInfo
17 // MemoryInfo: { total: number, available: number, used: number }
18 
19 // Get environment variable value
20 function os_env(name: string): string  // returns "" if unset
21 
22 // Get current working directory
23 function os_cwd(): string
24 
25 // Get command-line arguments
26 function os_args(): string[]
27 
28 // Exit process with code (0 = success)
29 function os_exit(code: number): void
30 
31 // Get process ID
32 function os_pid(): number
33 
34 // Get system hostname
35 function os_hostname(): string
36 
37 // Get OS user's home directory
38 function os_home(): string

The os module provides direct access to the operating system environment. It is primarily used for configuration, diagnostics, and process lifecycle management.

debug — Debugging Utilities
 1 // ── debug Module ───────────────────────────────────────────
 2 // Debug and diagnostic utilities.
 3 
 4 // Assert condition; throw AssertionError if false
 5 function debug_assert(condition: bool, message: string): void
 6 
 7 // Log value to stderr (for debugging)
 8 function debug_log(value: any): void
 9 
10 // Log with label prefix
11 function debug_log(label: string, value: any): void
12 
13 // Get current call stack trace as string
14 function debug_trace(): string
15 
16 // Benchmark a function: returns elapsed time in ms
17 function debug_benchmark(fn: fn() -> void, iterations: number): number
18 
19 // Dump intrinsic syscall trace (requires debug runtime)
20 function debug_dump_syscall_trace(): string
21 
22 // Enable/disable debug logging globally
23 function debug_set_logging(enabled: bool): void

Debug functions are no-ops in production builds (when compiled with --release or --aot). The dump_syscall_trace function only works when the runtime is compiled with DRYAD_DEBUG_INTRINSICS=1.

collections — List, Map, Set
 1 // ── Collections ───────────────────────────────────────────
 2 // Built-in data structure types.
 3 
 4 // ── List ───────────────────────────────────────────
 5 // Ordered, dynamically-sized sequence.
 6 
 7 //   let list = List.new()
 8 //   let list = List.fromArray([1, 2, 3])
 9 //
10 //   list.add(item): void              — append to end
11 //   list.get(index): any              — get by index
12 //   list.set(index, value): void      — set by index
13 //   list.insert(index, item): void    — insert at position
14 //   list.remove(index): void          — remove at index
15 //   list.removeItem(item): bool       — remove first match, returns true if found
16 //   list.clear(): void                — remove all elements
17 //   list.len(): number                — number of elements
18 //   list.isEmpty(): bool              — true if empty
19 //   list.contains(item): bool         — linear search
20 //   list.indexOf(item): number        — first index, -1 if not found
21 //   list.sort(comparator?): void      — sort in place (stable sort)
22 //   list.map(fn): List                — transform each element
23 //   list.filter(fn): List             — keep elements matching predicate
24 //   list.reduce(fn, initial): any     — accumulate left-to-right
25 //   list.forEach(fn): void            — side-effect iteration
26 //   list.slice(start, end): List      — sub-list (shallow copy)
27 //   list.concat(other): List          — concatenate two lists
28 //   list.toArray(): any[]             — convert to native array
29 //   list.join(separator): string      — join elements as string
30 //   list.reverse(): List              — reversed copy
31 
32 // ── Map ────────────────────────────────────────────
33 // Key-value dictionary (hash-based, insertion-order iteration).
34 
35 //   let map = Map.new()
36 //
37 //   map.set(key, value): void         — insert/update key
38 //   map.get(key): any                 — get value (null if missing)
39 //   map.has(key): bool                — key exists
40 //   map.delete(key): void             — remove key
41 //   map.clear(): void                 — remove all entries
42 //   map.len(): number                 — entry count
43 //   map.keys(): any[]                 — all keys
44 //   map.values(): any[]               — all values
45 //   map.entries(): [any, any][]       — key-value pairs
46 //   map.forEach(fn): void             — iterate (key, value)
47 //   map.toObject(): any               — convert to Dryad object
48 
49 // ── Set ────────────────────────────────────────────
50 // Unique value collection (hash-based).
51 
52 //   let set = Set.new()
53 //   let set = Set.fromArray([1, 2, 3])
54 //
55 //   set.add(item): void               — insert (no-op if exists)
56 //   set.has(item): bool               — membership test
57 //   set.delete(item): void            — remove item
58 //   set.clear(): void                 — remove all items
59 //   set.len(): number                 — element count
60 //   set.values(): any[]               — all unique values
61 //   set.forEach(fn): void             — iterate elements
62 //   set.union(other): Set             — set union
63 //   set.intersection(other): Set      — set intersection
64 //   set.difference(other): Set      — set difference
65 
66 // ── Iterator Protocol ──────────────────────────────
67 // List, Map, and Set all support iteration:
68 //   for (item in list) { ... }
69 //   for (entry in map) { ... }        // entry = [key, value]
70 //   for (item in set) { ... }

Collections are the only STDLIB modules available without an explicit import — List, Map, and Set are built-in types. All three support the for-in iteration protocol. List.sort uses a stable merge sort. Map and Set use hash-based storage with O(1) average-case lookup.

Found an error in the spec? Open a PR.
Official Version: 1.0 · May 2026