veko-lang.org
Download Free EPUB 3.0

Part V · Complete Tooling, CLI & Standard Library Reference

Appendix B.1

Standard Library Reference: Core, CLI, Math, Text, Thompson NFA Regex & Streams

Complete AST-verified API reference for 28 foundational, text, regex, collection, and I/O stream modules

Foundational pure-Veko standard library modules (lib/), extracted directly from live AST signatures and module docstrings.

Module (use [...])Source FileCapabilitiesTypesFunctions
bitslib/bits.vkZero host capabilities128
buflib/buf.vkZero host capabilities334
clilib/cli.vkZero host capabilities46
colllib/coll.vkZero host capabilities529
datetimelib/datetime.vk..clocks115
dialectlib/dialect.vkZero host capabilities15
difflib/diff.vkZero host capabilities13
fmtlib/fmt.vkZero host capabilities011
fslib/fs.vk..fs, ..clocks011
globlib/glob.vkZero host capabilities02
io/fslib/io/fs.vk..fs17
io/netlib/io/net.vk..net115
io/openlib/io/open.vk..net02
iolib/io.vkZero host capabilities511
mathlib/math.vkZero host capabilities048
pathlib/path.vkZero host capabilities011
randlib/rand.vk..clocks112
regexlib/regex.vkZero host capabilities45
retrylib/retry.vk..clocks25
semverlib/semver.vkZero host capabilities17
seqlib/seq.vkZero host capabilities019
sloglib/slog.vkZero host capabilities112
templatelib/template.vkZero host capabilities03
testing/fuzzlib/testing/fuzz.vkZero host capabilities25
testinglib/testing.vk..clocks210
text/relib/text/re.vkZero host capabilities37
textlib/text.vkZero host capabilities021
utf8lib/utf8.vkZero host capabilities17

Module bits

Exported Structs & Interfaces

  • VarintVal: VarintVal = struct { value i64, next_off i64 } — Result of decoding a varint at a byte offset.

Exported Functions

SymbolSignatureDescription
get-u24-beget-u24-be = fn [b bytes, off i64] i64Reads an unsigned 24-bit big-endian integer from b at off.
get-u24-leget-u24-le = fn [b bytes, off i64] i64Reads an unsigned 24-bit little-endian integer from b at off.
set-u24-beset-u24-be = fn [mut b bytes, off i64, v i64] i64Writes an unsigned 24-bit big-endian integer into b at off.
set-u24-leset-u24-le = fn [mut b bytes, off i64, v i64] i64Writes an unsigned 24-bit little-endian integer into b at off.
push-u24-bepush-u24-be = fn [mut b bytes, v i64] i64Appends an unsigned 24-bit big-endian integer to b, returning the new length.
push-u24-lepush-u24-le = fn [mut b bytes, v i64] i64Appends an unsigned 24-bit little-endian integer to b, returning the new length.
get-i16-leget-i16-le = fn [b bytes, off i64] i64Reads a signed 16-bit little-endian integer from b at off.
get-i16-beget-i16-be = fn [b bytes, off i64] i64Reads a signed 16-bit big-endian integer from b at off.
get-i32-leget-i32-le = fn [b bytes, off i64] i64Reads a signed 32-bit little-endian integer from b at off.
get-i32-beget-i32-be = fn [b bytes, off i64] i64Reads a signed 32-bit big-endian integer from b at off.
push-i16-lepush-i16-le = fn [mut b bytes, v i64] i64Appends a signed 16-bit little-endian integer to b.
push-i16-bepush-i16-be = fn [mut b bytes, v i64] i64Appends a signed 16-bit big-endian integer to b.
push-i32-lepush-i32-le = fn [mut b bytes, v i64] i64Appends a signed 32-bit little-endian integer to b.
push-i32-bepush-i32-be = fn [mut b bytes, v i64] i64Appends a signed 32-bit big-endian integer to b.
f64-to-bitsf64-to-bits = fn [x f64] i64Converts an IEEE-754 f64 value into its 64-bit integer bit pattern.
bits-to-f64bits-to-f64 = fn [raw i64] f64Reconstructs an IEEE-754 f64 value from its 64-bit integer bit pattern.
zigzag-encodezigzag-encode = fn [n i64] i64Encodes a signed i64 into an unsigned ZigZag i64 bit pattern.
zigzag-decodezigzag-decode = fn [u i64] i64Decodes an unsigned ZigZag i64 back into a signed i64.
push-varint-u64push-varint-u64 = fn [mut out bytes, v i64] i64Appends an unsigned LEB128 varint (64-bit) to out, returning the new length.
read-varint-u64read-varint-u64 = fn [b bytes, off i64] VarintValReads an unsigned LEB128 varint from b starting at off.
crc32crc32 = fn [data bytes] i64Computes the IEEE 802.3 CRC-32 checksum (0xEDB88320 reflected polynomial).
adler32adler32 = fn [data bytes] i64Computes the RFC 1950 Adler-32 checksum of data.
fnv1a-64fnv1a-64 = fn [data bytes] i64Computes the 64-bit FNV-1a non-cryptographic hash of data.
index-ofindex-of = fn [hay bytes, needle bytes, start i64] i64Finds the first index of needle inside hay at or after start, or -1 if absent.
starts-with?starts-with? = fn [data bytes, prefix bytes] boolReturns true if data starts with prefix.
ends-with?ends-with? = fn [data bytes, suffix bytes] boolReturns true if data ends with suffix.
xor-in-place!xor-in-place! = fn [mut dst bytes, mask bytes] i64XORs mask into dst in-place across min(len dst, len mask) bytes.
ct-eq?ct-eq? = fn [a bytes, b bytes] boolConstant-time equality comparison for equal-length byte buffers (returns false if lengths differ).

Verified Doctest (bits/get-u24-be)

VEKO
use [bits]
mut b = bytes/with-cap 4
_ = bits/push-u24-be mut b 0x123456
if (bits/get-u24-be b 0) != 0x123456 [ err 'u24-be mismatch' ] else [ .ok ]

Module buf

Exported Structs & Interfaces

  • ByteReader: ByteReader = struct { data bytes, pos i64 = ... } — Sequential cursor over an immutable bytes buffer.
  • ByteWriter: ByteWriter = struct { buf bytes } — Growable binary buffer builder for packet and file serialization.
  • StringBuilder: StringBuilder = struct { buf bytes } — Growable UTF-8 string builder backed by a pre-allocated bytes slab.

Exported Functions

