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

PackageDescription
stringLength-prefixed strings with immutable-style API
vecDynamic array (growable Vec<i64>)
hashmapHash map with open addressing and linear probing
sortQuicksort, binary search, merge, min/max for Vec
convValue conversions – itoa, atoi, hex, binary
mathInteger math, random numbers, GCD, primes

Data Formats

PackageDescription
jsonZero-copy JSON parser and serialiser
csvCSV reader and writer
base64Base64 encoding and decoding
tomlTOML configuration file parser
yamlYAML parser
xmlXML parser

File System and I/O

PackageDescription
fsLow-level file I/O via Linux syscalls
file_ioHigh-level file I/O helpers (slurp, write, copy)
ioBuffered I/O streams
tempfileTemporary file creation
globFile glob pattern matching
mmapMemory-mapped file I/O

Networking

PackageDescription
tcpTCP socket API (connect, listen, accept)
httpHTTP/1.1 request parser and response writer
httpclientHTTP client for making requests
httpserverHTTP server framework
dnsDNS resolver
tlsTLS/SSL support
udpUDP datagram sockets
wsWebSocket protocol

Text Processing

PackageDescription
regexRegular expression matching (backtracking engine)
fmtString formatting
diffText diffing
textwrapText wrapping and filling
encodingCharacter encoding conversions

Testing and Debugging

PackageDescription
testingTest framework with assertions
benchmarkPerformance benchmarking
logLogging framework
debugSoftware debugger — breakpoints, watchpoints, assertions
lintCode style checker — naming conventions, warnings
profileFunction-level profiler — timing, call counts, report

Concurrency and OS

PackageDescription
processProcess spawning and management
signalSignal handling
mutexMutual exclusion locks
schedScheduler primitives
osOS information and environment
platformPlatform detection

Data Structures

PackageDescription
heapBinary heap / priority queue
setHash set
queueFIFO queue
ringRing buffer
tupleTuple types

Numerics and Science

PackageDescription
bignumArbitrary precision integers
complexComplex number arithmetic
rationalRational number arithmetic
fixedpointFixed-point arithmetic
matrixMatrix operations
statisticsStatistical functions

Security

PackageDescription
cryptoCryptographic primitives
digestHash digests (SHA, MD5)
securerandomCryptographically secure random numbers
uuidUUID generation

All Packages (A-Z)

PackageDescription
argsCommand-line argument parsing
autogradAutomatic differentiation
avx512_opsAVX-512 SIMD operations
base64Base64 encoding/decoding
benchmarkPerformance benchmarking
bignumArbitrary precision integers
bitopsBitwise operations
calendarCalendar date calculations
complexComplex number arithmetic
comprehensionList comprehension helpers
compressData compression
configparserINI-style config file parser
contextContext propagation
convValue conversions (itoa, atoi, hex)
copyDeep copy utilities
cryptoCryptographic primitives
csvCSV reader/writer
dataData structure utilities
dataclassData class helpers
datetimeDate and time handling
debugSoftware debugger
decoratorDecorator pattern support
diffText diffing
digestHash digests
dnsDNS resolver
emailEmail message handling
encodingCharacter encoding
enumEnumeration helpers
erbTemplate engine
errnoError number definitions
file_ioHigh-level file I/O
fileutilsFile utility functions
findFile finding utilities
fixedpointFixed-point arithmetic
fmtString formatting
fnmatchFilename pattern matching
fsLow-level file I/O
ftpFTP client
getpassPassword input
globGlob pattern matching
gzipGzip compression
hashmapHash map
heapBinary heap
htmlparserHTML parser
httpHTTP/1.1 parser
httpclientHTTP client
httpserverHTTP server
ioBuffered I/O
ipaddrIP address handling
iterIterator utilities
jsonJSON parser/serialiser
kvstoreKey-value store
linecacheLine caching for files
lintCode style checker
logLogging
marshalObject serialisation
mathInteger math and random
matrixMatrix operations
metricsMetrics collection
mimetypesMIME type detection
mmapMemory-mapped I/O
mutexMutual exclusion
netrc.netrc file parser
nnNeural network primitives
observerObserver pattern
open3Process I/O capture
operatorOperator overloading helpers
optparseOption parsing
osOS utilities
packBinary packing/unpacking
pathnamePath manipulation
platformPlatform detection
plotData plotting
ppPretty printing
processProcess management
profileFunction-level profiler
ptxPTX GPU code generation
queueFIFO queue
rangeRange types
rationalRational numbers
regexRegular expressions
ringRing buffer
rocmROCm GPU support
schedScheduler primitives
securerandomSecure random numbers
selectI/O multiplexing
setHash set
shellShell command execution
signalSignal handling
smtpSMTP email sending
socketserverSocket server framework
sortSorting algorithms
statisticsStatistical functions
stringString type
stringioIn-memory string I/O
stringscannerString scanning
tarfileTar archive handling
tcpTCP sockets
tempfileTemporary files
testingTest framework
textwrapText wrapping
timeTime functions
timeoutTimeout handling
tlsTLS/SSL
tomlTOML parser
transformerTransformer model primitives
tsortTopological sort
tupleTuple types
udpUDP sockets
uriURI parsing
uuidUUID generation
vecDynamic array
weakrefWeak references
wsWebSocket protocol
xmlXML parser
yamlYAML parser
zipfileZip archive handling
zlibZlib compression

args

CLI Argument Parser

Functions

FunctionDescription
args_str_eqInternal: compare two C strings up to len bytes.
args_strlenInternal: strlen of a C string (null-terminated).
args_find_eqInternal: find ‘=’ in a C string, return index or -1.
args_newCreate argument parser.
args_parseParse all arguments (skip argv[0] which is the program name).
args_has_flagCheck if a flag is present.
args_get_optGet option value for –key=val. Returns 0 if not found.
args_positionalGet positional argument at index.
args_positional_countNumber of positional arguments.
args_argcTotal argc.

Details

args_str_eq

fn args_str_eq(a: &i8, b: &i8, len: i64) -> i64

Internal: compare two C strings up to len bytes.

autograd

Functions

FunctionDescription
grad_add_a
grad_add_b
grad_sub_a
grad_sub_b
grad_mul_a
grad_mul_b
grad_div_a
grad_div_b
grad_relu
grad_exp
grad_log
grad_tanh
grad_tensor_add
grad_tensor_mul
grad_tensor_relu
grad_tensor_sum
grad_matmul
grad_check_close

Details

grad_add_a

fn grad_add_a(grad_c: i64) -> i64

grad_add_b

fn grad_add_b(grad_c: i64) -> i64

grad_sub_a

fn grad_sub_a(grad_c: i64) -> i64

grad_sub_b

fn grad_sub_b(grad_c: i64) -> i64

grad_mul_a

fn grad_mul_a(b: i64, grad_c: i64) -> i64

grad_mul_b

fn grad_mul_b(a: i64, grad_c: i64) -> i64

grad_div_a

fn grad_div_a(b: i64, grad_c: i64) -> i64

grad_div_b

fn grad_div_b(a: i64, b: i64, grad_c: i64) -> i64

grad_relu

fn grad_relu(a: i64, grad_c: i64) -> i64

grad_exp

fn grad_exp(c: i64, grad_c: i64) -> i64

grad_log

fn grad_log(a: i64, grad_c: i64) -> i64

grad_tanh

fn grad_tanh(c: i64, grad_c: i64) -> i64

grad_tensor_add

fn grad_tensor_add(grad_c: i64, grad_a: i64, grad_b: i64) -> i64

grad_tensor_mul

fn grad_tensor_mul(a: i64, b: i64, grad_c: i64, grad_a: i64, grad_b: i64) -> i64

grad_tensor_relu

fn grad_tensor_relu(a: i64, grad_c: i64, grad_a: i64) -> i64

grad_tensor_sum

fn grad_tensor_sum(grad_c_scalar: i64, grad_a: i64) -> i64

grad_matmul

fn grad_matmul(a: i64, b: i64, grad_c: i64, grad_a: i64, grad_b: i64) -> i64

grad_check_close

fn grad_check_close(analytical: i64, numerical: i64, eps: i64) -> i64

avx512_ops

Functions

FunctionDescription
vec_add
vec_mul
vec_scale
vec_sum
vec_dot

Details

vec_add

fn vec_add(dst: i64, a: i64, b: i64) -> i64

vec_mul

fn vec_mul(dst: i64, a: i64, b: i64) -> i64

vec_scale

fn vec_scale(dst: i64, a: i64, s: i64) -> i64

vec_sum

fn vec_sum(a: i64) -> i64

vec_dot

fn vec_dot(a: i64, b: i64) -> i64

base64

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

FunctionSignatureDescription
b64_encode(src: &i8, src_len: i64, dst: &i8) -> i64Encode bytes to Base64
b64_decode(src: &i8, src_len: i64, dst: &i8) -> i64Decode Base64 to bytes
b64_encoded_len(src_len: i64) -> i64Calculate encoded output length
b64_decoded_len(src_len: i64) -> i64Calculate maximum decoded output length
b64_char(idx: i64) -> i64Get Base64 alphabet character
b64_val(ch: i64) -> i64Decode a Base64 character

Detailed API

b64_encode

fn b64_encode(src: &i8, src_len: i64, dst: &i8) -> i64

Encode 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

FunctionDescription
bench_now_nsGet current timestamp in nanoseconds.
bench_startStart a benchmark timer.
bench_stopStop timer, return elapsed nanoseconds.
bench_msStop timer, return elapsed milliseconds.
bench_usStop timer, return elapsed microseconds.
bench_print_intInternal: print integer.
bench_reportPrint benchmark result: “name: 12345ns (12.345ms)”
bench_iterRun fn_ptr() n times. Returns total nanoseconds.
bench_iter_reportRun fn_ptr() n times and print results.

Details

bench_now_ns

fn bench_now_ns() -> i64

Get current timestamp in nanoseconds.

bignum

Arbitrary Precision Integers

Constants

BN_BASE = 1000000000

Functions

FunctionDescription
_bn_allocInternal: allocate BigNum with given limb capacity.
bn_newCreate BigNum from i64 value.
bn_from_strParse decimal string to BigNum. Handles optional leading ‘-’.
bn_abs_cmpCompare magnitudes (ignoring sign). Returns -1, 0, or 1.
bn_cmpCompare two BigNums. Returns -1, 0, or 1.
_bn_add_magInternal: add magnitudes. Both must be non-negative limb arrays.
_bn_sub_magInternal: subtract magnitudes.
bn_addAdd two BigNums.
bn_subSubtract: a - b.
bn_mulMultiply two BigNums. Grade-school algorithm.
bn_is_zeroCheck if BigNum is zero.
bn_negateNegate: return new BigNum with flipped sign.
bn_to_strConvert BigNum to decimal string. Returns length written.
bn_to_i64Convert BigNum to i64 (truncates if too large).

Details

_bn_alloc

fn _bn_alloc(cap: i64) -> &i64

Internal: allocate BigNum with given limb capacity.

bitops

Bit Manipulation Utilities

Functions

FunctionDescription
bit_pow2Internal: power of 2 lookup.
bit_shlLeft shift: a « n.
bit_shrLogical right shift: a »> n (unsigned).
bit_andBitwise AND via arithmetic decomposition.
bit_orBitwise OR via arithmetic decomposition.
bit_xorBitwise XOR via arithmetic decomposition.
bit_notBitwise NOT (ones complement, 64-bit).
bit_getGet bit n of a (0 or 1).
bit_setSet bit n of a to 1.
bit_clearClear bit n of a to 0.
bit_toggleToggle bit n of a.
bit_countPopulation count (number of 1 bits).
bit_leading_zerosNumber of leading zero bits (from MSB).
bit_trailing_zerosNumber of trailing zero bits (from LSB).
bit_reverseReverse bit order.
bit_rotlRotate left by n positions.
bit_rotrRotate right by n positions.

Details

bit_pow2

fn bit_pow2(n: i64) -> i64

Internal: power of 2 lookup.

calendar

Calendar Utilities

Functions

FunctionDescription
_cal_is_leapInternal: leap year check.
_cal_dimInternal: days in month.
_cal_dateInternal: days since epoch (1970-01-01 = day 0).
_cal_copyInternal: copy literal.
cal_weekdayDay of week for a date. 0=Monday, 6=Sunday. Uses Tomohiko Sakamoto’s algorithm.
cal_is_leapCheck leap year.
cal_days_in_monthDays in month.
cal_day_nameGet day name (0=Mon..6=Sun). Returns length written.
cal_month_nameGet month name (1-12). Returns length written.
_cal_write_dayInternal: write 2-char number right-aligned.
cal_month_strGenerate a month calendar string. Returns length. Format: “Mo Tu We Th Fr Sa …

Details

_cal_is_leap

fn _cal_is_leap(year: i64) -> i64

Internal: leap year check.

complex

Complex Number Arithmetic

Functions

FunctionDescription
cx_newCreate complex number.
cx_addAdd two complex numbers.
cx_subSubtract: a - b.
cx_mulMultiply: (a+bi)(c+di) = (ac-bd) + (ad+bc)i.
cx_scaleScalar multiply.
cx_abs_sqMagnitude squared:
cx_conjugateComplex conjugate.
cx_eqEquality check.
cx_reReal part.
cx_imImaginary part.
cx_is_realCheck if purely real.
_cx_write_intInternal: write integer to buffer. Returns chars written.
cx_to_strFormat as string: “a+bi” or “a-bi”. Returns length.

Details

cx_new

fn cx_new(re: i64, im: i64) -> &i64

Create complex number.

comprehension

List/Dict Comprehensions

Functions

FunctionDescription
range
range2
range3
vec_comp_map
vec_comp_filter
vec_comp_map_filter
vec_sum
vec_any
vec_count
vec_each
vec_enumerate
vec_zip
vec_slice
vec_reverse
vec_sort
vec_min
vec_max
vec_flatten
vec_concat
vec_from_arr
map_from_vecs
map_keys
map_vals
map_items
map_comp_filter
map_comp_map_vals

Details

range

fn range(stop: i64) -> &i64

range2

fn range2(start: i64, stop: i64) -> &i64

range3

fn range3(start: i64, stop: i64, step: i64) -> &i64

vec_comp_map

fn vec_comp_map(v: &i64, f: i64) -> &i64

vec_comp_filter

fn vec_comp_filter(v: &i64, pred: i64) -> &i64

vec_comp_map_filter

