Standard Library Reference
Module Overview
| Module | Description | Source |
|---|---|---|
std.io | Print, read, file I/O | lib/std/io.br |
std.fs | File system paths, directory listing | lib/std/fs.br |
std.net | TCP, UDP, HTTP networking | lib/std/net.br |
std.tcp | Low-level TCP operations | lib/std/tcp.bd |
std.udp | Low-level UDP operations | lib/std/udp.bd |
std.http | HTTP client requests | lib/std/http.bd |
std.tls | TLS/SSL connections | lib/std/tls.bd |
std.websocket | WebSocket client/server | lib/std/websocket.bd |
std.dns | DNS resolution | lib/std/dns.bd |
std.smtp | Email sending via SMTP | lib/std/smtp.bd |
std.json | JSON parse/stringify (C) | lib/std/json.c |
std.yaml | YAML parser | lib/std/yaml.bd |
std.xml | XML parser | lib/std/xml.bd |
std.toml | TOML parser | lib/std/toml.bd |
std.csv | CSV parser | lib/std/csv.bd |
std.protobuf | Protocol Buffers decode | lib/std/protobuf.bd |
std.sqlite | SQLite database bridge | lib/std/sqlite.bd |
std.postgres | PostgreSQL database bridge | lib/std/postgres.bd |
std.mysql | MySQL database bridge | lib/std/mysql.bd |
std.mongodb | MongoDB database bridge | lib/std/mongodb.bd |
std.redis | Redis cache bridge | lib/std/redis.bd |
std.crypto | SHA256, AES-GCM encryption | lib/std/crypto.br |
std.hash | Hashing utilities | lib/std/hash.bd |
std.rsa | RSA encryption | lib/std/rsa.bd |
std.aes | AES encryption | lib/std/aes.bd |
std.zlib | Zlib compression | lib/std/zlib.bd |
std.zip | ZIP archive creation | lib/std/zip.bd |
std.gzip | Gzip compression | lib/std/gzip.bd |
std.lz4 | LZ4 compression | lib/std/lz4.bd |
std.tar | TAR archive creation | lib/std/tar.bd |
std.thread | Spawn, yield, Channel | lib/std/thread.br |
std.time | Now, sleep, format (C) | lib/std/time.c |
std.os | Environment variables | lib/std/os.bd |
std.process | Process spawning | lib/std/process.bd |
std.signal | Signal handling | lib/std/signal.bd |
std.regex | Regex match, replace, split (C) | lib/std/regex.c |
std.collections | List, Map, Set, LinkedList ops | lib/std/collections.c |
std.math | Sqrt, pow, trig, log, bitwise (C) | lib/std/math.c |
std.blas | Tensor matmul, SIMD, fused ops (C) | lib/std/blas.c |
std.test | Assertions, test runner | lib/std/test.bd |
std.mock | Test mocking utilities | lib/std/mock.bd |
std.compiler | Runtime compile/eval (C) | lib/std/compiler.c |
std.random | Random number generation | lib/std/random.bd |
std.stats | Statistical functions | lib/std/stats.bd |
std.linalg | Linear algebra operations | lib/std/linalg.bd |
std.matrix | Matrix creation and ops | lib/std/matrix.bd |
std.fft | FFT transform | lib/std/fft.bd |
std.image | Image loading/manipulation | lib/std/image.bd |
std.audio | Audio processing | lib/std/audio.bd |
std.color | Color space conversion | lib/std/color.bd |
std.mmap | Memory-mapped files | lib/std/mmap.bd |
std.dts | Distinction Tree Storage AI | lib/std/dts.bd |
std.diameter_patterns | Dialectical reasoning patterns | lib/std/diameter_patterns.bd |
std.benchmark | Benchmarking utilities | lib/std/benchmark.bd |
std.io — Input / Output
Printing, reading, and file operations. Implemented as native functions in the runtime.
import std.io
fn main() {
io.println("Hello, World!")
let name = io.readln()
io.print("You entered: ")
io.print(name)
let f = io.open("data.txt")
let content = f.read()
io.println(content)
f.close()
}| Function | Signature | Description |
|---|---|---|
io.print | (s: string) -> void | Print string to stdout |
io.println | (s: string) -> void | Print string with newline |
io.readln | () -> string | Read a line from stdin |
io.File.open | (path: string) -> File | Open a file |
file.read | () -> string | Read file contents |
file.write | (data: string) -> void | Write to file |
file.close | () -> void | Close file descriptor |
std.fs — File System
Path abstraction, directory listing, and metadata queries. Wraps POSIX opendir/readdir/closedir via FFI.
import std.fs
fn main() {
let p = fs.Path.new("/home/user/docs")
if p.exists() {
let files = fs.read_dir(p)
for f in files {
io.println(f)
}
}
let meta = fs.metadata(p)
}| Function | Description |
|---|---|
fs.Path.new(s) | Create a Path from string |
fs.Path.exists(self) | Check if path exists |
fs.read_dir(path) | List directory entries |
fs.metadata(path) | Get file metadata |
extern opendir | FFI: open directory handle |
extern readdir | FFI: read next entry |
extern closedir | FFI: close directory handle |
std.net — Networking
TCP streams, UDP sockets, TCP listeners, and an HTTP client. Implemented with raw C socket FFI.
import std.net
fn http_example() {
let client = net.HttpClient.new()
let resp = client.get("http://example.com/data")
io.println(resp)
}
fn tcp_echo() {
let stream = net.TcpStream.connect("127.0.0.1", 8080)
stream.write("Hello server")
let reply = stream.read(1024)
stream.close()
}
fn udp_send() {
let sock = net.UdpSocket.bind("0.0.0.0", 0)
sock.send_to("ping", "192.168.1.1", 9000)
sock.close()
}| Type | Methods |
|---|---|
TcpStream | connect(host, port), read(size), write(data), close() |
TcpListener | bind(host, port), accept(), close() |
UdpSocket | bind(host, port), send_to(data, host, port), close() |
HttpClient | new(), get(url) |
std.json — JSON Parsing
Written in C. Parses JSON strings into native Braid maps, lists, strings, numbers, booleans, and nil.
import std.json
fn main() {
let data = json.parse('{"name": "Braid", "version": 1}')
io.println(data["name"]) # "Braid"
io.print_int(data["version"]) # 1
let arr = json.parse('[1, 2, 3]')
let output = json.stringify(data)
io.println(output)
}std.crypto — Cryptography
SHA-256 hashing and AES-256 GCM encryption. Backed by C native implementations.
import std.crypto
fn main() {
let hash = crypto.sha256("hello")
io.println(hash)
let key = "0123456789abcdef"
let iv = "0123456789ab"
let encrypted = crypto.aes_gcm_encrypt(key, iv, "secret data")
io.println(encrypted)
}std.thread — Concurrency
Lightweight thread spawning, cooperative yielding, and channel-based message passing.
import std.thread
fn worker() {
io.println("Worker running")
}
fn main() {
let t = thread.spawn(worker)
thread.yield()
let ch = thread.Channel.new(10)
ch.send(42)
let val = ch.recv()
}| Function / Method | Description |
|---|---|
thread.spawn(f) | Spawn a new thread running function f |
thread.yield() | Cooperatively yield the current thread |
Channel.new(capacity) | Create a channel with buffer |
channel.send(val) | Send value into the channel |
channel.recv() | Receive value from the channel |
std.regex — Regular Expressions
POSIX regex matching exposed as a native C module.
import std.regex
fn main() {
let ok = regex.match("[0-9]+", "abc123")
io.println(ok) # true
}std.time — Time & OS
Unix timestamp, monotonic clock, sleep, and strftime formatting.
import std.time
fn main() {
let ts = time.now()
io.print_int(ts)
time.sleep(1000) # 1 second
let ms = time.clock()
let formatted = time.format(ts, "%Y-%m-%d")
io.println(formatted)
}| Function | Description |
|---|---|
time.now() | Current Unix timestamp (seconds) |
time.clock() | Monotonic clock in milliseconds |
time.sleep(ms) | Sleep for N milliseconds |
time.format(ts, fmt) | Format timestamp by strftime pattern |
std.collections — Data Structures
Native C implementations of hash maps, linked lists, and array lists.
import std.collections
fn main() {
let map = collections.hm_new()
collections.hm_set(map, "key1", 100)
let v = collections.hm_get(map, "key1")
let keys = collections.hm_keys(map)
let list = collections.ll_new()
collections.ll_push(list, "a")
collections.ll_push(list, "b")
let arr = [1, 2, 3]
collections.list_push(arr, 4)
let x = collections.list_pop(arr)
collections.list_size(arr)
}std.math — Mathematics
Trigonometric, logarithmic, power, rounding, bitwise, and type reflection functions.
import std.math
fn main() {
let x = math.sqrt(144.0)
let y = math.pow(2.0, 10.0)
let s = math.sin(3.14159)
let r = math.random()
let t = math.typeof(x)
let c = math.chr(65) # "A"
let n = math.ord("A") # 65
let b = math.bitwise_and(12, 7)
}Constants: math.PI, math.E. Bitwise: bitwise_and, bitwise_or, bitwise_xor, bitwise_not, shift_left, shift_right.
std.blas — BLAS / Tensor Operations
SIMD-accelerated tensor math with fused operations. Requires the tensor runtime.
import std.blas
fn main() {
let a = tensor_create([2, 3], ...)
let b = tensor_create([3, 2], ...)
let c = blas.matmul(a, b)
let d = blas.simd_tanh(c)
let e = blas.fused_matmul_relu(a, b)
let f = blas.fused_softmax(d, 1)
}| Function | Description |
|---|---|
blas.matmul(a, b) | Matrix multiply (auto-dispatch) |
blas.simd_exp | Element-wise exponential |
blas.simd_tanh | Element-wise tanh |
blas.simd_sigmoid | Element-wise sigmoid |
blas.fused_matmul_relu | Matmul + ReLU in one pass |
blas.fused_softmax | Softmax along axis |
blas.fused_matmul_add | Matmul + residual add |
std.compiler — Runtime Compilation
Compile and execute Braid source code at runtime. Uses the full lexer, parser, and bytecode generator.
import std.compiler
fn main() {
let code = "fn add(a, b) { return a + b }"
let result = compiler.eval(code + " add(3, 4)")
io.print_int(result) # 7
}Data Formats
Braid provides parsers for YAML, XML, TOML, CSV, and Protocol Buffers. Each is declared in .bd with native or Braid-based implementations.
import std.yaml
import std.xml
import std.toml
import std.csv
fn main() {
let y = yaml.parse("key: value")
let x = xml.parse("<root><item/></root>")
let t = toml.parse("[section]\nkey = "value"")
let c = csv.parse("a,b,c\n1,2,3")
}Databases
SQLite, PostgreSQL, MySQL, MongoDB, and Redis bridges are declared in .bd files, connecting to native C driver implementations.
import std.sqlite
import std.postgres
import std.mongodb
import std.redis
fn main() {
let db = sqlite.open("app.db")
postgres.connect("host=localhost dbname=test")
mongodb.connect("mongodb://localhost:27017")
redis.connect("127.0.0.1:6379")
}Compression & Archives
Zlib, Gzip, LZ4 compression and ZIP, TAR archive creation.
import std.zlib
import std.gzip
import std.zip
import std.tar
fn main() {
let compressed = zlib.compress("data")
let extracted = zlib.decompress(compressed)
zip.create("out.zip", ["file1.txt", "file2.txt"])
tar.create("out.tar", ["dir/"])
}Testing & Mocking
import std.test
import std.mock
fn test_addition() {
test.assert(1 + 1 == 2)
test.assert_eq(2 + 2, 4)
}
fn test_with_mock() {
let m = mock.create()
mock.expect(m, "compute", 42)
let result = call_with_mock(m)
test.assert(result == 42)
mock.verify(m)
}OS / Process / Signal
import std.os
import std.process
import std.signal
fn main() {
let path = os.env("PATH")
let pid = process.spawn(["ls", "-la"])
signal.handle(signal.SIGINT, fn() {
io.println("Interrupted")
})
}Source code for all modules is located under braid-lang/lib/std/ with .br/.bd declarations and .c native implementations.