SymbolSignatureDescription
reader-newreader-new = fn [data bytes] ByteReaderCreates a new ByteReader positioned at offset 0 of data.
reader-remainingreader-remaining = fn [r ByteReader] i64Returns the number of unread bytes remaining in r.
reader-eof?reader-eof? = fn [r ByteReader] boolReturns true when r has reached the end of its buffer.
reader-seekreader-seek = fn [mut r ByteReader, off i64] i64Moves the cursor of r to absolute byte offset off.
reader-skipreader-skip = fn [mut r ByteReader, n i64] i64Advances the cursor of r by n bytes.
read-u8read-u8 = fn [mut r ByteReader] i64Reads a single unsigned byte from r.
read-u16-leread-u16-le = fn [mut r ByteReader] i64Reads an unsigned 16-bit little-endian integer from r.
read-u16-beread-u16-be = fn [mut r ByteReader] i64Reads an unsigned 16-bit big-endian integer from r.
read-u32-leread-u32-le = fn [mut r ByteReader] i64Reads an unsigned 32-bit little-endian integer from r.
read-u32-beread-u32-be = fn [mut r ByteReader] i64Reads an unsigned 32-bit big-endian integer from r.
read-i64-leread-i64-le = fn [mut r ByteReader] i64Reads a 64-bit little-endian integer from r.
read-i64-beread-i64-be = fn [mut r ByteReader] i64Reads a 64-bit big-endian integer from r.
read-bytesread-bytes = fn [mut r ByteReader, n i64] bytesReads exactly n bytes from r.
read-strread-str = fn [mut r ByteReader, n i64] strReads n bytes from r and decodes them as a UTF-8 str.
read-restread-rest = fn [mut r ByteReader] bytesReads all remaining unread bytes from r.
read-untilread-until = fn [mut r ByteReader, delim i64] bytesReads bytes up to (but not including) delim, advancing past delim; returns err if not found.
writer-newwriter-new = fn [cap i64] ByteWriterCreates a new ByteWriter pre-allocated with cap bytes.
writer-lenwriter-len = fn [w ByteWriter] i64Returns the current byte length written into w.
writer-byteswriter-bytes = fn [w ByteWriter] bytesReturns the accumulated bytes buffer from w.
write-u8write-u8 = fn [mut w ByteWriter, v i64] i64Appends one byte to w.
write-u16-lewrite-u16-le = fn [mut w ByteWriter, v i64] i64Appends a 16-bit little-endian integer to w.
write-u16-bewrite-u16-be = fn [mut w ByteWriter, v i64] i64Appends a 16-bit big-endian integer to w.
write-u32-lewrite-u32-le = fn [mut w ByteWriter, v i64] i64Appends a 32-bit little-endian integer to w.
write-u32-bewrite-u32-be = fn [mut w ByteWriter, v i64] i64Appends a 32-bit big-endian integer to w.
write-i64-lewrite-i64-le = fn [mut w ByteWriter, v i64] i64Appends a 64-bit little-endian integer to w.
write-i64-bewrite-i64-be = fn [mut w ByteWriter, v i64] i64Appends a 64-bit big-endian integer to w.
write-byteswrite-bytes = fn [mut w ByteWriter, data bytes] i64Appends a bytes slice to w.
write-strwrite-str = fn [mut w ByteWriter, s str] i64Appends a UTF-8 str to w.
sb-newsb-new = fn [cap i64] StringBuilderCreates a new StringBuilder with initial capacity cap.
sb-pushsb-push = fn [mut sb StringBuilder, s str] i64Appends s to sb.
sb-push-linesb-push-line = fn [mut sb StringBuilder, s str] i64Appends s followed by \n to sb.
sb-push-bytesb-push-byte = fn [mut sb StringBuilder, b i64] i64Appends a single byte b to sb.
sb-lensb-len = fn [sb StringBuilder] i64Returns the current byte length of sb.
sb-buildsb-build = fn [sb StringBuilder] strReturns the built UTF-8 string.

Verified Doctest (buf/reader-new)

VEKO
use [buf]
mut w = buf/writer-new 16
_ = buf/write-u16-be mut w 0x0303
_ = buf/write-u32-le mut w 0x11223344
mut r = buf/reader-new (buf/writer-bytes w)
v1 = buf/read-u16-be mut r
v2 = buf/read-u32-le mut r
if v1 != 0x0303 or v2 != 0x11223344 or (not (buf/reader-eof? r)) [ err 'buf rw' ] else [ .ok ]

Module cli

Exported Structs & Interfaces

  • FlagSpec: FlagSpec = struct { name str, short str = ..., kind enum = ..., required bool = ..., default_val any = ..., help str = ... } — Describes a single CLI flag (--name, optional -s, and value kind .bool, .i64, .str, or .list).
  • CmdSpec: CmdSpec = struct { name str, summary str = ..., flags block[FlagSpec] = ..., min_args i64 = ... } — Describes a CLI subcommand and its command-specific flags.
  • CliSpec: CliSpec = struct { name str, version str = ..., summary str = ..., flags block[FlagSpec] = ..., commands block[CmdSpec] = ... } — Top-level specification for a command-line application.
  • CliResult: CliResult = struct { command str = ..., flags map = ..., args block[str] = ..., help_requested bool = ..., version_requested bool = ... } — Parsed command-line invocation produced by cli/parse.

Exported Functions

SymbolSignatureDescription
parseparse = fn [spec CliSpec, argv block[str]] CliResultParses argv according to spec, validating flag types, short clusters (-abc), --key=value syntax, subcommands, required flags, and -- positional separation.
flag-strflag-str = fn [res CliResult, name str, fallback str] strRetrieves a string flag value from res, falling back to fallback.
flag-i64flag-i64 = fn [res CliResult, name str, fallback i64] i64Retrieves an i64 flag value from res, falling back to fallback.
flag-boolflag-bool = fn [res CliResult, name str] boolRetrieves a boolean flag value from res (defaults to false).
flag-listflag-list = fn [res CliResult, name str] blockRetrieves a repeatable .list flag value from res (defaults to []).
render-helprender-help = fn [spec CliSpec] strRenders a clean --help usage guide for spec.

Verified Doctest (cli/parse)

VEKO
use [cli]
spec = cli/CliSpec {
  name = 'demo'
  flags = [
    cli/FlagSpec { name = 'port', short = 'p', kind = .i64, default_val = 8080 }
    cli/FlagSpec { name = 'verbose', short = 'v', kind = .bool, default_val = false }
  ]
}
res = cli/parse spec ['-v' '--port=9090' 'input.vk']
if (cli/flag-i64 res 'port' 0) != 9090 or (not (cli/flag-bool res 'verbose')) [
  err 'cli/parse mismatch'
] else [ .ok ]

Module coll

Exported Structs & Interfaces

  • Set: Set = struct { data map = ... } — Unordered set of scalar keys (str, i64, or .enum), backed by hybrid hashed map.
  • Ring: Ring = struct { buf block, cap i64, head i64 = ..., count i64 = ... } — Fixed-capacity O(1) FIFO ring buffer.
  • Heap: Heap = struct { items block = ... } — Binary min-heap priority queue storing { prio = i64, val = any } entries.
  • Lru: Lru = struct { cap i64, data map = ..., order block[str] = ... } — Bounded Least-Recently-Used cache keyed by str.
  • Memo: Memo = struct { cache map = ..., hits i64 = ... } — Simple key-value memoization cache for pure functions.

Exported Functions

SymbolSignatureDescription
set-newset-new = fn [] SetCreates a new empty Set.
set-fromset-from = fn [xs block] SetCreates a Set initialized with all elements of xs.
set-addset-add = fn [mut s Set, k any] i64Inserts k into s in-place.
set-removeset-remove = fn [mut s Set, k any] i64Removes k from s in-place.
set-has?set-has? = fn [s Set, k any] boolReturns true if k is in s.
set-lenset-len = fn [s Set] i64Returns the number of elements in s.
set-itemsset-items = fn [s Set] blockReturns all elements of s as a block.
set-unionset-union = fn [a Set, b Set] SetReturns the union a U b.
set-intersectset-intersect = fn [a Set, b Set] SetReturns the intersection a /\ b.
set-diffset-diff = fn [a Set, b Set] SetReturns the difference a \ b.
ring-newring-new = fn [cap i64] RingCreates a new bounded Ring with capacity cap > 0.
ring-lenring-len = fn [r Ring] i64Number of items currently stored in r.
ring-full?ring-full? = fn [r Ring] boolReturns true if r is at capacity.
ring-empty?ring-empty? = fn [r Ring] boolReturns true if r is empty.
ring-pushring-push = fn [mut r Ring, val any] i64Appends val to the tail of r; returns err if full.
ring-popring-pop = fn [mut r Ring] anyRemoves and returns the oldest item from r; returns err if empty.
ring-peekring-peek = fn [r Ring] anyReturns the oldest item in r without removing it; returns err if empty.
heap-newheap-new = fn [] HeapCreates a new empty min-Heap.
heap-lenheap-len = fn [h Heap] i64Returns the number of entries in h.
heap-pushheap-push = fn [mut h Heap, prio i64, val any] i64Pushes val with integer priority prio (smaller prio pops first).
heap-peekheap-peek = fn [h Heap] anyReturns the lowest-priority value without popping; returns err if empty.
heap-popheap-pop = fn [mut h Heap] anyPops and returns the value with the smallest priority; returns err if empty.
lru-newlru-new = fn [cap i64] LruCreates a new LRU cache holding at most cap > 0 entries.
lru-has?lru-has? = fn [c Lru, k str] boolReturns true if k is currently cached in c.
lru-lenlru-len = fn [c Lru] i64Returns the number of cached entries in c.
lru-getlru-get = fn [mut c Lru, k str] anyLooks up k in c, marking it most-recently-used; returns err if absent.
lru-putlru-put = fn [mut c Lru, k str, val any] i64Inserts or updates k -> val in c, evicting the least-recently-used key when full.
memo-newmemo-new = fn [] MemoCreates a new empty Memo cache.
memo-callmemo-call = fn [mut m Memo, key str, compute fn[->any]] anyReturns cached value for key, or invokes (compute) once, caches the result, and returns it.

