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.
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.
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
| Constant | Type | Value | Description |
|---|---|---|---|
PI | FLOAT | 3.141592653589793 | Ratio of circle circumference to diameter (Archimedes constant). |
E | FLOAT | 2.718281828459045 | Euler's number and base of natural logarithms. |
LN2 | FLOAT | 0.6931471805599453 | Natural logarithm of 2. |
LN10 | FLOAT | 2.302585092994046 | Natural logarithm of 10. |
SQRT2 | FLOAT | 1.4142135623730951 | Square root of 2 (Pythagoras constant). |
EPSILON | FLOAT | 2.220446e-16 | Machine epsilon representing difference between 1.0 and next representable float. |
Exported Functions
| Function | Signature | Return | Description & Edge Cases |
|---|---|---|---|
min | min(a, b) | NUMBER | Returns the smaller of two numbers. Compatible with Integer and Float. |
max | max(a, b) | NUMBER | Returns the greater of two numbers. |
clamp | clamp(val, min_val, max_val) | NUMBER | Clamps val within range [min_val, max_val]. |
sign | sign(x) | INTEGER | Returns 1 if positive, -1 if negative, 0 if zero. |
deg_to_rad | deg_to_rad(deg) | FLOAT | Converts angle in degrees to radians: deg * (PI / 180.0). |
rad_to_deg | rad_to_deg(rad) | FLOAT | Converts angle in radians to degrees: rad * (180.0 / PI). |
is_even | is_even(n) | BOOLEAN | Tests if integer n is evenly divisible by 2. |
is_odd | is_odd(n) | BOOLEAN | Tests if integer n is not evenly divisible by 2. |
gcd | gcd(a, b) | INTEGER | Computes Greatest Common Divisor using iterative Euclidean algorithm. Handles negative values. |
lcm | lcm(a, b) | INTEGER | Computes Least Common Multiple: (a / gcd(a, b)) * b. Returns 0 if either is 0. |
factorial | factorial(n) | INTEGER | Computes n! iteratively without stack recursion. Returns 1 for n <= 1. |
sum | sum(arr) | NUMBER | Calculates the arithmetic sum of numbers in an array. |
avg | avg(arr) | FLOAT | Calculates arithmetic mean. Safely returns 0.0 when array is empty. |
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
| Function | Signature | Return | Description & Edge Cases |
|---|---|---|---|
repeat | repeat(s, count) | STRING | Repeats string s by count times. Returns empty string if count <= 0. |
pad_left | pad_left(s, len, pad_char) | STRING | Pads left side of string to target length using single pad character. |
pad_right | pad_right(s, len, pad_char) | STRING | Pads right side of string to target length using single pad character. |
char_at | char_at(s, idx) | STRING | Returns single character at 0-based index. Returns "" if out of bounds. |
slice | slice(s, start, end) | STRING | Extracts substring from start up to end with boundary clamping. |
starts_with | starts_with(s, prefix) | BOOLEAN | Tests if string begins with prefix. Safe when prefix length exceeds string. |
ends_with | ends_with(s, suffix) | BOOLEAN | Tests if string ends with suffix. Safe when suffix length exceeds string. |
capitalize | capitalize(s) | STRING | Capitalizes initial character and preserves remainder. Returns "" on empty input. |
reverse | reverse(s) | STRING | Reverses string characters. |
is_empty | is_empty(s) | BOOLEAN | Returns true if string has zero length after trimming whitespace. |
truncate | truncate(s, max_len, suffix) | STRING | Truncates string to max length and attaches suffix (e.g. "..."). |
words | words(s) | ARRAY | Splits whitespace-trimmed string into an array of non-empty words. |
slugify | slugify(s) | STRING | Generates lower-case hyphen-separated URL slug from input string. |
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
| Function | Signature | Return | Description & Edge Cases |
|---|---|---|---|
map | map(arr, transform) | ARRAY | Transforms every element using callable transform(elem). |
filter | filter(arr, predicate) | ARRAY | Filters elements where predicate(elem) evaluates to truthy. |
reduce | reduce(arr, accum, initial) | ANY | Folds array from left with accum(res, elem) starting at initial. |
find | find(arr, predicate) | ANY | Returns first element where predicate(elem) is true, or null. |
find_index | find_index(arr, predicate) | INTEGER | Returns 0-based index of first matching element, or -1. |
every | every(arr, predicate) | BOOLEAN | Returns true only if predicate(elem) is truthy for all elements. |
some | some(arr, predicate) | BOOLEAN | Returns true if predicate(elem) is truthy for at least one element. |
contains_item | contains_item(arr, target) | BOOLEAN | Tests if array contains target item using structural equality. |
unique | unique(arr) | ARRAY | Returns deduplicated array preserving original insertion order. |
flatten | flatten(arr) | ARRAY | Recursively flattens arbitrarily nested multi-dimensional arrays into 1D array. |
chunk | chunk(arr, size) | ARRAY | Splits array into subarrays of specified size. Returns [] if size <= 0. |
zip | zip(arr1, arr2) | ARRAY | Pairs corresponding elements into [[a1, b1], [a2, b2], ...] up to shortest length. |
take | take(arr, n) | ARRAY | Returns new array with the first n elements. Clamped to array length. |
drop | drop(arr, n) | ARRAY | Returns new array omitting the first n elements. |
count | count(arr, predicate) | INTEGER | Counts total elements satisfying predicate. |
reverse_array | reverse_array(arr) | ARRAY | Returns new array in reversed order without mutating original. |
group_by | group_by(arr, key_fn) | HASH | Groups array elements into hash partitions mapped by key_fn(elem). |
key_by | key_by(arr, key_fn) | HASH | Indexes elements into a hash mapped by unique key from key_fn(elem). |
partition | partition(arr, predicate) | ARRAY | Splits array into two arrays: [matches, non_matches]. |
flat_map | flat_map(arr, transform) | ARRAY | Maps each element using transform function and flattens result by one level. |
compact | compact(arr) | ARRAY | Filters out all null values from array. |
sum_by | sum_by(arr, fn_num) | NUMBER | Calculates arithmetic sum of numerical values returned by fn_num(elem). |
min_by | min_by(arr, fn_val) | ANY | Returns array element that yields minimal value under fn_val(elem). |
max_by | max_by(arr, fn_val) | ANY | Returns array element that yields maximal value under fn_val(elem). |
frequencies | frequencies(arr) | HASH | Counts occurrences of each distinct element, returning frequency map. |
difference | difference(arr1, arr2) | ARRAY | Returns elements in arr1 that do not occur in arr2. |
intersection | intersection(arr1, arr2) | ARRAY | Returns distinct elements present in both arr1 and arr2. |
union | union(arr1, arr2) | ARRAY | Returns deduplicated combined elements from both arr1 and arr2. |
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
| Function | Signature | Return | Description & Edge Cases |
|---|---|---|---|
parse | parse(raw_str) | ANY | Parses valid JSON text into native BramandScript hash, array, string, number, or boolean. |
stringify | stringify(val) | STRING | Serializes BramandScript objects into a compact JSON string. |
safe_parse | safe_parse(raw_str, default_val) | ANY | Parses JSON text; if an error or invalid syntax is encountered, returns default_val cleanly without halting. |
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
| Function | Signature | Return | Description & Edge Cases |
|---|---|---|---|
read_text | read_text(path) | STRING | Reads complete file contents into a UTF-8 string. |
write_text | write_text(path, content) | BOOLEAN | Writes content to file, creating parent directories if necessary. |
append_text | append_text(path, content) | BOOLEAN | Appends content to file (creates file if non-existent). |
exists | exists(path) | BOOLEAN | Returns true if file or directory exists on filesystem. |
remove | remove(path) | BOOLEAN | Deletes specified file from filesystem. |
list_directory | list_directory(path) | ARRAY | Returns array of entry names in the specified directory. |
println | println(msg) | NULL | Prints message followed by newline. |
print_header | print_header(title) | NULL | Prints centered header enclosed in clean Unicode divider lines. |
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
| Function | Signature | Return | Description & Edge Cases |
|---|---|---|---|
assert_true | assert_true(cond, [msg]) | BOOLEAN | Asserts that condition evaluates to truthy. Exits with status 1 on failure. |
assert_false | assert_false(cond, [msg]) | BOOLEAN | Asserts that condition evaluates to falsy (false or null). |
assert_null | assert_null(val, [msg]) | BOOLEAN | Asserts that value is strictly null. |
assert_not_null | assert_not_null(val, [msg]) | BOOLEAN | Asserts that value is not null. |
assert_eq | assert_eq(actual, expected, [msg]) | NULL | Builtin: Performs deep structural equality check with formatted failure diff and cyclic protection. |
assert_ne | assert_ne(actual, expected, [msg]) | NULL | Builtin: Asserts that two values are not structurally equal. |
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
| Submodule | Signature | Return | Description & Capabilities |
|---|---|---|---|
std/tooling | import "std/tooling" as tool | HASH | Unified developer tooling framework re-exporting start_repl, run_cli, run_test_suites, run_pkg, disassemble, and format_source. |
std/tooling/repl | start_repl() | NULL | Interactive terminal REPL with multi-line delimiter tracking, session state persistence, syntax coloring, and commands (:help, :clear, :reset, :env, :type, :time, :disasm, :exit). |
std/tooling/cli | run_cli(args) | INT | Master CLI router supporting run, repl, test, fmt, pkg, disasm, bench, info, version, and help. |
std/tooling/test_runner | run_test_suites(paths) | INT | Automated test discovery and execution engine with execution timing, passed/failed counters, and formatted status reporting. |
std/tooling/pkg | run_pkg(args) | INT | Package manager CLI interface supporting list, install, remove, init, and path for ~/.bramand_libs/. |
std/tooling/disasm | disassemble(target) | STRING | Disassembles source code strings or closure functions into annotated bytecode instructions and constant table. |
std/tooling/fmt | format_source(src) | STRING | Canonical source code formatter applying 4-space indentation, operator spacing, and block normalizations. |
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
| Member | Signature | Return | Description |
|---|---|---|---|
new_logger | new_logger([level, format, sink]) | HASH | Creates a customized logger instance with specified level, format ("text" or "json"), and output callback sink. |
debug | debug(msg, [fields]) | NULL | Emits a DEBUG level log entry using default logger. |
info | info(msg, [fields]) | NULL | Emits an INFO level log entry using default logger. |
warn | warn(msg, [fields]) | NULL | Emits a WARN level log entry using default logger. |
err | err(msg, [fields]) | NULL | Emits an ERROR level log entry using default logger. |
set_level | set_level(level) | NULL | Updates the minimum log level filter on the default logger. |
set_format | set_format(fmt) | NULL | Sets output format to "text" or "json" on the default logger. |
LEVEL_DEBUG, LEVEL_INFO, LEVEL_WARN, LEVEL_ERROR | 10, 20, 30, 40 | INT | Integer constants representing severity levels. |
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
| Function | Signature | Return | Description |
|---|---|---|---|
with_backoff | with_backoff(operation, [max_retries, initial_delay_ms, max_delay_ms, factor]) | ANY | Executes operation with exponential backoff delay growth until success or max retries exhausted. |
with_linear | with_linear(operation, [max_retries, step_ms]) | ANY | Executes operation with linearly increasing delays: attempt * step_ms. |
with_fixed | with_fixed(operation, [max_retries, delay_ms]) | ANY | Executes operation with constant delay intervals between failed attempts. |
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
| Function | Signature | Return | Description |
|---|---|---|---|
parse_dotenv | parse_dotenv(content) | HASH | Parses dotenv format text supporting # comments, export KEY=VAL, and quoted strings. |
parse_ini | parse_ini(content) | HASH | Parses INI configuration with [section] headers and key-value properties. |
get | get(config, key, [default_val]) | ANY | Safely retrieves value for key, returning default_val (or null) if absent. |
get_or_default | get_or_default(config, key, default_val) | ANY | Retrieves value or default fallback. |
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
| Member | Signature | Return | Description & Behavior |
|---|---|---|---|
v4 | v4() | STRING | Generates a cryptographically secure random RFC 4122 version 4 UUID string. |
new | new() | STRING | Alias for v4(). |
validate | validate(id) | BOOLEAN | Validates whether string is a properly formatted 36-character hexadecimal UUID with hyphens. |
version | version(id) | INTEGER | Returns the UUID version integer (e.g. 4), or -1 if invalid. |
parse | parse(id) | HASH | Parses UUID into {"valid", "error", "version", "variant", "time_low", "time_mid", "time_hi_and_version", "clock_seq", "node", "raw"}. |
nil_uuid | nil_uuid() | STRING | Returns canonical nil UUID string ("00000000-0000-0000-0000-000000000000"). |
is_nil | is_nil(id) | BOOLEAN | Returns true if the specified ID equals the nil UUID string. |
NIL_UUID | NIL_UUID | STRING | Constant representing the 36-character nil UUID. |
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 / Method | Signature | Return | Description & Behavior |
|---|---|---|---|
new | new([capacity = 1]) | HASH | Creates a counting semaphore initialized with the specified permit capacity (minimum 1). |
acquire | sem.acquire() | BOOLEAN | Blocks until a permit is available, decrements the available counter, and returns true. |
try_acquire | sem.try_acquire() | BOOLEAN | Attempts immediate non-blocking acquisition. Returns true if acquired, false if at capacity. |
release | sem.release() | BOOLEAN | Releases a permit back to the semaphore, unblocking waiting tasks. Returns true. |
available | sem.available() | INTEGER | Returns current number of available permits. |
capacity | sem.capacity() | INTEGER | Returns total configured permit capacity. |
with_permit | sem.with_permit(action) | ANY | Acquires permit, executes action(), guarantees release() via defer, and returns result. |
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
| Member | Signature | Return | Description & Behavior |
|---|---|---|---|
new | new([options]) | HASH | Instantiates a circuit breaker with options: failure_threshold, reset_timeout, half_open_success_threshold, and fallback. |
execute | cb.execute(operation, [fallback]) | HASH | Runs operation protected by breaker. Returns {"ok", "fallback_used", "result", "error", "circuit_open", "state"}. |
state | cb.state() | STRING | Returns current state ("CLOSED", "OPEN", "HALF_OPEN"). Auto-transitions after timeout. |
trip | cb.trip() | NULL | Manually trips the circuit breaker into the OPEN state. |
reset | cb.reset() | NULL | Manually resets breaker to CLOSED state and clears consecutive failures. |
metrics | cb.metrics() | HASH | Returns 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" | STRING | Enumeration constants for circuit breaker states. |
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 / Method | Signature | Return | Description & Behavior |
|---|---|---|---|
new | new([num_workers = 4]) | HASH | Creates a concurrent worker pool with fixed number of Goroutines (minimum 1). |
map | pool.map(items, worker_fn) | ARRAY | Concurrently processes items with worker_fn(item); preserves exact input index order and captures errors cleanly. |
execute_all | pool.execute_all(jobs_list) | ARRAY | Concurrently runs an array of parameterless task functions [fn() { ... }, ...]. |
workers | pool.workers() | INTEGER | Returns the number of active worker tasks configured in the pool. |
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, 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:
24-bit TrueColor, HEX to RGB conversion, linear gradients, neon palettes.
ANSI escape stripping, visible string length, padding (left, right, center), truncation.
Screen clearing, cursor repositioning, cursor visibility, terminal size detection.
Unicode box rendering with styles (rounded, single, double, heavy, ascii) and title header.
Badges, status indicators, key-value metrics, cards, dividers, and alert banners.
Auto-sizing column layout, alignment (left/right/center), and header dividers.
High-resolution 1/8th sub-block progress bars, gradients, and animated spinners.
Unicode sparklines ( ▂▃▄▅▆▇█) and horizontal normalized bar charts.
Hierarchical tree view rendering with branch guides (├──, └──, │).
Text prompts, boolean confirmations, password masking, single-choice selection.
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 / Constant | Signature | Return | Description |
|---|---|---|---|
rgb | rgb(r, g, b) | STRING | Foreground 24-bit TrueColor ANSI escape sequence: \033[38;2;R;G;Bm. |
bg_rgb | bg_rgb(r, g, b) | STRING | Background 24-bit TrueColor ANSI escape sequence: \033[48;2;R;G;Bm. |
hex | hex(hex_str) | STRING | Parses HEX color ("#00f0ff" or "00f0ff") into foreground TrueColor ANSI code. |
bg_hex | bg_hex(hex_str) | STRING | Parses HEX color into background TrueColor ANSI code. |
rgb_to_hex | rgb_to_hex(r, g, b) | STRING | Encodes RGB triplet into 6-digit hex string with leading hash (e.g. "#38bdf8"). |
hex_to_rgb | hex_to_rgb(hex_str) | ARRAY | Decodes HEX string into integer array [r, g, b]. |
gradient | gradient(text, start_hex, end_hex) | STRING | Renders smooth linear gradient text interpolated from start HEX to end HEX. |
Palette Constants | NEON_CYAN, NEON_PINK, ... | STRING | Cyberpunk neon constants: #00f0ff, #ff007f, #00ff66, #ffe600, #b026ff, #ff5500. |
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:
| Function | Signature | Return | Description |
|---|---|---|---|
term_size | term_size() | HASH | Builtin: Returns {"cols": int, "rows": int} via stty/termios ioctl with env fallback. |
term_raw | term_raw(enable) | BOOLEAN | Builtin: Toggles raw mode (disables line buffering and echo; installs SIGINT restore handler). |
read_key | read_key([timeout_ms]) | STRING | Builtin: Reads keypress or escape sequence with optional timeout. Returns key name (e.g. "up", "enter"). |
poll_key | poll_key() | STRING | Builtin: Instant non-blocking keystroke check without delaying event loops. |
clear | clear() | NULL | Clears screen and repositions cursor to top-left (1, 1). |
cursor_to | cursor_to(x, y) | NULL | Repositions cursor to column x, row y. |
cursor_hide / cursor_show | cursor_hide() / cursor_show() | NULL | Hides or reveals the blinking terminal cursor. |
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 / Method | Signature | Return | Description |
|---|---|---|---|
new_table | new_table(headers, [options]) | Table | Instantiates an auto-sizing Table object with border options. |
Table.add_row | tbl.add_row(row_array) | Table | Appends a row of values. Returns table instance for chaining. |
Table.add_column | tbl.add_column(header, [align]) | Table | Appends column header with alignment ("left", "right", "center"). |
Table.render | tbl.render() | STRING | Renders complete auto-sized table string with Unicode borders. |
render_box | render_box(lines, [options]) | STRING | Renders box containing text lines with styles ("rounded", "single", "double", "heavy", "ascii"). |
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:
| Function | Signature | Return | Description |
|---|---|---|---|
render_bar | render_bar(cur, total, [opts]) | STRING | Smooth sub-block 1/8th resolution progress bar (█▉▊▋▌▍▎▏░) with linear color gradients. |
render_spinner | render_spinner(idx, [type]) | STRING | Cycles animated spinner frames ("dots", "line", "arc", "bounce"). |
sparkline | sparkline(numbers, [opts]) | STRING | In-line telemetry micro chart mapped across 8 vertical block levels ( ▂▃▄▅▆▇█). |
bar_chart_h | bar_chart_h(data_items, [opts]) | STRING | Horizontal bar chart where items are [label, value] with normalized bar scaling. |
render_tree | render_tree(root_node) | STRING | Renders tree hierarchy with branch guides (├──, └──, │). |
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:
| Function | Signature | Return | Description |
|---|---|---|---|
ask | ask(prompt, [default_val]) | STRING | Interactive user text prompt with optional default value fallback. |
confirm | confirm(prompt, [default_bool]) | BOOLEAN | Yes/No confirmation prompt (returns boolean true/false). |
secret | secret(prompt) | STRING | Raw mode masked password prompt displaying bullets (●●●●●). |
choose | choose(prompt, options) | STRING | Numbered single-choice selection menu. |
new_cli | new_cli(name, ver, desc) | CliApp | Constructs a CLI Application with subcommand routing and flag parsing. |
CliApp.command | app.command(name, desc, fn) | CliApp | Registers subcommand with handler: fn(ctx). |
CliApp.flag | app.flag(name, desc, def, [alias]) | CliApp | Registers flag with optional single-letter alias. |
CliApp.run | app.run(args_array) | INTEGER | Dispatches command matching and flag resolution. |
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())
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.
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)
Vectors & Matrices (Linear Algebra)
Perform linear algebra operations for numerical simulations, 3D graphics, machine learning algorithms, and physics modeling:
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
Trigonometric, Logarithmic & Statistical Library
All trigonometric, hyperbolic, transcendental, and statistical functions execute natively with zero external dependencies:
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
JSON, CSV & Base64 Serialization
Robust, zero-dependency serialization and deserialization primitives:
// 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)
Cryptography & CSPRNG (Secure Random & UUIDv4)
Cryptographically secure random number generation, secure UUID v4 tokens, SHA-256, SHA-512, MD5, and HMAC message authentication:
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, 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.
Radix Trie URL router supporting static, parameterized (:id), and wildcard (*path) routes.
HTTP request/response wrapper with query string parsing, case-insensitive headers, and JSON binding.
Composable onion pipeline with built-in cors, logger, rate_limit, and auth_bearer.
W3C Server-Sent Events formatter, ping keepalive heartbeats, and event stream parser.
Multi-room WebSocket broadcaster with targeted room dispatch and sender exclusion.
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 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.
Append-only WAL Key-Value storage engine with crash recovery and log compaction.
JSON document database with auto IDs, $set updates, and predicates ($gt, $in).
Fluent SQL and dataset query builder compiling to ANSI SQL and in-memory execution.
Active-Record schema validation layer (required, min_len, contains, in).
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
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).
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
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).
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")
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.
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 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).
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"
| Module | Constructors & Methods | Description |
|---|---|---|
std/math/rational | rational(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/decimal | decimal(val, [scale]).add(o), .sub(o), .mul(o), .div(o) | Fixed/arbitrary-scale decimal arithmetic for currencies, financial ledgers, and exact tax calculations. |
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:
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))
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.
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
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.
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]
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).
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]
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.
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 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.
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 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.
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 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.
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)
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
| Function | Signature | Return Type | Description |
|---|---|---|---|
now | dt.now() | HASH | Returns current datetime object with year, month, day, hour, iso, unix_ms, and methods. |
now_iso | dt.now_iso() | STRING | Returns current timestamp formatted as ISO 8601 / RFC 3339 string in UTC. |
now_ms | dt.now_ms() | INTEGER | Returns current epoch time in milliseconds. |
new | dt.new(year, month, day, [h=0, m=0, s=0]) | HASH | Constructs a datetime instance for specified calendar components. |
Date | dt.Date(year, month, day) | HASH | Constructs a calendar date instance initialized at midnight (00:00:00Z). |
parse | dt.parse(raw_str, [layout]) | HASH | Parses datetime string according to standard candidates or specified custom layout. |
format | dt.format(val, [layout]) | STRING | Formats datetime hash or epoch ms using layout tokens (e.g. "YYYY-MM-DD"). |
add | dt.add(val, amt, unit) | INTEGER | Adds amount of units ("days", "hours", "minutes", "seconds", "ms") to timestamp. |
diff | dt.diff(t1, t2, [unit = "ms"]) | FLOAT | INT | Calculates duration between two timestamps in specified unit. |
is_leap_year | dt.is_leap_year(year) | BOOLEAN | Determines if given Gregorian calendar year is a leap year. |
days_in_month | dt.days_in_month(year, month) | INTEGER | Returns total number of days (28–31) in given year and month. |
duration | dt.duration(ms) | HASH | Converts milliseconds into a map of total seconds, minutes, hours, and days. |
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
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
| Function | Signature | Return Type | Description |
|---|---|---|---|
join | path.join(a, b, [c, d, e]) | path.join(array) | STRING | Joins path elements into single normalized slash-delimited path. |
clean | path.clean(p) | STRING | Resolves ., .., and redundant slashes into canonical form. |
base | path.base(p) | STRING | Extracts trailing element of path (e.g. "file.txt"). |
dir | path.dir(p) | STRING | Returns directory path excluding the trailing file element. |
ext | path.ext(p) | STRING | Returns file extension starting with dot (e.g. ".bmd"). |
abs | path.abs(p) | STRING | Resolves relative path to absolute canonical filesystem path. |
is_abs | path.is_abs(p) | BOOLEAN | Checks if given path is absolute. |
split | path.split(p) | ARRAY | Splits path into [dir, file] array tuple. |
2. std/fs API Reference
| Function | Signature | Return Type | Description |
|---|---|---|---|
walk | fs.walk(path, [ext_filter]) | ARRAY | Recursively traverses directory tree, returning array of file entry hashes. |
glob | fs.glob(pattern) | ARRAY | Matches files matching shell pattern (e.g. "*.bmd", "src/**/*.go"). |
temp_file | fs.temp_file([prefix, ext]) | HASH | Creates a unique temporary file on the OS filesystem, returning path and name. |
tree | fs.tree(dir, [max_depth = -1]) | HASH | Builds a nested hierarchical JSON-serializable directory tree. |
stat | fs.stat(path) | HASH | Returns file metadata: path, name, size, is_dir, mode, mod_time. |
mkdir | fs.mkdir(path, [recursive = true]) | BOOLEAN | Creates directory path, creating parent directories when recursive is true. |
read_text | fs.read_text(path) | STRING | Reads complete contents of text file as UTF-8 string. |
write_text | fs.write_text(path, content) | BOOLEAN | Writes string contents into file, truncating existing content. |
append_text | fs.append_text(path, content) | BOOLEAN | Appends string content to end of file without truncating. |
exists | fs.exists(path) | BOOLEAN | Checks whether file or directory exists at path. |
remove | fs.remove(path) | BOOLEAN | Deletes specified file or empty directory. |
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"])
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
| Function | Signature | Return Type | Description |
|---|---|---|---|
hex_encode | enc.hex_encode(data) | STRING | Encodes byte buffer or string into lowercase hexadecimal representation. |
hex_decode | enc.hex_decode(hex_str) | STRING | Decodes hexadecimal string back into original raw string. |
url_encode | enc.url_encode(str) | STRING | Escapes characters for safe inclusion in URL query strings. |
url_decode | enc.url_decode(str) | STRING | Unescapes URL-encoded query string. |
url_parse_query | enc.url_parse_query(query_str) | HASH | Parses URL query string into key-value hash map. |
url_build_query | enc.url_build_query(hash) | STRING | Encodes key-value hash into canonical sorted URL query string. |
csv_parse | enc.csv_parse(str, [delim=",", headers=false]) | ARRAY | Parses CSV text into array of rows (or array of hashes if headers is true). |
csv_stringify | enc.csv_stringify(records, [delim=",", headers]) | STRING | Serializes array of records (arrays or hashes) into valid CSV string. |
base64_chunk | enc.base64_chunk(b64_str, [line_len=64]) | STRING | Splits long Base64 string with newline characters for MIME/PEM wrapping. |
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 (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))
| Method | Signature | Return Type | Description |
|---|---|---|---|
is_ok | res.is_ok() | BOOLEAN | Returns true if the Result is Ok. |
is_err | res.is_err() | BOOLEAN | Returns true if the Result is Err. |
unwrap | res.unwrap() | OBJECT | Returns inner value if Ok; raises fatal error if called on Err. |
unwrap_or | res.unwrap_or(fallback) | OBJECT | Returns inner value if Ok; returns fallback value if Err. |
unwrap_err | res.unwrap_err() | OBJECT | Extracts inner error value from Err. |
map | res.map(fn) | RESULT | Applies transformation function to inner value if Ok; preserves Err untouched. |
flat_map | res.flat_map(fn) | RESULT | Applies monadic function returning another Result, flattening the structure. |
2. Option Monad (Some(v) & None())
| Method | Signature | Return Type | Description |
|---|---|---|---|
is_some | opt.is_some() | BOOLEAN | Returns true if the Option contains a value (Some). |
is_none | opt.is_none() | BOOLEAN | Returns true if empty (None). |
unwrap | opt.unwrap() | OBJECT | Returns inner value if Some; raises error on None. |
unwrap_or | opt.unwrap_or(fallback) | OBJECT | Returns inner value if Some, otherwise fallback value. |
map | opt.map(fn) | OPTION | Applies transformation to inner value, wrapping back into Some. |
flat_map | opt.flat_map(fn) | OPTION | Monadic 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.
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
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
| Function | Signature | Return | Description |
|---|---|---|---|
net.create_server | net.create_server([addr], handler) | Server | Instantiates a TCP server wrapping net_listen_tcp. Dispatches incoming connections asynchronously. |
net.connect | net.connect(host, port, [on_connect]) | Socket | Dials a remote TCP server and returns a bidirectional streaming Socket instance. |
net.create_udp_socket | net.create_udp_socket([port_or_addr]) | UDPSocket | Binds a local UDP socket on specified port/address (default ephemeral port 0). |
net.dial_tls | net.dial_tls(addr, sni_name, timeout, [opts]) | Socket | Dials an encrypted TLS connection with mandatory Server Name Indication (SNI) verification. |
net.listen_tls | net.listen_tls(addr, cert_file, key_file) | Server | Binds an encrypted TLS listener using PEM certificate and private key files. |
2. Socket Instance Methods
| Method | Signature | Return | Description |
|---|---|---|---|
sock.read | sock.read([max_bytes]) | STRING | Reads up to max_bytes (default 4096) from the socket; returns null or EOF on close. |
sock.read_line | sock.read_line() | STRING | Reads a single line delimited by \n or \r\n from the internal buffer. |
sock.write | sock.write(data) | INTEGER | Writes string or byte slice data to the socket stream; returns number of bytes written. |
sock.set_timeout | sock.set_timeout(ms) | BOOLEAN | Sets read and write deadline timeout in milliseconds (0 clears timeout). |
sock.remote_addr | sock.remote_addr() | STRING | Returns remote peer IP and port address string (e.g. "192.168.1.5:49152"). |
sock.close | sock.close() | BOOLEAN | Closes the TCP connection and flushes remaining buffers. |
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();
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
| Function | Signature | Return | Description |
|---|---|---|---|
http.create_server | http.create_server(handler) | Server | Instantiates an HTTP server taking a callback fn(req, res) or a Trie Router. |
http.create_router | http.create_router() | Router | Constructs a Radix-Trie URL router with get, post, put, delete_req, group. |
http.get | http.get(url, [opts]) | Response | Sends HTTP GET request; response contains status, headers, body, json(), text(). |
http.post | http.post(url, body, [opts]) | Response | Sends HTTP POST request with automatic JSON body serialization. |
http.put | http.put(url, body, [opts]) | Response | Sends HTTP PUT request with payload and optional custom headers. |
http.delete_req | http.delete_req(url, [opts]) | Response | Sends HTTP DELETE request to target endpoint. |
http.request | http.request(options) | Response | Executes customized request with {"method", "url", "body", "headers", "timeout"}. |
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);
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
| Function | Signature | Return | Description |
|---|---|---|---|
ws.create_server | ws.create_server(port, on_connection) | Server | Instantiates a WebSocket server negotiating RFC 6455 handshakes and connection lifecycle. |
ws.connect | ws.connect(url, [on_open]) | Client | Dials a remote WebSocket endpoint (ws://), performs handshake, and returns connection. |
server.broadcast | server.broadcast(message) | INTEGER | Transmits text message to all active, non-closed client connections; returns count delivered. |
conn.send | conn.send(message) | BOOLEAN | Encodes and transmits an RFC 6455 text frame across the duplex socket. |
conn.ping | conn.ping([payload]) | BOOLEAN | Sends an RFC 6455 Ping control frame to verify peer liveness. |
conn.close | conn.close([code], [reason]) | BOOLEAN | Initiates graceful close handshake with status code (default 1000) and reason text. |
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);
});
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
| Function | Signature | Return | Description |
|---|---|---|---|
dns.resolve | dns.resolve(domain, [type], [server], [timeout]) | ARRAY | Resolves domain to array of record values (default type A, server "8.8.8.8:53"). |
dns.lookup | dns.lookup(domain, [server], [timeout]) | STRING | Convenience lookup returning the primary IPv4 address or null if unresolvable. |
dns.clear_cache | dns.clear_cache() | NULL | Flushes all in-memory DNS cache entries. |
dns.get_cache | dns.get_cache() | HASH | Returns snapshot of current cached domain records with expiration timestamps. |
dns.encode_query | dns.encode_query(domain, [type], [id]) | BYTES | Encodes RFC 1035 binary query packet ready for UDP socket transmission. |
dns.decode_response | dns.decode_response(bytes) | HASH | Parses binary DNS datagram, handling QNAME pointer compression (0xC0) and record sections. |
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);
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
| Function | Signature | Return | Description |
|---|---|---|---|
https.get | https.get(url, [opts]) | Response | Executes TLS-encrypted HTTPS GET request with automatic SNI negotiation. |
https.post | https.post(url, body, [opts]) | Response | Executes TLS-encrypted HTTPS POST request with JSON payload serialization. |
https.request | https.request(options) | Response | Generic encrypted request dispatcher supporting all standard HTTP methods over TLS. |
https.create_server | https.create_server(handler) | Server | Instantiates an HTTPS server wrapping a TLS listener with PEM certificate and key. |
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());
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 / Method | Signature | Return | Description |
|---|---|---|---|
process.spawn | process.spawn(command, [args]) | ChildProcess | Spawns an asynchronous child process with connected stdin, stdout, stderr streams. |
process.exec | process.exec(command, [opts]) | HASH | Executes command synchronously; returns {"exit_code", "stdout", "stderr"}. |
process.pipe | process.pipe(proc1, proc2) | ChildProcess | Pipes proc1.stdout directly into proc2.stdin via an asynchronous transfer coroutine. |
proc.stdin.write | proc.stdin.write(data) | INTEGER | Writes data to child process standard input stream. |
proc.stdin.end | proc.stdin.end([final_data]) | BOOLEAN | Closes subprocess standard input stream, triggering EOF in the child process. |
proc.stdout.read_all | proc.stdout.read_all() | STRING | Consumes and buffers all remaining standard output from the child process. |
proc.wait | proc.wait() | INTEGER | Waits for child process to terminate and returns integer exit status code. |
proc.kill | proc.kill([signal]) | BOOLEAN | Sends OS termination signal (SIGTERM or SIGKILL) to the child process. |
2. OS System Introspection (std/os)
| Field / Function | Type | Example | Description |
|---|---|---|---|
os.platform | STRING | "linux", "darwin" | Host operating system name. |
os.arch | STRING | "arm64", "amd64" | Host hardware CPU architecture. |
os.cpus() | INTEGER | 8 | Total number of logical CPU processing cores. |
os.memory() | HASH | {"alloc", "sys", "total_alloc"} | Current runtime memory allocations in bytes. |
os.get_env(key) | STRING | os.get_env("PATH") | Reads environment variable with optional default value. |
os.cwd() | STRING | "/home/bramand" | Returns current active working directory path. |
os.pid() | INTEGER | 14820 | Process identifier of the current BramandScript process. |
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"
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)
| Method | Signature | Return | Description |
|---|---|---|---|
Buffer.alloc | Buffer.alloc(size, [fill]) | Buffer | Allocates buffer of specified byte size pre-filled with integer value (default 0). |
Buffer.from | Buffer.from(data, [encoding]) | Buffer | Creates buffer from string ("utf8", "hex", "base64"), byte array, or raw bytes. |
Buffer.concat | Buffer.concat(list, [total_len]) | Buffer | Concatenates an array of buffers into a single continuous memory block. |
Buffer.compare | Buffer.compare(a, b) | INTEGER | Compares buffers lexicographically; returns 0 if identical, -1 if a < b, 1 if a > b. |
buf.read_uint32_be/le | buf.read_uint32_be(offset) | INTEGER | Reads a 32-bit unsigned integer in Big-Endian or Little-Endian order. |
buf.write_uint32_be/le | buf.write_uint32_be(val, offset) | Buffer | Writes a 32-bit unsigned integer in Big-Endian or Little-Endian order. |
buf.read_double_be/le | buf.read_double_be(offset) | FLOAT | Reads a 64-bit IEEE 754 double precision float at byte offset. |
buf.write_double_be/le | buf.write_double_be(val, offset) | Buffer | Writes a 64-bit IEEE 754 double precision float at byte offset. |
buf.copy | buf.copy(target, [tgt_start], [src_start], [src_end]) | INTEGER | Fast bulk memory copy between buffers; returns number of bytes copied. |
buf.slice | buf.slice([start], [end]) | Buffer | Returns a sub-buffer slice sharing underlying memory. |
2. Stream Combinators (std/io)
| Function | Signature | Return | Description |
|---|---|---|---|
io.BufferReader | io.BufferReader(buf) | Reader | Creates streaming reader over buffer with read(n), read_all(), seek(pos), is_eof(). |
io.BufferWriter | io.BufferWriter([capacity]) | Writer | Creates dynamically expanding buffer sink with write(data), to_buffer(), to_string(). |
io.pipe | io.pipe(readable, writable, [opts]) | INTEGER | Pipes data from readable stream to writable stream using chunked buffering; returns total bytes transferred. |
io.read_all | io.read_all(readable) | Buffer | Reads all remaining bytes from stream into a single contiguous Buffer. |
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);
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
| Builtin | Exact Signature | Return | Description & Behavior |
|---|---|---|---|
print | print(...args) | NULL | Prints space-separated arguments to stdout without a trailing newline. |
println | println(...args) | NULL | Prints space-separated arguments to stdout followed by a newline. |
print_raw | print_raw(...args) | NULL | Prints raw arguments directly without space separators or trailing newline. |
eprint | eprint(...args) | NULL | Prints space-separated arguments to stderr (os.Stderr). |
eprintln | eprintln(...args) | NULL | Prints space-separated arguments to stderr followed by a newline. |
input | input([prompt]) | STRING | Displays optional prompt and reads a line from stdin up to newline. |
read_line | read_line([prompt]) | STRING | Reads a line of text from standard input; supports terminal raw channel buffer. |
ensure_newline | ensure_newline() | BOOLEAN | Emits a trailing newline to stdout if the last character written was not a newline; returns true if a newline was emitted, false otherwise. |
color | color(name, text) | STRING | Wraps text in standard 16-color ANSI codes ("red", "green", etc.). |
styled | styled(text, style) | STRING | Wraps text in ANSI style codes ("bold", "dim", "italic", "underline"). |
2. Type Conversion & Introspection
| Builtin | Exact Signature | Return | Description & Behavior |
|---|---|---|---|
int | int(value) | INTEGER | Converts string, float, or boolean into 64-bit signed integer. |
float | float(value) | FLOAT | Converts integer or numeric string into 64-bit IEEE-754 float. |
str | str(value) | STRING | Converts any BramandScript runtime value into its string representation. |
bool | bool(value) | BOOLEAN | Evaluates truthiness: false, null, 0, 0.0, "", and empty bytes() are falsy; non-empty strings, non-zero numbers, and objects are truthy. |
type | type(object) | STRING | Returns object type name ("INTEGER", "ARRAY", "HASH", "BYTES"). |
error | error([message]) | ERROR | Instantiates a structured runtime Error object with .message, .stack_trace, and .frames. |
3. Arrays, Hashes & Collections
| Builtin | Exact Signature | Return | Description & Behavior |
|---|---|---|---|
len | len(collection) | INTEGER | Returns element count of Array/Bytes, rune count of String, or pair count of Hash. |
push | push(array, elem) | ARRAY | Thread-safe append of element into array; returns mutated array. |
append | append(array, elem) | ARRAY | Alias to push(). |
pop | pop(array) | ANY | Thread-safe removal and return of last element. Returns null if empty. |
slice | slice(coll, start, [end]) | COLL | Negative index slicing for Array, String, or Bytes (slice(arr, -2)). |
contains | contains(coll, target) | BOOLEAN | Checks item presence in Array, key existence in Hash, or substring in String. |
keys | keys(hash) | ARRAY | Returns array containing all keys in hash map. |
values | values(hash) | ARRAY | Returns array containing all values in hash map. |
delete | delete(hash, key) | NULL | Thread-safe deletion of key from hash map. |
sort | sort(array) | ARRAY | Returns sorted copy of array (ascending numeric or lexical order). |
4. String Processing Primitives
| Builtin | Exact Signature | Return | Description & Behavior |
|---|---|---|---|
substring | substring(s, start, [end]) | STRING | Rune-accurate substring extraction from start to optional end. |
reverse | reverse(coll) | COLL | Returns reversed copy of String (rune-accurate) or Array. |
split | split(s, sep) | ARRAY | Splits string into array of parts delimited by separator. |
join | join(arr, sep) | STRING | Concatenates array of elements into string separated by delimiter. |
trim | trim(s, [cutset]) | STRING | Trims whitespace or characters matching cutset from both ends. |
to_lower | to_lower(s) | STRING | Converts string to lowercase. |
to_upper | to_upper(s) | STRING | Converts string to uppercase. |
replace | replace(s, old, new) | STRING | Replaces all occurrences of old substring with new substring. |
5. Concurrency & Synchronization
| Builtin | Exact Signature | Return | Description & Behavior |
|---|---|---|---|
chan | chan([capacity]) | CHANNEL | Instantiates 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. |
close | close(channel) | NULL | Closes channel. Prevents further sends while allowing drain. |
mutex | mutex() | MUTEX | Instantiates mutual exclusion lock with .lock(), .unlock(), .try_lock(). |
wait_group | wait_group() | WAIT_GROUP | Instantiates synchronization counter with .add(), .done(), .wait(). |
sleep | sleep(ms) | NULL | Pauses execution thread for given duration in milliseconds. |
6. Filesystem & Process Environment
| Builtin | Exact Signature | Return | Description & Behavior |
|---|---|---|---|
read_file | read_file(path) | STRING | Reads file contents as UTF-8 string or raises error. |
write_file | write_file(path, content) | BOOLEAN | Writes content to file, creating parent directories automatically. |
append_file | append_file(path, content) | BOOLEAN | Appends content to file. |
delete_file | delete_file(path) | BOOLEAN | Removes file from filesystem. |
file_exists | file_exists(path) | BOOLEAN | Returns true if file or directory exists on filesystem. |
list_dir | list_dir([path]) | ARRAY | Lists directory entry names. Defaults to ".". |
chmod | chmod(path, mode) | BOOLEAN | Changes filesystem permission bits (e.g. 0755). |
is_dir | is_dir(path) | BOOLEAN | Returns true if path is a directory. |
env | env([key]) | STRING | HASH | Returns environment variable value, or full environment map. |
set_env | set_env(key, val) | BOOLEAN | Sets process environment variable. |
exec | exec(cmd, [args...]) | HASH | Executes external command; returns {"stdout": str, "stderr": str, "code": int}. |
args / argv | args() / argv() | ARRAY | Returns CLI arguments passed to the script as an array of strings. |
exit | exit([code]) | NULL | Terminates runtime process immediately with optional exit code. |
7. Clock, Epoch & ISO Timers
| Builtin | Exact Signature | Return | Description & Behavior |
|---|---|---|---|
now | now() | INTEGER | Returns current UNIX epoch in seconds. |
time_now | time_now() | FLOAT | Returns high-resolution UNIX epoch timestamp in seconds with fractional precision. |
time_ms | time_ms() | INTEGER | Returns current UNIX epoch in milliseconds. |
time_iso | time_iso([timestamp]) | STRING | Returns ISO 8601 UTC timestamp string ("2026-11-04T12:00:00Z"). |
date_format | date_format([ts], [fmt]) | STRING | Formats timestamp according to pattern (default: "2006-01-02 15:04:05"). |
8. Terminal Raw I/O & Keystrokes
| Builtin | Exact Signature | Return | Description & Behavior |
|---|---|---|---|
term_raw | term_raw(boolean) | BOOLEAN | Toggles terminal between raw mode (no echo/line buffer) and canonical sane mode. |
term_size | term_size() | HASH | Returns active terminal window dimensions: {"cols": int, "rows": int}. |
read_key | read_key([timeout_ms]) | STRING | Reads a single keypress or SGR mouse event sequence with optional timeout. |
poll_key | poll_key() | STRING | Non-blocking instant poll of pending keyboard input. |
9. Raw Byte Buffers, Binary I/O & Runes
| Builtin | Exact Signature | Return | Description & Behavior |
|---|---|---|---|
bytes | bytes([size | str | arr]) | BYTES | Allocates mutable binary byte buffer with thread-safe indexing and 1GB safety guardrail. |
read_u8 | read_u8(bytes, offset) | INTEGER | Reads unsigned 8-bit integer from byte buffer at given byte offset. |
write_u8 | write_u8(bytes, offset, val) | BYTES | Writes unsigned 8-bit integer into byte buffer at given byte offset. |
read_u16 | read_u16(b, off, [endian]) | INTEGER | Reads unsigned 16-bit integer (big-endian by default, or "le"). |
write_u16 | write_u16(b, off, v, [end]) | BYTES | Writes unsigned 16-bit integer into byte buffer. |
read_u32 | read_u32(b, off, [endian]) | INTEGER | Reads unsigned 32-bit integer (big-endian by default, or "le"). |
write_u32 | write_u32(b, off, v, [end]) | BYTES | Writes unsigned 32-bit integer into byte buffer. |
ord | ord(string) | INTEGER | Returns Unicode code point of the first rune in the given string. |
chr | chr(integer) | STRING | Converts Unicode code point integer into a single-character UTF-8 string. |
10. Dynamic Metaprogramming & Structural Interfaces
| Builtin | Exact Signature | Return | Description & Behavior |
|---|---|---|---|
eval | eval(code_str, [session]) | ANY | Dynamically parses, compiles, and evaluates BramandScript source in an isolated child VM or persistent stateful session. |
create_session | create_session() | SESSION | Allocates a persistent stateful evaluation session retaining global symbols, bindings, and constants across invocations. |
session_vars | session_vars(sess) | HASH | Returns a dictionary map of active user variables and values defined in an evaluation session. |
disasm | disasm(code_or_closure) | STRING | Disassembles source snippet or compiled closure function into human-readable bytecode instructions and constant table. |
implements | implements(obj, req) | BOOLEAN | Structural duck typing validator; checks if object provides method names (supports embedded structs). |
11. Arbitrary-Precision Big Numbers
| Builtin | Exact Signature | Return | Description & Behavior |
|---|---|---|---|
big_int / bigint | big_int(value) | BIGINT | Constructs 256-bit+ arbitrary precision integer from int, string, or BigInt. |
big_float / bigfloat | big_float(val, [prec]) | BIGFLOAT | Constructs arbitrary precision floating-point number with custom bit precision. |
12. Linear Algebra & Geometry
| Builtin | Exact Signature | Return | Description & Behavior |
|---|---|---|---|
vec / vector | vec(elements | ...nums) | VECTOR | Constructs mathematical vector with .dot(), .cross(), .magnitude(). |
matrix | matrix(2d_arr | r, c, [fill]) | MATRIX | Constructs numerical matrix with .mul(), .det(), .inv(), .transpose(). |
13. Mathematical & Transcendental Functions
| Builtin | Exact Signature | Return | Description & Behavior |
|---|---|---|---|
pi | pi() | FLOAT | Returns mathematical constant PI (3.141592653589793). |
e | e() | FLOAT | Returns Euler's number (2.718281828459045). |
sin / cos / tan | sin(x) / cos(x) / tan(x) | FLOAT | Trigonometric functions (argument in radians). |
asin / acos / atan | asin(x) / acos(x) / atan(x) | FLOAT | Inverse trigonometric functions. |
atan2 | atan2(y, x) | FLOAT | Four-quadrant inverse tangent of y and x. |
sinh / cosh / tanh | sinh(x) / cosh(x) / tanh(x) | FLOAT | Hyperbolic sine, cosine, and tangent. |
sqrt / cbrt | sqrt(x) / cbrt(x) | FLOAT | Square root (guards against x < 0) and cube root. |
hypot | hypot(a, b) | FLOAT | Euclidean hypotenuse without intermediate overflow: sqrt(a^2 + b^2). |
log / log10 / log2 | log(x) / log10(x) / log2(x) | FLOAT | Natural, base-10, and base-2 logarithms (guards against x <= 0). |
exp / pow | exp(x) / pow(b, exp) | FLOAT | Exponential e^x and power function base^exp. |
abs | abs(x) | NUMBER | Absolute value of Integer, Float, BigInt, or BigFloat. |
floor / ceil / round | floor(x) / ceil(x) / round(x) | INTEGER | Floating-point rounding to integer. |
trunc | trunc(x) | INTEGER | Truncates decimal portion, returning integer value. |
deg_to_rad / rad_to_deg | deg_to_rad(d) / rad_to_deg(r) | FLOAT | Converts between degrees and radians. |
pow_mod | pow_mod(b, exp, mod) | INTEGER | BIGINT | Fast modular exponentiation (b^exp % mod) for cryptographic and scientific sizes. |
min / max | min(...nums) / max(...nums) | NUMBER | Finds minimum or maximum number among arguments or array elements. |
14. Statistical Calculations
| Builtin | Exact Signature | Return | Description & Behavior |
|---|---|---|---|
sum | sum(array | ...nums) | NUMBER | Calculates arithmetic sum of numbers. |
mean / math_mean | mean(array | ...nums) | FLOAT | Calculates arithmetic mean. Returns null if empty. |
median | median(array | ...nums) | FLOAT | Calculates median value of sample numbers. |
mode | mode(array | ...nums) | NUMBER | Calculates most frequently occurring value in samples. |
variance | variance(array | ...nums) | FLOAT | Computes population variance: Σ(x - μ)^2 / N. |
std_dev | std_dev(array | ...nums) | FLOAT | Computes standard deviation: sqrt(variance). |
15. Formats & Serialization (JSON, CSV, Base64)
| Builtin | Exact Signature | Return | Description & Behavior |
|---|---|---|---|
json_parse | json_parse(json_str) | ANY | Parses JSON text into native BramandScript hash or array. |
json_stringify | json_stringify(obj, [indent]) | STRING | Serializes BramandScript objects into JSON with optional indentation. |
csv_parse | csv_parse(csv_str, [delim]) | ARRAY | Parses CSV formatted string into 2D array of string cells. |
csv_stringify | csv_stringify(2d_arr, [delim]) | STRING | Serializes 2D array into CSV string with escaping. |
base64_encode / base64_decode | base64_encode(s) / base64_decode(s) | STRING | Standard RFC 4648 Base64 encoding and decoding. |
base64_url_encode / base64_url_decode | base64_url_encode(s) / ... | STRING | URL-safe Base64 encoding without padding characters. |
16. Cryptography & CSPRNG
| Builtin | Exact Signature | Return | Description & Behavior |
|---|---|---|---|
sha256 / crypto_sha256 | sha256(data) | STRING | Computes SHA-256 cryptographic digest as hexadecimal string. |
sha512 | sha512(data) | STRING | Computes SHA-512 cryptographic digest as hexadecimal string. |
md5 | md5(data) | STRING | Computes MD5 hash digest as hexadecimal string. |
hmac_sha256 / crypto_hmac | hmac_sha256(key, msg) | STRING | Computes HMAC-SHA256 authentication code as hexadecimal string. |
random_bytes | random_bytes([count]) | STRING | Generates CSPRNG cryptographically secure random bytes (hex-encoded). |
random_int | random_int([min], max) | INTEGER | Generates uniform CSPRNG random integer in range [min, max]. |
uuid | uuid() | STRING | Generates an RFC 4122 Version 4 random UUID string. |
17. Sockets, HTTP & WebSockets
| Builtin | Exact Signature | Return | Description & Behavior |
|---|---|---|---|
tcp_listen | tcp_listen(addr) | TcpServer | Binds TCP listener on address (e.g. ":9000"). Provides .accept(). |
tcp_connect | tcp_connect(addr, [timeout]) | TcpConn | Connects to TCP server with timeout; provides .read(), .write(). |
udp_listen | udp_listen(addr) | UdpSocket | Binds UDP packet socket listener. |
udp_connect | udp_connect(addr) | UdpSocket | Connects UDP socket to remote address. |
http_get | http_get(url, [headers]) | HASH | Executes HTTP GET request; returns { status, status_code, body, headers, json }. |
http_post | http_post(url, body, [hdrs]) | HASH | Executes HTTP POST request with JSON or string payload. |
http_put | http_put(url, body, [hdrs]) | HASH | Executes HTTP PUT request. |
http_delete | http_delete(url, [headers]) | HASH | Executes HTTP DELETE request. |
http_request | http_request(opts_hash) | HASH | Unified client API accepting method, url, body, headers, and timeout. |
http_server | http_server() | HttpServer | Instantiates 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_connect | ws_connect(url) | WsConn | Connects to RFC 6455 WebSocket (ws:// or wss:// with strict TLS). |
ws_server | ws_server(addr, [path]) | WsServer | Binds WebSocket server listener with .accept(). |
18. AI Integration & Vector Similarity Search
| Builtin | Exact Signature | Return | Description & Behavior |
|---|---|---|---|
ai_prompt | ai_prompt(model, prompt, [opts]) | STRING | Queries LLM endpoint (OpenAI / Ollama / Gemini API compatible). |
ai_stream | ai_stream(opts, callback) | NULL | Streams SSE response tokens in real-time, invoking callback per chunk. |
ai_structured | ai_structured(opts, schema) | HASH | Enforces JSON schema validation on LLM output and returns native Hash. |
cosine_similarity | cosine_similarity(v1, v2) | FLOAT | Computes cosine similarity between two numeric vectors in range [-1.0, 1.0]. |
cosine_distance | cosine_distance(v1, v2) | FLOAT | Computes cosine distance: 1.0 - cosine_similarity. |
euclidean_distance | euclidean_distance(v1, v2) | FLOAT | Computes geometric Euclidean distance between two vectors. |
manhattan_distance | manhattan_distance(v1, v2) | FLOAT | Computes L1 Manhattan distance between two vectors. |
vector_search | vector_search(query, cands, [k]) | ARRAY | K-nearest-neighbor search ranking candidate embeddings by vector similarity. |
19. Test Runner, Benchmarking & Diagnostics
| Builtin | Exact Signature | Return | Description & Behavior |
|---|---|---|---|
assert | assert(cond, [msg]) | NULL | Asserts condition is truthy; raises fatal AssertionError if falsy. |
assert_true | assert_true(cond, [msg]) | BOOLEAN | Asserts condition evaluates to truthy; raises AssertionError if falsy. |
assert_false | assert_false(cond, [msg]) | BOOLEAN | Asserts condition evaluates to falsy (false, null, 0, 0.0, "", or empty bytes()); raises AssertionError if truthy. |
assert_eq | assert_eq(actual, expected, [msg]) | NULL | Asserts deep structural equality with cyclic structure protection and formatted diff. |
assert_ne | assert_ne(actual, expected, [msg]) | NULL | Asserts that two values are not structurally equal. |
panic | panic([msg]) | NULL | Halts VM execution immediately with an explicit fatal panic. |
throw | throw(value) | NULL | Raises a catchable runtime exception with an arbitrary payload value (can also be invoked via statement syntax: throw expr;). |
test | test(name, fn) | BOOLEAN | Executes isolated test block, measuring duration and catching assertion failures. |
describe | describe(suite_name, fn) | NULL | Groups related tests under a common suite heading with duration aggregation. |
benchmark | benchmark(name, fn, [iters]) | HASH | Runs warmup and iterations loop; returns {"name", "iterations", "total_ms", "ops_per_sec"}. |
20. Compression & Archiving Engine (std/compress)
| Builtin | Exact Signature | Return | Description & Behavior |
|---|---|---|---|
gzip_compress | gzip_compress(data) | BYTES | Compresses bytes or string using pure Go standard library gzip. |
gzip_decompress | gzip_decompress(data) | BYTES | Decompresses gzip archive bytes back to raw byte stream. |
zlib_compress | zlib_compress(data) | BYTES | Deflates byte payload with RFC 1950 zlib compression. |
zlib_decompress | zlib_decompress(data) | BYTES | Inflates zlib compressed byte payload back to original contents. |
tar_pack | tar_pack(files_hash_or_array) | BYTES | Packages multi-file directory hierarchy into standard POSIX tar archive. |
tar_unpack | tar_unpack(tar_bytes) | HASH | Extracts tar archive into file name to byte payload map. |
21. Binary Serialization & Struct Packing (std/binary/pack)
| Builtin | Exact Signature | Return | Description & Behavior |
|---|---|---|---|
struct_pack | struct_pack(fmt, values) | BYTES | Python-style binary struct packing (>I, <h, f, d, b, B, s, etc.). |
struct_unpack | struct_unpack(fmt, data) | ARRAY | Unpacks binary byte sequence according to format specifier. |
struct_calcsize | struct_calcsize(fmt) | INT | Calculates byte length required for specified format string. |
msgpack_encode | msgpack_encode(val) | BYTES | High-speed binary MessagePack encoding for primitives, arrays, and hashes. |
msgpack_decode | msgpack_decode(bytes) | OBJECT | Decodes MessagePack binary data back into native BramandScript objects. |
22. Modern Cryptography Suite (std/crypto/advanced)
| Builtin | Exact Signature | Return | Description & Behavior |
|---|---|---|---|
aes_gcm_encrypt | aes_gcm_encrypt(key, pt, [nonce], [aad]) | HASH | AES-256-GCM authenticated symmetric encryption with 128-bit integrity tag. |
aes_gcm_decrypt | aes_gcm_decrypt(key, ct, [nonce], [aad]) | BYTES | Decrypts and verifies authenticated AES-256-GCM ciphertext payload. |
ed25519_keypair | ed25519_keypair() | HASH | Generates cryptographically secure Ed25519 public/private keypair. |
ed25519_sign | ed25519_sign(priv_key, message) | BYTES | Generates 64-byte Ed25519 digital signature over message. |
ed25519_verify | ed25519_verify(pub_key, msg, sig) | BOOL | Verifies Ed25519 signature validity against public key. |
jwt_sign | jwt_sign(payload, secret, [alg]) | STRING | Generates signed JSON Web Token (HS256 HMAC or EdDSA Ed25519). |
jwt_verify | jwt_verify(token, secret, [alg]) | HASH | Validates 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 Builtin | Exact Signature | Return | Description & Behavior |
|---|---|---|---|
__iter_len | __iter_len(collection) | INTEGER | Returns the exact element count or key length for iteration loop boundaries. |
__iter_key | __iter_key(collection, index) | ANY | Returns the current iteration key (string key for hashes, integer index for arrays/strings/bytes). |
__iter_val | __iter_val(collection, index) | ANY | Retrieves the collection value element at the current iteration position. |
__iter_item | __iter_item(collection, index) | ARRAY | Yields 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 / Method | Exact Signature | Return | Description & Behavior |
|---|---|---|---|
stream | stream(source) | HASH | Creates reactive stream from array, channel, or custom generator function. |
stream.map | s.map(fn) | HASH | Transforms emitted items using mapping function. |
stream.filter | s.filter(pred) | HASH | Filters stream items according to predicate truthiness. |
stream.window | s.window(size) | HASH | Batches incoming events into chunks of fixed size. |
stream.debounce | s.debounce(ms) | HASH | Suppresses rapid successive items until quiet period elapses. |
stream.throttle | s.throttle(ms) | HASH | Limits emission frequency, enforcing minimum millisecond gap. |
stream.zip | s1.zip(s2) | HASH | Combines two streams pairwise into 2-element arrays. |
stream.concat | s1.concat(s2) | HASH | Sequentially emits all items of first stream then second stream. |
stream.switch_map | s.switch_map(fn) | HASH | Projects each item to an inner stream, canceling prior active inner stream. |
stream.collect | s.collect() | ARRAY | Collects 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 Function | Exact Signature | Return | Description & Behavior |
|---|---|---|---|
sql_query / sql.query | sql.query(sql_str, tables) | ARRAY | Executes SELECT with WHERE, JOIN (INNER, LEFT), GROUP BY, HAVING, ORDER BY, and LIMIT over dataset tables. |
sql.parse | sql.parse(sql_str) | HASH | Parses ANSI SQL string into structured AST node. |
sql.plan | sql.plan(ast) | HASH | Generates optimized query execution plan. |
sql.database | sql.database(tables) | HASH | Creates 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 Primitive | Exact Signature | Return | Description & Behavior |
|---|---|---|---|
cosine_similarity | cosine_similarity(v1, v2) | FLOAT | Computes normalized cosine similarity [-1.0, 1.0]. |
cosine_distance | cosine_distance(v1, v2) | FLOAT | Computes cosine distance (1.0 - cosine_similarity). |
euclidean_distance | euclidean_distance(v1, v2) | FLOAT | Computes straight-line L2 geometric distance. |
manhattan_distance | manhattan_distance(v1, v2) | FLOAT | Computes L1 grid taxicab distance. |
dot_product | dot_product(v1, v2) | FLOAT | Computes algebraic dot product of two vectors. |
vector_normalize | vector_normalize(v) | ARRAY | Computes unit vector with L2 norm equal to 1.0. |
ai.new_index | ai.new_index(metric) | HASH | Creates K-Nearest Neighbors spatial index with .add(), .search(), .save(), and .load(). |
ai.chunk_text | ai.chunk_text(text, opts) | ARRAY | Semantic sliding window text chunker with configurable chunk size and overlap. |
ai.build_rag_context | ai.build_rag_context(query, idx, k) | STRING | Retrieves top-k hits and formats into clean RAG LLM prompt context block. |