Standard Library & Builtins Ecosystem

Standard Library Reference

Exhaustive guide to all modular std/... packages, the Terminal UI & CLI framework (std/tui across 11 submodules), scientific math, linear algebra, cryptography, and an exhaustive dictionary of all 182 VM built-in functions.

Standard Library

Modular Standard Library (std/...)

BramandScript adheres to the Lean VM & Modular Standard Library Principle (Rule 12). Rather than polluting the core bytecode execution engine with high-level domain algorithms, capabilities are structured into clean, modular .bmd packages located in the stdlib/ directory.

Natively Resolved Imports

The bytecode compiler automatically resolves import "std/<module>" as <alias> without requiring relative filesystem paths or environment configuration. Modules are compiled once and exported as immutable namespace hashes.

1. std/math — Mathematical Constants & Algorithms

The std/math module delivers high-precision numerical constants and mathematical algorithms implemented directly in BramandScript with zero runtime overhead.

Exported Constants

ConstantTypeValueDescription
PIFLOAT3.141592653589793Ratio of circle circumference to diameter (Archimedes constant).
EFLOAT2.718281828459045Euler's number and base of natural logarithms.
LN2FLOAT0.6931471805599453Natural logarithm of 2.
LN10FLOAT2.302585092994046Natural logarithm of 10.
SQRT2FLOAT1.4142135623730951Square root of 2 (Pythagoras constant).
EPSILONFLOAT2.220446e-16Machine epsilon representing difference between 1.0 and next representable float.

Exported Functions

FunctionSignatureReturnDescription & Edge Cases
minmin(a, b)NUMBERReturns the smaller of two numbers. Compatible with Integer and Float.
maxmax(a, b)NUMBERReturns the greater of two numbers.
clampclamp(val, min_val, max_val)NUMBERClamps val within range [min_val, max_val].
signsign(x)INTEGERReturns 1 if positive, -1 if negative, 0 if zero.
deg_to_raddeg_to_rad(deg)FLOATConverts angle in degrees to radians: deg * (PI / 180.0).
rad_to_degrad_to_deg(rad)FLOATConverts angle in radians to degrees: rad * (180.0 / PI).
is_evenis_even(n)BOOLEANTests if integer n is evenly divisible by 2.
is_oddis_odd(n)BOOLEANTests if integer n is not evenly divisible by 2.
gcdgcd(a, b)INTEGERComputes Greatest Common Divisor using iterative Euclidean algorithm. Handles negative values.
lcmlcm(a, b)INTEGERComputes Least Common Multiple: (a / gcd(a, b)) * b. Returns 0 if either is 0.
factorialfactorial(n)INTEGERComputes n! iteratively without stack recursion. Returns 1 for n <= 1.
sumsum(arr)NUMBERCalculates the arithmetic sum of numbers in an array.
avgavg(arr)FLOATCalculates arithmetic mean. Safely returns 0.0 when array is empty.
bmd — std/math Usage Example
import "std/math" as math

let radius = 5.0
let circle_area = math.PI * radius * radius
println("Circle area:", circle_area)

println("GCD(84, 36):", math.gcd(84, 36))     // 12
println("LCM(12, 18):", math.lcm(12, 18))     // 36
println("5! =", math.factorial(5))             // 120
println("Average:", math.avg([10, 20, 30, 40])) // 25.0

2. std/strings — String Utilities & Transformations

Text manipulation, casing transformations, string padding, slicing, character inspection, and URL slug generation.

Exported Functions

FunctionSignatureReturnDescription & Edge Cases
repeatrepeat(s, count)STRINGRepeats string s by count times. Returns empty string if count <= 0.
pad_leftpad_left(s, len, pad_char)STRINGPads left side of string to target length using single pad character.
pad_rightpad_right(s, len, pad_char)STRINGPads right side of string to target length using single pad character.
char_atchar_at(s, idx)STRINGReturns single character at 0-based index. Returns "" if out of bounds.
sliceslice(s, start, end)STRINGExtracts substring from start up to end with boundary clamping.
starts_withstarts_with(s, prefix)BOOLEANTests if string begins with prefix. Safe when prefix length exceeds string.
ends_withends_with(s, suffix)BOOLEANTests if string ends with suffix. Safe when suffix length exceeds string.
capitalizecapitalize(s)STRINGCapitalizes initial character and preserves remainder. Returns "" on empty input.
reversereverse(s)STRINGReverses string characters.
is_emptyis_empty(s)BOOLEANReturns true if string has zero length after trimming whitespace.
truncatetruncate(s, max_len, suffix)STRINGTruncates string to max length and attaches suffix (e.g. "...").
wordswords(s)ARRAYSplits whitespace-trimmed string into an array of non-empty words.
slugifyslugify(s)STRINGGenerates lower-case hyphen-separated URL slug from input string.
bmd — std/strings Usage Example
import "std/strings" as str

let title = "bramand virtual machine"
println(str.capitalize(title))            // "Bramand virtual machine"
println(str.pad_left("42", 6, "0"))       // "000042"
println(str.slugify("Next Gen VM Engine")) // "next-gen-vm-engine"
println(str.truncate("A very long sentence here", 11, "...")) // "A very long..."

3. std/collections — Functional Primitives & Array Transforms

High-order functional programming utilities: mapping, filtering, reductions, recursive flattening, grouping, chunking, and array manipulation.

Exported Functions

FunctionSignatureReturnDescription & Edge Cases
mapmap(arr, transform)ARRAYTransforms every element using callable transform(elem).
filterfilter(arr, predicate)ARRAYFilters elements where predicate(elem) evaluates to truthy.
reducereduce(arr, accum, initial)ANYFolds array from left with accum(res, elem) starting at initial.
findfind(arr, predicate)ANYReturns first element where predicate(elem) is true, or null.
find_indexfind_index(arr, predicate)INTEGERReturns 0-based index of first matching element, or -1.
everyevery(arr, predicate)BOOLEANReturns true only if predicate(elem) is truthy for all elements.
somesome(arr, predicate)BOOLEANReturns true if predicate(elem) is truthy for at least one element.
contains_itemcontains_item(arr, target)BOOLEANTests if array contains target item using structural equality.
uniqueunique(arr)ARRAYReturns deduplicated array preserving original insertion order.
flattenflatten(arr)ARRAYRecursively flattens arbitrarily nested multi-dimensional arrays into 1D array.
chunkchunk(arr, size)ARRAYSplits array into subarrays of specified size. Returns [] if size <= 0.
zipzip(arr1, arr2)ARRAYPairs corresponding elements into [[a1, b1], [a2, b2], ...] up to shortest length.
taketake(arr, n)ARRAYReturns new array with the first n elements. Clamped to array length.
dropdrop(arr, n)ARRAYReturns new array omitting the first n elements.
countcount(arr, predicate)INTEGERCounts total elements satisfying predicate.
reverse_arrayreverse_array(arr)ARRAYReturns new array in reversed order without mutating original.
group_bygroup_by(arr, key_fn)HASHGroups array elements into hash partitions mapped by key_fn(elem).
key_bykey_by(arr, key_fn)HASHIndexes elements into a hash mapped by unique key from key_fn(elem).
partitionpartition(arr, predicate)ARRAYSplits array into two arrays: [matches, non_matches].
flat_mapflat_map(arr, transform)ARRAYMaps each element using transform function and flattens result by one level.
compactcompact(arr)ARRAYFilters out all null values from array.
sum_bysum_by(arr, fn_num)NUMBERCalculates arithmetic sum of numerical values returned by fn_num(elem).
min_bymin_by(arr, fn_val)ANYReturns array element that yields minimal value under fn_val(elem).
max_bymax_by(arr, fn_val)ANYReturns array element that yields maximal value under fn_val(elem).
frequenciesfrequencies(arr)HASHCounts occurrences of each distinct element, returning frequency map.
differencedifference(arr1, arr2)ARRAYReturns elements in arr1 that do not occur in arr2.
intersectionintersection(arr1, arr2)ARRAYReturns distinct elements present in both arr1 and arr2.
unionunion(arr1, arr2)ARRAYReturns deduplicated combined elements from both arr1 and arr2.
bmd — std/collections Usage Example
import "std/collections" as coll

let numbers = [1, 2, 3, 4, 5, 6, 7, 8]
let evens = coll.filter(numbers, fn(x) { return x % 2 == 0 })
let squared = coll.map(evens, fn(x) { return x * x })
println("Squared evens:", squared) // [4, 16, 36, 64]

// Deep recursive flatten
let nested = [1, [2, [3, [4, 5]]], 6]
println("Flat:", coll.flatten(nested)) // [1, 2, 3, 4, 5, 6]

// Grouping by parity
let grouped = coll.group_by(numbers, fn(x) {
    if x % 2 == 0 { return "even" }
    return "odd"
})
println("Even bucket:", grouped["even"]) // [2, 4, 6, 8]

4. std/json — Safe JSON Encoding & Decoding

Clean JSON deserialization, serialization, and defensive parsing preventing runtime errors.

Exported Functions

FunctionSignatureReturnDescription & Edge Cases
parseparse(raw_str)ANYParses valid JSON text into native BramandScript hash, array, string, number, or boolean.
stringifystringify(val)STRINGSerializes BramandScript objects into a compact JSON string.
safe_parsesafe_parse(raw_str, default_val)ANYParses JSON text; if an error or invalid syntax is encountered, returns default_val cleanly without halting.
bmd — std/json Usage Example
import "std/json" as json

let data = json.parse("{\"node\": \"cluster-01\", \"port\": 8080}")
println("Node:", data["node"])

// Defensive parsing with fallback
let bad_json = "{ corrupted: json }"
let safe_data = json.safe_parse(bad_json, {"fallback": true})
println("Fallback:", safe_data["fallback"]) // true

5. std/io — Safe Filesystem & Console Presentation

Convenient wrappers around file reading, writing, atomic appends, directory discovery, and console headers.

Exported Functions

FunctionSignatureReturnDescription & Edge Cases
read_textread_text(path)STRINGReads complete file contents into a UTF-8 string.
write_textwrite_text(path, content)BOOLEANWrites content to file, creating parent directories if necessary.
append_textappend_text(path, content)BOOLEANAppends content to file (creates file if non-existent).
existsexists(path)BOOLEANReturns true if file or directory exists on filesystem.
removeremove(path)BOOLEANDeletes specified file from filesystem.
list_directorylist_directory(path)ARRAYReturns array of entry names in the specified directory.
printlnprintln(msg)NULLPrints message followed by newline.
print_headerprint_header(title)NULLPrints centered header enclosed in clean Unicode divider lines.
bmd — std/io Usage Example
import "std/io" as io

io.print_header("Disk Quota Monitor")
io.write_text("cache/test.txt", "data payload\n")
if io.exists("cache/test.txt") {
    println("File created successfully.")
    io.remove("cache/test.txt")
}

6. std/testing — Zero-Dependency Test Assertions

Automated test assertions supporting custom test suites, regression runners, and CI verification pipelines.

Exported Functions & Builtin Assertions

FunctionSignatureReturnDescription & Edge Cases
assert_trueassert_true(cond, [msg])BOOLEANAsserts that condition evaluates to truthy. Exits with status 1 on failure.
assert_falseassert_false(cond, [msg])BOOLEANAsserts that condition evaluates to falsy (false or null).
assert_nullassert_null(val, [msg])BOOLEANAsserts that value is strictly null.
assert_not_nullassert_not_null(val, [msg])BOOLEANAsserts that value is not null.
assert_eqassert_eq(actual, expected, [msg])NULLBuiltin: Performs deep structural equality check with formatted failure diff and cyclic protection.
assert_neassert_ne(actual, expected, [msg])NULLBuiltin: Asserts that two values are not structurally equal.
bmd — std/testing Usage Example
import "std/testing" as t

describe("Authentication Security Suite", fn() {
    test("token length validation", fn() {
        let token = "bmd_secret_98765"
        t.assert_true(len(token) > 10, "token must exceed 10 chars")
        t.assert_not_null(token, "token must not be null")
        assert_eq(token[0], "b", "prefix must start with b")
        assert_ne(token, "", "token cannot be empty")
    })
})

7. std/tooling — Native BramandScript Tooling Ecosystem

Following modern runtime architectures (such as Node.js implementing its REPL and CLI dispatcher in JavaScript over V8), high-level developer tooling in BramandScript is authored 100% in pure BramandScript (.bmd) on top of minimal Go VM reflection and session primitives.

Submodules & Exported Interfaces