Verified Doctest (coll/set-new)

VEKO
use [coll]
mut s = coll/set-new
coll/set-add mut s 'alpha'
coll/set-add mut s 'beta'
if (coll/set-len s) != 2 or (not (coll/set-has? s 'alpha')) [ err 'set' ] else [ .ok ]

Module datetime

Exported Structs & Interfaces

  • DateTime: DateTime = struct { year i64, month i64, day i64, hour i64 = ..., minute i64 = ..., second i64 = ..., nanosecond i64 = ..., offset_sec i64 = ... } — Structured UTC / fixed-offset calendar date and time.

Exported Functions

SymbolSignatureDescription
leap-year?leap-year? = fn [year i64] boolReturns true if year is a Gregorian leap year.
days-in-monthdays-in-month = fn [year i64, month i64] i64Returns the number of days in month (1..12) of year.
from-unixfrom-unix = fn [unix_sec i64, ns i64] DateTimeConverts a Unix epoch timestamp in seconds (with optional sub-second ns) to a UTC DateTime.
from-unix-nsfrom-unix-ns = fn [unix_ns i64] DateTimeConverts a Unix epoch timestamp in nanoseconds (e.g. from time/unix) to a UTC DateTime.
now-utcnow-utc = fn [] DateTimeReturns the current UTC DateTime via time/unix (requires .clocks).
to-unixto-unix = fn [t DateTime] i64Converts t to Unix epoch seconds (accounting for t.offset_sec).
to-unix-nsto-unix-ns = fn [t DateTime] i64Converts t to Unix epoch nanoseconds.
weekdayweekday = fn [t DateTime] i64Returns the ISO weekday (0 = Sunday, 1 = Monday, ..., 6 = Saturday).
add-secondsadd-seconds = fn [t DateTime, delta_sec i64] DateTimeReturns a new DateTime shifted by delta_sec seconds, preserving t.offset_sec.
add-daysadd-days = fn [t DateTime, delta_days i64] DateTimeReturns a new DateTime shifted by delta_days days.
with-offsetwith-offset = fn [t DateTime, new_offset_sec i64] DateTimeConverts t to the same instant expressed at new_offset_sec east of UTC.
diff-secondsdiff-seconds = fn [a DateTime, b DateTime] i64Returns the difference (a - b) in seconds.
format-rfc3339format-rfc3339 = fn [t DateTime] strFormats t as an RFC 3339 / ISO 8601 timestamp ('YYYY-MM-DDTHH:MM:SS[.fff][Z|+HH:MM]').
format-httpformat-http = fn [t DateTime] strFormats t in UTC as an HTTP IMF-fixdate (RFC 9110, e.g. 'Thu, 01 Jan 1970 00:00:00 GMT').
parse-rfc3339parse-rfc3339 = fn [s str] DateTimeParses an RFC 3339 / ISO 8601 timestamp string into a DateTime.

Verified Doctest (datetime/leap-year?)

VEKO
use [dt = datetime]
if (not (dt/leap-year? 2024)) or (dt/leap-year? 1900) or (not (dt/leap-year? 2000)) [ err 'leap' ] else [ .ok ]

Module dialect

Exported Structs & Interfaces

  • Rule: Rule = struct { name str, pattern block, transform fn[map->any] } — Describes a single structural rewrite rule (pattern -> transform fn[map -> any]).

Exported Functions

SymbolSignatureDescription
rewrite-treerewrite-tree = fn [node any, visitor fn[any->any]] anyRecursively visits every node in a quoted/data block, applying visitor fn[any -> any] bottom-up to produce a transformed block tree.
collectcollect = fn [tree any, pred fn[any->bool]] blockCollects every node inside tree for which (pred node) returns true.
match-patternmatch-pattern = fn [pattern block, target block] mapMatches a flat or nested pattern against target block. String placeholders starting with '$' (e.g., '$proto', '$port') bind values into the returned map, and '*' matches any single element. Returns a bindings map on match, or err 'dialect/match-pattern: no match'.
apply-rulesapply-rules = fn [clauses block[block], rules block[Rule]] blockEvaluates a sequence of dialect clauses (block[block]) against an ordered list of Rules, returning a block of transformed results (or err on the first unmatched clause).
split-clausessplit-clauses = fn [items block, delim any] blockSplits a flat DSL token/item block into sub-blocks whenever delim appears.

Verified Doctest (dialect/rewrite-tree)

VEKO
use [d = dialect]
tree = [1 [2 3] 4]
out = d/rewrite-tree tree fn [node] [
  if (type-of node) == .i64_val [ node * 10 ] else [ node ]
]
if out != [10 [20 30] 40] [ err 'rewrite-tree' ] else [ .ok ]

Module diff

Exported Structs & Interfaces

  • DiffLine: DiffLine = struct { op enum, text str, old_line i64, new_line i64 } — One entry in a computed line diff (op = .eq, .del, or .add).

Exported Functions

SymbolSignatureDescription
diff-linesdiff-lines = fn [old_text str, new_text str] block[DiffLine]Computes a minimal line-by-line diff between strings old_text and new_text.
equal?equal? = fn [ops block[DiffLine]] boolReturns true if ops contains no additions or deletions.
format-unifiedformat-unified = fn [old_name str, new_name str, old_text str, new_text str] strFormats a unified diff string (--- old_name\n+++ new_name\n...) or '' when identical.

Verified Doctest (diff/diff-lines)

VEKO
use [diff]
ops = diff/diff-lines 'a\nb\nc' 'a\nx\nc\nd'
if (diff/equal? ops) [ err 'diff equal' ] else [ .ok ]

Module fmt

Exported Functions

SymbolSignatureDescription
int-radixint-radix = fn [n i64, base i64] strFormats a signed integer n in the given base (2..36).
pad-leftpad-left = fn [s str, width i64, pad_ch str] strPads s on the left with pad_ch (1-byte string) to reach width bytes.
pad-rightpad-right = fn [s str, width i64, pad_ch str] strPads s on the right with pad_ch (1-byte string) to reach width bytes.
hexhex = fn [n i64, width i64] strFormats a non-negative integer n as zero-padded lowercase hexadecimal of at least width chars.
hex-byteshex-bytes = fn [data bytes] strFormats a bytes buffer as a lowercase hexadecimal string.
sizesize = fn [n i64] strFormats a byte count into a human-readable IEC size string (B, KiB, MiB, GiB, TiB).
durdur = fn [ns i64] strFormats a duration in nanoseconds into a readable unit string (ns, us, ms, s, m/s).
formatformat = fn [tpl str, args block] strFormats tpl using positional placeholders ({0}, {1}, or auto-numbered {}). Double braces {{ and }} emit literal braces.
templatetemplate = fn [tpl str, vars map] strFormats tpl using named {key} placeholders looked up in vars. Double braces {{ and }} emit literal braces.
hexdumphexdump = fn [data bytes, cols i64] strRenders a canonical offset + hex + ASCII hexdump of data with cols bytes per row.
tabletable = fn [headers block[str], rows block] strRenders a clean padded ASCII table from headers (block[str]) and rows (block[block[str]]).

Verified Doctest (fmt/int-radix)

VEKO
use [fmt]
r1 = fmt/int-radix 255 16
r2 = fmt/int-radix -42 2
if r1 != 'ff' or r2 != '-101010' [ err 'fmt/int-radix mismatch' ] else [ .ok ]

