Skip to content

Standard Library

Buntos edited this page Dec 5, 2026 · 1 revision

Standard Library

The H standard library lives in std/ (and installs to $PREFIX/share/h/std/ via scripts/install.sh) and is written entirely in H. Because the module loader searches std/<name>.hl and $H_HOME/std/<name>.hl automatically, standard modules can be imported concisely or with explicit paths:

import math
import "std/str" as str
import json
import net
import http
import thread

For foreign runtime bridges (std/interop/druntime, std/interop/objc, std/interop/dotnet), see Foreign Interop.


Module Overview

Module Purpose
std/math C libm floating-point math plus @[nogc] integer/float helpers (pow_i64, gcd, lcm, clamp)
std/str String inspection, trimming, splitting, joining, ASCII case conversion, and integer parsing
std/path POSIX path manipulation (dirname, basename, extension, stem, join, has_ext)
std/fs Whole-file reading, writing, existence checks, and removal
std/process Process arguments (argc, argv, args), command execution, PID, and stderr logging
std/map Hash maps (StrIntMap, StrMap, StrKeyMap[V]), generic Map[K, V], Set[T], and fnv1a
std/result Generic Result[T, E] enum and combinators (is_ok, is_err, unwrap_or)
std/test Native unit-test assertion library integrated with hlc test
std/env Environment variables (get, get_or, set, unset), working directory (cwd), and args
std/time @[nogc] wall-clock and monotonic nanosecond/millisecond timers, sleep_ms, and Stopwatch
std/args Command-line flag, option, and positional argument parser (ArgParser)
std/json Recursive-descent JSON parser (JsonValue, parse) and serializer (stringify)
std/net IPv4 TCP (TcpListener, TcpStream) and UDP (UdpSocket) networking over POSIX sockets
std/http HTTP/1.1 request/response parser, response helpers, single-threaded server, and client on std/net + std/json
std/thread Boehm-GC-aware OS threads (GC_pthread_create), Mutex, CondVar, and generic Channel[T]

std/math

All functions in std/math are @[nogc] (including the extern "C" bindings to libm).

libm Bindings

  • sqrt(x: F64) -> F64
  • floor(x: F64) -> F64
  • ceil(x: F64) -> F64
  • sin(x: F64) -> F64
  • cos(x: F64) -> F64
  • pow_f64(base: F64, exp: F64) -> F64

Integer & Float Helpers (@[nogc])

  • abs_i64(x: I64) -> I64, abs_f64(x: F64) -> F64
  • min_i64(a: I64, b: I64) -> I64, min_f64(a: F64, b: F64) -> F64
  • max_i64(a: I64, b: I64) -> I64, max_f64(a: F64, b: F64) -> F64
  • clamp_i64(x: I64, lo: I64, hi: I64) -> I64, clamp_f64(x: F64, lo: F64, hi: F64) -> F64
  • pow_i64(base: I64, exp: I64) -> I64 — binary exponentiation (returns 1 for exp <= 0)
  • gcd(a: I64, b: I64) -> I64 — Euclidean greatest common divisor
  • lcm(a: I64, b: I64) -> I64 — least common multiple (0 if gcd == 0)

std/str

@[nogc] Inspection & Parsing

  • is_space(c: U8) -> Bool — matches ' ', '\t', '\n', '\r'
  • starts_with(s: String, prefix: String) -> Bool
  • ends_with(s: String, suffix: String) -> Bool
  • index_of(s: String, needle: String) -> Usize? — byte offset of first match or nil
  • contains(s: String, needle: String) -> Bool
  • parse_i64(s: String) -> I64? — parses optional leading +/- and decimal digits, returning nil on empty or invalid input

Allocating Transformations

  • trim(s: String) -> String — strips leading and trailing ASCII whitespace
  • split(s: String, sep: U8) -> Array[String] — splits on single-byte delimiter
  • join(parts: Array[String], sep: String) -> String
  • repeat(s: String, count: I64) -> String
  • to_upper(s: String) -> String — ASCII lowercase to uppercase
  • to_lower(s: String) -> String — ASCII uppercase to lowercase

std/path

POSIX / path utilities:

  • dirname(path: String) -> String — parent directory ("." if no slash, "/" for root)
  • basename(path: String) -> String — final path component
  • extension(path: String) -> String — extension including leading . (e.g. ".hl", or "" for dotfiles/no extension)
  • stem(path: String) -> String — basename without extension
  • join(a: String, b: String) -> String — joins with / without duplicating trailing slashes
  • has_ext(path: String, ext: String) -> Bool

