Expand description
§forge-alloc
Composable memory allocator primitives. Snap together at the type level to produce application-specific allocators with zero runtime dispatch overhead, compile-time-enforced guarantees, and pay-for-what-you-use security hardening.
forge-alloc bundles the three implementation layers as modules:
- backing — Layer 1: raw memory sources —
InlineBacked,StaticBacked,HeapBytes,MmapBacked,HugePageBacked,System. - layout — Layer 2: structure over a backing —
BumpArena,Slab,SizeClassed,StackAlloc,WithFallback, and more. - hardening — Layer 3: security & observability wrappers —
Canary,PoisonOnFree,Quarantine,GuardPage,Statistics, and more.
Conformance helpers for downstream Allocator / FixedRange
implementers live in testing (re-exported from
forge-alloc-core).
The trait contracts (Allocator, Deallocator, OsBacked,
FixedRange, FreelistProtection, NonZeroLayout, and the rest)
live in the companion forge-alloc-core crate and are re-exported here,
so a single forge-alloc dependency gives you the whole surface.
§Quick start
use forge_alloc::{Allocator, BumpArena, Deallocator, InlineBacked, NonZeroLayout};
// 1 KiB stack-local bump arena.
let arena = BumpArena::new(InlineBacked::<1024>::new()).unwrap();
let layout = NonZeroLayout::from_size_align(64, 8).unwrap();
let block = arena.allocate(layout).unwrap();
assert_eq!(block.cast::<u8>().as_ptr() as usize % 8, 0);
// deallocate is a no-op for BumpArena; reclaim happens via reset(&mut self).
unsafe { arena.deallocate(block.cast(), layout) };See ARCHITECTURE.md and COMPOSITION_RECIPES.md for the design
and caller-facing composition recipes.
Modules§
- cache_
padded CachePadded<T>— target-aware cache-line alignment.- testing
- Conformance helpers for downstream impls of
FixedRangeandAllocator. - traits
- Foundation traits.
Structs§
- Alloc
Error - The
AllocErrorerror indicates an allocation failure that may be due to resource exhaustion or to something wrong when combining the given input arguments with this allocator. - Alloc
Stats - Snapshot of allocation activity. All counters are atomic; reading is
Ordering::Relaxedbecause counter values are advisory (operators read them for diagnostics, not for ordering guarantees). - Always
Fail - Policy that fails every allocation.
- Arena
Pool - A pool of recyclable
BumpArenas — hand them out withcheckout, return them withgive_back(an O(1)resetplus retain up to a cap), so in steady state the same backings are reused with nomunmap/mmap/ re-fault. The motivating use is a per-commit / per-branch workload where throwing arenas away per unit of work would dominate the cost. - Bump
Arena - Bump arena over any
FixedRangebacking. - Bump
Deallocator - ZST deallocator token tied to a
BumpArena’s borrow. - Cache
Jitter - CacheJitter wrapper.
- Cache
Padded - Wraps a value so it occupies a whole cache line, preventing the neighboring fields in a struct from being invalidated when the wrapped atomic is written by another core.
- Canary
- The Canary wrapper.
- Extendable
Slab - Growable typed slab.
- Fail
After - Policy that permits the first
successesallocations and fails every allocation thereafter. - Fail
Every Nth - Policy that fails every
period-th allocation and permits the rest. - Fail
OnSize - Policy that fails any allocation whose requested size is at least
min_fail_bytes, and permits smaller ones. - Faulty
- Fault-injection wrapper: forces allocations to fail according to a
AllocFaultPolicy. - FnHandler
- Dispatches every event to a user-supplied closure. The closure receives
the level via
event.level. - Freelist
Corruption - Returned by
FreelistProtection::verifywhen the stored MAC does not match the expected value. - Generational
Slab - Generational slab.
- Guard
Page - Guard-page wrapper.
- Handle
- Stable, non-pointer handle to a slot in a
GenerationalSlab. - Heap
Bytes - Owner of a single global-allocator block, exposed as
FixedRange. - Huge
Page Aligned - HugePageAligned wrapper.
- Huge
Page Backed - OS-mapped anonymous region backed by huge / large pages.
- Inline
Backed - Fixed-size inline storage backing.
- Locked
Mmap Backed - OS-mapped anonymous region whose pages are locked into physical RAM.
- LogHandler
- Emits one
eprintln!line per event. Suitable for development; not recommended for production hot paths (stderr writes hit a global lock in libstd). - Mmap
Backed - OS-mapped anonymous region.
- Mmap
Flags - Optional flags for
MmapBacked::with_flags. - Never
Fail - Policy that never injects a failure — every allocation proceeds to the inner allocator unchanged.
- NoProtection
- Zero-overhead default.
signreturns0;verifyalways succeeds. The optimizer reliably folds calls throughNoProtectioninto no-ops in release builds. - NodeSet
- Compact set of NUMA node IDs (up to 64 nodes). Built directly into
a Linux nodemask word at
mbindtime. Bigger systems need a dynamic representation; that’s not yet shipped. - NonZero
Layout - A
Layoutwithsize > 0and a power-of-two alignment. - Null
Handler - Discards every event. Zero-overhead substitute when monitoring is disabled in a release build.
- Numa
Local - NumaLocal wrapper.
- Poison
OnFree - Wrapper that overwrites freed memory with a poison pattern.
- Protect
Flags - Memory protection bits passed to
OsBacked::protect. - Quarantine
- Quarantine wrapper.
- Scope
- A scratch scope over a
BumpArena, created byBumpArena::scope. - Shared
Bump Arena - Atomic-cursor bump arena.
- SipHashMAC
- SipHash-1-3 keyed MAC over the
(next_idx, slot_addr)pair. - Size
Classed - SizeClassed allocator.
- Slab
- Fixed-stride typed slab.
- Slab
Owner - Owns the slab. Has exclusive
allocateaccess.Send(can be moved across threads) but!Sync(one-at-a-time access — enforced byUnsafeCellon the inner slab plus our manualSendimpl with no correspondingSyncimpl). - Slab
Remote - Remote deallocation handle.
Send + Sync— freely cloneable across threads. ImplementsDeallocatoronly; cannot allocate. - Split
Metadata - SplitMetadata wrapper.
- Stack
Alloc - LIFO-discipline allocator over a
FixedRangebacking. - Static
Backed - Borrows an external byte buffer as a
FixedRange. - Statistics
- Wrapper that records allocation activity in
AllocStats. - StdCompat
- Adapter that exposes any
crate::Allocatoras anallocator_api2::alloc::Allocator. - System
- Adapter exposing the standard
Systemallocator as anforge_alloc_core::Allocator. - Watermark
- Watermark wrapper.
- Watermark
Event - Snapshot of allocation state when a
WatermarkHandlerfires. - Watermark
Thresholds - Threshold percentages for the warn / critical levels.
- With
Fallback - Router with primary + secondary allocator.
- Zeroize
OnFree - Wrapper that volatile-zeroes freed memory.
Enums§
- Batch
Policy - How aggressively the owner drains the remote-free queue.
- Numa
Policy - NUMA placement policy. v0.1 accepts an explicit node set rather
than dispatching against the calling thread’s node — supply
current_numa_node()if you want the local-at-construction behaviour. - Watermark
Level - Severity bucket emitted to a
WatermarkHandler.
Constants§
- ADAPTIVE_
COOLDOWN_ TICKS - Number of
maybe_drainticks between adaptive step adjustments. Tuned for low overhead and quick settling on bursty workloads. - ADAPTIVE_
LEVELS - Drain-threshold levels for
BatchPolicy::Adaptive. - CACHE_
LINE - The cache-line alignment used by
CachePaddedon this target. Surfaced so dependent crates andconst _: () = assert!(...)layout pins can reference the same value the wrapper itself uses. - DEFAULT_
CLASS_ SIZES_ 8 - Default class sizes (bytes): 8, 16, 32, 64, 128, 256, 512, 1024.
- DEFAULT_
POISON - Default poison byte.
0xDEis a recognizable hex marker that’s unlikely to be a valid value for most types and easy to spot in a memory dump. - MAX_
ALIGN - Maximum supported alignment for
InlineBackedallocations.
Traits§
- Alloc
Fault Policy - Decides whether a pending allocation request should be forced to fail.
- Allocator
- The allocation contract. Returns memory satisfying a
NonZeroLayoutorAllocError. ExtendsDeallocatorso that any allocator can also reclaim what it issued. - Deallocator
- The deallocation half of an allocator. Every type that issues memory must be able to take it back at drop time.
- Fixed
Range - Address range fixed at construction.
- Freelist
Protection - Pluggable integrity policy for slab freelists.
- Generation
Int - Width of the generation counter. Public so callers can pick
u32(default — 2^32 reuses per slot before wraparound) oru64(effectively unbounded). Internal trait sealed via the empty trait pattern. - OsBacked
- Allocators backed by OS-managed virtual memory.
- Watermark
Handler - Callback handler invoked on threshold crossings and on OOM.
Functions§
- current_
numa_ node - Best-effort detect of the calling thread’s NUMA node.
- default_
huge_ page_ size - Platform-default huge page size in bytes.
- mmap_
clear_ last_ os_ error - Clear the per-thread last-error slot. Mainly useful in tests; callers
in production typically just read
mmap_last_os_errorafter a failure. - mmap_
last_ os_ error - Return the most recent failing-syscall error captured into this
module’s slot on the current thread, or
Noneif none has been recorded since thread start ormmap_clear_last_os_errorwas last called. - mmap_
record_ os_ error - Record the current platform errno / GetLastError into the per-thread
last-error slot from an external crate. Use this immediately after a
failing syscall (e.g.
mbind,madvise,pthread_*) in a crate that composes withMmapBackedso callers can read a singlemmap_last_os_errorregardless of which layer’s syscall failed. - page_
size - The OS memory page size in bytes — 4 KiB on most x86-64, 16 KiB on
Apple Silicon. Pass this where a primitive needs a page-size argument
(such as
GuardPage) rather than hard-coding a value that is wrong on 16 KiB-page platforms.
Type Aliases§
- Crypto
Slab - The
HardenedSlabsecurity stack over RAM-locked, core-dump-excluded memory, wrapped in non-elidable scrub-on-free — the recommended composition for cryptographic key material (“crypto allocator”). - Hardened
Slab - Slab with split metadata and guard pages on both regions — the recommended maximum-hardening composition for security- critical data: PHI, key material, audit logs, allocation tokens.