BRAIDGROUP
RESEARCH & DEV
69. Library Docs

Standard Library Reference

Module Overview

ModuleDescriptionSource
std.ioPrint, read, file I/Olib/std/io.br
std.fsFile system paths, directory listinglib/std/fs.br
std.netTCP, UDP, HTTP networkinglib/std/net.br
std.tcpLow-level TCP operationslib/std/tcp.bd
std.udpLow-level UDP operationslib/std/udp.bd
std.httpHTTP client requestslib/std/http.bd
std.tlsTLS/SSL connectionslib/std/tls.bd
std.websocketWebSocket client/serverlib/std/websocket.bd
std.dnsDNS resolutionlib/std/dns.bd
std.smtpEmail sending via SMTPlib/std/smtp.bd
std.jsonJSON parse/stringify (C)lib/std/json.c
std.yamlYAML parserlib/std/yaml.bd
std.xmlXML parserlib/std/xml.bd
std.tomlTOML parserlib/std/toml.bd
std.csvCSV parserlib/std/csv.bd
std.protobufProtocol Buffers decodelib/std/protobuf.bd
std.sqliteSQLite database bridgelib/std/sqlite.bd
std.postgresPostgreSQL database bridgelib/std/postgres.bd
std.mysqlMySQL database bridgelib/std/mysql.bd
std.mongodbMongoDB database bridgelib/std/mongodb.bd
std.redisRedis cache bridgelib/std/redis.bd
std.cryptoSHA256, AES-GCM encryptionlib/std/crypto.br
std.hashHashing utilitieslib/std/hash.bd
std.rsaRSA encryptionlib/std/rsa.bd
std.aesAES encryptionlib/std/aes.bd
std.zlibZlib compressionlib/std/zlib.bd
std.zipZIP archive creationlib/std/zip.bd
std.gzipGzip compressionlib/std/gzip.bd
std.lz4LZ4 compressionlib/std/lz4.bd
std.tarTAR archive creationlib/std/tar.bd
std.threadSpawn, yield, Channellib/std/thread.br
std.timeNow, sleep, format (C)lib/std/time.c
std.osEnvironment variableslib/std/os.bd
std.processProcess spawninglib/std/process.bd
std.signalSignal handlinglib/std/signal.bd
std.regexRegex match, replace, split (C)lib/std/regex.c
std.collectionsList, Map, Set, LinkedList opslib/std/collections.c
std.mathSqrt, pow, trig, log, bitwise (C)lib/std/math.c
std.blasTensor matmul, SIMD, fused ops (C)lib/std/blas.c
std.testAssertions, test runnerlib/std/test.bd
std.mockTest mocking utilitieslib/std/mock.bd
std.compilerRuntime compile/eval (C)lib/std/compiler.c
std.randomRandom number generationlib/std/random.bd
std.statsStatistical functionslib/std/stats.bd
std.linalgLinear algebra operationslib/std/linalg.bd
std.matrixMatrix creation and opslib/std/matrix.bd
std.fftFFT transformlib/std/fft.bd
std.imageImage loading/manipulationlib/std/image.bd
std.audioAudio processinglib/std/audio.bd
std.colorColor space conversionlib/std/color.bd
std.mmapMemory-mapped fileslib/std/mmap.bd
std.dtsDistinction Tree Storage AIlib/std/dts.bd
std.diameter_patternsDialectical reasoning patternslib/std/diameter_patterns.bd
std.benchmarkBenchmarking utilitieslib/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()
}
FunctionSignatureDescription
io.print(s: string) -> voidPrint string to stdout
io.println(s: string) -> voidPrint string with newline
io.readln() -> stringRead a line from stdin
io.File.open(path: string) -> FileOpen a file
file.read() -> stringRead file contents
file.write(data: string) -> voidWrite to file
file.close() -> voidClose 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)
}
FunctionDescription
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 opendirFFI: open directory handle
extern readdirFFI: read next entry
extern closedirFFI: 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()
}
TypeMethods
TcpStreamconnect(host, port), read(size), write(data), close()
TcpListenerbind(host, port), accept(), close()
UdpSocketbind(host, port), send_to(data, host, port), close()
HttpClientnew(), 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 / MethodDescription
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)
}
FunctionDescription
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)
}
FunctionDescription
blas.matmul(a, b)Matrix multiply (auto-dispatch)
blas.simd_expElement-wise exponential
blas.simd_tanhElement-wise tanh
blas.simd_sigmoidElement-wise sigmoid
blas.fused_matmul_reluMatmul + ReLU in one pass
blas.fused_softmaxSoftmax along axis
blas.fused_matmul_addMatmul + 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.