Module fs

Exported Functions

SymbolSignatureDescription
exists?exists? = fn [p str] boolReturns true if p exists on the filesystem.
dir?dir? = fn [p str] boolReturns true if p exists and is a directory.
file?file? = fn [p str] boolReturns true if p exists and is a regular file (not a directory).
mkdir-allmkdir-all = fn [p str] enumRecursively creates directory p and all missing parent directories (idempotent).
remove-allremove-all = fn [p str] enumRecursively removes a file or directory tree (no-op if p does not exist).
walk-dirwalk-dir = fn [root_dir str] block[str]Recursively collects all file paths beneath root_dir.
glob-dirglob-dir = fn [root_dir str, pattern str] block[str]Recursively collects all file paths beneath root_dir whose basename or relative path matches pattern.
write-atomicwrite-atomic = fn [dst_path str, data bytes] i64Atomically writes data to dst_path via a sibling temporary file, os/fsync, and os/rename.
copy-filecopy-file = fn [src_path str, dst_path str] i64Copies src_path to dst_path atomically, returning the number of bytes copied.
with-temp-dirwith-temp-dir = fn [prefix str, work fn[str->any]] anyCreates a unique temporary directory under os/temp-dir, invokes (work dir_path), and removes the directory via defer.
list-entrieslist-entries = fn [dir_path str] block[map]Lists entries in dir_path as { name = str, is_dir = bool, size = i64 } maps (ready for ui/widgets/entries-from-list).

Verified Doctest (fs/mkdir-all)

VEKO
use [fs]
base = str/join [(os/temp-dir) '/veko_fs_dt_mkdir'] ''
_ = fs/remove-all base
leaf = str/join [base '/a/b/c'] ''
_ = fs/mkdir-all leaf
ok = fs/dir? leaf
_ = fs/remove-all base
if not ok [ err 'mkdir-all' ] else [ .ok ]

Module glob

Exported Functions

SymbolSignatureDescription
match?match? = fn [pattern str, target str] boolMatches target against glob pattern (* matches non-/, ** matches across /, ? matches one non-/, [abc]/[a-z]/[!0-9] matches a character class).
filterfilter = fn [pattern str, paths block[str]] block[str]Filters paths returning all strings matching glob pattern.

Verified Doctest (glob/match?)

VEKO
use [glob]
a = glob/match? 'src/**/*.vk' 'src/crypto/sha256.vk'
b = glob/match? 'lib/*.vk' 'lib/sub/a.vk'
c = glob/match? 'file_[0-9].txt' 'file_7.txt'
if (not a) or b or (not c) [ err 'glob/match?' ] else [ .ok ]

Module io/fs

Exported Structs & Interfaces

  • FileStreamState: FileStreamState = struct { fd i64, path str, pos i64 = ... } — Backing state for a positioned file-backed io/Stream.

Exported Functions

SymbolSignatureDescription
open-fileopen-file = fn [path str, mode str] io/StreamOpens path with mode ('r', 'w', 'rw', or 'a') and wraps the handle in an io/Stream.
open-readopen-read = fn [path str] io/StreamOpens path read-only as an io/Stream.
open-writeopen-write = fn [path str] io/StreamOpens path for writing (creating or truncating) as an io/Stream.
seekseek = fn [mut s io/Stream, offset i64] i64Seeks a file-backed io/Stream s to absolute byte offset.
syncsync = fn [s io/Stream] enumFlushes a file-backed io/Stream s to durable storage via os/fsync.
pread-exactpread-exact = fn [fd i64, offset i64, n i64] bytesReads exact n bytes at offset from raw positioned handle fd (errors on short read/EOF).
pwrite-allpwrite-all = fn [fd i64, offset i64, data bytes] i64Writes all bytes of data at offset to raw positioned handle fd.

Verified Doctest (io/fs/open-file)

VEKO
use [io, ifs = io/fs]
p = 'dist/.doctest_io_fs.bin'
mut ws = ifs/open-file p 'w'
_ = io/write-all mut ws (bytes/from-str 'stream-disk-ok')
_ = io/close mut ws
mut rs = ifs/open-file p 'r'
got = io/read-all mut rs
_ = io/close mut rs
_ = os/remove/or p [ .ok ]
if (bytes/to-str got) != 'stream-disk-ok' [ err 'io/fs open-file' ] else [ .ok ]

Module io/net

Exported Structs & Interfaces

  • TcpStreamState: TcpStreamState = struct { sock i64, peer str } — Backing state for a TCP socket-backed io/Stream.

Exported Functions

SymbolSignatureDescription
tcp-streamtcp-stream = fn [sock i64, peer str] io/StreamWraps an existing connected TCP socket handle sock in an io/Stream.
resolve-ipv4resolve-ipv4 = fn [host str] block[str]Resolves host to IPv4 addresses using .net-only primitives (localhost, numeric IPv4, net/resolve, and pure-Veko UDP DNS fallback).
dial-tcp-timeoutdial-tcp-timeout = fn [host str, port i64, timeout dur] io/StreamDials a TCP connection to host:port with an enforced timeout duration and returns an io/Stream.
dial-tcpdial-tcp = fn [host str, port i64] io/StreamDials a TCP connection to host:port with a default 10s deadline and returns an io/Stream.
stream-socketstream-socket = fn [s io/Stream] i64Returns the underlying OS socket handle from a TCP-backed io/Stream.
set-timeoutset-timeout = fn [s io/Stream, timeout dur] enumApplies a read/write deadline timeout to a TCP-backed io/Stream.
poll-streamspoll-streams = fn [streams block[io/Stream], timeout dur] blockPolls streams (block[io/Stream]) for readability up to timeout and returns indices of ready streams.
set-nonblockset-nonblock = fn [sock i64, enabled bool] enumToggles non-blocking mode (O_NONBLOCK / FIONBIO) on OS socket sock.
listen-nonblocklisten-nonblock = fn [addr str] i64Binds a TCP listener on addr ('127.0.0.1:0') and enables non-blocking mode.
dial-tcp-nonblockdial-tcp-nonblock = fn [host str, port i64] i64Starts a non-blocking TCP connection to host:port (returns socket handle in connecting/connected state).
sock-errorsock-error = fn [sock i64] i64Reads SO_ERROR on sock (returns 0 when healthy/connected, or non-zero OS error code).
try-accepttry-accept = fn [ln i64] i64Non-blocking accept on listener ln: returns >= 0 client socket, -1 if would-block, or err.
try-read-intotry-read-into = fn [sock i64, mut buf bytes, max_n i64] i64Non-blocking read appending up to max_n bytes into mut buf. Returns > 0 bytes read, 0 on clean peer EOF, -1 if would-block, or err.
try-writetry-write = fn [sock i64, data bytes] i64Non-blocking write of data on sock: returns >= 0 bytes written, -1 if would-block, or err.
try-write-fromtry-write-from = fn [sock i64, data bytes, offset i64] i64Non-blocking write of data[offset..(len data)] on sock.

Verified Doctest (io/net/tcp-stream)

VEKO
use [io, inet = io/net]
s = inet/tcp-stream 42 '127.0.0.1:8080'
if s.name != 'tcp://127.0.0.1:8080' or (inet/stream-socket s) != 42 [ err 'io/net' ] else [ .ok ]

Module io/open

Exported Functions

SymbolSignatureDescription
default-muxdefault-mux = fn [] io/SchemeMuxOpens a SchemeMux pre-registered with mem://, file://, tcp://, tls://, http://, and https://.
openopen = fn [uri str] io/StreamConvenience wrapper that opens any mem://, file://, tcp://, tls://, http://, or https:// URI as an io/Stream.

Verified Doctest (io/open/default-mux)

VEKO
use [io, iopen = io/open]
mux = iopen/default-mux
mut s = io/mux-open mux 'mem://hello-open'
got = io/read-all mut s
if (bytes/to-str got) != 'hello-open' [ err 'io/open mem' ] else [ .ok ]

Module io