fn vec_comp_map_filter(v: &i64, f: i64, pred: i64) -> &i64

vec_sum

fn vec_sum(v: &i64) -> i64

vec_any

fn vec_any(v: &i64, pred: i64) -> i64

vec_count

fn vec_count(v: &i64, pred: i64) -> i64

vec_each

fn vec_each(v: &i64, f: i64)

vec_enumerate

fn vec_enumerate(v: &i64) -> &i64

vec_zip

fn vec_zip(a: &i64, b: &i64) -> &i64

vec_slice

fn vec_slice(v: &i64, start: i64, stop: i64) -> &i64

vec_reverse

fn vec_reverse(v: &i64) -> &i64

vec_sort

fn vec_sort(v: &i64) -> &i64

vec_min

fn vec_min(v: &i64) -> i64

vec_max

fn vec_max(v: &i64) -> i64

vec_flatten

fn vec_flatten(vecs: &i64, n: i64) -> &i64

vec_concat

fn vec_concat(a: &i64, b: &i64) -> &i64

vec_from_arr

fn vec_from_arr(arr: &i64, len: i64) -> &i64

map_from_vecs

fn map_from_vecs(keys: &i64, vals: &i64) -> &i64

map_keys

fn map_keys(m: &i64) -> &i64

map_vals

fn map_vals(m: &i64) -> &i64

map_items

fn map_items(m: &i64) -> &i64

map_comp_filter

fn map_comp_filter(m: &i64, pred: i64) -> &i64

map_comp_map_vals

fn map_comp_map_vals(m: &i64, f: i64) -> &i64

compress

Compression Utilities (RLE + LZ77 stubs)

Functions

FunctionDescription
_cmp_byte_atInternal byte reader.
compress_rleRLE compress data into out. Returns compressed length. Format: repeated [coun…
decompress_rleRLE decompress data into out. Returns decompressed length.
compress_lz77LZ77 compress (stub — not implemented). Returns -1.
decompress_lz77LZ77 decompress (stub — not implemented). Returns -1.

Details

_cmp_byte_at

fn _cmp_byte_at(buf: &i8, idx: i64) -> i64

Internal byte reader.

compress_rle

fn compress_rle(data: &i8, len: i64, out: &i8) -> i64

RLE compress data into out. Returns compressed length. Format: repeated [count][byte] pairs.

configparser

INI File Parser

Functions

FunctionDescription
_ini_byte_atInternal byte reader.
_ini_copyInternal: copy bytes from src+off to dst, length len.
_ini_eqInternal: compare two byte ranges for equality.
_ini_skip_wsInternal: skip whitespace at pos. Returns new pos.
_ini_skip_lineInternal: skip to end of line. Returns pos after newline.
_ini_add_entryInternal: add one entry. Val info passed via h[11], h[12].
_ini_parse_sectionInternal: parse section header. Sets h[9], h[10]. Returns pos after line.
_ini_trim_endInternal: trim trailing whitespace. Returns new end position.
_ini_parse_kvInternal: parse key=value line. Returns pos after line.
ini_parseParse INI data from buf. Returns handle.
ini_parse_fullAlias for compatibility.
ini_countNumber of entries in the INI handle.
ini_getGet value for section+key. Copies to out, returns length. -1 if not found.
ini_get_i64Get value as i64. Returns 0 if not found. Parses directly from data buffer to…
ini_has_sectionCheck if section exists. Returns 1 if found, 0 otherwise.
ini_setSet a value for section+key. Overwrites if exists, appends if new. Val and vl…
_ini_write_section_kvsInternal: write section’s key=value pairs.
ini_writeWrite INI data to out buffer. Returns length written.

Details

_ini_byte_at

fn _ini_byte_at(buf: &i8, idx: i64) -> i64

Internal byte reader.

context

Structs

CtxTimespec

struct CtxTimespec {
    tv_sec: i64
    tv_nsec: i64
}

Functions

FunctionDescription
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() -> i64

ctx_background

fn ctx_background() -> &i64

ctx_with_cancel

fn ctx_with_cancel(parent: &i64) -> &i64

ctx_with_deadline

fn ctx_with_deadline(parent: &i64, deadline_ns: i64) -> &i64

ctx_with_timeout

fn ctx_with_timeout(parent: &i64, timeout_ns: i64) -> &i64

ctx_cancel

fn ctx_cancel(ctx: &i64)

ctx_done

fn ctx_done(ctx: &i64) -> i64

ctx_done_chan

fn ctx_done_chan(ctx: &i64) -> &i64

ctx_err

fn ctx_err(ctx: &i64) -> i64

ctx_deadline

fn ctx_deadline(ctx: &i64) -> i64

conv

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

FunctionSignatureDescription
conv_itoa(val: i64, dst: &i8) -> i64Integer to decimal string
conv_atoi(src: &i8, len: i64) -> i64Decimal string to integer
conv_itohex(val: i64, dst: &i8) -> i64Integer to hex string (lowercase)
conv_hextoi(src: &i8, len: i64) -> i64Hex string to integer
conv_itobin(val: i64, dst: &i8) -> i64Integer to binary string
conv_itoa_pad(val: i64, dst: &i8, width: i64) -> i64Integer to zero-padded decimal

Detailed API

conv_itoa

fn conv_itoa(val: i64, dst: &i8) -> i64

Convert an integer to its decimal string representation. Handles negative numbers (writes a leading -). The result is written to dst.

copy

Deep Copy Utilities

Functions

FunctionDescription
_cp_byte_atInternal byte reader.
copy_bytesCopy n bytes from src to dst. Returns n.
copy_i64_arrayCopy an i64 array of given length. Returns new array pointer.
copy_vecDeep copy a vec structure. Vec layout: [0]=len, [1]=cap, [2..]=data
copy_bufCopy a byte buffer. Returns new buffer.
copy_i64_rangeCopy n i64 values from src+soff to dst+doff.

Details

_cp_byte_at

fn _cp_byte_at(buf: &i8, idx: i64) -> i64

Internal byte reader.

crypto

// jda::crypto — Cryptographic primitives

Constants

SHA256_BLOCK  = 64    // bytes per block
SHA256_DIGEST = 32    // bytes in output
SHA1_DIGEST = 20
AES_BLOCK = 16

Structs

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

FunctionDescription
sha256_k
rotr32
sha256_transform
sha256_init
sha256_update
sha256_final
sha256
rotl32
sha1_transform
sha1_init
sha1_update
sha1_final
sha1
hmac_sha256
aes_sbox
xtime
gf_mul
aes_key_expand
aes_add_round_key
aes_sub_bytes
aes_shift_rows
aes_mix_columns
aes_encrypt_block
aes_ctr
aes128_ctr_init
aes256_ctr_init
chacha20_quarter_round
chacha20_block
chacha20_encrypt
poly1305_init
poly1305_mac
chacha20_poly1305_seal
chacha20_poly1305_open
ct_memcmp
hex_encode
base64_encode

Details

sha256_k

fn sha256_k(i: i64) -> u32

rotr32

fn rotr32(x: u32, n: u32) -> u32

sha256_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) -> u32

sha1_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) -> u8

xtime

fn xtime(x: u8) -> u8

gf_mul

fn gf_mul(a: u8, b: u8) -> u8

aes_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) -> i32

hex_encode

fn hex_encode(inp: &u8, len: i64, out: &i8)

base64_encode

fn base64_encode(inp: &u8, in_len: i64, out: &i8) -> i64

csv

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

FunctionSignatureDescription
csv_parse_row(src: &i8, len: i64) -> &i64Parse a single CSV row
csv_field_count(row: &i64) -> i64Number of fields in a row
csv_field(row: &i64, idx: i64, dst: &i8) -> i64Copy field to buffer
csv_field_int(row: &i64, idx: i64) -> i64Parse field as integer
csv_parse_all(src: &i8, len: i64) -> &i64Parse all rows from CSV data
csv_row_count(rows: &i64) -> i64Number of parsed rows
csv_get_row(rows: &i64, idx: i64) -> &i64Get row by index
csv_write_row(fields: &i64, lengths: &i64, count: i64, dst: &i8) -> i64Write a CSV row

Detailed API

csv_parse_row

fn csv_parse_row(src: &i8, len: i64) -> &i64

Parse 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

FunctionDescription
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) -> Tensor

csv_load

fn csv_load(path: ref []i8, label_cols: i64) -> Result<;own Dataset, []i8>

csv_count_rows

fn csv_count_rows(src: ref []i8) -> i64

csv_count_cols

fn csv_count_cols(src: ref []i8) -> i64

parse_csv_f32

fn parse_csv_f32(src: ref []i8, pos: i64) -> (f32, i64)

dataclass

Data Class Utilities

Functions

FunctionDescription
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) -> i64

cmp_gt

fn cmp_gt(lt: i64, eq: i64) -> i64

cmp_ge

fn cmp_ge(lt: i64, eq: i64) -> i64

cmp

fn cmp(lt_ab: i64, lt_ba: i64) -> i64

cmp_is_min

fn cmp_is_min(lt: i64) -> i64

cmp_clamp

fn cmp_clamp(val_lt_lo: i64, hi_lt_val: i64) -> i64

validate_range

fn validate_range(val: i64, lo: i64, hi: i64) -> i64

validate_positive

fn validate_positive(val: i64) -> i64

validate_non_negative

fn validate_non_negative(val: i64) -> i64

datetime

Date, Time, and DateTime Functions

Functions

FunctionDescription
_dt_time_syscallInternal: get current time via time(2) syscall 201.
dt_is_leapCheck if year is a leap year.
dt_days_in_monthDays in a given month (1-12).
dt_dateConvert year/month/day to days since epoch (1970-01-01 = day 0).
dt_yearExtract year from days since epoch.
_dt_day_of_yearInternal: remaining days after subtracting full years.
dt_monthExtract month from days since epoch.
dt_dayExtract day-of-month from days since epoch.
dt_weekdayDay of week: 0=Thu (epoch was Thursday), 1=Fri, …, 6=Wed. More useful: (dt_…
dt_nowCurrent unix timestamp in seconds.
dt_from_tsConvert unix timestamp to days since epoch.
_dt_write2Internal: write 2-digit number to buffer.
_dt_write4Internal: write 4-digit number to buffer.
dt_formatFormat timestamp as “YYYY-MM-DD HH:MM:SS”. Returns length (always 19).
dt_diffDifference between two timestamps in seconds.
dt_add_daysAdd days to a timestamp.
dt_add_hoursAdd hours to a timestamp.

Details

_dt_time_syscall

fn _dt_time_syscall() -> i64

Internal: 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

FunctionSignatureDescription
dbg_init()Initialise debugger state
dbg_enable()Enable debug output
dbg_disable()Disable debug output
dbg_is_enabled() -> i64Check 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() -> i64Return number of active watchpoints
dbg_check() -> i64Check 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() -> i64Return 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

FunctionDescription
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) -> i64

apply2

fn apply2(f: i64, x: i64, y: i64) -> i64

fold

fn fold(f: i64, arr: &i64, len: i64, init: i64) -> i64

map_arr

fn map_arr(f: i64, arr: &i64, len: i64, out: &i64) -> i64

filter_arr

fn filter_arr(f: i64, arr: &i64, len: i64, out: &i64) -> i64

for_each

fn for_each(f: i64, arr: &i64, len: i64) -> i64

find_idx

fn find_idx(f: i64, arr: &i64, len: i64) -> i64

all_of

fn all_of(f: i64, arr: &i64, len: i64) -> i64

any_of

fn any_of(f: i64, arr: &i64, len: i64) -> i64

count_of

fn count_of(f: i64, arr: &i64, len: i64) -> i64

retry_call

fn retry_call(f: i64, arg: i64, max_attempts: i64) -> i64

pipeline

fn pipeline(fns: &i64, nfns: i64, initial: i64) -> i64

tabulate

fn tabulate(f: i64, out: &i64, n: i64) -> i64

zip_with

fn zip_with(f: i64, xs: &i64, ys: &i64, len: i64, out: &i64) -> i64

diff

Sequence Comparison and Diff

Functions

FunctionDescription
_diff_byte_atInternal byte reader.
diff_lcs_lenCompute Longest Common Subsequence length. Uses O(n*m) DP. Max input ~200 cha…
diff_ratioCompute similarity ratio * 10000. ratio = 2 * lcs_len / (alen + blen) * 10000
diff_linesSimple line-by-line diff output. Lines prefixed with +/- / (space). Compares …

Details

_diff_byte_at

fn _diff_byte_at(buf: &i8, idx: i64) -> i64

Internal byte reader.

diff_lcs_len

fn diff_lcs_len(a: &i8, alen: i64, b: &i8, blen: i64) -> i64

Compute Longest Common Subsequence length. Uses O(n*m) DP. Max input ~200 chars (limited by alloc_pages).

digest

Message Digest Algorithms

Functions

FunctionDescription
_dig_copyInternal: byte copy.
_dig_hexInternal: hex digit.
digest_hexConvert binary hash to hex string. Returns hex length (2 * hlen).
_md5_sInternal: MD5 per-round shift amounts.
_md5_tInternal: MD5 sine-derived constants (T[i] = floor(2^32 * abs(sin(i+1)))).
_md5_rotlInternal: 32-bit left rotate.
_md5_read32Internal: read 32-bit LE from buffer.
_md5_write32Internal: write 32-bit LE to buffer.
md5MD5 hash. out must be 16 bytes.
md5_hexMD5 as hex string. Returns 32.
_sha512_kSHA-512 round constants (first 16 of 80).
sha512SHA-512 hash. out must be 64 bytes. Note: Simplified implementation — produ…
sha512_hexSHA-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

FunctionDescription
_dns_copy
_dns_open_read
_dns_read
_dns_close
_dns_socket_udp
_dns_sendto
_dns_connect
_dns_send
_dns_recv
_dns_close_sock
dns_nameserverInternal: parse /etc/resolv.conf to find first nameserver IP. Writes 4 bytes …
_dns_build_queryInternal: build DNS query packet for A record. Returns packet length.
dns_resolveResolve hostname to IPv4. Writes 4 bytes to out. Returns 1 on success.
dns_resolve_strResolve 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) -> i64

dns_nameserver

fn dns_nameserver(out: &i8) -> i64

Internal: parse /etc/resolv.conf to find first nameserver IP. Writes 4 bytes to out. Returns 1 if found, 0 if not.

email

Email Message Parser/Composer

Functions

