# Tangu Programming Language — Complete Documentation & Standard Library Reference (v0.32.0) > Canonical URL: https://tangu.dev/llms-full.txt > Index URL: https://tangu.dev/llms.txt > GitHub: https://github.com/tangu-dev ## Idiomatic Tangu & Agent Rules Always obey these core conventions when writing, refactoring, or reviewing Tangu (`.tan`, `.data.tan`, `#shtml`, `#css`, `#sql`) code: 1. **Stack annotations vertically above `(def ...)` or `(let ...)`**: - Always place `#pub`, `#inline`, `#test`, `#bench`, `#(Func ...)`, and `#(doc ...)` on separate lines preceding `(def ...)`—never inside the `def` form: ```tangu #pub #(Func [Int Int] Int) (def add (Func [a b] (+ a b))) ``` 2. **Function parameter forms (`Func`)**: - Zero parameters: `(Func () body)` (never `(Func [] body)`). - Single parameter: `(Func x body)` (never `(Func [x] body)` unless typed `#Int x` or destructured). - Multiple or typed parameters: `(Func [a b] body)` or `(Func [#Int a #Int b] body)`. 3. **Universal sequence vocabulary & zero prelude imports**: - Always use `count-of` (never `len` or `size`), `is-empty?` (never `(== (count-of x) 0)` or `(> (count-of x) 0)`), `contains?`, `first-of`, `last-of`, `nth-of`, `rest-of`, `slice`, `push`, `pop`, `put`, `put-all`, `remove`, `swap-remove`, `sort`, `sort<-`, `reverse`, `reverse<-`, `concat`, `concat<-`. - Never import prelude symbols (`say`, `echo`, `read`, `write`, `count-of`, `is-empty?`, `map`, `filter`, `trim`, `split`, `join`, `replace`, etc.). 4. **Equality & strict boolean conditions**: - Always use `==` and `!=` for equality checks (never `=`). - `if`, `unless`, `while`, and `cond` require a strict `Bool` (`true` or `false`). Use `is-some?`, `is-none?`, `is-error?`, or `is-empty?` explicitly. 5. **Mutability (`#var` vs `#mut`)**: - Use `(let #var x 0)` + `(<- x 1)` (or `(+<- x 1)`) to rebind a local variable. - Use `(let #mut arr [])` + `(push arr item)` to mutate a collection or struct field in place. 6. **Key-paths, map punning & spreading**: - Use `obj:field` for required field access and `obj?field` for nil-safe optional traversal. - Use `{_ host _ port}` for map punning (`{:host host :port port}`) and `{...base :extra 1}` for map spreading. 7. **Error handling (`try`, `ok-or`, `some-or`)**: - `(try expr (else fallback-return))` unwraps `Some` or strictly early-returns from the enclosing function on both `Error` and `()` (`None`). - `(ok-or cand1 ... default)` provides a local fallback for both `Error` and `()` without returning from the function. - `(some-or cand1 ... default)` provides a local fallback for `()` (`None`) only. 8. **Structs, traits & `derive`**: - Define structs with `(def User (Struct #Int id #String #{:format :email} email (#String status "active")))`. - Prefer `(derive User Eq Hash Ord Clone To-String Default To-JSON From-JSON)` over manual trait implementations. 9. **Directory-as-module & sorted `use` imports**: - Every directory of `.tan` files is a module; never import `.tan` filenames directly. - Group and sort `(use ...)` statements alphabetically by module path: `@standard` (`/fs`, `/string`) first, then `@scope/pkg`, then relative (`./`, `../`). 10. **Database consistency (`/postgres/client`)**: - Use `query-strong` or `query-one-strong` for `INSERT/UPDATE/DELETE ... RETURNING` and read-after-write queries so they execute on the primary writer rather than a read replica. - Always pass user inputs as `$1, $2` positional parameters to `#sql "..."`—never interpolate variables into SQL strings with `${...}`. --- # Overview ## Why Tangu? Tangu is a high-performance, general-purpose language designed around a single core principle: **code, configuration, markup, stylesheets, and database queries should share one homoiconic s-expression representation**. - **Homoiconic & agent-native**: Every Tangu program, `.data.tan` manifest, `#shtml` UI tree, and `#css` rule sheet is an s-expression AST with zero syntactic ambiguity, making refactoring, macro expansion, formatting, and AI-assisted code generation deterministic. - **Expressive static & dynamic ergonomics**: Combine lightweight gradual type annotations (`#Int`, `#(Array String)`), rich compile-time linting, and structural pattern matching (`when`) with REPL-driven productivity. - **Batteries-included standard library**: Over 70 built-in `@standard` modules covering HTTP servers, full-stack `/web/app` routing, PostgreSQL & SQLite connection pools, ICU4X internationalization (`/i18n`), SIMD vectors (`/simd`), cryptography (`/crypto`, `/jwt`), and image codecs (`/image/*`). ## A language for humans and machines ### Application code (`.tan`) ```tangu #pub (def User (Struct #String #{:min-len 2 :max-len 50} name #(Array String) roles )) (derive User Eq Clone To-JSON From-JSON) #pub #(Func User String) (def describe-user (Func user (let badge (if (contains? user:roles "admin") "Admin" (else "Member"))) "${user:name} (${badge}): ${(join user:roles ", ")}" )) ``` ### Structured data & manifests (`.data.tan`) Configuration files, package manifests (`manifest.data.tan`), and route metadata use pure Tangu data literals without boilerplate punctuation: ```tangu { :name "tangu-site" :version "0.32.0" :server { :host "127.0.0.1" :port 8005 } :targets [:native :jit :js :rust] } ``` ### Composable UI & stylesheets (`#shtml`, `#css`, `#sql`) Reader tags specialize s-expressions for HTML components, scoped CSS rules, and parameterized SQL queries: ```tangu #pub (def (Func [label tone] #shtml [:span.inline-flex.items-center.px-3.py-1.corner-full {:class tone} label ] )) #pub (def card-styles #css [ [".status-card" { :background-color "var(--color-surface-container-low)" :border "1px solid var(--color-outline-variant)" :padding "24px" }] ]) ``` ## Multi-target execution engine Tangu decouples language semantics from the execution backend so you can iterate instantaneously in development and deploy native binaries or JavaScript bundles in production: | Mode | Command | Description | | :--- | :--- | :--- | | **Tree-walk & bytecode VM** | `tangu run main.tan` | Instantaneous startup with a compact 16-byte `Value` representation, flat `SymbolId` caches, and precise source-mapped stack traces. | | **Cranelift JIT** | `tangu run --jit main.tan` | In-memory native machine-code compilation via Cranelift from Tangu's Typed Intermediate Representation (TIR). | | **Native AOT binary** | `tangu compile --target native main.tan` | Ahead-of-time compilation into standalone native executables. | | **Rust & JavaScript transpilers** | `tangu compile --target rust\|js main.tan` | Lowers TIR into idiomatic Rust crates or ES modules with source maps. | ## Built-in developer toolchain The `tangu` CLI ships as a single self-contained binary with everything needed to build, test, document, and maintain projects: | Command | Purpose | | :--- | :--- | | `tangu run` (`r`) | Execute a `.tan` script or package `main.tan` entry point (`--jit`, `--opt none\|basic\|aggressive`). | | `tangu repl` | Interactive Read-Eval-Print Loop with history and tab completion. | | `tangu test` (`t`) | Discover and execute `#test` functions across `*.test.tan` files in parallel. | | `tangu check` (`c`) | Run fast static type checking and symbol resolution without executing code. | | `tangu lint` | Run static lint rules (`redundant-prelude-imports`, `unused-variables`, naming conventions, and auto-fixes). | | `tangu fmt` | Format `.tan`, `.data.tan`, `#shtml`, and `#css` files deterministically (`--check` in CI). | | `tangu doc` (`docs`) | Introspect documentation for any module (`tangu doc /fs`), symbol (`tangu doc count-of`), or search query (`tangu doc -s json`). | | `tangu bench` | Run `#bench` performance suites across optimization levels. | | `tangu doctor` & `upgrade` | Verify local environment setup and self-upgrade the toolchain from `tangu.dev`. | --- # Language tutorial (`https://tangu.dev/tutorial/`) Progressive step-by-step guide from installation and s-expressions to structs, traits, pattern matching, and modules. ## Installation & first steps ### Installing Tangu Install the `tangu` CLI, Language Server (`tangu-lsp`), formatter (`tangu-format`), and standard libraries with the official installer script: ```sh curl -fsSL https://tangu.dev/install.sh | sh ``` Verify your installation and inspect the active toolchain paths: ```sh tangu --version tangu doctor ``` ### Hello, Tangu Create `hello.tan` and run it with `tangu run hello.tan` (or `tangu r hello.tan`): ```tangu (let language "Tangu") (say "Hello from ${language}!") ``` - `say` prints values followed by a newline (`echo` prints without a trailing newline). - Strings support inline `${...}` interpolation for any expression implementing `To-String`. - Line comments start with `;` (or `;;` for module headers). ## Primitives, literals & sized integers Tangu provides rich literal syntax for numbers, exact decimals, strings, characters, booleans, and symbols: ```tangu (let count 42) ; Int (64-bit signed integer) (let hex-mask 0xff_00) ; Hexadecimal Int literal (0b... binary, 0o... octal) (let ratio 3.14159) ; Float (64-bit IEEE 754) (let price 19.99d) ; Dec (128-bit exact fixed-point decimal for finance) (let is-active true) ; Bool (true or false) (let letter (Char "A")) ; Char (Unicode scalar value) (let status :ready) ; Key-Symbol (self-evaluating interned keyword) (let empty ()) ; None / unit value ``` ### Explicit sized integers When interoperating with binary protocols, SIMD, or databases, use sized integer literal suffixes or explicit constructors: - **Signed**: `I8`, `I16`, `I32`, `I64` (`Int`), `I128`, `ISize` - **Unsigned**: `U8` (`Byte`), `U16`, `U32`, `U64`, `U128`, `USize` ```tangu (let port 8005u16) (let byte-val 255u8) (let idx 1000usize) (let offset (I32 -128)) ``` ## Bindings, scope & mutability ### `def` vs `let` - Use **`def`** for top-level and mutually recursive function, struct, or constant declarations (hoisted within their scope). - Use **`let`** for sequential local bindings inside functions and scripts. ```tangu ; Always stack annotations (#pub, #inline, #test) vertically above (def ...) #pub #inline (def square (Func x (* x x))) (let result (square 12)) ``` ### Rebindable variables (`#var`) vs interior mutation (`#mut`) Bindings are immutable by default. Tangu distinguishes between **rebinding a variable** (`#var`) and **mutating a collection in place** (`#mut`): ```tangu ; #var allows reassigning the variable binding with <- or +<- (let #var total 0) (<- total 10) (+<- total 5) ; total is now 15 ; #mut allows mutating the contents of a collection or struct (let #mut items [1 2 3]) (push items 4) ; items is now [1 2 3 4] ``` ## Collections, key-paths & negative indexing ### Arrays, lists, maps, sets & ranges ```tangu (let nums [10 20 30 40]) ; Array (contiguous growable vector) (let quoted '(a b c)) ; List (s-expression linked list) (let tags (Set ["web" "db"])) ; Set (unique hashed values) (let r 0..10) ; Half-open Range (0 through 9) (let evens 0..=10|2) ; Inclusive Range with step 2 (0, 2, 4, 6, 8, 10) ``` Maps (`{...}`) accept `:key` symbols or string keys without commas, and support `...` map spreading and `{_ var}` punning: ```tangu (let host "127.0.0.1") (let port 8005) (let base-config {_ host _ port}) ; Punned keys {:host host :port port} (let dev-config {...base-config :debug true}) ; Spread base-config and override/add keys ``` ### Universal sequence operations All sequence types (`Array`, `List`, `String`, `Set`, `Map`, `Range`, `Slab`) share a single vocabulary in the prelude: ```tangu (count-of nums) ; => 4 (is-empty? nums) ; => false (contains? nums 20) ; => true (first-of nums) ; => 10 (last-of nums) ; => 40 (nth-of nums 2) ; => 30 (nums -1) ; => 40 (negative index from the end) (slice nums 1 -1) ; => [20 30] (reverse nums) ; => [40 30 20 10] ``` ### Required (`:`) vs optional (`?`) key-path navigation Navigate nested maps and structs concisely using `:` for required fields and `?` for nil-safe optional traversal: ```tangu (let payload {:user {:profile {:handle "gmosx"}}}) (let handle payload:user:profile:handle) ; => "gmosx" (errors if missing) (let bio (some-or payload?user?profile?bio "No bio yet")) ``` ## Control flow & pattern matching ### Strict boolean conditions (`if`, `unless`, `cond`) Conditions in Tangu require a strict `Bool` (`true` or `false`)—never rely on truthy/falsy coercion: ```tangu ; Multi-statement if with explicit (else ...) (if (not (is-empty? items)) (say "Processing items") (first-of items) (else (say "Queue is empty") () )) ; Flat multi-branch cond with _ default arm (let label (cond (== status :ok) "Healthy" (== status :degraded) "Warning" _ "Offline" )) ``` ### Structural pattern matching (`when`) Use `when` to match literals, runtime types, array destructuring (`[head ...tail]`), map keys (`{:role r}`), and `Error` values: ```tangu (def handle-response (Func resp (when resp {:status 200 :body b} "OK: ${b}" {:status 404} "Not found" [first ...rest] "List starting with ${first} (${(count-of rest)} more)" {:variant v :message msg} "Failed (${v}): ${msg}" _ "Unhandled response" ) )) ``` ### Loops (`for`, `for->seq`, `while`) Use `for` for side effects and `for->seq` to build an `Array` comprehension (using `(continue)` to skip elements): ```tangu ; Iterate over values in a sequence (for [name ["alpha" "beta"]] (say name) ) ; Comprehension producing [4 16 36] (let even-squares (for->seq [n 1..=6] (if (!= (% n 2) 0) (continue) ) (* n n) )) ``` ## Functions, implicit closures & pipelines ### Function parameter forms (`Func`) `Func` uses three canonical parameter shapes: 1. **Zero parameters**: `(Func () body)` 2. **Single parameter**: `(Func x (* x 2))` 3. **Multiple or typed parameters**: `(Func [#Int a #Int b] (+ a b))` (with optional signature annotation `#(Func [Int Int] Int)` stacked above `def`) ```tangu ; Rest parameters (...rest) and map destructuring (def format-tag (Func [{name tone} ...children] "${name}:${tone} (${(count-of children)})" )) ``` ### Implicit closures (`%0`, `%1`) & pipelines (`|>`) For concise higher-order transforms, `%0` (or `%`), `%1`, `%2` create an implicit closure automatically, and `|>` threads a value through expression chains via `%0`: ```tangu (let doubled (map [1 2 3 4] (* %0 2))) ; => [2 4 6 8] (let big (filter doubled (> %0 4))) ; => [6 8] ; Pipeline threading (let summary (|> " hello tangu world " (trim %0) (split %0 " ") (count-of %0) )) ; => 3 ``` ## Structs, validation constraints & traits ### Defining structs & field constraints Define nominal product types with `Struct`, optional `#(Or T)` fields, default values, and declarative validation constraints (`#{...}`): ```tangu #pub (def Account (Struct #Int #{:min 1} id #String #{:format :email} email #String #{:min-len 2 :max-len 32} handle #(Or String) bio (#String status "active") )) ``` Validate dynamic maps before constructing a `Struct` using `/validation`: ```tangu (use {validate} /validation) (let raw {:id 1 :email "dev@tangu.dev" :handle "gmosx"}) (let checked (validate raw Account)) ``` ### Pure copy-update vs in-place mutation ```tangu (let acc (Account {:id 1 :email "dev@tangu.dev" :handle "gmosx"})) ; Pure copy-update (returns a new Account with updated :bio) (let updated (Account acc {:bio "Systems programmer"})) ; In-place mutation on a #mut binding (let #mut mutable-acc (clone acc)) (<- mutable-acc:bio "Updated in place") ``` ### Deriving standard traits (`derive`) Prefer `(derive ...)` over manual boilerplate for standard traits: ```tangu (def Point (Struct #Int x #Int y)) (derive Point Eq Hash Ord Clone To-String Default To-JSON From-JSON) ``` ### Custom traits & implementations (`Trait` & `impl`) ```tangu (def Renderable (Trait #(Func This String) (render (Func this)) )) (impl Renderable Point (let render (Func self "(${self:x}, ${self:y})")) ) ``` ## Error handling (`Error`, `try`, `ok-or`, `some-or`) Tangu represents recoverable failures as first-class `Error` values rather than unchecked exceptions: ```tangu #(Func String (Or Int Error)) (def parse-port (Func raw (let n (try (Int raw) (else (Error :invalid-port "Port must be an integer: ${raw}") ))) (if (or (< n 1) (> n 65_535)) (return (Error :out-of-range "Port ${n} is outside 1..65_535")) ) n )) ; Local fallback for Error values with ok-or (let port (ok-or (parse-port "8005") 8000)) ; Local fallback for None () values with some-or (let host (some-or config?host "127.0.0.1")) ``` ## Modules, testing & tooling ### Directory-as-module & `use` imports In Tangu, **a directory is a module**: all `.tan` files in a directory merge into a single module namespace. Export public symbols with `#pub` stacked above `(def ...)` or `(let ...)`: ```tangu ; Sort imports alphabetically by module path: (use /fs) (use {strip-prefix strip-suffix} /string) (use {} @acme/ui/components/cards) (use {helper} ./utils) ``` ### Writing `#test` suites (`*.test.tan`) Place tests in `*.test.tan` files alongside your code or under `tests/` and run `tangu test`: ```tangu #test (def point-equality-and-update-works (Func () (let p1 (Point 10 20)) (let p2 (Point p1 {:x 99})) (assert-eq! p1:x 10) (assert-eq! p2:x 99) (assert! (!= p1 p2)) )) ``` --- # Prelude & core built-ins (`https://tangu.dev/stdlib-prelude/`) Special forms, universal sequence accessors, core types, arithmetic/bitwise operators, and derivable traits. ## Special forms & declarations Core syntactic forms built into the Tangu compiler and evaluator. ### def `(def name value)` Declares a top-level or hoisted binding (function, struct, trait, or constant). Stack attributes like `#pub`, `#inline`, and `#test` on lines above `(def ...)`. ```tangu (def add (Func [a b] (+ a b))) ``` ### let `(let pattern value)` Binds a local immutable variable (or rebindable `#var` / mutable `#mut` binding) sequentially within the current lexical scope. Supports array `[a b]` and map `{:x}` destructuring. ```tangu (let [first ...rest] [10 20 30]) ``` ### Func `(Func params body...)` Constructs a first-class lexical closure. Parameter forms: `()` for zero args, `x` for single arg, or `[a b ...rest]` for multiple/typed/destructured args. ```tangu (let double (Func x (* x 2))) ``` ### Struct `(Struct #Type #{constraints}? field (#Type field default) ...)` Defines a nominal product type with typed fields, optional default values, and declarative validation constraints. ```tangu (def Point (Struct #Int x #Int y)) ``` ### Trait `(Trait #(Func [This ...] Ret) (method (Func [this ...])) ...)` Defines a polymorphic trait interface that can be implemented for structs or built-in types via `impl`. ```tangu (def Printable (Trait #(Func This String) (format (Func this)))) ``` ### impl `(impl Trait-Name Target-Type (let method (Func [self ...] ...)))` Implements a `Trait` for a target `Struct` or type. ```tangu (impl Printable Point (let format (Func self "${self:x},${self:y}"))) ``` ### derive `(derive Struct-Type Trait1 Trait2 ...)` Automatically synthesizes standard trait implementations (`Eq`, `Hash`, `Ord`, `Clone`, `To-String`, `Default`, `To-JSON`, `From-JSON`) for a `Struct`. ```tangu (derive Point Eq Hash Ord Clone To-String Default) ``` ### use `(use {sym1 sym2} /module/path)` Imports a module or selective symbol bindings from `@standard` (`/path`), a package (`@scope/pkg`), or a relative path (`./mod`). Supports `#lazy` deferred loading. ```tangu (use {join split} /string) ``` ### <- `(<- target new-value)` Reassigns a `#var` binding or updates a `#mut` struct field / collection element in place (`+<-` increments in place). ```tangu (let #var x 1) (<- x 2) ``` ### #lazy / #static `(let #lazy x expr), (let #static cache expr)` `#lazy` defers evaluation of a binding or `(use #lazy ...)` module until first access; `#static` evaluates a function-local binding once and caches it across calls. ```tangu (let #static lookup-table {:a 1 :b 2}) ``` ### %file / %dir / %module / %profile `%file, %dir, %module, %profile` Compile-time context intrinsics expanding to the current source file path (`%file`), parent directory (`%dir`), module path (`%module`), and active build profile (`%profile`). ```tangu (let config-path "${%dir}/config.data.tan") ``` ## Control flow & pattern matching Branching, structural pattern matching, iteration, and early-return error handling. ### if `(if cond then-body... (else else-body...))` Evaluates `cond` (which must be a strict `Bool`); runs `then-body` when `true` or the optional `(else ...)` block when `false`. ```tangu (if (> x 0) "positive" (else "non-positive")) ``` ### unless `(unless cond body...)` Executes `body` when `cond` evaluates to `false`. ```tangu (unless (is-empty? items) (process items)) ``` ### cond `(cond test1 expr1 test2 expr2 _ default-expr)` Multi-branch conditional evaluating flat `test expr` pairs in order; `_` provides the fallback arm. ```tangu (cond (== code 200) :ok (== code 404) :not-found _ :error) ``` ### when `(when target pattern1 expr1 ... _ default-expr)` Structural pattern matching over literals, runtime types (`Int`, `String`, `Error`), arrays (`[x ...xs]`), and maps (`{:status 200}`). ```tangu (when resp {:status 200 :body b} b Error "failed" _ "other") ``` ### for `(for [binding seq] body...)` Iterates over any sequence, range, map, or iterator for side effects. Supports `[item seq]` and `[[key val] map]`. ```tangu (for [x 0..5] (say x)) ``` ### for->seq `(for->seq [binding seq] body...)` List/Array comprehension collecting the result of each iteration into a new `Array`. Call `(continue)` to skip an element. ```tangu (for->seq [x [1 2 3]] (* x 10)) ; => [10 20 30] ``` ### while `(while cond body...)` Repeatedly evaluates `body` while `cond` remains `true`. Supports `(break)` and `(continue)`. ```tangu (while (< i 10) (+<- i 1)) ``` ### try `(try expr (else fallback-return-expr))` Unwraps a computation if it is `Some` (neither `()` nor `Error`); on `Error` or `()`, strictly early-returns the failure or the `(else ...)` value from the enclosing function. ```tangu (let data (try (decode raw-json))) ``` ### some-or `(some-or cand1 ... default-expr)` Short-circuiting local fallback for `()` (None): returns the first non-`()` candidate, or `default-expr` (passes `Error` values through unchanged). ```tangu (let port (some-or config?port 8005)) ``` ### ok-or `(ok-or cand1 ... fallback-expr)` Short-circuiting local fallback for both `Error` and `()` (None): returns the first valid candidate, or `fallback-expr` without early-returning from the function. ```tangu (let parsed (ok-or (Int input) 0)) ``` ### |> `(|> initial-value (step1 %0) (step2 %0 arg) ...)` Pipeline operator threading the result of each expression into `%0` (or `%`) of the next step. ```tangu (|> " hello " (trim %0) (to-upper-case %0)) ; => "HELLO" ``` ## Universal sequence & collection intrinsics Polymorphic functions available without imports across Array, List, String, Map, Set, Range, and Slab. ### count-of `(count-of coll) -> Int` Returns the number of elements in a collection, Unicode scalar values in a `String`, or delegates to the `Countable` trait. ```tangu (count-of [10 20 30]) ; => 3 ``` ### byte-count-of `(byte-count-of str-or-slab) -> Int` Returns the exact UTF-8 byte length of a `String` or byte length of a `Slab` in O(1) time. ```tangu (byte-count-of "café") ; => 5 ``` ### is-empty? `(is-empty? coll) -> Bool` Returns `true` if `coll` has zero elements (`count-of == 0`). ```tangu (is-empty? []) ; => true ``` ### contains? `(contains? coll item) -> Bool` Checks element membership in an `Array`/`List`/`Set`/`Range`, substring presence in a `String`, key presence in a `Map`, or invokes the `Contains` trait. ```tangu (contains? [1 2 3] 2) ; => true ``` ### contains-key? `(contains-key? map key) -> Bool` Returns `true` if `map` contains `key`. ```tangu (contains-key? {:a 1} :a) ; => true ``` ### first-of `(first-of seq) -> (Or Any None)` Returns the first element of `seq`, or `()` if empty. ```tangu (first-of [10 20 30]) ; => 10 ``` ### last-of `(last-of seq) -> (Or Any None)` Returns the last element of `seq`, or `()` if empty. ```tangu (last-of [10 20 30]) ; => 30 ``` ### nth-of `(nth-of seq index) -> (Or Any None)` Returns the element at zero-based `index` (supporting negative indices from the end). ```tangu (nth-of [10 20 30] 1) ; => 20 ``` ### rest-of `(rest-of seq) -> Array` Returns a slice containing all elements after the first. ```tangu (rest-of [1 2 3]) ; => [2 3] ``` ### slice `(slice seq start end?) -> Seq` Extracts a sub-slice from `start` up to `end` (supporting negative offsets like `-1`). ```tangu (slice [10 20 30 40] 1 -1) ; => [20 30] ``` ### byte-slice `(byte-slice str-or-slab start end) -> String | Slab` Extracts a zero-copy or O(k) byte range `[start..end)` from a `String` or `Slab`. ```tangu (byte-slice "hello world" 0 5) ; => "hello" ``` ### reverse `(reverse seq) -> Seq` Returns a new `Array`, `List`, or `String` with elements in reverse order. ```tangu (reverse [1 2 3]) ; => [3 2 1] ``` ### concat `(concat seq1 seq2 ...) -> Seq` Concatenates multiple arrays, lists, or strings into a single sequence. ```tangu (concat [1 2] [3 4]) ; => [1 2 3 4] ``` ### push `(push #mut array item...) -> Array` Appends one or more elements to the end of a mutable `Array`. ```tangu (let #mut a [1]) (push a 2 3) ``` ### pop `(pop #mut array) -> (Or Any None)` Removes and returns the last element of a mutable `Array`. ```tangu (pop a) ``` ### put `(put #mut coll key-or-item value?) -> Coll` Inserts or updates a key-value pair in a mutable `Map`, or inserts an element into a `Set`. ```tangu (put m :status :ready) ``` ### put-all / put-many `(put-all #mut coll source-coll), (put-many #mut map [k1 v1] [k2 v2] ...)` Merges all entries from `source-coll` (`put-all`) or multiple `[key value]` pairs (`put-many`) into a mutable `Map` or `Set`. ```tangu (put-all m {:host "127.0.0.1" :port 8005}) ``` ### remove / swap-remove `(remove #mut coll key-or-index) -> Any, (swap-remove #mut array index) -> Any` `remove` deletes and returns an entry by key (`Map`/`Set`) or index (`Array`); `swap-remove` removes an `Array` element in O(1) time by swapping it with the last element. ```tangu (remove m :status) ``` ### keys-of `(keys-of map) -> Array` Returns an `Array` of all keys in `map`. ```tangu (keys-of {:a 1 :b 2}) ``` ### values-of `(values-of map) -> Array` Returns an `Array` of all values in `map`. ```tangu (values-of {:a 1 :b 2}) ``` ### entries-of `(entries-of map) -> Array` Returns an `Array` of `[key value]` pairs from `map`. ```tangu (entries-of {:a 1}) ; => [[:a 1]] ``` ### sort / sort<- `(sort array) -> Array, (sort<- #mut array) -> Array` `sort` returns a sorted copy of `array` using natural `Ord` comparison; `sort<-` sorts a `#mut` array in place. ```tangu (sort [3 1 2]) ; => [1 2 3] ``` ### sort-by `(sort-by array key-or-cmp-fn) -> Array` Sorts `array` by a key-extractor function `(Func x key)` or comparator `(Func [a b] Int)`. ```tangu (sort-by users (Func u u:age)) ``` ### reverse<- / concat<- / roll `(reverse<- #mut array), (concat<- #mut array other), (roll seq offset)` In-place array reversal (`reverse<-`), in-place array extension (`concat<-`), and circular element rotation (`roll`). ```tangu (roll [1 2 3 4] 1) ; => [4 1 2 3] ``` ### map `(map seq fn) -> Array` Applies `fn` to each element of `seq` and returns a new `Array`. ```tangu (map [1 2 3] (* %0 2)) ; => [2 4 6] ``` ### filter `(filter seq pred-fn) -> Array` Returns a new `Array` containing elements of `seq` for which `pred-fn` returns `true`. ```tangu (filter [1 2 3 4] (> %0 2)) ; => [3 4] ``` ### collect `(collect seq-or-iter) -> Array` Materializes any lazy iterator, range, set, or sequence into a contiguous `Array`. ```tangu (collect 0..5) ; => [0 1 2 3 4] ``` ## String intrinsics Built-in UTF-8 string search, splitting, replacement, and case conversion. ### trim `(trim str) -> String` Strips leading and trailing whitespace (`trim-start` and `trim-end` strip one side). ```tangu (trim " hi ") ; => "hi" ``` ### split `(split str delimiter) -> (Array String)` Splits `str` around `delimiter` into an `Array` of substrings. ```tangu (split "a,b,c" ",") ; => ["a" "b" "c"] ``` ### join `(join array separator?) -> String` Joins elements of `array` into a single `String` separated by `separator`. ```tangu (join ["a" "b"] "-") ; => "a-b" ``` ### replace `(replace str pattern replacement) -> String` Replaces all occurrences of `pattern` in `str` with `replacement` (`replace-first` replaces only the first). ```tangu (replace "foo-bar" "-" "_") ; => "foo_bar" ``` ### starts-with? `(starts-with? str prefix) -> Bool` Returns `true` if `str` starts with `prefix`. ```tangu (starts-with? "/stdlib-web" "/stdlib") ; => true ``` ### ends-with? `(ends-with? str suffix) -> Bool` Returns `true` if `str` ends with `suffix`. ```tangu (ends-with? "main.tan" ".tan") ; => true ``` ### to-lower-case `(to-lower-case str) -> String` Converts `str` to lowercase Unicode characters. ```tangu (to-lower-case "Tangu") ; => "tangu" ``` ### to-upper-case `(to-upper-case str) -> String` Converts `str` to uppercase Unicode characters. ```tangu (to-upper-case "tangu") ; => "TANGU" ``` ## Types, introspection & sized integers Runtime type predicates, deep cloning, hashing, and explicit sized integer constructors. ### type-of `(type-of value) -> Symbol` Returns the runtime type name of `value` (`Int`, `Float`, `Dec`, `String`, `Array`, `Map`, or a `Struct` name). ```tangu (type-of [1 2]) ; => Array ``` ### is-a? `(is-a? Type value) -> Bool` Returns `true` if `value` is an instance of `Type` (or implements trait `Type`). ```tangu (is-a? Int 42) ; => true ``` ### is-some? `(is-some? value) -> Bool` Returns `true` if `value` is neither `()` (None) nor an `Error`. ```tangu (is-some? 0) ; => true ``` ### is-none? `(is-none? value) -> Bool` Returns `true` if `value` is `()` (None). ```tangu (is-none? ()) ; => true ``` ### is-error? `(is-error? value) -> Bool` Returns `true` if `value` is an `Error`. ```tangu (is-error? (Error :fail "msg")) ; => true ``` ### clone `(clone value) -> Any` Returns a deep structural copy of `value`, duplicating mutable collections and structs. ```tangu (let copy (clone original)) ``` ### hash `(hash value) -> Int` Computes the deterministic 64-bit hash of any value or `Struct` implementing `Hash`. ```tangu (hash {:a 1 :b 2}) ``` ### I8 / I16 / I32 / I64 / I128 / ISize `12i8, 123i16, 12_345i32, -10isize, (I32 val) -> I32` Signed sized integer literal suffixes and constructors wrapping modulo the bit width (`8`, `16`, `32`, `64`, `128`, or pointer width). ```tangu (let offset 12_345i32) ``` ### U8 / U16 / U32 / U64 / U128 / USize `255u8, 8005u16, 1000usize, (U8 val) -> U8` Unsigned sized integer literal suffixes and constructors (`U8` is also aliased as `Byte`). ```tangu (let port 8005u16) ``` ### cast `(cast Target-Type value) -> Target-Type` Performs an explicit numeric or structural type conversion to `Target-Type`. ```tangu (cast Float 42) ; => 42.0 ``` ## Core & derivable traits Built-in traits supported by `(derive My-Struct ...)` and custom `(impl Trait My-Struct ...)`. ### Eq `(derive My-Struct Eq)` Structural equality comparison via `(== a b)` and `(!= a b)`. ```tangu (derive Point Eq) ``` ### Ord `(derive My-Struct Ord)` Total ordering comparison via `<`, `<=`, `>`, `>=`, and `sort`. ```tangu (derive Point Eq Ord) ``` ### Hash `(derive My-Struct Hash)` Deterministic hashing via `(hash x)`, enabling use as `Map` keys and `Set` elements. ```tangu (derive Point Eq Hash) ``` ### Clone `(derive My-Struct Clone)` Deep structural duplication via `(clone x)`. ```tangu (derive Point Clone) ``` ### To-String `(derive My-Struct To-String)` Human-readable string conversion via `(String x)` and string interpolation. ```tangu (derive Point To-String) ``` ### Default `(derive My-Struct Default)` Zero-argument default construction via `(construct-default My-Struct)`. ```tangu (derive Point Default) ``` ### Countable `(def Countable (Trait #(Func This Int) (count-of (Func this))))` Custom length/size reporting for `(count-of x)` and `(is-empty? x)`. ```tangu (impl Countable Queue (let count-of (Func self (count-of self:items)))) ``` ### Contains `(def Contains (Trait #(Func [This Any] Bool) (contains? (Func [this item]))))` Custom membership testing for `(contains? x item)`. ```tangu (impl Contains Span (let contains? (Func [self v] (and (>= v self:lo) (<= v self:hi))))) ``` ### To-JSON / From-JSON `(derive My-Struct To-JSON From-JSON)` Zero-boilerplate JSON serialization with `(encode x)` and typed deserialization with `(from-json My-Struct data)` or `(decode raw My-Struct)`. ```tangu (derive Point To-JSON From-JSON) ``` ## Arithmetic, bitwise & math intrinsics Numeric operators and transcendental functions available in the prelude. ### + / - / * / / / % / ** `(+ a b ...), (- a b), (* a b ...), (/ a b), (% a b), (** base exp)` Arithmetic addition, subtraction, multiplication, division, remainder (`%`), and exponentiation (`**`) across `Int`, `Float`, `Dec`, and sized integers. ```tangu (+ 10 20 30) ; => 60 ``` ### == / != / < / <= / > / >= `(== a b), (!= a b), (< a b), (<= a b), (> a b), (>= a b)` Equality and relational ordering comparisons returning `Bool`. ```tangu (<= 10 20) ; => true ``` ### and / or / not `(and a b ...), (or a b ...), (not a)` Short-circuiting boolean conjunction (`and`), disjunction (`or`), and negation (`not`). ```tangu (and (> x 0) (< x 100)) ``` ### abs / min / max / clamp `(abs x), (min a b), (max a b), (clamp x lo hi)` Absolute value, minimum, maximum, and range clamping. ```tangu (clamp 150 0 100) ; => 100 ``` ### floor / ceil / round / trunc `(floor x), (ceil x), (round x), (trunc x)` Floating-point and decimal rounding functions. ```tangu (round 3.6) ; => 4.0 ``` ### sqrt / sin / cos / tan / log / exp `(sqrt x), (sin x), (cos x), (tan x), (log x), (exp x)` Square root, trigonometric functions, natural logarithm, and exponential. ```tangu (sqrt 16.0) ; => 4.0 ``` ### bit-and / bit-or / bit-xor / bit-not / bit-shl / bit-shr `(bit-and a b), (bit-or a b), (bit-xor a b), (bit-shl x n), (bit-shr x n)` Bitwise AND, OR, XOR, NOT, left shift (`bit-shl`), and arithmetic/logical right shift (`bit-shr`). ```tangu (bit-shl 1 8) ; => 256 ``` ## I/O, data parsing & assertion intrinsics Console output, safe `.data.tan` loading, AST parsing, and test assertions. ### say / echo `(say value...), (echo value...)` `say` prints arguments to stdout followed by a newline; `echo` prints without a trailing newline. ```tangu (say "Listening on port ${port}") ``` ### read / write `(read path) -> String, (write path content) -> None` Convenience prelude functions to read a UTF-8 file into a `String` or write a `String` to disk. ```tangu (let text (read "readme.text")) ``` ### read-data / load-data `(read-data str) -> Any, (load-data path) -> Any` Safely parses a pure `.data.tan` literal from a string or file without evaluating executable calls. ```tangu (let manifest (load-data "manifest.data.tan")) ``` ### parse-expr / parse-exprs `(parse-expr str) -> Expr, (parse-exprs str) -> (Array Expr)` Parses Tangu source code into homoiconic s-expression AST nodes. ```tangu (let ast (parse-expr "(+ 1 2)")) ``` ### assert / assert-eq! / assert-ne! `(assert cond msg?), (assert-eq! left right), (assert-ne! left right)` Test and invariant assertions that panic with source location and diff details when violated. ```tangu (assert-eq! (+ 2 2) 4) ``` ### panic! `(panic! message)` Immediately aborts the current evaluation or test with `message`. ```tangu (panic! "unreachable state") ``` --- # Collections & iteration (`https://tangu.dev/stdlib-collections/`) Lazy iterator combinators (/iter), sets (/set), sorted and unordered maps, vectors (/vec), and ring buffers. ## Module /iter Lazy iterator adapters and eager sequence reductions (map, filter, fold, reduce, zip, take, drop, chunk, flatten, group-by, partition). ```tangu (use /iter) ``` ### Iter `(arr)` Exported function in `/iter`. ### all? `(xs f)` Exported function in `/iter`. ### any? `(xs f)` Exported function in `/iter`. ### chunks `(Func [Array Int] Array)` Exported function in `/iter`. ### compact `(xs)` Exported function in `/iter`. ### drop `(iter/drop coll n) -> List` Returns collection excluding first n items. ```tangu (iter/drop [1 2 3 4] 2) ; -> [3 4] ``` ### filter `(iter/filter coll predicate) -> List` Returns elements of collection for which predicate returns true. ```tangu (iter/filter [1 2 3 4] (Func [x] (== (% x 2) 0))) ; -> [2 4] ``` ### filter-unique `(iter/filter-unique coll) -> Array` Deduplicates elements of collection in O(N) time while preserving first-seen insertion order. ```tangu (use {filter-unique} /iter) (filter-unique ["b" "a" "b" "c"]) ; -> ["b" "a" "c"] ``` ### filter-unique-by `(iter/filter-unique-by coll key-fn) -> Array` Deduplicates elements of collection by `(key-fn item)` in O(N) time while preserving first-seen insertion order. ```tangu (use {filter-unique-by} /iter) (filter-unique-by users (Func [u] u:id)) ``` ### find `(iter/find coll predicate) -> (Or Any)` Returns the first element satisfying predicate, or () if none found. ```tangu (iter/find [1 2 3] (Func [x] (> x 1))) ; -> 2 ``` ### find-index `(Func [Array Func] Any)` Exported function in `/iter`. ### flat-map `(xs func)` Exported function in `/iter`. ### flatten `(xs)` Exported function in `/iter`. ### fold `(iter/fold coll init func) -> Any` Folds collection left-to-right with accumulator and reducer function. ```tangu (iter/fold [1 2 3] 0 (Func [acc x] (+ acc x))) ; -> 6 ``` ### group-by `(Func [Any Any] Map)` Exported function in `/iter`. ### map `(iter/map coll func) -> List` Applies function to each item in collection, returning a new List of results. ```tangu (iter/map [1 2 3] (Func [x] (* x 2))) ; -> [2 4 6] ``` ### next `(it)` Exported function in `/iter`. ### partition `(Func [Array Func] Array)` Exported function in `/iter`. ### reduce `(Func [Array Func] Any)` Exported function in `/iter`. ### rewind `(it step)` Exported function in `/iter`. ### take `(iter/take coll n) -> List` Returns first n items from collection. ```tangu (iter/take [1 2 3 4] 2) ; -> [1 2] ``` ### windows `(Func [Array Int] Array)` Exported function in `/iter`. ## Module /set Hash-based unordered set operations: union, intersection, difference, symmetric-difference, subset?, and superset?. ```tangu (use /set) ``` ### Set `(Set) -> Set` Constructs a new empty Set or initializes a Set with the given items. ```tangu (use /set) (let s (Set)) (put s "apple") ``` ### contains? `(Func [Set Any] Any)` Exported function in `/set`. ### count-of `(Func Set Int)` Exported function in `/set`. ### difference `(Func Any Set)` Exported function in `/set`. ### intersection `(Func Any Set)` Exported function in `/set`. ### into-iter `(Func Set Any)` Exported function in `/set`. ### put `(put set item) -> Set` Inserts an element into the set. ### remove `(Func [Set Any] Any)` Exported function in `/set`. ### subset? `(Func [Set Set] Any)` Exported function in `/set`. ### union `(Func Any Set)` Exported function in `/set`. ### values-of `(values-of set) -> Array` Returns an Array containing all elements in the set. ## Module /map Map transformation helpers (pick, extend, union) complementing the prelude Map intrinsics. ```tangu (use /map) ``` ### extend `(target source)` Exported function in `/map`. ### pick `(source keys)` Exported function in `/map`. ### union `(x y)` Exported function in `/map`. ## Module /sorted-map B-Tree backed ordered map (Sorted-Map) maintaining keys in ascending sorted order. ```tangu (use /sorted-map) ``` ### Sorted-Map `(Sorted-Map ...)` Exported function in `/sorted-map`. ### contains-key? `(contains-key? ...)` Exported function in `/sorted-map`. ### count `(count ...)` Exported function in `/sorted-map`. ### count-of `(count-of ...)` Exported function in `/sorted-map`. ### entries-of `(entries-of ...)` Exported function in `/sorted-map`. ### first-entry `(first-entry ...)` Exported function in `/sorted-map`. ### get `(get ...)` Exported function in `/sorted-map`. ### into-iter `(into-iter ...)` Exported function in `/sorted-map`. ### is-empty? `(is-empty? ...)` Exported function in `/sorted-map`. ### keys-of `(keys-of ...)` Exported function in `/sorted-map`. ### last-entry `(last-entry ...)` Exported function in `/sorted-map`. ### put `(put ...)` Exported function in `/sorted-map`. ### remove `(remove ...)` Exported function in `/sorted-map`. ### values-of `(values-of ...)` Exported function in `/sorted-map`. ## Module /unordered-map Explicit hash map wrapper (Unordered-Map) with entry iteration and key/value views. ```tangu (use /unordered-map) ``` ### Unordered-Map `(Unordered-Map ...)` Exported function in `/unordered-map`. ### contains-key? `(contains-key? ...)` Exported function in `/unordered-map`. ### count `(count ...)` Exported function in `/unordered-map`. ### count-of `(count-of ...)` Exported function in `/unordered-map`. ### entries-of `(entries-of ...)` Exported function in `/unordered-map`. ### get `(get ...)` Exported function in `/unordered-map`. ### into-iter `(into-iter ...)` Exported function in `/unordered-map`. ### is-empty? `(is-empty? ...)` Exported function in `/unordered-map`. ### keys-of `(keys-of ...)` Exported function in `/unordered-map`. ### put `(put ...)` Exported function in `/unordered-map`. ### remove `(remove ...)` Exported function in `/unordered-map`. ### values-of `(values-of ...)` Exported function in `/unordered-map`. ## Module /circular-buffer Fixed-capacity ring buffer (Circular-Buffer) supporting O(1) push/pop and sequence iteration. ```tangu (use /circular-buffer) ``` ### Circular-Buffer `(Circular-Buffer ...)` Exported function in `/circular-buffer`. ### Iter `(Iter ...)` Exported function in `/circular-buffer`. ### as-array `(as-array ...)` Exported function in `/circular-buffer`. ### count-of `(count-of ...)` Exported function in `/circular-buffer`. ### into-iter `(into-iter ...)` Exported function in `/circular-buffer`. ### push `(push ...)` Exported function in `/circular-buffer`. ### put `(put ...)` Exported function in `/circular-buffer`. ## Module /vec 2D, 3D, and 4D Euclidean vector math (Vec2, Vec3, Vec4): dot product, cross product, normalization, and distance. ```tangu (use /vec) ``` ### Vec2 `Struct` in `/vec` 2D vector with `#Float` components. | Field | Type | Default | | :--- | :--- | :--- | | `x` | `Float` | `—` | | `y` | `Float` | `—` | ### Vec3 `Struct` in `/vec` 3D vector with `#Float` components. | Field | Type | Default | | :--- | :--- | :--- | | `x` | `Float` | `—` | | `y` | `Float` | `—` | | `z` | `Float` | `—` | ### Vec4 `Struct` in `/vec` 4D homogeneous vector with `#Float` components. | Field | Type | Default | | :--- | :--- | :--- | | `x` | `Float` | `—` | | `y` | `Float` | `—` | | `z` | `Float` | `—` | | `field_7` | `Any` | `—` | ### Vec `Trait` in `/vec` Algebraic vector trait for N-dimensional `#Float` Structs. Automatically implemented via `(derive T Vec)`. ### cross `(a b)` Computes the 3D cross product in homogeneous 4D coordinates (t = 0.0). ### perp `(v)` Returns the 2D perpendicular vector `(-y, x)` (90-degree counterclockwise rotation). ## Module /func Higher-order function utilities including partial application (curry), dynamic argument invocation (apply), and memoization (memoize). ```tangu (use /func) ``` ### apply `(Func [Any (Array Any)] Any)` Exported function in `/func`. ### curry `(Func Any Any)` Exported function in `/func`. ### memoize `(Func Any Any)` Exported function in `/func`. --- # Text, strings & localization (`https://tangu.dev/stdlib-text/`) String manipulation (/string), regular expressions (/regex), CommonMark (/text/cmark), HTML escaping, and ICU4X (/i18n). ## Module /string UTF-8 string manipulation: case conversion, trimming, padding, splitting, joining, and substring search. ```tangu (use /string) ``` ### byte-count-of `(Func String Any)` Exported function in `/string`. ### byte-slice `(Func [String Int Int] Any)` Exported function in `/string`. ### chars `(chars str) -> Array` Converts string into an array of individual Unicode Char elements. ```tangu (chars "tan") ; -> ['t' 'a' 'n'] ``` ### contains? `(contains? str substring) -> Bool` Returns true if str contains the given substring. ```tangu (contains? "hello world" "world") ; -> true ``` ### count-of `(Func String Any)` Exported function in `/string`. ### ends-with? `(ends-with? str suffix) -> Bool` Returns true if str ends with suffix. ```tangu (ends-with? "main.tan" ".tan") ; -> true ``` ### format-string `(Func Any Any)` Exported function in `/string`. ### ignore-case-contains? `(string/ignore-case-contains? str substring) -> Bool` Returns true if str contains the given substring (case-insensitive, zero-allocation for ASCII). ```tangu (use {ignore-case-contains?} /string) (ignore-case-contains? "TikTok.com" "tiktok.com") ; -> true ``` ### ignore-case-index-of `(string/ignore-case-index-of str sub) -> (Or Int)` Returns 0-based character index of substring `sub` in `str` (case-insensitive), or () if not found. ```tangu (use {ignore-case-index-of} /string) (ignore-case-index-of "Hello World" "world") ; -> 6 ``` ### index-of `(Func [String String] Any)` Exported function in `/string`. ### is-blank? `(string/is-blank? x) -> Bool` Returns true if x is (), "", or contains only whitespace characters. ```tangu (use {is-blank?} /string) (is-blank? " ") ; -> true ``` ### last-index-of `(string/last-index-of str sub) -> (Or Int)` Returns last 0-based character index of substring `sub` in `str` (optionally up to `end-index`), or () if not found. ```tangu (use {last-index-of} /string) (last-index-of "hello world" "o") ; -> 7 ``` ### pad-left `(pad-left str width) -> String` Pads string on the left with spaces until it reaches width. ```tangu (pad-left "42" 5) ; -> " 42" ``` ### pad-right `(pad-right str width) -> String` Pads string on the right with spaces until it reaches width. ```tangu (pad-right "42" 5) ; -> "42 " ``` ### repeat `(Func [String Int] String)` Exported function in `/string`. ### replace `(replace str from to) -> String` Replaces all occurrences of `from` with `to` in `str`. ```tangu (replace "foo bar" "bar" "baz") ; -> "foo baz" ``` ### slice `(slice str start) -> String` Returns substring from start to end index. Supports negative indices and Range literals like (slice str 0..5). ```tangu (slice "hello" 0 2) ; -> "he" ``` ### split `(split str delimiter) -> List` Splits str by separator delimiter, returning a List of substrings. ```tangu (split "a,b,c" ",") ; -> ["a" "b" "c"] ``` ### starts-with? `(starts-with? str prefix) -> Bool` Returns true if str begins with prefix. ```tangu (starts-with? "/api/users" "/api") ; -> true ``` ### strip-prefix `(Func [String String] String)` Exported function in `/string`. ### strip-suffix `(Func [String String] String)` Exported function in `/string`. ### to-lower-case `(to-lower-case str) -> String` Converts all characters in string to lowercase. ```tangu (to-lower-case "TANGU") ; -> "tangu" ``` ### to-upper-case `(to-upper-case str) -> String` Converts all characters in string to uppercase. ```tangu (to-upper-case "tangu") ; -> "TANGU" ``` ### trim `(trim str) -> String` Returns a copy of the string with leading and trailing whitespace removed. ```tangu (trim " hello ") ; -> "hello" ``` ### trim-end `(trim-end str) -> String` Returns string with trailing whitespace removed. ### trim-start `(trim-start str) -> String` Returns string with leading whitespace removed. ## Module /regex Compiled regular expressions (Regex) supporting matching, replacement, splitting, and named/indexed capture groups. ```tangu (use /regex) ``` ### Regex `(Regex ...)` Exported function in `/regex`. ### capture `(capture ...)` Exported function in `/regex`. ### captures `(captures ...)` Exported function in `/regex`. ### captures-all `(captures-all ...)` Exported function in `/regex`. ### is-matching? `(is-matching? ...)` Exported function in `/regex`. ### matching? `(matching? ...)` Exported function in `/regex`. ### replace `(replace ...)` Exported function in `/regex`. ### split `(split ...)` Exported function in `/regex`. ### split-matches `(split-matches ...)` Exported function in `/regex`. ## Module /text Human-readable text capitalization and formatting utilities. ```tangu (use /text) ``` ### capitalize `(capitalize ...)` Exported function in `/text`. ## Module /text/case Identifier case conversion between camelCase, PascalCase, snake_case, SCREAMING_SNAKE_CASE, and kebab-case. ```tangu (use /text/case) ``` ### camel-split `(text)` Exported function in `/text/case`. ### camel-to-kebab `(text)` Exported function in `/text/case`. ### camel-to-snake `(text)` Exported function in `/text/case`. ### is-screaming? `(text)` Exported function in `/text/case`. ### kebab-join `(words)` Exported function in `/text/case`. ### kebab-split `(phrase)` Exported function in `/text/case`. ### snake-join `(words)` Exported function in `/text/case`. ### snake-split `(phrase)` Exported function in `/text/case`. ### snake-to-kebab `(text)` Exported function in `/text/case`. ### to-kebab `(text)` Exported function in `/text/case`. ## Module /text/cmark CommonMark and GitHub Flavored Markdown (tables, strikethrough, task lists) to HTML compiler (to-html). ```tangu (use /text/cmark) ``` ### to-html `(to-html markdown) -> String` Compiles CommonMark and GitHub Flavored Markdown text into an HTML string. ## Module /i18n Unicode CLDR internationalization powered by ICU4X: locale-aware numbers, currencies, dates, relative time, plurals, collation, and grapheme segmentation. ```tangu (use /i18n) ``` ### canonical-locale `(canonical-locale ...)` Exported function in `/i18n`. ### fold-case `(fold-case ...)` Exported function in `/i18n`. ### format `(i18n/format value) -> String` Polymorphically formats numbers, /chrono temporal and duration values, and sequences according to locale rules. ```tangu (i18n/format 1234567.89d "el-GR") (i18n/format ["Αθήνα" "Θεσσαλονίκη"] "el") ``` ### format-date-time `(i18n/format-date-time temporal [locale-or-opts]) -> String` Formats a /chrono temporal value according to CLDR calendar and locale conventions. ```tangu (i18n/format-date-time (chrono/Date 2025 3 25) {:locale "el-GR" :style :long}) ``` ### format-duration `(i18n/format-duration duration [locale-or-opts]) -> String` Formats a /chrono Duration, Span, or unit Map into localized unit lists or digital clock notation. ```tangu (i18n/format-duration {:hours 2 :minutes 45} {:locale "el" :style :long}) ``` ### format-list `(i18n/format-list items [locale-or-opts]) -> String` Formats a sequence of items using locale-specific list conjunctions or disjunctions. ```tangu (i18n/format-list ["Αθήνα" "Πάτρα" "Κρήτη"] "el") ``` ### format-number `(i18n/format-number n [locale-or-opts]) -> String` Formats a number with locale-specific grouping, decimal separators, currency symbols, percentages, or compact notation. ```tangu (i18n/format-number 1234.5d {:locale "el-GR" :style :currency :currency "EUR"}) (i18n/format-number 1250000 {:locale "en-US" :notation :compact}) ``` ### format-relative `(i18n/format-relative delta unit [locale-or-opts]) -> String` Formats relative time phrases such as "yesterday", "χθες", or "in 3 hours". ```tangu (i18n/format-relative -1 :day "el") ``` ### graphemes `(i18n/graphemes text [locale]) -> Array` Segments a string into an Array of UAX #29 extended grapheme clusters. ```tangu (i18n/graphemes "👨‍👩‍👧‍👦🇬🇷") ``` ### locale-comparator `(locale-comparator ...)` Exported function in `/i18n`. ### locale-compare `(i18n/locale-compare a b [locale-or-opts]) -> Int` Compares two strings using the Unicode Collation Algorithm, returning -1, 0, or 1. ```tangu (i18n/locale-compare "α" "ά" {:locale "el" :sensitivity :base}) ``` ### locale-sort `(i18n/locale-sort items [locale-or-opts]) -> Array` Returns a new sequence sorted by locale collation rules, supporting :key and :reverse. ```tangu (i18n/locale-sort ["Ωμέγα" "Αθήνα" "Άρτα"] "el") ``` ### maximize-locale `(maximize-locale ...)` Exported function in `/i18n`. ### minimize-locale `(minimize-locale ...)` Exported function in `/i18n`. ### parse-locale `(i18n/parse-locale tag [opts]) -> Map` Parses and canonicalizes a BCP 47 locale tag into a Map of subtags and Unicode extension preferences. ```tangu (i18n/parse-locale "el-GR-u-ca-gregory-hc-h23") ``` ### plural `(i18n/plural n forms-map [locale-or-opts]) -> Any` Selects a localized plural form from a category map or formats a singular/plural noun pair. ```tangu (i18n/plural 5 "μήνυμα" "μηνύματα" "el") ``` ### plural-category `(i18n/plural-category n [locale-or-opts]) -> Symbol` Returns the CLDR plural category (:zero, :one, :two, :few, :many, :other) for a number. ```tangu (i18n/plural-category 1 "el") ``` ### segment `(segment ...)` Exported function in `/i18n`. ### sentences `(sentences ...)` Exported function in `/i18n`. ### strip-accents `(i18n/strip-accents s) -> String` Removes combining diacritical marks via NFD decomposition and NFC recomposition. ```tangu (i18n/strip-accents "Καλημέρα Αθήνα café") ``` ### to-locale-lower-case `(to-locale-lower-case ...)` Exported function in `/i18n`. ### to-locale-title-case `(to-locale-title-case ...)` Exported function in `/i18n`. ### to-locale-upper-case `(i18n/to-locale-upper-case s [locale]) -> String` Converts a string to uppercase using locale-specific Unicode case mapping rules. ```tangu (i18n/to-locale-upper-case "Καλημέρα Ελλάδα" "el") ``` ### words `(i18n/words text [locale-or-opts]) -> Array` Extracts word-like tokens from a string using UAX #29 word boundary rules. ```tangu (i18n/words "Καλημέρα κόσμε!") ``` ## Module /html HTML entity escaping, attribute sanitization, and tag stripping for safe user-content rendering. ```tangu (use /html) ``` ### escape `(escape ...)` Exported function in `/html`. ### escape-text `(escape-text ...)` Exported function in `/html`. ### sanitize `(sanitize ...)` Exported function in `/html`. ### strip-tags `(strip-tags ...)` Exported function in `/html`. --- # System, filesystem & I/O (`https://tangu.dev/stdlib-system/`) Filesystem operations (/fs), buffered I/O (/io), path manipulation (/path), processes (/process), OS threads (/thread), and async coroutines (/coro). ## Module /fs Filesystem operations: reading, writing, copying, moving, directory traversal, globbing, and path canonicalization. ```tangu (use /fs) ``` ### canonicalize `(fs/canonicalize path) -> String` Resolves relative paths, symlinks, and `..` segments to an absolute normalized path. ```tangu (let abs-path (fs/canonicalize "../config.json")) ``` ### close `(close handle) -> None` Closes the underlying connection, pool, file descriptor, or stream. ### copy `(fs/copy source target) -> Int` Copies source file to target destination, returning bytes copied. ```tangu (fs/copy "a.txt" "b.txt") ``` ### copy-directory `(copy-directory ...)` Exported function in `/fs`. ### create `(create ...)` Exported function in `/fs`. ### create-directory `(fs/create-directory path) -> Bool` Recursively creates the directory at path (equivalent to mkdir -p). ```tangu (fs/create-directory "./build/dist") ``` ### exists? `(fs/exists? path) -> Bool` Returns true if the file or directory at path exists, otherwise false. ```tangu (if (fs/exists? "./data.json") (echo "found") (else (echo "missing")))" ``` ### flush `(flush writer) -> None` Flushes all buffered output bytes in `writer` to the underlying OS stream. ### get-current-dir `(fs/get-current-dir) -> String` Returns the absolute path of the current working directory. ### is-directory? `(fs/is-directory? path) -> Bool` Returns true if path exists and points to a directory. ### is-file? `(fs/is-file? path) -> Bool` Returns true if path exists and points to a regular file. ### list `(fs/list path) -> List` Lists file and folder paths in the directory. Accepts optional {:include-dirs true}. ```tangu (let files (fs/list ".")) ``` ### list-as-tree `(fs/list-as-tree path) -> List` Recursively walks directory and returns hierarchy tree. ### open `(open ...)` Exported function in `/fs`. ### read `(read ...)` Exported function in `/fs`. ### read-all `(read-all reader) -> Slab` Reads all remaining bytes from `reader` until EOF into a `Slab`. ### read-byte `(read-byte reader) -> (Or U8 None)` Reads a single byte (`U8`) from `reader`, or returns `()` at EOF. ### read-char `(read-char reader) -> (Or Char None)` Reads a single UTF-8 `Char` from `reader`, or returns `()` at EOF. ### read-line `(read-line reader) -> (Or String None)` Reads a line of UTF-8 text from `reader` (stripping trailing newline), or returns `()` at EOF. ### read-slab-from-file `(fs/read-slab-from-file path) -> Slab` Reads raw bytes of a file into a binary Slab buffer. ### read-string `(read-string reader) -> String` Reads all remaining UTF-8 text from `reader` until EOF into a `String`. ### read-string-from-file `(fs/read-string-from-file path) -> String` Reads the complete UTF-8 contents of a file at path into a String. Returns an Error if the file cannot be read. ```tangu (let content (fs/read-string-from-file "config.json")) ``` ### remove-directory `(fs/remove-directory path) -> Bool` Recursively removes the directory at path and all its contents. ```tangu (fs/remove-directory "./tmp") ``` ### remove-file `(remove-file ...)` Exported function in `/fs`. ### rename `(fs/rename from to) -> Bool` Renames or moves a file or directory from one path to another. ```tangu (fs/rename "old.txt" "new.txt") ``` ### write `(write ...)` Exported function in `/fs`. ### write-byte `(write-byte writer byte) -> None` Writes a single byte (`U8`) to `writer`. ### write-line `(write-line writer line) -> None` Writes `line` followed by a newline character to `writer`. ### write-slab-to-file `(fs/write-slab-to-file path slab) -> Int` Writes binary Slab buffer to file at path. Returns number of bytes written. ### write-string `(write-string writer str) -> None` Writes a UTF-8 `String` to `writer`. ### write-string-to-file `(fs/write-string-to-file path content) -> Int` Writes content to path, automatically creating parent directories if necessary. Returns the number of bytes written. ```tangu (fs/write-string-to-file "./output/log.txt" "Task completed.") ``` ### writeln `(writeln ...)` Exported function in `/fs`. ## Module /io Buffered and standard stream I/O (Buf-Reader, Buf-Writer, Stdin, Stdout, Stderr, read-line, write-line, flush, and ask). ```tangu (use /io) ``` ### Buf-Reader `(Func Any Any)` Wraps an input stream or file handle in a buffered reader. ### Buf-Writer `(Func Any Any)` Wraps an output stream or file handle in a buffered writer. ### Stderr `(Stderr) -> Stream` Returns a handle to the standard error stream (`stderr`). ### Stdin `(Stdin) -> Stream` Returns a handle to the standard input stream (`stdin`). ### Stdout `(Stdout) -> Stream` Returns a handle to the standard output stream (`stdout`). ### ask `(Func Any Any)` Prints an optional `prompt` to `stdout`, flushes it, and reads a single line of user input from `stdin`. ### flush `(Func Any Any)` Flushes all buffered output bytes in `writer` to the underlying OS stream. ### read `(Func [Any Int] Any)` Exported function in `/io`. ### read-all `(Func Any Any)` Reads all remaining bytes from `reader` until EOF into a `Slab`. ### read-byte `(Func Any Any)` Reads a single byte (`U8`) from `reader`, or returns `()` at EOF. ### read-char `(Func Any Any)` Reads a single UTF-8 `Char` from `reader`, or returns `()` at EOF. ### read-line `(Func Any Any)` Reads a line of UTF-8 text from `reader` (stripping trailing newline), or returns `()` at EOF. ### read-string `(Func Any Any)` Reads all remaining UTF-8 text from `reader` until EOF into a `String`. ### stderr `(stderr ...)` Exported function in `/io`. ### stdin `(stdin ...)` Exported function in `/io`. ### stdout `(stdout ...)` Exported function in `/io`. ### write `(Func [Any Any] Any)` Exported function in `/io`. ### write-byte `(Func [Any Any] Any)` Writes a single byte (`U8`) to `writer`. ### write-line `(Func [Any Any] Any)` Writes `line` followed by a newline character to `writer`. ### write-string `(Func [Any Any] Any)` Writes a UTF-8 `String` to `writer`. ## Module /path Cross-platform lexical path manipulation: dirname, filename, extension-of, stem-of, join, and normalize. ```tangu (use /path) ``` ### basename-of `(path/basename-of path) -> String` Returns the trailing component of a path. ```tangu (path/basename-of "/home/user/doc.txt") -> "doc.txt" ``` ### dirname-of `(path/dirname-of path) -> String` Returns the parent directory portion of a path, or empty string if none. ```tangu (path/dirname-of "/home/user/doc.txt") -> "/home/user" ``` ### extension-of `(path/extension-of path) -> String` Returns the full file extension (e.g. "tar.gz", "data.tan"), or empty string if none. ```tangu (path/extension-of "archive.tar.gz") -> "tar.gz" ``` ### get-dirname `(Func Any Any)` Exported function in `/path`. ### get-extension `(Func Any Any)` Exported function in `/path`. ### is-absolute? `(path/is-absolute? path) -> Bool` Returns true if the path is absolute. ```tangu (path/is-absolute? "/usr/bin") -> true ``` ### is-relative? `(path/is-relative? path) -> Bool` Returns true if the path is relative. ```tangu (path/is-relative? "src/main.tan") -> true ``` ### join `(path/join ...parts) -> String` Safely joins multiple path segments using platform-specific path separators. ```tangu (path/join "src" "bin" "main.tan") ``` ### normalize `(path/normalize path) -> String` Lexically normalizes path by resolving "." and ".." segments without accessing the filesystem. ```tangu (path/normalize "a/b/../c") -> "a/c" ``` ### path-join `(Func Any String)` Exported function in `/path`. ### relative-to `(path/relative-to base target) -> String` Computes the relative path required to navigate from base to target. ```tangu (path/relative-to "/a/b" "/a/b/c/d") -> "c/d" ``` ### resolve `(path/resolve ...paths) -> String` Resolves a sequence of paths into an absolute normalized path relative to the current working directory. ```tangu (path/resolve "config" "app.json") ``` ### split `(path/split path) -> Array` Splits a path into an Array of its constituent component strings. ```tangu (path/split "a/b/c") -> ["a" "b" "c"] ``` ### stem-of `(path/stem-of path) -> String` Returns the file stem (basename minus full extension). Preserves: stem-of + "." + extension-of == basename-of. ```tangu (path/stem-of "archive.tar.gz") -> "archive" ``` ## Module /os Host operating system, CPU architecture, hostname, and environment introspection. ```tangu (use /os) ``` ### arch `(os/arch) -> String` Returns the CPU architecture (e.g. "x86_64", "aarch64"). ```tangu (let target-arch (os/arch)) ``` ### cpu-count `(os/cpu-count) -> Int` Returns the number of logical CPU cores available to the current process. ```tangu (let concurrency (os/cpu-count)) ``` ### family `(os/family) -> String` Returns the operating system family (e.g. "unix", "windows"). ```tangu (if (= (os/family) "unix") (writeln "POSIX compliant")) ``` ### home-dir `(os/home-dir) -> (Or String ())` Returns the current user's home directory path, or () if not found. ```tangu (let home (os/home-dir)) ``` ### host-name `(os/host-name) -> String` Returns the network hostname of the host system. ```tangu (let host (os/host-name)) ``` ### os-name `(os/os-name) -> String` Returns the operating system name (e.g. "linux", "macos", "windows"). ```tangu (let os (os/os-name)) ``` ### temp-dir `(os/temp-dir) -> String` Returns the default directory path for temporary files. ```tangu (let tmp (os/temp-dir)) ``` ### uptime `(os/uptime) -> Float` Returns system uptime in seconds as a floating-point number. ```tangu (let secs (os/uptime)) ``` ## Module /os/well-known Cross-platform XDG / OS standard directories (config-dir, cache-dir, data-dir, home-dir, download-dir). ```tangu (use /os/well-known) ``` ### cache-dir `(cache-dir ...)` Exported function in `/os/well-known`. ### config-dir `(config-dir ...)` Exported function in `/os/well-known`. ### data-dir `(data-dir ...)` Exported function in `/os/well-known`. ### data-local-dir `(data-local-dir ...)` Exported function in `/os/well-known`. ### desktop-dir `(desktop-dir ...)` Exported function in `/os/well-known`. ### document-dir `(document-dir ...)` Exported function in `/os/well-known`. ### download-dir `(download-dir ...)` Exported function in `/os/well-known`. ### executable-dir `(executable-dir ...)` Exported function in `/os/well-known`. ### font-dir `(font-dir ...)` Exported function in `/os/well-known`. ### get-app-dirs `(get-app-dirs ...)` Exported function in `/os/well-known`. ### get-user-dirs `(get-user-dirs ...)` Exported function in `/os/well-known`. ### home-dir `(home-dir ...)` Exported function in `/os/well-known`. ### music-dir `(music-dir ...)` Exported function in `/os/well-known`. ### picture-dir `(picture-dir ...)` Exported function in `/os/well-known`. ### preference-dir `(preference-dir ...)` Exported function in `/os/well-known`. ### public-dir `(public-dir ...)` Exported function in `/os/well-known`. ### runtime-dir `(runtime-dir ...)` Exported function in `/os/well-known`. ### state-dir `(state-dir ...)` Exported function in `/os/well-known`. ### template-dir `(template-dir ...)` Exported function in `/os/well-known`. ### video-dir `(video-dir ...)` Exported function in `/os/well-known`. ## Module /process Subprocess execution (exec, spawn), environment variables (env, env-vars), working directory, and exit codes. ```tangu (use /process) ``` ### args `(process/args) -> Array` Returns the array of command-line arguments passed to the running script. ```tangu (let [file target] (process/args)) ``` ### env `(process/env) -> Map` Reads environment variables. With 0 args returns a Map of all vars; with 1 arg returns the value or (); with 2 args returns fallback when unset. ```tangu (let vars (process/env)) (let port (process/env "PORT" "8080")) ``` ### env-vars `(Func Any Any)` Exported function in `/process`. ### exec `(process/exec cmd) -> String` Executes a shell command and captures its standard output as a String. ```tangu (let out (process/exec "git rev-parse HEAD")) ``` ### exit `(Func Any Any)` Exported function in `/process`. ### exit! `(process/exit! [code]) -> Never` Immediately terminates the current process with the given integer exit code (defaults to 0). ```tangu (process/exit! 1) ``` ### expect-env-var `(name)` Returns the value of the environment variable `name`, or panics if undefined. ### get-args `(Func () Array)` Exported function in `/process`. ### get-env `(Func () Map)` Exported function in `/process`. ### has-env? `(process/has-env? name) -> Bool` Returns true if the environment variable is set in the current process. ```tangu (if (process/has-env? "DEBUG") (writeln "debugging enabled")) ``` ### pid `(process/pid) -> Int` Returns the current process identifier (PID). ```tangu (let current-pid (process/pid)) ``` ### run `(process/run cmd) -> Map` Executes a subprocess directly without invoking `sh -c`, preventing shell command injection and returning `{:status Int :stdout String :stderr String :ok Bool}`. ```tangu (let res (process/run ["git" "status" "--porcelain"])) (let res (process/run ["env"] {:clear-env true :env {:MODE "safe"}})) ``` ### set-env `(process/set-env name value) -> ()` Sets an environment variable for the current process. ```tangu (process/set-env "API_KEY" "secret") ``` ### set-env-var `(Func String String String)` Exported function in `/process`. ### shell `(process/shell cmd) -> Int` Executes a shell command streaming standard I/O to the console, returning the exit status code. ```tangu (let code (process/shell "npm test")) ``` ### unset-env `(process/unset-env name) -> ()` Unsets an environment variable from the current process. ```tangu (process/unset-env "API_KEY") ``` ## Module /runtime Multi-threaded Tokio async runtime management (Async-Runtime, run, block-on). ```tangu (use /runtime) ``` ### Async-Runtime `(Func [] AsyncRuntime)` Exported function in `/runtime`. ### Async-Runtime-construct `(Func [] AsyncRuntime)` Exported function in `/runtime`. ### block-on `(block-on ...)` Exported function in `/runtime`. ### run `(rt func)` Exported function in `/runtime`. ## Module /thread OS thread spawning, sleeping, and parallel task synchronization (spawn, sleep, await, await-all). ```tangu (use /thread) ``` ### await `(await ...)` Exported function in `/thread`. ### await-all `(await-all ...)` Exported function in `/thread`. ### sleep `(sleep ...)` Exported function in `/thread`. ### spawn `(spawn ...)` Exported function in `/thread`. ## Module /coro Lightweight cooperative coroutines (spawn, await) and multi-producer/multi-consumer channels (channel, send, recv). ```tangu (use /coro) ``` ### await `(Func [Coro-Future] Any)` Exported function in `/coro`. ### await-all `(Func Any Any)` Exported function in `/coro`. ### channel `(coro/channel) -> Channel` Creates an async FIFO communication channel. ### recv `(coro/recv channel) -> Any` Receives a message from channel, yielding execution until one is available. ### send `(coro/send channel message) -> ()` Sends a value into the channel. ### sleep `(Func Int None)` Exported function in `/coro`. ### spawn `(coro/spawn (Func [] ...)) -> Task` Spawns a non-blocking asynchronous coroutine task. ## Module /tracing Structured diagnostic logging (trace, debug, info, warn, error) with pluggable observer sinks. ```tangu (use /tracing) ``` ### Default-Tracing-Observer `(port)` Exported function in `/tracing`. ### add-tracing-observer `(observer)` Exported function in `/tracing`. ### debug `(event)` Exported function in `/tracing`. ### error `(event)` Exported function in `/tracing`. ### info `(event)` Exported function in `/tracing`. ### is-level-enabled `(level)` Exported function in `/tracing`. ### next-event `(ob level event)` Exported function in `/tracing`. ### set-tracing-level `(level)` Exported function in `/tracing`. ### start `(observers)` Exported function in `/tracing`. ### stop `(...)` Exported function in `/tracing`. ### trace `(event)` Exported function in `/tracing`. ### warn `(event)` Exported function in `/tracing`. ## Module /panic Unrecoverable developer error macros and placeholders (todo!, unimplemented!). ```tangu (use /panic) ``` ### todo! `(text)` Exported function in `/panic`. ### unimplemented! `(text)` Exported function in `/panic`. ### unreachable! `(Func [Any] Any)` Exported function in `/panic`. --- # Data, codecs & validation (`https://tangu.dev/stdlib-data/`) JSON encoding/decoding (/codec/json), URI encoding (/codec/uri), CSV tables (/csv), Base64 (/base64), and struct validation. ## Module /codec/json Fast bidirectional JSON serialization (encode, decode, from-json) and derivable To-JSON / From-JSON traits. ```tangu (use /codec/json) ``` ### From-JSON `Trait` in `/codec/json` Trait allowing structs and types to be hydrated from decoded JSON data via `(derive My-Struct From-JSON)` or custom `(impl From-JSON My-Struct ...)`. ### To-JSON `Trait` in `/codec/json` Trait allowing types and structs to override default field-by-field JSON serialization. ### decode `(json/decode json-string) -> Any` Parses a JSON text string or Slab byte buffer into native Tangu Maps, Lists, Numbers, Strings, Booleans, or `()`. When a `Target-Type` is provided as the second argument, hydrates the decoded data into the specified Struct or compound type via `From-JSON`. Returns an Error if malformed. ```tangu (use /codec/json) (let data (json/decode "{\"id\": 1, \"name\": \"Alice\"}")) (assert-eq! (data :name) "Alice") (use /codec/json) (def User (Struct #Int id #String name)) (derive User From-JSON) (let u (json/decode "{\"id\": 1, \"name\": \"Alice\"}" User)) ``` ### encode `(json/encode expr) -> String` Serializes a Tangu Map, List, Number, String, Boolean, or Struct instance into a JSON formatted string. Optional struct fields set to `()` serialize as null. ```tangu (use /codec/json) (let json-str (json/encode {:name "Bob" :scores [95 99]})) ``` ### from-json `(json/from-json Target-Type data) -> Target-Type` Hydrates a decoded JSON Map or value into an instance of `Target-Type`, recursively converting nested struct fields, arrays, and optional fields. ```tangu (use {From-JSON from-json} /codec/json) (def Product (Struct #Int id #String title)) (derive Product From-JSON) (let p (from-json Product {:id 42 :title "Book"})) ``` ## Module /codec/json-codec Bidirectional JSON codec interface for structured serialization. ```tangu (use /codec/json-codec) ``` ### From-JSON `Trait` in `/codec/json-codec` Trait allowing structs and types to be hydrated from decoded JSON data via `(derive My-Struct From-JSON)` or custom `(impl From-JSON My-Struct ...)`. ### To-JSON `Trait` in `/codec/json-codec` Trait allowing types and structs to override default field-by-field JSON serialization. ### decode `(json/decode json-string) -> Any` Parses a JSON text string or Slab byte buffer into native Tangu Maps, Lists, Numbers, Strings, Booleans, or `()`. When a `Target-Type` is provided as the second argument, hydrates the decoded data into the specified Struct or compound type via `From-JSON`. Returns an Error if malformed. ```tangu (use /codec/json) (let data (json/decode "{\"id\": 1, \"name\": \"Alice\"}")) (assert-eq! (data :name) "Alice") (use /codec/json) (def User (Struct #Int id #String name)) (derive User From-JSON) (let u (json/decode "{\"id\": 1, \"name\": \"Alice\"}" User)) ``` ### encode `(json/encode expr) -> String` Serializes a Tangu Map, List, Number, String, Boolean, or Struct instance into a JSON formatted string. Optional struct fields set to `()` serialize as null. ```tangu (use /codec/json) (let json-str (json/encode {:name "Bob" :scores [95 99]})) ``` ### from-json `(json/from-json Target-Type data) -> Target-Type` Hydrates a decoded JSON Map or value into an instance of `Target-Type`, recursively converting nested struct fields, arrays, and optional fields. ```tangu (use {From-JSON from-json} /codec/json) (def Product (Struct #Int id #String title)) (derive Product From-JSON) (let p (from-json Product {:id 42 :title "Book"})) ``` ## Module /codec/uri Percent-encoding and URL query-string serialization (encode-uri-component, decode-uri-component, to-urlencoded-string). ```tangu (use /codec/uri) ``` ### decode-uri-component `(decode-uri-component str) -> String` Decodes a percent-encoded URI component string. ### encode-uri-component `(encode-uri-component str) -> String` Percent-encodes special characters in a URI component string. ### to-urlencoded-string `(to-urlencoded-string map) -> String` Serializes a Map of key-value pairs into an `application/x-www-form-urlencoded` query string. ## Module /csv RFC 4180 CSV reader and writer supporting tuple rows and header-mapped records. ```tangu (use /csv) ``` ### read-records `(read-records ...)` Exported function in `/csv`. ### read-tuples `(read-tuples ...)` Exported function in `/csv`. ### write-tuples `(write-tuples ...)` Exported function in `/csv`. ## Module /base64 RFC 4648 Base64 encoding and decoding for strings and byte slabs. ```tangu (use /base64) ``` ### decode-base64 `(decode-base64 encoded) -> Slab` Decodes a Base64 string into a byte `Slab`. ### encode-base64 `(encode-base64 bytes) -> String` Encodes a `String` or byte `Slab` into a standard Base64 string. ## Module /validation Declarative Struct field constraint validation (#{:min-len ... :format :email ...}) returning structured ValidationErrors. ```tangu (use /validation) ``` ### Validation `Struct` in `/validation` Struct type in `/validation`. | Field | Type | Default | | :--- | :--- | :--- | | `ok` | `Bool` | `—` | | `errors` | `Map` | `—` | ### ValidationErrors `Struct` in `/validation` Struct type in `/validation`. | Field | Type | Default | | :--- | :--- | :--- | | `errors` | `Map` | `—` | ### get-cached-descriptor `(target)` Exported function in `/validation`. ### is-valid? `(target)` Returns `true` if the value conforms to the expected format or schema. ### validate `(args)` Exported function in `/validation`. ## Module /glue/date-util Business-day and calendar utilities for workdays, weekends, and nth-weekday calculations. ```tangu (use /glue/date-util) ``` ### compute-nth-weekday `(year month weekday n)` Exported function in `/glue/date-util`. ### ensure-work-day-max `(date)` Exported function in `/glue/date-util`. ### ensure-work-day-min `(date)` Exported function in `/glue/date-util`. ### is-weekend-day? `(date)` Exported function in `/glue/date-util`. ### is-work-day? `(date)` Exported function in `/glue/date-util`. ## Module /glue/fs-util High-level directory copying, path sanitization, and parent directory creation helpers. ```tangu (use /glue/fs-util) ``` ### copy-directory `(source-path target-path)` Recursively Copies a directory. The function is resilient: - ensures the target-path directory exists. ### copy-file `(source-path target-path)` Exported function in `/glue/fs-util`. ### ensure-dirname `(path)` Exported function in `/glue/fs-util`. ### sanitize-path `(path)` Exported function in `/glue/fs-util`. ## Module /glue/gen-util Code generation header and banner formatting utilities. ```tangu (use /glue/gen-util) ``` ### wrap-generated `(generated source-path)` Exported function in `/glue/gen-util`. --- # Time, date & scheduling (`https://tangu.dev/stdlib-time/`) High-precision clocks, civil dates, time zones, durations (/chrono), Gregorian calendars (/calendar/gregorian), and cron schedules (/cron). ## Module /chrono High-precision monotonic timers (Steady-Clock), civil dates (Date, Time, Date-Time), IANA time zones (Zoned-Date-Time), and durations. ```tangu (use /chrono) ``` ### != `(!= ...)` Exported function in `/chrono`. ### + `(+ ...)` Exported function in `/chrono`. ### - `(- ...)` Exported function in `/chrono`. ### < `(< ...)` Exported function in `/chrono`. ### <= `(<= ...)` Exported function in `/chrono`. ### == `(== ...)` Exported function in `/chrono`. ### > `(> ...)` Exported function in `/chrono`. ### >= `(>= ...)` Exported function in `/chrono`. ### Date `(Date ...)` Exported function in `/chrono`. ### Date-Time `(Date-Time ...)` Exported function in `/chrono`. ### Date-Time/local `(Date-Time/local ...)` Exported function in `/chrono`. ### Date-Time/utc `(Date-Time/utc ...)` Exported function in `/chrono`. ### Date/local `(Date/local ...)` Exported function in `/chrono`. ### Date/utc `(Date/utc ...)` Exported function in `/chrono`. ### Duration `(Duration ...)` Exported function in `/chrono`. ### Duration-from `(Duration-from start-instant) -> Duration` Calculates the elapsed duration since start-instant as [secs nanos]. ### Instant `(Instant) -> Instant` Captures the current high-resolution monotonic timer instant. ```tangu (let t0 (Instant)) ; work... (let elapsed (Duration-from t0)) ``` ### Local-Time `(Local-Time ...)` Exported function in `/chrono`. ### Span `(Span ...)` Exported function in `/chrono`. ### Steady-Clock/elapsed `(Steady-Clock/elapsed ...)` Exported function in `/chrono`. ### Steady-Clock/measure `(Steady-Clock/measure ...)` Exported function in `/chrono`. ### Steady-Clock/now `(Steady-Clock/now ...)` Exported function in `/chrono`. ### Steady-Instant `(Steady-Instant ...)` Exported function in `/chrono`. ### Time `(Time ...)` Exported function in `/chrono`. ### Time/local `(Time/local ...)` Exported function in `/chrono`. ### Time/utc `(Time/utc ...)` Exported function in `/chrono`. ### Zoned-Date-Time `(Zoned-Date-Time ...)` Exported function in `/chrono`. ### Zoned-Date-Time/in `(Zoned-Date-Time/in ...)` Exported function in `/chrono`. ### Zoned-Date-Time/local `(Zoned-Date-Time/local ...)` Exported function in `/chrono`. ### Zoned-Date-Time/utc `(Zoned-Date-Time/utc ...)` Exported function in `/chrono`. ### Zoned-Time `(Zoned-Time ...)` Exported function in `/chrono`. ### add-days `(add-days ...)` Exported function in `/chrono`. ### add-secs `(add-secs ...)` Exported function in `/chrono`. ### add-weeks `(add-weeks ...)` Exported function in `/chrono`. ### age `(age ...)` Exported function in `/chrono`. ### date-diff `(date-diff ...)` Exported function in `/chrono`. ### date-trunc `(date-trunc ...)` Exported function in `/chrono`. ### day-of-week `(day-of-week ...)` Exported function in `/chrono`. ### day-of-week-iso `(day-of-week-iso ...)` Exported function in `/chrono`. ### day-of-week-symbol `(day-of-week-symbol ...)` Exported function in `/chrono`. ### day-of-year `(day-of-year ...)` Exported function in `/chrono`. ### days `(days ...)` Exported function in `/chrono`. ### epoch-millis `(epoch-millis ...)` Exported function in `/chrono`. ### epoch-nanos `(epoch-nanos ...)` Exported function in `/chrono`. ### epoch-seconds `(epoch-seconds ...)` Exported function in `/chrono`. ### format-date `(format-date ...)` Exported function in `/chrono`. ### format-string `(format-string ...)` Exported function in `/chrono`. ### hours `(hours ...)` Exported function in `/chrono`. ### is-leap-year? `(is-leap-year? ...)` Exported function in `/chrono`. ### is-weekday? `(is-weekday? ...)` Exported function in `/chrono`. ### is-weekend? `(is-weekend? ...)` Exported function in `/chrono`. ### micros `(micros ...)` Exported function in `/chrono`. ### millis `(millis ...)` Exported function in `/chrono`. ### minutes `(minutes ...)` Exported function in `/chrono`. ### months `(months ...)` Exported function in `/chrono`. ### nanos `(nanos ...)` Exported function in `/chrono`. ### nanos-of `(nanos-of ...)` Exported function in `/chrono`. ### now `(chrono/now) -> String` Returns the current UTC time as an ISO-8601 formatted string. ### offset-of `(offset-of ...)` Exported function in `/chrono`. ### seconds `(seconds ...)` Exported function in `/chrono`. ### seconds-of `(seconds-of ...)` Exported function in `/chrono`. ### timestamp `(timestamp ...)` Exported function in `/chrono`. ### timestamp-of `(timestamp-of ...)` Exported function in `/chrono`. ### timezone-of `(timezone-of ...)` Exported function in `/chrono`. ### to-date `(to-date ...)` Exported function in `/chrono`. ### to-date-time `(to-date-time ...)` Exported function in `/chrono`. ### to-duration `(to-duration ...)` Exported function in `/chrono`. ### to-instant `(to-instant ...)` Exported function in `/chrono`. ### to-iso-string `(to-iso-string ...)` Exported function in `/chrono`. ### to-rfc-3339 `(to-rfc-3339 ...)` Exported function in `/chrono`. ### to-span `(to-span ...)` Exported function in `/chrono`. ### to-string `(to-string ...)` Exported function in `/chrono`. ### to-time `(to-time ...)` Exported function in `/chrono`. ### to-zoned `(to-zoned ...)` Exported function in `/chrono`. ### weekday-of `(weekday-of ...)` Exported function in `/chrono`. ### weeks `(weeks ...)` Exported function in `/chrono`. ### with-timezone `(with-timezone ...)` Exported function in `/chrono`. ### years `(years ...)` Exported function in `/chrono`. ## Module /calendar/gregorian Pure Gregorian calendar arithmetic: leap years, days in month, weekday indices, and date addition/comparison. ```tangu (use /calendar/gregorian) ``` ### add-days `(date day-offset)` Shifts a Gregorian date by whole days. ### add-months `(date month-offset)` Shifts a Gregorian date map by a whole number of months. ### add-months-to-year-month `(year month month-offset)` Shifts a year-month pair by whole months. ### compare-dates `(left right)` Compares two Gregorian dates. ### compute-weekday-index `(date)` Returns the weekday index for a Gregorian date using Sunday as zero. ### construct-date `(year month day)` Constructs a valid Gregorian date map. ### construct-today-date `(...)` Returns the current local Gregorian date. ### date-from-epoch-days `(epoch-days)` Converts an epoch day count into a Gregorian date. ### date-from-iso-text `(text)` Parses an ISO date string into a Gregorian date map. ### days-in-month `(year month)` Returns the number of days in a Gregorian month. ### epoch-days-from-date `(date)` Converts a Gregorian date into an epoch day count. ### is-leap-year? `(year)` Returns true when the year uses the Gregorian leap-year rules. ### is-same-date? `(left right)` Returns true when two Gregorian dates match exactly. ### iso-text-from-date `(date)` Formats a Gregorian date as YYYY-MM-DD. ## Module /cron Standard 5-field cron expression parsing and schedule matching (Cron, is-matching?, is-matching-now?). ```tangu (use /cron) ``` ### Cron `(Cron ...)` Exported function in `/cron`. ### is-matching-now? `(is-matching-now? ...)` Exported function in `/cron`. ### is-matching? `(is-matching? ...)` Exported function in `/cron`. ### is-valid? `(is-valid? value) -> Bool` Returns `true` if the value conforms to the expected format or schema. --- # Web, HTTP & CLI (`https://tangu.dev/stdlib-web/`) HTTP client/server (/http/*), full-stack web apps (/web/app/*), WebSockets, SHTML/CSS representation, and CLI argument parsing (/cli). ## Module /http Core HTTP method, status code, content-type, and header inspection predicates. ```tangu (use /http) ``` ### content-type-of `Constant (Any)` Constant in `/http`. ### form-of `Constant (Any)` Constant in `/http`. ### get-header `Constant (Any)` Constant in `/http`. ### header-of `Constant (Any)` Re-export case-insensitive header and URI lookup helpers ### json-of `Constant (Any)` Constant in `/http`. ### path-of `Constant (Any)` Constant in `/http`. ### query-of `Constant (Any)` Constant in `/http`. ### query-string-of `Constant (Any)` Constant in `/http`. ### is-delete? `(req)` Exported function in `/http`. ### is-get? `(req)` Request method and content inspectors ### is-head? `(req)` Exported function in `/http`. ### is-json-request? `(req)` Exported function in `/http`. ### is-options? `(req)` Exported function in `/http`. ### is-patch? `(req)` Exported function in `/http`. ### is-post? `(req)` Exported function in `/http`. ### is-put? `(req)` Exported function in `/http`. ### request `(method url headers body)` Request / Response constructors ### response `(status headers body)` Exported function in `/http`. ## Module /http/client Asynchronous & synchronous HTTP/HTTPS client with connection pooling, headers, timeouts, and streaming bodies. ```tangu (use /http/client) ``` ### Client `(Client ...)` Exported function in `/http/client`. ### content-type-of `(content-type-of req-or-resp) -> (Or String None)` Returns the `Content-Type` header of an HTTP request or response. ### delete `(delete ...)` Exported function in `/http/client`. ### get `(get ...)` Exported function in `/http/client`. ### get-text `(get-text ...)` Exported function in `/http/client`. ### head `(head ...)` Exported function in `/http/client`. ### header-of `(header-of req name) -> (Or String None)` Looks up a request or response HTTP header case-insensitively. ### options `(options ...)` Exported function in `/http/client`. ### patch `(patch ...)` Exported function in `/http/client`. ### post `(post ...)` Exported function in `/http/client`. ### put `(put ...)` Exported function in `/http/client`. ### request `(request ...)` Exported function in `/http/client`. ## Module /http/client/json Convenience helpers for sending and decoding JSON HTTP requests (post-json). ```tangu (use /http/client/json) ``` ### post-json `(client url body headers)` Exported function in `/http/client/json`. ## Module /http/server High-performance Axum/Tokio HTTP/1.1 & HTTP/2 server supporting static file serving, SSE, multipart forms, and WebSockets. ```tangu (use /http/server) ``` ### close-websocket `(close-websocket ...)` Exported function in `/http/server`. ### content-type-of `(content-type-of req-or-resp) -> (Or String None)` Returns the `Content-Type` header of an HTTP request or response. ### form-of `(form-of req) -> Map` Parses an `application/x-www-form-urlencoded` or `multipart/form-data` request body into a Map. ### handle-static `(handle-static {:dir path :fallback file?}) -> Handler` Creates an HTTP handler that serves static files from `:dir` with automatic MIME detection. ### header-of `(header-of req name) -> (Or String None)` Looks up a request or response HTTP header case-insensitively. ### json-of `(json-of req-or-resp) -> Any` Decodes a JSON HTTP request or response body into native Tangu data structures. ### path-of `(path-of req) -> String` Extracts and URL-decodes the request path from an HTTP request Map. ### query-of `(query-of req) -> Map` Parses the URL query string of an HTTP request into a key-value Map. ### query-string-of `(query-string-of req) -> String` Returns the raw query string portion of an HTTP request URI. ### read-form-urlencoded `(read-form-urlencoded ...)` Exported function in `/http/server`. ### read-multipart-form-data `(read-multipart-form-data ...)` Exported function in `/http/server`. ### receive-websocket-message `(receive-websocket-message ...)` Exported function in `/http/server`. ### send-sse-event `(send-sse-event ...)` Exported function in `/http/server`. ### send-websocket-message `(send-websocket-message ...)` Exported function in `/http/server`. ### serve `(serve ...)` Exported function in `/http/server`. ### sse-response `(sse-response ...)` Exported function in `/http/server`. ### websocket-response `(websocket-response ...)` Exported function in `/http/server`. ## Module /web/app Core full-stack web application primitives: cookies, flash messages, query/form params, responses, and URL routing. ```tangu (use /web/app) ``` ### *request* `Constant (Any)` Constant in `/web/app`. ### add-classes `Constant (Any)` Constant in `/web/app`. ### close-websocket `Constant (Any)` Constant in `/web/app`. ### content-type-of `Constant (Any)` Constant in `/web/app`. ### cookies-of `Constant (Any)` Constant in `/web/app`. ### form-of `Constant (Any)` Constant in `/web/app`. ### get-header `Constant (Any)` Direct zero-allocation native Rust header and URI lookups. ### is-delete? `Constant (Any)` Constant in `/web/app`. ### is-get? `Constant (Any)` Constant in `/web/app`. ### is-head? `Constant (Any)` Constant in `/web/app`. ### is-json-request? `Constant (Any)` Constant in `/web/app`. ### is-options? `Constant (Any)` Constant in `/web/app`. ### is-patch? `Constant (Any)` Constant in `/web/app`. ### is-post? `Constant (Any)` Constant in `/web/app`. ### is-put? `Constant (Any)` Constant in `/web/app`. ### is-safe-external-url `Constant (Any)` Constant in `/web/app`. ### json-of `Constant (Any)` Constant in `/web/app`. ### merge-attrs `Constant (Any)` Constant in `/web/app`. ### parse-component-params `Constant (Any)` Constant in `/web/app`. ### path-of `Constant (Any)` Constant in `/web/app`. ### query-of `Constant (Any)` Constant in `/web/app`. ### query-string-of `Constant (Any)` Constant in `/web/app`. ### receive-websocket-message `Constant (Any)` Constant in `/web/app`. ### safe-origin `Constant (Any)` Constant in `/web/app`. ### send-sse-event `Constant (Any)` Constant in `/web/app`. ### send-websocket-message `Constant (Any)` Constant in `/web/app`. ### sse-response `Constant (Any)` Constant in `/web/app`. ### websocket-response `Constant (Any)` Constant in `/web/app`. ### with-cookie `Constant (Any)` Constant in `/web/app`. ### Cookie `(params)` Cookie { name value path expires domain secure HttpOnly } ### attach-cookie `(resp cookie)` Adds a cookie to an existing response. ### build-query-string `(query-map)` Serializes a dictionary of query parameters into a URL query string component. Automatically sorts keys alphabetically for predictable and deterministic URLs. ### clear-flash-cookie `(resp)` Attaches a Set-Cookie header to clear the flash cookie on response. ### clear-named-routes `(...)` Clears all registered routes in the package default registry (useful for testing). ### client-ip-of `(req)` Resolves the client IP address from X-Forwarded-For, X-Real-IP, or remote-addr. ### coerce-map-to-struct `(raw-map struct-type)` Exported function in `/web/app`. ### compile-template `(path-template name)` Pre-compiles a route path template into an optimized token structure. Segments are tokenized into :literal, :param, or :wildcard. ### construct-app-config `(env-defaults-path)` Builds app config from process env vars and a fallback config data file. ### construct-app-config-from-env `(current-env env-defaults)` Builds app config by preferring env values and falling back to defaults. ### cookie->header `(cookie)` Exported function in `/web/app`. ### cookie-base64-decode `(encoded)` Restores base64 padding before decoding a cookie payload. ### cookie-base64-encode `(text)` Removes base64 padding so cookie values survive parser round-trips. ### decode-form-value `(value)` Decodes a single form-urlencoded field value. ### get-bearer-token `(req)` Exported function in `/web/app`. ### get-cookie `(req name default-val)` Exported function in `/web/app`. ### get-cookies `(req)` Exported function in `/web/app`. ### get-flash `(req)` Reads and decodes flash data from request cookies. ### get-path-param `(req name default-val)` Exported function in `/web/app`. ### get-path-param-int `(req name default-val)` Exported function in `/web/app`. ### get-query-param `(req name default-val)` Exported function in `/web/app`. ### get-query-param-bool `(req name default-val)` Exported function in `/web/app`. ### get-query-param-int `(req name default-val)` Exported function in `/web/app`. ### has-flash? `(req)` Returns true if the request contains a `_flash=` cookie header without decoding it. ### header-map `(headers)` Normalizes a map of HTTP headers so all keys are lowercase strings for O(1) lookup. ### interpolate-template `(compiled params)` Interpolates parameters into a pre-compiled route template. Consumed parameters are removed from the candidate pool; remaining parameters are appended to the URL as a query string. ### is-fetch? `(req)` Exported function in `/web/app`. ### is-safe-external-url? `(raw-url)` Validates whether a URL is a safe public target and not an internal network or cloud metadata address (SSRF guard). ### is-stage-slots-request? `(req)` Exported function in `/web/app`. ### read-body `(req)` Exported function in `/web/app`. ### read-json `(req struct-type)` Exported function in `/web/app`. ### read-json-cookie `(req cookie-name)` Reads and decodes a JSON payload stored in a cookie. ### read-query `(req struct-type)` Exported function in `/web/app`. ### redirect `(uri status-or-headers extra-headers)` Exported function in `/web/app`. ### redirect-with-flash `(url data)` Creates a redirect response with an ephemeral flash payload. ### register-named-routes `(routes-map)` Registers pre-compiled named routes into the package default registry. ### remove-cookie-header `(headers name)` Exported function in `/web/app`. ### respond-css `(css headers)` Exported function in `/web/app`. ### respond-error `(status code-or-err details-or-headers extra-headers)` Exported function in `/web/app`. ### respond-html `(html headers)` Exported function in `/web/app`. ### respond-json `(data status-or-headers extra-headers)` Exported function in `/web/app`. ### respond-method-not-allowed `(allowed req)` Exported function in `/web/app`. ### respond-no-content `(headers)` Exported function in `/web/app`. ### respond-not-found `(req)` Returns the default 404 Not Found HTML or JSON response. ### respond-stage-slots `(payload extra)` Exported function in `/web/app`. ### respond-status `(status raw-message headers)` Exported function in `/web/app`. ### respond-text `(text headers)` Exported function in `/web/app`. ### respond-xml `(xml headers)` Respond with XML content. ### router `(route-defs)` Exported function in `/web/app`. ### safe-origin? `(client-origin expected-origin)` Strictly compares a client-supplied origin against an expected origin, preventing prefix bypasses. ### safe-referer-path `(req fallback-args)` Resolves a safe redirect path from the request Referer header, falling back to a default path. Verifies the Referer is either a safe relative path or belongs to the current request host / localhost. ### safe-relative-path `(raw-path)` Validates and returns a safe relative path slice, strictly preventing path traversal attacks. Rejects leading slashes, backslashes, null bytes, and traversal segments (".." or "."). ### sanitize-return-to `(raw-return-to fallback-args)` Sanitizes a return-to parameter to prevent open redirect vulnerabilities. Returns fallback (defaulting to "/") if raw-return-to is empty, invalid, or external. ### serve `(handler options rt)` Exported function in `/web/app`. ### set-cookie-header `(headers cookie)` Exported function in `/web/app`. ### url-for `(args)` Polymorphic reverse routing constructor: - (url-for name) - (url-for name params) - (url-for req name) - (url-for req name params) - (url-for registry name params) ### url-for-with-registry `(registry name params)` Resolves a route name within an explicit named routes registry map. ### verify-webhook-signature `(req secret header-name)` Verifies an HMAC-SHA256 webhook signature header against the raw request body in constant time. ### with-header `(resp name val)` Returns a response with a single header added or updated in-place. ### with-headers `(resp extra-headers)` Returns a response with multiple headers added or updated in-place. ### with-status `(resp status)` Returns a response with the status code updated in-place. ## Module /web/app/server Opinionated HTTP server launcher reading HOST and PORT from the environment. ```tangu (use /web/app/server) ``` ### serve `(server/serve handler options) -> ()` Starts an embedded HTTP server listening on the configured host and port. ```tangu (use server /web/app/server) (server/serve (Func [req] {:status 200 :body "OK"}) {:port 8080}) ``` ## Module /web/app/handlers Composable HTTP request handlers: chain-handlers, route-map, route-fs, handle-html, handle-css, and handle-not-found. ```tangu (use /web/app/handlers) ``` ### chain-handlers `(handlers)` Composes an array of handlers, returning the first non-404 response or falling back to 404. ### handle-css `(path rest)` Serves a `.css.tan` stylesheet with in-memory caching and `?reload` / `?nocache` cache busting. ### handle-html `(path)` Exported function in `/web/app/handlers`. ### handle-not-found `(_req)` Default `404 Not Found` handler. ### route-fs `(base-path)` Exported function in `/web/app/handlers`. ### route-graph `(graph)` Exported function in `/web/app/handlers`. ### route-map `(routes)` Exported function in `/web/app/handlers`. ## Module /web/app/middleware Production HTTP middlewares: CSRF, CORS, session, ETag, rate limiting, security headers, bearer/basic auth, and scripts injection. ```tangu (use /web/app/middleware) ``` ### *scripts-accumulator* `Constant (Any)` Constant in `/web/app/middleware`. ### *scripts-seen* `Constant (Any)` Constant in `/web/app/middleware`. ### default-scripts-insertion-marker `Constant (Any)` Constant in `/web/app/middleware`. ### allow-methods-middleware `(allowed-methods next-handler)` Rejects methods outside allowlist with 405 and Allow header. ### basic-auth-middleware `(args)` Exported function in `/web/app/middleware`. ### bearer-auth-middleware `(verify-fn next-handler)` Authenticates API requests via `Authorization: Bearer `. Supports both `(bearer-auth-middleware verify-fn next-handler)` and curried `((bearer-auth-middleware verify-fn) next-handler)` forms. ### body-size-limit-middleware `(max-bytes next-handler)` Limits request payload size and returns 413 when known size exceeds max-bytes. ### cors-middleware `(args)` Exported function in `/web/app/middleware`. ### csrf-middleware `(args)` Exported function in `/web/app/middleware`. ### etag-middleware `(inner-handler)` Middleware that generates Weak ETags (W/"<16-hex-hash>") using a-hash (15+ GB/s) for GET/HEAD 200 OK responses. Returns 304 Not Modified with zero body payload when the client If-None-Match header matches. ### rate-limit-middleware `(args)` Bounded in-memory fixed-window rate limiter middleware. Supports `(rate-limit-middleware options next-handler)`, `(rate-limit-middleware next-handler)`, and curried `((rate-limit-middleware options) next-handler)`. ### request-id-middleware `(next-handler)` Ensures request-id is available in attrs and returned in response headers. ### scripts-middleware `(args)` Exported function in `/web/app/middleware`. ### security-headers-middleware `(args)` Exported function in `/web/app/middleware`. ### session-middleware `(store options)` Session middleware factory. Creates middleware that manages sessions via cookies. Parameters: store - Session store instance (from construct-session-store) options - Configuration map: :cookie-name - Cookie name (default: "SESSION-ID") :max-age - Session lifetime in seconds (default: 3600) :secure - Set Secure flag on cookie (default: false) :same-site - SameSite policy: "Strict", "Lax", or "None" (default: "Lax") :path - Cookie path (default: "/") :domain - Cookie domain (default: not set) ### static-files-middleware `(next-handler)` Exported function in `/web/app/middleware`. ### traceparent-middleware `(next-handler)` Exported function in `/web/app/middleware`. ### tracing-middleware `(next-handler)` Exported function in `/web/app/middleware`. ### use-script `(script)` Exported function in `/web/app/middleware`. ## Module /web/app/forms HTML form binding, type coercion, CSRF token fields (), and field validation error rendering (). ```tangu (use /web/app/forms) ``` ### Validation `Constant (Any)` Constant in `/web/app/forms`. ### ValidationErrors `Constant (Any)` Constant in `/web/app/forms`. ### is-valid? `Constant (Any)` Constant in `/web/app/forms`. ### validate `Constant (Any)` Constant in `/web/app/forms`. ### `(args)` Exported function in `/web/app/forms`. ### `(target field)` Exported function in `/web/app/forms`. ### coerce-field-value `(raw-value type-name constraints)` Exported function in `/web/app/forms`. ### extract-inner-type `(type-str)` Exported function in `/web/app/forms`. ### get-csrf-token `(req)` Exported function in `/web/app/forms`. ### is-maybe-type? `(type-str)` Exported function in `/web/app/forms`. ### read-form `(req struct-type)` Exported function in `/web/app/forms`. ### respond-form-errors `(args)` Exported function in `/web/app/forms`. ### validate-form `(args)` Exported function in `/web/app/forms`. ## Module /web/app/session Cookie and server-side session state management. ```tangu (use /web/app/session) ``` ### construct-session `(options)` Constructs a new session with optional initial data. Options: :data - Initial session data map (default: {}) :max-age - Session lifetime in seconds (default: 3600) ### construct-session-store `(options)` Constructs a new session store with optional configuration. Options: :cleanup-interval - Interval in seconds for expired session cleanup (default: 300) ### delete-session-value `(session key)` Deletes a value from the session data. Returns the updated session. ### get-session `(req)` Gets the session from request attributes. Returns None if no session is attached. ### get-session-value `(session key)` Gets a value from the session data. ### invalidate-session `(session)` Marks a session as invalidated (expired). The middleware will clear the session cookie and remove from store. ### set-session-value `(session key value)` Sets a value in the session data. Returns the updated session. ### store-cleanup `(store)` Exported function in `/web/app/session`. ### store-delete `(store session-id)` Deletes a session from the store. ### store-get `(store session-id)` Retrieves a session by ID from the store. Returns None if session not found or expired. ### store-put `(store session)` Stores a session in the store. ### valid-session? `(session)` Checks if a session is valid (not invalidated and not expired). ## Module /web/app/graph Filesystem-driven application route graph (App-Graph) for breadcrumbs, navigation trails, and static site crawling. ```tangu (use /web/app/graph) ``` ### App-Graph `Struct` in `/web/app/graph` Struct type in `/web/app/graph`. | Field | Type | Default | | :--- | :--- | :--- | | `spec` | `Any` | `—` | | `index` | `Any` | `—` | ### App-Node `Constant (Any)` Constant in `/web/app/graph`. ### construct-app-graph-from-fs `(params)` Construct an App-Graph from html.tan files and sidecar metadata. ### get-trail `(graph path vars)` Exported function in `/web/app/graph`. ### graph-to-assoc `(graph)` Exported function in `/web/app/graph`. ### make-app-graph `(spec)` Construct a graph from a spec tree. ## Module /web/app/graph/sitemap XML and plain-text sitemap generators and HTTP handlers constructed from an App-Graph. ```tangu (use /web/app/graph/sitemap) ``` ### construct-sitemap-url-list-handler `(graph base-url rest)` Construct a handler that serves a sitemap URL list. ### construct-sitemap-xml-handler `(graph base-url rest)` Construct a handler that serves sitemap XML. ### graph->sitemap-url-list `(graph base-url rest)` Render sitemap as a plain-text URL list. ### graph->sitemap-urls `(graph base-url rest)` Collect sitemap URLs from an App-Graph. ### graph->sitemap-xml `(graph base-url rest)` Render sitemap as XML content. ## Module /web/app/graph/openapi Automatic OpenAPI 3.1 specification generator from /web/app route graphs and Struct schemas. ```tangu (use /web/app/graph/openapi) ``` ### graph->openapi `(graph info overrides)` Construct an OpenAPI spec from an App-Graph. ### routes->openapi `(routes info)` Constructs an OpenAPI 3.0.3 specification directly from route arrays and optional Struct metadata. ### struct->openapi-schema `(struct-type)` Converts a Tangu `Struct` type into an OpenAPI 3.0 JSON Schema map. ## Module /web/push RFC 8291 Web Push payload encryption and VAPID key generation. ```tangu (use /web/push) ``` ### encrypt `(encrypt ...)` Exported function in `/web/push`. ### generate-keys `(generate-keys ...)` Exported function in `/web/push`. ## Module /websocket/client WebSocket client supporting text/binary frames, ping/pong, and clean closure. ```tangu (use /websocket/client) ``` ### close `(close handle) -> None` Closes the underlying connection, pool, file descriptor, or stream. ### connect `(connect config) -> Pool` Establishes a connection or connection pool using a URI string or configuration Map. ### receive `(receive ...)` Exported function in `/websocket/client`. ### send `(send ...)` Exported function in `/websocket/client`. ## Module /repr/html SHTML (#shtml / #html) element tree rendering, class merging, and template formatting (format-html). ```tangu (use /repr/html) ``` ### add-classes `(add-classes ...)` Exported function in `/repr/html`. ### escape-html `(escape-html ...)` Exported function in `/repr/html`. ### format-class `(format-class ...)` Exported function in `/repr/html`. ### format-html `(format-html ...)` Exported function in `/repr/html`. ### format-html-template `(format-html-template ...)` Exported function in `/repr/html`. ### merge-attrs `(merge-attrs ...)` Exported function in `/repr/html`. ### parse-component-params `(parse-component-params ...)` Exported function in `/repr/html`. ### shtml->html `(shtml->html ...)` Exported function in `/repr/html`. ## Module /repr/css CSS AST formatting and nested selector compilation (format-css, scss->css). ```tangu (use /repr/css) ``` ### format-css `(format-css ...)` Exported function in `/repr/css`. ### scss->css `(scss->css ...)` Exported function in `/repr/css`. ## Module /dialect/css-expr S-expression CSS dialect compiler lowering #css trees into standard CSS stylesheets. ```tangu (use /dialect/css-expr) ``` ### to-css `(to-css ...)` Exported function in `/dialect/css-expr`. ## Module /cli Declarative command-line argument parser supporting subcommands, flags, options, and automatic help generation. ```tangu (use /cli) ``` ### action `(args)` Declarative route DSL constructors ### cmd `(args)` Exported function in `/cli`. ### echo-help `(router-arg target-path)` Prints help information for available CLI commands. ### format-help `(router-arg target-path)` Formats help information for available CLI commands as a string. ### mount `(args)` Exported function in `/cli`. ### query `(args)` Executes a `SELECT` query (routed to read replicas when configured) and returns an Array of row Maps. ### router `(route-defs)` Constructs a CLI Router with grouped queries and actions. ### run `(cli-router args)` Resolves and executes CLI router. ### scope `(args)` Exported function in `/cli`. ## Module /ansi ANSI terminal escape sequences for styling text with foreground/background colors, bold, dim, italic, and underline. ```tangu (use /ansi) ``` ### blue `(s)` Exported function in `/ansi`. ### bold `(s)` Exported function in `/ansi`. ### green `(s)` Exported function in `/ansi`. ### italic `(s)` Exported function in `/ansi`. ### red `(s)` example: (echo "hello " (a/red "George") ", how do you feel?") ### reset `(...)` Exported function in `/ansi`. ### yellow `(s)` Exported function in `/ansi`. ## Module /color Color space conversion, hex parsing, WCAG contrast ratios, and tonal transformations (lighten, darken, saturate, mix). ```tangu (use /color) ``` ### HSL `Struct` in `/color` Cylindrical HSL color space: - h: hue angle in degrees (0.0..360.0) - s: saturation (0.0..1.0) - l: lightness (0.0..1.0) - a: alpha (0.0..1.0, default 1.0) | Field | Type | Default | | :--- | :--- | :--- | | `h` | `Float` | `—` | | `s` | `Float` | `—` | | `l` | `Float` | `—` | | `field_7` | `Any` | `—` | ### Oklch `Struct` in `/color` Perceptual Oklch color space: - l: perceived lightness (0.0..1.0) - c: chroma (0.0..~0.4) - h: hue angle in degrees (0.0..360.0) - a: alpha (0.0..1.0, default 1.0) | Field | Type | Default | | :--- | :--- | :--- | | `l` | `Float` | `—` | | `c` | `Float` | `—` | | `h` | `Float` | `—` | | `field_7` | `Any` | `—` | ### RGB `Struct` in `/color` 3-channel linear or sRGB color (0.0..1.0). Derives `Eq` and `Vec` for full Euclidean vector arithmetic (`+`, `-`, `*`, `/`, `cmul`, `lerp`, `dot`). | Field | Type | Default | | :--- | :--- | :--- | | `r` | `Float` | `—` | | `g` | `Float` | `—` | | `b` | `Float` | `—` | ### RGBA `Struct` in `/color` 4-channel sRGB color with alpha (0.0..1.0, default alpha 1.0). | Field | Type | Default | | :--- | :--- | :--- | | `r` | `Float` | `—` | | `g` | `Float` | `—` | | `b` | `Float` | `—` | | `field_7` | `Any` | `—` | ### contrast-ratio `(contrast-ratio ...)` Exported function in `/color`. ### darken `(darken ...)` Exported function in `/color`. ### desaturate `(desaturate ...)` Exported function in `/color`. ### invert `(invert ...)` Exported function in `/color`. ### lighten `(lighten ...)` Exported function in `/color`. ### linear-to-srgb `(linear-to-srgb ...)` Exported function in `/color`. ### luminance `(luminance ...)` Exported function in `/color`. ### mix `(mix ...)` Exported function in `/color`. ### parse `(parse ...)` Exported function in `/color`. ### rotate-hue `(rotate-hue ...)` Exported function in `/color`. ### saturate `(saturate ...)` Exported function in `/color`. ### srgb-to-linear `(srgb-to-linear ...)` Exported function in `/color`. ### to-css `(to-css ...)` Exported function in `/color`. ### to-hex `(to-hex ...)` Exported function in `/color`. ### to-hsl `(to-hsl ...)` Exported function in `/color`. ### to-int `(to-int ...)` Exported function in `/color`. ### to-oklch `(to-oklch ...)` Exported function in `/color`. ### to-rgb `(to-rgb ...)` Exported function in `/color`. ### to-rgba `(to-rgba ...)` Exported function in `/color`. ### to-u8 `(to-u8 ...)` Exported function in `/color`. ### with-alpha `(with-alpha ...)` Exported function in `/color`. --- # PostgreSQL & SQLite databases (`https://tangu.dev/stdlib-database/`) Connection pools, read/write replica routing, strong vs eventual consistency queries (/postgres/client), and embedded SQLite (/sqlite/client). ## Module /postgres/client Pooled PostgreSQL client supporting primary/replica cluster routing, strong vs eventual consistency queries (query, query-strong, query-one, query-one-strong), batch execution, and ACID transactions. ```tangu (use /postgres/client) ``` ### begin `(begin pool) -> Transaction` Begins a new ACID database transaction on the connection pool or primary writer. ### command `(command pool sql params?) -> Int` Executes a DDL or DML statement on the primary writer and returns the affected row count. ### connect `(connect config) -> Pool` Establishes a connection or connection pool using a URI string or configuration Map. ### exec `(exec pool sql params?) -> Int` Executes a SQL statement (`INSERT`, `UPDATE`, `DELETE`) on the primary writer and returns the number of affected rows. ### exec-batch `(exec-batch pool sql) -> None` Executes a multi-statement SQL script (such as schema migrations) in a single batch. ### get-reader `(get-reader ...)` Exported function in `/postgres/client`. ### get-writer `(get-writer ...)` Exported function in `/postgres/client`. ### is-cluster? `(is-cluster? ...)` Exported function in `/postgres/client`. ### pool-stats `(pool-stats ...)` Exported function in `/postgres/client`. ### pool-status `(pool-status ...)` Exported function in `/postgres/client`. ### query `(query pool sql params?) -> (Array Map)` Executes a `SELECT` query (routed to read replicas when configured) and returns an Array of row Maps. ### query-exists-strong? `(query-exists-strong? ...)` Exported function in `/postgres/client`. ### query-exists? `(query-exists? ...)` Exported function in `/postgres/client`. ### query-maps `(query-maps ...)` Exported function in `/postgres/client`. ### query-maps-strong `(query-maps-strong ...)` Exported function in `/postgres/client`. ### query-one `(query-one pool sql params?) -> (Or Map None)` Executes a query and returns the first matching row Map, or `()` if no rows match. ### query-one-strong `(query-one-strong pool sql params?) -> (Or Map None)` Executes a single-row query strictly on the primary writer connection (`INSERT/UPDATE ... RETURNING` or post-mutation reads). ### query-one-tuple `(query-one-tuple ...)` Exported function in `/postgres/client`. ### query-scalar `(query-scalar ...)` Exported function in `/postgres/client`. ### query-scalar-strong `(query-scalar-strong ...)` Exported function in `/postgres/client`. ### query-strong `(query-strong pool sql params?) -> (Array Map)` Executes a query strictly on the primary writer connection to guarantee read-after-write consistency (required for `INSERT/UPDATE ... RETURNING`). ### query-tuples `(query-tuples ...)` Exported function in `/postgres/client`. ### query-tuples-one `(query-tuples-one ...)` Exported function in `/postgres/client`. ### query-tuples-one-strong `(query-tuples-one-strong ...)` Exported function in `/postgres/client`. ### query-tuples-strong `(query-tuples-strong ...)` Exported function in `/postgres/client`. ## Module /sqlite/client Embedded SQLite connection pool supporting parameterized SQL queries, row maps, and transactions. ```tangu (use /sqlite/client) ``` ### begin `(sqlite/begin conn (Func [tx] ...)) -> Any` Executes closure inside a database transaction, committing on success or rolling back on Error. ### changes `(changes ...)` Exported function in `/sqlite/client`. ### command `(command pool sql params?) -> Int` Executes a DDL or DML statement on the primary writer and returns the affected row count. ### connect `(sqlite/connect path) -> Connection` Opens or creates an SQLite database connection. ```tangu (let db (sqlite/connect "app.db")) ``` ### exec `(sqlite/exec conn sql ...params) -> Int` Executes INSERT/UPDATE/DELETE statement, returning number of affected rows. ```tangu (sqlite/exec db "UPDATE users SET status = ? WHERE id = ?" "active" 10) ``` ### exec-batch `(exec-batch pool sql) -> None` Executes a multi-statement SQL script (such as schema migrations) in a single batch. ### get-reader `(get-reader ...)` Exported function in `/sqlite/client`. ### get-writer `(get-writer ...)` Exported function in `/sqlite/client`. ### is-cluster? `(is-cluster? ...)` Exported function in `/sqlite/client`. ### pool-stats `(pool-stats ...)` Exported function in `/sqlite/client`. ### pool-status `(pool-status ...)` Exported function in `/sqlite/client`. ### query `(sqlite/query conn sql ...params) -> Array` Executes SQL query and returns rows as an Array of Maps. ```tangu (let rows (sqlite/query db "SELECT id, name FROM users WHERE active = ?" 1)) ``` ### query-exists-strong? `(query-exists-strong? ...)` Exported function in `/sqlite/client`. ### query-exists? `(sqlite/query-exists? conn sql ...params) -> Bool` Executes SQL query and returns true if at least one row matches (or if a single boolean column is true), or false if empty. ```tangu (ok-or (await (sqlite/query-exists? db "SELECT 1 FROM users WHERE id = ?" id)) false) ``` ### query-maps `(query-maps ...)` Exported function in `/sqlite/client`. ### query-maps-strong `(query-maps-strong ...)` Exported function in `/sqlite/client`. ### query-one `(sqlite/query-one conn sql ...params) -> (Or Map)` Executes SQL query and returns first matching row Map, or () if empty. ### query-one-strong `(query-one-strong pool sql params?) -> (Or Map None)` Executes a single-row query strictly on the primary writer connection (`INSERT/UPDATE ... RETURNING` or post-mutation reads). ### query-one-tuple `(query-one-tuple ...)` Exported function in `/sqlite/client`. ### query-scalar `(sqlite/query-scalar conn sql ...params) -> (Or Any)` Executes SQL query and returns column 0 of the first matching row directly as a scalar, or () if empty. ```tangu (ok-or (await (sqlite/query-scalar db "SELECT COUNT(*) FROM users")) 0) ``` ### query-scalar-strong `(query-scalar-strong ...)` Exported function in `/sqlite/client`. ### query-strong `(query-strong pool sql params?) -> (Array Map)` Executes a query strictly on the primary writer connection to guarantee read-after-write consistency (required for `INSERT/UPDATE ... RETURNING`). ### query-tuples `(query-tuples ...)` Exported function in `/sqlite/client`. ### query-tuples-one `(query-tuples-one ...)` Exported function in `/sqlite/client`. ### query-tuples-one-strong `(query-tuples-one-strong ...)` Exported function in `/sqlite/client`. ### query-tuples-strong `(query-tuples-strong ...)` Exported function in `/sqlite/client`. --- # Security, hashing & cryptography (`https://tangu.dev/stdlib-security/`) SHA-256 and HMAC (/crypto), CSPRNG tokens, fast non-cryptographic hashes (/hash), JWT signing/verification (/jwt), and UUIDs (/uuid). ## Module /crypto Cryptographic hashing (sha256), HMAC authentication (hmac-sha256), CSPRNG token generation, and constant-time comparison. ```tangu (use /crypto) ``` ### hash-password `(hash-password ...)` Exported function in `/crypto`. ### hmac-sha256 `(crypto/hmac-sha256 key data) -> String` Computes HMAC-SHA256 signature using secret key and payload, returning hex string. ```tangu (crypto/hmac-sha256 "secret-key" "message") ``` ### random-bytes `(crypto/random-bytes count) -> Slab` Generates cryptographically secure random bytes as a Slab buffer. ```tangu (let key (crypto/random-bytes 32)) ``` ### random-hex `(crypto/random-hex count) -> String` Generates a cryptographically secure random hex string of 2 * count characters. ```tangu (let hex-token (crypto/random-hex 16)) ``` ### random-urlsafe `(crypto/random-urlsafe [count]) -> String` Generates a cryptographically secure URL-safe base64 string without padding. ```tangu (let token (crypto/random-urlsafe 32)) ``` ### sha256 `(crypto/sha256 data) -> String` Computes SHA-256 digest of String or Slab, returning a 64-character lowercase hexadecimal string. ```tangu (crypto/sha256 "hello world") ``` ### timing-safe-eq? `(crypto/timing-safe-eq? a b) -> Bool` Constant-time comparison between two Strings or Slabs to protect against timing attacks. ```tangu (if (crypto/timing-safe-eq? user-sig expected-sig) ...) ``` ### verify-password `(verify-password ...)` Exported function in `/crypto`. ## Module /hash Fast non-cryptographic hash algorithms: AHash, FNV-1a, SipHash-1-3, and XXHash64. ```tangu (use /hash) ``` ### a-hash `(a-hash value) -> Int` Computes a fast 64-bit AHash digest of `value`. ### fnv-1a `(fnv-1a value) -> Int` Computes a 64-bit FNV-1a non-cryptographic hash of `value`. ### sip-hash-1-3 `(sip-hash-1-3 value) -> Int` Computes a 64-bit SipHash-1-3 digest of `value`. ### xx-hash-64 `(xx-hash-64 value) -> Int` Computes a 64-bit XXHash64 digest of `value`. ## Module /jwt JSON Web Token (JWT) signing and verification using HMAC-SHA256 (HS256). ```tangu (use /jwt) ``` ### sign-jwt `(sign-jwt claims secret) -> String` Signs a claims Map as an HS256 JSON Web Token using `secret`. ### verify-jwt `(verify-jwt token secret) -> (Result Map Error)` Verifies an HS256 JSON Web Token signature and expiration, returning the decoded claims Map. ## Module /uuid RFC 9562 UUIDv4 (random) and UUIDv7 (time-ordered) generation and validation. ```tangu (use /uuid) ``` ### UUIDv4/str `(UUIDv4/str ...)` Exported function in `/uuid`. ### UUIDv7/str `(UUIDv7/str ...)` Exported function in `/uuid`. ### construct-v4-str `(construct-v4-str ...)` Exported function in `/uuid`. ### construct-v7-str `(construct-v7-str ...)` Exported function in `/uuid`. ### is-valid? `(is-valid? value) -> Bool` Returns `true` if the value conforms to the expected format or schema. ### make-v4-uuid `(make-v4-uuid ...)` Exported function in `/uuid`. --- # Mathematics, SIMD & image codecs (`https://tangu.dev/stdlib-math-media/`) Transcendental math (/math), statistics, 4x4 matrices (/mat), portable SIMD vectors (/simd), PRNGs (/rng), and AVIF/JPEG/PNG/WebP codecs. ## Module /math Mathematical constants (pi, e, phi) complementing the prelude transcendental math functions. ```tangu (use /math) ``` ### e `Constant (Any)` Euler's number e ### phi `Constant (Any)` The golden ratio φ ### pi `Constant (Any)` Archimedes' constant π ## Module /num Numeric interpolation (lerp) and rounding helpers (round-to-multiple). ```tangu (use /num) ``` ### lerp `(a b t)` Exported function in `/num`. ### round-to-multiple `(n m)` Round a number to the nearest m multiple. Extra decimals are truncated (floor behavior). ## Module /statistics Descriptive statistics: mean, median, variance, standard deviation, min/max, and linear regression. ```tangu (use /statistics) ``` ### absolute-difference `(x y)` Exported function in `/statistics`. ### compute-max `(xs)` Exported function in `/statistics`. ### compute-min `(xs)` Exported function in `/statistics`. ### compute-sum `(xs)` Exported function in `/statistics`. ### difference `(x y)` Exported function in `/statistics`. ### mean `(xs)` Exported function in `/statistics`. ### mean-absolute-deviation `(xs)` Exported function in `/statistics`. ### population-standard-deviation `(xs)` Exported function in `/statistics`. ### population-variance `(xs)` Exported function in `/statistics`. ### relative-change `(x x-ref)` Exported function in `/statistics`. ### rolling-mean `(window-size xs)` Exported function in `/statistics`. ### rolling-standard-deviation `(window-size xs)` Exported function in `/statistics`. ### sample-standard-deviation `(xs)` Exported function in `/statistics`. ### sample-standard-deviation-given-mean `(xs m)` Exported function in `/statistics`. ### sample-variance `(xs m)` Exported function in `/statistics`. ### sample-variance-given-mean `(xs m)` Exported function in `/statistics`. ### weighted-mean `(xs ws)` Compute the weighted arithmetic mean. ## Module /mat 4x4 homogeneous floating-point matrix math (Mat4) for 3D transforms, projections, rotations, and inversions. ```tangu (use /mat) ``` ### * `(a b)` Matrix multiplication (4x4 * 4x1) = 4x1 ### Mat4 `(r1 r2 r3 r4)` Exported function in `/mat`. ### Mat4-one `(angle)` Exported function in `/mat`. ### Mat4-projection `(fov aspect near far)` Exported function in `/mat`. ### Mat4-rotation-x `(angle)` Exported function in `/mat`. ### Mat4-rotation-y `(angle)` Exported function in `/mat`. ### Mat4-rotation-z `(angle)` Exported function in `/mat`. ### Mat4-translation `(tx ty tz)` Exported function in `/mat`. ### Mat4-zero `(angle)` Exported function in `/mat`. ### put `(m i j value)` Exported function in `/mat`. ## Module /simd Portable 128-bit SIMD vector types (F32x4, F64x2, I32x4, I64x2, U8x16) and lane-parallel arithmetic. ```tangu (use /simd) ``` ### F32x4 `(Func Any Any)` Exported function in `/simd`. ### F64x2 `(Func Any Any)` Exported function in `/simd`. ### I32x4 `(Func Any Any)` Exported function in `/simd`. ### I64x2 `(Func Any Any)` Exported function in `/simd`. ### U8x16 `(Func Any Any)` Exported function in `/simd`. ### abs `(Func Any Any)` Exported function in `/simd`. ### add-float-arrays `(Func Any Any)` Exported function in `/simd`. ### all-true? `(Func Any Any)` Exported function in `/simd`. ### any-true? `(Func Any Any)` Exported function in `/simd`. ### clamp `(Func Any Any)` Exported function in `/simd`. ### dot `(dot a b) -> Float` Computes the dot product of two SIMD vectors. ### dot-float-arrays `(Func Any Any)` Exported function in `/simd`. ### dot-int-arrays `(Func Any Any)` Exported function in `/simd`. ### fast-inv `(Func Any Any)` Exported function in `/simd`. ### fast-inv-sqrt `(Func Any Any)` Exported function in `/simd`. ### fma `(Func Any Any)` Exported function in `/simd`. ### lane-at `(Func Any Any)` Exported function in `/simd`. ### max `(Func Any Any)` Exported function in `/simd`. ### min `(Func Any Any)` Exported function in `/simd`. ### product `(Func Any Any)` Exported function in `/simd`. ### reduce-max `(Func Any Any)` Exported function in `/simd`. ### reduce-min `(Func Any Any)` Exported function in `/simd`. ### select `(Func Any Any)` Exported function in `/simd`. ### simd-eq `(Func Any Any)` Exported function in `/simd`. ### simd-ge `(Func Any Any)` Exported function in `/simd`. ### simd-gt `(Func Any Any)` Exported function in `/simd`. ### simd-le `(Func Any Any)` Exported function in `/simd`. ### simd-lt `(Func Any Any)` Exported function in `/simd`. ### simd-ne `(Func Any Any)` Exported function in `/simd`. ### splat `(splat val) -> Simd128` Broadcasts a scalar number into all lanes of a 128-bit SIMD vector. ```tangu (use /simd) (let v (f32x4/splat 1.0)) ``` ### sqrt `(Func Any Any)` Exported function in `/simd`. ### sum `(sum vec) -> Number` Performs horizontal sum across all lanes of a SIMD vector. ### sum-float-array `(Func Any Any)` Exported function in `/simd`. ### sum-int-array `(Func Any Any)` Exported function in `/simd`. ### swizzle `(Func Any Any)` Exported function in `/simd`. ### to-array `(Func Any Any)` Exported function in `/simd`. ### to-bitmask `(Func Any Any)` Exported function in `/simd`. ### to-float-array `(Func Any Any)` Exported function in `/simd`. ### with-lane `(Func Any Any)` Exported function in `/simd`. ### zero `(Func Any Any)` Exported function in `/simd`. ## Module /rng Pseudo-random number generation (random, random-float) for integers, floats, and ranges. ```tangu (use /rng) ``` ### random `(random ...)` Exported function in `/rng`. ### random-float `(random-float ...)` Exported function in `/rng`. ## Module /image In-memory raster image representation (Image) with format detection, cropping, and Lanczos3/bilinear resizing. ```tangu (use /image) ``` ### Image `(Image ...)` Exported function in `/image`. ### crop `(crop ...)` Exported function in `/image`. ### detect-format `(detect-format ...)` Exported function in `/image`. ### resize `(resize ...)` Exported function in `/image`. ## Module /image/avif AVIF image decoder and encoder supporting files and byte slabs. ```tangu (use /image/avif) ``` ### Coder `(Coder ...)` Exported function in `/image/avif`. ### decode-from-file `(decode-from-file ...)` Exported function in `/image/avif`. ### decode-from-slab `(decode-from-slab ...)` Exported function in `/image/avif`. ### encode-to-file `(encode-to-file ...)` Exported function in `/image/avif`. ### encode-to-slab `(encode-to-slab ...)` Exported function in `/image/avif`. ### write `(write ...)` Exported function in `/image/avif`. ## Module /image/jpeg JPEG image decoder and encoder supporting quality configuration, files, and byte slabs. ```tangu (use /image/jpeg) ``` ### Coder `(Coder ...)` Exported function in `/image/jpeg`. ### decode-from-file `(decode-from-file ...)` Exported function in `/image/jpeg`. ### decode-from-slab `(decode-from-slab ...)` Exported function in `/image/jpeg`. ### encode-to-file `(encode-to-file ...)` Exported function in `/image/jpeg`. ### encode-to-slab `(encode-to-slab ...)` Exported function in `/image/jpeg`. ### write `(write ...)` Exported function in `/image/jpeg`. ## Module /image/png Lossless PNG image decoder and encoder supporting files and byte slabs. ```tangu (use /image/png) ``` ### Coder `(Coder ...)` Exported function in `/image/png`. ### decode-from-file `(decode-from-file ...)` Exported function in `/image/png`. ### decode-from-slab `(decode-from-slab ...)` Exported function in `/image/png`. ### encode-to-file `(encode-to-file ...)` Exported function in `/image/png`. ### encode-to-slab `(encode-to-slab ...)` Exported function in `/image/png`. ### write `(write ...)` Exported function in `/image/png`. ## Module /image/webp WebP image decoder and encoder supporting files and byte slabs. ```tangu (use /image/webp) ``` ### Coder `(Coder ...)` Exported function in `/image/webp`. ### decode-from-file `(decode-from-file ...)` Exported function in `/image/webp`. ### decode-from-slab `(decode-from-slab ...)` Exported function in `/image/webp`. ### encode-to-file `(encode-to-file ...)` Exported function in `/image/webp`. ### encode-to-slab `(encode-to-slab ...)` Exported function in `/image/webp`. ### write `(write ...)` Exported function in `/image/webp`.