SubmoduleSignatureReturnDescription & Capabilities
std/toolingimport "std/tooling" as toolHASHUnified developer tooling framework re-exporting start_repl, run_cli, run_test_suites, run_pkg, disassemble, and format_source.
std/tooling/replstart_repl()NULLInteractive terminal REPL with multi-line delimiter tracking, session state persistence, syntax coloring, and commands (:help, :clear, :reset, :env, :type, :time, :disasm, :exit).
std/tooling/clirun_cli(args)INTMaster CLI router supporting run, repl, test, fmt, pkg, disasm, bench, info, version, and help.
std/tooling/test_runnerrun_test_suites(paths)INTAutomated test discovery and execution engine with execution timing, passed/failed counters, and formatted status reporting.
std/tooling/pkgrun_pkg(args)INTPackage manager CLI interface supporting list, install, remove, init, and path for ~/.bramand_libs/.
std/tooling/disasmdisassemble(target)STRINGDisassembles source code strings or closure functions into annotated bytecode instructions and constant table.
std/tooling/fmtformat_source(src)STRINGCanonical source code formatter applying 4-space indentation, operator spacing, and block normalizations.
bmd — std/tooling Programmatic Usage
import "std/tooling/disasm" as d
import "std/tooling/fmt" as f

// Disassemble a function closure dynamically
fn square(x) { return x * x }
println(d.disassemble(square))

// Canonical formatting
let formatted = f.format_source("fn add(a,b){return a+b}")
println(formatted)

8. std/log — Enterprise Structured Logging

Production-ready structured logger featuring configurable log levels (DEBUG, INFO, WARN, ERROR), multiple formatting modes (colorized terminal text and machine-readable JSON), ISO-8601 timestamps, contextual key-value fields, and custom sinks.

Exported Functions & Constants

MemberSignatureReturnDescription
new_loggernew_logger([level, format, sink])HASHCreates a customized logger instance with specified level, format ("text" or "json"), and output callback sink.
debugdebug(msg, [fields])NULLEmits a DEBUG level log entry using default logger.
infoinfo(msg, [fields])NULLEmits an INFO level log entry using default logger.
warnwarn(msg, [fields])NULLEmits a WARN level log entry using default logger.
errerr(msg, [fields])NULLEmits an ERROR level log entry using default logger.
set_levelset_level(level)NULLUpdates the minimum log level filter on the default logger.
set_formatset_format(fmt)NULLSets output format to "text" or "json" on the default logger.
LEVEL_DEBUG, LEVEL_INFO, LEVEL_WARN, LEVEL_ERROR10, 20, 30, 40INTInteger constants representing severity levels.
bmd — std/log Structured Logging Example
import "std/log" as log

// Standard text logging with contextual attributes
log.info("Server started", {"port": 8080, "env": "production"})

// JSON formatted logging for cloud log aggregators
log.set_format("json")
log.warn("Database latency high", {"latency_ms": 450, "pool": "primary"})

// Instance logger with custom sink
let custom = log.new_logger(log.LEVEL_DEBUG, "json", fn(entry) {
    println("[SINK]", entry["message"])
})
custom.debug("Cache miss", {"key": "user:123"})

9. std/retry — Exponential Backoff & Fault Tolerance

Enterprise resilience and retry framework supporting exponential backoff, linear backoff, and fixed interval retries with maximum delay clamping and automatic exception recovery.

Exported Functions

FunctionSignatureReturnDescription
with_backoffwith_backoff(operation, [max_retries, initial_delay_ms, max_delay_ms, factor])ANYExecutes operation with exponential backoff delay growth until success or max retries exhausted.
with_linearwith_linear(operation, [max_retries, step_ms])ANYExecutes operation with linearly increasing delays: attempt * step_ms.
with_fixedwith_fixed(operation, [max_retries, delay_ms])ANYExecutes operation with constant delay intervals between failed attempts.
bmd — std/retry Exponential Backoff Example
import "std/retry" as retry

let attempts = 0
let fetch_data = fn() {
    attempts = attempts + 1
    if attempts < 3 {
        throw "Connection timed out"
    }
    return {"status": 200, "data": "OK"}
}

// Retries up to 4 times with exponential backoff starting at 20ms
let result = retry.with_backoff(fetch_data, 4, 20, 500, 2)
println("Final result:", result["status"]) // 200

10. std/config — Unified Configuration & Dotenv Parser

Lightweight configuration engine supporting Twelve-Factor app .env files and sectioned .ini format configuration with automatic comment stripping, quoted string unescaping, and default fallback lookup.

Exported Functions

FunctionSignatureReturnDescription
parse_dotenvparse_dotenv(content)HASHParses dotenv format text supporting # comments, export KEY=VAL, and quoted strings.
parse_iniparse_ini(content)HASHParses INI configuration with [section] headers and key-value properties.
getget(config, key, [default_val])ANYSafely retrieves value for key, returning default_val (or null) if absent.
get_or_defaultget_or_default(config, key, default_val)ANYRetrieves value or default fallback.
bmd — std/config Usage Example
import "std/config" as cfg

let raw_env = "# Server Environment\nPORT=8080\nHOST=0.0.0.0\nexport DEBUG=true\n"
let env = cfg.parse_dotenv(raw_env)

println("Host:", env["HOST"]) // "0.0.0.0"
println("Port:", cfg.get(env, "PORT", "3000")) // "8080"
println("DB URL:", cfg.get(env, "DATABASE_URL", "sqlite://app.db")) // "sqlite://app.db"

11. std/uuid — RFC 4122 v4 UUID Generator & Parser

Cryptographically secure RFC 4122 Version 4 UUID generation, full format validation, nil UUID checking, and canonical component parsing (time_low, time_mid, time_hi_and_version, clock_seq, node).

Exported Functions & Constants

MemberSignatureReturnDescription & Behavior
v4v4()STRINGGenerates a cryptographically secure random RFC 4122 version 4 UUID string.
newnew()STRINGAlias for v4().
validatevalidate(id)BOOLEANValidates whether string is a properly formatted 36-character hexadecimal UUID with hyphens.
versionversion(id)INTEGERReturns the UUID version integer (e.g. 4), or -1 if invalid.
parseparse(id)HASHParses UUID into {"valid", "error", "version", "variant", "time_low", "time_mid", "time_hi_and_version", "clock_seq", "node", "raw"}.
nil_uuidnil_uuid()STRINGReturns canonical nil UUID string ("00000000-0000-0000-0000-000000000000").
is_nilis_nil(id)BOOLEANReturns true if the specified ID equals the nil UUID string.
NIL_UUIDNIL_UUIDSTRINGConstant representing the 36-character nil UUID.
bmd — std/uuid Example
import "std/uuid" as uuid

let id = uuid.v4()
println("UUID:", id) // "c4b69d4e-5e36-4071-87a2-7fa6203923c5"
println("Valid:", uuid.validate(id)) // true
println("Version:", uuid.version(id)) // 4

let parsed = uuid.parse(id)
println("Variant:", parsed.variant)   // "RFC4122"
println("Time Low:", parsed.time_low) // "c4b69d4e"

12. std/semaphore — Counting Semaphore & Concurrency Limiter

Counting semaphore abstraction for bounding concurrent executions across spawn tasks, providing non-blocking try_acquire() and exception-safe with_permit() wrappers.

Exported Functions & Methods

Function / MethodSignatureReturnDescription & Behavior
newnew([capacity = 1])HASHCreates a counting semaphore initialized with the specified permit capacity (minimum 1).
acquiresem.acquire()BOOLEANBlocks until a permit is available, decrements the available counter, and returns true.
try_acquiresem.try_acquire()BOOLEANAttempts immediate non-blocking acquisition. Returns true if acquired, false if at capacity.
releasesem.release()BOOLEANReleases a permit back to the semaphore, unblocking waiting tasks. Returns true.
availablesem.available()INTEGERReturns current number of available permits.
capacitysem.capacity()INTEGERReturns total configured permit capacity.
with_permitsem.with_permit(action)ANYAcquires permit, executes action(), guarantees release() via defer, and returns result.
bmd — std/semaphore Example
import "std/semaphore" as sem_mod

let sem = sem_mod.new(3) // Limit to 3 concurrent operations

// Automatic permit acquire and deferred release
let res = sem.with_permit(fn() {
    println("Active permits in use. Available:", sem.available())
    return "work done"
})

13. std/circuitbreaker — Enterprise Microservice Resiliency

Production-grade Circuit Breaker pattern with Closed, Open, and Half-Open states, automated reset timeout probe recovery, fallback delegation, and runtime metrics tracking.

Exported Functions, Methods & Constants

MemberSignatureReturnDescription & Behavior
newnew([options])HASHInstantiates a circuit breaker with options: failure_threshold, reset_timeout, half_open_success_threshold, and fallback.
executecb.execute(operation, [fallback])HASHRuns operation protected by breaker. Returns {"ok", "fallback_used", "result", "error", "circuit_open", "state"}.
statecb.state()STRINGReturns current state ("CLOSED", "OPEN", "HALF_OPEN"). Auto-transitions after timeout.
tripcb.trip()NULLManually trips the circuit breaker into the OPEN state.
resetcb.reset()NULLManually resets breaker to CLOSED state and clears consecutive failures.
metricscb.metrics()HASHReturns health statistics: {"state", "consecutive_failures", "total_calls", "total_successes", "total_failures", "trips", "reset_timeout", "failure_threshold"}.
STATE_CLOSED, STATE_OPEN, STATE_HALF_OPEN"CLOSED", "OPEN", "HALF_OPEN"STRINGEnumeration constants for circuit breaker states.
bmd — std/circuitbreaker Example
import "std/circuitbreaker" as cb_mod

let cb = cb_mod.new({
    "failure_threshold": 3,
    "reset_timeout": 5000,
    "fallback": fn() { return {"cached": true, "data": []} }
})

let response = cb.execute(fn() {
    return fetchRemoteService()
})

14. std/pool — High-Throughput Worker Pool

Worker pool abstraction for parallelizing concurrent workloads with a fixed concurrency quota, ensuring thread-safe job distribution and input-order-preserving parallel map() operations.

Exported Functions & Methods

Function / MethodSignatureReturnDescription & Behavior
newnew([num_workers = 4])HASHCreates a concurrent worker pool with fixed number of Goroutines (minimum 1).
mappool.map(items, worker_fn)ARRAYConcurrently processes items with worker_fn(item); preserves exact input index order and captures errors cleanly.
execute_allpool.execute_all(jobs_list)ARRAYConcurrently runs an array of parameterless task functions [fn() { ... }, ...].
workerspool.workers()INTEGERReturns the number of active worker tasks configured in the pool.
bmd — std/pool Parallel Processing Example
import "std/pool" as pool_mod

let pool = pool_mod.new(8) // 8 concurrent workers
let urls = ["item1", "item2", "item3", "item4"]

// Parallel map preserving exact output index order
let results = pool.map(urls, fn(url) {
    return processTask(url)
})
Terminal UI & CLI Ecosystem

Terminal UI, TrueColor & CLI Framework (std/tui)

The std/tui standard library module provides an international-grade, zero-dependency Terminal User Interface and CLI application framework built entirely in BramandScript and Go's standard library. It encompasses 11 integrated submodules and native terminal builtins for rich command-line experiences:

std/tui/color

24-bit TrueColor, HEX to RGB conversion, linear gradients, neon palettes.

std/tui/style

ANSI escape stripping, visible string length, padding (left, right, center), truncation.

std/tui/terminal

Screen clearing, cursor repositioning, cursor visibility, terminal size detection.

std/tui/border

Unicode box rendering with styles (rounded, single, double, heavy, ascii) and title header.

std/tui/component

Badges, status indicators, key-value metrics, cards, dividers, and alert banners.

std/tui/table

Auto-sizing column layout, alignment (left/right/center), and header dividers.

std/tui/progress

High-resolution 1/8th sub-block progress bars, gradients, and animated spinners.

std/tui/chart

Unicode sparklines ( ▂▃▄▅▆▇█) and horizontal normalized bar charts.

std/tui/tree

Hierarchical tree view rendering with branch guides (├──, └──, │).

std/tui/input

Text prompts, boolean confirmations, password masking, single-choice selection.

std/tui/cli

Argument & flag parser, subcommand routing, flag aliases, automated help generator.

1. std/tui/color — TrueColor Engine & Linear Gradients

Create rich 24-bit TrueColor ANSI strings using RGB or HEX definitions. The gradient generator calculates smooth linear color interpolations across arbitrary string lengths:

