Skip to content

Standard Library Overview

The SafeC standard library (std/) covers core utilities, collections, allocators, networking, filesystems, DSP, debugging, and security. Each module is a .h (declarations) + .sc (implementation) pair. Include prelude.h to pull in every module at once.

c
#include "prelude.h"

int main() {
    println("Hello from SafeC stdlib!");
    return 0;
}

Module Categories

Core

ModuleHeaderDescription
memmem.hAllocation, deallocation, safe memcpy/memmove/memset/memcmp; cache-line helpers, alignment utilities
ioio.hFormatted output (stdout/stderr), stdin input, buffer formatting
strstr.hString length, comparison, copy, search, tokenisation, duplication
mathmath.hConstants (PI, E, …), float/double math, classification
threadthread.hThreads, mutexes, condition variables, read-write locks
atomicatomic.hLock-free atomic operations (C11 <stdatomic.h> wrappers)

Serialization

ModuleHeaderDescription
valueserial/value.hFormat-agnostic Value tree (Null/Bool/Int/Float/String/Array/Object)
jsonserial/json.hJSON writer + parser, exact round-trip
xmlserial/xml.hXML writer + parser (own-grammar round-trip)
htmlserial/html.hHTML fragment writer + parser (<dl>/<ul> shape)

Collections

ModuleHeaderDescription
slicecollections/slice.hBounds-checked fat pointer + generic array functions
veccollections/vec.hDynamic array with push/pop/sort/filter/map
stringcollections/string.hMutable, heap-allocated growable string (30+ methods)
stackcollections/stack.hLIFO stack backed by growable array
queuecollections/queue.hFIFO circular buffer queue
listcollections/list.hDoubly linked list
mapcollections/map.hHash map (open addressing, linear probing)
bstcollections/bst.hUnbalanced binary search tree
btreecollections/btree.hB-tree ordered map (order-4, 256-node pool)
ringbuffercollections/ringbuffer.hSPSC lock-free power-of-two ring buffer
static_collectionscollections/static_vec.hHeader-only zero-heap vec + map macros

Allocators

ModuleHeaderDescription
bumpalloc/bump.hLinear bump-pointer arena; O(1) alloc, reset-only free
slaballoc/slab.hFreelist slab for fixed-size objects; O(1) alloc/dealloc
poolalloc/pool.hFixed-block pool for mixed content; O(1) alloc/free
tlsfalloc/tlsf.hTwo-Level Segregated Fit; O(1) worst-case general heap

Synchronization

ModuleHeaderDescription
spinlocksync/spinlock.hBusy-wait mutual exclusion (__sync_lock_test_and_set)
lockfreesync/lockfree.hWait-free SPSC ring buffer with compiler barriers
channelsync/channel.hTyped (chan_send_t<T>/chan_recv_t<T>) wrappers over the language's built-in bounded blocking MPMC channel (chan_create/chan_send/chan_recv/chan_close)
mpscsync/mpsc.hSpinlock-guarded bounded MPSC ring buffer, non-blocking API
tasksync/task.hCooperative round-robin task scheduler
thread_baresync/thread_bare.hPriority-ordered freestanding threads (no OS)
bare_spawnsync/bare_spawn.scReference "Hook" backend for the spawn/join language keywords on freestanding targets

IPC

ModuleHeaderDescription
pipeipc/pipe.hAnonymous pipes (hosted) — one-way byte stream, typically parent/child after fork()
udsipc/uds.hUnix domain sockets (hosted) — named IPC between unrelated processes, non-blocking/Reactor-pairable

Real-Time Scheduler

ModuleHeaderDescription
reactorsched/reactor.hReactor — kqueue-backed I/O event loop driving TaskScheduler
io_nbsched/io_nb.hNon-blocking file/socket helpers meant to pair with the reactor

Networking