Exported Structs & Interfaces

  • ReadStep: ReadStep = struct { chunk bytes, state any } — Result of a single stream read step carrying the read chunk and updated ORO stream state.
  • WriteStep: WriteStep = struct { written i64, state any } — Result of a single stream write step carrying bytes written and updated ORO stream state.
  • Stream: Stream = struct { name str, closed bool = ..., state any = ..., read_step fn[any,i64->ReadStep], write_step fn[any,bytes->WriteStep], close_step fn[any->any] } — Generic byte stream supporting read, write, and close over ORO value state.
  • MemState: MemState = struct { buf bytes, pos i64 = ... } — Internal backing state for io/mem-stream.
  • SchemeMux: SchemeMux = struct { openers map[fn[str->Stream]] = ... } — URI scheme multiplexer mapping scheme names (such as 'mem') to stream opener closures.

Exported Functions

SymbolSignatureDescription
mem-streammem-stream = fn [initial bytes] StreamCreates an in-memory read/write Stream initialized with initial bytes.
readread = fn [mut s Stream, max_n i64] bytesReads up to max_n bytes from s (returns empty bytes on EOF).
writewrite = fn [mut s Stream, data bytes] i64Writes data to s, returning the number of bytes written.
closeclose = fn [mut s Stream] enumCloses s cleanly and returns .ok.
read-allread-all = fn [mut s Stream] bytesReads all remaining bytes from s until EOF.
write-allwrite-all = fn [mut s Stream, data bytes] i64Writes every byte of data to s, looping on short writes.
copycopy = fn [mut src Stream, mut dst Stream, chunk_size i64] i64Copies all remaining bytes from src into dst in chunk_size slices, returning total bytes copied.
mux-newmux-new = fn [] SchemeMuxCreates an empty SchemeMux.
mux-registermux-register = fn [mut mux SchemeMux, scheme str, opener fn[str->Stream]] i64Registers a scheme handler opener = fn [rest str] Stream [ ... ] under scheme.
mux-defaultmux-default = fn [] SchemeMuxCreates a default SchemeMux pre-registered with mem://<initial-utf8>.
mux-openmux-open = fn [mux SchemeMux, uri str] StreamOpens a Stream for uri (e.g. 'mem://payload') by dispatching on the URI scheme before ://.

Verified Doctest (io/mem-stream)

VEKO
use [io]
mut s = io/mem-stream (bytes/from-str 'hello ')
_ = io/write mut s (bytes/from-str 'veko')
all = io/read-all mut s
if (bytes/to-str all) != 'hello veko' [ err 'io mem-stream' ] else [ .ok ]

Module math

Exported Functions

SymbolSignatureDescription
pipi = fn [] f64Circle constant pi (folded at compile time).
tautau = fn [] f64Full turn tau = 2 * pi (folded at compile time).
ee = fn [] f64Euler's number e (folded at compile time).
ln2ln2 = fn [] f64Natural logarithm of 2 (folded at compile time).
sqrt2sqrt2 = fn [] f64Square root of 2 (folded at compile time).
i64-maxi64-max = fn [] i64Maximum signed 64-bit integer (2^63 - 1, folded at compile time).
i64-mini64-min = fn [] i64Minimum signed 64-bit integer (-2^63).
abs-i64abs-i64 = fn [x i64] i64Absolute value of x (returns x for i64-min).
min-i64min-i64 = fn [a i64, b i64] i64Smaller of two signed 64-bit integers.
max-i64max-i64 = fn [a i64, b i64] i64Larger of two signed 64-bit integers.
clamp-i64clamp-i64 = fn [x i64, lo i64, hi i64] i64Clamps x to the inclusive range [lo, hi].
add-checkedadd-checked = fn [a i64, b i64] i64Checked 64-bit signed addition; returns err on overflow.
sub-checkedsub-checked = fn [a i64, b i64] i64Checked 64-bit signed subtraction; returns err on overflow.
mul-checkedmul-checked = fn [a i64, b i64] i64Checked 64-bit signed multiplication; returns err on overflow.
add-satadd-sat = fn [a i64, b i64] i64Saturating 64-bit signed addition (clamps at i64-min / i64-max).
sub-satsub-sat = fn [a i64, b i64] i64Saturating 64-bit signed subtraction (clamps at i64-min / i64-max).
gcdgcd = fn [a i64, b i64] i64Greatest common divisor of a and b (non-negative).
lcmlcm = fn [a i64, b i64] i64Least common multiple of a and b (0 if either argument is 0).
pow-i64pow-i64 = fn [base i64, exp i64] i64Integer exponentiation base ^ exp for exp >= 0.
isqrtisqrt = fn [n i64] i64Integer floor square root of n >= 0.
popcountpopcount = fn [x i64] i64Counts the number of 1-bits in the 64-bit representation of x.
clzclz = fn [x i64] i64Counts leading zero bits in the 64-bit unsigned representation of x (64 for x == 0).
ctzctz = fn [x i64] i64Counts trailing zero bits in the 64-bit representation of x (64 for x == 0).
rotl64rotl64 = fn [x i64, r i64] i64Rotates a 64-bit word left by r bits (mod 64).
rotr64rotr64 = fn [x i64, r i64] i64Rotates a 64-bit word right by r bits (mod 64).
rotl32rotl32 = fn [x i64, r i64] i64Rotates a 32-bit unsigned word left by r bits (mod 32).
rotr32rotr32 = fn [x i64, r i64] i64Rotates a 32-bit unsigned word right by r bits (mod 32).
abs-f64abs-f64 = fn [x f64] f64Absolute value of x.
min-f64min-f64 = fn [a f64, b f64] f64Smaller of two f64 values.
max-f64max-f64 = fn [a f64, b f64] f64Larger of two f64 values.
clamp-f64clamp-f64 = fn [x f64, lo f64, hi f64] f64Clamps x to [lo, hi].
isnan?isnan? = fn [x f64] boolReturns true if x is IEEE-754 NaN.
isinf?isinf? = fn [x f64] boolReturns true if x is positive or negative infinity.
trunctrunc = fn [x f64] f64Truncates x toward zero.
floorfloor = fn [x f64] f64Largest integer <= x as f64.
ceilceil = fn [x f64] f64Smallest integer >= x as f64.
roundround = fn [x f64] f64Rounds x to the nearest integer (halfway away from zero).
sqrtsqrt = fn [x f64] f64Double-precision square root lowered to hardware f64/sqrt (sqrtsd / f64.sqrt / fsqrt).
expexp = fn [x f64] f64Exponential function e^x.
lnln = fn [x f64] f64Natural logarithm ln(x) for x > 0.
log2log2 = fn [x f64] f64Base-2 logarithm log2(x).
log10log10 = fn [x f64] f64Base-10 logarithm log10(x).
powpow = fn [base f64, exponent f64] f64Floating-point power base^exponent.
sinsin = fn [x f64] f64Sine of x in radians.
coscos = fn [x f64] f64Cosine of x in radians.
tantan = fn [x f64] f64Tangent of x in radians.
atanatan = fn [x f64] f64Arctangent of x in radians ([-pi/2, pi/2]).
atan2atan2 = fn [y f64, x f64] f64Two-argument arctangent atan2(y, x) in radians ([-pi, pi]).

Verified Doctest (math/clamp-i64)

VEKO
use [m = math]
if (m/clamp-i64 15 0 10) != 10 or (m/clamp-i64 -3 0 10) != 0 [ err 'clamp-i64' ] else [ .ok ]

Module path

Exported Functions

SymbolSignatureDescription
is-abs?is-abs? = fn [p str] boolReturns true if p is an absolute POSIX (/a/b) or Windows drive (C:/a/b) path.
normalizenormalize = fn [p str] strLexically normalizes p, converting backslashes to /, collapsing duplicate slashes, and resolving . and .. segments cleanly.
joinjoin = fn [a str, b str] strJoins two path segments a and b and normalizes the result.
join-alljoin-all = fn [parts block[str]] strJoins a block of path segments and normalizes the result.
split-partssplit-parts = fn [p str] block[str]Splits a normalized path into its non-empty path segments.
dirdir = fn [p str] strReturns the parent directory portion of p.
basebase = fn [p str] strReturns the final filename component of p.
extext = fn [p str] strReturns the file extension including the leading . (or '' if none).
stemstem = fn [p str] strReturns the base filename without its final extension.
with-extwith-ext = fn [p str, new_ext str] strReplaces (or appends) the file extension of p with new_ext (with or without leading .).
confineconfine = fn [root str, rel str] strSafely resolves rel inside root, returning err if rel is absolute or escapes root via ...