FunctionDescription
_email_byte_atInternal byte reader.
_email_copyInternal: copy bytes.
_email_lowerInternal: case-insensitive compare single bytes.
_email_eq_ciInternal: case-insensitive compare.
_email_find_bodyInternal: find the blank line separating headers from body. Returns offset of…
_email_parse_hdrInternal: parse one header line starting at pos. Sets name_off, name_len, val…
email_parseParse an email message. Returns handle.
_email_get_hdrInternal: find header by name (case-insensitive), copy value to out.
email_fromGet From header value.
email_toGet To header value.
email_subjectGet Subject header value.
email_bodyGet email body.
email_headerGet any header value by name.
email_header_countReturn number of headers.

Details

_email_byte_at

fn _email_byte_at(buf: &i8, idx: i64) -> i64

Internal byte reader.

encoding

Character Encoding Utilities

Functions

FunctionDescription
enc_utf8_validValidate UTF-8 byte sequence. Returns 1 if valid, 0 if invalid.
enc_utf8_char_countCount UTF-8 codepoints in buffer.
enc_utf8_byte_lenByte length of first nchars codepoints.
enc_is_asciiCheck if all bytes are ASCII (< 128).
enc_to_upperConvert ASCII lowercase to uppercase. Returns length.
enc_to_lowerConvert ASCII uppercase to lowercase. Returns length.
enc_latin1_to_utf8Convert Latin-1 (ISO 8859-1) to UTF-8. Returns output length.
enc_utf8_codepoint_atRead UTF-8 codepoint at byte offset. Returns codepoint value.
enc_utf8_nextGet next byte offset after codepoint at given offset.

Details

enc_utf8_valid

fn enc_utf8_valid(buf: &i8, len: i64) -> i64

Validate UTF-8 byte sequence. Returns 1 if valid, 0 if invalid.

enum

Enumeration Type with Named Constants

Functions

FunctionDescription
_enum_byte_atInternal byte reader.
_enum_streqInternal: compare two strings.
_enum_copyInternal: copy bytes.
enum_newCreate a new enum type. name/nlen is the enum’s name (for display). Layout: […
enum_addAdd a variant to the enum. Returns index on success, -1 if full.
enum_by_nameLookup value by variant name. Returns value or -1 if not found.
enum_by_valLookup name by value. Writes name to out, returns length. -1 if not found.
enum_countReturn number of variants.
enum_hasCheck if a variant name exists. Returns 1 or 0.
enum_name_atGet variant name at index. Returns length written, -1 if out of bounds.
enum_val_atGet variant value at index. Returns -1 if out of bounds.

Details

_enum_byte_at

fn _enum_byte_at(buf: &i8, idx: i64) -> i64

Internal byte reader.

erb

Template Engine

Functions

FunctionDescription
_erb_copy
_erb_streq
erb_vars_newCreate variable map.
erb_vars_setSet a variable in the map.
_erb_lookupInternal: lookup variable value. Returns value length, copies to out.
erb_renderRender template with variable substitution. Replaces <%= name %> with variabl…
erb_escape_htmlHTML-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) -> i64

erb_vars_new

fn erb_vars_new() -> &i64

Create variable map.

errno

Named Error Constants and Descriptions

Functions

FunctionDescription
_errno_copyInternal: copy string literal to output buffer.
_errno_byte_atInternal byte reader helper.
_errno_streqInternal: compare two strings.
errno_nameGet the name string for an errno code. Returns length written, -1 if unknown.
errno_descGet a human-readable description for an errno code.
errno_from_nameLookup errno code by name string. Returns code or -1 if unknown.

Details

_errno_copy

fn _errno_copy(dst: &i8, src: &i8, len: i64) -> i64

Internal: 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

FunctionSignatureDescription
fs_slurp(path: &i8) -> i64Read entire file into a buffer
fs_write_str(path: &i8, data: &i8, len: i64) -> i64Write string to file
fs_append_str(path: &i8, data: &i8, len: i64) -> i64Append string to file
fs_copy(src: &i8, dst: &i8) -> i64Copy a file
fs_rename(src: &i8, dst: &i8) -> i64Rename/move a file
fs_tmpname(out: &i8, suffix: i64) -> i64Generate a temp file path
buf_count_lines(buf: &i8, len: i64) -> i64Count lines in a buffer
buf_line_start(buf: &i8, len: i64, line_idx: i64) -> i64Get offset of line N
buf_line_len(buf: &i8, total_len: i64, start: i64) -> i64Get length of line at offset
path_join(dir: &i8, dir_len: i64, name: &i8, name_len: i64, out: &i8) -> i64Join directory and filename
path_basename(path: &i8, len: i64) -> i64Find basename offset in path
path_ext(path: &i8, len: i64) -> i64Find extension dot offset
cstr_length(s: &i8) -> i64Length of null-terminated string
buf_eq(a: &i8, b: &i8, n: i64) -> i64Compare n bytes for equality

Detailed API

fs_slurp

fn fs_slurp(path: &i8) -> i64

Read 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

FunctionDescription
_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_pRecursive mkdir -p. Creates all intermediate directories. Path must be null-t…
fu_rmdirRemove empty directory.
fu_rm_rfRecursive rm -rf. Removes files and directories.
fu_cpCopy a single file. Returns bytes copied or -1 on error.
fu_mvMove/rename file or directory.
fu_touchCreate empty file (or truncate existing).
fu_chmodChange file permissions.
fu_file_eqCompare 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
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) -> i64

Recursive mkdir -p. Creates all intermediate directories. Path must be null-terminated. Returns 0 on success.

find

Recursive Directory Traversal

Constants

FIND_DT_DIR = 4
FIND_DT_REG = 8

Functions

FunctionDescription
find_strlenInternal: strlen of null-terminated string.
find_copyInternal: copy bytes.
find_join_pathInternal: build full path “dir/name” into dst, return length.
find_is_dotInternal: is this “.” or “..”?
find_add_entryInternal: store a path in the result.
find_readdirInternal: read directory entries using getdents64.
find_walkRecursively walk a directory. Returns FindResult.
find_countNumber of entries found.
find_pathCopy path at index to dst. Returns length.
find_typeEntry type at index.
find_is_fileIs entry at index a regular file?
find_is_dirIs entry at index a directory?
find_filesWalk directory returning only files.

Details

find_strlen

fn find_strlen(s: &i8) -> i64

Internal: strlen of null-terminated string.

fixedpoint

Scaled Integer Arithmetic (4 Decimal Places)

Functions

FunctionDescription
_fp_byte_atInternal byte reader.
fp_from_intConvert integer to fixed-point.
fp_from_partsCreate from whole and fractional parts (frac is 0-9999).
fp_addAdd two fixed-point values.
fp_subSubtract two fixed-point values.
fp_mulMultiply two fixed-point values.
fp_divDivide two fixed-point values.
fp_wholeGet whole part.
fp_fracGet fractional part (0-9999).
fp_cmpCompare: -1, 0, or 1.
fp_absAbsolute value.
fp_sqrtSquare root of fixed-point value.
fp_to_strFormat fixed-point value to string. Returns length.
fp_from_strParse fixed-point from string. Returns scaled value.

Details

_fp_byte_at

fn _fp_byte_at(buf: &i8, idx: i64) -> i64

Internal byte reader.

fmt

Minimal String Formatting

Functions

FunctionDescription
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) -> i64

fmt_hex

fn fmt_hex(buf: &i8, val: i64) -> i64

str_len

fn str_len(s: &i8) -> i64

str_eq

fn str_eq(a: &i8, b: &i8) -> i64

str_copy

fn str_copy(dst: &i8, src: &i8, len: i64) -> i64

mem_set

fn mem_set(dst: &i8, val: i64, len: i64)

eprint_str

fn eprint_str(s: &i8, len: i64)
fn print_str(s: &i8, len: i64)

fnmatch

Filename Pattern Matching

Functions

FunctionDescription
_fnm_byte_atInternal byte reader.
_fnm_matchInternal: recursive match helper. Returns 1 if pat[pi..] matches name[ni..].
fnmatchMatch a filename against a glob pattern. Returns 1 if matches.
fnmatch_has_magicCheck if pattern contains glob special characters (*, ?, [).
fnmatch_escapeEscape glob special characters in a path. Returns length written.

Details

_fnm_byte_at

fn _fnm_byte_at(buf: &i8, idx: i64) -> i64

Internal byte reader.

_fnm_match

fn _fnm_match(pat: &i8, plen: i64, pi: i64, name: &i8, nlen: i64, ni: i64) -> i64

Internal: 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

FunctionSignatureDescription
fs_read_file(path: &i8, buf: &i8, max_bytes: i64) -> i64Read file into buffer
fs_write_file(path: &i8, data: &i8, len: i64) -> i64Write data to file (create/truncate)
fs_append_file(path: &i8, data: &i8, len: i64) -> i64Append data to file
fs_exists(path: &i8) -> i64Check if file exists
fs_unlink(path: &i8) -> i64Delete a file
fs_mkdir(path: &i8) -> i64Create a directory (mode 0755)
fs_file_size(path: &i8) -> i64Get file size in bytes

Detailed API

fs_read_file

fn fs_read_file(path: &i8, buf: &i8, max_bytes: i64) -> i64

Read 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

FunctionDescription
_ftp_byte_atInternal byte reader.
_ftp_copyInternal: copy bytes.
_ftp_crlfInternal: write CRLF.
ftp_format_userFormat USER command: “USER user\r\n”
ftp_format_passFormat PASS command: “PASS pass\r\n”
ftp_format_retrFormat RETR command: “RETR name\r\n”
ftp_format_cwdFormat CWD command: “CWD path\r\n”
ftp_format_listFormat LIST command: “LIST\r\n”
ftp_parse_replyParse FTP reply code from buffer (first 3 digits).
_ftp_parse_numInternal: parse a decimal number from buf starting at pos, until comma or ‘)’.
_ftp_skip_numInternal: find next comma or ‘)’ position from pos.
ftp_parse_pasvParse 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) -> i64

Internal byte reader.

getpass

Password Input Helpers

Functions

FunctionDescription
_getpass_byte_atInternal byte reader.
getpass_maskReplace each byte of input with ‘*’ (42). Returns len.
getpass_validate_lenCheck if len is between min and max inclusive. Returns 1 if valid.
_getpass_has_digitInternal: check if password has at least one digit.
_getpass_has_upperInternal: check if password has at least one uppercase letter.
_getpass_has_lowerInternal: check if password has at least one lowercase letter.
_getpass_has_specialInternal: check if password has at least one special character.
getpass_strengthCompute 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) -> i64

Internal byte reader.

glob

Glob Pattern Matching (fnmatch-style)

Functions

FunctionDescription
_glob_byte_atInternal byte reader.
_glob_match_classInternal: match character class [abc] or [!abc]. Returns packed value: matche…
_glob_do_matchInternal recursive match with bounded depth. pi=pattern index, si=string index.
glob_matchMatch a glob pattern against a string. Returns 1 if matches, 0 otherwise.
glob_has_magicCheck if pattern contains wildcard characters (*, ?, [).
glob_escapeEscape special glob characters in str. Wraps each *, ?, [, ] in [x]. Returns …

Details

_glob_byte_at

fn _glob_byte_at(buf: &i8, idx: i64) -> i64

Internal byte reader.

gzip

Gzip Format (Stored Blocks Only)

Functions

FunctionDescription
_gz_byte_atInternal byte reader.
_gz_crc32_byteCRC-32 table (precomputed for polynomial 0xEDB88320). We compute it on-the-fl…
gzip_crc32Compute CRC-32 of buffer.
_gz_write16Internal: write little-endian 16-bit value.
_gz_write32Internal: write little-endian 32-bit value.
_gz_read32Internal: read little-endian 32-bit value.
gzip_compressCompress data with gzip stored-block format. Returns output length.
gzip_is_gzipCheck if buffer starts with gzip magic bytes.
gzip_orig_sizeRead original size from gzip trailer (last 4 bytes).
gzip_decompressDecompress gzip stored-block data. Returns output length.

Details

_gz_byte_at

fn _gz_byte_at(buf: &i8, idx: i64) -> i64

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

OffsetFieldDescription
[0]capacityAlways a power of 2
[1]sizeNumber 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

FunctionSignatureDescription
map_new(cap: i64) -> &i64Create 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) -> i64Lookup value by key (0 if missing)
map_has(m: &i64, key: i64) -> i64Check if key exists
map_del(m: &i64, key: i64) -> i64Delete a key
map_len(m: &i64) -> i64Get entry count
map_puts(m: &i64, key: &i8, klen: i64, val: i64)String-keyed insert
map_gets(m: &i64, key: &i8, klen: i64) -> i64String-keyed lookup
map_hass(m: &i64, key: &i8, klen: i64) -> i64String-keyed existence check
hash_i64(key: i64) -> i64Hash an integer (Knuth multiplicative)
str_hash(s: &i8, len: i64) -> i64Hash a byte buffer (djb2)

Detailed API

map_new

fn map_new(cap: i64) -> &i64

Create 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

FunctionDescription
heap_pages_for
heap_new
heap_min
heap_max
heap_cmpInternal: 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_vecBuild heap from existing vec.
heap_sortHeap sort a vec ascending in-place.

Details

heap_pages_for

fn heap_pages_for(n: i64) -> i64

heap_new

fn heap_new(cap: i64, mode: i64) -> &i64

heap_min

fn heap_min(cap: i64) -> &i64

heap_max

fn heap_max(cap: i64) -> &i64

heap_cmp

fn heap_cmp(a: i64, b: i64, mode: i64) -> i64

Internal: should a come before b based on heap mode?

htmlparser

Simple HTML Tag Parser (SAX-style events)

Functions

FunctionDescription
_html_byte_atInternal byte reader.
_html_copyInternal: copy bytes from src+off to dst+doff, length n.
_html_add_evtInternal: add an event to the handle.
_html_find_gtInternal: find ‘>’ starting from pos. Returns index of ‘>’ or len if not found.
_html_find_ltInternal: find ‘<’ starting from pos. Returns index of ‘<’ or len if not found.
_html_tag_endInternal: find end of tag name (space or end). Returns index.
html_parseParse HTML buffer into events.
html_event_countReturn event count.
html_event_typeReturn event type at index (1=open, 2=close, 3=text).
html_event_tagCopy tag name at event idx to out. Return length.
html_event_textCopy text content at event idx to out. Return length.
html_strip_tagsStrip all HTML tags, return plain text length.
_html_poke_ampInternal: poke a string literal byte sequence for HTML escape.
_html_poke_lt
_html_poke_gt
_html_poke_quot
html_escapeEscape HTML special characters: & < > "

