Repository navigation
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 threadFor foreign runtime bridges (std/interop/druntime, std/interop/objc, std/interop/dotnet), see Foreign Interop.
| 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]
|
All functions in std/math are @[nogc] (including the extern "C" bindings to libm).
sqrt(x: F64) -> F64floor(x: F64) -> F64ceil(x: F64) -> F64sin(x: F64) -> F64cos(x: F64) -> F64pow_f64(base: F64, exp: F64) -> F64
-
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 (returns1forexp <= 0) -
gcd(a: I64, b: I64) -> I64— Euclidean greatest common divisor -
lcm(a: I64, b: I64) -> I64— least common multiple (0ifgcd == 0)
-
is_space(c: U8) -> Bool— matches' ','\t','\n','\r' starts_with(s: String, prefix: String) -> Boolends_with(s: String, suffix: String) -> Bool-
index_of(s: String, needle: String) -> Usize?— byte offset of first match ornil contains(s: String, needle: String) -> Bool-
parse_i64(s: String) -> I64?— parses optional leading+/-and decimal digits, returningnilon empty or invalid input
-
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) -> Stringrepeat(s: String, count: I64) -> String-
to_upper(s: String) -> String— ASCII lowercase to uppercase -
to_lower(s: String) -> String— ASCII uppercase to lowercase
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
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-managedString, ornilon failure -
write_file(path: String, content: String) -> Bool— creates or overwrites file; returnstrueon success -
exists(path: String) -> Bool— returnstrueifpathis readable -
remove(path: String) -> Bool— deletes file; returnstrueon success
-
argc() -> I32— argument count captured at startup byhl_init_args -
argv(idx: I32) -> String— argument atidx(or""if out of range) -
args() -> Array[String]— all command-line arguments includingargv[0] -
run(cmd: String) -> I32— executes command viahl_run_cmd(system), returning exit code (or128if signaled,-1on error) -
pid() -> I32— current process ID (getpid) -
eputs(msg: String) -> Void— writes line to stderr (fd 2)
-
@[nogc] fnv1a(s: String) -> U64— 64-bit FNV-1a hash over string bytes
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)
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)
enum Result[T, E]
ok(T)
err(E)
endis_ok[T, E](r: Result[T, E]) -> Boolis_err[T, E](r: Result[T, E]) -> Boolunwrap_or[T, E](r: Result[T, E], fallback: T) -> T
Integrates directly with the postfix ? error propagation operator. See Generics and Interfaces.
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) -> Voidassert(cond: Bool, msg: String) -> Voidassert_eq[T](actual: T, expected: T, msg: String) -> Voidassert_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
POSIX environment and process directory helpers:
-
get(name: String) -> String?— wrapsgetenv get_or(name: String, fallback: String) -> String-
set(name: String, val: String) -> Bool— wrapssetenv(..., overwrite = 1) -
unset(name: String) -> Bool— wrapsunsetenv -
cwd() -> String— wrapsgetcwdusing a 4096-byte scoped arena buffer -
args() -> Array[String]— returns all command-line arguments
Wraps POSIX clock_gettime and nanosleep with a @[repr(C)] struct Timespec:
-
now_ns() -> I64—CLOCK_REALTIME(clock ID0) in nanoseconds since Unix epoch -
now_ms() -> I64— wall-clock milliseconds -
monotonic_ns() -> I64—CLOCK_MONOTONIC(clock ID1) in nanoseconds -
monotonic_ms() -> I64— monotonic milliseconds -
sleep_ms(ms: I64) -> Void— sleeps formsmilliseconds (no-op ifms <= 0)
-
Stopwatch.new()— capturesmonotonic_ns() elapsed_ns() -> I64elapsed_ms() -> I64reset() -> Void
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— marksnameas a boolean flag so it does not consume the following argument -
parse(argv: Array[String], start_idx: Usize) -> Void— parses arguments starting atstart_idx(typically1to skipargv[0]) has_flag(name: String) -> Boolget_opt(name: String) -> String?get_opt_or(name: String, fallback: String) -> String- Field
positionals: Array[String]— remaining positional arguments (and everything after--)
Full recursive-descent JSON parser and compact serializer built on Result[T, String]:
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)
endj_null() -> JsonValuej_bool(b: Bool) -> JsonValue-
j_num(n: F64) -> JsonValue,j_int(n: I64) -> JsonValue j_str(s: String) -> JsonValuej_arr(xs: Array[JsonValue]) -> JsonValuej_obj(fields: Array[JsonField]) -> JsonValue
-
parse(src: String) -> Result[JsonValue, String]— parses strings (including\",\\,\/,\n,\r,\t,\b,\f, and ASCII\uXXXXescapes), numbers (integer, decimal, exponent), booleans,null, arrays, and objects; rejects trailing garbage. -
stringify(v: JsonValue) -> String— emits compact JSON (rendering exact integer-valuedF64numbers 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 returnT?). - 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?.
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:
-
@[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_listen(host: String, port: U16) -> Result[TcpListener, String]— pass port0for an OS-assigned ephemeral port tcp_connect(host: String, port: U16) -> Result[TcpStream, String]-
class TcpListener:-
local_port() -> U16— queries bound port viagetsockname accept() -> Result[TcpStream, String]close() -> Void
-
-
class TcpStream:-
write_str(data: String) -> Result[Usize, String]— loopssenduntil all bytes are written -
read_str(max_bytes: Usize) -> Result[String, String]— reads up tomax_bytesinto a scoped arena and copies toString close() -> Void
-
udp_bind(host: String, port: U16) -> Result[UdpSocket, String]-
class UdpSocket:local_port() -> U16send_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().
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).
-
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)
- Fields:
-
class HttpResponse:- Fields:
status: I32,reason: String,content_type: String,body: String
- Fields:
- 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)
-
-
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 withContent-Type,Content-Length, andConnection: close -
read_http_stream(stream: TcpStream) -> Result[String, String]— reads until\r\n\r\nand allContent-Lengthbody bytes have arrived
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, invokeshandler, writes the response, and closes the connection viadefer 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]
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")
endGC-safe multithreading and synchronization built on Boehm GC's GC_pthread_create / GC_pthread_join and POSIX pthread_mutex_t / pthread_cond_t.
-
spawn(task: Fn() -> Void) -> Threadstores the 16-byte fat closure{ fn_ptr, env_ptr }inside a GC-allocatedTaskSlot(kept alive onThread.slot_keepaliveuntiljoin()) and spawns the OS thread viaGC_pthread_createusing a@[nogc]C-ABI trampoline (hl_thread_trampoline). - Because
GC_pthread_createregisters the new thread's stack with Boehm GC, spawned threads can freely allocate GCclassobjects,Arrays, and interpolatedStrings and exchange them overChannel[T].
spawn(task: Fn() -> Void) -> Thread-
class Thread:-
join() -> Bool— joins viaGC_pthread_join(idempotent if already joined) and releasesslot_keepalive
-
-
class Mutex(backed by 64-byteHeap.alloc[StaticArray[U64, 8]]()):Mutex.new()-
@[nogc] lock() -> Void,@[nogc] unlock() -> Void,@[nogc] destroy() -> Void
-
class CondVar(backed by 64-byteHeap.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 byMutex+CondVar:Channel[T].new()-
send(val: T) -> Bool— returnsfalseif channel is closed -
recv() -> T?— blocks until an item arrives, returningnilonce closed and drained -
close() -> Void— marks closed and broadcasts to all waiting receivers -
destroy() -> Void— destroys underlyingCondVarandMutex(use withdefer ch.destroy())
Next: Foreign Interop