std/fs

Wraps the runtime file I/O primitives (hl_read_file, hl_write_file, hl_remove_file):

  • read_file(path: String) -> String? — reads entire file into a GC-managed String, or nil on failure
  • write_file(path: String, content: String) -> Bool — creates or overwrites file; returns true on success
  • exists(path: String) -> Bool — returns true if path is readable
  • remove(path: String) -> Bool — deletes file; returns true on success

std/process

  • argc() -> I32 — argument count captured at startup by hl_init_args
  • argv(idx: I32) -> String — argument at idx (or "" if out of range)
  • args() -> Array[String] — all command-line arguments including argv[0]
  • run(cmd: String) -> I32 — executes command via hl_run_cmd (system), returning exit code (or 128 if signaled, -1 on error)
  • pid() -> I32 — current process ID (getpid)
  • eputs(msg: String) -> Void — writes line to stderr (fd 2)

std/map

Hash Function

  • @[nogc] fnv1a(s: String) -> U64 — 64-bit FNV-1a hash over string bytes

Open-Addressing Hash Tables

StrIntMap, StrMap, and generic StrKeyMap[V] are open-addressing hash tables backed by FNV-1a hashing, linear probing, tombstone deletion states (0 empty, 1 occupied, 2 tombstone), initial capacity 16, and automatic 2x rehashing at 70% load factor:

  • class StrIntMap — String -> I64 (new(), set(key, val), get(key) -> I64?, has(key) -> Bool, remove(key) -> Bool, len() -> Usize)
  • class StrMap — String -> String (new(), set(key, val), get(key) -> String?, has(key) -> Bool, remove(key) -> Bool, len() -> Usize)
  • class StrKeyMap[V] — String -> V (new(), set(key, val), get(key) -> V?, has(key) -> Bool, remove(key) -> Bool, len() -> Usize)

Generic Equality-Based Collections

For arbitrary ==-comparable types without requiring a hash interface:

  • class Map[K, V] — parallel-array associative map (new(), len() -> Usize, is_empty() -> Bool, set(key, val), get(key) -> V?, has(key) -> Bool, remove(key) -> Bool)
  • class Set[T] — unordered unique set with swap-remove (new(), len() -> Usize, has(val) -> Bool, add(val) -> Bool, remove(val) -> Bool)

std/result

enum Result[T, E]
  ok(T)
  err(E)
end
  • is_ok[T, E](r: Result[T, E]) -> Bool
  • is_err[T, E](r: Result[T, E]) -> Bool
  • unwrap_or[T, E](r: Result[T, E], fallback: T) -> T

Integrates directly with the postfix ? error propagation operator. See Generics and Interfaces.


std/test

Used by hlc test harnesses and user test files (*_test.hl). Tracks global check and failure counters:

  • reset_counts() -> Void, fail_count() -> I64, check_count() -> I64
  • fail(msg: String) -> Void
  • assert(cond: Bool, msg: String) -> Void
  • assert_eq[T](actual: T, expected: T, msg: String) -> Void
  • assert_neq[T](actual: T, unexpected: T, msg: String) -> Void
  • assert_eq_i64(actual: I64, expected: I64, msg: String) -> Void — prints actual/expected values on failure
  • assert_eq_str(actual: String, expected: String, msg: String) -> Void — prints actual/expected strings on failure
  • assert_eq_bool(actual: Bool, expected: Bool, msg: String) -> Void — prints actual/expected booleans on failure

std/env

POSIX environment and process directory helpers:

  • get(name: String) -> String? — wraps getenv
  • get_or(name: String, fallback: String) -> String
  • set(name: String, val: String) -> Bool — wraps setenv(..., overwrite = 1)
  • unset(name: String) -> Bool — wraps unsetenv
  • cwd() -> String — wraps getcwd using a 4096-byte scoped arena buffer
  • args() -> Array[String] — returns all command-line arguments

std/time

Wraps POSIX clock_gettime and nanosleep with a @[repr(C)] struct Timespec:

@[nogc] Clock & Sleep Functions

  • now_ns() -> I64 — CLOCK_REALTIME (clock ID 0) in nanoseconds since Unix epoch
  • now_ms() -> I64 — wall-clock milliseconds
  • monotonic_ns() -> I64 — CLOCK_MONOTONIC (clock ID 1) in nanoseconds
  • monotonic_ms() -> I64 — monotonic milliseconds
  • sleep_ms(ms: I64) -> Void — sleeps for ms milliseconds (no-op if ms <= 0)

class Stopwatch

  • Stopwatch.new() — captures monotonic_ns()
  • elapsed_ns() -> I64
  • elapsed_ms() -> I64
  • reset() -> Void

std/args

class ArgParser parses GNU-style long options (--key=val, --key val), short options (-k val), boolean flags (--flag, -f), and -- positional terminators:

  • ArgParser.new()
  • register_flag(name: String) -> Void — marks name as a boolean flag so it does not consume the following argument
  • parse(argv: Array[String], start_idx: Usize) -> Void — parses arguments starting at start_idx (typically 1 to skip argv[0])
  • has_flag(name: String) -> Bool
  • get_opt(name: String) -> String?
  • get_opt_or(name: String, fallback: String) -> String
  • Field positionals: Array[String] — remaining positional arguments (and everything after --)

std/json

Full recursive-descent JSON parser and compact serializer built on Result[T, String]:

Data Model

enum JsonValue
  jnull
  jbool(Bool)
  jnum(F64)
  jstr(String)
  jarr(Array[JsonValue])
  jobj(Array[JsonField])
end

class JsonField
  key: String
  val: JsonValue
  def initialize(@key: String, @val: JsonValue)
end

Constructors

  • j_null() -> JsonValue
  • j_bool(b: Bool) -> JsonValue
  • j_num(n: F64) -> JsonValue, j_int(n: I64) -> JsonValue
  • j_str(s: String) -> JsonValue
  • j_arr(xs: Array[JsonValue]) -> JsonValue
  • j_obj(fields: Array[JsonField]) -> JsonValue