Verified Doctest (path/normalize)

VEKO
use [path]
if (path/normalize 'a/b/../c/./d.vk') != 'a/c/d.vk' [ err 'normalize' ] else [ .ok ]

Module rand

Exported Structs & Interfaces

  • Rng: Rng = struct { s0 i64, s1 i64, s2 i64, s3 i64 } — Deterministic xoshiro256++ pseudo-random number generator (256-bit state). Not for cryptographic keys; use rand/csprng-bytes or random/bytes for cryptography.

Exported Functions

SymbolSignatureDescription
splitmix64-stepsplitmix64-step = fn [seed i64] mapOne SplitMix64 mixing step returning { val = i64, next_seed = i64 }.
seedseed = fn [seed_val i64] RngSeeds a deterministic xoshiro256++ Rng from a 64-bit seed via SplitMix64.
next-u64next-u64 = fn [mut r Rng] i64Advances r using xoshiro256++ and returns the next 64-bit word.
rangerange = fn [mut r Rng, lo i64, hi i64] i64Returns a pseudo-random integer uniformly in [lo, hi) (lo < hi).
f64-unitf64-unit = fn [mut r Rng] f64Returns a uniform f64 in [0.0, 1.0) using 53 bits of precision.
bytes-fillbytes-fill = fn [mut r Rng, n i64] bytesProduces n pseudo-random bytes from r.
shuffleshuffle = fn [mut r Rng, mut xs block] i64In-place Fisher-Yates shuffle of xs using r.
choosechoose = fn [mut r Rng, xs block] anyPicks a random element from non-empty block xs.
csprng-bytescsprng-bytes = fn [n i64] bytesReturns n cryptographically secure random bytes from the OS/hardware CSPRNG (random/bytes).
uuid-v4uuid-v4 = fn [] strGenerates a random RFC 4122 Version 4 UUID string (xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx) using the OS/hardware CSPRNG.
uuid-v7-atuuid-v7-at = fn [unix_ms i64] strGenerates an RFC 9562 time-ordered Version 7 UUID string (xxxxxxxx-xxxx-7xxx-yxxx-xxxxxxxxxxxx) from a caller-provided 48-bit Unix millisecond timestamp unix_ms and OS CSPRNG entropy.
uuid-v7uuid-v7 = fn [] strGenerates an RFC 9562 Version 7 UUID using the live UTC wall clock (time/unix) and OS CSPRNG.

Verified Doctest (rand/seed)

VEKO
use [rand]
mut r1 = rand/seed 42
mut r2 = rand/seed 42
a = rand/next-u64 mut r1
b = rand/next-u64 mut r2
if a != b or a == 0 [ err 'rand/seed' ] else [ .ok ]

Module regex

Exported Structs & Interfaces

  • NfaState: NfaState = struct { op i64, arg i64 = ..., out1 i64 = ..., out2 i64 = ... } — Single Thompson NFA state node.
  • CharClass: CharClass = struct { negated bool = ..., ranges block = ... } — Character class specification (negated + list of [lo, hi] byte ranges).
  • Regex: Regex = struct { pattern str, states block[NfaState], classes block[CharClass], start i64 } — Compiled Thompson NFA regular expression.
  • Match: Match = struct { text str, start i64, end i64 } — A matched substring span [start, end) within the input string.

Exported Functions

SymbolSignatureDescription
compilecompile = fn [pattern str] RegexCompiles a regular expression pattern into a linear-time Thompson NFA Regex.
findfind = fn [rx Regex, input str] MatchFinds the first match of rx anywhere in input, or returns err 'regex/find: no match'.
is-match?is-match? = fn [rx Regex, input str] boolReturns true if rx matches anywhere inside input.
find-allfind-all = fn [rx Regex, input str] block[Match]Finds all non-overlapping matches of rx in input.
replace-allreplace-all = fn [rx Regex, input str, replacement str] strReplaces every non-overlapping match of rx in input with replacement.

Verified Doctest (regex/compile)

VEKO
use [re = regex]
rx = re/compile '^[a-z]+-[0-9]+$'
if (not (re/is-match? rx 'veko-10')) or (re/is-match? rx 'Veko-10') [ err 'regex' ] else [ .ok ]

Module retry

Exported Structs & Interfaces

  • RetryOpts: RetryOpts = struct { max_attempts i64 = ..., base_delay dur = ..., max_delay dur = ..., jitter_pct i64 = ... } — Retry policy configuration with sensible defaults.
  • RateLimiter: RateLimiter = struct { capacity i64, tokens i64, refill_per_sec i64, last_ns i64 } — Token-bucket rate limiter (monotonic clock backed via time/now).

Exported Functions

SymbolSignatureDescription
backoff-delaybackoff-delay = fn [opts RetryOpts, attempt i64] durComputes the deterministic exponential backoff delay (in dur) for 0-based attempt.
runrun = fn [opts RetryOpts, action fn[i64->any]] anyExecutes action (fn [attempt i64] any) up to opts.max_attempts times until it returns a non-err result.
limiter-newlimiter-new = fn [capacity i64, refill_per_sec i64] RateLimiterCreates a new full token-bucket RateLimiter with capacity burst tokens refilling at refill_per_sec.
allow-at?allow-at? = fn [mut rl RateLimiter, cost i64, now_ns i64] boolAttempts to consume cost tokens at timestamp now_ns, returning true if allowed.
allow?allow? = fn [mut rl RateLimiter, cost i64] boolAttempts to consume cost tokens using the current monotonic clock (time/now).

Verified Doctest (retry/backoff-delay)

VEKO
use [retry]
opts = retry/RetryOpts { base_delay = 50ms, max_delay = 300ms, jitter_pct = 0 }
if (retry/backoff-delay opts 0) != 50ms or (retry/backoff-delay opts 2) != 200ms or (retry/backoff-delay opts 4) != 300ms [
  err 'backoff'
] else [ .ok ]

Module semver

Exported Structs & Interfaces

  • SemVer: SemVer = struct { major i64, minor i64, patch i64, pre str = ..., build str = ... } — Structured SemVer 2.0.0 version (major.minor.patch[-pre][+build]).

Exported Functions

SymbolSignatureDescription
parseparse = fn [raw_s str] SemVerParses a SemVer 2.0.0 string (accepts optional leading 'v').
formatformat = fn [v SemVer] strFormats a SemVer back into canonical 'MAJOR.MINOR.PATCH[-pre][+build]'.
comparecompare = fn [a SemVer, b SemVer] i64Compares two SemVer values per SemVer 2.0.0 precedence (-1, 0, or 1; ignores +build).
bump-majorbump-major = fn [v SemVer] SemVerExported semver/bump-major operation.
bump-minorbump-minor = fn [v SemVer] SemVerExported semver/bump-minor operation.
bump-patchbump-patch = fn [v SemVer] SemVerExported semver/bump-patch operation.
satisfies?satisfies? = fn [v SemVer, constraint str] boolReturns true if v satisfies a comma-separated SemVer constraint (e.g. '^1.2.0', '~1.2.3', '>=1.0.0, <2.0.0').

Verified Doctest (semver/parse)

VEKO
use [sv = semver]
v = sv/parse 'v1.4.2-rc.1+build.9'
if v.major != 1 or v.minor != 4 or v.patch != 2 or v.pre != 'rc.1' or v.build != 'build.9' [
  err 'semver parse'
] else [ .ok ]

Module seq

Exported Functions