ModuleHeaderDescription
net-corenet/net_core.hPacketBuf, NetIf, byte-order utilities, IP/MAC helpers
ethernetnet/ethernet.hEthernetHdr, eth_parse, eth_build
arpnet/arp.hArpTable (16-entry FIFO), arp_build_packet, arp_parse_packet
ipv4net/ipv4.hIpv4Hdr, Internet checksum, ipv4_parse, ipv4_build
ipv6net/ipv6.hIpv6Addr/Ipv6Hdr, link-local/loopback predicates, ipv6_frame
udpnet/udp.hUdpHdr, udp_parse, udp_build, udp_frame
tcpnet/tcp.hTcpConn 10-state machine, pseudo-header checksum
dnsnet/dns.hA-record query builder + reply parser (label compression)
dhcpnet/dhcp.hDhcpClient DORA handshake

HTTP & Web

ModuleHeaderDescription
httphttp/http.hHTTP/1.1 client + server (http_serve/http_serve_threaded), request/response types
corshttp/cors.hCORS preflight detection + response headers
jwthttp/jwt.hHS256 JWT sign/verify (HMAC-SHA256)
oauth2http/oauth2.hOAuth2 client: authorization-code + refresh-token exchange (RFC 6749)
websockethttp/websocket.hWebSocket handshake + frame read/write
rpcrpc/rpc.hgRPC-inspired RPC-over-HTTP (length-prefixed framing, path-based dispatch)
server_fnrpc/server_fn.h"Write once, call from anywhere" JSON-marshaled server functions (Dioxus/Leptos-style)
reactivereactive/signal.hSignal<T> fine-grained reactive state (WASM client hydration)
wasmwasm/dom.h, wasm/hydrate.hwasm32 DOM interop + client hydration; wasm/wasm_rt.h is a freestanding malloc/free runtime (wasm32-only — never linked into the hosted stdlib archive)
scxn/a (transpiler)JSX/TSX-style HTML templating — .scx files transpile to plain SafeC before safec ever sees them

Machine Learning — see ML

GUI (std/gui/)

A retained-mode widget toolkit over a portable GuiWindow/GuiEvent API, with four backends selected by including the matching .sc file: gui_cocoa.sc (macOS, Objective-C runtime interop — fully verified on real hardware), gui_win32.sc/gui_x11.sc (Windows/X11 — written and type-checked against the real Win32/Xlib ABI shapes, unverified: no Windows/X11 host available), and gui_fb.sc (bare-metal linear framebuffer — fully verified, zero OS dependency). gui_widget.h is the widget tree (containers, button/label/checkbox/textinput/slider, a custom-widget extension API); gui_draw.h/gui_font.h handle primitives and bitmap fonts; gui_png.h/gui_svg.h are from-scratch PNG (DEFLATE) and SVG decoders/renderers.

Filesystems

ModuleHeaderDescription
blockfs/block.hBlockDevice driver interface (function pointer–based)
partitionfs/partition.hMBR partition table parser (4 primary entries)
vfsfs/vfs.hVFS with longest-prefix mount routing; VfsNode forwarding
fatfs/fat.hFAT32 read-only driver; 8.3 path walk, cluster chain
extfs/ext.hext2 read-only driver; inode walk, direct-block reads
tmpfsfs/tmpfs.hIn-memory FS; 32 inodes, 64 KiB data pool; full CRUD

DSP & Real-Time