Function / ConstantSignatureReturnDescription
rgbrgb(r, g, b)STRINGForeground 24-bit TrueColor ANSI escape sequence: \033[38;2;R;G;Bm.
bg_rgbbg_rgb(r, g, b)STRINGBackground 24-bit TrueColor ANSI escape sequence: \033[48;2;R;G;Bm.
hexhex(hex_str)STRINGParses HEX color ("#00f0ff" or "00f0ff") into foreground TrueColor ANSI code.
bg_hexbg_hex(hex_str)STRINGParses HEX color into background TrueColor ANSI code.
rgb_to_hexrgb_to_hex(r, g, b)STRINGEncodes RGB triplet into 6-digit hex string with leading hash (e.g. "#38bdf8").
hex_to_rgbhex_to_rgb(hex_str)ARRAYDecodes HEX string into integer array [r, g, b].
gradientgradient(text, start_hex, end_hex)STRINGRenders smooth linear gradient text interpolated from start HEX to end HEX.
Palette ConstantsNEON_CYAN, NEON_PINK, ...STRINGCyberpunk neon constants: #00f0ff, #ff007f, #00ff66, #ffe600, #b026ff, #ff5500.
bmd — TrueColor & Gradients
import "std/tui" as tui

// 24-bit TrueColor from HEX or RGB
let neon = tui.hex("#00f0ff") + "Cyberpunk Theme" + tui.RESET
println(neon)

// Multi-color linear gradient
let heading = tui.gradient("✦ BRAMAND CLUSTER ENGINE ✦", "#00f0ff", "#ff007f")
println(heading)

// Pre-defined Neon color palette constants
println(tui.hex(tui.NEON_GREEN) + "Node Operational" + tui.RESET)

2. std/tui/terminal & Native Keystroke Builtins

Low-level terminal inspection, cursor movement, and raw mode keystroke polling enable real-time games, interactive editors, and dynamic TUIs:

FunctionSignatureReturnDescription
term_sizeterm_size()HASHBuiltin: Returns {"cols": int, "rows": int} via stty/termios ioctl with env fallback.
term_rawterm_raw(enable)BOOLEANBuiltin: Toggles raw mode (disables line buffering and echo; installs SIGINT restore handler).
read_keyread_key([timeout_ms])STRINGBuiltin: Reads keypress or escape sequence with optional timeout. Returns key name (e.g. "up", "enter").
poll_keypoll_key()STRINGBuiltin: Instant non-blocking keystroke check without delaying event loops.
clearclear()NULLClears screen and repositions cursor to top-left (1, 1).
cursor_tocursor_to(x, y)NULLRepositions cursor to column x, row y.
cursor_hide / cursor_showcursor_hide() / cursor_show()NULLHides or reveals the blinking terminal cursor.
bmd — Terminal Builtins
import "std/tui" as tui

// Query terminal columns and rows
let dims = term_size()
println("Viewport:", dims.cols, "columns by", dims.rows, "rows")

// Enable raw mode for single keypress capture (no enter key required)
term_raw(true)
println("Press any key to proceed (or 'q' to quit)...")
let key = read_key() // Blocks until keypress or SGR sequence
if key == "q" {
    term_raw(false)
    exit(0)
}

// Non-blocking poll for pending key
let pending = poll_key()
term_raw(false) // Always restore canonical mode!

// Screen clearing & cursor positioning
tui.clear()
tui.cursor_to(5, 10)
println("Coordinates (5, 10)")

3. std/tui/table & std/tui/border

Tables automatically compute column widths while taking ANSI escape sequences into account (ignoring color codes for width calculations):

Function / MethodSignatureReturnDescription
new_tablenew_table(headers, [options])TableInstantiates an auto-sizing Table object with border options.
Table.add_rowtbl.add_row(row_array)TableAppends a row of values. Returns table instance for chaining.
Table.add_columntbl.add_column(header, [align])TableAppends column header with alignment ("left", "right", "center").
Table.rendertbl.render()STRINGRenders complete auto-sized table string with Unicode borders.
render_boxrender_box(lines, [options])STRINGRenders box containing text lines with styles ("rounded", "single", "double", "heavy", "ascii").
bmd — Table & Box Rendering
import "std/tui" as tui

// Render responsive Unicode box
let box_str = tui.box([
    tui.bold("Cluster Node Status"),
    tui.dim("Region: us-east-1 · Uptime: 99.98%"),
    tui.status("ok", "All VM fibers operational")
], {
    "title": "SYSTEM TELEMETRY",
    "border": "rounded",
    "border_color": tui.hex("#00f0ff"),
    "width": 50
})
println(box_str)

// Auto-sizing Table
let tbl = tui.new_table(["Service", "Port", "Status", "Latency"], {
    "border": "rounded",
    "border_color": tui.hex("#38bdf8")
})
tbl.add_row(["bmd.http.gateway", "8080", tui.badge("ACTIVE", "#10b981", "#ffffff"), "1.24 ms"])
tbl.add_row(["bmd.compiler.daemon", "9010", tui.badge("READY", "#3b82f6", "#ffffff"), "0.38 ms"])
tbl.add_row(["bmd.storage.kv", "9020", tui.badge("OK", "#06b6d4", "#ffffff"), "0.15 ms"])
tbl.print()

4. std/tui/progress, std/tui/chart & std/tui/tree

Sub-block 1/8th Unicode precision progress bars, sparkline trends, and hierarchical tree views:

FunctionSignatureReturnDescription
render_barrender_bar(cur, total, [opts])STRINGSmooth sub-block 1/8th resolution progress bar (█▉▊▋▌▍▎▏░) with linear color gradients.
render_spinnerrender_spinner(idx, [type])STRINGCycles animated spinner frames ("dots", "line", "arc", "bounce").
sparklinesparkline(numbers, [opts])STRINGIn-line telemetry micro chart mapped across 8 vertical block levels ( ▂▃▄▅▆▇█).
bar_chart_hbar_chart_h(data_items, [opts])STRINGHorizontal bar chart where items are [label, value] with normalized bar scaling.
render_treerender_tree(root_node)STRINGRenders tree hierarchy with branch guides (├──, └──, │).
bmd — Visualizations & Trees
import "std/tui" as tui

// 1. Sub-block Smooth Progress Bar with Gradient
let bar = tui.render_bar(68, 100, {
    "width": 30,
    "show_pct": true,
    "gradient_start": "#00f0ff",
    "gradient_end": "#10b981"
})
println("Heap Memory: " + bar)

// 2. Unicode Sparkline
let traffic = [12, 18, 32, 45, 60, 85, 95, 78, 62, 40, 25, 10]
println("Load Trend (60s): " + tui.sparkline(traffic, {"color": tui.CYAN}))

// 3. Hierarchical Tree
let root = tui.new_tree_node("bramandScript", [
    tui.new_tree_node("compiler", [
        tui.new_tree_node("lexer.go", []),
        tui.new_tree_node("parser.go", [])
    ]),
    tui.new_tree_node("vm", [
        tui.new_tree_node("vm.go", []),
        tui.new_tree_node("builtins.go", [])
    ])
])
println(tui.render_tree(root))

5. std/tui/input & std/tui/cli

Interactive user input dialogs with raw-mode password masking and full-featured CLI subcommand dispatch:

FunctionSignatureReturnDescription
askask(prompt, [default_val])STRINGInteractive user text prompt with optional default value fallback.
confirmconfirm(prompt, [default_bool])BOOLEANYes/No confirmation prompt (returns boolean true/false).
secretsecret(prompt)STRINGRaw mode masked password prompt displaying bullets (●●●●●).
choosechoose(prompt, options)STRINGNumbered single-choice selection menu.
new_clinew_cli(name, ver, desc)CliAppConstructs a CLI Application with subcommand routing and flag parsing.
CliApp.commandapp.command(name, desc, fn)CliAppRegisters subcommand with handler: fn(ctx).
CliApp.flagapp.flag(name, desc, def, [alias])CliAppRegisters flag with optional single-letter alias.
CliApp.runapp.run(args_array)INTEGERDispatches command matching and flag resolution.
bmd — Interactive Prompts & CLI Framework
import "std/tui" as tui

// 1. Password input with masked bullets (●●●●●)
let pass = tui.secret("Enter cluster token: ")

// 2. Boolean confirmation
if tui.confirm("Deploy to production?", false) {
    println("Deploying...")
}

// 3. Full CLI Application Framework
let app = tui.new_cli("cluster", "1.0.0", "Cloud Cluster Management Tool")

app.command("deploy", "Deploy application payload to node", fn(ctx) {
    let target = ctx.args[0]
    let is_prod = ctx.flags["prod"] == true
    println("Deploying target:", target, "prod:", is_prod)
    return 0
})

app.command("status", "Inspect cluster health vitals", fn(ctx) {
    println(tui.status("ok", "Cluster healthy across all nodes."))
    return 0
})

app.run(args())
Scientific Math

Arbitrary-Precision BigInt & BigFloat

BramandScript provides native arbitrary-precision arithmetic powered by Go's standard math/big package. Overloaded operators (+, -, *, /, %, **, unary -) and comparison operators work seamlessly with BigInt and BigFloat types.

bmd — Arbitrary-Precision Big Numbers
let a = big_int("115792089237316195423570985008687907853269984665640564039457584007913129639935")
let b = big_int(2)
let sum = a + b
println("BigInt sum:", sum)

let f1 = big_float("3.1415926535897932384626433832795028841971", 256)
let f2 = big_float("2.7182818284590452353602874713526624977572", 256)
println("High precision product:", f1 * f2)
Linear Algebra

Vectors & Matrices (Linear Algebra)

Perform linear algebra operations for numerical simulations, 3D graphics, machine learning algorithms, and physics modeling:

bmd — Vector & Matrix Operations
let v1 = vec(1.0, 2.0, 3.0)
let v2 = vec(4.0, 5.0, 6.0)
println("Dot product:", v1.dot(v2))       // 32.0
println("Cross product:", v1.cross(v2))   // [-3.0, 6.0, -3.0]
println("Magnitude:", v1.magnitude())      // 3.7416573867739413

let m1 = matrix([[1, 2], [3, 4]])
let m2 = matrix([[2, 0], [1, 2]])
let prod = m1 * m2
println("Matrix multiplication:\n" + str(prod))
println("Determinant:", m1.det())         // -2.0
Scientific Computing

Trigonometric, Logarithmic & Statistical Library

All trigonometric, hyperbolic, transcendental, and statistical functions execute natively with zero external dependencies:

bmd — Math & Statistics
let samples = [12.5, 14.2, 11.8, 15.6, 13.9, 14.2]
println("Mean:", mean(samples))
println("Median:", median(samples))
println("Mode:", mode(samples))
println("Variance:", variance(samples))
println("Std Dev:", std_dev(samples))

println("Hypot(3, 4):", hypot(3.0, 4.0)) // 5.0
println("Log2(1024):", log2(1024.0))     // 10.0
Data Serialization

JSON, CSV & Base64 Serialization

Robust, zero-dependency serialization and deserialization primitives:

bmd — Formats Serialization
// CSV parsing and generation
let csv_data = "name,role,level\nAlice,Admin,5\nBob,Dev,3"
let rows = csv_parse(csv_data)
println("CSV Rows:", rows)

// Base64 and Base64-URL
let encoded = base64_encode("BramandScript Engine")
let decoded = base64_decode(encoded)
println("Base64 roundtrip:", decoded)
Security & Cryptography

Cryptography & CSPRNG (Secure Random & UUIDv4)

Cryptographically secure random number generation, secure UUID v4 tokens, SHA-256, SHA-512, MD5, and HMAC message authentication:

bmd — Cryptographic Primitives
let hash = sha256("admin_secret_key")
println("SHA-256:", hash)

let token = uuid()
println("UUID v4:", token)

let mac = hmac_sha256("signing_key", "order_id=1024&amount=500")
println("HMAC-SHA256:", mac)

let rand_val = random_int(1, 1000)
println("CSPRNG Integer:", rand_val)
Web & Networking

Web, HTTP Routing & Real-Time Hub (std/net)

The std/net package provides a high-performance web microframework built from scratch in BramandScript. It features a Radix/Trie URL router with parameter extraction, unified HTTP context with JSON body binding, composable onion middleware chaining, W3C Server-Sent Events (SSE), and multi-room WebSocket hubs.

std/net/router

Radix Trie URL router supporting static, parameterized (:id), and wildcard (*path) routes.

std/net/context

HTTP request/response wrapper with query string parsing, case-insensitive headers, and JSON binding.

std/net/middleware

Composable onion pipeline with built-in cors, logger, rate_limit, and auth_bearer.

std/net/sse

W3C Server-Sent Events formatter, ping keepalive heartbeats, and event stream parser.

std/net/ws_room

Multi-room WebSocket broadcaster with targeted room dispatch and sender exclusion.

bmd — Web Routing & Context
import "std/net" as net

let router = net.create_router()

// Route with path parameters and query binding
router.get("/api/v1/users/:id", fn(ctx) {
    let user_id = ctx.param("id", "0")
    let verbose = ctx.query_param("verbose", "false")
    ctx.status(200)
    return ctx.send_json({
        "id": user_id,
        "name": "Aryan",
        "verbose": verbose == "true"
    })
})

// Route groups
let v1 = router.group("/api/v1")
v1.post("/echo", fn(ctx) {
    let body = ctx.json_body()
    return ctx.send_json(body)
})
Database & Storage

Database & Storage Engine (std/db)

The std/db package delivers embedded persistence capabilities written 100% in BramandScript. It includes an append-only Write-Ahead Log (WAL) Key-Value store with log compaction, a JSON document collection database with MongoDB-style query operators, a fluent ANSI SQL query builder, and an Active-Record schema validation model layer.

std/db/kv

Append-only WAL Key-Value storage engine with crash recovery and log compaction.

std/db/doc

JSON document database with auto IDs, $set updates, and predicates ($gt, $in).

std/db/query

Fluent SQL and dataset query builder compiling to ANSI SQL and in-memory execution.

std/db/model

Active-Record schema validation layer (required, min_len, contains, in).

bmd — Document Collections & QueryBuilder
import "std/db" as db

// 1. JSON Document Collection with Predicate Queries
let coll = db.create_collection("catalog", "catalog.json")
coll.insert({ "name": "Mechanical Keyboard", "price": 129.99, "category": "gear" })
coll.insert({ "name": "4K Monitor", "price": 399.00, "category": "display" })

// Filter documents where price > 100
let premium = coll.find({ "price": { "$gt": 100.0 } })

// 2. Fluent QueryBuilder to ANSI SQL
let q = db.query("users")
q.select(["id", "username", "email"])
q.where_gt("age", 18)
q.order_by("created_at", "DESC")
q.limit(10)

let sql = q.to_sql()
// SELECT id, username, email FROM users WHERE age > 18 ORDER BY created_at DESC LIMIT 10
Scientific Tensors

Multi-Dimensional Tensor & Linear Algebra (std/math/tensor)

The std/math/tensor module delivers arbitrary N-dimensional tensor data structures with row-major memory layouts and strided coordinates. It natively computes 2D matrix multiplication (matmul), matrix transposition, determinant calculation, Gauss-Jordan matrix inversion, and solving linear systems (A * x = b).

bmd — Matrix Inversion & Linear System Solving
import "std/math/tensor" as tensor

let A = tensor.from_array([
    [4.0, 7.0, 2.0],
    [3.0, 6.0, 1.0],
    [2.0, 5.0, 3.0]
])

println("det(A):", A.det())           // 9.0

// Invert matrix using Gauss-Jordan elimination
let A_inv = A.inv()

// Solve linear system: A * x = b where b = [10, 8, 3]^T
let b = tensor.from_array([[10.0], [8.0], [3.0]])
let x = A_inv.matmul(b)
// Solved: x = 3, y = 0, z = -1
Data Science & Analytics

Tabular DataFrame Engine (std/dataframe)

The std/dataframe module provides a Pandas-style tabular data analysis engine for BramandScript. It supports automated type-inferred CSV parsing, functional row filtering, column selection, sorting, grouped aggregations (group_by), and automated summary statistics (describe).

bmd — DataFrame Loading, GroupBy & Aggregations
import "std/dataframe" as df

let raw_csv = read_file("employees.csv")
let frame = df.from_csv(raw_csv)

// Filter senior staff with salary >= 120,000
let seniors = frame.filter(fn(row) {
    return int(row["salary"]) >= 120000
})

// Group by department with multiple aggregation metrics
let summary = frame.group_by("department").agg({
    "salary": "mean",
    "sales": "sum",
    "id": "count"
})

// Export aggregated results directly to CSV
summary.save_csv("dept_summary.csv")
Machine Learning

Neural Networks & Autograd Engine (std/ml)

The std/ml module is a pure BramandScript reverse-mode automatic differentiation (Autograd) and deep learning library inspired by Micrograd. It manages scalar computation graphs, reverse topological sort backpropagation, neural network layers, Multi-Layer Perceptrons (MLP), loss functions, and gradient descent optimization.

bmd — Multi-Layer Perceptron (MLP) Training Loop
import "std/ml" as ml

// Construct 2 -> 4 -> 1 MLP
let model = ml.new_mlp(2, [4, 1])

// Training iteration:
let x = [ml.val(0.5), ml.val(0.8)]
let y_target = ml.val(1.0)

// 1. Forward pass
let y_pred = model.call(x)
let loss = ml.mse_loss([y_pred], [y_target])

// 2. Backward pass (reverse-mode automatic differentiation)
model.zero_grad()
loss.backward()

// 3. Optimizer step
model.step(0.05)
Exact Arithmetic

Exact Rational Numbers & Arbitrary Decimal Engine (std/math/rational & decimal)

Financial and scientific applications cannot tolerate binary IEEE-754 floating-point rounding errors (e.g. 0.1 + 0.2 != 0.3). BramandScript provides two first-class modules: exact fractional arithmetic with automatic GCD reduction (std/math/rational) and arbitrary/fixed-precision decimal arithmetic (std/math/decimal).

bmd — Exact Fractions & Fixed-Scale Decimals
import "std/math/rational" as r
import "std/math/decimal" as d

// 1. Exact Fractions with Automatic GCD Reduction
let f1 = r.rational(2, 6)             // Automatically reduced to 1/3
let f2 = r.rational(1, 6)
let sum = f1.add(f2)                  // 1/3 + 1/6 = 1/2
let prod = f1.mul(r.rational(3, 2))   // 1/3 * 3/2 = 1/2
println("Sum:", sum.to_string())      // "1/2"
println("Float value:", sum.to_float()) // 0.5

// 2. Exact Financial Decimal Arithmetic (Zero Float Drift)
let d1 = d.decimal("0.1")
let d2 = d.decimal("0.2")
let total = d1.add(d2)
println("Exact decimal sum:", total.to_string()) // "0.3"
ModuleConstructors & MethodsDescription
std/math/rationalrational(n, d), fraction(n, d)
.add(o), .sub(o), .mul(o), .div(o), .pow(p)
Exact integer rational fractions; automatically simplifies via Euclidean GCD. Returns .to_string() and .to_float().
std/math/decimaldecimal(val, [scale])
.add(o), .sub(o), .mul(o), .div(o)
Fixed/arbitrary-scale decimal arithmetic for currencies, financial ledgers, and exact tax calculations.
Mathematics

Complex Numbers, Number Theory & Constants (std/math/complex, ntheory, constants)

A full-featured mathematical engine supporting Cartesian/polar complex numbers with Euler identity evaluation, cryptographic number theory (Miller-Rabin primality, Pollard-rho, extended GCD, modular inverse), and Chudnovsky-grade constant generation:

bmd — Complex Numbers & Cryptographic Number Theory
import "std/math/complex" as c
import "std/math/ntheory" as nt
import "std/math/constants" as consts

// Complex Cartesian & Polar Arithmetic
let z1 = c.complex(3, 4)
println("|z1| magnitude:", z1.abs())      // 5.0
println("z1 conjugate:", z1.conj().to_string()) // "3 - 4i"

// Euler Identity Verification: e^(i*pi) + 1 = 0
let i_pi = c.complex(0, 3.141592653589793)
let euler = i_pi.exp() // Real part ~ -1.0, Imag ~ 0.0

// Cryptographic Number Theory
println("Is 7919 prime?", nt.is_prime(7919))            // true
println("Prime factors of 84:", nt.prime_factors(84))  // [2, 2, 3, 7]
println("Modular inverse of 7 mod 26:", nt.mod_inv(7, 26)) // 15
println("Combinations 6C2:", nt.nCr(6, 2))             // 15

// High-Precision Pi, E, and Golden Ratio Phi Digits
println("Pi (20 digits):", consts.compute_pi_digits(20))
println("E (20 digits):", consts.compute_e_digits(20))
Scientific Computing

Calculus, Optimization & ODE Solvers (std/math/calculus, opt, ode)

High-precision numerical differentiation, adaptive Simpson and Gauss-Legendre quadrature integration, root-finding (Newton-Raphson, Bisection, Brent-Dekker), scalar/gradient minimization, and 4th-order Runge-Kutta (RK4) differential equation integrators.

bmd — Numerical Derivatives, Quadrature, Root Finding & ODEs
import "std/math/calculus" as calc
import "std/math/opt" as opt
import "std/math/ode" as ode

// 1. Numerical Differentiation: f(x) = x^3 at x = 2 -> f'(2) = 12
let f = fn(x) { return x * x * x; }
let d1 = calc.diff(f, 2.0)
let d2 = calc.diff2(f, 2.0)
println("d/dx x^3 at 2.0:", d1) // ~12.0

// 2. Numerical Integration: Integrate x^2 from 0 to 3 -> (3^3)/3 = 9.0
let quad = calc.integrate_simpson(fn(x) { return x * x; }, 0.0, 3.0, 50)
println("Simpson integral:", quad) // 9.0

// 3. Non-Linear Root Finding: x^2 - 4 = 0 -> root = 2.0
let root = opt.root_brent(fn(x) { return (x * x) - 4.0; }, 0.0, 5.0)
println("Brent root:", root.root) // 2.0

// 4. 4th-Order Runge-Kutta ODE Solver: dy/dt = -y, y(0) = 1.0 -> y(1.0) = 1/e
let trajectory = ode.ode_solve_rk4(fn(t, y) { return -y; }, 1.0, 0.0, 1.0, 0.1)
let final_state = trajectory[len(trajectory) - 1]
println("y(1.0) via RK4:", final_state[1]) // ~0.367879
Linear Algebra & Spectral Analysis

Matrix Decompositions, Spectral Analysis & Sparse CSR (std/math/decomp, eigen, sparse)

Industrial-grade numerical linear algebra factorizations (LU with partial row pivoting, QR via Householder reflections, Cholesky decomposition), linear system solvers, least-squares regression, eigenvalue extraction via shifted QR, and memory-efficient Compressed Sparse Row (CSR) matrices.

bmd — LU/QR/Cholesky Factorization & Eigenvalues
import "std/math/decomp" as decomp
import "std/math/eigen" as eigen
import "std/math/sparse" as sparse

// 1. Solve Linear System A * x = b via LU Decomposition
let A = [
    [3.0, 2.0, -1.0],
    [2.0, -2.0, 4.0],
    [-1.0, 0.5, -1.0]
]
let b = [1.0, -2.0, 0.0]
let x = decomp.solve_linear_system(A, b)
println("Solution vector x:", x)

// 2. Symmetric Spectral Analysis via QR Eigenvalues
let sym = [
    [2.0, 1.0],
    [1.0, 2.0]
]
let spectral = eigen.eigen_qr(sym, 100, 0.0000000001)
println("Eigenvalues:", spectral.eigenvalues) // [3.0, 1.0]
println("Spectral radius:", eigen.spectral_radius(sym)) // 3.0

// 3. Compressed Sparse Row (CSR) Matrix Operations
let dense = [
    [1.0, 0.0, 0.0],
    [0.0, 0.0, 3.0],
    [4.0, 0.0, 5.0]
]
let csr = sparse.csr_from_dense(dense)
println("Non-zero entries (nnz):", csr.nnz()) // 4
let result_v = csr.matmul_vec([2.0, 10.0, 4.0]) // [2.0, 12.0, 28.0]
Iterators & Generators

Resumable Iterators & Generator Streams (std/iter)

First-class stateful coroutine generators with yield, plus fluent lazy streaming operations (take, drop, map, filter, cycle, zip, to_array).

bmd — Coroutine Generators & Lazy Streams
import "std/iter" as iter

// Generator function yielding values on demand
let gen = iter.generator(fn(yield) {
    let i = 1
    while true {
        yield i * 10
        i += 1
    }
})

// Take first 4 items lazily without evaluating infinite loop
let first_four = iter.take(gen, 4) // [10, 20, 30, 40]
println("First four:", first_four)

// Fluent streaming transformations
let stream = iter.range(1, 10, 2) // [1, 3, 5, 7, 9]
let doubled = stream.map(fn(x) { return x * 2; }).filter(fn(x) { return x > 5; })
println("Stream array:", doubled.to_array()) // [6, 10, 14, 18]
Compression

Native Compression & Archiving (std/compress)

Compress and decompress data streams or package entire file hierarchies into standard POSIX tar archives in pure Go standard library with zero external CLI dependencies.

bmd — Gzip, Zlib & Tar Archive Packaging
import "std/compress/gzip" as gzip
import "std/compress/zlib" as zlib
import "std/compress/tar" as tar

// 1. Gzip Compression Round-Trip
let raw_text = "BramandScript pure standard library offline-first high performance!"
let gz_bytes = gzip.compress(raw_text)
let restored = gzip.decompress(gz_bytes)
println("Gzip verified:", str(restored) == raw_text)

// 2. Tar Multi-File Directory Archiving
let archive_bytes = tar.pack({
    "config.bmd": "let port = 8080;",
    "static/index.html": "<h1>Bramand App</h1>"
})
let extracted_files = tar.unpack(archive_bytes)
println("Unpacked config:", str(extracted_files["config.bmd"]))
Binary Protocols

Binary Struct Packing & MessagePack (std/binary/pack)

Compact wire protocols, telemetry serialization, and network socket framing using Python-style struct.pack / unpack format specifiers (>I, <h, f, d, s) and MessagePack binary encoding.

bmd — Struct Packing & MsgPack Serialization
import "std/binary/pack" as bin

// 1. Python-style binary struct packing (>hhi4s = Big-Endian int16, int16, int32, 4-char string)
let format = ">hhi4s"
let packed_bytes = bin.pack(format, [42, -99, 123456, "BMD!"])
let unpacked_arr = bin.unpack(format, packed_bytes)
println("Unpacked ID:", unpacked_arr[0], "Magic:", unpacked_arr[3])

// 2. High-Speed MessagePack Encoding
let data = { "user": "bramand", "id": 101, "scores": [98.5, 95.0] }
let msgpack_bytes = bin.encode(data)
let decoded_data = bin.decode(msgpack_bytes)
println("Decoded user:", decoded_data.user) // "bramand"
Modern Cryptography

Modern Cryptography Suite: AES-256-GCM, Ed25519 & JWT (std/crypto/advanced)

Commercial-grade authenticated symmetric encryption with 128-bit authentication tags (AES-256-GCM), high-speed elliptic curve digital signatures (Ed25519), and secure JSON Web Token (JWT) signing and verification.

bmd — AES-256-GCM, Ed25519 & JWT Signatures
import "std/crypto/advanced" as crypto

// 1. Authenticated Symmetric Encryption (AES-256-GCM)
let key = "abcdefghijklmnopqrstuvwxyz123456" // 32-byte key
let secret_msg = "Ultra confidential transaction payload"
let enc = crypto.encrypt_gcm(key, secret_msg, null, "aad-data")
let dec = crypto.decrypt_gcm(key, enc.combined, null, "aad-data")
println("Decrypted message:", str(dec))

// 2. Ed25519 Digital Signatures
let kp = crypto.keypair_ed25519()
let message = "Authorize wire transfer #9842"
let signature = crypto.sign_ed25519(kp.private_key, message)
let is_valid = crypto.verify_ed25519(kp.public_key, message, signature)
println("Ed25519 signature valid?", is_valid) // true

// 3. JSON Web Token (JWT) Verification
let payload = { "sub": "user_42", "role": "admin", "iat": 1700000000 }
let secret = "production_secure_jwt_secret_key"
let token = crypto.sign_jwt(payload, secret, "HS256")
let result = crypto.verify_jwt(token, secret, "HS256")
println("JWT verified?", result.valid, "Role:", result.payload.role)
Terminal Visualizations

Terminal Unicode & Braille Plotting Engine (std/tui/plot)

Scientific, financial, and machine learning visualization library rendering high-resolution 2x4 Braille dot-matrix curves, scatter plots, and Unicode box bar charts directly inside any terminal without GUI dependencies.

bmd — Braille Function Plotting & Bar Charts
import "std/tui/plot" as plot

// Plot a mathematical function curve using high-resolution Braille dots
let parabola = plot.plot_function(fn(x) { return x * x; }, -2.0, 2.0, "Parabola", 40, 10)
println(parabola)

// Render a clean Unicode horizontal bar chart
let categories = ["Compiler", "VM Exec", "Stdlib", "Crypto"]
let timings_ms = [4.2, 12.8, 8.5, 3.1]
let bar_chart = plot.plot_bar(categories, timings_ms, "Hotspot Profile", 25)
println(bar_chart)
Enterprise Stdlib Calendar Arithmetic

Date, Time & Calendar Engine (std/datetime)

A high-performance date, time, duration, and calendar arithmetic suite. Supports ISO 8601, RFC 3339, Unix epoch millisecond timestamps, UTC conversions, leap year verification, calendar offsets, and custom format conversions (YYYY-MM-DD HH:mm:ss).

1. Functions Reference

FunctionSignatureReturn TypeDescription
nowdt.now()HASHReturns current datetime object with year, month, day, hour, iso, unix_ms, and methods.
now_isodt.now_iso()STRINGReturns current timestamp formatted as ISO 8601 / RFC 3339 string in UTC.
now_msdt.now_ms()INTEGERReturns current epoch time in milliseconds.
newdt.new(year, month, day, [h=0, m=0, s=0])HASHConstructs a datetime instance for specified calendar components.
Datedt.Date(year, month, day)HASHConstructs a calendar date instance initialized at midnight (00:00:00Z).
parsedt.parse(raw_str, [layout])HASHParses datetime string according to standard candidates or specified custom layout.
formatdt.format(val, [layout])STRINGFormats datetime hash or epoch ms using layout tokens (e.g. "YYYY-MM-DD").
adddt.add(val, amt, unit)INTEGERAdds amount of units ("days", "hours", "minutes", "seconds", "ms") to timestamp.
diffdt.diff(t1, t2, [unit = "ms"])FLOAT | INTCalculates duration between two timestamps in specified unit.
is_leap_yeardt.is_leap_year(year)BOOLEANDetermines if given Gregorian calendar year is a leap year.
days_in_monthdt.days_in_month(year, month)INTEGERReturns total number of days (28–31) in given year and month.
durationdt.duration(ms)HASHConverts milliseconds into a map of total seconds, minutes, hours, and days.
bramand — Date and Calendar Operations
import "std/datetime" as dt

// Construct calendar date
let d = dt.new(2026, 11, 9, 14, 30, 0)
println("ISO 8601:", d.to_iso())        // 2026-11-09T14:30:00Z
println("Weekday:", d["weekday"])        // "Monday"
println("Is leap year:", d.is_leap_year()) // false

// Calendar arithmetic
let next_week = d.add_days(7)
println("Next week:", next_week.to_iso())

// Duration diff calculations
let span = next_week.diff(d)
println("Days span:", span["days"])      // 7
Enterprise Stdlib Cross-Platform I/O

File System & Path Engine (std/fs & std/path)

Production filesystem engine supporting recursive directory walking with filters, pattern matching (glob), temporary file creation, directory tree hierarchies, file metadata (stat), and canonical path normalization.

1. std/path API Reference

FunctionSignatureReturn TypeDescription
joinpath.join(a, b, [c, d, e]) | path.join(array)STRINGJoins path elements into single normalized slash-delimited path.
cleanpath.clean(p)STRINGResolves ., .., and redundant slashes into canonical form.
basepath.base(p)STRINGExtracts trailing element of path (e.g. "file.txt").
dirpath.dir(p)STRINGReturns directory path excluding the trailing file element.
extpath.ext(p)STRINGReturns file extension starting with dot (e.g. ".bmd").
abspath.abs(p)STRINGResolves relative path to absolute canonical filesystem path.
is_abspath.is_abs(p)BOOLEANChecks if given path is absolute.
splitpath.split(p)ARRAYSplits path into [dir, file] array tuple.

2. std/fs API Reference

FunctionSignatureReturn TypeDescription
walkfs.walk(path, [ext_filter])ARRAYRecursively traverses directory tree, returning array of file entry hashes.
globfs.glob(pattern)ARRAYMatches files matching shell pattern (e.g. "*.bmd", "src/**/*.go").
temp_filefs.temp_file([prefix, ext])HASHCreates a unique temporary file on the OS filesystem, returning path and name.
treefs.tree(dir, [max_depth = -1])HASHBuilds a nested hierarchical JSON-serializable directory tree.
statfs.stat(path)HASHReturns file metadata: path, name, size, is_dir, mode, mod_time.
mkdirfs.mkdir(path, [recursive = true])BOOLEANCreates directory path, creating parent directories when recursive is true.
read_textfs.read_text(path)STRINGReads complete contents of text file as UTF-8 string.
write_textfs.write_text(path, content)BOOLEANWrites string contents into file, truncating existing content.
append_textfs.append_text(path, content)BOOLEANAppends string content to end of file without truncating.
existsfs.exists(path)BOOLEANChecks whether file or directory exists at path.
removefs.remove(path)BOOLEANDeletes specified file or empty directory.
bramand — Path manipulation & recursive directory walking
import "std/path" as path
import "std/fs" as fs

let full_path = path.join(["/var", "log", "app.log"])
println("Base:", path.base(full_path)) // "app.log"
println("Ext:", path.ext(full_path))   // ".log"
println("Dir:", path.dir(full_path))   // "/var/log"

// Create and inspect a temporary file
let tmp = fs.temp_file("bench", ".txt")
fs.write_text(tmp["path"], "performance payload")

let st = fs.stat(tmp["path"])
println("File size in bytes:", st["size"])
println("Modified timestamp:", st["mod_time"])

fs.remove(tmp["path"])
Enterprise Stdlib Data Serialization

Universal Data Encoding Suite (std/encoding)

Universal serialization suite featuring RFC 4180 compliant CSV parser and formatter, Hexadecimal encoders/decoders, URL query parameter builders/parsers, and Base64 wrapping utilities.

1. Functions Reference

FunctionSignatureReturn TypeDescription
hex_encodeenc.hex_encode(data)STRINGEncodes byte buffer or string into lowercase hexadecimal representation.
hex_decodeenc.hex_decode(hex_str)STRINGDecodes hexadecimal string back into original raw string.
url_encodeenc.url_encode(str)STRINGEscapes characters for safe inclusion in URL query strings.
url_decodeenc.url_decode(str)STRINGUnescapes URL-encoded query string.
url_parse_queryenc.url_parse_query(query_str)HASHParses URL query string into key-value hash map.
url_build_queryenc.url_build_query(hash)STRINGEncodes key-value hash into canonical sorted URL query string.
csv_parseenc.csv_parse(str, [delim=",", headers=false])ARRAYParses CSV text into array of rows (or array of hashes if headers is true).
csv_stringifyenc.csv_stringify(records, [delim=",", headers])STRINGSerializes array of records (arrays or hashes) into valid CSV string.
base64_chunkenc.base64_chunk(b64_str, [line_len=64])STRINGSplits long Base64 string with newline characters for MIME/PEM wrapping.
bramand — CSV and Hex encoding operations
import "std/encoding" as enc

// Hex Encode / Decode
let hex = enc.hex_encode("BramandScript 2026")
println("Hex:", hex)
println("Decoded:", enc.hex_decode(hex))

// URL Query Builder & Parser
let query = enc.url_build_query({ "search": "actor model", "page": 1 })
println("Encoded query:", query) // "page=1&search=actor+model"

// CSV Formatting & Parsing with Headers
let data = [
    { "id": "1", "name": "Alice", "role": "Architect" },
    { "id": "2", "name": "Bob", "role": "Lead" }
]
let csv_text = enc.csv_stringify(data)
let parsed = enc.csv_parse(csv_text, ",", true)
println("First record role:", parsed[0]["role"]) // "Architect"
Monadic Safety Algebraic Types

Monadic Safety (Result, Option & ?)

BramandScript introduces first-class algebraic container types (Result and Option) combined with the postfix try-propagation operator (?) to eliminate runtime panics, uncaught exceptions, and defensive boilerplate checks.

1. Result Monad (Ok(v) & Err(e))

MethodSignatureReturn TypeDescription
is_okres.is_ok()BOOLEANReturns true if the Result is Ok.
is_errres.is_err()BOOLEANReturns true if the Result is Err.
unwrapres.unwrap()OBJECTReturns inner value if Ok; raises fatal error if called on Err.
unwrap_orres.unwrap_or(fallback)OBJECTReturns inner value if Ok; returns fallback value if Err.
unwrap_errres.unwrap_err()OBJECTExtracts inner error value from Err.
mapres.map(fn)RESULTApplies transformation function to inner value if Ok; preserves Err untouched.
flat_mapres.flat_map(fn)RESULTApplies monadic function returning another Result, flattening the structure.

2. Option Monad (Some(v) & None())

MethodSignatureReturn TypeDescription
is_someopt.is_some()BOOLEANReturns true if the Option contains a value (Some).
is_noneopt.is_none()BOOLEANReturns true if empty (None).
unwrapopt.unwrap()OBJECTReturns inner value if Some; raises error on None.
unwrap_oropt.unwrap_or(fallback)OBJECTReturns inner value if Some, otherwise fallback value.
mapopt.map(fn)OPTIONApplies transformation to inner value, wrapping back into Some.
flat_mapopt.flat_map(fn)OPTIONMonadic bind for chained transformations returning an Option.

3. Postfix Try-Propagation Operator (?)

Appending ? to any expression evaluating to a Result or Option automatically unwraps the successful value, or performs an early-return from the enclosing function unwinding the error or none value directly to the caller.

bramand — Monadic pipeline with ? operator
let parse_integer = fn(s) {
    if len(s) == 0 {
        return Err("empty string")
    }
    return Ok(int(s))
}

let calculate_average = fn(str_a, str_b) {
    let a = parse_integer(str_a)? // Unwraps Ok, or early-returns Err!
    let b = parse_integer(str_b)? // Unwraps Ok, or early-returns Err!
    return Ok((a + b) / 2)
}

let success = calculate_average("40", "60")
println("Result:", success.unwrap()) // 50

let failure = calculate_average("", "60")
println("Failure caught:", failure.is_err()) // true
println("Fallback:", failure.unwrap_or(0))   // 0
Tier 1 Networking Go Host Primitives

Low-Level Sockets & Networking (std/net)

The std/net module provides low-level duplex streaming TCP sockets, high-throughput UDP packet sockets, and TLS encryption primitives implemented directly in the Go standard library with zero external dependencies.

1. Functions & Factory Methods

FunctionSignatureReturnDescription
net.create_servernet.create_server([addr], handler)ServerInstantiates a TCP server wrapping net_listen_tcp. Dispatches incoming connections asynchronously.
net.connectnet.connect(host, port, [on_connect])SocketDials a remote TCP server and returns a bidirectional streaming Socket instance.
net.create_udp_socketnet.create_udp_socket([port_or_addr])UDPSocketBinds a local UDP socket on specified port/address (default ephemeral port 0).
net.dial_tlsnet.dial_tls(addr, sni_name, timeout, [opts])SocketDials an encrypted TLS connection with mandatory Server Name Indication (SNI) verification.
net.listen_tlsnet.listen_tls(addr, cert_file, key_file)ServerBinds an encrypted TLS listener using PEM certificate and private key files.

2. Socket Instance Methods

MethodSignatureReturnDescription
sock.readsock.read([max_bytes])STRINGReads up to max_bytes (default 4096) from the socket; returns null or EOF on close.
sock.read_linesock.read_line()STRINGReads a single line delimited by \n or \r\n from the internal buffer.
sock.writesock.write(data)INTEGERWrites string or byte slice data to the socket stream; returns number of bytes written.
sock.set_timeoutsock.set_timeout(ms)BOOLEANSets read and write deadline timeout in milliseconds (0 clears timeout).
sock.remote_addrsock.remote_addr()STRINGReturns remote peer IP and port address string (e.g. "192.168.1.5:49152").
sock.closesock.close()BOOLEANCloses the TCP connection and flushes remaining buffers.
bmd — Multi-Client TCP Socket Server & Client
import "std/net" as net;

let server = net.create_server(fn(sock) {
    sock.set_timeout(5000);
    let line = sock.read_line();
    sock.write("ECHO: " + trim(line) + "\n");
    sock.close();
});
server.listen(9001);

let client = net.connect("127.0.0.1", 9001);
client.write("Hello Bramand!\n");
let reply = client.read_line();
println("Received:", trim(reply));
client.close();
server.close();
Tier 2 Protocol 100% Pure BMD

Pure BramandScript HTTP/1.1 Engine (std/http)

A 100% self-hosted RFC 7230 HTTP/1.1 engine written entirely in BramandScript on top of raw TCP sockets. Includes an RFC 7230 wire parser, server with Request and Response abstractions, client convenience helpers, Radix Trie router, and middleware.

1. HTTP Client & Server API

FunctionSignatureReturnDescription
http.create_serverhttp.create_server(handler)ServerInstantiates an HTTP server taking a callback fn(req, res) or a Trie Router.
http.create_routerhttp.create_router()RouterConstructs a Radix-Trie URL router with get, post, put, delete_req, group.
http.gethttp.get(url, [opts])ResponseSends HTTP GET request; response contains status, headers, body, json(), text().
http.posthttp.post(url, body, [opts])ResponseSends HTTP POST request with automatic JSON body serialization.
http.puthttp.put(url, body, [opts])ResponseSends HTTP PUT request with payload and optional custom headers.
http.delete_reqhttp.delete_req(url, [opts])ResponseSends HTTP DELETE request to target endpoint.
http.requesthttp.request(options)ResponseExecutes customized request with {"method", "url", "body", "headers", "timeout"}.
bmd — REST API Service with Router & Middleware
import "std/http" as http;

let router = http.create_router();

router.get("/api/items/:id", fn(req, res) {
    let id = req.params["id"];
    res.json({ "id": id, "name": "Quantum CPU", "price": 4999 });
});

router.post("/api/items", fn(req, res) {
    let data = req.json();
    res.status(201).json({ "created": data, "id": 101 });
});

let server = http.create_server(router);
server.listen(8080);
Tier 2 Protocol RFC 6455 Pure BMD

Pure BramandScript WebSocket Engine (std/ws)

A 100% self-hosted RFC 6455 WebSocket engine written entirely in BramandScript atop raw TCP sockets. Includes handshake key derivation (Sec-WebSocket-Accept with SHA-1 and Base64), binary frame encoder/decoder with FIN bit, opcode bitfields, 4-byte client XOR payload masking, 7-bit/16-bit/64-bit payload lengths, and room broadcast.

1. WebSocket Server & Client API

FunctionSignatureReturnDescription
ws.create_serverws.create_server(port, on_connection)ServerInstantiates a WebSocket server negotiating RFC 6455 handshakes and connection lifecycle.
ws.connectws.connect(url, [on_open])ClientDials a remote WebSocket endpoint (ws://), performs handshake, and returns connection.
server.broadcastserver.broadcast(message)INTEGERTransmits text message to all active, non-closed client connections; returns count delivered.
conn.sendconn.send(message)BOOLEANEncodes and transmits an RFC 6455 text frame across the duplex socket.
conn.pingconn.ping([payload])BOOLEANSends an RFC 6455 Ping control frame to verify peer liveness.
conn.closeconn.close([code], [reason])BOOLEANInitiates graceful close handshake with status code (default 1000) and reason text.
bmd — Realtime WebSocket Broadcast & Telemetry
import "std/ws" as ws;

let server = ws.create_server(8081, fn(conn) {
    conn.on("message", fn(msg) {
        conn.send("ACK: " + msg);
        server.broadcast("ANNOUNCE: " + msg);
    });
});

let client = ws.connect("ws://127.0.0.1:8081/feed", fn(c) {
    c.send("TELEMETRY_ONLINE");
});

client.on("message", fn(msg) {
    println("Received:", msg);
});
Tier 2 Protocol RFC 1035 Pure BMD

Pure BramandScript UDP DNS Resolver (std/dns)

A 100% self-hosted RFC 1035 UDP DNS packet codec and resolver engine. Directly formats binary queries, parses 12-byte headers, resolves QNAME labels with 0xC0 compression pointers, and manages an in-memory TTL cache.

1. Functions Reference

FunctionSignatureReturnDescription
dns.resolvedns.resolve(domain, [type], [server], [timeout])ARRAYResolves domain to array of record values (default type A, server "8.8.8.8:53").
dns.lookupdns.lookup(domain, [server], [timeout])STRINGConvenience lookup returning the primary IPv4 address or null if unresolvable.
dns.clear_cachedns.clear_cache()NULLFlushes all in-memory DNS cache entries.
dns.get_cachedns.get_cache()HASHReturns snapshot of current cached domain records with expiration timestamps.
dns.encode_querydns.encode_query(domain, [type], [id])BYTESEncodes RFC 1035 binary query packet ready for UDP socket transmission.
dns.decode_responsedns.decode_response(bytes)HASHParses binary DNS datagram, handling QNAME pointer compression (0xC0) and record sections.
bmd — DNS Query & In-Memory TTL Cache
import "std/dns" as dns;

// Resolve domain via UDP query datagram
let ips = dns.resolve("bramand.org", dns.TYPE_A, "8.8.8.8:53");
println("Resolved IPs:", ips);

// Secondary lookup resolves instantly from in-memory TTL cache (0ms latency)
let primary_ip = dns.lookup("bramand.org");
println("Primary IP:", primary_ip);
Tier 2 Protocol Secure TLS

Pure BramandScript HTTPS Engine (std/https)

Combines raw TLS dialer sockets (tls_dial) with the pure BMD HTTP wire parser and client pipeline. Enforces Server Name Indication (SNI) verification and TLS certificate validation by default.

1. Functions Reference

FunctionSignatureReturnDescription
https.gethttps.get(url, [opts])ResponseExecutes TLS-encrypted HTTPS GET request with automatic SNI negotiation.
https.posthttps.post(url, body, [opts])ResponseExecutes TLS-encrypted HTTPS POST request with JSON payload serialization.
https.requesthttps.request(options)ResponseGeneric encrypted request dispatcher supporting all standard HTTP methods over TLS.
https.create_serverhttps.create_server(handler)ServerInstantiates an HTTPS server wrapping a TLS listener with PEM certificate and key.
bmd — Secure HTTPS GET & POST
import "std/https" as https;

let res = https.get("https://api.github.com/zen", {
    "headers": { "User-Agent": "BramandScript/1.0" }
});
println("HTTPS Status:", res["status"], "Body:", res.text());
System & IPC Process Streaming

Process IPC & Operating System (std/process & std/os)

The std/process and std/os modules deliver native child process lifecycle management, standard I/O streaming pipes, Unix IPC pipelines, exit code verification, and host system introspection.

1. Subprocess & Stream Pipeline API (std/process)

Function / MethodSignatureReturnDescription
process.spawnprocess.spawn(command, [args])ChildProcessSpawns an asynchronous child process with connected stdin, stdout, stderr streams.
process.execprocess.exec(command, [opts])HASHExecutes command synchronously; returns {"exit_code", "stdout", "stderr"}.
process.pipeprocess.pipe(proc1, proc2)ChildProcessPipes proc1.stdout directly into proc2.stdin via an asynchronous transfer coroutine.
proc.stdin.writeproc.stdin.write(data)INTEGERWrites data to child process standard input stream.
proc.stdin.endproc.stdin.end([final_data])BOOLEANCloses subprocess standard input stream, triggering EOF in the child process.
proc.stdout.read_allproc.stdout.read_all()STRINGConsumes and buffers all remaining standard output from the child process.
proc.waitproc.wait()INTEGERWaits for child process to terminate and returns integer exit status code.
proc.killproc.kill([signal])BOOLEANSends OS termination signal (SIGTERM or SIGKILL) to the child process.

2. OS System Introspection (std/os)

Field / FunctionTypeExampleDescription
os.platformSTRING"linux", "darwin"Host operating system name.
os.archSTRING"arm64", "amd64"Host hardware CPU architecture.
os.cpus()INTEGER8Total number of logical CPU processing cores.
os.memory()HASH{"alloc", "sys", "total_alloc"}Current runtime memory allocations in bytes.
os.get_env(key)STRINGos.get_env("PATH")Reads environment variable with optional default value.
os.cwd()STRING"/home/bramand"Returns current active working directory path.
os.pid()INTEGER14820Process identifier of the current BramandScript process.
bmd — Unix Pipeline IPC: proc1.pipe(proc2)
import "std/process" as process;

// IPC Unix pipeline: echo -> tr -> read
let p1 = process.spawn("echo", ["hello world"]);
let p2 = process.spawn("tr", ["a-z", "A-Z"]);
p1.pipe(p2);

let output = p2.stdout.read_all();
p1.wait();
p2.wait();
println("Transformed output:", trim(output)); // "HELLO WORLD"
Binary Codecs Stream Piping

Byte Buffers & Binary Stream Piping (std/buffer & std/io)

The std/buffer and std/io modules deliver high-performance byte buffer manipulation, Big-Endian / Little-Endian numeric serialization, IEEE 754 float codecs, and streaming pipe combinators with zero data loss.

1. Buffer Class & Static Factory (std/buffer)

MethodSignatureReturnDescription
Buffer.allocBuffer.alloc(size, [fill])BufferAllocates buffer of specified byte size pre-filled with integer value (default 0).
Buffer.fromBuffer.from(data, [encoding])BufferCreates buffer from string ("utf8", "hex", "base64"), byte array, or raw bytes.
Buffer.concatBuffer.concat(list, [total_len])BufferConcatenates an array of buffers into a single continuous memory block.
Buffer.compareBuffer.compare(a, b)INTEGERCompares buffers lexicographically; returns 0 if identical, -1 if a < b, 1 if a > b.
buf.read_uint32_be/lebuf.read_uint32_be(offset)INTEGERReads a 32-bit unsigned integer in Big-Endian or Little-Endian order.
buf.write_uint32_be/lebuf.write_uint32_be(val, offset)BufferWrites a 32-bit unsigned integer in Big-Endian or Little-Endian order.
buf.read_double_be/lebuf.read_double_be(offset)FLOATReads a 64-bit IEEE 754 double precision float at byte offset.
buf.write_double_be/lebuf.write_double_be(val, offset)BufferWrites a 64-bit IEEE 754 double precision float at byte offset.
buf.copybuf.copy(target, [tgt_start], [src_start], [src_end])INTEGERFast bulk memory copy between buffers; returns number of bytes copied.
buf.slicebuf.slice([start], [end])BufferReturns a sub-buffer slice sharing underlying memory.

2. Stream Combinators (std/io)

FunctionSignatureReturnDescription
io.BufferReaderio.BufferReader(buf)ReaderCreates streaming reader over buffer with read(n), read_all(), seek(pos), is_eof().
io.BufferWriterio.BufferWriter([capacity])WriterCreates dynamically expanding buffer sink with write(data), to_buffer(), to_string().
io.pipeio.pipe(readable, writable, [opts])INTEGERPipes data from readable stream to writable stream using chunked buffering; returns total bytes transferred.
io.read_allio.read_all(readable)BufferReads all remaining bytes from stream into a single contiguous Buffer.
bmd — Binary Buffer Codecs & Stream Piping
import "std/buffer" as buffer;
import "std/io" as io;

let Buffer = buffer.Buffer;

// 1. Pack binary header & float payload
let buf = Buffer.alloc(16);
buf.write_uint32_be(0xCAFEBABE, 0);
buf.write_uint32_be(1024, 4);
buf.write_double_be(3.14159265, 8);

// 2. Stream piping through BufferReader -> BufferWriter
let reader = io.BufferReader(buf);
let writer = io.BufferWriter();
let total = io.pipe(reader, writer, { "chunk_size": 4 });

let cloned = writer.to_buffer();
assert_eq(Buffer.compare(buf, cloned), 0);
println("Piped bytes with 100% integrity:", total);
Chapter 15

Standard Builtin Functions Reference

All 180+ builtin functions are implemented natively in Go without external dependencies. They are indexed in compiler/builtins.go and executed via opcode OpGetBuiltin with zero overhead. Not a single builtin is omitted from this exhaustive reference:

1. Console Output & Standard I/O

BuiltinExact SignatureReturnDescription & Behavior
printprint(...args)NULLPrints space-separated arguments to stdout without a trailing newline.
printlnprintln(...args)NULLPrints space-separated arguments to stdout followed by a newline.
print_rawprint_raw(...args)NULLPrints raw arguments directly without space separators or trailing newline.
eprinteprint(...args)NULLPrints space-separated arguments to stderr (os.Stderr).
eprintlneprintln(...args)NULLPrints space-separated arguments to stderr followed by a newline.
inputinput([prompt])STRINGDisplays optional prompt and reads a line from stdin up to newline.
read_lineread_line([prompt])STRINGReads a line of text from standard input; supports terminal raw channel buffer.
ensure_newlineensure_newline()BOOLEANEmits a trailing newline to stdout if the last character written was not a newline; returns true if a newline was emitted, false otherwise.
colorcolor(name, text)STRINGWraps text in standard 16-color ANSI codes ("red", "green", etc.).
styledstyled(text, style)STRINGWraps text in ANSI style codes ("bold", "dim", "italic", "underline").

2. Type Conversion & Introspection

BuiltinExact SignatureReturnDescription & Behavior
intint(value)INTEGERConverts string, float, or boolean into 64-bit signed integer.
floatfloat(value)FLOATConverts integer or numeric string into 64-bit IEEE-754 float.
strstr(value)STRINGConverts any BramandScript runtime value into its string representation.
boolbool(value)BOOLEANEvaluates truthiness: false, null, 0, 0.0, "", and empty bytes() are falsy; non-empty strings, non-zero numbers, and objects are truthy.
typetype(object)STRINGReturns object type name ("INTEGER", "ARRAY", "HASH", "BYTES").
errorerror([message])ERRORInstantiates a structured runtime Error object with .message, .stack_trace, and .frames.

3. Arrays, Hashes & Collections

BuiltinExact SignatureReturnDescription & Behavior
lenlen(collection)INTEGERReturns element count of Array/Bytes, rune count of String, or pair count of Hash.
pushpush(array, elem)ARRAYThread-safe append of element into array; returns mutated array.
appendappend(array, elem)ARRAYAlias to push().
poppop(array)ANYThread-safe removal and return of last element. Returns null if empty.
sliceslice(coll, start, [end])COLLNegative index slicing for Array, String, or Bytes (slice(arr, -2)).
containscontains(coll, target)BOOLEANChecks item presence in Array, key existence in Hash, or substring in String.
keyskeys(hash)ARRAYReturns array containing all keys in hash map.
valuesvalues(hash)ARRAYReturns array containing all values in hash map.
deletedelete(hash, key)NULLThread-safe deletion of key from hash map.
sortsort(array)ARRAYReturns sorted copy of array (ascending numeric or lexical order).

4. String Processing Primitives

BuiltinExact SignatureReturnDescription & Behavior
substringsubstring(s, start, [end])STRINGRune-accurate substring extraction from start to optional end.
reversereverse(coll)COLLReturns reversed copy of String (rune-accurate) or Array.
splitsplit(s, sep)ARRAYSplits string into array of parts delimited by separator.
joinjoin(arr, sep)STRINGConcatenates array of elements into string separated by delimiter.
trimtrim(s, [cutset])STRINGTrims whitespace or characters matching cutset from both ends.
to_lowerto_lower(s)STRINGConverts string to lowercase.
to_upperto_upper(s)STRINGConverts string to uppercase.
replacereplace(s, old, new)STRINGReplaces all occurrences of old substring with new substring.

5. Concurrency & Synchronization

BuiltinExact SignatureReturnDescription & Behavior
chanchan([capacity])CHANNELInstantiates an unbuffered or buffered channel for thread-safe message passing. Provides instance methods: .send(val, [timeout_ms]), .try_send(val), .recv([timeout_ms]), .try_recv(), .close(), and property .capacity.
closeclose(channel)NULLCloses channel. Prevents further sends while allowing drain.
mutexmutex()MUTEXInstantiates mutual exclusion lock with .lock(), .unlock(), .try_lock().
wait_groupwait_group()WAIT_GROUPInstantiates synchronization counter with .add(), .done(), .wait().
sleepsleep(ms)NULLPauses execution thread for given duration in milliseconds.

6. Filesystem & Process Environment

BuiltinExact SignatureReturnDescription & Behavior
read_fileread_file(path)STRINGReads file contents as UTF-8 string or raises error.
write_filewrite_file(path, content)BOOLEANWrites content to file, creating parent directories automatically.
append_fileappend_file(path, content)BOOLEANAppends content to file.
delete_filedelete_file(path)BOOLEANRemoves file from filesystem.
file_existsfile_exists(path)BOOLEANReturns true if file or directory exists on filesystem.
list_dirlist_dir([path])ARRAYLists directory entry names. Defaults to ".".
chmodchmod(path, mode)BOOLEANChanges filesystem permission bits (e.g. 0755).
is_diris_dir(path)BOOLEANReturns true if path is a directory.
envenv([key])STRING | HASHReturns environment variable value, or full environment map.
set_envset_env(key, val)BOOLEANSets process environment variable.
execexec(cmd, [args...])HASHExecutes external command; returns {"stdout": str, "stderr": str, "code": int}.
args / argvargs() / argv()ARRAYReturns CLI arguments passed to the script as an array of strings.
exitexit([code])NULLTerminates runtime process immediately with optional exit code.

7. Clock, Epoch & ISO Timers

BuiltinExact SignatureReturnDescription & Behavior
nownow()INTEGERReturns current UNIX epoch in seconds.
time_nowtime_now()FLOATReturns high-resolution UNIX epoch timestamp in seconds with fractional precision.
time_mstime_ms()INTEGERReturns current UNIX epoch in milliseconds.
time_isotime_iso([timestamp])STRINGReturns ISO 8601 UTC timestamp string ("2026-11-04T12:00:00Z").
date_formatdate_format([ts], [fmt])STRINGFormats timestamp according to pattern (default: "2006-01-02 15:04:05").

8. Terminal Raw I/O & Keystrokes

BuiltinExact SignatureReturnDescription & Behavior
term_rawterm_raw(boolean)BOOLEANToggles terminal between raw mode (no echo/line buffer) and canonical sane mode.
term_sizeterm_size()HASHReturns active terminal window dimensions: {"cols": int, "rows": int}.
read_keyread_key([timeout_ms])STRINGReads a single keypress or SGR mouse event sequence with optional timeout.
poll_keypoll_key()STRINGNon-blocking instant poll of pending keyboard input.

9. Raw Byte Buffers, Binary I/O & Runes

BuiltinExact SignatureReturnDescription & Behavior
bytesbytes([size | str | arr])BYTESAllocates mutable binary byte buffer with thread-safe indexing and 1GB safety guardrail.
read_u8read_u8(bytes, offset)INTEGERReads unsigned 8-bit integer from byte buffer at given byte offset.
write_u8write_u8(bytes, offset, val)BYTESWrites unsigned 8-bit integer into byte buffer at given byte offset.
read_u16read_u16(b, off, [endian])INTEGERReads unsigned 16-bit integer (big-endian by default, or "le").
write_u16write_u16(b, off, v, [end])BYTESWrites unsigned 16-bit integer into byte buffer.
read_u32read_u32(b, off, [endian])INTEGERReads unsigned 32-bit integer (big-endian by default, or "le").
write_u32write_u32(b, off, v, [end])BYTESWrites unsigned 32-bit integer into byte buffer.
ordord(string)INTEGERReturns Unicode code point of the first rune in the given string.
chrchr(integer)STRINGConverts Unicode code point integer into a single-character UTF-8 string.

10. Dynamic Metaprogramming & Structural Interfaces

BuiltinExact SignatureReturnDescription & Behavior
evaleval(code_str, [session])ANYDynamically parses, compiles, and evaluates BramandScript source in an isolated child VM or persistent stateful session.
create_sessioncreate_session()SESSIONAllocates a persistent stateful evaluation session retaining global symbols, bindings, and constants across invocations.
session_varssession_vars(sess)HASHReturns a dictionary map of active user variables and values defined in an evaluation session.
disasmdisasm(code_or_closure)STRINGDisassembles source snippet or compiled closure function into human-readable bytecode instructions and constant table.
implementsimplements(obj, req)BOOLEANStructural duck typing validator; checks if object provides method names (supports embedded structs).

11. Arbitrary-Precision Big Numbers

BuiltinExact SignatureReturnDescription & Behavior
big_int / bigintbig_int(value)BIGINTConstructs 256-bit+ arbitrary precision integer from int, string, or BigInt.
big_float / bigfloatbig_float(val, [prec])BIGFLOATConstructs arbitrary precision floating-point number with custom bit precision.

12. Linear Algebra & Geometry

BuiltinExact SignatureReturnDescription & Behavior
vec / vectorvec(elements | ...nums)VECTORConstructs mathematical vector with .dot(), .cross(), .magnitude().
matrixmatrix(2d_arr | r, c, [fill])MATRIXConstructs numerical matrix with .mul(), .det(), .inv(), .transpose().

13. Mathematical & Transcendental Functions

BuiltinExact SignatureReturnDescription & Behavior
pipi()FLOATReturns mathematical constant PI (3.141592653589793).
ee()FLOATReturns Euler's number (2.718281828459045).
sin / cos / tansin(x) / cos(x) / tan(x)FLOATTrigonometric functions (argument in radians).
asin / acos / atanasin(x) / acos(x) / atan(x)FLOATInverse trigonometric functions.
atan2atan2(y, x)FLOATFour-quadrant inverse tangent of y and x.
sinh / cosh / tanhsinh(x) / cosh(x) / tanh(x)FLOATHyperbolic sine, cosine, and tangent.
sqrt / cbrtsqrt(x) / cbrt(x)FLOATSquare root (guards against x < 0) and cube root.
hypothypot(a, b)FLOATEuclidean hypotenuse without intermediate overflow: sqrt(a^2 + b^2).
log / log10 / log2log(x) / log10(x) / log2(x)FLOATNatural, base-10, and base-2 logarithms (guards against x <= 0).
exp / powexp(x) / pow(b, exp)FLOATExponential e^x and power function base^exp.
absabs(x)NUMBERAbsolute value of Integer, Float, BigInt, or BigFloat.
floor / ceil / roundfloor(x) / ceil(x) / round(x)INTEGERFloating-point rounding to integer.
trunctrunc(x)INTEGERTruncates decimal portion, returning integer value.
deg_to_rad / rad_to_degdeg_to_rad(d) / rad_to_deg(r)FLOATConverts between degrees and radians.
pow_modpow_mod(b, exp, mod)INTEGER | BIGINTFast modular exponentiation (b^exp % mod) for cryptographic and scientific sizes.
min / maxmin(...nums) / max(...nums)NUMBERFinds minimum or maximum number among arguments or array elements.

14. Statistical Calculations

BuiltinExact SignatureReturnDescription & Behavior
sumsum(array | ...nums)NUMBERCalculates arithmetic sum of numbers.
mean / math_meanmean(array | ...nums)FLOATCalculates arithmetic mean. Returns null if empty.
medianmedian(array | ...nums)FLOATCalculates median value of sample numbers.
modemode(array | ...nums)NUMBERCalculates most frequently occurring value in samples.
variancevariance(array | ...nums)FLOATComputes population variance: Σ(x - μ)^2 / N.
std_devstd_dev(array | ...nums)FLOATComputes standard deviation: sqrt(variance).

15. Formats & Serialization (JSON, CSV, Base64)

BuiltinExact SignatureReturnDescription & Behavior
json_parsejson_parse(json_str)ANYParses JSON text into native BramandScript hash or array.
json_stringifyjson_stringify(obj, [indent])STRINGSerializes BramandScript objects into JSON with optional indentation.
csv_parsecsv_parse(csv_str, [delim])ARRAYParses CSV formatted string into 2D array of string cells.
csv_stringifycsv_stringify(2d_arr, [delim])STRINGSerializes 2D array into CSV string with escaping.
base64_encode / base64_decodebase64_encode(s) / base64_decode(s)STRINGStandard RFC 4648 Base64 encoding and decoding.
base64_url_encode / base64_url_decodebase64_url_encode(s) / ...STRINGURL-safe Base64 encoding without padding characters.

16. Cryptography & CSPRNG

BuiltinExact SignatureReturnDescription & Behavior
sha256 / crypto_sha256sha256(data)STRINGComputes SHA-256 cryptographic digest as hexadecimal string.
sha512sha512(data)STRINGComputes SHA-512 cryptographic digest as hexadecimal string.
md5md5(data)STRINGComputes MD5 hash digest as hexadecimal string.
hmac_sha256 / crypto_hmachmac_sha256(key, msg)STRINGComputes HMAC-SHA256 authentication code as hexadecimal string.
random_bytesrandom_bytes([count])STRINGGenerates CSPRNG cryptographically secure random bytes (hex-encoded).
random_intrandom_int([min], max)INTEGERGenerates uniform CSPRNG random integer in range [min, max].
uuiduuid()STRINGGenerates an RFC 4122 Version 4 random UUID string.

17. Sockets, HTTP & WebSockets

BuiltinExact SignatureReturnDescription & Behavior
tcp_listentcp_listen(addr)TcpServerBinds TCP listener on address (e.g. ":9000"). Provides .accept().
tcp_connecttcp_connect(addr, [timeout])TcpConnConnects to TCP server with timeout; provides .read(), .write().
udp_listenudp_listen(addr)UdpSocketBinds UDP packet socket listener.
udp_connectudp_connect(addr)UdpSocketConnects UDP socket to remote address.
http_gethttp_get(url, [headers])HASHExecutes HTTP GET request; returns { status, status_code, body, headers, json }.
http_posthttp_post(url, body, [hdrs])HASHExecutes HTTP POST request with JSON or string payload.
http_puthttp_put(url, body, [hdrs])HASHExecutes HTTP PUT request.
http_deletehttp_delete(url, [headers])HASHExecutes HTTP DELETE request.
http_requesthttp_request(opts_hash)HASHUnified client API accepting method, url, body, headers, and timeout.
http_serverhttp_server()HttpServerInstantiates built-in low-level HTTP server engine (.get(), .post(), .static(), .listen()). For advanced radix-trie routing with parameterized (:id) or wildcard (*path) routes and middleware, use import "std/net".
ws_connectws_connect(url)WsConnConnects to RFC 6455 WebSocket (ws:// or wss:// with strict TLS).
ws_serverws_server(addr, [path])WsServerBinds WebSocket server listener with .accept().

18. AI Integration & Vector Similarity Search

BuiltinExact SignatureReturnDescription & Behavior
ai_promptai_prompt(model, prompt, [opts])STRINGQueries LLM endpoint (OpenAI / Ollama / Gemini API compatible).
ai_streamai_stream(opts, callback)NULLStreams SSE response tokens in real-time, invoking callback per chunk.
ai_structuredai_structured(opts, schema)HASHEnforces JSON schema validation on LLM output and returns native Hash.
cosine_similaritycosine_similarity(v1, v2)FLOATComputes cosine similarity between two numeric vectors in range [-1.0, 1.0].
cosine_distancecosine_distance(v1, v2)FLOATComputes cosine distance: 1.0 - cosine_similarity.
euclidean_distanceeuclidean_distance(v1, v2)FLOATComputes geometric Euclidean distance between two vectors.
manhattan_distancemanhattan_distance(v1, v2)FLOATComputes L1 Manhattan distance between two vectors.
vector_searchvector_search(query, cands, [k])ARRAYK-nearest-neighbor search ranking candidate embeddings by vector similarity.

19. Test Runner, Benchmarking & Diagnostics

BuiltinExact SignatureReturnDescription & Behavior
assertassert(cond, [msg])NULLAsserts condition is truthy; raises fatal AssertionError if falsy.
assert_trueassert_true(cond, [msg])BOOLEANAsserts condition evaluates to truthy; raises AssertionError if falsy.
assert_falseassert_false(cond, [msg])BOOLEANAsserts condition evaluates to falsy (false, null, 0, 0.0, "", or empty bytes()); raises AssertionError if truthy.
assert_eqassert_eq(actual, expected, [msg])NULLAsserts deep structural equality with cyclic structure protection and formatted diff.
assert_neassert_ne(actual, expected, [msg])NULLAsserts that two values are not structurally equal.
panicpanic([msg])NULLHalts VM execution immediately with an explicit fatal panic.
throwthrow(value)NULLRaises a catchable runtime exception with an arbitrary payload value (can also be invoked via statement syntax: throw expr;).
testtest(name, fn)BOOLEANExecutes isolated test block, measuring duration and catching assertion failures.
describedescribe(suite_name, fn)NULLGroups related tests under a common suite heading with duration aggregation.
benchmarkbenchmark(name, fn, [iters])HASHRuns warmup and iterations loop; returns {"name", "iterations", "total_ms", "ops_per_sec"}.

20. Compression & Archiving Engine (std/compress)

BuiltinExact SignatureReturnDescription & Behavior
gzip_compressgzip_compress(data)BYTESCompresses bytes or string using pure Go standard library gzip.
gzip_decompressgzip_decompress(data)BYTESDecompresses gzip archive bytes back to raw byte stream.
zlib_compresszlib_compress(data)BYTESDeflates byte payload with RFC 1950 zlib compression.
zlib_decompresszlib_decompress(data)BYTESInflates zlib compressed byte payload back to original contents.
tar_packtar_pack(files_hash_or_array)BYTESPackages multi-file directory hierarchy into standard POSIX tar archive.
tar_unpacktar_unpack(tar_bytes)HASHExtracts tar archive into file name to byte payload map.

21. Binary Serialization & Struct Packing (std/binary/pack)

BuiltinExact SignatureReturnDescription & Behavior
struct_packstruct_pack(fmt, values)BYTESPython-style binary struct packing (>I, <h, f, d, b, B, s, etc.).
struct_unpackstruct_unpack(fmt, data)ARRAYUnpacks binary byte sequence according to format specifier.
struct_calcsizestruct_calcsize(fmt)INTCalculates byte length required for specified format string.
msgpack_encodemsgpack_encode(val)BYTESHigh-speed binary MessagePack encoding for primitives, arrays, and hashes.
msgpack_decodemsgpack_decode(bytes)OBJECTDecodes MessagePack binary data back into native BramandScript objects.

22. Modern Cryptography Suite (std/crypto/advanced)

BuiltinExact SignatureReturnDescription & Behavior
aes_gcm_encryptaes_gcm_encrypt(key, pt, [nonce], [aad])HASHAES-256-GCM authenticated symmetric encryption with 128-bit integrity tag.
aes_gcm_decryptaes_gcm_decrypt(key, ct, [nonce], [aad])BYTESDecrypts and verifies authenticated AES-256-GCM ciphertext payload.
ed25519_keypaired25519_keypair()HASHGenerates cryptographically secure Ed25519 public/private keypair.
ed25519_signed25519_sign(priv_key, message)BYTESGenerates 64-byte Ed25519 digital signature over message.
ed25519_verifyed25519_verify(pub_key, msg, sig)BOOLVerifies Ed25519 signature validity against public key.
jwt_signjwt_sign(payload, secret, [alg])STRINGGenerates signed JSON Web Token (HS256 HMAC or EdDSA Ed25519).
jwt_verifyjwt_verify(token, secret, [alg])HASHValidates JWT signature, decoding header and verified payload hash.

23. Compiler & VM Iteration Helpers

The following four builtins are internal execution primitives compiled into bytecode by the Pratt parser to power zero-allocation, high-throughput for-in loop iterations over Arrays, Hashes, Strings, and raw Bytes:

Internal BuiltinExact SignatureReturnDescription & Behavior
__iter_len__iter_len(collection)INTEGERReturns the exact element count or key length for iteration loop boundaries.
__iter_key__iter_key(collection, index)ANYReturns the current iteration key (string key for hashes, integer index for arrays/strings/bytes).
__iter_val__iter_val(collection, index)ANYRetrieves the collection value element at the current iteration position.
__iter_item__iter_item(collection, index)ARRAYYields a 2-element tuple [key, val] for dual-variable iteration loops.

24. Native Reactive Event Streams (std/stream)

High-performance push/pull reactive stream pipelines with backpressure flow control signals, windowed operators, and multiplexing combinators:

Stream Function / MethodExact SignatureReturnDescription & Behavior
streamstream(source)HASHCreates reactive stream from array, channel, or custom generator function.
stream.maps.map(fn)HASHTransforms emitted items using mapping function.
stream.filters.filter(pred)HASHFilters stream items according to predicate truthiness.
stream.windows.window(size)HASHBatches incoming events into chunks of fixed size.
stream.debounces.debounce(ms)HASHSuppresses rapid successive items until quiet period elapses.
stream.throttles.throttle(ms)HASHLimits emission frequency, enforcing minimum millisecond gap.
stream.zips1.zip(s2)HASHCombines two streams pairwise into 2-element arrays.
stream.concats1.concat(s2)HASHSequentially emits all items of first stream then second stream.
stream.switch_maps.switch_map(fn)HASHProjects each item to an inner stream, canceling prior active inner stream.
stream.collects.collect()ARRAYCollects all emitted stream items into a concrete array.

25. In-Memory Relational SQL Suite (std/sql)

ANSI SQL parser, query planner, and relational query engine executing joins, filters, and aggregations across in-memory datasets and DataFrames:

SQL FunctionExact SignatureReturnDescription & Behavior
sql_query / sql.querysql.query(sql_str, tables)ARRAYExecutes SELECT with WHERE, JOIN (INNER, LEFT), GROUP BY, HAVING, ORDER BY, and LIMIT over dataset tables.
sql.parsesql.parse(sql_str)HASHParses ANSI SQL string into structured AST node.
sql.plansql.plan(ast)HASHGenerates optimized query execution plan.
sql.databasesql.database(tables)HASHCreates managed in-memory relational database with .query() and .insert().

26. Local AI Vector Metrics & Spatial Index (std/ai)

Pure Go stdlib hardware floating-point accelerated metrics, K-Nearest Neighbors (KNN) spatial index, and RAG document chunking pipeline:

AI PrimitiveExact SignatureReturnDescription & Behavior
cosine_similaritycosine_similarity(v1, v2)FLOATComputes normalized cosine similarity [-1.0, 1.0].
cosine_distancecosine_distance(v1, v2)FLOATComputes cosine distance (1.0 - cosine_similarity).
euclidean_distanceeuclidean_distance(v1, v2)FLOATComputes straight-line L2 geometric distance.
manhattan_distancemanhattan_distance(v1, v2)FLOATComputes L1 grid taxicab distance.
dot_productdot_product(v1, v2)FLOATComputes algebraic dot product of two vectors.
vector_normalizevector_normalize(v)ARRAYComputes unit vector with L2 norm equal to 1.0.
ai.new_indexai.new_index(metric)HASHCreates K-Nearest Neighbors spatial index with .add(), .search(), .save(), and .load().
ai.chunk_textai.chunk_text(text, opts)ARRAYSemantic sliding window text chunker with configurable chunk size and overlap.
ai.build_rag_contextai.build_rag_context(query, idx, k)STRINGRetrieves top-k hits and formats into clean RAG LLM prompt context block.