SymbolSignatureDescription
reversereverse = fn [xs block] blockReturns a new block containing the elements of xs in reverse order.
taketake = fn [xs block, k i64] blockReturns the first k elements of xs (clamped to [0, len xs]).
dropdrop = fn [xs block, k i64] blockDrops the first k elements of xs and returns the remainder.
foldfold = fn [xs block, init any, step fn[any,any->any]] anyLeft-folds xs starting from init using step = fn [acc, elem] [ ... ].
any?any? = fn [xs block, pred fn[any->bool]] boolReturns true if pred holds for at least one element in xs.
all?all? = fn [xs block, pred fn[any->bool]] boolReturns true if pred holds for every element in xs.
findfind = fn [xs block, pred fn[any->bool]] anyReturns the first element matching pred, or err 'seq/find: not found' (combine with /or).
partitionpartition = fn [xs block, pred fn[any->bool]] mapSplits xs into { yes = [...], no = [...] } according to pred.
uniqueunique = fn [xs block] blockRemoves duplicate scalar/hashable elements from xs, preserving first-seen order.
chunkchunk = fn [xs block, size i64] blockSplits xs into consecutive chunks of length size (last chunk may be shorter).
zipzip = fn [a block, b block] blockZips two blocks a and b into pairs [ [a0 b0] [a1 b1] ... ] up to min(len a, len b).
enumerateenumerate = fn [xs block] blockProduces [ [0 xs[0]] [1 xs[1]] ... ].
flattenflatten = fn [xs block] blockFlattens one level of nested blocks into a single block.
group-bygroup-by = fn [xs block, key_fn fn[any->str]] mapGroups elements of xs into a map keyed by (key-fn elem).
count-bycount-by = fn [xs block, key_fn fn[any->str]] mapCounts elements of xs per key produced by (key-fn elem).
range-seqrange-seq = fn [start i64, stop i64, step i64] block[i64]Generates an integer sequence [start, start + step, ...] stopping before stop.
sort-bysort-by = fn [xs block, cmp fn[any,any->i64]] blockStable O(N log N) merge sort using comparator cmp = fn [a, b] i64 [ ... ] (< 0, 0, > 0).
sortsort = fn [xs block] blockStable O(N log N) ascending sort for ordered scalars (i64, f64, or str).
binary-searchbinary-search = fn [xs block, target any] i64Binary search on a sorted block xs; returns index >= 0 if found or -1 otherwise.

Verified Doctest (seq/reverse)

VEKO
use [seq]
if (seq/reverse [1 2 3]) != [3 2 1] [ err 'reverse' ] else [ .ok ]

Module slog

Exported Structs & Interfaces

  • Logger: Logger = struct { level enum = ..., format enum = ..., fields map = ..., use_clock bool = ... } — Immutable structured logger configuration (clone & extend cleanly with with-level / with-fields).

Exported Functions

SymbolSignatureDescription
new-jsonnew-json = fn [min_level enum] LoggerCreates a JSON structured logger with the given minimum level (.debug, .info, .warn, .error).
new-kvnew-kv = fn [min_level enum] LoggerCreates a human-readable key=value (kv) structured logger with the given minimum level.
with-levelwith-level = fn [lg Logger, min_level enum] LoggerReturns a child logger with an updated minimum log level.
with-fieldswith-fields = fn [lg Logger, extra map] LoggerReturns a child logger with additional contextual key/value fields merged in.
enabled?enabled? = fn [lg Logger, lvl enum] boolReturns true if lvl meets or exceeds lg.level.
format-lineformat-line = fn [lg Logger, lvl enum, msg str, extra map] strFormats a single structured log line (without emitting I/O — ideal for testing and custom sinks).
emitemit = fn [lg Logger, lvl enum, msg str, extra map] enumEmits a structured log line to os/stderr if lvl is enabled on lg.
emit-streamemit-stream = fn [lg Logger, mut stream io/Stream, lvl enum, msg str, extra map] enumEmits a structured log line to any io/Stream if lvl is enabled on lg.
debugdebug = fn [lg Logger, msg str, extra map] enumConvenience level emitters targeting os/stderr.
infoinfo = fn [lg Logger, msg str, extra map] enumExported slog/info operation.
warnwarn = fn [lg Logger, msg str, extra map] enumExported slog/warn operation.
errorerror = fn [lg Logger, msg str, extra map] enumExported slog/error operation.

Verified Doctest (slog/format-line)

VEKO
use [slog]
lg = (slog/new-kv .debug) \ struct/with { use_clock = false } \ slog/with-fields { svc = 'api' }
line = slog/format-line lg .info 'ready' { port = 8080 }
if (not (str/contains? line 'level=INFO')) or (not (str/contains? line 'svc=api')) or (not (str/contains? line 'port=8080')) [
  err 'slog format'
] else [ .ok ]

Module template

Exported Functions