ModuleHeaderDescription
fixeddsp/fixed.hQ8.24 fixed-point arithmetic (newtype Fixed = int)
dspdsp/dsp.hdsp_dot, dsp_scale, dsp_add, dsp_clip, dsp_peak, dsp_rms, SIMD-FMA dsp_dot_f64
complex_dspdsp/complex_dsp.hValue-type Complex/FComplex with operator overloading (+,-,*,/,abs,arg,conj)
dftdsp/dft.hDirect O(n²) DFT/IDFT, arbitrary length (float + Q8.24)
fftdsp/fft.hIn-place radix-2 Cooley-Tukey FFT/IFFT, O(n log n), power-of-two length (float + Q8.24)
convolutiondsp/convolution.hLinear convolution — direct O(len_x·len_h) (SIMD-accelerated) and FFT-based O(n log n)
windowdsp/window.hRectangular/Hann/Hamming/Blackman analysis windows
filterdsp/filter.hGeneral streaming FIR/IIR (feedforward/feedback) difference-equation filters (float + Q8.24)
biquaddsp/biquad.h2nd-order IIR sections + RBJ "Audio EQ Cookbook" designers + general bilinear transform
dctdsp/dct.hDCT-II/DCT-III (JPEG/MPEG-style discrete cosine transform), float + Q8.24
stftdsp/stft.hShort-Time Fourier Transform + inverse (windowed overlap-add) + multi-resolution STFT loss
resampledsp/resample.hUp/downsampling — nearest, linear, windowed-sinc (band-limited); float + Q8.24 nearest/linear
ztransformdsp/ztransform.hArbitrary-order bilinear (Laplace-to-Z) transform + Z-domain frequency response evaluator
combdsp/comb.hFeedforward/feedback comb filters + Karplus-Strong string synthesis (float + Q8.24)
minphasedsp/minphase.hMinimum-phase reconstruction via real cepstrum (homomorphic processing)
cqtdsp/cqt.hConstant-Q Transform (log-spaced bins, direct-correlation form)
cwtdsp/cwt.hContinuous Wavelet Transform (Morlet wavelet, time-scale scalogram)
imagingdsp/imaging.h2D convolution, 2D FFT (row-column decomposition), Gaussian/Sobel kernels
audio_bufferdsp/audio_buffer.hMulti-channel SPSC audio ring buffer (interleaved Fixed frames)
timer_wheeldsp/timer_wheel.h256-slot O(1) timer wheel; one-shot + periodic

Security & Cryptography

ModuleHeaderDescription
aescrypto/aes.hAES-128/256 ECB + CBC; full S-box + key expansion
sha256crypto/sha256.hSHA-256/224; streaming and one-shot API
rngcrypto/rng.hChaCha20 CSPRNG; rdrand//dev/urandom seeding
secure_alloccrypto/secure_alloc.hSlab allocator with zeroing-on-free
x509crypto/x509.hX.509 DER/ASN.1 parser; SAN, wildcard hostname, validity
tlscrypto/tls.hTLS 1.3 record layer; AES-CBC + PKCS#7 + nonce XOR seq

Debugging & Profiling

ModuleHeaderDescription
perfdebug/perf.hArch-dispatched cycle counter (RDTSC/cntvct_el0/CSR); ns calibration
coveragedebug/coverage.h1024-site coverage tracker; COV_SITE() macro; report()
jtagdebug/jtag.hdebug_break per arch; ARM/AArch64 semihosting; ITM ports

SIMD