Details

_html_byte_at

fn _html_byte_at(buf: &i8, idx: i64) -> i64

Internal 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)
}

A single HTTP header as name-value pair:

httpclient

HTTP Client Helpers

Functions

FunctionDescription
_hcli_byte_atInternal byte reader.
_hcli_copyInternal: copy bytes.
_hcli_parse_intInternal: parse integer from ASCII digits at position.
_hcli_find_bodyInternal: find double CRLF. Returns offset of body start or -1.
_hcli_lowerInternal: compare bytes case-insensitively.
_hcli_eq_nocase
http_parse_responseParse an HTTP response. Returns handle.
http_resp_statusGet status code.
http_resp_headerGet a header value. Searches for “Name: value\r\n”. Returns length of value c…
http_resp_body_offsetGet body start offset.
http_resp_body_lenGet body length.
http_build_get_requestBuild a GET request. Returns total length in out.

Details

_hcli_byte_at

fn _hcli_byte_at(buf: &i8, idx: i64) -> i64

Internal byte reader.

httpserver

HTTP Server Helpers

Functions

FunctionDescription
_hsrv_byte_atInternal byte reader.
_hsrv_copyInternal: copy bytes.
_hsrv_startsInternal: check if buf at off starts with prefix of plen bytes.
_hsrv_find_bodyInternal: find double CRLF (header/body separator). Returns offset or -1.
_hsrv_write_http11Internal: write a string literal byte-by-byte. Returns new offset. Writes “HT…
_hsrv_write_crlfInternal: write CRLF. Returns new offset.
_hsrv_write_intInternal: write integer as decimal. Returns new offset. Handles values up to …
http_parse_requestParse an HTTP request. Returns handle.
http_req_methodGet method code (0=GET, 1=POST, 2=PUT, 3=DELETE, 4=PATCH, 5=HEAD).
http_req_pathCopy path to output buffer. Returns path length.
http_req_path_lenGet path length.
http_respond_okFormat a 200 OK response with body. Returns total length in out.
http_respond_404Format a 404 Not Found response. Returns total length in out.
http_status_lineFormat a status line for a given code. Returns length.

Details

_hsrv_byte_at

fn _hsrv_byte_at(buf: &i8, idx: i64) -> i64

Internal byte reader.

io

Buffered I/O and Stream Helpers

Functions

FunctionDescription
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) -> i64

io_write_stdout

fn io_write_stdout(data: &i8, len: i64) -> i64

io_write_stderr

fn io_write_stderr(data: &i8, len: i64) -> i64

io_read_line

fn io_read_line(fd: i64, buf: &i8, max_bytes: i64) -> i64

io_read_fd

fn io_read_fd(fd: i64, buf: &i8, max_bytes: i64) -> i64

io_write_fd

fn io_write_fd(fd: i64, data: &i8, len: i64) -> i64

io_flush_fd

fn io_flush_fd(fd: i64) -> i64

io_print_i64

fn io_print_i64(val: i64) -> i64

io_print_str

fn io_print_str(s: &i8, len: i64) -> i64

io_println

fn io_println(s: &i8, len: i64) -> i64

ipaddr

IP Address Parsing and Manipulation

Functions

FunctionDescription
ip_from_octetsBuild IP from 4 octets.
ip_octetGet octet n (0=first/MSB, 3=last/LSB).
ip_parseParse “a.b.c.d” string to integer.
ip_write_intInternal: write integer digits to buffer, return length.
ip_formatFormat integer IP to “a.b.c.d” string. Returns length.
ip_is_privateIs this a private (RFC 1918) address?
ip_is_loopbackIs this a loopback address?
ip_is_multicastIs this a multicast address?
ip_maskInternal: create subnet mask from prefix length.
ip_networkNetwork address for addr/prefix.
ip_broadcastBroadcast address for addr/prefix.
ip_in_subnetCheck if addr is within network/prefix.
ip_to_sockaddrWrite 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) -> i64

Build IP from 4 octets.

iter

Chainable Iterator Adapters

Functions

FunctionDescription
iter_from
iter_map
iter_filter
iter_take
iter_skip
iter_chain
iter_apply_one
iter_materialize
iter_collect
iter_sum
iter_count
iter_any
iter_all
iter_find
iter_fold
iter_foreach
iter_min
iter_max
iter_enumerate
iter_zip

Details

iter_from

fn iter_from(arr: &i64, len: i64) -> i64

iter_map

fn iter_map(f: i64) -> i64

iter_filter

fn iter_filter(f: i64) -> i64

iter_take

fn iter_take(n: i64) -> i64

iter_skip

fn iter_skip(n: i64) -> i64

iter_chain

fn iter_chain(arr2: &i64, len2: i64) -> i64

iter_apply_one

fn iter_apply_one(val: i64) -> i64

iter_materialize

fn iter_materialize(out: &i64) -> i64

iter_collect

fn iter_collect(out: &i64) -> i64

iter_sum

fn iter_sum() -> i64

iter_count

fn iter_count() -> i64

iter_any

fn iter_any(f: i64) -> i64

iter_all

fn iter_all(f: i64) -> i64

iter_find

fn iter_find(f: i64) -> i64

iter_fold

fn iter_fold(init: i64, f: i64) -> i64

iter_foreach

fn iter_foreach(f: i64) -> i64

iter_min

fn iter_min() -> i64

iter_max

fn iter_max() -> i64

iter_enumerate

fn iter_enumerate(out_idx: &i64, out_val: &i64) -> i64

iter_zip

fn iter_zip(arr2: &i64, out_a: &i64, out_b: &i64) -> i64

json

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

FunctionSignatureDescription
json_parse(src: []i8) -> Result<JsonValue, []i8>Parse a JSON string into a value
json_write(val: ref JsonValue, buf: []mut i8) -> i64Serialise to compact JSON
json_write_pretty(val: ref JsonValue, buf: []mut i8) -> i64Serialise 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

FunctionDescription
_kv_byte_atInternal byte reader.
_kv_copyInternal: copy bytes.
_kv_eqInternal: compare two byte ranges.
_kv_findInternal: find key index, returns -1 if not found.
kv_newCreate a new key-value store.
kv_putInsert or update a key-value pair. Returns 1 on update, 0 on insert.
kv_getGet value for a key. Copies to out buffer. Returns length, or -1 if not found.
kv_delDelete a key. Returns 1 if found, 0 if not found.
kv_hasCheck if key exists. Returns 1 or 0.
kv_countReturn the number of active entries.
kv_keysCopy key data into out buffer. Returns number of keys written. For each key: …
kv_key_copyCopy key bytes to output buffer given index from kv_keys.

Details

_kv_byte_at

fn _kv_byte_at(buf: &i8, idx: i64) -> i64

Internal byte reader.

linecache

Random Access to Text Lines in Files

Functions

FunctionDescription
_lc_byte_atInternal byte reader helper.
_lc_openInternal: read file via syscalls.
_lc_readInternal: read from fd.
_lc_closeInternal: close fd.
linecache_openOpen a file and index its lines. Layout: [0]=line_count, [1]=data_ptr, [2]=da…
linecache_getlineGet a line by number (1-based). Returns length, -1 if out of range.
linecache_countReturn total number of lines.
linecache_closeRelease linecache (no-op in Jda — no GC, no free).

Details

_lc_byte_at

fn _lc_byte_at(buf: &i8, idx: i64) -> i64

Internal 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

FunctionSignatureDescription
lint_init()Initialise linter state
lint_reset()Reset warning count to zero
lint_is_snake(name: &i8) -> i64Check if name is snake_case
lint_is_upper(name: &i8) -> i64Check if name is UPPER_SNAKE
lint_is_pascal(name: &i8) -> i64Check if name is PascalCase
lint_check_fn(name: &i8) -> i64Validate function name (snake_case)
lint_check_const(name: &i8) -> i64Validate constant name (UPPER_SNAKE)
lint_check_struct(name: &i8) -> i64Validate struct name (PascalCase)
lint_check_var(name: &i8) -> i64Validate 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() -> i64Return total warning count
lint_check_line_len(line: &i8, maxlen: i64) -> i64Check if line exceeds max length
lint_has_trailing_ws(line: &i8) -> i64Check 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 = 0
LOG_DEBUG = 1
LOG_INFO  = 2
LOG_WARN  = 3
LOG_ERROR = 4
LOG_FATAL = 5

Functions

FunctionDescription
log_set_levelSet minimum log level.
log_write_stderrInternal: write a string to stderr.
log_write_int_stderrInternal: write an integer to stderr.
log_write_levelInternal: write level prefix.
log_write_timestampInternal: write timestamp (seconds since epoch).
log_msgInternal: log a message at given level.
log_msg_iInternal: 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    = 0
MARSHAL_I64    = 1
MARSHAL_STR    = 2
MARSHAL_ARRAY  = 3
MARSHAL_MAP    = 4

Functions

FunctionDescription
_msh_copy
_msh_write32Internal: write 4-byte LE integer.
_msh_read32Internal: read 4-byte LE integer.
_msh_write64Internal: write 8-byte LE integer.
_msh_read64Internal: read 8-byte LE integer.
marshal_nilWrite nil. Returns new offset.
marshal_i64Write i64 value. Returns new offset.
marshal_strWrite string. Returns new offset.
marshal_array_beginWrite array header (type tag + count). Returns new offset. Caller must then w…
marshal_map_beginWrite map header (type tag + pair count). Returns new offset. Caller must the…
unmarshal_typePeek type tag at offset.
unmarshal_i64Read i64 value (skips type tag). Returns the value.
unmarshal_str_lenRead string length at offset.
unmarshal_strRead string. Copies to out. Returns new offset (past string).
unmarshal_array_countGet array count at offset.
unmarshal_skipSkip 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) -> i64

Internal: 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

FunctionSignatureDescription
math_abs(x: i64) -> i64Absolute value
math_min(a: i64, b: i64) -> i64Minimum of two values
math_max(a: i64, b: i64) -> i64Maximum of two values
math_clamp(x: i64, lo: i64, hi: i64) -> i64Clamp to range [lo, hi]
math_gcd(a: i64, b: i64) -> i64Greatest common divisor
math_lcm(a: i64, b: i64) -> i64Least common multiple
math_pow(base: i64, exp: i64) -> i64Integer exponentiation
math_isqrt(n: i64) -> i64Integer square root (floor)
math_log2(n: i64) -> i64Floor of log base 2
math_factorial(n: i64) -> i64Factorial (iterative)
math_fib(n: i64) -> i64Fibonacci number (iterative)
math_is_prime(n: i64) -> i64Primality test
math_next_pow2(n: i64) -> i64Smallest power of 2 >= n
math_divmod(a: i64, b: i64, quot_ptr: &i64, rem_ptr: &i64) -> i64Quotient and remainder
math_rand_seed(seed: i64) -> i64Seed the RNG
math_rand() -> i64Generate pseudo-random i64
math_rand_range(lo: i64, hi: i64) -> i64Random in range [lo, hi)

Detailed API

math_abs

fn math_abs(x: i64) -> i64

Return the absolute value of x.

matrix

Integer Matrix Operations

Functions

FunctionDescription
mat_pages_for
mat_newCreate 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) -> i64

mat_new

fn mat_new(rows: i64, cols: i64) -> &i64

Create a rows x cols matrix initialized to 0.

mat_rows

fn mat_rows(m: &i64) -> i64

mat_cols

fn mat_cols(m: &i64) -> i64

mat_get

fn mat_get(m: &i64, r: i64, c: i64) -> i64

mat_set

fn mat_set(m: &i64, r: i64, c: i64, val: i64)

mat_add

fn mat_add(a: &i64, b: &i64) -> &i64

mat_sub

fn mat_sub(a: &i64, b: &i64) -> &i64

mat_mul

fn mat_mul(a: &i64, b: &i64) -> &i64

mat_scale

fn mat_scale(m: &i64, s: i64) -> &i64

mat_transpose

fn mat_transpose(m: &i64) -> &i64

mat_identity

fn mat_identity(n: i64) -> &i64

mat_trace

fn mat_trace(m: &i64) -> i64

mat_eq

fn mat_eq(a: &i64, b: &i64) -> i64

mat_copy

fn mat_copy(m: &i64) -> &i64

mat_fill

fn mat_fill(m: &i64, val: i64)

metrics

// jda::ml::metrics — Model Evaluation Metrics

Functions

FunctionDescription
true_positives
true_negatives
false_positives
false_negatives
accuracy
precision
recall
f1_score
f_beta
specificity
matthews_corrcoef
confusion_matrix
cm_precision
cm_recall
f1_macro
f1_weighted
f1_micro
roc_auc
average_precision
mae
mse
rmse
r_squared
mape
huber_loss
median_absolute_error
hamming_loss
subset_accuracy
print_classification_report
print_confusion_matrix

Details

true_positives

fn true_positives(pred: ref []i64, true: ref []i64) -> i64

true_negatives

fn true_negatives(pred: ref []i64, true: ref []i64) -> i64

false_positives

fn false_positives(pred: ref []i64, true: ref []i64) -> i64

false_negatives

fn false_negatives(pred: ref []i64, true: ref []i64) -> i64

accuracy

fn accuracy(pred: ref []i64, true: ref []i64) -> f64

precision

fn precision(pred: ref []i64, true: ref []i64) -> f64

recall

fn recall(pred: ref []i64, true: ref []i64) -> f64

f1_score

fn f1_score(pred: ref []i64, true: ref []i64) -> f64

f_beta

fn f_beta(pred: ref []i64, true: ref []i64, beta: f64) -> f64

specificity

fn specificity(pred: ref []i64, true: ref []i64) -> f64

matthews_corrcoef

fn matthews_corrcoef(pred: ref []i64, true: ref []i64) -> f64

confusion_matrix