SymbolSignatureDescription
escape-htmlescape-html = fn [s str] strEscapes HTML entities (&, <, >, ", ').
render-htmlrender-html = fn [tpl str, ctx map] strRenders tpl against ctx with automatic HTML escaping on {{ expr }} ({{{ raw }}} opts out).
render-textrender-text = fn [tpl str, ctx map] strRenders tpl against ctx as plain text (no HTML escaping).

Verified Doctest (template/render-html)

VEKO
use [tpl = template]
out = tpl/render-html '<h1>{{ user.name }}</h1>{{#if admin}}<ul>{{#each tags}}<li>{{ . }}</li>{{/each}}</ul>{{/if}}' { user = { name = '<Ada>' }, admin = true, tags = ['oro' 'pqc'] }
if out != '<h1>&lt;Ada&gt;</h1><ul><li>oro</li><li>pqc</li></ul>' [ err 'template html' ] else [ .ok ]

Module testing/fuzz

Exported Structs & Interfaces

  • FuzzConfig: FuzzConfig = struct { seed i64 = ..., runs i64 = ..., max_len i64 = ... } — Configuration for a deterministic fuzzing campaign.
  • FuzzResult: FuzzResult = struct { ok bool = ..., runs i64 = ..., seed i64 = ..., failing_input any = ..., shrunk_input any = ..., shrink_steps i64 = ..., failure_msg str = ... } — Outcome of a fuzzing run, including the minimal delta-debugged counterexample on failure.

Exported Functions

SymbolSignatureDescription
next-u64next-u64 = fn [state i64] StepU64Advances a 64-bit SplitMix64 state and returns StepU64 { state, val }.
fuzz-bytesfuzz-bytes = fn [cfg FuzzConfig, prop fn[bytes->any]] FuzzResultFuzzes prop over boundary byte vectors and cfg.runs pseudo-random bytes slices, shrinking any failing input to its minimal reproducing byte sequence.
fuzz-strfuzz-str = fn [cfg FuzzConfig, prop fn[str->any]] FuzzResultFuzzes prop over boundary strings and cfg.runs valid UTF-8 / delimiter strings, shrinking any failure down to the minimal failing UTF-8 string.
fuzz-blockfuzz-block = fn [cfg FuzzConfig, prop fn[block->any]] FuzzResultFuzzes prop over structured homoiconic Veko blocks (i64, str, bool, .enum, and nested [ ... ] sub-blocks) and shrinks any failure to the minimal failing block.
assert-fuzzassert-fuzz = fn [res FuzzResult, label str] anyReturns .ok if res.ok == true, or a formatted err describing the seed and minimal counterexample.

Verified Doctest (testing/fuzz/fuzz-bytes)

VEKO
use [fz = testing/fuzz]
cfg = fz/FuzzConfig { seed = 42, runs = 80, max_len = 32 }
ok_res = fz/fuzz-bytes cfg fn [b bytes] any [ (len b) <= 32 ]
if not ok_res.ok [ return (err 'expected ok_res to pass') ]
// Plant a bug triggered whenever consecutive bytes [0xfe 0xff] or byte >= 200 appear
bad = fz/fuzz-bytes cfg fn [b bytes] any [
    mut i = 0
    while i < (len b) [
        if b[i] >= 200 [ return (err 'high byte boom') ]
        i = i + 1
    ]
    true
]
if bad.ok or (len bad.shrunk_input) != 1 [ err 'expected shrunk 1-byte reproducer' ] else [ .ok ]

Module testing

Exported Structs & Interfaces

  • Suite: Suite = struct { name str, passed i64 = ..., failed i64 = ..., failures block[str] = ... } — Mutable test suite accumulator tracking pass/fail counts and failure diagnostics.
  • BenchResult: BenchResult = struct { name str, iters i64, total_ns i64, ns_per_op i64 } — Timing result returned by testing/bench.

Exported Functions

SymbolSignatureDescription
newnew = fn [name str] SuiteCreates a new empty test Suite with the given name.
okok = fn [mut s Suite, cond bool, label str] boolAsserts that cond is true.
eqeq = fn [mut s Suite, actual any, expected any, label str] boolAsserts that actual == expected.
neqneq = fn [mut s Suite, actual any, unexpected any, label str] boolAsserts that actual != unexpected.
is-erris-err = fn [mut s Suite, val any, label str] boolAsserts that val is a Veko err.
is-okis-ok = fn [mut s Suite, val any, label str] boolAsserts that val is not a Veko err.
approxapprox = fn [mut s Suite, actual f64, expected f64, eps f64, label str] boolAsserts that two floats are within eps (|actual - expected| <= eps).
finishfinish = fn [s Suite] i64Finalizes a Suite, returning 0 when all assertions passed or an err summarizing failures.
reportreport = fn [s Suite] i64Prints a compact single-line summary for s and returns finish s.
benchbench = fn [name str, iters i64, work fn[->any]] BenchResultExecutes work iters times and returns monotonic timing measurements (BenchResult).

Verified Doctest (testing/new)

VEKO
use [t = testing]
mut s = t/new 'math-smoke'
_ = t/eq mut s (2 + 2) 4 'addition'
r = t/finish s
if err? r [ r ] else [ .ok ]

Module text/re

Exported Structs & Interfaces

  • NfaInst: NfaInst = struct { op i64, ch i64 = ..., out i64 = ..., out1 i64 = ..., cset bytes = ..., neg bool = ... } — Single compiled Thompson NFA instruction.
  • Regex: Regex = struct { pattern str, insts block[NfaInst], start_pc i64 } — Compiled regular expression automaton.
  • Match: Match = struct { start i64, end i64, text str } — Byte-span match result (start..end slice of the input string).

Exported Functions

SymbolSignatureDescription
compilecompile = fn [pattern str] RegexCompiles pattern into a linear-time Regex NFA (returns err on invalid syntax; combine with /or).
is-match?is-match? = fn [rx Regex, text str] boolReturns true if rx matches anywhere inside text.
match?match? = fn [pattern str, text str] boolConvenience one-shot match test compiling pattern and testing text.
findfind = fn [rx Regex, text str] MatchFinds the leftmost match of rx in text, or returns err if not found (combine with /or).
find-allfind-all = fn [rx Regex, text str] block[Match]Finds all non-overlapping matches of rx in text.
replace-allreplace-all = fn [rx Regex, text str, replacement str] strReplaces all non-overlapping matches of rx in text with replacement.
splitsplit = fn [rx Regex, text str] block[str]Splits text around non-overlapping non-empty matches of rx.

Verified Doctest (text/re/compile)

VEKO
use [re = text/re]
rx = re/compile 'v[0-9]+\\.[0-9]+'
ms = re/find-all rx 'release v1.0 and v2.14 ready'
if (len ms) != 2 or ms[0].text != 'v1.0' or ms[1].text != 'v2.14' [ err 're find-all' ] else [ .ok ]

Module text

Exported Functions

SymbolSignatureDescription
starts-with?starts-with? = fn [s str, pfx str] boolReturns true if s starts with pfx.
ends-with?ends-with? = fn [s str, sfx str] boolReturns true if s ends with sfx.
contains?contains? = fn [s str, needle str] boolReturns true if s contains needle.
index-ofindex-of = fn [s str, needle str, start i64] i64Finds the first byte index of needle in s starting at start, or -1 if absent.
last-index-oflast-index-of = fn [s str, needle str] i64Finds the last byte index of needle in s, or -1 if absent.
replacereplace = fn [s str, old_s str, new_s str] strReplaces the first occurrence of old_s in s with new_s.
replace-allreplace-all = fn [s str, old_s str, new_s str] strReplaces every non-overlapping occurrence of old_s in s with new_s.
repeatrepeat = fn [s str, count i64] strRepeats s count times ('' if count <= 0).
trim-prefixtrim-prefix = fn [s str, pfx str] strStrips pfx from the start of s if present.
trim-suffixtrim-suffix = fn [s str, sfx str] strStrips sfx from the end of s if present.
lineslines = fn [s str] block[str]Splits s into lines, handling both \n and \r\n.
ascii-space?ascii-space? = fn [b i64] boolReturns true if ASCII byte b is whitespace ( , \t, \r, \n).
ascii-alpha?ascii-alpha? = fn [b i64] boolReturns true if ASCII byte b is an ASCII letter (A..Z or a..z).
ascii-digit?ascii-digit? = fn [b i64] boolReturns true if ASCII byte b is an ASCII decimal digit (0..9).
ascii-alnum?ascii-alnum? = fn [b i64] boolReturns true if ASCII byte b is alphanumeric (A..Z, a..z, 0..9).
ascii-hex?ascii-hex? = fn [b i64] boolReturns true if ASCII byte b is a hexadecimal digit (0..9, a..f, A..F).
wordswords = fn [s str] block[str]Splits s on contiguous ASCII whitespace into non-empty words.
slugifyslugify = fn [s str] strConverts s into a lowercase URL-safe ASCII slug ('Hello, Veko 1.0!' -> 'hello-veko-1-0').
utf8-lenutf8-len = fn [s str] i64Counts Unicode code points in a UTF-8 string s.
utf8-codepointsutf8-codepoints = fn [s str] block[i64]Decodes a UTF-8 string into a block[i64] of Unicode scalar code points.
utf8-from-codepointsutf8-from-codepoints = fn [cps block[i64]] strEncodes a block[i64] of Unicode code points into a UTF-8 str.

Verified Doctest (text/starts-with?)

VEKO
use [text]
if (not (text/starts-with? 'veko-1.0' 'veko')) or (text/starts-with? 'hi' 'hello') [ err 'starts-with' ] else [ .ok ]

Module utf8

Exported Structs & Interfaces

  • RuneStep: RuneStep = struct { codepoint i64, width i64 } — Decoded Unicode codepoint and the number of UTF-8 bytes consumed (1..4).

Exported Functions

SymbolSignatureDescription
decode-runedecode-rune = fn [raw bytes, off i64] RuneStepDecodes one UTF-8 codepoint from raw starting at byte offset off. Rejects overlong encodings, UTF-16 surrogates (0xD800..0xDFFF), and codepoints > 0x10FFFF.
encode-runeencode-rune = fn [cp i64] bytesEncodes a single Unicode scalar value cp into 1..4 UTF-8 bytes.
valid?valid? = fn [raw bytes] boolReturns true if raw consists exclusively of valid RFC 3629 UTF-8 codepoints.
rune-countrune-count = fn [s str] i64Returns the number of Unicode scalar values (runes) in UTF-8 string s.
runesrunes = fn [s str] block[i64]Decodes UTF-8 string s into a block[i64] of Unicode codepoints.
from-runesfrom-runes = fn [cps block[i64]] strEncodes a block[i64] of Unicode codepoints back into a UTF-8 string.
rune-slicerune-slice = fn [s str, start i64, end_idx i64] strSlices string s safely by rune indices [start..end_idx) without ever splitting multi-byte codepoints.

Verified Doctest (utf8/decode-rune)

VEKO
use [utf8]
b = utf8/encode-rune 0x03BB // Greek lambda
st = utf8/decode-rune b 0
if st.codepoint != 0x03BB or st.width != 2 [ err 'decode-rune' ] else [ .ok ]