ModuleHeaderDescription
simdsimd/simd.hPortable core: f32x4/i32x8/... type aliases over native vec<T,N>; load/store, splat, fma, min/max, horizontal reductions
x86_64 / aarch64 / riscv / wasm / spirv / cortex_m / cuda / rocmsimd/*.hThin per-ISA convenience layers (native-preferred-width naming, real-hardware verification notes) — same portable source underneath, no separate implementation

Hardware Abstraction Layer

ModuleHeaderDescription
gpiohal/gpio.hGpioPin: direction, read/write/toggle, pull-up/down
i2chal/i2c.hI2cBus: polling master — write/read/write_read/probe
spihal/spi.hSpiDevice: polling master — transfer/write/read, chip-select
uarthal/uart.hUart: polling serial — byte/string I/O, ready flags
timerhal/timer.hTimer: period/start/stop/read/flag
watchdoghal/watchdog.hWatchdog: enable/feed/caused_reset
cortex_mhal/cortex_m.hNVIC, SysTick, SCB (ARM Cortex-M)
aarch64hal/aarch64.hSystem registers, Generic Timer, GICv2 (ARMv8-A)
riscvhal/riscv.hCSR access, CLINT, PLIC

Interrupts & MMIO

ModuleHeaderDescription
mmiointerrupt/mmio.hMmioReg + free-function register read/write/field access
bitfieldinterrupt/bitfield.hPure bit-manipulation functions (bf_extract32, bf_insert32, ...)
isrinterrupt/isr.hSoftware ISR dispatch table (256 slots)
vector_tableinterrupt/vector_table.hHardware vector table — Cortex-M VTOR/RISC-V mtvec/AArch64 VBAR_EL1
clockinterrupt/clock.hPLL/clock-source configuration

Kernel Primitives

ModuleHeaderDescription
framekernel/frame.hBitmap physical frame allocator (4 KiB frames)
pagingkernel/paging.hPageEntry/PageTable — raw page table manipulation
mmukernel/mmu.hMmuContext — 2-level virtual memory, map/unmap/walk/TLB/activate
processkernel/process.hPCB — process control block
schedulerkernel/scheduler.hPriority round-robin scheduler over PCBs
ipckernel/ipc.hMailbox — fixed-capacity message queue
syscallkernel/syscall.hSyscall registration/dispatch table

Testing & Benchmarking

ModuleHeaderDescription
testtest/test.hTestSuite + ASSERT_* macros
benchtest/bench.hBenchSuite — wall-clock timed iteration benchmarks
fuzztest/fuzz.hFuzzTarget — lightweight in-process mutation fuzzer

Utilities

HeaderDescription
bit.hBit manipulation (C23 <stdbit.h> + popcount/clz/ctz/bswap builtins)
convert.hString ↔ number parsing (C11/C17), *ok success flag on failure
dma.hCache-coherent DMA buffer descriptors (64-byte aligned)
fmt.hSafe snprintf-based formatting into caller-supplied buffers
heap.hUnified heap: TLSF-backed static buffer (freestanding) or malloc/free/realloc (hosted)
log.hConfigurable logging, zero overhead when LOG_LEVEL is 0
panic.hOpt-in panic handler — infinite loop (freestanding) or abort() (hosted) by default
result.hExplicit Result error-propagation type (heap-allocated, mirrors ?T optional)
sys.hProcess-control constants (EXIT_SUCCESS/EXIT_FAILURE), PRNG constants
complex.hComplex numbers (C99 <complex.h>) as [real, imag] float/double pairs

C Compatibility Headers

HeaderDescription
assert.hRuntime assertions (runtime_assert, assert_true); NDEBUG support
ctype.hCharacter classification (char_is_alpha, char_is_digit, ...) and conversion
errno.hThread-local errno value and error descriptions (C11)
fenv.hFloating-point exception flags and rounding mode (C99)
locale.hLocale category constants (C11)
signal.hSignal handler installation and dispatch (C11)
time.hCalendar/wall-clock time (C11), complements sys.h's high-resolution clocks
stdckdint.hChecked integer arithmetic (C23-style ckd_add/ckd_sub/ckd_mul)
stdint.hFixed-width integer types
stddef.hsize_t, NULL, offsetof
stdbool.hBoolean constants
limits.hInteger limits
float.hFloating-point limits
inttypes.hFormat macros for fixed-width types

Generic Pattern

The standard library's own collections predate SafeC's generic-struct support (see Generics — structs and unions can be generic now) and haven't been migrated to it: they still use void* structs for the underlying data structure, with generic<T> wrapper functions for type-safe access. T is inferred from T* arguments at the call site via monomorphization. This keeps a single compiled struct per collection type rather than one per element type T — a real tradeoff independent of whether generic structs exist, not just a workaround for their absence (see Collections for the full rationale).

c
#include "collections/vec.h"

int main() {
    struct Vec v = vec_new(sizeof(int));

    // Type-erased API
    int x = 42;
    vec_push(&v, &x);

    // Generic typed wrapper — T inferred from int* argument
    vec_push_t(&v, 100);
    int* p = vec_at(&v, 0);  // returns int*

    vec_free(&v);
    return 0;
}

This void*-plus-typed-wrapper shape is the same general technique behind explicit runtime polymorphism (a struct holding void* data plus a fn field) — see Polymorphism & OOP.

Including the Standard Library

Individual modules:

c
#include "mem.h"
#include "io.h"
#include "collections/vec.h"

All modules at once:

c
#include "prelude.h"

When building with the safeguard package manager, the standard library is automatically compiled to build/deps/libsafec_std.a and linked.

When building manually, pass the std directory with -I:

bash
./build/safec myfile.sc -I /path/to/SafeC/std --emit-llvm -o myfile.ll
clang myfile.ll -o myfile

Released under the MIT License.