Standard Library
weight: 20
The Jda standard library ships with 117 packages covering everything from basic data structures to networking, cryptography, and machine learning primitives. All packages are written in pure Jda – no C, no libc, just direct Linux syscalls at the bottom.
Core Packages
| Package | Description |
|---|---|
| string | Length-prefixed strings with immutable-style API |
| vec | Dynamic array (growable Vec<i64>) |
| hashmap | Hash map with open addressing and linear probing |
| sort | Quicksort, binary search, merge, min/max for Vec |
| conv | Value conversions – itoa, atoi, hex, binary |
| math | Integer math, random numbers, GCD, primes |
Data Formats
| Package | Description |
|---|---|
| json | Zero-copy JSON parser and serialiser |
| csv | CSV reader and writer |
| base64 | Base64 encoding and decoding |
| toml | TOML configuration file parser |
| yaml | YAML parser |
| xml | XML parser |
File System and I/O
| Package | Description |
|---|---|
| fs | Low-level file I/O via Linux syscalls |
| file_io | High-level file I/O helpers (slurp, write, copy) |
| io | Buffered I/O streams |
| tempfile | Temporary file creation |
| glob | File glob pattern matching |
| mmap | Memory-mapped file I/O |
Networking
| Package | Description |
|---|---|
| tcp | TCP socket API (connect, listen, accept) |
| http | HTTP/1.1 request parser and response writer |
| httpclient | HTTP client for making requests |
| httpserver | HTTP server framework |
| dns | DNS resolver |
| tls | TLS/SSL support |
| udp | UDP datagram sockets |
| ws | WebSocket protocol |
Text Processing
| Package | Description |
|---|---|
| regex | Regular expression matching (backtracking engine) |
| fmt | String formatting |
| diff | Text diffing |
| textwrap | Text wrapping and filling |
| encoding | Character encoding conversions |
Testing and Debugging
| Package | Description |
|---|---|
| testing | Test framework with assertions |
| benchmark | Performance benchmarking |
| log | Logging framework |
| debug | Software debugger — breakpoints, watchpoints, assertions |
| lint | Code style checker — naming conventions, warnings |
| profile | Function-level profiler — timing, call counts, report |
Concurrency and OS
| Package | Description |
|---|---|
| process | Process spawning and management |
| signal | Signal handling |
| mutex | Mutual exclusion locks |
| sched | Scheduler primitives |
| os | OS information and environment |
| platform | Platform detection |
Data Structures
| Package | Description |
|---|---|
| heap | Binary heap / priority queue |
| set | Hash set |
| queue | FIFO queue |
| ring | Ring buffer |
| tuple | Tuple types |
Numerics and Science
| Package | Description |
|---|---|
| bignum | Arbitrary precision integers |
| complex | Complex number arithmetic |
| rational | Rational number arithmetic |
| fixedpoint | Fixed-point arithmetic |
| matrix | Matrix operations |
| statistics | Statistical functions |
Security
| Package | Description |
|---|---|
| crypto | Cryptographic primitives |
| digest | Hash digests (SHA, MD5) |
| securerandom | Cryptographically secure random numbers |
| uuid | UUID generation |
All Packages (A-Z)
| Package | Description |
|---|---|
| args | Command-line argument parsing |
| autograd | Automatic differentiation |
| avx512_ops | AVX-512 SIMD operations |
| base64 | Base64 encoding/decoding |
| benchmark | Performance benchmarking |
| bignum | Arbitrary precision integers |
| bitops | Bitwise operations |
| calendar | Calendar date calculations |
| complex | Complex number arithmetic |
| comprehension | List comprehension helpers |
| compress | Data compression |
| configparser | INI-style config file parser |
| context | Context propagation |
| conv | Value conversions (itoa, atoi, hex) |
| copy | Deep copy utilities |
| crypto | Cryptographic primitives |
| csv | CSV reader/writer |
| data | Data structure utilities |
| dataclass | Data class helpers |
| datetime | Date and time handling |
| debug | Software debugger |
| decorator | Decorator pattern support |
| diff | Text diffing |
| digest | Hash digests |
| dns | DNS resolver |
| Email message handling | |
| encoding | Character encoding |
| enum | Enumeration helpers |
| erb | Template engine |
| errno | Error number definitions |
| file_io | High-level file I/O |
| fileutils | File utility functions |
| find | File finding utilities |
| fixedpoint | Fixed-point arithmetic |
| fmt | String formatting |
| fnmatch | Filename pattern matching |
| fs | Low-level file I/O |
| ftp | FTP client |
| getpass | Password input |
| glob | Glob pattern matching |
| gzip | Gzip compression |
| hashmap | Hash map |
| heap | Binary heap |
| htmlparser | HTML parser |
| http | HTTP/1.1 parser |
| httpclient | HTTP client |
| httpserver | HTTP server |
| io | Buffered I/O |
| ipaddr | IP address handling |
| iter | Iterator utilities |
| json | JSON parser/serialiser |
| kvstore | Key-value store |
| linecache | Line caching for files |
| lint | Code style checker |
| log | Logging |
| marshal | Object serialisation |
| math | Integer math and random |
| matrix | Matrix operations |
| metrics | Metrics collection |
| mimetypes | MIME type detection |
| mmap | Memory-mapped I/O |
| mutex | Mutual exclusion |
| netrc | .netrc file parser |
| nn | Neural network primitives |
| observer | Observer pattern |
| open3 | Process I/O capture |
| operator | Operator overloading helpers |
| optparse | Option parsing |
| os | OS utilities |
| pack | Binary packing/unpacking |
| pathname | Path manipulation |
| platform | Platform detection |
| plot | Data plotting |
| pp | Pretty printing |
| process | Process management |
| profile | Function-level profiler |
| ptx | PTX GPU code generation |
| queue | FIFO queue |
| range | Range types |
| rational | Rational numbers |
| regex | Regular expressions |
| ring | Ring buffer |
| rocm | ROCm GPU support |
| sched | Scheduler primitives |
| securerandom | Secure random numbers |
| select | I/O multiplexing |
| set | Hash set |
| shell | Shell command execution |
| signal | Signal handling |
| smtp | SMTP email sending |
| socketserver | Socket server framework |
| sort | Sorting algorithms |
| statistics | Statistical functions |
| string | String type |
| stringio | In-memory string I/O |
| stringscanner | String scanning |
| tarfile | Tar archive handling |
| tcp | TCP sockets |
| tempfile | Temporary files |
| testing | Test framework |
| textwrap | Text wrapping |
| time | Time functions |
| timeout | Timeout handling |
| tls | TLS/SSL |
| toml | TOML parser |
| transformer | Transformer model primitives |
| tsort | Topological sort |
| tuple | Tuple types |
| udp | UDP sockets |
| uri | URI parsing |
| uuid | UUID generation |
| vec | Dynamic array |
| weakref | Weak references |
| ws | WebSocket protocol |
| xml | XML parser |
| yaml | YAML parser |
| zipfile | Zip archive handling |
| zlib | Zlib compression |
args
CLI Argument Parser
Functions
| Function | Description |
|---|---|
args_str_eq | Internal: compare two C strings up to len bytes. |
args_strlen | Internal: strlen of a C string (null-terminated). |
args_find_eq | Internal: find ‘=’ in a C string, return index or -1. |
args_new | Create argument parser. |
args_parse | Parse all arguments (skip argv[0] which is the program name). |
args_has_flag | Check if a flag is present. |
args_get_opt | Get option value for –key=val. Returns 0 if not found. |
args_positional | Get positional argument at index. |
args_positional_count | Number of positional arguments. |
args_argc | Total argc. |
Details
args_str_eq
fn args_str_eq(a: &i8, b: &i8, len: i64) -> i64Internal: compare two C strings up to len bytes.
autograd
Functions
Details
grad_add_a
fn grad_add_a(grad_c: i64) -> i64grad_add_b
fn grad_add_b(grad_c: i64) -> i64grad_sub_a
fn grad_sub_a(grad_c: i64) -> i64grad_sub_b
fn grad_sub_b(grad_c: i64) -> i64grad_mul_a
fn grad_mul_a(b: i64, grad_c: i64) -> i64grad_mul_b
fn grad_mul_b(a: i64, grad_c: i64) -> i64grad_div_a
fn grad_div_a(b: i64, grad_c: i64) -> i64grad_div_b
fn grad_div_b(a: i64, b: i64, grad_c: i64) -> i64grad_relu
fn grad_relu(a: i64, grad_c: i64) -> i64grad_exp
fn grad_exp(c: i64, grad_c: i64) -> i64grad_log
fn grad_log(a: i64, grad_c: i64) -> i64grad_tanh
fn grad_tanh(c: i64, grad_c: i64) -> i64grad_tensor_add
fn grad_tensor_add(grad_c: i64, grad_a: i64, grad_b: i64) -> i64grad_tensor_mul
fn grad_tensor_mul(a: i64, b: i64, grad_c: i64, grad_a: i64, grad_b: i64) -> i64grad_tensor_relu
fn grad_tensor_relu(a: i64, grad_c: i64, grad_a: i64) -> i64grad_tensor_sum
fn grad_tensor_sum(grad_c_scalar: i64, grad_a: i64) -> i64grad_matmul
fn grad_matmul(a: i64, b: i64, grad_c: i64, grad_a: i64, grad_b: i64) -> i64grad_check_close
fn grad_check_close(analytical: i64, numerical: i64, eps: i64) -> i64avx512_ops
Functions
| Function | Description |
|---|---|
vec_add | |
vec_mul | |
vec_scale | |
vec_sum | |
vec_dot |
Details
vec_add
fn vec_add(dst: i64, a: i64, b: i64) -> i64vec_mul
fn vec_mul(dst: i64, a: i64, b: i64) -> i64vec_scale
fn vec_scale(dst: i64, a: i64, s: i64) -> i64vec_sum
fn vec_sum(a: i64) -> i64vec_dot
fn vec_dot(a: i64, b: i64) -> i64base64
Base64 encoding and decoding following the standard Base64 alphabet (RFC 4648). Encodes binary data to ASCII text and decodes it back.
Usage
import base64
fn main() {
let src = "Hello, World!"
let src_len = 13
// Calculate output size and allocate
let enc_len = b64_encoded_len(src_len)
let enc: &i8 = alloc_pages(1)
// Encode
let n = b64_encode(src, src_len, enc)
// enc[0..n] contains "SGVsbG8sIFdvcmxkIQ=="
syscall(1, 1, enc, n)
// Decode
let dec: &i8 = alloc_pages(1)
let m = b64_decode(enc, n, dec)
// dec[0..m] contains "Hello, World!"
syscall(1, 1, dec, m)
}Function Reference
| Function | Signature | Description |
|---|---|---|
b64_encode | (src: &i8, src_len: i64, dst: &i8) -> i64 | Encode bytes to Base64 |
b64_decode | (src: &i8, src_len: i64, dst: &i8) -> i64 | Decode Base64 to bytes |
b64_encoded_len | (src_len: i64) -> i64 | Calculate encoded output length |
b64_decoded_len | (src_len: i64) -> i64 | Calculate maximum decoded output length |
b64_char | (idx: i64) -> i64 | Get Base64 alphabet character |
b64_val | (ch: i64) -> i64 | Decode a Base64 character |
Detailed API
b64_encode
fn b64_encode(src: &i8, src_len: i64, dst: &i8) -> i64Encode src_len bytes from src into Base64, writing the result to dst. The output includes = padding to make the output length a multiple of 4. The caller must ensure dst has enough space (use b64_encoded_len to calculate).
benchmark
In-Language Micro-Benchmarking
Functions
| Function | Description |
|---|---|
bench_now_ns | Get current timestamp in nanoseconds. |
bench_start | Start a benchmark timer. |
bench_stop | Stop timer, return elapsed nanoseconds. |
bench_ms | Stop timer, return elapsed milliseconds. |
bench_us | Stop timer, return elapsed microseconds. |
bench_print_int | Internal: print integer. |
bench_report | Print benchmark result: “name: 12345ns (12.345ms)” |
bench_iter | Run fn_ptr() n times. Returns total nanoseconds. |
bench_iter_report | Run fn_ptr() n times and print results. |
Details
bench_now_ns
fn bench_now_ns() -> i64Get current timestamp in nanoseconds.
bignum
Arbitrary Precision Integers
Constants
BN_BASE = 1000000000Functions
| Function | Description |
|---|---|
_bn_alloc | Internal: allocate BigNum with given limb capacity. |
bn_new | Create BigNum from i64 value. |
bn_from_str | Parse decimal string to BigNum. Handles optional leading ‘-’. |
bn_abs_cmp | Compare magnitudes (ignoring sign). Returns -1, 0, or 1. |
bn_cmp | Compare two BigNums. Returns -1, 0, or 1. |
_bn_add_mag | Internal: add magnitudes. Both must be non-negative limb arrays. |
_bn_sub_mag | Internal: subtract magnitudes. |
bn_add | Add two BigNums. |
bn_sub | Subtract: a - b. |
bn_mul | Multiply two BigNums. Grade-school algorithm. |
bn_is_zero | Check if BigNum is zero. |
bn_negate | Negate: return new BigNum with flipped sign. |
bn_to_str | Convert BigNum to decimal string. Returns length written. |
bn_to_i64 | Convert BigNum to i64 (truncates if too large). |
Details
_bn_alloc
fn _bn_alloc(cap: i64) -> &i64Internal: allocate BigNum with given limb capacity.
bitops
Bit Manipulation Utilities
Functions
| Function | Description |
|---|---|
bit_pow2 | Internal: power of 2 lookup. |
bit_shl | Left shift: a « n. |
bit_shr | Logical right shift: a »> n (unsigned). |
bit_and | Bitwise AND via arithmetic decomposition. |
bit_or | Bitwise OR via arithmetic decomposition. |
bit_xor | Bitwise XOR via arithmetic decomposition. |
bit_not | Bitwise NOT (ones complement, 64-bit). |
bit_get | Get bit n of a (0 or 1). |
bit_set | Set bit n of a to 1. |
bit_clear | Clear bit n of a to 0. |
bit_toggle | Toggle bit n of a. |
bit_count | Population count (number of 1 bits). |
bit_leading_zeros | Number of leading zero bits (from MSB). |
bit_trailing_zeros | Number of trailing zero bits (from LSB). |
bit_reverse | Reverse bit order. |
bit_rotl | Rotate left by n positions. |
bit_rotr | Rotate right by n positions. |
Details
bit_pow2
fn bit_pow2(n: i64) -> i64Internal: power of 2 lookup.
calendar
Calendar Utilities
Functions
| Function | Description |
|---|---|
_cal_is_leap | Internal: leap year check. |
_cal_dim | Internal: days in month. |
_cal_date | Internal: days since epoch (1970-01-01 = day 0). |
_cal_copy | Internal: copy literal. |
cal_weekday | Day of week for a date. 0=Monday, 6=Sunday. Uses Tomohiko Sakamoto’s algorithm. |
cal_is_leap | Check leap year. |
cal_days_in_month | Days in month. |
cal_day_name | Get day name (0=Mon..6=Sun). Returns length written. |
cal_month_name | Get month name (1-12). Returns length written. |
_cal_write_day | Internal: write 2-char number right-aligned. |
cal_month_str | Generate a month calendar string. Returns length. Format: “Mo Tu We Th Fr Sa … |
Details
_cal_is_leap
fn _cal_is_leap(year: i64) -> i64Internal: leap year check.
complex
Complex Number Arithmetic
Functions
| Function | Description |
|---|---|
cx_new | Create complex number. |
cx_add | Add two complex numbers. |
cx_sub | Subtract: a - b. |
cx_mul | Multiply: (a+bi)(c+di) = (ac-bd) + (ad+bc)i. |
cx_scale | Scalar multiply. |
cx_abs_sq | Magnitude squared: |
cx_conjugate | Complex conjugate. |
cx_eq | Equality check. |
cx_re | Real part. |
cx_im | Imaginary part. |
cx_is_real | Check if purely real. |
_cx_write_int | Internal: write integer to buffer. Returns chars written. |
cx_to_str | Format as string: “a+bi” or “a-bi”. Returns length. |
Details
cx_new
fn cx_new(re: i64, im: i64) -> &i64Create complex number.
comprehension
List/Dict Comprehensions
Functions
Details
range
fn range(stop: i64) -> &i64range2
fn range2(start: i64, stop: i64) -> &i64range3
fn range3(start: i64, stop: i64, step: i64) -> &i64vec_comp_map
fn vec_comp_map(v: &i64, f: i64) -> &i64vec_comp_filter
fn vec_comp_filter(v: &i64, pred: i64) -> &i64vec_comp_map_filter
fn vec_comp_map_filter(v: &i64, f: i64, pred: i64) -> &i64vec_sum
fn vec_sum(v: &i64) -> i64vec_any
fn vec_any(v: &i64, pred: i64) -> i64vec_count
fn vec_count(v: &i64, pred: i64) -> i64vec_each
fn vec_each(v: &i64, f: i64)vec_enumerate
fn vec_enumerate(v: &i64) -> &i64vec_zip
fn vec_zip(a: &i64, b: &i64) -> &i64vec_slice
fn vec_slice(v: &i64, start: i64, stop: i64) -> &i64vec_reverse
fn vec_reverse(v: &i64) -> &i64vec_sort
fn vec_sort(v: &i64) -> &i64vec_min
fn vec_min(v: &i64) -> i64vec_max
fn vec_max(v: &i64) -> i64vec_flatten
fn vec_flatten(vecs: &i64, n: i64) -> &i64vec_concat
fn vec_concat(a: &i64, b: &i64) -> &i64vec_from_arr
fn vec_from_arr(arr: &i64, len: i64) -> &i64map_from_vecs
fn map_from_vecs(keys: &i64, vals: &i64) -> &i64map_keys
fn map_keys(m: &i64) -> &i64map_vals
fn map_vals(m: &i64) -> &i64map_items
fn map_items(m: &i64) -> &i64map_comp_filter
fn map_comp_filter(m: &i64, pred: i64) -> &i64map_comp_map_vals
fn map_comp_map_vals(m: &i64, f: i64) -> &i64compress
Compression Utilities (RLE + LZ77 stubs)
Functions
| Function | Description |
|---|---|
_cmp_byte_at | Internal byte reader. |
compress_rle | RLE compress data into out. Returns compressed length. Format: repeated [coun… |
decompress_rle | RLE decompress data into out. Returns decompressed length. |
compress_lz77 | LZ77 compress (stub — not implemented). Returns -1. |
decompress_lz77 | LZ77 decompress (stub — not implemented). Returns -1. |
Details
_cmp_byte_at
fn _cmp_byte_at(buf: &i8, idx: i64) -> i64Internal byte reader.
compress_rle
fn compress_rle(data: &i8, len: i64, out: &i8) -> i64RLE compress data into out. Returns compressed length. Format: repeated [count][byte] pairs.
configparser
INI File Parser
Functions
| Function | Description |
|---|---|
_ini_byte_at | Internal byte reader. |
_ini_copy | Internal: copy bytes from src+off to dst, length len. |
_ini_eq | Internal: compare two byte ranges for equality. |
_ini_skip_ws | Internal: skip whitespace at pos. Returns new pos. |
_ini_skip_line | Internal: skip to end of line. Returns pos after newline. |
_ini_add_entry | Internal: add one entry. Val info passed via h[11], h[12]. |
_ini_parse_section | Internal: parse section header. Sets h[9], h[10]. Returns pos after line. |
_ini_trim_end | Internal: trim trailing whitespace. Returns new end position. |
_ini_parse_kv | Internal: parse key=value line. Returns pos after line. |
ini_parse | Parse INI data from buf. Returns handle. |
ini_parse_full | Alias for compatibility. |
ini_count | Number of entries in the INI handle. |
ini_get | Get value for section+key. Copies to out, returns length. -1 if not found. |
ini_get_i64 | Get value as i64. Returns 0 if not found. Parses directly from data buffer to… |
ini_has_section | Check if section exists. Returns 1 if found, 0 otherwise. |
ini_set | Set a value for section+key. Overwrites if exists, appends if new. Val and vl… |
_ini_write_section_kvs | Internal: write section’s key=value pairs. |
ini_write | Write INI data to out buffer. Returns length written. |
Details
_ini_byte_at
fn _ini_byte_at(buf: &i8, idx: i64) -> i64Internal byte reader.
context
Structs
CtxTimespec
struct CtxTimespec {
tv_sec: i64
tv_nsec: i64
}Functions
| Function | Description |
|---|---|
ctx_now_ns | |
ctx_background | |
ctx_with_cancel | |
ctx_with_deadline | |
ctx_with_timeout | |
ctx_cancel | |
ctx_done | |
ctx_done_chan | |
ctx_err | |
ctx_deadline |
Details
ctx_now_ns
fn ctx_now_ns() -> i64ctx_background
fn ctx_background() -> &i64ctx_with_cancel
fn ctx_with_cancel(parent: &i64) -> &i64ctx_with_deadline
fn ctx_with_deadline(parent: &i64, deadline_ns: i64) -> &i64ctx_with_timeout
fn ctx_with_timeout(parent: &i64, timeout_ns: i64) -> &i64ctx_cancel
fn ctx_cancel(ctx: &i64)ctx_done
fn ctx_done(ctx: &i64) -> i64ctx_done_chan
fn ctx_done_chan(ctx: &i64) -> &i64ctx_err
fn ctx_err(ctx: &i64) -> i64ctx_deadline
fn ctx_deadline(ctx: &i64) -> i64conv
Functions for converting between integers and their string representations in decimal, hexadecimal, and binary. All output is written to caller-provided buffers.
Usage
import conv
fn main() {
let buf: &i8 = alloc_pages(1)
// Integer to decimal string
let len = conv_itoa(42, buf)
syscall(1, 1, buf, len) // prints: 42
// Decimal string to integer
let n = conv_atoi("12345", 5)
print(n) // 12345
// Integer to hex
let hlen = conv_itohex(255, buf)
syscall(1, 1, buf, hlen) // prints: ff
// Hex string to integer
let h = conv_hextoi("1a2b", 4)
print(h) // 6699
// Integer to binary
let blen = conv_itobin(42, buf)
syscall(1, 1, buf, blen) // prints: 101010
// Zero-padded decimal
let plen = conv_itoa_pad(7, buf, 3)
syscall(1, 1, buf, plen) // prints: 007
}Function Reference
| Function | Signature | Description |
|---|---|---|
conv_itoa | (val: i64, dst: &i8) -> i64 | Integer to decimal string |
conv_atoi | (src: &i8, len: i64) -> i64 | Decimal string to integer |
conv_itohex | (val: i64, dst: &i8) -> i64 | Integer to hex string (lowercase) |
conv_hextoi | (src: &i8, len: i64) -> i64 | Hex string to integer |
conv_itobin | (val: i64, dst: &i8) -> i64 | Integer to binary string |
conv_itoa_pad | (val: i64, dst: &i8, width: i64) -> i64 | Integer to zero-padded decimal |
Detailed API
conv_itoa
fn conv_itoa(val: i64, dst: &i8) -> i64Convert an integer to its decimal string representation. Handles negative numbers (writes a leading -). The result is written to dst.
copy
Deep Copy Utilities
Functions
| Function | Description |
|---|---|
_cp_byte_at | Internal byte reader. |
copy_bytes | Copy n bytes from src to dst. Returns n. |
copy_i64_array | Copy an i64 array of given length. Returns new array pointer. |
copy_vec | Deep copy a vec structure. Vec layout: [0]=len, [1]=cap, [2..]=data |
copy_buf | Copy a byte buffer. Returns new buffer. |
copy_i64_range | Copy n i64 values from src+soff to dst+doff. |
Details
_cp_byte_at
fn _cp_byte_at(buf: &i8, idx: i64) -> i64Internal byte reader.
crypto
// jda::crypto — Cryptographic primitives
Constants
SHA256_BLOCK = 64 // bytes per blockSHA256_DIGEST = 32 // bytes in outputSHA1_DIGEST = 20AES_BLOCK = 16Structs
Sha256Ctx
struct Sha256Ctx {
state: u32[8] // H0-H7
count: u64 // total bytes hashed
buf: u8[64] // partial block
buf_len: i64
}Sha1Ctx
struct Sha1Ctx {
state: u32[5]
count: u64
buf: u8[64]
buf_len: i64
}AesCtx
struct AesCtx {
round_keys: u8[240] // enough for AES-256 (15×16 bytes)
nr: i32 // number of rounds: 10 for AES-128, 14 for AES-256
nk: i32 // key size in u32 words: 4 or 8
}Poly1305Ctx
struct Poly1305Ctx {
r: u32[5] // clamped key r (130-bit)
h: u32[5] // accumulator
pad: u32[4] // s (pad key)
}Functions
Details
sha256_k
fn sha256_k(i: i64) -> u32rotr32
fn rotr32(x: u32, n: u32) -> u32sha256_transform
fn sha256_transform(ctx: &Sha256Ctx, blk: &u8)sha256_init
fn sha256_init(ctx: &Sha256Ctx)sha256_update
fn sha256_update(ctx: &Sha256Ctx, data: &u8, len: i64)sha256_final
fn sha256_final(ctx: &Sha256Ctx, out: &u8)sha256
fn sha256(data: &u8, len: i64, out: &u8)rotl32
fn rotl32(x: u32, n: u32) -> u32sha1_transform
fn sha1_transform(ctx: &Sha1Ctx, blk: &u8)sha1_init
fn sha1_init(ctx: &Sha1Ctx)sha1_update
fn sha1_update(ctx: &Sha1Ctx, data: &u8, len: i64)sha1_final
fn sha1_final(ctx: &Sha1Ctx, out: &u8)sha1
fn sha1(data: &u8, len: i64, out: &u8)hmac_sha256
fn hmac_sha256(key: &u8, key_len: i64, msg: &u8, msg_len: i64, out: &u8)aes_sbox
fn aes_sbox(x: u8) -> u8xtime
fn xtime(x: u8) -> u8gf_mul
fn gf_mul(a: u8, b: u8) -> u8aes_key_expand
fn aes_key_expand(ctx: &AesCtx, key: &u8, key_len: i32)aes_add_round_key
fn aes_add_round_key(state: &u8, rk: &u8)aes_sub_bytes
fn aes_sub_bytes(state: &u8)aes_shift_rows
fn aes_shift_rows(state: &u8)aes_mix_columns
fn aes_mix_columns(state: &u8)aes_encrypt_block
fn aes_encrypt_block(ctx: &AesCtx, inp: &u8, out: &u8)aes_ctr
fn aes_ctr(ctx: &AesCtx, nonce: &u8, inp: &u8, len: i64, out: &u8)aes128_ctr_init
fn aes128_ctr_init(ctx: &AesCtx, key: &u8)aes256_ctr_init
fn aes256_ctr_init(ctx: &AesCtx, key: &u8)chacha20_quarter_round
fn chacha20_quarter_round(a: &u32, b: &u32, c: &u32, d: &u32)chacha20_block
fn chacha20_block(key: &u32, counter: u32, nonce: &u32, out: &u32)chacha20_encrypt
fn chacha20_encrypt(key: &u8, nonce: &u8, counter: u32,poly1305_init
fn poly1305_init(ctx: &Poly1305Ctx, key: &u8)poly1305_mac
fn poly1305_mac(key: &u8, msg: &u8, msg_len: i64, out: &u8)chacha20_poly1305_seal
fn chacha20_poly1305_seal(key: &u8, nonce: &u8,chacha20_poly1305_open
fn chacha20_poly1305_open(key: &u8, nonce: &u8,ct_memcmp
fn ct_memcmp(a: &u8, b: &u8, len: i64) -> i32hex_encode
fn hex_encode(inp: &u8, len: i64, out: &i8)base64_encode
fn base64_encode(inp: &u8, in_len: i64, out: &i8) -> i64csv
CSV (Comma-Separated Values) reader and writer. Parse CSV data into rows, extract individual fields as strings or integers, and write rows back to CSV format.
Usage
Reading CSV
import csv
fn main() {
let data = "name,age,city\nAlice,30,NYC\nBob,25,LA"
let len = 37
// Parse all rows
let rows = csv_parse_all(data, len)
let count = csv_row_count(rows)
print(count) // 3 (including header)
// Get a specific row
let row1 = csv_get_row(rows, 1) // "Alice,30,NYC"
print(csv_field_count(row1)) // 3
// Extract fields
let buf: &i8 = alloc_pages(1)
let flen = csv_field(row1, 0, buf) // copies "Alice" to buf
let age = csv_field_int(row1, 1) // 30
print(age)
}Writing CSV
import csv
fn main() {
// Prepare field data
let fields: &i64 = alloc_pages(1)
let lengths: &i64 = alloc_pages(1)
fields[0] = "Alice"
lengths[0] = 5
fields[1] = "30"
lengths[1] = 2
fields[2] = "NYC"
lengths[2] = 3
let out: &i8 = alloc_pages(1)
let n = csv_write_row(fields, lengths, 3, out)
// out[0..n] contains "Alice,30,NYC"
}Function Reference
| Function | Signature | Description |
|---|---|---|
csv_parse_row | (src: &i8, len: i64) -> &i64 | Parse a single CSV row |
csv_field_count | (row: &i64) -> i64 | Number of fields in a row |
csv_field | (row: &i64, idx: i64, dst: &i8) -> i64 | Copy field to buffer |
csv_field_int | (row: &i64, idx: i64) -> i64 | Parse field as integer |
csv_parse_all | (src: &i8, len: i64) -> &i64 | Parse all rows from CSV data |
csv_row_count | (rows: &i64) -> i64 | Number of parsed rows |
csv_get_row | (rows: &i64, idx: i64) -> &i64 | Get row by index |
csv_write_row | (fields: &i64, lengths: &i64, count: i64, dst: &i8) -> i64 | Write a CSV row |
Detailed API
csv_parse_row
fn csv_parse_row(src: &i8, len: i64) -> &i64Parse a single CSV row (one line) from the source buffer. Fields are separated by commas. The returned pointer is a row handle used with csv_field_count, csv_field, and csv_field_int.
data
// jda::ml::data — DataLoader & Dataset Primitives
Structs
Dataset
struct Dataset {
x: Tensor // shape [N x D_in]
y: Tensor // shape [N x D_out] (or [N] for classification)
n: i64 // number of samples (== x.shape[0])
x_dim: i64 // feature dimension
y_dim: i64 // label dimension
}Sampler
struct Sampler {
indices: []i64
pos: i64
n: i64
}Batch
struct Batch {
x: Tensor // [B x D_in]
y: Tensor // [B x D_out]
size: i64 // actual batch size (may be < requested at epoch end)
}DataLoader
struct DataLoader {
ds: ref Dataset
sampler: own Sampler
batch_size: i64
shuffle: bool
drop_last: bool // skip final incomplete batch
epoch: i64
seed: u64
}Functions
| Function | Description |
|---|---|
one_hot | |
csv_load | |
csv_count_rows | |
csv_count_cols | |
parse_csv_f32 |
Details
one_hot
fn one_hot(classes: ref []i64, n_classes: i64) -> Tensorcsv_load
fn csv_load(path: ref []i8, label_cols: i64) -> Result<own Dataset, []i8>csv_count_rows
fn csv_count_rows(src: ref []i8) -> i64csv_count_cols
fn csv_count_cols(src: ref []i8) -> i64parse_csv_f32
fn parse_csv_f32(src: ref []i8, pos: i64) -> (f32, i64)dataclass
Data Class Utilities
Functions
| Function | Description |
|---|---|
cmp_le | |
cmp_gt | |
cmp_ge | |
cmp | |
cmp_is_min | |
cmp_clamp | |
validate_range | |
validate_positive | |
validate_non_negative |
Details
cmp_le
fn cmp_le(lt: i64, eq: i64) -> i64cmp_gt
fn cmp_gt(lt: i64, eq: i64) -> i64cmp_ge
fn cmp_ge(lt: i64, eq: i64) -> i64cmp
fn cmp(lt_ab: i64, lt_ba: i64) -> i64cmp_is_min
fn cmp_is_min(lt: i64) -> i64cmp_clamp
fn cmp_clamp(val_lt_lo: i64, hi_lt_val: i64) -> i64validate_range
fn validate_range(val: i64, lo: i64, hi: i64) -> i64validate_positive
fn validate_positive(val: i64) -> i64validate_non_negative
fn validate_non_negative(val: i64) -> i64datetime
Date, Time, and DateTime Functions
Functions
| Function | Description |
|---|---|
_dt_time_syscall | Internal: get current time via time(2) syscall 201. |
dt_is_leap | Check if year is a leap year. |
dt_days_in_month | Days in a given month (1-12). |
dt_date | Convert year/month/day to days since epoch (1970-01-01 = day 0). |
dt_year | Extract year from days since epoch. |
_dt_day_of_year | Internal: remaining days after subtracting full years. |
dt_month | Extract month from days since epoch. |
dt_day | Extract day-of-month from days since epoch. |
dt_weekday | Day of week: 0=Thu (epoch was Thursday), 1=Fri, …, 6=Wed. More useful: (dt_… |
dt_now | Current unix timestamp in seconds. |
dt_from_ts | Convert unix timestamp to days since epoch. |
_dt_write2 | Internal: write 2-digit number to buffer. |
_dt_write4 | Internal: write 4-digit number to buffer. |
dt_format | Format timestamp as “YYYY-MM-DD HH:MM:SS”. Returns length (always 19). |
dt_diff | Difference between two timestamps in seconds. |
dt_add_days | Add days to a timestamp. |
dt_add_hours | Add hours to a timestamp. |
Details
_dt_time_syscall
fn _dt_time_syscall() -> i64Internal: get current time via time(2) syscall 201.
debug
A software debugger toolkit for Jda programs. Provides breakpoints that pause execution, variable inspection with formatted output, runtime assertions that abort on failure, watchpoints that detect value changes, and hit counters.
Usage
import debug
fn main() {
dbg_init()
dbg_enable()
let x = 42
dbg_inspect_int("x", x)
// Output: [DBG] x = 42
dbg_assert_eq(x, 42, "x should be 42")
// Watchpoints
dbg_watch(0, "x", &x)
x = 99
let changed = dbg_check()
// changed == 1
// Hit counter
dbg_counter_reset()
dbg_counter_inc()
dbg_counter_inc()
dbg_counter_print("iterations")
// Output: [DBG] iterations: 2
ret 0
}Function Reference
| Function | Signature | Description |
|---|---|---|
dbg_init | () | Initialise debugger state |
dbg_enable | () | Enable debug output |
dbg_disable | () | Disable debug output |
dbg_is_enabled | () -> i64 | Check if debugging is enabled |
dbg_print | (msg: &i8) | Print debug message (no newline) |
dbg_println | (msg: &i8) | Print debug message with newline |
dbg_break | (label: &i8) | Breakpoint — pauses execution via stdin read |
dbg_inspect_int | (name: &i8, val: i64) | Print [DBG] name = <decimal> |
dbg_inspect_hex | (name: &i8, val: i64) | Print [DBG] name = 0x<hex> |
dbg_inspect_ptr | (name: &i8, ptr: i64) | Print [DBG] name = 0x<hex> (pointer) |
dbg_inspect_bool | (name: &i8, val: i64) | Print [DBG] name = true/false |
dbg_assert | (cond: i64, msg: &i8) | Assert condition is truthy, abort if false |
dbg_assert_eq | (a: i64, b: i64, msg: &i8) | Assert a == b |
dbg_assert_ne | (a: i64, b: i64, msg: &i8) | Assert a != b |
dbg_assert_gt | (a: i64, b: i64, msg: &i8) | Assert a > b |
dbg_assert_lt | (a: i64, b: i64, msg: &i8) | Assert a < b |
dbg_watch | (slot: i64, name: &i8, ptr: &i64) | Watch a memory address for changes (max 16 slots) |
dbg_unwatch | (slot: i64) | Stop watching a slot |
dbg_watch_count | () -> i64 | Return number of active watchpoints |
dbg_check | () -> i64 | Check all watchpoints, return count of changed values |
dbg_counter_reset | () | Reset the hit counter to zero |
dbg_counter_inc | () | Increment the hit counter |
dbg_counter_get | () -> i64 | Return current counter value |
dbg_counter_print | (label: &i8) | Print [DBG] label: <count> |
Detailed API
dbg_init
fn dbg_init()Initialise the debugger. Resets all watchpoints, counters, and enables output. Call once at the start of your program.
decorator
Decorator / Higher-Order Function Patterns
Functions
| Function | Description |
|---|---|
apply1 | |
apply2 | |
fold | |
map_arr | |
filter_arr | |
for_each | |
find_idx | |
all_of | |
any_of | |
count_of | |
retry_call | |
pipeline | |
tabulate | |
zip_with |
Details
apply1
fn apply1(f: i64, x: i64) -> i64apply2
fn apply2(f: i64, x: i64, y: i64) -> i64fold
fn fold(f: i64, arr: &i64, len: i64, init: i64) -> i64map_arr
fn map_arr(f: i64, arr: &i64, len: i64, out: &i64) -> i64filter_arr
fn filter_arr(f: i64, arr: &i64, len: i64, out: &i64) -> i64for_each
fn for_each(f: i64, arr: &i64, len: i64) -> i64find_idx
fn find_idx(f: i64, arr: &i64, len: i64) -> i64all_of
fn all_of(f: i64, arr: &i64, len: i64) -> i64any_of
fn any_of(f: i64, arr: &i64, len: i64) -> i64count_of
fn count_of(f: i64, arr: &i64, len: i64) -> i64retry_call
fn retry_call(f: i64, arg: i64, max_attempts: i64) -> i64pipeline
fn pipeline(fns: &i64, nfns: i64, initial: i64) -> i64tabulate
fn tabulate(f: i64, out: &i64, n: i64) -> i64zip_with
fn zip_with(f: i64, xs: &i64, ys: &i64, len: i64, out: &i64) -> i64diff
Sequence Comparison and Diff
Functions
| Function | Description |
|---|---|
_diff_byte_at | Internal byte reader. |
diff_lcs_len | Compute Longest Common Subsequence length. Uses O(n*m) DP. Max input ~200 cha… |
diff_ratio | Compute similarity ratio * 10000. ratio = 2 * lcs_len / (alen + blen) * 10000 |
diff_lines | Simple line-by-line diff output. Lines prefixed with +/- / (space). Compares … |
Details
_diff_byte_at
fn _diff_byte_at(buf: &i8, idx: i64) -> i64Internal byte reader.
diff_lcs_len
fn diff_lcs_len(a: &i8, alen: i64, b: &i8, blen: i64) -> i64Compute Longest Common Subsequence length. Uses O(n*m) DP. Max input ~200 chars (limited by alloc_pages).
digest
Message Digest Algorithms
Functions
| Function | Description |
|---|---|
_dig_copy | Internal: byte copy. |
_dig_hex | Internal: hex digit. |
digest_hex | Convert binary hash to hex string. Returns hex length (2 * hlen). |
_md5_s | Internal: MD5 per-round shift amounts. |
_md5_t | Internal: MD5 sine-derived constants (T[i] = floor(2^32 * abs(sin(i+1)))). |
_md5_rotl | Internal: 32-bit left rotate. |
_md5_read32 | Internal: read 32-bit LE from buffer. |
_md5_write32 | Internal: write 32-bit LE to buffer. |
md5 | MD5 hash. out must be 16 bytes. |
md5_hex | MD5 as hex string. Returns 32. |
_sha512_k | SHA-512 round constants (first 16 of 80). |
sha512 | SHA-512 hash. out must be 64 bytes. Note: Simplified implementation — produ… |
sha512_hex | SHA-512 as hex string. Returns 128. |
Details
_dig_copy
fn _dig_copy(dst: &i8, doff: i64, src: &i8, soff: i64, n: i64)Internal: byte copy.
dns
DNS Resolver
Functions
| Function | Description |
|---|---|
_dns_copy | |
_dns_open_read | |
_dns_read | |
_dns_close | |
_dns_socket_udp | |
_dns_sendto | |
_dns_connect | |
_dns_send | |
_dns_recv | |
_dns_close_sock | |
dns_nameserver | Internal: parse /etc/resolv.conf to find first nameserver IP. Writes 4 bytes … |
_dns_build_query | Internal: build DNS query packet for A record. Returns packet length. |
dns_resolve | Resolve hostname to IPv4. Writes 4 bytes to out. Returns 1 on success. |
dns_resolve_str | Resolve hostname to “x.x.x.x” string. Returns string length. |
Details
_dns_copy
fn _dns_copy(dst: &i8, doff: i64, src: &i8, soff: i64, n: i64)_dns_open_read
fn _dns_open_read(path: &i8) -> i64_dns_read
fn _dns_read(fd: i64, buf: &i8, max: i64) -> i64_dns_close
fn _dns_close(fd: i64) -> i64_dns_socket_udp
fn _dns_socket_udp() -> i64_dns_sendto
fn _dns_sendto(fd: i64, buf: &i8, len: i64, addr: &i8) -> i64_dns_connect
fn _dns_connect(fd: i64, addr: &i8, addrlen: i64) -> i64_dns_send
fn _dns_send(fd: i64, buf: &i8, len: i64) -> i64_dns_recv
fn _dns_recv(fd: i64, buf: &i8, max: i64) -> i64_dns_close_sock
fn _dns_close_sock(fd: i64) -> i64dns_nameserver
fn dns_nameserver(out: &i8) -> i64Internal: parse /etc/resolv.conf to find first nameserver IP. Writes 4 bytes to out. Returns 1 if found, 0 if not.
Email Message Parser/Composer
Functions
| Function | Description |
|---|---|
_email_byte_at | Internal byte reader. |
_email_copy | Internal: copy bytes. |
_email_lower | Internal: case-insensitive compare single bytes. |
_email_eq_ci | Internal: case-insensitive compare. |
_email_find_body | Internal: find the blank line separating headers from body. Returns offset of… |
_email_parse_hdr | Internal: parse one header line starting at pos. Sets name_off, name_len, val… |
email_parse | Parse an email message. Returns handle. |
_email_get_hdr | Internal: find header by name (case-insensitive), copy value to out. |
email_from | Get From header value. |
email_to | Get To header value. |
email_subject | Get Subject header value. |
email_body | Get email body. |
email_header | Get any header value by name. |
email_header_count | Return number of headers. |
Details
_email_byte_at
fn _email_byte_at(buf: &i8, idx: i64) -> i64Internal byte reader.
encoding
Character Encoding Utilities
Functions
| Function | Description |
|---|---|
enc_utf8_valid | Validate UTF-8 byte sequence. Returns 1 if valid, 0 if invalid. |
enc_utf8_char_count | Count UTF-8 codepoints in buffer. |
enc_utf8_byte_len | Byte length of first nchars codepoints. |
enc_is_ascii | Check if all bytes are ASCII (< 128). |
enc_to_upper | Convert ASCII lowercase to uppercase. Returns length. |
enc_to_lower | Convert ASCII uppercase to lowercase. Returns length. |
enc_latin1_to_utf8 | Convert Latin-1 (ISO 8859-1) to UTF-8. Returns output length. |
enc_utf8_codepoint_at | Read UTF-8 codepoint at byte offset. Returns codepoint value. |
enc_utf8_next | Get next byte offset after codepoint at given offset. |
Details
enc_utf8_valid
fn enc_utf8_valid(buf: &i8, len: i64) -> i64Validate UTF-8 byte sequence. Returns 1 if valid, 0 if invalid.
enum
Enumeration Type with Named Constants
Functions
| Function | Description |
|---|---|
_enum_byte_at | Internal byte reader. |
_enum_streq | Internal: compare two strings. |
_enum_copy | Internal: copy bytes. |
enum_new | Create a new enum type. name/nlen is the enum’s name (for display). Layout: [… |
enum_add | Add a variant to the enum. Returns index on success, -1 if full. |
enum_by_name | Lookup value by variant name. Returns value or -1 if not found. |
enum_by_val | Lookup name by value. Writes name to out, returns length. -1 if not found. |
enum_count | Return number of variants. |
enum_has | Check if a variant name exists. Returns 1 or 0. |
enum_name_at | Get variant name at index. Returns length written, -1 if out of bounds. |
enum_val_at | Get variant value at index. Returns -1 if out of bounds. |
Details
_enum_byte_at
fn _enum_byte_at(buf: &i8, idx: i64) -> i64Internal byte reader.
erb
Template Engine
Functions
| Function | Description |
|---|---|
_erb_copy | |
_erb_streq | |
erb_vars_new | Create variable map. |
erb_vars_set | Set a variable in the map. |
_erb_lookup | Internal: lookup variable value. Returns value length, copies to out. |
erb_render | Render template with variable substitution. Replaces <%= name %> with variabl… |
erb_escape_html | HTML-escape string (&, <, >, “, ‘). Returns output length. |
Details
_erb_copy
fn _erb_copy(dst: &i8, doff: i64, src: &i8, soff: i64, n: i64)_erb_streq
fn _erb_streq(a: &i8, aoff: i64, alen: i64, b: &i8, boff: i64, blen: i64) -> i64erb_vars_new
fn erb_vars_new() -> &i64Create variable map.
errno
Named Error Constants and Descriptions
Functions
| Function | Description |
|---|---|
_errno_copy | Internal: copy string literal to output buffer. |
_errno_byte_at | Internal byte reader helper. |
_errno_streq | Internal: compare two strings. |
errno_name | Get the name string for an errno code. Returns length written, -1 if unknown. |
errno_desc | Get a human-readable description for an errno code. |
errno_from_name | Lookup errno code by name string. Returns code or -1 if unknown. |
Details
_errno_copy
fn _errno_copy(dst: &i8, src: &i8, len: i64) -> i64Internal: copy string literal to output buffer.
file_io
Ergonomic wrappers around the low-level fs package. Provides Python-style convenience for reading entire files, writing strings, copying, renaming, and working with paths. Depends on fs.jda.
Usage
import fs
import file_io
fn main() {
// Read an entire file
let buf = fs_slurp("/tmp/data.txt")
let size = fs_file_size("/tmp/data.txt")
// Count lines
let lines = buf_count_lines(buf, size)
print(lines)
// Write a string to a file
fs_write_str("/tmp/out.txt", "hello world\n", 12)
// Copy a file
fs_copy("/tmp/out.txt", "/tmp/backup.txt")
// Path manipulation
let out: &i8 = alloc_pages(1)
let len = path_join("/home/user", 10, "file.txt", 8, out)
// out now contains: /home/user/file.txt
}Function Reference
| Function | Signature | Description |
|---|---|---|
fs_slurp | (path: &i8) -> i64 | Read entire file into a buffer |
fs_write_str | (path: &i8, data: &i8, len: i64) -> i64 | Write string to file |
fs_append_str | (path: &i8, data: &i8, len: i64) -> i64 | Append string to file |
fs_copy | (src: &i8, dst: &i8) -> i64 | Copy a file |
fs_rename | (src: &i8, dst: &i8) -> i64 | Rename/move a file |
fs_tmpname | (out: &i8, suffix: i64) -> i64 | Generate a temp file path |
buf_count_lines | (buf: &i8, len: i64) -> i64 | Count lines in a buffer |
buf_line_start | (buf: &i8, len: i64, line_idx: i64) -> i64 | Get offset of line N |
buf_line_len | (buf: &i8, total_len: i64, start: i64) -> i64 | Get length of line at offset |
path_join | (dir: &i8, dir_len: i64, name: &i8, name_len: i64, out: &i8) -> i64 | Join directory and filename |
path_basename | (path: &i8, len: i64) -> i64 | Find basename offset in path |
path_ext | (path: &i8, len: i64) -> i64 | Find extension dot offset |
cstr_length | (s: &i8) -> i64 | Length of null-terminated string |
buf_eq | (a: &i8, b: &i8, n: i64) -> i64 | Compare n bytes for equality |
Detailed API
fs_slurp
fn fs_slurp(path: &i8) -> i64Read an entire file into an auto-allocated buffer. Uses fs_file_size to determine the size, allocates pages, and reads the file contents. Use fs_file_size separately to get the byte count.
fileutils
High-Level File Utilities
Functions
| Function | Description |
|---|---|
_fu_rename | |
_fu_chmod_raw | |
_fu_rmdir_raw | |
_fu_open_creat | |
_fu_close | |
_fu_mkdir | |
_fu_access | |
_fu_unlink | |
_fu_open_read | |
_fu_read | |
_fu_open_write | |
_fu_write | |
_fu_getdents | |
_fu_strlen | |
_fu_copy_bytes | |
fu_mkdir_p | Recursive mkdir -p. Creates all intermediate directories. Path must be null-t… |
fu_rmdir | Remove empty directory. |
fu_rm_rf | Recursive rm -rf. Removes files and directories. |
fu_cp | Copy a single file. Returns bytes copied or -1 on error. |
fu_mv | Move/rename file or directory. |
fu_touch | Create empty file (or truncate existing). |
fu_chmod | Change file permissions. |
fu_file_eq | Compare two files for content equality. Returns 1 if equal, 0 if not. |
Details
_fu_rename
fn _fu_rename(old: &i8, new_path: &i8) -> i64_fu_chmod_raw
fn _fu_chmod_raw(path: &i8, mode: i64) -> i64_fu_rmdir_raw
fn _fu_rmdir_raw(path: &i8) -> i64_fu_open_creat
fn _fu_open_creat(path: &i8) -> i64_fu_close
fn _fu_close(fd: i64) -> i64_fu_mkdir
fn _fu_mkdir(path: &i8) -> i64_fu_access
fn _fu_access(path: &i8) -> i64_fu_unlink
fn _fu_unlink(path: &i8) -> i64_fu_open_read
fn _fu_open_read(path: &i8) -> i64_fu_read
fn _fu_read(fd: i64, buf: &i8, max: i64) -> i64_fu_open_write
fn _fu_open_write(path: &i8) -> i64_fu_write
fn _fu_write(fd: i64, data: &i8, len: i64) -> i64_fu_getdents
fn _fu_getdents(fd: i64, buf: &i8, size: i64) -> i64_fu_strlen
fn _fu_strlen(s: &i8) -> i64_fu_copy_bytes
fn _fu_copy_bytes(dst: &i8, doff: i64, src: &i8, soff: i64, n: i64)fu_mkdir_p
fn fu_mkdir_p(path: &i8) -> i64Recursive mkdir -p. Creates all intermediate directories. Path must be null-terminated. Returns 0 on success.
find
Recursive Directory Traversal
Constants
FIND_DT_DIR = 4FIND_DT_REG = 8Functions
| Function | Description |
|---|---|
find_strlen | Internal: strlen of null-terminated string. |
find_copy | Internal: copy bytes. |
find_join_path | Internal: build full path “dir/name” into dst, return length. |
find_is_dot | Internal: is this “.” or “..”? |
find_add_entry | Internal: store a path in the result. |
find_readdir | Internal: read directory entries using getdents64. |
find_walk | Recursively walk a directory. Returns FindResult. |
find_count | Number of entries found. |
find_path | Copy path at index to dst. Returns length. |
find_type | Entry type at index. |
find_is_file | Is entry at index a regular file? |
find_is_dir | Is entry at index a directory? |
find_files | Walk directory returning only files. |
Details
find_strlen
fn find_strlen(s: &i8) -> i64Internal: strlen of null-terminated string.
fixedpoint
Scaled Integer Arithmetic (4 Decimal Places)
Functions
| Function | Description |
|---|---|
_fp_byte_at | Internal byte reader. |
fp_from_int | Convert integer to fixed-point. |
fp_from_parts | Create from whole and fractional parts (frac is 0-9999). |
fp_add | Add two fixed-point values. |
fp_sub | Subtract two fixed-point values. |
fp_mul | Multiply two fixed-point values. |
fp_div | Divide two fixed-point values. |
fp_whole | Get whole part. |
fp_frac | Get fractional part (0-9999). |
fp_cmp | Compare: -1, 0, or 1. |
fp_abs | Absolute value. |
fp_sqrt | Square root of fixed-point value. |
fp_to_str | Format fixed-point value to string. Returns length. |
fp_from_str | Parse fixed-point from string. Returns scaled value. |
Details
_fp_byte_at
fn _fp_byte_at(buf: &i8, idx: i64) -> i64Internal byte reader.
fmt
Minimal String Formatting
Functions
| Function | Description |
|---|---|
fmt_i64 | |
fmt_hex | |
str_len | |
str_eq | |
str_copy | |
mem_set | |
eprint_str | |
print_str |
Details
fmt_i64
fn fmt_i64(buf: &i8, val: i64) -> i64fmt_hex
fn fmt_hex(buf: &i8, val: i64) -> i64str_len
fn str_len(s: &i8) -> i64str_eq
fn str_eq(a: &i8, b: &i8) -> i64str_copy
fn str_copy(dst: &i8, src: &i8, len: i64) -> i64mem_set
fn mem_set(dst: &i8, val: i64, len: i64)eprint_str
fn eprint_str(s: &i8, len: i64)print_str
fn print_str(s: &i8, len: i64)fnmatch
Filename Pattern Matching
Functions
| Function | Description |
|---|---|
_fnm_byte_at | Internal byte reader. |
_fnm_match | Internal: recursive match helper. Returns 1 if pat[pi..] matches name[ni..]. |
fnmatch | Match a filename against a glob pattern. Returns 1 if matches. |
fnmatch_has_magic | Check if pattern contains glob special characters (*, ?, [). |
fnmatch_escape | Escape glob special characters in a path. Returns length written. |
Details
_fnm_byte_at
fn _fnm_byte_at(buf: &i8, idx: i64) -> i64Internal byte reader.
_fnm_match
fn _fnm_match(pat: &i8, plen: i64, pi: i64, name: &i8, nlen: i64, ni: i64) -> i64Internal: recursive match helper. Returns 1 if pat[pi..] matches name[ni..].
fs
Minimal file I/O via direct Linux syscalls. No libc dependency. Each internal helper function contains at most one syscall to avoid register corruption in the current compiler.
For higher-level convenience functions, see file_io.
Usage
import fs
fn main() {
// Write a file
let data = "Hello from Jda!\n"
fs_write_file("/tmp/hello.txt", data, 16)
// Check existence
if fs_exists("/tmp/hello.txt") == 1 {
print(1) // file exists
}
// Read it back
let buf: &i8 = alloc_pages(1)
let n = fs_read_file("/tmp/hello.txt", buf, 4096)
print(n) // 16
// Get file size
let size = fs_file_size("/tmp/hello.txt")
print(size) // 16
// Create a directory
fs_mkdir("/tmp/jda_test")
// Clean up
fs_unlink("/tmp/hello.txt")
}Function Reference
| Function | Signature | Description |
|---|---|---|
fs_read_file | (path: &i8, buf: &i8, max_bytes: i64) -> i64 | Read file into buffer |
fs_write_file | (path: &i8, data: &i8, len: i64) -> i64 | Write data to file (create/truncate) |
fs_append_file | (path: &i8, data: &i8, len: i64) -> i64 | Append data to file |
fs_exists | (path: &i8) -> i64 | Check if file exists |
fs_unlink | (path: &i8) -> i64 | Delete a file |
fs_mkdir | (path: &i8) -> i64 | Create a directory (mode 0755) |
fs_file_size | (path: &i8) -> i64 | Get file size in bytes |
Detailed API
fs_read_file
fn fs_read_file(path: &i8, buf: &i8, max_bytes: i64) -> i64Read up to max_bytes from a file into the provided buffer. Opens the file, reads in a loop until EOF or max_bytes is reached, then closes the file descriptor.
ftp
FTP Protocol Helpers
Functions
| Function | Description |
|---|---|
_ftp_byte_at | Internal byte reader. |
_ftp_copy | Internal: copy bytes. |
_ftp_crlf | Internal: write CRLF. |
ftp_format_user | Format USER command: “USER user\r\n” |
ftp_format_pass | Format PASS command: “PASS pass\r\n” |
ftp_format_retr | Format RETR command: “RETR name\r\n” |
ftp_format_cwd | Format CWD command: “CWD path\r\n” |
ftp_format_list | Format LIST command: “LIST\r\n” |
ftp_parse_reply | Parse FTP reply code from buffer (first 3 digits). |
_ftp_parse_num | Internal: parse a decimal number from buf starting at pos, until comma or ‘)’. |
_ftp_skip_num | Internal: find next comma or ‘)’ position from pos. |
ftp_parse_pasv | Parse PASV response: “227 Entering Passive Mode (h1,h2,h3,h4,p1,p2).” Extract… |
Details
_ftp_byte_at
fn _ftp_byte_at(buf: &i8, idx: i64) -> i64Internal byte reader.
getpass
Password Input Helpers
Functions
| Function | Description |
|---|---|
_getpass_byte_at | Internal byte reader. |
getpass_mask | Replace each byte of input with ‘*’ (42). Returns len. |
getpass_validate_len | Check if len is between min and max inclusive. Returns 1 if valid. |
_getpass_has_digit | Internal: check if password has at least one digit. |
_getpass_has_upper | Internal: check if password has at least one uppercase letter. |
_getpass_has_lower | Internal: check if password has at least one lowercase letter. |
_getpass_has_special | Internal: check if password has at least one special character. |
getpass_strength | Compute password strength score (0-4). +1 for length >= 8, +1 for digit, +1 f… |
Details
_getpass_byte_at
fn _getpass_byte_at(buf: &i8, idx: i64) -> i64Internal byte reader.
glob
Glob Pattern Matching (fnmatch-style)
Functions
| Function | Description |
|---|---|
_glob_byte_at | Internal byte reader. |
_glob_match_class | Internal: match character class [abc] or [!abc]. Returns packed value: matche… |
_glob_do_match | Internal recursive match with bounded depth. pi=pattern index, si=string index. |
glob_match | Match a glob pattern against a string. Returns 1 if matches, 0 otherwise. |
glob_has_magic | Check if pattern contains wildcard characters (*, ?, [). |
glob_escape | Escape special glob characters in str. Wraps each *, ?, [, ] in [x]. Returns … |
Details
_glob_byte_at
fn _glob_byte_at(buf: &i8, idx: i64) -> i64Internal byte reader.
gzip
Gzip Format (Stored Blocks Only)
Functions
| Function | Description |
|---|---|
_gz_byte_at | Internal byte reader. |
_gz_crc32_byte | CRC-32 table (precomputed for polynomial 0xEDB88320). We compute it on-the-fl… |
gzip_crc32 | Compute CRC-32 of buffer. |
_gz_write16 | Internal: write little-endian 16-bit value. |
_gz_write32 | Internal: write little-endian 32-bit value. |
_gz_read32 | Internal: read little-endian 32-bit value. |
gzip_compress | Compress data with gzip stored-block format. Returns output length. |
gzip_is_gzip | Check if buffer starts with gzip magic bytes. |
gzip_orig_size | Read original size from gzip trailer (last 4 bytes). |
gzip_decompress | Decompress gzip stored-block data. Returns output length. |
Details
_gz_byte_at
fn _gz_byte_at(buf: &i8, idx: i64) -> i64Internal byte reader.
hashmap
Hash map mapping i64 keys to i64 values. Uses open addressing with linear probing and power-of-2 capacity. Automatic rehashing at 70% load factor. No external dependencies.
Also provides string-keyed convenience functions (map_puts, map_gets, map_hass) that hash byte buffers with djb2 and use the hash as the integer key.
Memory Layout
Each map is a pointer to a 5-word header (&i64):
| Offset | Field | Description |
|---|---|---|
[0] | capacity | Always a power of 2 |
[1] | size | Number of occupied entries |
[2] | keys_ptr | &i64 array of keys |
[3] | vals_ptr | &i64 array of values |
[4] | state_ptr | &i64 array (0=empty, 1=occupied, 2=tombstone) |
Usage
import hashmap
fn main() {
let m = map_new(64)
// Integer keys
map_put(m, 42, 100)
map_put(m, 99, 200)
print(map_get(m, 42)) // 100
print(map_has(m, 99)) // 1
// String keys
map_puts(m, "name", 4, 1001)
map_puts(m, "age", 3, 30)
print(map_gets(m, "name", 4)) // 1001
print(map_hass(m, "age", 3)) // 1
// Delete
map_del(m, 42)
print(map_has(m, 42)) // 0
print(map_len(m)) // 3
}Function Reference
| Function | Signature | Description |
|---|---|---|
map_new | (cap: i64) -> &i64 | Create a new hash map |
map_put | (m: &i64, key: i64, val: i64) | Insert or update a key-value pair |
map_get | (m: &i64, key: i64) -> i64 | Lookup value by key (0 if missing) |
map_has | (m: &i64, key: i64) -> i64 | Check if key exists |
map_del | (m: &i64, key: i64) -> i64 | Delete a key |
map_len | (m: &i64) -> i64 | Get entry count |
map_puts | (m: &i64, key: &i8, klen: i64, val: i64) | String-keyed insert |
map_gets | (m: &i64, key: &i8, klen: i64) -> i64 | String-keyed lookup |
map_hass | (m: &i64, key: &i8, klen: i64) -> i64 | String-keyed existence check |
hash_i64 | (key: i64) -> i64 | Hash an integer (Knuth multiplicative) |
str_hash | (s: &i8, len: i64) -> i64 | Hash a byte buffer (djb2) |
Detailed API
map_new
fn map_new(cap: i64) -> &i64Create a new hash map with the given capacity. Capacity is rounded up to the next power of 2, with a minimum of 16. The map is initially empty.
heap
Binary Heap (generic min/max)
Functions
| Function | Description |
|---|---|
heap_pages_for | |
heap_new | |
heap_min | |
heap_max | |
heap_cmp | Internal: should a come before b based on heap mode? |
heap_grow | |
heap_sift_up | |
heap_sift_down | |
heap_push | |
heap_pop | |
heap_peek | |
heap_len | |
heap_empty | |
heap_from_vec | Build heap from existing vec. |
heap_sort | Heap sort a vec ascending in-place. |
Details
heap_pages_for
fn heap_pages_for(n: i64) -> i64heap_new
fn heap_new(cap: i64, mode: i64) -> &i64heap_min
fn heap_min(cap: i64) -> &i64heap_max
fn heap_max(cap: i64) -> &i64heap_cmp
fn heap_cmp(a: i64, b: i64, mode: i64) -> i64Internal: should a come before b based on heap mode?
htmlparser
Simple HTML Tag Parser (SAX-style events)
Functions
| Function | Description |
|---|---|
_html_byte_at | Internal byte reader. |
_html_copy | Internal: copy bytes from src+off to dst+doff, length n. |
_html_add_evt | Internal: add an event to the handle. |
_html_find_gt | Internal: find ‘>’ starting from pos. Returns index of ‘>’ or len if not found. |
_html_find_lt | Internal: find ‘<’ starting from pos. Returns index of ‘<’ or len if not found. |
_html_tag_end | Internal: find end of tag name (space or end). Returns index. |
html_parse | Parse HTML buffer into events. |
html_event_count | Return event count. |
html_event_type | Return event type at index (1=open, 2=close, 3=text). |
html_event_tag | Copy tag name at event idx to out. Return length. |
html_event_text | Copy text content at event idx to out. Return length. |
html_strip_tags | Strip all HTML tags, return plain text length. |
_html_poke_amp | Internal: poke a string literal byte sequence for HTML escape. |
_html_poke_lt | |
_html_poke_gt | |
_html_poke_quot | |
html_escape | Escape HTML special characters: & < > " |
Details
_html_byte_at
fn _html_byte_at(buf: &i8, idx: i64) -> i64Internal byte reader.
http
HTTP/1.1 request parser and response writer. Parses raw HTTP request bytes into structured data and writes formatted HTTP responses to TCP sockets. Designed for use with the tcp package.
Types
HttpRequest
Parsed HTTP request with zero-copy slices into the raw buffer:
struct HttpRequest {
method: []i8 // "GET", "POST", etc.
path: []i8 // "/index.html"
query: []i8 // "key=val&key2=val2" (empty if no query)
version: []i8 // "HTTP/1.1"
headers: []Header // parsed headers (up to MAX_HEADERS)
body: []i8 // request body (empty for GET/HEAD)
}Header
A single HTTP header as name-value pair:
httpclient
HTTP Client Helpers
Functions
| Function | Description |
|---|---|
_hcli_byte_at | Internal byte reader. |
_hcli_copy | Internal: copy bytes. |
_hcli_parse_int | Internal: parse integer from ASCII digits at position. |
_hcli_find_body | Internal: find double CRLF. Returns offset of body start or -1. |
_hcli_lower | Internal: compare bytes case-insensitively. |
_hcli_eq_nocase | |
http_parse_response | Parse an HTTP response. Returns handle. |
http_resp_status | Get status code. |
http_resp_header | Get a header value. Searches for “Name: value\r\n”. Returns length of value c… |
http_resp_body_offset | Get body start offset. |
http_resp_body_len | Get body length. |
http_build_get_request | Build a GET request. Returns total length in out. |
Details
_hcli_byte_at
fn _hcli_byte_at(buf: &i8, idx: i64) -> i64Internal byte reader.
httpserver
HTTP Server Helpers
Functions
| Function | Description |
|---|---|
_hsrv_byte_at | Internal byte reader. |
_hsrv_copy | Internal: copy bytes. |
_hsrv_starts | Internal: check if buf at off starts with prefix of plen bytes. |
_hsrv_find_body | Internal: find double CRLF (header/body separator). Returns offset or -1. |
_hsrv_write_http11 | Internal: write a string literal byte-by-byte. Returns new offset. Writes “HT… |
_hsrv_write_crlf | Internal: write CRLF. Returns new offset. |
_hsrv_write_int | Internal: write integer as decimal. Returns new offset. Handles values up to … |
http_parse_request | Parse an HTTP request. Returns handle. |
http_req_method | Get method code (0=GET, 1=POST, 2=PUT, 3=DELETE, 4=PATCH, 5=HEAD). |
http_req_path | Copy path to output buffer. Returns path length. |
http_req_path_len | Get path length. |
http_respond_ok | Format a 200 OK response with body. Returns total length in out. |
http_respond_404 | Format a 404 Not Found response. Returns total length in out. |
http_status_line | Format a status line for a given code. Returns length. |
Details
_hsrv_byte_at
fn _hsrv_byte_at(buf: &i8, idx: i64) -> i64Internal byte reader.
io
Buffered I/O and Stream Helpers
Functions
| Function | Description |
|---|---|
io_read_stdin | |
io_write_stdout | |
io_write_stderr | |
io_read_line | |
io_read_fd | |
io_write_fd | |
io_flush_fd | |
io_print_i64 | |
io_print_str | |
io_println |
Details
io_read_stdin
fn io_read_stdin(buf: &i8, max_bytes: i64) -> i64io_write_stdout
fn io_write_stdout(data: &i8, len: i64) -> i64io_write_stderr
fn io_write_stderr(data: &i8, len: i64) -> i64io_read_line
fn io_read_line(fd: i64, buf: &i8, max_bytes: i64) -> i64io_read_fd
fn io_read_fd(fd: i64, buf: &i8, max_bytes: i64) -> i64io_write_fd
fn io_write_fd(fd: i64, data: &i8, len: i64) -> i64io_flush_fd
fn io_flush_fd(fd: i64) -> i64io_print_i64
fn io_print_i64(val: i64) -> i64io_print_str
fn io_print_str(s: &i8, len: i64) -> i64io_println
fn io_println(s: &i8, len: i64) -> i64ipaddr
IP Address Parsing and Manipulation
Functions
| Function | Description |
|---|---|
ip_from_octets | Build IP from 4 octets. |
ip_octet | Get octet n (0=first/MSB, 3=last/LSB). |
ip_parse | Parse “a.b.c.d” string to integer. |
ip_write_int | Internal: write integer digits to buffer, return length. |
ip_format | Format integer IP to “a.b.c.d” string. Returns length. |
ip_is_private | Is this a private (RFC 1918) address? |
ip_is_loopback | Is this a loopback address? |
ip_is_multicast | Is this a multicast address? |
ip_mask | Internal: create subnet mask from prefix length. |
ip_network | Network address for addr/prefix. |
ip_broadcast | Broadcast address for addr/prefix. |
ip_in_subnet | Check if addr is within network/prefix. |
ip_to_sockaddr | Write struct sockaddr_in (16 bytes) to dst for use with connect/bind. AF_INET… |
Details
ip_from_octets
fn ip_from_octets(a: i64, b: i64, c: i64, d: i64) -> i64Build IP from 4 octets.
iter
Chainable Iterator Adapters
Functions
Details
iter_from
fn iter_from(arr: &i64, len: i64) -> i64iter_map
fn iter_map(f: i64) -> i64iter_filter
fn iter_filter(f: i64) -> i64iter_take
fn iter_take(n: i64) -> i64iter_skip
fn iter_skip(n: i64) -> i64iter_chain
fn iter_chain(arr2: &i64, len2: i64) -> i64iter_apply_one
fn iter_apply_one(val: i64) -> i64iter_materialize
fn iter_materialize(out: &i64) -> i64iter_collect
fn iter_collect(out: &i64) -> i64iter_sum
fn iter_sum() -> i64iter_count
fn iter_count() -> i64iter_any
fn iter_any(f: i64) -> i64iter_all
fn iter_all(f: i64) -> i64iter_find
fn iter_find(f: i64) -> i64iter_fold
fn iter_fold(init: i64, f: i64) -> i64iter_foreach
fn iter_foreach(f: i64) -> i64iter_min
fn iter_min() -> i64iter_max
fn iter_max() -> i64iter_enumerate
fn iter_enumerate(out_idx: &i64, out_val: &i64) -> i64iter_zip
fn iter_zip(arr2: &i64, out_a: &i64, out_b: &i64) -> i64json
Zero-copy JSON parser and serialiser. The parser returns slices that point directly into the source buffer – no allocations for strings. The serialiser writes directly to a caller-supplied buffer. Both are thread-safe (no global state).
Types
JsonValue (enum)
A tagged union covering all JSON types:
enum JsonValue {
Null
Bool(bool)
Int(i64)
Float(f64)
Str([]i8) // slice into original source buffer (zero-copy)
Array([]JsonValue) // elements stored in caller's region
Object([]JsonPair) // key-value pairs
}JsonPair (struct)
struct JsonPair {
key: []i8 // slice into source buffer
val: JsonValue
}Parser (struct)
struct Parser {
src: []i8
pos: i64
}Usage
Parsing JSON
import json
fn main() {
let src = "{\"name\": \"Jda\", \"version\": 1, \"fast\": true}"
let val = json_parse(src).unwrap()
let name = val.get("name").unwrap().as_str().unwrap()
let version = val.get("version").unwrap().as_i64().unwrap()
let fast = val.get("fast").unwrap().as_bool().unwrap()
}Writing JSON
import json
fn main() {
let val = JsonValue::Object([
JsonPair { key: "status", val: JsonValue::Str("ok") },
JsonPair { key: "code", val: JsonValue::Int(200) },
])
let buf = [4096]i8
let n = json_write(val, buf)
// buf now contains: {"status":"ok","code":200}
// Pretty-printed output
let n2 = json_write_pretty(val, buf)
}Function Reference
| Function | Signature | Description |
|---|---|---|
json_parse | (src: []i8) -> Result<JsonValue, []i8> | Parse a JSON string into a value |
json_write | (val: ref JsonValue, buf: []mut i8) -> i64 | Serialise to compact JSON |
json_write_pretty | (val: ref JsonValue, buf: []mut i8) -> i64 | Serialise to indented JSON |
Detailed API
json_parse
fn json_parse(src: []i8) -> Result<JsonValue, []i8>Parse a complete JSON document from src. Returns Ok(JsonValue) on success or Err(message) on failure. Trailing characters after the root value are an error.
kvstore
Simple Key-Value Store
Functions
| Function | Description |
|---|---|
_kv_byte_at | Internal byte reader. |
_kv_copy | Internal: copy bytes. |
_kv_eq | Internal: compare two byte ranges. |
_kv_find | Internal: find key index, returns -1 if not found. |
kv_new | Create a new key-value store. |
kv_put | Insert or update a key-value pair. Returns 1 on update, 0 on insert. |
kv_get | Get value for a key. Copies to out buffer. Returns length, or -1 if not found. |
kv_del | Delete a key. Returns 1 if found, 0 if not found. |
kv_has | Check if key exists. Returns 1 or 0. |
kv_count | Return the number of active entries. |
kv_keys | Copy key data into out buffer. Returns number of keys written. For each key: … |
kv_key_copy | Copy key bytes to output buffer given index from kv_keys. |
Details
_kv_byte_at
fn _kv_byte_at(buf: &i8, idx: i64) -> i64Internal byte reader.
linecache
Random Access to Text Lines in Files
Functions
| Function | Description |
|---|---|
_lc_byte_at | Internal byte reader helper. |
_lc_open | Internal: read file via syscalls. |
_lc_read | Internal: read from fd. |
_lc_close | Internal: close fd. |
linecache_open | Open a file and index its lines. Layout: [0]=line_count, [1]=data_ptr, [2]=da… |
linecache_getline | Get a line by number (1-based). Returns length, -1 if out of range. |
linecache_count | Return total number of lines. |
linecache_close | Release linecache (no-op in Jda — no GC, no free). |
Details
_lc_byte_at
fn _lc_byte_at(buf: &i8, idx: i64) -> i64Internal byte reader helper.
lint
A code style checker for Jda source code. Validates naming conventions (snake_case for functions/variables, UPPER_SNAKE for constants, PascalCase for structs), checks line length, and detects trailing whitespace.
Usage
import lint
fn main() {
lint_init()
// Check naming conventions
lint_check_fn("my_function") // OK — snake_case
lint_check_fn("myFunction") // warning — not snake_case
lint_check_const("MAX_SIZE") // OK — UPPER_SNAKE
lint_check_struct("MyStruct") // OK — PascalCase
// Check line style
lint_check_line_len("short line", 80) // OK
lint_has_trailing_ws("hello ") // returns 1
lint_summary()
// Output: [LINT] 1 warning(s)
ret 0
}Function Reference
| Function | Signature | Description |
|---|---|---|
lint_init | () | Initialise linter state |
lint_reset | () | Reset warning count to zero |
lint_is_snake | (name: &i8) -> i64 | Check if name is snake_case |
lint_is_upper | (name: &i8) -> i64 | Check if name is UPPER_SNAKE |
lint_is_pascal | (name: &i8) -> i64 | Check if name is PascalCase |
lint_check_fn | (name: &i8) -> i64 | Validate function name (snake_case) |
lint_check_const | (name: &i8) -> i64 | Validate constant name (UPPER_SNAKE) |
lint_check_struct | (name: &i8) -> i64 | Validate struct name (PascalCase) |
lint_check_var | (name: &i8) -> i64 | Validate variable name (snake_case) |
lint_warn | (name: &i8, msg: &i8) | Print a lint warning |
lint_add_warning | (msg: &i8) | Add a custom warning |
lint_warning_count | () -> i64 | Return total warning count |
lint_check_line_len | (line: &i8, maxlen: i64) -> i64 | Check if line exceeds max length |
lint_has_trailing_ws | (line: &i8) -> i64 | Check for trailing whitespace |
lint_summary | () | Print warning summary |
Detailed API
lint_init
fn lint_init()Initialise the linter. Resets internal warning count to zero. Call once before using other lint functions.
log
Structured Logging
Constants
LOG_TRACE = 0LOG_DEBUG = 1LOG_INFO = 2LOG_WARN = 3LOG_ERROR = 4LOG_FATAL = 5Functions
| Function | Description |
|---|---|
log_set_level | Set minimum log level. |
log_write_stderr | Internal: write a string to stderr. |
log_write_int_stderr | Internal: write an integer to stderr. |
log_write_level | Internal: write level prefix. |
log_write_timestamp | Internal: write timestamp (seconds since epoch). |
log_msg | Internal: log a message at given level. |
log_msg_i | Internal: log message + integer at given level. |
log_trace | |
log_debug | |
log_info | |
log_warn | |
log_error | |
log_fatal | |
log_trace_i | |
log_debug_i | |
log_info_i | |
log_warn_i | |
log_error_i |
Details
log_set_level
fn log_set_level(level: i64)Set minimum log level.
marshal
Binary Serialization
Constants
MARSHAL_NIL = 0MARSHAL_I64 = 1MARSHAL_STR = 2MARSHAL_ARRAY = 3MARSHAL_MAP = 4Functions
| Function | Description |
|---|---|
_msh_copy | |
_msh_write32 | Internal: write 4-byte LE integer. |
_msh_read32 | Internal: read 4-byte LE integer. |
_msh_write64 | Internal: write 8-byte LE integer. |
_msh_read64 | Internal: read 8-byte LE integer. |
marshal_nil | Write nil. Returns new offset. |
marshal_i64 | Write i64 value. Returns new offset. |
marshal_str | Write string. Returns new offset. |
marshal_array_begin | Write array header (type tag + count). Returns new offset. Caller must then w… |
marshal_map_begin | Write map header (type tag + pair count). Returns new offset. Caller must the… |
unmarshal_type | Peek type tag at offset. |
unmarshal_i64 | Read i64 value (skips type tag). Returns the value. |
unmarshal_str_len | Read string length at offset. |
unmarshal_str | Read string. Copies to out. Returns new offset (past string). |
unmarshal_array_count | Get array count at offset. |
unmarshal_skip | Skip one marshaled value. Returns new offset. |
Details
_msh_copy
fn _msh_copy(dst: &i8, doff: i64, src: &i8, soff: i64, n: i64)_msh_write32
fn _msh_write32(buf: &i8, off: i64, val: i64) -> i64Internal: write 4-byte LE integer.
math
Integer math library with common functions, random number generation (xorshift64), and number theory utilities. No external dependencies.
Usage
import math
fn main() {
// Basic math
print(math_abs(-42)) // 42
print(math_min(10, 20)) // 10
print(math_max(10, 20)) // 20
print(math_clamp(150, 0, 100)) // 100
// Powers and roots
print(math_pow(2, 10)) // 1024
print(math_isqrt(144)) // 12
print(math_log2(256)) // 8
// Number theory
print(math_gcd(48, 18)) // 6
print(math_lcm(4, 6)) // 12
print(math_is_prime(17)) // 1
print(math_factorial(10)) // 3628800
print(math_fib(10)) // 55
// Random numbers
math_rand_seed(12345)
let r = math_rand_range(1, 100)
print(r) // pseudo-random value in [1, 100)
}Function Reference
| Function | Signature | Description |
|---|---|---|
math_abs | (x: i64) -> i64 | Absolute value |
math_min | (a: i64, b: i64) -> i64 | Minimum of two values |
math_max | (a: i64, b: i64) -> i64 | Maximum of two values |
math_clamp | (x: i64, lo: i64, hi: i64) -> i64 | Clamp to range [lo, hi] |
math_gcd | (a: i64, b: i64) -> i64 | Greatest common divisor |
math_lcm | (a: i64, b: i64) -> i64 | Least common multiple |
math_pow | (base: i64, exp: i64) -> i64 | Integer exponentiation |
math_isqrt | (n: i64) -> i64 | Integer square root (floor) |
math_log2 | (n: i64) -> i64 | Floor of log base 2 |
math_factorial | (n: i64) -> i64 | Factorial (iterative) |
math_fib | (n: i64) -> i64 | Fibonacci number (iterative) |
math_is_prime | (n: i64) -> i64 | Primality test |
math_next_pow2 | (n: i64) -> i64 | Smallest power of 2 >= n |
math_divmod | (a: i64, b: i64, quot_ptr: &i64, rem_ptr: &i64) -> i64 | Quotient and remainder |
math_rand_seed | (seed: i64) -> i64 | Seed the RNG |
math_rand | () -> i64 | Generate pseudo-random i64 |
math_rand_range | (lo: i64, hi: i64) -> i64 | Random in range [lo, hi) |
Detailed API
math_abs
fn math_abs(x: i64) -> i64Return the absolute value of x.
matrix
Integer Matrix Operations
Functions
| Function | Description |
|---|---|
mat_pages_for | |
mat_new | Create a rows x cols matrix initialized to 0. |
mat_rows | |
mat_cols | |
mat_get | |
mat_set | |
mat_add | |
mat_sub | |
mat_mul | |
mat_scale | |
mat_transpose | |
mat_identity | |
mat_trace | |
mat_eq | |
mat_copy | |
mat_fill |
Details
mat_pages_for
fn mat_pages_for(n: i64) -> i64mat_new
fn mat_new(rows: i64, cols: i64) -> &i64Create a rows x cols matrix initialized to 0.
mat_rows
fn mat_rows(m: &i64) -> i64mat_cols
fn mat_cols(m: &i64) -> i64mat_get
fn mat_get(m: &i64, r: i64, c: i64) -> i64mat_set
fn mat_set(m: &i64, r: i64, c: i64, val: i64)mat_add
fn mat_add(a: &i64, b: &i64) -> &i64mat_sub
fn mat_sub(a: &i64, b: &i64) -> &i64mat_mul
fn mat_mul(a: &i64, b: &i64) -> &i64mat_scale
fn mat_scale(m: &i64, s: i64) -> &i64mat_transpose
fn mat_transpose(m: &i64) -> &i64mat_identity
fn mat_identity(n: i64) -> &i64mat_trace
fn mat_trace(m: &i64) -> i64mat_eq
fn mat_eq(a: &i64, b: &i64) -> i64mat_copy
fn mat_copy(m: &i64) -> &i64mat_fill
fn mat_fill(m: &i64, val: i64)metrics
// jda::ml::metrics — Model Evaluation Metrics
Functions
Details
true_positives
fn true_positives(pred: ref []i64, true: ref []i64) -> i64true_negatives
fn true_negatives(pred: ref []i64, true: ref []i64) -> i64false_positives
fn false_positives(pred: ref []i64, true: ref []i64) -> i64false_negatives
fn false_negatives(pred: ref []i64, true: ref []i64) -> i64accuracy
fn accuracy(pred: ref []i64, true: ref []i64) -> f64precision
fn precision(pred: ref []i64, true: ref []i64) -> f64recall
fn recall(pred: ref []i64, true: ref []i64) -> f64f1_score
fn f1_score(pred: ref []i64, true: ref []i64) -> f64f_beta
fn f_beta(pred: ref []i64, true: ref []i64, beta: f64) -> f64specificity
fn specificity(pred: ref []i64, true: ref []i64) -> f64matthews_corrcoef
fn matthews_corrcoef(pred: ref []i64, true: ref []i64) -> f64confusion_matrix
fn confusion_matrix(pred: ref []i64, true: ref []i64,cm_precision
fn cm_precision(cm: ref []i64, c: i64, n_classes: i64) -> f64cm_recall
fn cm_recall(cm: ref []i64, c: i64, n_classes: i64) -> f64f1_macro
fn f1_macro(pred: ref []i64, true: ref []i64, n_classes: i64) -> f64f1_weighted
fn f1_weighted(pred: ref []i64, true: ref []i64, n_classes: i64) -> f64f1_micro
fn f1_micro(pred: ref []i64, true: ref []i64, n_classes: i64) -> f64roc_auc
fn roc_auc(scores: ref []f32, true: ref []i64) -> f64average_precision
fn average_precision(scores: ref []f32, true: ref []i64) -> f64mae
fn mae(pred: ref []f32, true: ref []f32) -> f64mse
fn mse(pred: ref []f32, true: ref []f32) -> f64rmse
fn rmse(pred: ref []f32, true: ref []f32) -> f64r_squared
fn r_squared(pred: ref []f32, true: ref []f32) -> f64mape
fn mape(pred: ref []f32, true: ref []f32) -> f64huber_loss
fn huber_loss(pred: ref []f32, true: ref []f32, delta: f32) -> f64median_absolute_error
fn median_absolute_error(pred: ref []f32, true: ref []f32) -> f64hamming_loss
fn hamming_loss(pred: ref [][]i64, true: ref [][]i64) -> f64subset_accuracy
fn subset_accuracy(pred: ref [][]i64, true: ref [][]i64) -> f64print_classification_report
fn print_classification_report(pred: ref []i64, true: ref []i64,print_confusion_matrix
fn print_confusion_matrix(cm: ref []i64, n_classes: i64,mimetypes
File Extension to MIME Type Mapping
Functions
| Function | Description |
|---|---|
_mime_byte_at | Internal byte reader. |
_mime_copy | Internal: copy literal to output. |
_mime_eq | Internal: compare strings. |
mime_type | Get MIME type for file extension (without dot). Returns length, -1 if unknown. |
mime_guess | Guess MIME type from filename/path. Extracts extension after last dot. |
mime_is_text | Check if extension maps to a text/* type. |
Details
_mime_byte_at
fn _mime_byte_at(buf: &i8, idx: i64) -> i64Internal byte reader.
_mime_copy
fn _mime_copy(dst: &i8, src: &i8, len: i64) -> i64Internal: copy literal to output.
mmap
Memory-Mapped Region Utilities
Functions
| Function | Description |
|---|---|
_mmap_byte_at | Internal byte reader. |
mmap_region_new | Create a new memory region of at least size bytes. |
mmap_read_byte | Read a byte at the given offset. |
mmap_write_byte | Write a byte at the given offset. |
mmap_read_i64 | Read an i64 at the given byte offset (must be 8-byte aligned). |
mmap_write_i64 | Write an i64 at the given byte offset (must be 8-byte aligned). |
mmap_fill | Fill len bytes starting at off with value val. |
mmap_region_size | Return the size of the region. |
Details
_mmap_byte_at
fn _mmap_byte_at(buf: &i8, idx: i64) -> i64Internal byte reader.
mutex
Mutex and Condition Variable
Constants
FUTEX_WAIT = 0FUTEX_WAKE = 1Functions
| Function | Description |
|---|---|
_mtx_futex_wait | Internal: futex syscall wrapper. |
_mtx_futex_wake | |
mutex_new | Create new mutex (unlocked). |
mutex_lock | Lock mutex. Blocks if already locked. |
mutex_unlock | Unlock mutex. |
mutex_trylock | Non-blocking try-lock. Returns 1 if acquired, 0 if not. |
condvar_new | Create condition variable. |
condvar_wait | Wait on condition variable. Must hold mutex m. Releases mutex, waits, re-acqu… |
condvar_signal | Wake one waiter. |
condvar_broadcast | Wake all waiters. |
spinlock_new | Create simple spinlock. |
spinlock_lock | Spinlock: busy-wait until acquired. |
spinlock_unlock | Spinlock: release. |
Details
_mtx_futex_wait
fn _mtx_futex_wait(addr: &i64, expected: i64) -> i64Internal: futex syscall wrapper.
netrc
.netrc File Parser
Functions
| Function | Description |
|---|---|
_netrc_byte_at | Internal byte reader. |
_netrc_copy | Internal: copy bytes from src+off to dst, length len. |
_netrc_eq | Internal: compare bytes. |
_netrc_is_ws | Internal: check if ch is whitespace (space=32, tab=9, newline=10, cr=13). |
_netrc_skip_ws | Internal: skip whitespace, return new position. |
_netrc_token_end | Internal: read a token starting at pos, return end position. Token is delimit… |
_netrc_is_machine | Internal: check if token at buf[off..off+tlen] matches “machine” (7 chars). |
_netrc_is_default | Internal: check if token is “default” (7 chars). |
_netrc_is_login | Internal: check if token is “login” (5 chars). |
_netrc_is_password | Internal: check if token is “password” (8 chars). |
netrc_parse | Parse .netrc data. Returns handle. |
netrc_count | Number of entries. |
netrc_lookup | Look up entry by host. Returns index or -1. |
netrc_login | Copy login at index to out. Returns length. |
netrc_password | Copy password at index to out. Returns length. |
Details
_netrc_byte_at
fn _netrc_byte_at(buf: &i8, idx: i64) -> i64Internal byte reader.
nn
Functions
| Function | Description |
|---|---|
linear_forward | |
backward_weights | |
backward_bias | |
backward_input | |
relu_forward | |
relu_backward | |
mse_loss | |
mse_backward | |
sgd_step | |
zero_tensor |
Details
linear_forward
fn linear_forward(x: i64, w: i64, bias: i64, out: i64) -> i64backward_weights
fn backward_weights(x: i64, w: i64, grad_out: i64, grad_w: i64) -> i64backward_bias
fn backward_bias(grad_out: i64, grad_b: i64, batch: i64, out_f: i64) -> i64backward_input
fn backward_input(w: i64, grad_out: i64, grad_in: i64) -> i64relu_forward
fn relu_forward(a: i64, out: i64) -> i64relu_backward
fn relu_backward(pre_relu: i64, grad_out: i64, grad_in: i64) -> i64mse_loss
fn mse_loss(pred: i64, target: i64) -> i64mse_backward
fn mse_backward(pred: i64, target: i64, grad_out: i64) -> i64sgd_step
fn sgd_step(params: i64, grads: i64, lr: i64) -> i64zero_tensor
fn zero_tensor(t: i64) -> i64observer
Publish/Subscribe Event Pattern
Functions
| Function | Description |
|---|---|
obs_new | Create an event bus. |
obs_find_topic | Internal: find or create slot for topic. |
obs_subscribe | Subscribe a handler function pointer to a topic. Handler signature: fn(data: … |
obs_emit_i | Emit an event to all subscribers of a topic. Calls each handler with the data… |
obs_unsubscribe_all | Remove all handlers for a topic. |
obs_subscriber_count | Number of subscribers for a topic. |
Details
obs_new
fn obs_new(max_topics: i64) -> &i64Create an event bus.
open3
Capture Child Process I/O
Functions
| Function | Description |
|---|---|
_o3_pipe | |
_o3_fork | |
_o3_dup2 | |
_o3_close | |
_o3_execve | |
_o3_exit | |
_o3_read | |
_o3_write | |
_o3_wait4 | |
open3_popen | Spawn command with piped stdin/stdout/stderr. cmd = path to executable (null-… |
open3_pid | Get child PID. |
open3_write | Write data to child’s stdin. |
open3_read | Read from child’s stdout. |
open3_read_err | Read from child’s stderr. |
open3_close_stdin | Close child’s stdin (signals EOF to child). |
open3_wait | Wait for child to exit. Returns exit code (0-255) or -1 on error. |
open3_capture2 | Run command and capture stdout. Returns bytes read. |
open3_capture3 | Run command and capture stdout + stderr. Returns stdout bytes read. |
Details
_o3_pipe
fn _o3_pipe(fds: &i64) -> i64_o3_fork
fn _o3_fork() -> i64_o3_dup2
fn _o3_dup2(old: i64, new_fd: i64) -> i64_o3_close
fn _o3_close(fd: i64) -> i64_o3_execve
fn _o3_execve(path: &i8, argv: &i64, envp: &i64) -> i64_o3_exit
fn _o3_exit(code: i64)_o3_read
fn _o3_read(fd: i64, buf: &i8, max: i64) -> i64_o3_write
fn _o3_write(fd: i64, data: &i8, len: i64) -> i64_o3_wait4
fn _o3_wait4(pid: i64, status: &i64) -> i64open3_popen
fn open3_popen(cmd: &i8, argv: &i64) -> &i64Spawn command with piped stdin/stdout/stderr. cmd = path to executable (null-terminated). argv = null-terminated array of args (argv[0] = cmd name). Returns context pointer.
operator
Operators as Functions
Functions
| Function | Description |
|---|---|
op_add | Addition. |
op_sub | Subtraction. |
op_mul | Multiplication. |
op_div | Division (integer). Returns 0 if b is 0. |
op_mod | Modulo. Returns 0 if b is 0. |
op_neg | Negation. |
op_abs | Absolute value. |
op_min | Minimum. |
op_max | Maximum. |
op_eq | Equality: 1 if a == b, 0 otherwise. |
op_ne | Not equal: 1 if a != b, 0 otherwise. |
op_lt | Less than: 1 if a < b. |
op_le | Less than or equal: 1 if a <= b. |
op_gt | Greater than: 1 if a > b. |
op_ge | Greater than or equal: 1 if a >= b. |
op_and | Bitwise AND. |
op_or | Bitwise OR. |
op_xor | Bitwise XOR. |
op_not | Bitwise NOT. |
op_shl | Left shift. |
op_shr | Right shift. |
op_clamp | Clamp value to range [lo, hi]. |
op_sign | Sign: -1, 0, or 1. |
Details
op_add
fn op_add(a: i64, b: i64) -> i64Addition.
optparse
Rich CLI Option Parser
Functions
| Function | Description |
|---|---|
_opt_copy | |
_opt_streq | |
_opt_strlen | |
opt_new | Create new option parser with max options. |
opt_add | Add an option. short=0 for no short flag. has_val=1 if takes value. |
_opt_find_long | Internal: find option by long name. Returns index or -1. |
_opt_find_short | Internal: find option by short flag. Returns index or -1. |
opt_parse | Parse command-line arguments. argc/argv from os_argv(). Returns 0 on success,… |
opt_get | Get option value. Copies value to out, returns length. 0 if not found. |
opt_has | Check if option was provided. Returns 1 or 0. |
opt_positional | Get positional argument at index. Copies to out, returns length. |
opt_npos | Number of positional arguments found. |
opt_help | Print help message to stdout. |
Details
_opt_copy
fn _opt_copy(dst: &i8, doff: i64, src: &i8, soff: i64, n: i64)_opt_streq
fn _opt_streq(a: &i8, aoff: i64, alen: i64, b: &i8, boff: i64, blen: i64) -> i64_opt_strlen
fn _opt_strlen(s: &i8) -> i64opt_new
fn opt_new(max: i64) -> &i64Create new option parser with max options.
os
Operating System Interface
Functions
| Function | Description |
|---|---|
os_getenv | Get environment variable value. Scans /proc/self/environ for name=value pairs. |
os_getcwd | Get current working directory. |
os_chdir | Change current directory. |
os_getpid | Get current process ID. |
os_getppid | Get parent process ID. |
os_getuid | Get user ID. |
os_exit | Exit the process. |
os_fork | Fork the current process. |
os_exec | Execute a program (replaces current process image). |
os_wait | Wait for child process. |
os_kill | Send signal to process. |
os_sleep_ms | Sleep for given milliseconds. |
os_hostname | Get hostname. |
os_uname | Get system info (uname). |
Details
os_getenv
fn os_getenv(name: &i8, name_len: i64, buf: &i8, max: i64) -> i64Get environment variable value. Scans /proc/self/environ for name=value pairs.
pack
Binary Pack/Unpack
Functions
| Function | Description |
|---|---|
pack_i8 | Write 1 byte. Returns off+1. |
pack_i16_le | Write 2 bytes little-endian. Returns off+2. |
pack_i16_be | Write 2 bytes big-endian. Returns off+2. |
pack_i32_le | Write 4 bytes little-endian. Returns off+4. |
pack_i32_be | Write 4 bytes big-endian. Returns off+4. |
pack_i64_le | Write 8 bytes little-endian. Returns off+8. |
pack_i64_be | Write 8 bytes big-endian. Returns off+8. |
pack_str | Write length-prefixed string (4-byte LE length + raw bytes). Returns new offset. |
pack_raw | Write raw bytes (no length prefix). Returns new offset. |
unpack_i8 | Read 1 unsigned byte. |
unpack_i16_le | Read 2 bytes little-endian. |
unpack_i16_be | Read 2 bytes big-endian. |
unpack_i32_le | Read 4 bytes little-endian. |
unpack_i32_be | Read 4 bytes big-endian. |
unpack_i64_le | Read 8 bytes little-endian. |
unpack_i64_be | Read 8 bytes big-endian. |
unpack_str | Read length-prefixed string. Reads 4-byte LE length, then copies bytes to out… |
unpack_str_len | Get string length from length-prefixed string at offset. |
Details
pack_i8
fn pack_i8(buf: &i8, off: i64, val: i64) -> i64Write 1 byte. Returns off+1.
pathname
Path Manipulation Utilities
Functions
| Function | Description |
|---|---|
pn_copy | Internal: copy bytes from src to dst. |
pn_dirname | Get directory portion of path. Returns length written to out. “/usr/bin/gcc” … |
pn_extname | Get file extension including dot. Returns length written to out. “foo.tar.gz”… |
pn_is_absolute | Check if path is absolute (starts with /). |
pn_normalize | Normalize path: resolve . and .. components, collapse multiple slashes. Retur… |
pn_split_ext | Split path into stem and extension. Returns stem length. “archive.tar.gz” -> … |
pn_join3 | Join 3 path segments: a/b/c. Returns length written to out. |
pn_has_ext | Check if path has given extension. Case-sensitive. |
Details
pn_copy
fn pn_copy(dst: &i8, doff: i64, src: &i8, soff: i64, n: i64)Internal: copy bytes from src to dst.
platform
Platform Detection and System Information
Functions
| Function | Description |
|---|---|
_platform_uname | Internal: uname syscall wrapper (syscall 63). struct utsname: 5 fields of 65 … |
_plat_byte_at | Internal byte reader helper. |
_plat_copy_field | Internal: copy string from utsname field to output. |
_plat_copy_lit | Internal: copy literal bytes. |
platform_system | Get OS name. Returns length written. |
platform_release | Get kernel release string. Returns length written. |
platform_machine | Get machine architecture. Returns length written. |
platform_node | Get hostname. Returns length written. |
platform_info | Get combined platform info: “Linux x86_64 |
platform_is_x86_64 | Check if platform is x86_64. Always returns 1 (Jda only targets x86-64). |
platform_page_size | Get system page size. Always 4096 on Linux x86-64. |
Details
_platform_uname
fn _platform_uname(buf: &i8) -> i64Internal: uname syscall wrapper (syscall 63). struct utsname: 5 fields of 65 bytes each = 325 bytes total. [0..64] = sysname, [65..129] = nodename, [130..194] = release, [195..259] = version, [260..324] = machine
plot
Terminal & SVG Visualization
Functions
| Function | Description |
|---|---|
print_repeat | |
plot_bar | |
plot_bars | |
plot_line | |
hist_bin | |
plot_hist | |
scatter_points | |
scatter_print | |
plot_heatmap | |
stat_min | |
stat_max | |
stat_sum | |
stat_mean | |
plot_summary |
Details
print_repeat
fn print_repeat(ch: &i8, n: i64) -> i64plot_bar
fn plot_bar(val: i64, max_val: i64, width: i64) -> i64plot_bars
fn plot_bars(arr: &i64, len: i64, width: i64) -> i64plot_line
fn plot_line(arr: &i64, len: i64, height: i64) -> i64hist_bin
fn hist_bin(arr: &i64, len: i64, nbins: i64, lo: i64, hi: i64, bins: &i64) -> i64plot_hist
fn plot_hist(arr: &i64, len: i64, nbins: i64, lo: i64, hi: i64, width: i64, bins: &i64) -> i64scatter_points
fn scatter_points(xs: &i64, ys: &i64, len: i64, grid: &i64, dim: i64) -> i64scatter_print
fn scatter_print(grid: &i64, width: i64, height: i64) -> i64plot_heatmap
fn plot_heatmap(data: &i64, rows: i64, cols: i64) -> i64stat_min
fn stat_min(arr: &i64, len: i64) -> i64stat_max
fn stat_max(arr: &i64, len: i64) -> i64stat_sum
fn stat_sum(arr: &i64, len: i64) -> i64stat_mean
fn stat_mean(arr: &i64, len: i64) -> i64plot_summary
fn plot_summary(arr: &i64, len: i64) -> i64pp
Pretty Printer
Functions
| Function | Description |
|---|---|
pp_nl | Print newline. |
pp_sep | Print separator. |
pp_indent | Print indentation (2 spaces per level). |
pp_print_int | Internal: print integer to stdout using write buf. |
pp_int | Print an integer. |
pp_str | Print a string with double quotes. |
pp_hex | Print integer as hex. |
pp_bin | Print integer as binary. |
pp_vec | Pretty-print a vec: [1, 2, 3] |
pp_vec_named | Pretty-print a named vec: name = [1, 2, 3] |
pp_mat | Pretty-print a matrix with alignment. |
pp_bytes | Hex dump of raw bytes (16 per line). |
pp_label | Print a label: “name: " |
pp_kv_int | Print “key = value\n” |
pp_kv_hex | Print “key = 0xvalue\n” |
Details
pp_nl
fn pp_nl()Print newline.
prelude
Standard Library Prelude
Structs
Timespec
struct Timespec {
tv_sec: i64
tv_nsec: i64
}Functions
Details
set_byte
fn set_byte(buf: &i8, off: i64, val: i64)get_byte
fn get_byte(buf: &i8, off: i64) -> i64fmt_i64
fn fmt_i64(buf: &i8, val: i64) -> i64fmt_hex
fn fmt_hex(buf: &i8, val: i64) -> i64str_len
fn str_len(s: &i8) -> i64str_eq
fn str_eq(a: &i8, b: &i8) -> i64str_copy
fn str_copy(dst: &i8, src: &i8, len: i64) -> i64mem_set
fn mem_set(dst: &i8, val: i64, len: i64)eprint_str
fn eprint_str(s: &i8, len: i64)print_str
fn print_str(s: &i8, len: i64)print_int
fn print_int(val: i64)fs_read_file
fn fs_read_file(path: &i8, buf: &i8, max_bytes: i64) -> i64fs_write_file
fn fs_write_file(path: &i8, data: &i8, len: i64) -> i64fs_append_file
fn fs_append_file(path: &i8, data: &i8, len: i64) -> i64fs_exists
fn fs_exists(path: &i8) -> i64fs_unlink
fn fs_unlink(path: &i8) -> i64fs_mkdir
fn fs_mkdir(path: &i8) -> i64fs_file_size
fn fs_file_size(path: &i8) -> i64time_now_ns
fn time_now_ns() -> i64time_now_us
fn time_now_us() -> i64time_now_ms
fn time_now_ms() -> i64time_sleep_ns
fn time_sleep_ns(ns: i64)time_sleep_ms
fn time_sleep_ms(ms: i64)time_elapsed_ns
fn time_elapsed_ns(start_ns: i64) -> i64time_unix_secs
fn time_unix_secs() -> i64process
// jda::process — Process management
Constants
SYS_READ = 0SYS_WRITE = 1SYS_OPEN = 2SYS_CLOSE = 3SYS_STAT = 4SYS_MMAP = 9SYS_RT_SIGACTION = 13SYS_RT_SIGPROCMASK = 14SYS_RT_SIGRETURN = 15SYS_IOCTL = 16SYS_PIPE = 22SYS_DUP = 32SYS_DUP2 = 33SYS_GETPID = 39SYS_CLONE = 56SYS_FORK = 57SYS_VFORK = 58SYS_EXECVE = 59SYS_EXIT = 60SYS_WAIT4 = 61SYS_KILL = 62SYS_GETPPID = 110SYS_GETUID = 102SYS_GETGID = 104SYS_GETEUID = 107SYS_GETEGID = 108SYS_SIGALTSTACK= 131SYS_PRCTL = 157SYS_SETPGID = 109SYS_GETPGID = 121SYS_SETSID = 112SYS_ENVIRON = -1 // accessed via auxv, not a syscallSIGHUP = 1 // hangupSIGINT = 2 // interrupt (Ctrl-C)SIGQUIT = 3 // quitSIGILL = 4 // illegal instructionSIGTRAP = 5 // trace / breakpointSIGABRT = 6 // abortSIGBUS = 7 // bus errorSIGFPE = 8 // floating-point exceptionSIGKILL = 9 // kill (cannot be caught)SIGUSR1 = 10 // user-defined 1SIGSEGV = 11 // segfaultSIGUSR2 = 12 // user-defined 2SIGPIPE = 13 // broken pipeSIGALRM = 14 // alarm clockSIGTERM = 15 // terminationSIGCHLD = 17 // child stopped or exitedSIGCONT = 18 // continueSIGSTOP = 19 // stop (cannot be caught)SIGTSTP = 20 // terminal stop (Ctrl-Z)SIGTTIN = 21 // background read from ttySIGTTOU = 22 // background write to ttySIGURG = 23 // urgent data on socketSIGWINCH = 28 // terminal resizeSIG_DFL = 0 // default actionSIG_IGN = 1 // ignore signalWNOHANG = 1 // non-blocking waitpidPR_SET_NAME = 15PR_GET_NAME = 16PR_SET_DUMPABLE = 4PR_GET_DUMPABLE = 3PR_SET_PDEATHSIG = 1 // signal sent to child when parent diesStructs
SigAction
struct SigAction {
handler: i64 // fn pointer or SIG_DFL / SIG_IGN
flags: i64 // SA_* flags
restorer: i64 // signal trampoline (kernel sets this)
mask: u64[2] // signal mask (128 bits)
}ProcInfo
struct ProcInfo {
pid: i32
ppid: i32
uid: i32
gid: i32
euid: i32
egid: i32
pgid: i32
sid: i32
}SpawnOpts
struct SpawnOpts {
stdin_fd: i32 // -1 = inherit
stdout_fd: i32 // -1 = inherit
stderr_fd: i32 // -1 = inherit
cwd: &i8 // null = inherit
env: &&i8 // null = inherit current environ
detach: i32 // 1 = new session (setsid)
}ChildProc
struct ChildProc {
pid: i32
stdin: i32 // write end of stdin pipe (-1 if not piped)
stdout: i32 // read end of stdout pipe (-1 if not piped)
stderr: i32 // read end of stderr pipe (-1 if not piped)
}WaitResult
struct WaitResult {
pid: i32
status: i32
exited: i32
code: i32 // exit code if exited
signal: i32 // signal if killed by signal
}Pipe
struct Pipe {
read_fd: i32
write_fd: i32
}Functions
Details
wifexited
fn wifexited(status: i32) -> i32 wexitstatus
fn wexitstatus(status: i32) -> i32wifsignaled
fn wifsignaled(status: i32) -> i32wtermsig
fn wtermsig(status: i32) -> i32 wifstopped
fn wifstopped(status: i32) -> i32 wstopsig
fn wstopsig(status: i32) -> i32 getpid
fn getpid() -> i32getppid
fn getppid() -> i32getuid
fn getuid() -> i32getgid
fn getgid() -> i32exit
fn exit(code: i32)abort
fn abort()fork
fn fork() -> i32execve
fn execve(path: &i8, argv: &&i8, envp: &&i8) -> i32exec_argv
fn exec_argv(path: &i8, argv: &&i8) -> i32waitpid
fn waitpid(pid: i32, status: &i32, options: i32) -> i32wait_any
fn wait_any(opts: i32) -> WaitResultrun
fn run(path: &i8, argv: &&i8) -> i32pipe2
fn pipe2(fds: &i32) -> i32dup2
fn dup2(old_fd: i32, new_fd: i32) -> i32close_fd
fn close_fd(fd: i32)spawn
fn spawn(path: &i8, argv: &&i8, opts: &SpawnOpts) -> ChildProcspawn_output
fn spawn_output(path: &i8, argv: &&i8, out: &i8, cap: i64) -> i64kill
fn kill(pid: i32, sig: i32) -> i32killpg
fn killpg(pgid: i32, sig: i32) -> i32raise_sig
fn raise_sig(sig: i32)signal
fn signal(sig: i32, handler: i64) -> i32signal_ignore
fn signal_ignore(sig: i32)signal_default
fn signal_default(sig: i32)signal_block
fn signal_block(sig: i32)signal_unblock
fn signal_unblock(sig: i32)environ
fn environ() -> &&i8process_init
fn process_init(argc: i64, argv: &&i8)getenv
fn getenv(name: &i8) -> &i8setenv
fn setenv(name: &i8, value: &i8, overwrite: i32) -> i32unsetenv
fn unsetenv(name: &i8) -> i32proc_info
fn proc_info() -> ProcInfopipe_open
fn pipe_open() -> Pipepipe_write
fn pipe_write(p: &Pipe, data: &i8, len: i64) -> i64pipe_read
fn pipe_read(p: &Pipe, buf: &i8, cap: i64) -> i64pipe_close_write
fn pipe_close_write(p: &Pipe)pipe_close_read
fn pipe_close_read(p: &Pipe) daemonize
fn daemonize() -> i32set_process_name
fn set_process_name(name: &i8)get_process_name
fn get_process_name(out: &i8)set_pdeathsig
fn set_pdeathsig(sig: i32)disable_coredump
fn disable_coredump()profile
A function-level profiler for Jda programs. Measures execution time and call counts using clock_gettime(CLOCK_MONOTONIC). Supports up to 64 profiling slots with enter/leave instrumentation and a flat profile report.
Usage
import profile
fn main() {
prof_init()
prof_enable()
// Profile a hot function
prof_enter(0, "sort")
sort_vec(v)
prof_leave(0)
prof_enter(1, "search")
binary_search(v, 42)
prof_leave(1)
// Print flat profile report
prof_report()
// Output:
// === Profile Report ===
// sort 1 calls 1234 us 1234 us/call
// search 1 calls 12 us 12 us/call
// === End Report ===
ret 0
}Function Reference
| Function | Signature | Description |
|---|---|---|
prof_init | () | Initialise profiler state |
prof_enable | () | Enable profiling |
prof_disable | () | Disable profiling |
prof_enabled | () -> i64 | Check if profiling is enabled |
prof_enter | (slot: i64, name: &i8) | Start timing a slot |
prof_leave | (slot: i64) | Stop timing a slot |
prof_calls | (slot: i64) -> i64 | Return call count for a slot |
prof_total_ns | (slot: i64) -> i64 | Return total nanoseconds for a slot |
prof_avg_ns | (slot: i64) -> i64 | Return average nanoseconds per call |
prof_name | (slot: i64) -> &i8 | Return name of a slot |
prof_slot_count | () -> i64 | Return number of used slots |
prof_reset | (slot: i64) | Reset a single slot |
prof_reset_all | () | Reset all slots |
prof_report | () | Print flat profile report |
Detailed API
prof_init
fn prof_init()Initialise the profiler. Resets all 64 slots and enables profiling. Call once at program start.
ptx
Functions
| Function | Description |
|---|---|
ptx_has_gpu | |
ptx_vecadd | |
ptx_matmul | |
ptx_scale | |
ptx_dot | |
ptx_relu |
Details
ptx_has_gpu
fn ptx_has_gpu() -> i64ptx_vecadd
fn ptx_vecadd(a: i64, b: i64, c: i64, len: i64) -> i64ptx_matmul
fn ptx_matmul(a: i64, b: i64, c: i64, M: i64, N: i64, K: i64) -> i64ptx_scale
fn ptx_scale(a: i64, c: i64, scalar: i64, len: i64) -> i64ptx_dot
fn ptx_dot(a: i64, b: i64, len: i64) -> i64ptx_relu
fn ptx_relu(a: i64, c: i64, len: i64) -> i64queue
Queue, Stack, and Priority Queue
Functions
Details
queue_pages_for
fn queue_pages_for(n: i64) -> i64queue_new
fn queue_new() -> &i64queue_grow
fn queue_grow(q: &i64)queue_push
fn queue_push(q: &i64, val: i64)queue_pop
fn queue_pop(q: &i64) -> i64queue_peek
fn queue_peek(q: &i64) -> i64queue_len
fn queue_len(q: &i64) -> i64queue_empty
fn queue_empty(q: &i64) -> i64stack_new
fn stack_new() -> &i64stack_push
fn stack_push(s: &i64, val: i64)stack_pop
fn stack_pop(s: &i64) -> i64stack_peek
fn stack_peek(s: &i64) -> i64stack_len
fn stack_len(s: &i64) -> i64stack_empty
fn stack_empty(s: &i64) -> i64pq_new
fn pq_new() -> &i64pq_parent
fn pq_parent(i: i64) -> i64pq_left
fn pq_left(i: i64) -> i64pq_right
fn pq_right(i: i64) -> i64pq_sift_up
fn pq_sift_up(pq: &i64, idx: i64)pq_sift_down
fn pq_sift_down(pq: &i64, idx: i64)pq_push
fn pq_push(pq: &i64, val: i64)pq_pop
fn pq_pop(pq: &i64) -> i64pq_peek
fn pq_peek(pq: &i64) -> i64pq_len
fn pq_len(pq: &i64) -> i64pq_empty
fn pq_empty(pq: &i64) -> i64range
Range Type
Functions
| Function | Description |
|---|---|
range_new | Create exclusive range [start, end). |
range_inclusive | Create inclusive range [start, end]. |
range_step | Create range with custom step. |
range_contains | Check if value is in range. |
range_size | Number of elements in range. |
range_each | Fill buffer with range values. Returns count. |
range_to_vec | Create vec from range values. Returns vec pointer (&i64). |
range_sum | Sum all elements in range. |
range_first | First element of range. |
range_last | Last element of range. |
Details
range_new
fn range_new(start: i64, end_val: i64) -> &i64Create exclusive range [start, end).
rational
Rational Number Arithmetic
Functions
| Function | Description |
|---|---|
_rat_gcd | Internal: GCD (Euclidean algorithm). |
_rat_abs | Internal: absolute value. |
rat_new | Create rational number, auto-simplified. |
rat_add | Add: a/b + c/d = (ad + bc) / bd. |
rat_sub | Subtract: a/b - c/d = (ad - bc) / bd. |
rat_mul | Multiply: (a/b) * (c/d) = ac / bd. |
rat_div | Divide: (a/b) / (c/d) = ad / bc. |
rat_cmp | Compare: returns -1, 0, or 1. |
rat_eq | Equality check. |
rat_to_i64 | Truncated integer value (num / den). |
rat_num | Numerator. |
rat_den | Denominator. |
rat_is_integer | Check if integer (den == 1). |
rat_abs | Absolute value. |
rat_negate | Negate. |
_rat_write_int | Internal: write integer to buffer. |
rat_to_str | Format as “num/den” string. Returns length. |
Details
_rat_gcd
fn _rat_gcd(a: i64, b: i64) -> i64Internal: GCD (Euclidean algorithm).
regex
Backtracking regex engine written in pure Jda. No external dependencies.
Supported Syntax
| Pattern | Description |
|---|---|
. | Any character |
* | Zero or more (greedy) |
+ | One or more (greedy) |
? | Zero or one |
[abc] | Character class |
[a-z] | Character range |
[^abc] | Negated character class |
^ | Start-of-string anchor |
$ | End-of-string anchor |
\d | Digit [0-9] |
\w | Word character [a-zA-Z0-9_] |
\s | Whitespace [ \t\n\r] |
\. | Escaped literal dot |
Usage
import regex
fn main() {
// Full match: does the entire string match?
print(regex_match("hello", 5, "hello", 5)) // 1
print(regex_match("hel+o", 5, "hello", 5)) // 1
// Search: find first match position
let pos = regex_search("\\d+", 3, "abc123def", 9)
print(pos) // 3
// Count: non-overlapping matches
let n = regex_count("[a-z]+", 6, "foo bar baz", 11)
print(n) // 3
}Function Reference
| Function | Signature | Description |
|---|---|---|
regex_match | (pat: &i8, pl: i64, text: &i8, tl: i64) -> i64 | Full match (entire text) |
regex_search | (pat: &i8, pl: i64, text: &i8, tl: i64) -> i64 | Find first match position |
regex_count | (pat: &i8, pl: i64, text: &i8, tl: i64) -> i64 | Count non-overlapping matches |
re_match_at | (pat: &i8, pl: i64, text: &i8, tp: i64, tl: i64) -> i64 | Match at specific position |
Detailed API
regex_match
fn regex_match(pat: &i8, pl: i64, text: &i8, tl: i64) -> i64Test whether the pattern matches the entire text string. The match must consume all bytes.
ring
Ring Buffer (Circular Buffer)
Functions
| Function | Description |
|---|---|
ring_pages_for | |
ring_new | Create ring buffer with given capacity. |
ring_push | Push a value. If full, overwrites oldest and returns evicted value. Returns 0… |
ring_pop | Pop oldest value. Returns 0 if empty. |
ring_peek | Peek at oldest without removing. |
ring_peek_newest | Peek at newest without removing. |
ring_len | |
ring_cap | |
ring_full | |
ring_empty | |
ring_get | Get element at logical index (0 = oldest). |
ring_clear | Clear the ring buffer. |
ring_sum | Sum of all elements. |
ring_avg | Integer average (0 if empty). |
Details
ring_pages_for
fn ring_pages_for(n: i64) -> i64ring_new
fn ring_new(cap: i64) -> &i64Create ring buffer with given capacity.
rocm
Functions
| Function | Description |
|---|---|
rocm_has_gpu | |
rocm_add | |
rocm_mm | |
rocm_scale | |
rocm_dot | |
rocm_relu |
Details
rocm_has_gpu
fn rocm_has_gpu() -> i64rocm_add
fn rocm_add(a: i64, b: i64, c: i64, len: i64) -> i64rocm_mm
fn rocm_mm(a: i64, b: i64, c: i64, M: i64, N: i64, K: i64) -> i64rocm_scale
fn rocm_scale(a: i64, c: i64, scalar: i64, len: i64) -> i64rocm_dot
fn rocm_dot(a: i64, b: i64, len: i64) -> i64rocm_relu
fn rocm_relu(a: i64, c: i64, len: i64) -> i64sched
Simple Task Scheduler (Min-Heap)
Functions
| Function | Description |
|---|---|
sched_new | Create a new scheduler. |
_sched_swap | Internal: swap two entries in the heap. |
_sched_sift_up | Internal: sift up from index i. |
_sched_sift_down | Internal: sift down from index i, with count elements. |
sched_enter | Add a task to the scheduler. |
sched_cancel | Cancel a task by id. Returns 1 if found and removed. |
sched_next | Return id of the next (earliest) task, or -1 if empty. |
sched_next_time | Return time of the next (earliest) task. |
_sched_pop | Internal: remove the root element from the heap. |
sched_run | Run the next task if its time <= now. Returns task id or -1. |
sched_empty | Return 1 if the scheduler has no tasks. |
sched_count | Return the number of tasks. |
Details
sched_new
fn sched_new() -> &i64Create a new scheduler.
securerandom
Cryptographic Random Number Generation
Functions
| Function | Description |
|---|---|
_srand_getrandom | Internal: getrandom syscall (318 on x86-64). |
srand_bytes | Fill buffer with n random bytes. Returns n on success, -1 on error. |
_srand_hex_digit | Internal: hex digit. |
srand_hex | Generate hex-encoded random bytes. Writes 2*nbytes chars to out. Returns numb… |
srand_base64 | Base64 encode random bytes. Returns chars written. |
srand_uuid4 | Generate UUID v4 string (36 chars: xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx). |
srand_range | Random integer in range [lo, hi). Uses getrandom for uniform distribution. |
Details
_srand_getrandom
fn _srand_getrandom(buf: &i8, n: i64) -> i64Internal: getrandom syscall (318 on x86-64).
select
Functions
| Function | Description |
|---|---|
chan_ready | |
chan_select | |
chan_select_val | |
chan_select_idx |
Details
chan_ready
fn chan_ready(ch: &i64) -> i64chan_select
fn chan_select(chs: &i64, n: i64) -> i64chan_select_val
fn chan_select_val() -> i64chan_select_idx
fn chan_select_idx() -> i64set
Hash Set (Set
Functions
| Function | Description |
|---|---|
set_pages_for | |
set_new | Create a new set with given capacity (rounded up to power of 2, min 16). |
set_hash | Internal: hash function for i64. |
set_rehash | Internal: rehash when load factor > 0.7. |
set_add | Insert a value into the set. |
set_has | Check if value is in the set. |
set_del | Remove a value from the set. Returns 1 if found, 0 otherwise. |
set_len | Number of elements. |
set_clear | Remove all elements. |
set_union | Union: returns new set containing all elements from a and b. |
set_intersect | Intersection: returns new set of elements in both a and b. |
set_diff | Difference: returns new set of elements in a but not in b. |
set_subset | Subset: returns 1 if all elements of a are in b. |
set_eq | Equality: same elements in both sets. |
set_to_vec | Convert set to vec (unordered). |
Details
set_pages_for
fn set_pages_for(n: i64) -> i64set_new
fn set_new(cap: i64) -> &i64Create a new set with given capacity (rounded up to power of 2, min 16).
shell
Shell Word Splitting and Escaping
Functions
| Function | Description |
|---|---|
shell_needs_escape | Internal: does this byte need escaping in a shell context? |
shell_escape | Escape a string for safe shell use with backslashes. Returns output length. |
shell_quote | Single-quote a string (strongest quoting). Handles embedded single quotes wit… |
shell_join | Join multiple words into a single shell-safe string with spaces. words: array… |
shell_split | Split a shell string into words respecting quotes. Stores offsets and lengths… |
Details
shell_needs_escape
fn shell_needs_escape(ch: i64) -> i64Internal: does this byte need escaping in a shell context?
signal
Signal Handling
Constants
SIG_HUP = 1SIG_INT = 2SIG_QUIT = 3SIG_ILL = 4SIG_TRAP = 5SIG_ABRT = 6SIG_BUS = 7SIG_FPE = 8SIG_KILL = 9SIG_USR1 = 10SIG_SEGV = 11SIG_USR2 = 12SIG_PIPE = 13SIG_ALRM = 14SIG_TERM = 15SIG_CHLD = 17SIG_CONT = 18SIG_STOP = 19SIG_TSTP = 20SIG_WINCH = 28SIG_DFL_VAL = 0SIG_IGN_VAL = 1SA_RESTORER = 67108864Functions
| Function | Description |
|---|---|
_sig_rt_sigaction | |
_sig_getpid | |
_sig_kill_raw | |
_sig_rt_sigprocmask | |
_sig_rt_sigpending | |
sig_action | Set signal handler. handler = function pointer. Returns 0 on success, -1 on e… |
sig_ignore | Ignore a signal. |
sig_default | Restore default signal handler. |
sig_raise | Send signal to self. |
sig_kill | Send signal to another process. |
sig_block | Block a signal. how=0 (SIG_BLOCK). |
sig_unblock | Unblock a signal. how=1 (SIG_UNBLOCK). |
sig_pending | Check if any signals are pending. Returns bitmask. |
Details
_sig_rt_sigaction
fn _sig_rt_sigaction(sig: i64, act: &i64, old: &i64) -> i64_sig_getpid
fn _sig_getpid() -> i64_sig_kill_raw
fn _sig_kill_raw(pid: i64, sig: i64) -> i64_sig_rt_sigprocmask
fn _sig_rt_sigprocmask(how: i64, set: &i64, old: &i64) -> i64_sig_rt_sigpending
fn _sig_rt_sigpending(set: &i64) -> i64sig_action
fn sig_action(signum: i64, handler: i64) -> i64Set signal handler. handler = function pointer. Returns 0 on success, -1 on error.
smtp
SMTP Protocol Helpers
Functions
| Function | Description |
|---|---|
_smtp_byte_at | Internal byte reader. |
_smtp_copy | Internal: copy bytes from src to dst+doff. |
_smtp_crlf | Internal: write CRLF at position. |
smtp_format_ehlo | Format EHLO command: “EHLO domain\r\n” |
smtp_format_mail_from | Format MAIL FROM command: “MAIL FROM: |
smtp_format_rcpt_to | Format RCPT TO command: “RCPT TO: |
smtp_format_data | Format DATA command: “DATA\r\n” |
smtp_parse_reply | Parse SMTP reply code from buffer. Returns integer code (e.g. 250). Expects f… |
smtp_reply_is_ok | Check if reply code is success (2xx). |
Details
_smtp_byte_at
fn _smtp_byte_at(buf: &i8, idx: i64) -> i64Internal byte reader.
socketserver
TCP/UDP Server Primitives
Functions
| Function | Description |
|---|---|
_srv_byte_at | Internal byte reader. |
_srv_copy | Internal: copy bytes. |
_srv_parse_int | Internal: parse integer from bytes at offset, returns value. |
srv_tcp_new | Create a TCP server handle. |
srv_tcp_start | Start listening (stub — returns -1, would use socket/bind/listen syscalls). |
srv_tcp_accept | Accept a connection (stub — returns -1). |
srv_parse_addr | Parse “host:port” string into a server handle. |
srv_addr_port | Get the port from a server handle. |
srv_addr_host_len | Get the host length from a server handle. |
srv_addr_host | Copy host string to output buffer. Returns length. |
Details
_srv_byte_at
fn _srv_byte_at(buf: &i8, idx: i64) -> i64Internal byte reader.
sort
In-place sorting of Vec<i64> (from the vec package). Uses introsort (quicksort with insertion sort for small partitions). Pure integer comparisons. Depends on vec.jda.
Usage
import vec
import sort
fn main() {
let v = vec_new(16)
vec_push(v, 50)
vec_push(v, 10)
vec_push(v, 40)
vec_push(v, 20)
vec_push(v, 30)
sort_vec(v)
// v is now [10, 20, 30, 40, 50]
print(sort_binary_search(v, 30)) // 2
print(sort_min(v)) // 10
print(sort_max(v)) // 50
}Function Reference
| Function | Signature | Description |
|---|---|---|
sort_vec | (v: &i64) | Sort ascending in-place |
sort_vec_desc | (v: &i64) | Sort descending in-place |
sort_is_sorted | (v: &i64) -> i64 | Check if sorted ascending |
sort_reverse | (v: &i64) | Reverse in-place |
sort_min | (v: &i64) -> i64 | Minimum element |
sort_max | (v: &i64) -> i64 | Maximum element |
sort_binary_search | (v: &i64, val: i64) -> i64 | Binary search (vec must be sorted) |
sort_unique | (v: &i64) -> &i64 | Remove duplicates from sorted vec |
sort_merge | (a: &i64, b: &i64) -> &i64 | Merge two sorted vecs |
Detailed API
sort_vec
fn sort_vec(v: &i64)Sort a vec in ascending order, in-place. Uses quicksort with a Lomuto partition scheme, falling back to insertion sort for partitions of 16 elements or fewer.
statistics
Statistical Functions (Integer-Scaled)
Functions
| Function | Description |
|---|---|
stat_sum | Sum of all values. |
stat_mean_x10k | Mean * 10000. |
_stat_sort | Internal: simple insertion sort for small arrays. |
stat_median | Median (middle value of sorted data). |
stat_mode | Mode (most frequent value). Uses O(n^2) counting to avoid alloc_pages overlap. |
stat_min | Minimum value. |
stat_max | Maximum value. |
stat_range | Range (max - min). |
stat_variance_x10k | Variance * 10000. Uses sum of squared deviations. |
_stat_isqrt | Integer square root (helper for stdev). |
stat_stdev_x10k | Standard deviation * 10000. |
stat_percentile | Percentile (0-100). Returns value at that percentile. |
Details
stat_sum
fn stat_sum(data: &i64, n: i64) -> i64Sum of all values.
string
Length-prefixed strings built on &i8 byte buffers. All operations return new strings (immutable-style API) – the original string is never modified.
Memory Layout
Each string is a pointer to a 3-word header (&i64):
| Offset | Field | Description |
|---|---|---|
[0] | length | Byte count of the string content |
[1] | capacity | Allocated bytes in the data buffer |
[2] | data_ptr | &i8 pointer to the raw byte buffer |
Usage
import string
fn main() {
// Create a string from a literal
let greeting = str_from("hello", 5)
let world = str_from(" world", 6)
// Concatenate
let msg = str_concat(greeting, world)
str_print(msg) // prints: hello world
// Search
let pos = str_index_of(msg, str_from("world", 5))
print(pos) // prints: 6
// Transform
let upper = str_to_upper(msg)
str_print(upper) // prints: HELLO WORLD
}Function Reference
| Function | Signature | Description |
|---|---|---|
str_new | () -> &i64 | Create an empty string |
str_from | (src: &i8, len: i64) -> &i64 | Create a string from a byte literal |
str_clone | (s: &i64) -> &i64 | Deep copy a string |
str_len | (s: &i64) -> i64 | Get byte length |
str_byte | (s: &i64, idx: i64) -> i64 | Get byte at index |
str_eq | (a: &i64, b: &i64) -> i64 | Content equality (returns 1 or 0) |
str_concat | (a: &i64, b: &i64) -> &i64 | Concatenate two strings |
str_append | (s: &i64, src: &i8, len: i64) -> &i64 | Append literal bytes |
str_slice | (s: &i64, start: i64, end: i64) -> &i64 | Substring [start, end) |
str_index_of | (s: &i64, sub: &i64) -> i64 | Find first occurrence (or -1) |
str_contains | (s: &i64, sub: &i64) -> i64 | Check if string contains substring |
str_starts_with | (s: &i64, pfx: &i64) -> i64 | Check prefix match |
str_ends_with | (s: &i64, sfx: &i64) -> i64 | Check suffix match |
str_count | (s: &i64, sub: &i64) -> i64 | Count non-overlapping occurrences |
str_to_upper | (s: &i64) -> &i64 | ASCII uppercase copy |
str_to_lower | (s: &i64) -> &i64 | ASCII lowercase copy |
str_print | (s: &i64) | Write string to stdout |
Detailed API
str_new
fn str_new() -> &i64Create an empty string with a default capacity of 16 bytes.
stringio
In-Memory String I/O
Functions
| Function | Description |
|---|---|
_sio_byte_at | |
_sio_copy | |
sio_new | Create empty StringIO with given capacity. |
sio_from | Create StringIO from existing string. |
sio_write | Write data at current position. Returns bytes written. |
sio_read | Read n bytes from current position. Returns bytes read. |
sio_getline | Read until newline or max bytes. Returns bytes read (including newline). |
sio_seek | Set read/write position. |
sio_rewind | Reset position to beginning. |
sio_eof | 1 if at end of data. |
sio_len | Current data length. |
sio_pos | Current read/write position. |
sio_string | Copy all contents to out buffer. Returns length. |
sio_putc | Write a single byte at current position. |
sio_getc | Read a single byte at current position. Returns -1 at EOF. |
Details
_sio_byte_at
fn _sio_byte_at(buf: &i8, idx: i64) -> i64_sio_copy
fn _sio_copy(dst: &i8, doff: i64, src: &i8, soff: i64, n: i64)sio_new
fn sio_new(cap: i64) -> &i64Create empty StringIO with given capacity.
stringscanner
Stateful String Scanner
Functions
| Function | Description |
|---|---|
_ss_byte_at | |
_ss_copy | |
ss_new | Create new scanner over source string. |
ss_scan | Try to match pattern at current position. If found, advance and return 1. |
ss_check | Check if pattern matches at current position without advancing. |
ss_skip | Advance position by n bytes. |
ss_skip_until | Skip forward until pattern is found. Returns distance skipped, -1 if not found. |
ss_rest | Copy remaining unscanned portion to out. Returns length. |
ss_rest_len | Length of remaining unscanned portion. |
ss_eos | 1 if at end of string. |
ss_pos | Current scan position. |
ss_reset | Reset scanner to beginning. |
ss_matched | Copy last matched string to out. Returns length. |
ss_peek | Peek at next n bytes without advancing. Returns bytes copied. |
ss_scan_byte | Read one byte and advance. Returns byte value or -1 at end. |
Details
_ss_byte_at
fn _ss_byte_at(buf: &i8, idx: i64) -> i64_ss_copy
fn _ss_copy(dst: &i8, doff: i64, src: &i8, soff: i64, n: i64)ss_new
fn ss_new(src: &i8, len: i64) -> &i64Create new scanner over source string.
tarfile
POSIX ustar Tar Archive Format
Functions
| Function | Description |
|---|---|
_tar_byte_at | Internal byte reader. |
_tar_write_octal | Internal: write octal string (zero-padded, len chars) at position. Writes rig… |
_tar_read_octal | Internal: read octal number from buffer. |
_tar_checksum | Internal: compute header checksum. |
_tar_zero_block | Internal: zero-fill a 512-byte block. |
tar_create | Create a write handle. out is the output buffer. |
tar_add_file | Add a file entry to the tar archive. |
tar_finish | Write two zero blocks to finish the archive. Returns total length. |
tar_open | Open a tar archive for reading. |
tar_next | Advance to next entry. Returns 1 if entry found, 0 if end of archive. |
tar_entry_name | Copy current entry name to out. Returns length. |
tar_entry_size | Get size of current entry data. |
tar_entry_data | Copy current entry data to out. Returns length. |
Details
_tar_byte_at
fn _tar_byte_at(buf: &i8, idx: i64) -> i64Internal byte reader.
tcp
TCP socket API built on direct Linux syscalls. Provides structs for socket addresses, TCP streams, and TCP listeners, along with byte-order conversion utilities.
Types
SockAddrIn
IPv4 socket address, matching the Linux sockaddr_in layout:
struct SockAddrIn {
sin_family: u16 // AF_INET = 2
sin_port: u16 // port in network byte order (big-endian)
sin_addr: u32 // IPv4 address in network byte order
sin_zero: [8]u8 // padding
}TcpStream
A connected TCP socket:
struct TcpStream {
fd: i32 // socket file descriptor
peer_addr: u32 // peer IPv4 address
peer_port: u16 // peer port number
}TcpListener
A listening TCP socket:
tempfile
Temporary Files and Directories
Functions
| Function | Description |
|---|---|
tmp_rand_suffix | Internal: generate random suffix (6 alphanumeric chars). |
tmp_write_prefix | Internal: write “/tmp/” prefix. |
tmp_name | Generate a unique temp path name. Returns length. |
tmp_make_handle | Handle layout: [0]=fd, [1]=path_ptr, [2]=path_len, [3]=is_dir |
tmp_file | Create a temporary file. Returns handle. |
tmp_dir | Create a temporary directory. Returns handle. |
tmp_path | Copy path to dst buffer. Returns length. |
tmp_fd | Get file descriptor. |
tmp_write | Write bytes to temp file. |
tmp_read | Read bytes from temp file (seeks to start first). |
tmp_close | Close the file descriptor. |
tmp_remove | Delete the temp file or directory. |
Details
tmp_rand_suffix
fn tmp_rand_suffix(dst: &i8, off: i64) -> i64Internal: generate random suffix (6 alphanumeric chars).
tensor_ops
Functions
| Function | Description |
|---|---|
tensor_add | |
tensor_sub | |
tensor_mul_elem | |
tensor_scale | |
tensor_sum | |
tensor_mean | |
tensor_max | |
tensor_relu | |
tensor_sigmoid | |
tensor_tanh_t | |
tensor_softmax | |
tensor_transpose | |
matmul |
Details
tensor_add
fn tensor_add(a: i64, b: i64, out: i64)tensor_sub
fn tensor_sub(a: i64, b: i64, out: i64)tensor_mul_elem
fn tensor_mul_elem(a: i64, b: i64, out: i64)tensor_scale
fn tensor_scale(a: i64, s: i64, out: i64)tensor_sum
fn tensor_sum(a: i64) -> i64tensor_mean
fn tensor_mean(a: i64) -> i64tensor_max
fn tensor_max(a: i64) -> i64tensor_relu
fn tensor_relu(a: i64, out: i64)tensor_sigmoid
fn tensor_sigmoid(a: i64, out: i64)tensor_tanh_t
fn tensor_tanh_t(a: i64, out: i64)tensor_softmax
fn tensor_softmax(a: i64, out: i64)tensor_transpose
fn tensor_transpose(a: i64, out: i64)matmul
fn matmul(a: i64, b: i64, out: i64)tensor_slice
Functions
Details
tensor_reshape_1d
fn tensor_reshape_1d(t: i64, d0: i64) -> i64tensor_reshape_2d
fn tensor_reshape_2d(t: i64, d0: i64, d1: i64) -> i64tensor_slice1d
fn tensor_slice1d(t: i64, start: i64, stop: i64, step: i64) -> i64tensor_slice2d
fn tensor_slice2d(t: i64, row_start: i64, row_stop: i64, col_start: i64, col_stop: i64) -> i64tensor_row
fn tensor_row(t: i64, row: i64) -> i64tensor_col
fn tensor_col(t: i64, col: i64) -> i64broadcast_add_1d
fn broadcast_add_1d(a: i64, b: i64, out: i64)broadcast_add_2d1d
fn broadcast_add_2d1d(a: i64, b: i64, out: i64)broadcast_add_2d_col
fn broadcast_add_2d_col(a: i64, b: i64, out: i64)broadcast_mul_1d
fn broadcast_mul_1d(a: i64, b: i64, out: i64)broadcast_mul_2d1d
fn broadcast_mul_2d1d(a: i64, b: i64, out: i64)broadcast_mul_2d_col
fn broadcast_mul_2d_col(a: i64, b: i64, out: i64)broadcast_scalar_add
fn broadcast_scalar_add(t: i64, s: i64, out: i64)broadcast_scalar_mul
fn broadcast_scalar_mul(t: i64, s: i64, out: i64)broadcast_scalar_sub
fn broadcast_scalar_sub(t: i64, s: i64, out: i64)broadcast_scalar_div
fn broadcast_scalar_div(t: i64, s: i64, out: i64)tensor_sum_axis0
fn tensor_sum_axis0(t: i64, rows: i64, cols: i64) -> i64tensor_sum_axis1
fn tensor_sum_axis1(t: i64, rows: i64, cols: i64) -> i64tensor_mean_axis0
fn tensor_mean_axis0(t: i64, rows: i64, cols: i64) -> i64tensor_mean_axis1
fn tensor_mean_axis1(t: i64, rows: i64, cols: i64) -> i64tensor_max_axis0
fn tensor_max_axis0(t: i64, rows: i64, cols: i64) -> i64tensor_max_axis1
fn tensor_max_axis1(t: i64, rows: i64, cols: i64) -> i64tensor_concat1d
fn tensor_concat1d(a: i64, b: i64) -> i64tensor_vstack
fn tensor_vstack(a: i64, b: i64, cols: i64) -> i64tensor_hstack
fn tensor_hstack(a: i64, b: i64) -> i64tensor_where
fn tensor_where(cond: i64, a: i64, b: i64, out: i64)tensor_clamp
fn tensor_clamp(t: i64, lo: i64, hi: i64, out: i64)tensor_arange
fn tensor_arange(start: i64, stop: i64, step: i64) -> i64tensor_linspace
fn tensor_linspace(start: i64, stop: i64, n: i64) -> i64tensor_copy_1d
fn tensor_copy_1d(t: i64) -> i64tensor_copy_2d
fn tensor_copy_2d(t: i64) -> i64testing
A lightweight test framework for writing and running tests. Provides named test blocks, assertion functions for common comparisons, and a summary report with pass/fail counts. All output is written to stderr.
Usage
import testing
fn main() {
// Test basic arithmetic
test_begin("addition", 8)
assert_eq(2 + 2, 4)
assert_ne(2 + 2, 5)
test_end()
// Test comparisons
test_begin("comparisons", 11)
assert_gt(10, 5)
assert_lt(3, 7)
assert_ge(5, 5)
assert_le(4, 4)
test_end()
// Test booleans
test_begin("booleans", 8)
assert_true(1)
assert_false(0)
test_end()
// Print summary and get failure count
let failures = test_summary()
// Output:
// 3 tests, 0 failures
//
// Exit with failure count as exit code
syscall(60, failures, 0, 0)
}Function Reference
| Function | Signature | Description |
|---|---|---|
test_begin | (name: &i8, len: i64) | Begin a named test |
test_end | () | End the current test |
assert_eq | (a: i64, b: i64) | Assert a == b |
assert_ne | (a: i64, b: i64) | Assert a != b |
assert_true | (val: i64) | Assert non-zero (truthy) |
assert_false | (val: i64) | Assert zero (falsy) |
assert_gt | (a: i64, b: i64) | Assert a > b |
assert_lt | (a: i64, b: i64) | Assert a < b |
assert_ge | (a: i64, b: i64) | Assert a >= b |
assert_le | (a: i64, b: i64) | Assert a <= b |
test_summary | () -> i64 | Print summary, return failure count |
Detailed API
test_begin
fn test_begin(name: &i8, len: i64)Begin a named test. The name is printed to stderr to identify the test being run. Must be paired with test_end.
textwrap
Text Wrapping and Formatting
Functions
| Function | Description |
|---|---|
_tw_byte_at | Internal byte reader. |
_tw_copy | Internal: copy bytes. |
textwrap_fill | Wrap text at word boundaries. Inserts newlines. Returns total length. |
textwrap_wrap | Wrap text (alias for fill). |
textwrap_dedent | Remove common leading whitespace from all lines. |
textwrap_indent | Add prefix to each line. |
textwrap_shorten | Truncate text to width, adding […] if too long. |
Details
_tw_byte_at
fn _tw_byte_at(buf: &i8, idx: i64) -> i64Internal byte reader.
_tw_copy
fn _tw_copy(dst: &i8, doff: i64, src: &i8, soff: i64, n: i64)Internal: copy bytes.
time
Clocks & Sleep
Structs
Timespec
struct Timespec {
tv_sec: i64
tv_nsec: i64
}Functions
| Function | Description |
|---|---|
time_now_ns | |
time_now_us | |
time_now_ms | |
time_sleep_ns | |
time_sleep_ms | |
time_elapsed_ns | |
time_unix_secs |
Details
time_now_ns
fn time_now_ns() -> i64time_now_us
fn time_now_us() -> i64time_now_ms
fn time_now_ms() -> i64time_sleep_ns
fn time_sleep_ns(ns: i64)time_sleep_ms
fn time_sleep_ms(ms: i64)time_elapsed_ns
fn time_elapsed_ns(start_ns: i64) -> i64time_unix_secs
fn time_unix_secs() -> i64timeout
Deadline and Timeout Utilities
Functions
| Function | Description |
|---|---|
timeout_now | Get current time in milliseconds since epoch. |
timeout_deadline | Create a deadline ms milliseconds from now. |
timeout_remaining | Milliseconds remaining until deadline (0 if expired). |
timeout_expired | Check if deadline has passed. |
timeout_sleep_ms | Sleep for ms milliseconds using nanosleep. |
timeout_elapsed | Milliseconds elapsed since a start timestamp. |
timeout_timer_start | Start a timer. Returns current time in ms. |
timeout_timer_stop | Stop a timer. Returns elapsed milliseconds. |
timeout_print_int | Internal: print integer to stdout. |
timeout_timer_print | Print “label: Nms\n” for profiling. |
Details
timeout_now
fn timeout_now() -> i64Get current time in milliseconds since epoch.
tls
TLS 1.2 Client (Minimal)
Functions
| Function | Description |
|---|---|
_tls_copy | |
_tls_socket_tcp | |
_tls_connect_raw | |
_tls_send | |
_tls_recv | |
_tls_close | |
_tls_getrandom | |
tcp_connect | Connect to host:port via TCP. Returns socket fd or -1. |
_tls_build_client_hello | Internal: build TLS ClientHello message. |
tls_connect | Connect to host:port with TLS 1.2 handshake. Returns TLS context or 0 on fail… |
tls_write | Write data over TLS connection. Returns bytes written. Simplified: sends as T… |
tls_read | Read data from TLS connection. Returns bytes read. |
tls_close | Close TLS connection. |
Details
_tls_copy
fn _tls_copy(dst: &i8, doff: i64, src: &i8, soff: i64, n: i64)_tls_socket_tcp
fn _tls_socket_tcp() -> i64_tls_connect_raw
fn _tls_connect_raw(fd: i64, addr: &i8, len: i64) -> i64_tls_send
fn _tls_send(fd: i64, buf: &i8, len: i64) -> i64_tls_recv
fn _tls_recv(fd: i64, buf: &i8, max: i64) -> i64_tls_close
fn _tls_close(fd: i64) -> i64_tls_getrandom
fn _tls_getrandom(buf: &i8, n: i64) -> i64tcp_connect
fn tcp_connect(host: &i8, hlen: i64, port: i64) -> i64Connect to host:port via TCP. Returns socket fd or -1.
toml
Subset TOML Parser
Functions
| Function | Description |
|---|---|
_toml_byte_at | Internal byte reader. |
_toml_eq | Internal: compare bytes. |
_toml_skip_ws | Internal: skip whitespace. |
_toml_skip_line | Internal: skip to end of line. |
_toml_store | Internal: store bytes to data_buf, return offset where stored. |
_toml_store_dotted | Internal: store a dotted key (table.key) to data_buf. |
_toml_add | Internal: add entry. |
_toml_parse_int | Internal: parse integer from buf at off with given length. |
_toml_trim_end | Internal: trim trailing ws. Returns new end pos. |
_toml_parse_table | Internal: parse table header. Returns pos after line. |
_toml_store_key | Internal: store key (dotted if table is set). Returns stored key offset and s… |
_toml_parse_quoted | Internal: parse a quoted string value. Returns pos after closing quote. |
_toml_parse_unquoted | Internal: parse an unquoted value. Returns pos after line. |
_toml_parse_kv | Internal: parse key=value line. Returns pos after line. |
toml_parse | Parse TOML data. Returns handle. |
toml_count | Number of entries. |
_toml_find | Internal: find entry by key. Returns index or -1. |
toml_get_str | Get string value for key. Copies to out, returns length. -1 if not found. |
toml_get_i64 | Get integer value for key. Returns 0 if not found. |
toml_get_bool | Get boolean value for key. Returns 0 or 1. Returns -1 if not found. |
Details
_toml_byte_at
fn _toml_byte_at(buf: &i8, idx: i64) -> i64Internal byte reader.
transformer
Functions
| Function | Description |
|---|---|
row_max | |
softmax_row | |
softmax_rows | |
compute_mean | |
compute_var | |
norm_apply | |
layer_norm_fwd | |
attn_scores | |
attn_apply | |
attention_fwd | |
gelu_fwd | |
embed_fwd | |
pos_encode | |
linear_fwd | |
residual_add | |
relu_fwd |
Details
row_max
fn row_max(x: i64, base: i64, cols: i64) -> i64softmax_row
fn softmax_row(x: i64, out: i64, base: i64, cols: i64) -> i64softmax_rows
fn softmax_rows(x: i64, out: i64, rows: i64, cols: i64) -> i64compute_mean
fn compute_mean(x: i64) -> i64compute_var
fn compute_var(x: i64, mean: i64) -> i64norm_apply
fn norm_apply(x: i64, out: i64, mean: i64, std: i64, gamma: i64, beta: i64) -> i64layer_norm_fwd
fn layer_norm_fwd(x: i64, out: i64, gamma: i64, beta: i64) -> i64attn_scores
fn attn_scores(q: i64, k: i64, scores: i64, seq: i64, dk: i64) -> i64attn_apply
fn attn_apply(attn: i64, v: i64, out: i64, seq: i64, dk: i64) -> i64attention_fwd
fn attention_fwd(q: i64, k: i64, v: i64, out: i64, seq: i64, dk: i64) -> i64gelu_fwd
fn gelu_fwd(x: i64, out: i64) -> i64embed_fwd
fn embed_fwd(tokens: i64, table: i64, out: i64, seq: i64, d_model: i64) -> i64pos_encode
fn pos_encode(x: i64, seq: i64, d_model: i64) -> i64linear_fwd
fn linear_fwd(x: i64, w: i64, bias: i64, out: i64) -> i64residual_add
fn residual_add(a: i64, b: i64, out: i64) -> i64relu_fwd
fn relu_fwd(x: i64, out: i64) -> i64tsort
Topological Sort
Functions
| Function | Description |
|---|---|
tsort_new | Create a graph with n nodes (labeled 0..n-1). |
tsort_add_edge | Add a directed edge from → to. |
tsort_sort | Topological sort using Kahn’s algorithm. Returns vec of node IDs in topologic… |
tsort_has_cycle | Check if graph has a cycle. |
tsort_node_count | Number of nodes. |
tsort_edge_count | Number of edges. |
Details
tsort_new
fn tsort_new(n: i64) -> &i64Create a graph with n nodes (labeled 0..n-1).
tsort_add_edge
fn tsort_add_edge(g: &i64, from: i64, to: i64)Add a directed edge from → to.
tuple
Tuples / Multiple Return Values
Functions
| Function | Description |
|---|---|
pair | Create a pair (2-tuple). |
fst | First element. |
snd | Second element. |
triple | Create a triple (3-tuple). |
trd | Third element. |
tup_get | Generic indexed access. |
tup_set | Generic indexed mutation. |
pair_eq | Pair equality (element-wise). |
pair_swap | Swap pair elements. |
triple_eq | Triple equality (element-wise). |
result_ok | Result-style: success value with no error. |
result_err | Result-style: error with code. |
is_ok | Is result a success? (error code == 0) |
is_err | Is result an error? (error code != 0) |
unwrap | Get the value from a result. |
err_code | Get the error code from a result. |
Details
pair
fn pair(a: i64, b: i64) -> &i64Create a pair (2-tuple).
udp
// jda::net::udp — UDP Socket API
Constants
SYS_SOCKET = 41SYS_BIND = 49SYS_SENDTO = 44SYS_RECVFROM = 45SYS_SETSOCKOPT = 54SYS_CLOSE = 3AF_INET = 2SOCK_DGRAM = 2SOCK_NONBLOCK = 2048IPPROTO_UDP = 17SOL_SOCKET = 1SO_REUSEADDR = 2SO_REUSEPORT = 15SO_BROADCAST = 6IPPROTO_IP = 0IP_ADD_MEMBERSHIP = 35 // join multicast groupIP_DROP_MEMBERSHIP = 36 // leave multicast groupIP_MULTICAST_TTL = 33IP_MULTICAST_LOOP = 34EAGAIN = 11Structs
UdpPeer
struct UdpPeer {
addr: u32 // IPv4 address (host byte order)
port: u16
}UdpSocket
struct UdpSocket {
fd: i32
local_port: u16
}Functions
| Function | Description |
|---|---|
udp_echo_server |
Details
udp_echo_server
fn udp_echo_server(port: u16)uri
URI/URL Parsing and Encoding
Functions
| Function | Description |
|---|---|
uri_copy | Internal: copy bytes from src+off to dst, return len. |
uri_is_unreserved | Internal: is this byte unreserved (RFC 3986)? |
uri_hex_char | Internal: hex nibble to char. |
uri_hex_val | Internal: hex char to nibble. |
uri_parse | Parse a URI string into components. |
uri_scheme | |
uri_host | |
uri_port | |
uri_path | |
uri_query | |
uri_fragment | |
uri_encode | Percent-encode a string. Returns output length. |
uri_decode | Percent-decode a string. Returns output length. |
uri_query_get | Get a query parameter value by key. Returns length (0 if not found). query/ql… |
Details
uri_copy
fn uri_copy(src: &i8, off: i64, len: i64, dst: &i8) -> i64Internal: copy bytes from src+off to dst, return len.
uuid
UUID Generation
Functions
| Function | Description |
|---|---|
uuid_hex | Internal: write hex digit to buffer. |
uuid_v4 | Generate UUID v4 into dst buffer. Returns 36 (length). |
uuid_v4_print | Generate and print a UUID v4 to stdout. |
Details
uuid_hex
fn uuid_hex(val: i64) -> i64Internal: write hex digit to buffer.
uuid_v4
fn uuid_v4(dst: &i8) -> i64Generate UUID v4 into dst buffer. Returns 36 (length).
uuid_v4_print
fn uuid_v4_print()Generate and print a UUID v4 to stdout.
vec
Growable array of i64 values. Doubles capacity automatically when full. No external dependencies.
Memory Layout
Each vec is a pointer to a 3-word header (&i64):
| Offset | Field | Description |
|---|---|---|
[0] | length | Number of elements currently stored |
[1] | capacity | Number of allocated slots |
[2] | data_ptr | &i64 pointer to the backing array |
Usage
import vec
fn main() {
let v = vec_new(16)
// Add elements
vec_push(v, 10)
vec_push(v, 20)
vec_push(v, 30)
print(vec_len(v)) // 3
print(vec_get(v, 1)) // 20
// Modify in place
vec_set(v, 1, 25)
print(vec_get(v, 1)) // 25
// Remove last element
let last = vec_pop(v)
print(last) // 30
print(vec_len(v)) // 2
}Function Reference
| Function | Signature | Description |
|---|---|---|
vec_new | (cap: i64) -> &i64 | Create a new vec with initial capacity |
vec_len | (v: &i64) -> i64 | Get number of elements |
vec_cap | (v: &i64) -> i64 | Get current capacity |
vec_push | (v: &i64, val: i64) | Append an element |
vec_pop | (v: &i64) -> i64 | Remove and return last element |
vec_get | (v: &i64, idx: i64) -> i64 | Get element at index |
vec_set | (v: &i64, idx: i64, val: i64) | Set element at index |
vec_clear | (v: &i64) | Reset length to 0 |
vec_last | (v: &i64) -> i64 | Get last element |
vec_contains | (v: &i64, val: i64) -> i64 | Check if value exists |
vec_remove | (v: &i64, idx: i64) -> i64 | Remove at index, shift left |
Detailed API
vec_new
fn vec_new(cap: i64) -> &i64Create a new vec with the given initial capacity. The minimum capacity is 16 – values below 16 are rounded up.
weakref
Weak References
Functions
| Function | Description |
|---|---|
weakref_new | Create new weak reference to target pointer. |
weakref_deref | Dereference: get target pointer. Returns 0 if released. |
weakref_alive | Check if reference is still alive. |
weakref_release | Release the weak reference (mark target as gone). |
weakref_id | Get unique reference ID. |
weakref_registry_new | Registry: tracks a collection of weak references. Layout: [0]=count, [1]=capa… |
weakref_register | Register a weak reference in the registry. |
weakref_sweep | Sweep: count dead references and compact the registry. Returns number of dead… |
Details
weakref_new
fn weakref_new(target: i64) -> &i64Create new weak reference to target pointer.
ws
// jda::net::ws — WebSocket Protocol (RFC 6455)
Constants
WS_OP_CONTINUATION = 0x0WS_OP_TEXT = 0x1WS_OP_BINARY = 0x2WS_OP_CLOSE = 0x8WS_OP_PING = 0x9WS_OP_PONG = 0xAWS_MAX_FRAME = 65536 // 64 KB max frame (configurable)Structs
WsConn
struct WsConn {
stream: TcpStream
is_server: bool // server-side conns don't mask outgoing frames
}Functions
| Function | Description |
|---|---|
ws_accept | |
ws_connect | |
ws_recv | |
ws_read_frame | |
ws_send_text | |
ws_send_binary | |
ws_ping | |
ws_close | |
ws_send_frame | |
tcp_read_exact | |
sha1 | |
rol32 | |
base64_encode |
Details
ws_accept
fn ws_accept(stream: own TcpStream) -> Result<own WsConn, []i8>ws_connect
fn ws_connect(host: ref []i8, port: u16, path: ref []i8)ws_recv
fn ws_recv(conn: &WsConn, r: &mut Region) -> Result<WsMessage, []i8>ws_read_frame
fn ws_read_frame(conn: &WsConn, r: &mut Region)ws_send_text
fn ws_send_text(conn: &WsConn, text: ref []i8)ws_send_binary
fn ws_send_binary(conn: &WsConn, data: ref []u8)ws_ping
fn ws_ping(conn: &WsConn)ws_close
fn ws_close(conn: &WsConn, code: u16, reason: ref []i8)ws_send_frame
fn ws_send_frame(conn: &WsConn, opcode: u8, data: []u8, mask: bool)tcp_read_exact
fn tcp_read_exact(fd: i32, buf: *u8, n: i64) -> Result<(), []i8>sha1
fn sha1(msg: ref []i8, out: []mut u8)rol32
fn rol32(x: u32, n: u32) -> u32 => (x << n) | (x >> (32 - n))base64_encode
fn base64_encode(src: []u8, dst: []mut i8) -> i64xml
Simple XML Parser (SAX-style events)
Functions
| Function | Description |
|---|---|
_xml_byte_at | Internal byte reader. |
_xml_copy | Internal: copy bytes. |
_xml_add_evt | Internal: add event. |
_xml_tag_name_end | Internal: find end of tag name (space or > or /). |
_xml_find_lt | Internal: find ‘<’ from pos. |
_xml_find_gt | Internal: find ‘>’ from pos. |
_xml_skip_comment | Internal: skip comment . Returns position after –>. |
_xml_skip_pi | Internal: skip PI . Returns position after ?>. |
_xml_process_tag | Internal: process a tag starting at ‘<’. Returns new pos. |
xml_parse | Parse XML buffer into events. |
xml_event_count | Return event count. |
xml_event_type | Return event type at index. |
xml_event_name | Copy event name/text to out. Return length. |
xml_event_text | Copy event text to out. Return length. |
xml_escape | Escape XML special chars: & < > " ' |
_xml_check_lt | Internal: check 3-char entity after &. |
_xml_check_gt | |
_xml_check_amp | |
_xml_check_quot | |
_xml_check_apos | |
xml_unescape | Unescape XML entities: & < > " ' |
Details
_xml_byte_at
fn _xml_byte_at(buf: &i8, idx: i64) -> i64Internal byte reader.
yaml
YAML Parser/Emitter (Subset)
Functions
| Function | Description |
|---|---|
_yaml_copy | |
_yaml_streq | |
_yaml_add | Internal: add a key-value pair to the document. |
yaml_parse | Parse YAML string into document. Returns doc pointer. |
yaml_get | Get string value by key. Copies to out, returns length. 0 if not found. |
yaml_get_i64 | Get integer value by key. |
yaml_count | Number of entries. |
yaml_key_at | Get key at index. Returns key length. |
yaml_val_at | Get value at index. Returns value length. |
yaml_emit | Emit YAML from document. Returns output length. |
Details
_yaml_copy
fn _yaml_copy(dst: &i8, doff: i64, src: &i8, soff: i64, n: i64)_yaml_streq
fn _yaml_streq(a: &i8, aoff: i64, alen: i64, b: &i8, boff: i64, blen: i64) -> i64_yaml_add
fn _yaml_add(doc: &i64, key: &i8, koff: i64, klen: i64, val: &i8, voff: i64, vlen: i64)Internal: add a key-value pair to the document.
zipfile
ZIP Archive Format (Stored Only)
Functions
| Function | Description |
|---|---|
_zip_byte_at | Internal byte reader. |
_zip_w16 | Internal: write little-endian 16-bit. |
_zip_w32 | Internal: write little-endian 32-bit. |
_zip_r16 | Internal: read little-endian 16-bit. |
_zip_r32 | Internal: read little-endian 32-bit. |
_zip_crc32_byte | Simple CRC-32 for ZIP (same algorithm as gzip). |
_zip_crc32 | Compute CRC-32 for data. |
zip_create | Create a write handle. |
zip_add | Add a stored file entry to the ZIP. |
zip_finish | Write central directory and EOCD. Returns total archive length. |
_zip_find_eocd | Internal: scan for EOCD to find central directory. |
zip_open | Open a ZIP archive for reading. |
zip_count | Number of entries in the ZIP. |
zip_entry_name | Copy entry name at index to out. Returns length. |
zip_entry_size | Get data size for entry at index. |
zip_entry_data | Copy entry data at index to out. Returns length. |
Details
_zip_byte_at
fn _zip_byte_at(buf: &i8, idx: i64) -> i64Internal byte reader.
zlib
Compression (CRC-32, Deflate/Inflate)
Constants
CRC32_POLY = 3988292384CRC-32 polynomial: 0xEDB88320 (reversed)
Functions
| Function | Description |
|---|---|
zlib_crc32 | CRC-32 of data buffer. |
zlib_crc32_update | Incremental CRC-32 update. |
zlib_adler32 | Adler-32 checksum. |
zlib_compress | Compress using simplified DEFLATE (stored blocks, no Huffman for simplicity)…. |
zlib_decompress | Decompress zlib-compressed data (handles stored blocks). Returns decompressed… |
Details
zlib_crc32
fn zlib_crc32(data: &i8, len: i64) -> i64CRC-32 of data buffer.
zlib_crc32_update
fn zlib_crc32_update(crc: i64, data: &i8, len: i64) -> i64Incremental CRC-32 update.
zlib_adler32
fn zlib_adler32(data: &i8, len: i64) -> i64Adler-32 checksum.