Parsing, Serialization & Accessors

  • parse(src: String) -> Result[JsonValue, String] — parses strings (including \", \\, \/, \n, \r, \t, \b, \f, and ASCII \uXXXX escapes), numbers (integer, decimal, exponent), booleans, null, arrays, and objects; rejects trailing garbage.
  • stringify(v: JsonValue) -> String — emits compact JSON (rendering exact integer-valued F64 numbers in (-2^53, 2^53) without decimal point).
  • escape_json_str(s: String) -> String
  • Typed extractors: as_bool, as_f64, as_i64, as_str, as_arr, as_obj (all return T?).
  • Object field lookups: obj_get(v, key) -> JsonValue?, obj_get_str(v, key) -> String?, obj_get_i64(v, key) -> I64?, obj_get_bool(v, key) -> Bool?.

std/net

IPv4 TCP and UDP networking built directly on POSIX sockets (AF_INET = 2, SOCK_STREAM = 1, SOCK_DGRAM = 2, SO_REUSEADDR) with @[repr(C)] struct SockAddrIn:

Byte-Order & Address Helpers

  • @[nogc] htons_u16(port: U16) -> U16, @[nogc] ntohs_u16(nport: U16) -> U16
  • make_ipv4_addr(host: String, port: U16, out_addr: Ptr[SockAddrIn]) -> Bool

TCP

  • tcp_listen(host: String, port: U16) -> Result[TcpListener, String] — pass port 0 for an OS-assigned ephemeral port
  • tcp_connect(host: String, port: U16) -> Result[TcpStream, String]
  • class TcpListener:
    • local_port() -> U16 — queries bound port via getsockname
    • accept() -> Result[TcpStream, String]
    • close() -> Void
  • class TcpStream:
    • write_str(data: String) -> Result[Usize, String] — loops send until all bytes are written
    • read_str(max_bytes: Usize) -> Result[String, String] — reads up to max_bytes into a scoped arena and copies to String
    • close() -> Void

UDP

  • udp_bind(host: String, port: U16) -> Result[UdpSocket, String]
  • class UdpSocket:
    • local_port() -> U16
    • send_to(host: String, port: U16, data: String) -> Result[Usize, String]
    • recv(max_bytes: Usize) -> Result[String, String]
    • close() -> Void

Pair open listeners, streams, and sockets with defer conn.close().


std/http

HTTP/1.1 request/response parser, response helpers, single-threaded server, and client built directly on std/net, std/json, and std/map (demonstrated end to end in examples/http_json_api.hl).

Request & Response Types

  • class HttpRequest:
    • Fields: method: String, path: String, query: String, headers: StrMap, body: String
    • header(name: String) -> String? — case-insensitive header lookup (headers are normalized to lowercase on parse)
  • class HttpResponse:
    • Fields: status: I32, reason: String, content_type: String, body: String
  • Response builders:
    • ok_text(body: String) -> HttpResponse (200 OK, text/plain; charset=utf-8)
    • ok_json(val: JsonValue) -> HttpResponse (200 OK, application/json)
    • bad_request(msg: String = "bad request") -> HttpResponse (400 Bad Request)
    • not_found(msg: String = "not found") -> HttpResponse (404 Not Found)

Wire Framing & Parsing

  • parse_request(raw: String) -> Result[HttpRequest, String] — parses request line (METHOD /path?query HTTP/1.1), headers, and body
  • parse_response(raw: String) -> Result[HttpResponse, String] — parses status line, Content-Type, and body
  • format_response(resp: HttpResponse) -> String — formats an HTTP/1.1 response with Content-Type, Content-Length, and Connection: close
  • read_http_stream(stream: TcpStream) -> Result[String, String] — reads until \r\n\r\n and all Content-Length body bytes have arrived

Server & Client

  • http_listen(host: String = "127.0.0.1", port: U16 = 0) -> Result[HttpServer, String]
  • class HttpServer:
    • local_port() -> U16
    • serve_one(handler: Fn(HttpRequest) -> HttpResponse) -> Result[Bool, String] — accepts one connection, parses the request, invokes handler, writes the response, and closes the connection via defer
    • close() -> Void
  • http_request(host: String, port: U16, method: String, path: String, body: String = "", content_type: String = "text/plain") -> Result[HttpResponse, String]
  • http_get(host: String, port: U16, path: String) -> Result[HttpResponse, String]
  • http_post_json(host: String, port: U16, path: String, payload: JsonValue) -> Result[HttpResponse, String]

Example (examples/http_json_api.hl)

import http
import json

def handle_api(req: HttpRequest) -> HttpResponse
  if req.method == "GET" and req.path == "/health"
    return http.ok_json(json.j_obj([
      JsonField.new("status", json.j_str("ok")),
      JsonField.new("lang", json.j_str("H"))
    ]))
  end
  http.not_found("route #{req.path} not found")
end

std/thread

GC-safe multithreading and synchronization built on Boehm GC's GC_pthread_create / GC_pthread_join and POSIX pthread_mutex_t / pthread_cond_t.

How GC-Safe Thread Spawning Works

  • spawn(task: Fn() -> Void) -> Thread stores the 16-byte fat closure { fn_ptr, env_ptr } inside a GC-allocated TaskSlot (kept alive on Thread.slot_keepalive until join()) and spawns the OS thread via GC_pthread_create using a @[nogc] C-ABI trampoline (hl_thread_trampoline).
  • Because GC_pthread_create registers the new thread's stack with Boehm GC, spawned threads can freely allocate GC class objects, Arrays, and interpolated Strings and exchange them over Channel[T].

Types & Functions

  • spawn(task: Fn() -> Void) -> Thread
  • class Thread:
    • join() -> Bool — joins via GC_pthread_join (idempotent if already joined) and releases slot_keepalive
  • class Mutex (backed by 64-byte Heap.alloc[StaticArray[U64, 8]]()):
    • Mutex.new()
    • @[nogc] lock() -> Void, @[nogc] unlock() -> Void, @[nogc] destroy() -> Void
  • class CondVar (backed by 64-byte Heap.alloc[StaticArray[U64, 8]]()):
    • CondVar.new()
    • @[nogc] wait(mtx: Mutex) -> Void, @[nogc] signal() -> Void, @[nogc] broadcast() -> Void, @[nogc] destroy() -> Void
  • class Channel[T] — unbounded thread-safe MPSC/MPMC queue protected by Mutex + CondVar:
    • Channel[T].new()
    • send(val: T) -> Bool — returns false if channel is closed
    • recv() -> T? — blocks until an item arrives, returning nil once closed and drained
    • close() -> Void — marks closed and broadcasts to all waiting receivers
    • destroy() -> Void — destroys underlying CondVar and Mutex (use with defer ch.destroy())

Next: Foreign Interop

Clone this wiki locally