fn confusion_matrix(pred: ref []i64, true: ref []i64,

cm_precision

fn cm_precision(cm: ref []i64, c: i64, n_classes: i64) -> f64

cm_recall

fn cm_recall(cm: ref []i64, c: i64, n_classes: i64) -> f64

f1_macro

fn f1_macro(pred: ref []i64, true: ref []i64, n_classes: i64) -> f64

f1_weighted

fn f1_weighted(pred: ref []i64, true: ref []i64, n_classes: i64) -> f64

f1_micro

fn f1_micro(pred: ref []i64, true: ref []i64, n_classes: i64) -> f64

roc_auc

fn roc_auc(scores: ref []f32, true: ref []i64) -> f64

average_precision

fn average_precision(scores: ref []f32, true: ref []i64) -> f64

mae

fn mae(pred: ref []f32, true: ref []f32) -> f64

mse

fn mse(pred: ref []f32, true: ref []f32) -> f64

rmse

fn rmse(pred: ref []f32, true: ref []f32) -> f64

r_squared

fn r_squared(pred: ref []f32, true: ref []f32) -> f64

mape

fn mape(pred: ref []f32, true: ref []f32) -> f64

huber_loss

fn huber_loss(pred: ref []f32, true: ref []f32, delta: f32) -> f64

median_absolute_error

fn median_absolute_error(pred: ref []f32, true: ref []f32) -> f64

hamming_loss

fn hamming_loss(pred: ref [][]i64, true: ref [][]i64) -> f64

subset_accuracy

fn subset_accuracy(pred: ref [][]i64, true: ref [][]i64) -> f64
fn print_classification_report(pred: ref []i64, true: ref []i64,
fn print_confusion_matrix(cm: ref []i64, n_classes: i64,

mimetypes

File Extension to MIME Type Mapping

Functions

FunctionDescription
_mime_byte_atInternal byte reader.
_mime_copyInternal: copy literal to output.
_mime_eqInternal: compare strings.
mime_typeGet MIME type for file extension (without dot). Returns length, -1 if unknown.
mime_guessGuess MIME type from filename/path. Extracts extension after last dot.
mime_is_textCheck if extension maps to a text/* type.

Details

_mime_byte_at

fn _mime_byte_at(buf: &i8, idx: i64) -> i64

Internal byte reader.

_mime_copy

fn _mime_copy(dst: &i8, src: &i8, len: i64) -> i64

Internal: copy literal to output.

mmap

Memory-Mapped Region Utilities

Functions

FunctionDescription
_mmap_byte_atInternal byte reader.
mmap_region_newCreate a new memory region of at least size bytes.
mmap_read_byteRead a byte at the given offset.
mmap_write_byteWrite a byte at the given offset.
mmap_read_i64Read an i64 at the given byte offset (must be 8-byte aligned).
mmap_write_i64Write an i64 at the given byte offset (must be 8-byte aligned).
mmap_fillFill len bytes starting at off with value val.
mmap_region_sizeReturn the size of the region.

Details

_mmap_byte_at

fn _mmap_byte_at(buf: &i8, idx: i64) -> i64

Internal byte reader.

mutex

Mutex and Condition Variable

Constants

FUTEX_WAIT = 0
FUTEX_WAKE = 1

Functions

FunctionDescription
_mtx_futex_waitInternal: futex syscall wrapper.
_mtx_futex_wake
mutex_newCreate new mutex (unlocked).
mutex_lockLock mutex. Blocks if already locked.
mutex_unlockUnlock mutex.
mutex_trylockNon-blocking try-lock. Returns 1 if acquired, 0 if not.
condvar_newCreate condition variable.
condvar_waitWait on condition variable. Must hold mutex m. Releases mutex, waits, re-acqu…
condvar_signalWake one waiter.
condvar_broadcastWake all waiters.
spinlock_newCreate simple spinlock.
spinlock_lockSpinlock: busy-wait until acquired.
spinlock_unlockSpinlock: release.

Details

_mtx_futex_wait

fn _mtx_futex_wait(addr: &i64, expected: i64) -> i64

Internal: futex syscall wrapper.

netrc

.netrc File Parser

Functions

FunctionDescription
_netrc_byte_atInternal byte reader.
_netrc_copyInternal: copy bytes from src+off to dst, length len.
_netrc_eqInternal: compare bytes.
_netrc_is_wsInternal: check if ch is whitespace (space=32, tab=9, newline=10, cr=13).
_netrc_skip_wsInternal: skip whitespace, return new position.
_netrc_token_endInternal: read a token starting at pos, return end position. Token is delimit…
_netrc_is_machineInternal: check if token at buf[off..off+tlen] matches “machine” (7 chars).
_netrc_is_defaultInternal: check if token is “default” (7 chars).
_netrc_is_loginInternal: check if token is “login” (5 chars).
_netrc_is_passwordInternal: check if token is “password” (8 chars).
netrc_parseParse .netrc data. Returns handle.
netrc_countNumber of entries.
netrc_lookupLook up entry by host. Returns index or -1.
netrc_loginCopy login at index to out. Returns length.
netrc_passwordCopy password at index to out. Returns length.

Details

_netrc_byte_at

fn _netrc_byte_at(buf: &i8, idx: i64) -> i64

Internal byte reader.

nn

Functions

FunctionDescription
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) -> i64

backward_weights

fn backward_weights(x: i64, w: i64, grad_out: i64, grad_w: i64) -> i64

backward_bias

fn backward_bias(grad_out: i64, grad_b: i64, batch: i64, out_f: i64) -> i64

backward_input

fn backward_input(w: i64, grad_out: i64, grad_in: i64) -> i64

relu_forward

fn relu_forward(a: i64, out: i64) -> i64

relu_backward

fn relu_backward(pre_relu: i64, grad_out: i64, grad_in: i64) -> i64

mse_loss

fn mse_loss(pred: i64, target: i64) -> i64

mse_backward

fn mse_backward(pred: i64, target: i64, grad_out: i64) -> i64

sgd_step

fn sgd_step(params: i64, grads: i64, lr: i64) -> i64

zero_tensor

fn zero_tensor(t: i64) -> i64

observer

Publish/Subscribe Event Pattern

Functions

FunctionDescription
obs_newCreate an event bus.
obs_find_topicInternal: find or create slot for topic.
obs_subscribeSubscribe a handler function pointer to a topic. Handler signature: fn(data: …
obs_emit_iEmit an event to all subscribers of a topic. Calls each handler with the data…
obs_unsubscribe_allRemove all handlers for a topic.
obs_subscriber_countNumber of subscribers for a topic.

Details

obs_new

fn obs_new(max_topics: i64) -> &i64

Create an event bus.

open3

Capture Child Process I/O

Functions

FunctionDescription
_o3_pipe
_o3_fork
_o3_dup2
_o3_close
_o3_execve
_o3_exit
_o3_read
_o3_write
_o3_wait4
open3_popenSpawn command with piped stdin/stdout/stderr. cmd = path to executable (null-…
open3_pidGet child PID.
open3_writeWrite data to child’s stdin.
open3_readRead from child’s stdout.
open3_read_errRead from child’s stderr.
open3_close_stdinClose child’s stdin (signals EOF to child).
open3_waitWait for child to exit. Returns exit code (0-255) or -1 on error.
open3_capture2Run command and capture stdout. Returns bytes read.
open3_capture3Run 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) -> i64

open3_popen

fn open3_popen(cmd: &i8, argv: &i64) -> &i64

Spawn 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

FunctionDescription
op_addAddition.
op_subSubtraction.
op_mulMultiplication.
op_divDivision (integer). Returns 0 if b is 0.
op_modModulo. Returns 0 if b is 0.
op_negNegation.
op_absAbsolute value.
op_minMinimum.
op_maxMaximum.
op_eqEquality: 1 if a == b, 0 otherwise.
op_neNot equal: 1 if a != b, 0 otherwise.
op_ltLess than: 1 if a < b.
op_leLess than or equal: 1 if a <= b.
op_gtGreater than: 1 if a > b.
op_geGreater than or equal: 1 if a >= b.
op_andBitwise AND.
op_orBitwise OR.
op_xorBitwise XOR.
op_notBitwise NOT.
op_shlLeft shift.
op_shrRight shift.
op_clampClamp value to range [lo, hi].
op_signSign: -1, 0, or 1.

Details

op_add

fn op_add(a: i64, b: i64) -> i64

Addition.

optparse

Rich CLI Option Parser

Functions

FunctionDescription
_opt_copy
_opt_streq
_opt_strlen
opt_newCreate new option parser with max options.
opt_addAdd an option. short=0 for no short flag. has_val=1 if takes value.
_opt_find_longInternal: find option by long name. Returns index or -1.
_opt_find_shortInternal: find option by short flag. Returns index or -1.
opt_parseParse command-line arguments. argc/argv from os_argv(). Returns 0 on success,…
opt_getGet option value. Copies value to out, returns length. 0 if not found.
opt_hasCheck if option was provided. Returns 1 or 0.
opt_positionalGet positional argument at index. Copies to out, returns length.
opt_nposNumber of positional arguments found.
opt_helpPrint 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) -> i64

opt_new

fn opt_new(max: i64) -> &i64

Create new option parser with max options.

os

Operating System Interface

Functions

FunctionDescription
os_getenvGet environment variable value. Scans /proc/self/environ for name=value pairs.
os_getcwdGet current working directory.
os_chdirChange current directory.
os_getpidGet current process ID.
os_getppidGet parent process ID.
os_getuidGet user ID.
os_exitExit the process.
os_forkFork the current process.
os_execExecute a program (replaces current process image).
os_waitWait for child process.
os_killSend signal to process.
os_sleep_msSleep for given milliseconds.
os_hostnameGet hostname.
os_unameGet system info (uname).

Details

os_getenv

fn os_getenv(name: &i8, name_len: i64, buf: &i8, max: i64) -> i64

Get environment variable value. Scans /proc/self/environ for name=value pairs.

pack

Binary Pack/Unpack

Functions

FunctionDescription
pack_i8Write 1 byte. Returns off+1.
pack_i16_leWrite 2 bytes little-endian. Returns off+2.
pack_i16_beWrite 2 bytes big-endian. Returns off+2.
pack_i32_leWrite 4 bytes little-endian. Returns off+4.
pack_i32_beWrite 4 bytes big-endian. Returns off+4.
pack_i64_leWrite 8 bytes little-endian. Returns off+8.
pack_i64_beWrite 8 bytes big-endian. Returns off+8.
pack_strWrite length-prefixed string (4-byte LE length + raw bytes). Returns new offset.
pack_rawWrite raw bytes (no length prefix). Returns new offset.
unpack_i8Read 1 unsigned byte.
unpack_i16_leRead 2 bytes little-endian.
unpack_i16_beRead 2 bytes big-endian.
unpack_i32_leRead 4 bytes little-endian.
unpack_i32_beRead 4 bytes big-endian.
unpack_i64_leRead 8 bytes little-endian.
unpack_i64_beRead 8 bytes big-endian.
unpack_strRead length-prefixed string. Reads 4-byte LE length, then copies bytes to out…
unpack_str_lenGet string length from length-prefixed string at offset.

Details

pack_i8

fn pack_i8(buf: &i8, off: i64, val: i64) -> i64

Write 1 byte. Returns off+1.

pathname

Path Manipulation Utilities

Functions

FunctionDescription
pn_copyInternal: copy bytes from src to dst.
pn_dirnameGet directory portion of path. Returns length written to out. “/usr/bin/gcc” …
pn_extnameGet file extension including dot. Returns length written to out. “foo.tar.gz”…
pn_is_absoluteCheck if path is absolute (starts with /).
pn_normalizeNormalize path: resolve . and .. components, collapse multiple slashes. Retur…
pn_split_extSplit path into stem and extension. Returns stem length. “archive.tar.gz” -> …
pn_join3Join 3 path segments: a/b/c. Returns length written to out.
pn_has_extCheck 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

FunctionDescription
_platform_unameInternal: uname syscall wrapper (syscall 63). struct utsname: 5 fields of 65 …
_plat_byte_atInternal byte reader helper.
_plat_copy_fieldInternal: copy string from utsname field to output.
_plat_copy_litInternal: copy literal bytes.
platform_systemGet OS name. Returns length written.
platform_releaseGet kernel release string. Returns length written.
platform_machineGet machine architecture. Returns length written.
platform_nodeGet hostname. Returns length written.
platform_infoGet combined platform info: “Linux x86_64 ”. Returns length.
platform_is_x86_64Check if platform is x86_64. Always returns 1 (Jda only targets x86-64).
platform_page_sizeGet system page size. Always 4096 on Linux x86-64.

Details

_platform_uname

fn _platform_uname(buf: &i8) -> i64

Internal: 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

FunctionDescription
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

fn print_repeat(ch: &i8, n: i64) -> i64

plot_bar

fn plot_bar(val: i64, max_val: i64, width: i64) -> i64

plot_bars

fn plot_bars(arr: &i64, len: i64, width: i64) -> i64

plot_line

fn plot_line(arr: &i64, len: i64, height: i64) -> i64

hist_bin

fn hist_bin(arr: &i64, len: i64, nbins: i64, lo: i64, hi: i64, bins: &i64) -> i64

plot_hist

fn plot_hist(arr: &i64, len: i64, nbins: i64, lo: i64, hi: i64, width: i64, bins: &i64) -> i64

scatter_points

fn scatter_points(xs: &i64, ys: &i64, len: i64, grid: &i64, dim: i64) -> i64

scatter_print

fn scatter_print(grid: &i64, width: i64, height: i64) -> i64

plot_heatmap

fn plot_heatmap(data: &i64, rows: i64, cols: i64) -> i64

stat_min

fn stat_min(arr: &i64, len: i64) -> i64

stat_max

fn stat_max(arr: &i64, len: i64) -> i64

stat_sum

fn stat_sum(arr: &i64, len: i64) -> i64

stat_mean

fn stat_mean(arr: &i64, len: i64) -> i64

plot_summary

fn plot_summary(arr: &i64, len: i64) -> i64

pp

Pretty Printer

Functions

FunctionDescription
pp_nlPrint newline.
pp_sepPrint separator.
pp_indentPrint indentation (2 spaces per level).
pp_print_intInternal: print integer to stdout using write buf.
pp_intPrint an integer.
pp_strPrint a string with double quotes.
pp_hexPrint integer as hex.
pp_binPrint integer as binary.
pp_vecPretty-print a vec: [1, 2, 3]
pp_vec_namedPretty-print a named vec: name = [1, 2, 3]
pp_matPretty-print a matrix with alignment.
pp_bytesHex dump of raw bytes (16 per line).
pp_labelPrint a label: “name: "
pp_kv_intPrint “key = value\n”
pp_kv_hexPrint “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

FunctionDescription
set_byte
get_byte
fmt_i64
fmt_hex
str_len
str_eq
str_copy
mem_set
eprint_str
print_str
print_int
fs_read_file
fs_write_file
fs_append_file
fs_exists
fs_unlink
fs_mkdir
fs_file_size
time_now_ns
time_now_us
time_now_ms
time_sleep_ns
time_sleep_ms
time_elapsed_ns
time_unix_secs

Details

set_byte

fn set_byte(buf: &i8, off: i64, val: i64)

get_byte

fn get_byte(buf: &i8, off: i64) -> i64

fmt_i64

fn fmt_i64(buf: &i8, val: i64) -> i64

fmt_hex

fn fmt_hex(buf: &i8, val: i64) -> i64

str_len

fn str_len(s: &i8) -> i64

str_eq

fn str_eq(a: &i8, b: &i8) -> i64

str_copy

fn str_copy(dst: &i8, src: &i8, len: i64) -> i64

mem_set

fn mem_set(dst: &i8, val: i64, len: i64)

eprint_str

fn eprint_str(s: &i8, len: i64)
fn print_str(s: &i8, len: i64)
fn print_int(val: i64)

fs_read_file

fn fs_read_file(path: &i8, buf: &i8, max_bytes: i64) -> i64

fs_write_file

fn fs_write_file(path: &i8, data: &i8, len: i64) -> i64

fs_append_file

fn fs_append_file(path: &i8, data: &i8, len: i64) -> i64

fs_exists

fn fs_exists(path: &i8) -> i64
fn fs_unlink(path: &i8) -> i64

fs_mkdir

fn fs_mkdir(path: &i8) -> i64

fs_file_size

fn fs_file_size(path: &i8) -> i64

time_now_ns

fn time_now_ns() -> i64

time_now_us

fn time_now_us() -> i64

time_now_ms

fn time_now_ms() -> i64

time_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) -> i64

time_unix_secs

fn time_unix_secs() -> i64

process

// jda::process — Process management

Constants

SYS_READ      =  0
SYS_WRITE     =  1
SYS_OPEN      =  2
SYS_CLOSE     =  3
SYS_STAT      =  4
SYS_MMAP      =  9
SYS_RT_SIGACTION   = 13
SYS_RT_SIGPROCMASK = 14
SYS_RT_SIGRETURN   = 15
SYS_IOCTL     = 16
SYS_PIPE      = 22
SYS_DUP       = 32
SYS_DUP2      = 33
SYS_GETPID    = 39
SYS_CLONE     = 56
SYS_FORK      = 57
SYS_VFORK     = 58
SYS_EXECVE    = 59
SYS_EXIT      = 60
SYS_WAIT4     = 61
SYS_KILL      = 62
SYS_GETPPID   = 110
SYS_GETUID    = 102
SYS_GETGID    = 104
SYS_GETEUID   = 107
SYS_GETEGID   = 108
SYS_SIGALTSTACK= 131
SYS_PRCTL     = 157
SYS_SETPGID   = 109
SYS_GETPGID   = 121
SYS_SETSID    = 112
SYS_ENVIRON   = -1   // accessed via auxv, not a syscall
SIGHUP    =  1    // hangup
SIGINT    =  2    // interrupt (Ctrl-C)
SIGQUIT   =  3    // quit
SIGILL    =  4    // illegal instruction
SIGTRAP   =  5    // trace / breakpoint
SIGABRT   =  6    // abort
SIGBUS    =  7    // bus error
SIGFPE    =  8    // floating-point exception
SIGKILL   =  9    // kill (cannot be caught)
SIGUSR1   = 10    // user-defined 1
SIGSEGV   = 11    // segfault
SIGUSR2   = 12    // user-defined 2
SIGPIPE   = 13    // broken pipe
SIGALRM   = 14    // alarm clock
SIGTERM   = 15    // termination
SIGCHLD   = 17    // child stopped or exited
SIGCONT   = 18    // continue
SIGSTOP   = 19    // stop (cannot be caught)
SIGTSTP   = 20    // terminal stop (Ctrl-Z)
SIGTTIN   = 21    // background read from tty
SIGTTOU   = 22    // background write to tty
SIGURG    = 23    // urgent data on socket
SIGWINCH  = 28    // terminal resize
SIG_DFL   = 0     // default action
SIG_IGN   = 1     // ignore signal
WNOHANG   = 1     // non-blocking waitpid
PR_SET_NAME   = 15
PR_GET_NAME   = 16
PR_SET_DUMPABLE = 4
PR_GET_DUMPABLE = 3
PR_SET_PDEATHSIG = 1   // signal sent to child when parent dies

Structs

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

FunctionDescription
wifexited
wexitstatus
wifsignaled
wtermsig
wifstopped
wstopsig
getpid
getppid
getuid
getgid
exit
abort
fork
execve
exec_argv
waitpid
wait_any
run
pipe2
dup2
close_fd
spawn
spawn_output
kill
killpg
raise_sig
signal
signal_ignore
signal_default
signal_block
signal_unblock
environ
process_init
getenv
setenv
unsetenv
proc_info
pipe_open
pipe_write
pipe_read
pipe_close_write
pipe_close_read
daemonize
set_process_name
get_process_name
set_pdeathsig
disable_coredump

Details

wifexited

fn wifexited(status: i32) -> i32  

wexitstatus

fn wexitstatus(status: i32) -> i32

wifsignaled

fn wifsignaled(status: i32) -> i32

wtermsig

fn wtermsig(status: i32) -> i32   

wifstopped

fn wifstopped(status: i32) -> i32 

wstopsig

fn wstopsig(status: i32) -> i32   

getpid

fn getpid() -> i32

getppid

fn getppid() -> i32

getuid

fn getuid() -> i32

getgid

fn getgid() -> i32

exit

fn exit(code: i32)

abort

fn abort()

fork

fn fork() -> i32

execve

fn execve(path: &i8, argv: &&i8, envp: &&i8) -> i32

exec_argv

fn exec_argv(path: &i8, argv: &&i8) -> i32

waitpid

fn waitpid(pid: i32, status: &i32, options: i32) -> i32

wait_any

fn wait_any(opts: i32) -> WaitResult

run

fn run(path: &i8, argv: &&i8) -> i32

pipe2

fn pipe2(fds: &i32) -> i32

dup2

fn dup2(old_fd: i32, new_fd: i32) -> i32

close_fd

fn close_fd(fd: i32)

spawn

fn spawn(path: &i8, argv: &&i8, opts: &SpawnOpts) -> ChildProc

spawn_output

fn spawn_output(path: &i8, argv: &&i8, out: &i8, cap: i64) -> i64

kill

fn kill(pid: i32, sig: i32) -> i32

killpg

fn killpg(pgid: i32, sig: i32) -> i32

raise_sig

fn raise_sig(sig: i32)

signal

fn signal(sig: i32, handler: i64) -> i32

signal_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() -> &&i8

process_init

fn process_init(argc: i64, argv: &&i8)

getenv

fn getenv(name: &i8) -> &i8

setenv

fn setenv(name: &i8, value: &i8, overwrite: i32) -> i32

unsetenv

fn unsetenv(name: &i8) -> i32

proc_info

fn proc_info() -> ProcInfo

pipe_open

fn pipe_open() -> Pipe

pipe_write

fn pipe_write(p: &Pipe, data: &i8, len: i64) -> i64

pipe_read

fn pipe_read(p: &Pipe, buf: &i8, cap: i64) -> i64

pipe_close_write

fn pipe_close_write(p: &Pipe)

pipe_close_read

fn pipe_close_read(p: &Pipe) 

daemonize

fn daemonize() -> i32

set_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

FunctionSignatureDescription
prof_init()Initialise profiler state
prof_enable()Enable profiling
prof_disable()Disable profiling
prof_enabled() -> i64Check 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) -> i64Return call count for a slot
prof_total_ns(slot: i64) -> i64Return total nanoseconds for a slot
prof_avg_ns(slot: i64) -> i64Return average nanoseconds per call
prof_name(slot: i64) -> &i8Return name of a slot
prof_slot_count() -> i64Return 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

FunctionDescription
ptx_has_gpu
ptx_vecadd
ptx_matmul
ptx_scale
ptx_dot
ptx_relu

Details

ptx_has_gpu

fn ptx_has_gpu() -> i64

ptx_vecadd

fn ptx_vecadd(a: i64, b: i64, c: i64, len: i64) -> i64

ptx_matmul

fn ptx_matmul(a: i64, b: i64, c: i64, M: i64, N: i64, K: i64) -> i64

ptx_scale

fn ptx_scale(a: i64, c: i64, scalar: i64, len: i64) -> i64

ptx_dot

fn ptx_dot(a: i64, b: i64, len: i64) -> i64

ptx_relu

fn ptx_relu(a: i64, c: i64, len: i64) -> i64

queue

Queue, Stack, and Priority Queue

Functions

FunctionDescription
queue_pages_for
queue_new
queue_grow
queue_push
queue_pop
queue_peek
queue_len
queue_empty
stack_new
stack_push
stack_pop
stack_peek
stack_len
stack_empty
pq_new
pq_parent
pq_left
pq_right
pq_sift_up
pq_sift_down
pq_push
pq_pop
pq_peek
pq_len
pq_empty

Details

queue_pages_for

fn queue_pages_for(n: i64) -> i64

queue_new

fn queue_new() -> &i64

queue_grow

fn queue_grow(q: &i64)

queue_push

fn queue_push(q: &i64, val: i64)

queue_pop

fn queue_pop(q: &i64) -> i64

queue_peek

fn queue_peek(q: &i64) -> i64

queue_len

fn queue_len(q: &i64) -> i64

queue_empty

fn queue_empty(q: &i64) -> i64

stack_new

fn stack_new() -> &i64

stack_push

fn stack_push(s: &i64, val: i64)

stack_pop

fn stack_pop(s: &i64) -> i64

stack_peek

fn stack_peek(s: &i64) -> i64

stack_len

fn stack_len(s: &i64) -> i64

stack_empty

fn stack_empty(s: &i64) -> i64

pq_new

fn pq_new() -> &i64

pq_parent

fn pq_parent(i: i64) -> i64

pq_left

fn pq_left(i: i64) -> i64

pq_right

fn pq_right(i: i64) -> i64

pq_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) -> i64

pq_peek

fn pq_peek(pq: &i64) -> i64

pq_len

fn pq_len(pq: &i64) -> i64

pq_empty

fn pq_empty(pq: &i64) -> i64

range

Range Type

Functions

FunctionDescription
range_newCreate exclusive range [start, end).
range_inclusiveCreate inclusive range [start, end].
range_stepCreate range with custom step.
range_containsCheck if value is in range.
range_sizeNumber of elements in range.
range_eachFill buffer with range values. Returns count.
range_to_vecCreate vec from range values. Returns vec pointer (&i64).
range_sumSum all elements in range.
range_firstFirst element of range.
range_lastLast element of range.

Details

range_new

fn range_new(start: i64, end_val: i64) -> &i64

Create exclusive range [start, end).

rational

Rational Number Arithmetic

Functions

FunctionDescription
_rat_gcdInternal: GCD (Euclidean algorithm).
_rat_absInternal: absolute value.
rat_newCreate rational number, auto-simplified.
rat_addAdd: a/b + c/d = (ad + bc) / bd.
rat_subSubtract: a/b - c/d = (ad - bc) / bd.
rat_mulMultiply: (a/b) * (c/d) = ac / bd.
rat_divDivide: (a/b) / (c/d) = ad / bc.
rat_cmpCompare: returns -1, 0, or 1.
rat_eqEquality check.
rat_to_i64Truncated integer value (num / den).
rat_numNumerator.
rat_denDenominator.
rat_is_integerCheck if integer (den == 1).
rat_absAbsolute value.
rat_negateNegate.
_rat_write_intInternal: write integer to buffer.
rat_to_strFormat as “num/den” string. Returns length.

Details

_rat_gcd

fn _rat_gcd(a: i64, b: i64) -> i64

Internal: GCD (Euclidean algorithm).

regex

Backtracking regex engine written in pure Jda. No external dependencies.

Supported Syntax

PatternDescription
.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
\dDigit [0-9]
\wWord character [a-zA-Z0-9_]
\sWhitespace [ \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

FunctionSignatureDescription
regex_match(pat: &i8, pl: i64, text: &i8, tl: i64) -> i64Full match (entire text)
regex_search(pat: &i8, pl: i64, text: &i8, tl: i64) -> i64Find first match position
regex_count(pat: &i8, pl: i64, text: &i8, tl: i64) -> i64Count non-overlapping matches
re_match_at(pat: &i8, pl: i64, text: &i8, tp: i64, tl: i64) -> i64Match at specific position

Detailed API

regex_match

fn regex_match(pat: &i8, pl: i64, text: &i8, tl: i64) -> i64

Test whether the pattern matches the entire text string. The match must consume all bytes.

ring

Ring Buffer (Circular Buffer)

Functions

FunctionDescription
ring_pages_for
ring_newCreate ring buffer with given capacity.
ring_pushPush a value. If full, overwrites oldest and returns evicted value. Returns 0…
ring_popPop oldest value. Returns 0 if empty.
ring_peekPeek at oldest without removing.
ring_peek_newestPeek at newest without removing.
ring_len
ring_cap
ring_full
ring_empty
ring_getGet element at logical index (0 = oldest).
ring_clearClear the ring buffer.
ring_sumSum of all elements.
ring_avgInteger average (0 if empty).

Details

ring_pages_for

fn ring_pages_for(n: i64) -> i64

ring_new

fn ring_new(cap: i64) -> &i64

Create ring buffer with given capacity.

rocm

Functions

FunctionDescription
rocm_has_gpu
rocm_add
rocm_mm
rocm_scale
rocm_dot
rocm_relu

Details

rocm_has_gpu

fn rocm_has_gpu() -> i64

rocm_add

fn rocm_add(a: i64, b: i64, c: i64, len: i64) -> i64

rocm_mm

fn rocm_mm(a: i64, b: i64, c: i64, M: i64, N: i64, K: i64) -> i64

rocm_scale

fn rocm_scale(a: i64, c: i64, scalar: i64, len: i64) -> i64

rocm_dot

fn rocm_dot(a: i64, b: i64, len: i64) -> i64

rocm_relu

fn rocm_relu(a: i64, c: i64, len: i64) -> i64

sched

Simple Task Scheduler (Min-Heap)

Functions

FunctionDescription
sched_newCreate a new scheduler.
_sched_swapInternal: swap two entries in the heap.
_sched_sift_upInternal: sift up from index i.
_sched_sift_downInternal: sift down from index i, with count elements.
sched_enterAdd a task to the scheduler.
sched_cancelCancel a task by id. Returns 1 if found and removed.
sched_nextReturn id of the next (earliest) task, or -1 if empty.
sched_next_timeReturn time of the next (earliest) task.
_sched_popInternal: remove the root element from the heap.
sched_runRun the next task if its time <= now. Returns task id or -1.
sched_emptyReturn 1 if the scheduler has no tasks.
sched_countReturn the number of tasks.

Details

sched_new

fn sched_new() -> &i64

Create a new scheduler.

securerandom

Cryptographic Random Number Generation

Functions

FunctionDescription
_srand_getrandomInternal: getrandom syscall (318 on x86-64).
srand_bytesFill buffer with n random bytes. Returns n on success, -1 on error.
_srand_hex_digitInternal: hex digit.
srand_hexGenerate hex-encoded random bytes. Writes 2*nbytes chars to out. Returns numb…
srand_base64Base64 encode random bytes. Returns chars written.
srand_uuid4Generate UUID v4 string (36 chars: xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx).
srand_rangeRandom integer in range [lo, hi). Uses getrandom for uniform distribution.

Details

_srand_getrandom

fn _srand_getrandom(buf: &i8, n: i64) -> i64

Internal: getrandom syscall (318 on x86-64).

set

Hash Set (Set)

Functions

FunctionDescription
set_pages_for
set_newCreate a new set with given capacity (rounded up to power of 2, min 16).
set_hashInternal: hash function for i64.
set_rehashInternal: rehash when load factor > 0.7.
set_addInsert a value into the set.
set_hasCheck if value is in the set.
set_delRemove a value from the set. Returns 1 if found, 0 otherwise.
set_lenNumber of elements.
set_clearRemove all elements.
set_unionUnion: returns new set containing all elements from a and b.
set_intersectIntersection: returns new set of elements in both a and b.
set_diffDifference: returns new set of elements in a but not in b.
set_subsetSubset: returns 1 if all elements of a are in b.
set_eqEquality: same elements in both sets.
set_to_vecConvert set to vec (unordered).

Details

set_pages_for

fn set_pages_for(n: i64) -> i64

set_new

fn set_new(cap: i64) -> &i64

Create a new set with given capacity (rounded up to power of 2, min 16).

shell

Shell Word Splitting and Escaping

Functions

FunctionDescription
shell_needs_escapeInternal: does this byte need escaping in a shell context?
shell_escapeEscape a string for safe shell use with backslashes. Returns output length.
shell_quoteSingle-quote a string (strongest quoting). Handles embedded single quotes wit…
shell_joinJoin multiple words into a single shell-safe string with spaces. words: array…
shell_splitSplit a shell string into words respecting quotes. Stores offsets and lengths…

Details

shell_needs_escape

fn shell_needs_escape(ch: i64) -> i64

Internal: does this byte need escaping in a shell context?

signal

Signal Handling

Constants

SIG_HUP    =  1
SIG_INT    =  2
SIG_QUIT   =  3
SIG_ILL    =  4
SIG_TRAP   =  5
SIG_ABRT   =  6
SIG_BUS    =  7
SIG_FPE    =  8
SIG_KILL   =  9
SIG_USR1   = 10
SIG_SEGV   = 11
SIG_USR2   = 12
SIG_PIPE   = 13
SIG_ALRM   = 14
SIG_TERM   = 15
SIG_CHLD   = 17
SIG_CONT   = 18
SIG_STOP   = 19
SIG_TSTP   = 20
SIG_WINCH  = 28
SIG_DFL_VAL = 0
SIG_IGN_VAL = 1
SA_RESTORER = 67108864

Functions

FunctionDescription
_sig_rt_sigaction
_sig_getpid
_sig_kill_raw
_sig_rt_sigprocmask
_sig_rt_sigpending
sig_actionSet signal handler. handler = function pointer. Returns 0 on success, -1 on e…
sig_ignoreIgnore a signal.
sig_defaultRestore default signal handler.
sig_raiseSend signal to self.
sig_killSend signal to another process.
sig_blockBlock a signal. how=0 (SIG_BLOCK).
sig_unblockUnblock a signal. how=1 (SIG_UNBLOCK).
sig_pendingCheck 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) -> i64

sig_action

fn sig_action(signum: i64, handler: i64) -> i64

Set signal handler. handler = function pointer. Returns 0 on success, -1 on error.

smtp

SMTP Protocol Helpers

Functions

FunctionDescription
_smtp_byte_atInternal byte reader.
_smtp_copyInternal: copy bytes from src to dst+doff.
_smtp_crlfInternal: write CRLF at position.
smtp_format_ehloFormat EHLO command: “EHLO domain\r\n”
smtp_format_mail_fromFormat MAIL FROM command: “MAIL FROM:\r\n”
smtp_format_rcpt_toFormat RCPT TO command: “RCPT TO:\r\n”
smtp_format_dataFormat DATA command: “DATA\r\n”
smtp_parse_replyParse SMTP reply code from buffer. Returns integer code (e.g. 250). Expects f…
smtp_reply_is_okCheck if reply code is success (2xx).

Details

_smtp_byte_at

fn _smtp_byte_at(buf: &i8, idx: i64) -> i64

Internal byte reader.

socketserver

TCP/UDP Server Primitives

Functions

FunctionDescription
_srv_byte_atInternal byte reader.
_srv_copyInternal: copy bytes.
_srv_parse_intInternal: parse integer from bytes at offset, returns value.
srv_tcp_newCreate a TCP server handle.
srv_tcp_startStart listening (stub — returns -1, would use socket/bind/listen syscalls).
srv_tcp_acceptAccept a connection (stub — returns -1).
srv_parse_addrParse “host:port” string into a server handle.
srv_addr_portGet the port from a server handle.
srv_addr_host_lenGet the host length from a server handle.
srv_addr_hostCopy host string to output buffer. Returns length.

Details

_srv_byte_at

fn _srv_byte_at(buf: &i8, idx: i64) -> i64

Internal 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

FunctionSignatureDescription
sort_vec(v: &i64)Sort ascending in-place
sort_vec_desc(v: &i64)Sort descending in-place
sort_is_sorted(v: &i64) -> i64Check if sorted ascending
sort_reverse(v: &i64)Reverse in-place
sort_min(v: &i64) -> i64Minimum element
sort_max(v: &i64) -> i64Maximum element
sort_binary_search(v: &i64, val: i64) -> i64Binary search (vec must be sorted)
sort_unique(v: &i64) -> &i64Remove duplicates from sorted vec
sort_merge(a: &i64, b: &i64) -> &i64Merge 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

FunctionDescription
stat_sumSum of all values.
stat_mean_x10kMean * 10000.
_stat_sortInternal: simple insertion sort for small arrays.
stat_medianMedian (middle value of sorted data).
stat_modeMode (most frequent value). Uses O(n^2) counting to avoid alloc_pages overlap.
stat_minMinimum value.
stat_maxMaximum value.
stat_rangeRange (max - min).
stat_variance_x10kVariance * 10000. Uses sum of squared deviations.
_stat_isqrtInteger square root (helper for stdev).
stat_stdev_x10kStandard deviation * 10000.
stat_percentilePercentile (0-100). Returns value at that percentile.

Details

stat_sum

fn stat_sum(data: &i64, n: i64) -> i64

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

OffsetFieldDescription
[0]lengthByte count of the string content
[1]capacityAllocated 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

FunctionSignatureDescription
str_new() -> &i64Create an empty string
str_from(src: &i8, len: i64) -> &i64Create a string from a byte literal
str_clone(s: &i64) -> &i64Deep copy a string
str_len(s: &i64) -> i64Get byte length
str_byte(s: &i64, idx: i64) -> i64Get byte at index
str_eq(a: &i64, b: &i64) -> i64Content equality (returns 1 or 0)
str_concat(a: &i64, b: &i64) -> &i64Concatenate two strings
str_append(s: &i64, src: &i8, len: i64) -> &i64Append literal bytes
str_slice(s: &i64, start: i64, end: i64) -> &i64Substring [start, end)
str_index_of(s: &i64, sub: &i64) -> i64Find first occurrence (or -1)
str_contains(s: &i64, sub: &i64) -> i64Check if string contains substring
str_starts_with(s: &i64, pfx: &i64) -> i64Check prefix match
str_ends_with(s: &i64, sfx: &i64) -> i64Check suffix match
str_count(s: &i64, sub: &i64) -> i64Count non-overlapping occurrences
str_to_upper(s: &i64) -> &i64ASCII uppercase copy
str_to_lower(s: &i64) -> &i64ASCII lowercase copy
str_print(s: &i64)Write string to stdout

Detailed API

str_new

fn str_new() -> &i64

Create an empty string with a default capacity of 16 bytes.

stringio

In-Memory String I/O

Functions

FunctionDescription
_sio_byte_at
_sio_copy
sio_newCreate empty StringIO with given capacity.
sio_fromCreate StringIO from existing string.
sio_writeWrite data at current position. Returns bytes written.
sio_readRead n bytes from current position. Returns bytes read.
sio_getlineRead until newline or max bytes. Returns bytes read (including newline).
sio_seekSet read/write position.
sio_rewindReset position to beginning.
sio_eof1 if at end of data.
sio_lenCurrent data length.
sio_posCurrent read/write position.
sio_stringCopy all contents to out buffer. Returns length.
sio_putcWrite a single byte at current position.
sio_getcRead 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) -> &i64

Create empty StringIO with given capacity.

stringscanner

Stateful String Scanner

Functions

FunctionDescription
_ss_byte_at
_ss_copy
ss_newCreate new scanner over source string.
ss_scanTry to match pattern at current position. If found, advance and return 1.
ss_checkCheck if pattern matches at current position without advancing.
ss_skipAdvance position by n bytes.
ss_skip_untilSkip forward until pattern is found. Returns distance skipped, -1 if not found.
ss_restCopy remaining unscanned portion to out. Returns length.
ss_rest_lenLength of remaining unscanned portion.
ss_eos1 if at end of string.
ss_posCurrent scan position.
ss_resetReset scanner to beginning.
ss_matchedCopy last matched string to out. Returns length.
ss_peekPeek at next n bytes without advancing. Returns bytes copied.
ss_scan_byteRead 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) -> &i64

Create new scanner over source string.

tarfile

POSIX ustar Tar Archive Format

Functions

FunctionDescription
_tar_byte_atInternal byte reader.
_tar_write_octalInternal: write octal string (zero-padded, len chars) at position. Writes rig…
_tar_read_octalInternal: read octal number from buffer.
_tar_checksumInternal: compute header checksum.
_tar_zero_blockInternal: zero-fill a 512-byte block.
tar_createCreate a write handle. out is the output buffer.
tar_add_fileAdd a file entry to the tar archive.
tar_finishWrite two zero blocks to finish the archive. Returns total length.
tar_openOpen a tar archive for reading.
tar_nextAdvance to next entry. Returns 1 if entry found, 0 if end of archive.
tar_entry_nameCopy current entry name to out. Returns length.
tar_entry_sizeGet size of current entry data.
tar_entry_dataCopy current entry data to out. Returns length.

Details

_tar_byte_at

fn _tar_byte_at(buf: &i8, idx: i64) -> i64

Internal 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

FunctionDescription
tmp_rand_suffixInternal: generate random suffix (6 alphanumeric chars).
tmp_write_prefixInternal: write “/tmp/” prefix.
tmp_nameGenerate a unique temp path name. Returns length.
tmp_make_handleHandle layout: [0]=fd, [1]=path_ptr, [2]=path_len, [3]=is_dir
tmp_fileCreate a temporary file. Returns handle.
tmp_dirCreate a temporary directory. Returns handle.
tmp_pathCopy path to dst buffer. Returns length.
tmp_fdGet file descriptor.
tmp_writeWrite bytes to temp file.
tmp_readRead bytes from temp file (seeks to start first).
tmp_closeClose the file descriptor.
tmp_removeDelete the temp file or directory.

Details

tmp_rand_suffix

fn tmp_rand_suffix(dst: &i8, off: i64) -> i64

Internal: generate random suffix (6 alphanumeric chars).

tensor_ops

Functions

FunctionDescription
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) -> i64

tensor_mean

fn tensor_mean(a: i64) -> i64

tensor_max

fn tensor_max(a: i64) -> i64

tensor_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

FunctionDescription
tensor_reshape_1d
tensor_reshape_2d
tensor_slice1d
tensor_slice2d
tensor_row
tensor_col
broadcast_add_1d
broadcast_add_2d1d
broadcast_add_2d_col
broadcast_mul_1d
broadcast_mul_2d1d
broadcast_mul_2d_col
broadcast_scalar_add
broadcast_scalar_mul
broadcast_scalar_sub
broadcast_scalar_div
tensor_sum_axis0
tensor_sum_axis1
tensor_mean_axis0
tensor_mean_axis1
tensor_max_axis0
tensor_max_axis1
tensor_concat1d
tensor_vstack
tensor_hstack
tensor_where
tensor_clamp
tensor_arange
tensor_linspace
tensor_copy_1d
tensor_copy_2d

Details

tensor_reshape_1d

fn tensor_reshape_1d(t: i64, d0: i64) -> i64

tensor_reshape_2d

fn tensor_reshape_2d(t: i64, d0: i64, d1: i64) -> i64

tensor_slice1d

fn tensor_slice1d(t: i64, start: i64, stop: i64, step: i64) -> i64

tensor_slice2d

fn tensor_slice2d(t: i64, row_start: i64, row_stop: i64, col_start: i64, col_stop: i64) -> i64

tensor_row

fn tensor_row(t: i64, row: i64) -> i64

tensor_col

fn tensor_col(t: i64, col: i64) -> i64

broadcast_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) -> i64

tensor_sum_axis1

fn tensor_sum_axis1(t: i64, rows: i64, cols: i64) -> i64

tensor_mean_axis0

fn tensor_mean_axis0(t: i64, rows: i64, cols: i64) -> i64

tensor_mean_axis1

fn tensor_mean_axis1(t: i64, rows: i64, cols: i64) -> i64

tensor_max_axis0

fn tensor_max_axis0(t: i64, rows: i64, cols: i64) -> i64

tensor_max_axis1

fn tensor_max_axis1(t: i64, rows: i64, cols: i64) -> i64

tensor_concat1d

fn tensor_concat1d(a: i64, b: i64) -> i64

tensor_vstack

fn tensor_vstack(a: i64, b: i64, cols: i64) -> i64

tensor_hstack

fn tensor_hstack(a: i64, b: i64) -> i64

tensor_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) -> i64

tensor_linspace

fn tensor_linspace(start: i64, stop: i64, n: i64) -> i64

tensor_copy_1d

fn tensor_copy_1d(t: i64) -> i64

tensor_copy_2d

fn tensor_copy_2d(t: i64) -> i64

testing

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

FunctionSignatureDescription
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() -> i64Print 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

FunctionDescription
_tw_byte_atInternal byte reader.
_tw_copyInternal: copy bytes.
textwrap_fillWrap text at word boundaries. Inserts newlines. Returns total length.
textwrap_wrapWrap text (alias for fill).
textwrap_dedentRemove common leading whitespace from all lines.
textwrap_indentAdd prefix to each line.
textwrap_shortenTruncate text to width, adding […] if too long.

Details

_tw_byte_at

fn _tw_byte_at(buf: &i8, idx: i64) -> i64

Internal 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

FunctionDescription
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() -> i64

time_now_us

fn time_now_us() -> i64

time_now_ms

fn time_now_ms() -> i64

time_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) -> i64

time_unix_secs

fn time_unix_secs() -> i64

timeout

Deadline and Timeout Utilities

Functions

FunctionDescription
timeout_nowGet current time in milliseconds since epoch.
timeout_deadlineCreate a deadline ms milliseconds from now.
timeout_remainingMilliseconds remaining until deadline (0 if expired).
timeout_expiredCheck if deadline has passed.
timeout_sleep_msSleep for ms milliseconds using nanosleep.
timeout_elapsedMilliseconds elapsed since a start timestamp.
timeout_timer_startStart a timer. Returns current time in ms.
timeout_timer_stopStop a timer. Returns elapsed milliseconds.
timeout_print_intInternal: print integer to stdout.
timeout_timer_printPrint “label: Nms\n” for profiling.

Details

timeout_now

fn timeout_now() -> i64

Get current time in milliseconds since epoch.

tls

TLS 1.2 Client (Minimal)

Functions

FunctionDescription
_tls_copy
_tls_socket_tcp
_tls_connect_raw
_tls_send
_tls_recv
_tls_close
_tls_getrandom
tcp_connectConnect to host:port via TCP. Returns socket fd or -1.
_tls_build_client_helloInternal: build TLS ClientHello message.
tls_connectConnect to host:port with TLS 1.2 handshake. Returns TLS context or 0 on fail…
tls_writeWrite data over TLS connection. Returns bytes written. Simplified: sends as T…
tls_readRead data from TLS connection. Returns bytes read.
tls_closeClose 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) -> i64

tcp_connect

fn tcp_connect(host: &i8, hlen: i64, port: i64) -> i64

Connect to host:port via TCP. Returns socket fd or -1.

toml

Subset TOML Parser

Functions

FunctionDescription
_toml_byte_atInternal byte reader.
_toml_eqInternal: compare bytes.
_toml_skip_wsInternal: skip whitespace.
_toml_skip_lineInternal: skip to end of line.
_toml_storeInternal: store bytes to data_buf, return offset where stored.
_toml_store_dottedInternal: store a dotted key (table.key) to data_buf.
_toml_addInternal: add entry.
_toml_parse_intInternal: parse integer from buf at off with given length.
_toml_trim_endInternal: trim trailing ws. Returns new end pos.
_toml_parse_tableInternal: parse table header. Returns pos after line.
_toml_store_keyInternal: store key (dotted if table is set). Returns stored key offset and s…
_toml_parse_quotedInternal: parse a quoted string value. Returns pos after closing quote.
_toml_parse_unquotedInternal: parse an unquoted value. Returns pos after line.
_toml_parse_kvInternal: parse key=value line. Returns pos after line.
toml_parseParse TOML data. Returns handle.
toml_countNumber of entries.
_toml_findInternal: find entry by key. Returns index or -1.
toml_get_strGet string value for key. Copies to out, returns length. -1 if not found.
toml_get_i64Get integer value for key. Returns 0 if not found.
toml_get_boolGet 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) -> i64

Internal byte reader.

transformer

Functions

FunctionDescription
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) -> i64

softmax_row

fn softmax_row(x: i64, out: i64, base: i64, cols: i64) -> i64

softmax_rows

fn softmax_rows(x: i64, out: i64, rows: i64, cols: i64) -> i64

compute_mean

fn compute_mean(x: i64) -> i64

compute_var

fn compute_var(x: i64, mean: i64) -> i64

norm_apply

fn norm_apply(x: i64, out: i64, mean: i64, std: i64, gamma: i64, beta: i64) -> i64

layer_norm_fwd

fn layer_norm_fwd(x: i64, out: i64, gamma: i64, beta: i64) -> i64

attn_scores

fn attn_scores(q: i64, k: i64, scores: i64, seq: i64, dk: i64) -> i64

attn_apply

fn attn_apply(attn: i64, v: i64, out: i64, seq: i64, dk: i64) -> i64

attention_fwd

fn attention_fwd(q: i64, k: i64, v: i64, out: i64, seq: i64, dk: i64) -> i64

gelu_fwd

fn gelu_fwd(x: i64, out: i64) -> i64

embed_fwd

fn embed_fwd(tokens: i64, table: i64, out: i64, seq: i64, d_model: i64) -> i64

pos_encode

fn pos_encode(x: i64, seq: i64, d_model: i64) -> i64

linear_fwd

fn linear_fwd(x: i64, w: i64, bias: i64, out: i64) -> i64

residual_add

fn residual_add(a: i64, b: i64, out: i64) -> i64

relu_fwd

fn relu_fwd(x: i64, out: i64) -> i64

tsort

Topological Sort

Functions

FunctionDescription
tsort_newCreate a graph with n nodes (labeled 0..n-1).
tsort_add_edgeAdd a directed edge from → to.
tsort_sortTopological sort using Kahn’s algorithm. Returns vec of node IDs in topologic…
tsort_has_cycleCheck if graph has a cycle.
tsort_node_countNumber of nodes.
tsort_edge_countNumber of edges.

Details

tsort_new

fn tsort_new(n: i64) -> &i64

Create 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

FunctionDescription
pairCreate a pair (2-tuple).
fstFirst element.
sndSecond element.
tripleCreate a triple (3-tuple).
trdThird element.
tup_getGeneric indexed access.
tup_setGeneric indexed mutation.
pair_eqPair equality (element-wise).
pair_swapSwap pair elements.
triple_eqTriple equality (element-wise).
result_okResult-style: success value with no error.
result_errResult-style: error with code.
is_okIs result a success? (error code == 0)
is_errIs result an error? (error code != 0)
unwrapGet the value from a result.
err_codeGet the error code from a result.

Details

pair

fn pair(a: i64, b: i64) -> &i64

Create a pair (2-tuple).

udp

// jda::net::udp — UDP Socket API

Constants

SYS_SOCKET     = 41
SYS_BIND       = 49
SYS_SENDTO     = 44
SYS_RECVFROM   = 45
SYS_SETSOCKOPT = 54
SYS_CLOSE      = 3
AF_INET        = 2
SOCK_DGRAM     = 2
SOCK_NONBLOCK  = 2048
IPPROTO_UDP    = 17
SOL_SOCKET     = 1
SO_REUSEADDR   = 2
SO_REUSEPORT   = 15
SO_BROADCAST   = 6
IPPROTO_IP     = 0
IP_ADD_MEMBERSHIP  = 35    // join multicast group
IP_DROP_MEMBERSHIP = 36    // leave multicast group
IP_MULTICAST_TTL   = 33
IP_MULTICAST_LOOP  = 34
EAGAIN         = 11

Structs

UdpPeer

struct UdpPeer {
    addr: u32    // IPv4 address (host byte order)
    port: u16
}

UdpSocket

struct UdpSocket {
    fd:         i32
    local_port: u16
}

Functions

FunctionDescription
udp_echo_server

Details

udp_echo_server

fn udp_echo_server(port: u16)

uri

URI/URL Parsing and Encoding

Functions

FunctionDescription
uri_copyInternal: copy bytes from src+off to dst, return len.
uri_is_unreservedInternal: is this byte unreserved (RFC 3986)?
uri_hex_charInternal: hex nibble to char.
uri_hex_valInternal: hex char to nibble.
uri_parseParse a URI string into components.
uri_scheme
uri_host
uri_port
uri_path
uri_query
uri_fragment
uri_encodePercent-encode a string. Returns output length.
uri_decodePercent-decode a string. Returns output length.
uri_query_getGet 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) -> i64

Internal: copy bytes from src+off to dst, return len.

uuid

UUID Generation

Functions

FunctionDescription
uuid_hexInternal: write hex digit to buffer.
uuid_v4Generate UUID v4 into dst buffer. Returns 36 (length).
uuid_v4_printGenerate and print a UUID v4 to stdout.

Details

uuid_hex

fn uuid_hex(val: i64) -> i64

Internal: write hex digit to buffer.

uuid_v4

fn uuid_v4(dst: &i8) -> i64

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

OffsetFieldDescription
[0]lengthNumber of elements currently stored
[1]capacityNumber 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

FunctionSignatureDescription
vec_new(cap: i64) -> &i64Create a new vec with initial capacity
vec_len(v: &i64) -> i64Get number of elements
vec_cap(v: &i64) -> i64Get current capacity
vec_push(v: &i64, val: i64)Append an element
vec_pop(v: &i64) -> i64Remove and return last element
vec_get(v: &i64, idx: i64) -> i64Get 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) -> i64Get last element
vec_contains(v: &i64, val: i64) -> i64Check if value exists
vec_remove(v: &i64, idx: i64) -> i64Remove at index, shift left

Detailed API

vec_new

fn vec_new(cap: i64) -> &i64

Create a new vec with the given initial capacity. The minimum capacity is 16 – values below 16 are rounded up.

weakref

Weak References

Functions

FunctionDescription
weakref_newCreate new weak reference to target pointer.
weakref_derefDereference: get target pointer. Returns 0 if released.
weakref_aliveCheck if reference is still alive.
weakref_releaseRelease the weak reference (mark target as gone).
weakref_idGet unique reference ID.
weakref_registry_newRegistry: tracks a collection of weak references. Layout: [0]=count, [1]=capa…
weakref_registerRegister a weak reference in the registry.
weakref_sweepSweep: count dead references and compact the registry. Returns number of dead…

Details

weakref_new

fn weakref_new(target: i64) -> &i64

Create new weak reference to target pointer.

ws

// jda::net::ws — WebSocket Protocol (RFC 6455)

Constants

WS_OP_CONTINUATION = 0x0
WS_OP_TEXT         = 0x1
WS_OP_BINARY       = 0x2
WS_OP_CLOSE        = 0x8
WS_OP_PING         = 0x9
WS_OP_PONG         = 0xA
WS_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

FunctionDescription
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) -> i64

xml

Simple XML Parser (SAX-style events)

Functions

FunctionDescription
_xml_byte_atInternal byte reader.
_xml_copyInternal: copy bytes.
_xml_add_evtInternal: add event.
_xml_tag_name_endInternal: find end of tag name (space or > or /).
_xml_find_ltInternal: find ‘<’ from pos.
_xml_find_gtInternal: find ‘>’ from pos.
_xml_skip_commentInternal: skip comment . Returns position after –>.
_xml_skip_piInternal: skip PI . Returns position after ?>.
_xml_process_tagInternal: process a tag starting at ‘<’. Returns new pos.
xml_parseParse XML buffer into events.
xml_event_countReturn event count.
xml_event_typeReturn event type at index.
xml_event_nameCopy event name/text to out. Return length.
xml_event_textCopy event text to out. Return length.
xml_escapeEscape XML special chars: & < > " '
_xml_check_ltInternal: check 3-char entity after &.
_xml_check_gt
_xml_check_amp
_xml_check_quot
_xml_check_apos
xml_unescapeUnescape XML entities: & < > " '

Details

_xml_byte_at

fn _xml_byte_at(buf: &i8, idx: i64) -> i64

Internal byte reader.

yaml

YAML Parser/Emitter (Subset)

Functions

FunctionDescription
_yaml_copy
_yaml_streq
_yaml_addInternal: add a key-value pair to the document.
yaml_parseParse YAML string into document. Returns doc pointer.
yaml_getGet string value by key. Copies to out, returns length. 0 if not found.
yaml_get_i64Get integer value by key.
yaml_countNumber of entries.
yaml_key_atGet key at index. Returns key length.
yaml_val_atGet value at index. Returns value length.
yaml_emitEmit 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

FunctionDescription
_zip_byte_atInternal byte reader.
_zip_w16Internal: write little-endian 16-bit.
_zip_w32Internal: write little-endian 32-bit.
_zip_r16Internal: read little-endian 16-bit.
_zip_r32Internal: read little-endian 32-bit.
_zip_crc32_byteSimple CRC-32 for ZIP (same algorithm as gzip).
_zip_crc32Compute CRC-32 for data.
zip_createCreate a write handle.
zip_addAdd a stored file entry to the ZIP.
zip_finishWrite central directory and EOCD. Returns total archive length.
_zip_find_eocdInternal: scan for EOCD to find central directory.
zip_openOpen a ZIP archive for reading.
zip_countNumber of entries in the ZIP.
zip_entry_nameCopy entry name at index to out. Returns length.
zip_entry_sizeGet data size for entry at index.
zip_entry_dataCopy entry data at index to out. Returns length.

Details

_zip_byte_at

fn _zip_byte_at(buf: &i8, idx: i64) -> i64

Internal byte reader.

zlib

Compression (CRC-32, Deflate/Inflate)

Constants

CRC32_POLY = 3988292384

CRC-32 polynomial: 0xEDB88320 (reversed)

Functions

FunctionDescription
zlib_crc32CRC-32 of data buffer.
zlib_crc32_updateIncremental CRC-32 update.
zlib_adler32Adler-32 checksum.
zlib_compressCompress using simplified DEFLATE (stored blocks, no Huffman for simplicity)….
zlib_decompressDecompress zlib-compressed data (handles stored blocks). Returns decompressed…

Details

zlib_crc32

fn zlib_crc32(data: &i8, len: i64) -> i64

CRC-32 of data buffer.

zlib_crc32_update

fn zlib_crc32_update(crc: i64, data: &i8, len: i64) -> i64

Incremental CRC-32 update.

zlib_adler32

fn zlib_adler32(data: &i8, len: i64) -> i64

Adler-32 checksum.