49 mem standard library
The mem module provides unified, explicit memory management: low-level byte operations, regional bump arenas, and fixed-capacity object pools. The arena runtime contract documents scope switching, marks, generation invalidation, and arena lifetimes.
#use mem49.1 Low-level memory utilities
| Function | Signature | Description |
|---|---|---|
mem::copy |
Addr, Addr, Int => () |
Copies bytes count from source to destination |
mem::move |
Addr, Addr, Int => () |
Copies bytes count with support for overlap |
mem::zero |
Addr, Int => () |
Fills memory range with zeros |
mem::set |
Addr, Int, Int => () |
Fills memory range with specified byte value |
mem::align_forward |
Addr, Int => Addr |
Advances address to meet alignment requirement |
mem::is_aligned |
Addr, Int => <> |
Checks whether address satisfies alignment |
mem::index_byte |
Addr, Int, Int => < Int | > |
memchr(3): offset of the first byte in [p, p + len), or <--> if absent |
49.2 Regional bump arenas
Arenas provide allocation without per-object free overhead. All allocations within an arena are freed simultaneously when the arena is reset or destroyed.
#type Arena (raw: Addr, cap: Int)
#type ArenaStats (bytes_allocated: Int, num_chunks: Int, cap: Int)
#type ArenaProvenance (arena: Addr, generation: Int, scope_depth: Int,
resets: Int, bytes_allocated: Int, num_chunks: Int)| Function | Signature | Description |
|---|---|---|
mem::arena |
Int => Arena |
Creates an arena with initial chunk capacity (bytes) |
mem::try_arena |
Int => < Arena | > |
Creates an arena or returns <--> when allocation fails |
mem::arena_default |
() => Arena |
Creates an arena with default 64 MB chunk capacity |
mem::global_arena |
() => Arena |
Returns the persistent thread-default global arena descriptor |
mem::current |
() => Addr |
Returns the active arena descriptor (global arena when no scoped arena is selected) |
mem::set_current |
Addr => Addr |
Selects an arena and returns the previously active descriptor |
mem::set_global |
() => Addr |
Selects the current thread’s global arena and returns the previous descriptor |
mem::save |
Arena => Int |
Saves an allocation mark in the given arena |
mem::restore_to |
Arena, Int => () |
Restores the arena to a mark returned by save |
mem::alloc |
Arena, Int => Addr |
Allocates uninitialized memory of given byte size |
mem::reset |
Arena => () |
Rewinds arena offset to zero, retaining chunks |
mem::release |
Arena => () |
Frees backing chunks while keeping the arena descriptor reusable |
mem::destroy |
Arena => () |
Frees all backing chunks and arena descriptor |
mem::stats |
Arena => ArenaStats |
Retrieves allocation metrics and chunk counts |
mem::provenance |
Arena => ArenaProvenance |
Retrieves generation epoch, scope depth, reset count, and allocation totals |
mem::current_provenance |
() => ArenaProvenance |
Retrieves provenance for the currently active ambient arena |
mem::owns_addr |
Arena, Addr => <> |
Returns <+> when ptr falls within the live allocated chunks of a |
mem::with |
Arena, (() => ()) => () |
Runs action with arena set as ambient allocator |
mem::with_value |
#param T: Type, Arena, (() => T) => T |
Runs an action in an arena and returns its value |
mem::escape |
(() => ()) => () |
Runs action in the global arena, restoring the prior arena afterward |
mem::escape_value |
#param T: Type, (() => T) => T |
Runs an action in the global arena and returns its value |
current and set_current are low-level controls for integrations. Prefer with, with_value, escape, and escape_value for scoped switching because they restore the previous arena when the callback returns. Marks belong to the arena passed to save and must be restored to that same arena. release drops the arena’s chunks but leaves its descriptor valid for later allocations.
#use mem
ar = mem::arena(1024)
buf = mem::alloc(ar, 256)
// ... use buf ...
mem::destroy(ar)49.3 Arena Lifetime & Escape Contract
Every Edva thread has an implicit persistent global arena (mem::global_arena!) and an ambient current arena (mem::current!). Implicit allocations (String concatenation, records, Builder, dynamic arrays, maps, boxed ramifications/enums, and closure environments) allocate in whichever arena is ambient at the allocation site.
- Scalars and bitfields (
Int,i8..u64,Float,f32,Rune,<>,(), fixed bitfields): passed and returned by value with no arena backing; safe to return across anymem::with_value,mem::reset,mem::destroy, or block restore boundary. - Records, nested containers, and boxed unions: allocated in the ambient arena at construction or growth time (array
+=doubling, map rehash). A container created in the global arena that grows while a request arenaais ambient acquires backing buffers inaunless growth runs insidemem::escape(...). - Deep string copies (
++s): always allocate a fresh{ len, data }string and byte buffer in the current ambient arena (stripping scope generation tags). To promote aStringbuilt inside a request arenaaso it survivesmem::reset(a)ormem::destroy(a), copy it insidemem::escapeormem::escape_value(e.g.mem::escape_value((!=> ++s))). - Module globals: With
--check-arena-escapes, a global assignment rejects heap-backed values from live, separately managed arenas, even after switching away from the arena. Native builds reportE4012and Wasm builds trap. Allocate or copy the value on the main thread’s persistent arena before assigning it. The check covers the value and its backing storage. References inside records, collections, and captures still need explicit lifetime management. - Closures & asynchronous callbacks:
- Synchronous callbacks invoked strictly before the request arena resets may run inside
mem::with(req, ...)and capture request-scoped values freely. - Deferred / asynchronous callbacks stored beyond
mem::reset(req)ormem::destroy(req)must allocate both the closure environment and any captured strings/records in the persistent arena (construct or promote the callback and its captured values insidemem::escape). - Capturing closures passed to
mem::with/mem::with_valueallocate their capture environment in the caller’s active arena before switching arenas, so unbounded request loops should pass non-capturing closures or bracket each iteration withmem::set_current(ormem::saveandmem::restore_toon the outer arena).
- Synchronous callbacks invoked strictly before the request arena resets may run inside
- Frame-bound views & block-scoped addresses (unsafe boundaries):
- Typed memory views (
@[ptr RecordType]) borrow external/frame storage without copying. The compiler statically rejects returning a view directly, wrapped in a composite/variant/map, captured in a closure, written to a global, or stored through a field/index write (E3150). - Taking
&builder/&localinside an implicit top-level arena-restore block produces a block-scopedAddr. The compiler statically rejects returning it or any composite/closure holding it (E3133), as well as writing it or any composite/closure containing it to an outer variable, member, or element (E3134). - Runtime scope tags validate mortal
Stringreads (E4010) and block-scopedAddrdereferences (E4011) across implicit save/restore scopes. Explicitmem::save,mem::restore_to,mem::reset, andmem::destroybump the arena reset count and generation epoch (mem::provenance), and ownership can be queried in tests or debug builds viamem::owns_addr.
- Typed memory views (
#use mem
req = mem::arena(4096)
retained: String{}
mem::with(req, !=>
tmp = "req_" + "ok"
safe = mem::escape_value((!=> ++tmp))
mem::escape((!=> retained += safe))
)
mem::reset(req)
prov = mem::provenance(req)
// prov.resets == 1, prov.bytes_allocated == 0
mem::destroy(req)49.3.1 Thread & Task Arena Ownership
Concurrent execution with task::spawn and task::join enforces strict per-thread arena isolation:
- Thread-default base arenas: On the main thread,
@global_arenaserves as the persistent fallback base arena. Eachtask::spawnworker receives its own heap-allocated childArena, installed as both its ambient arena (@dva_arena_tls) and its thread-local base arena (@dva_arena_base_tls). mem::escape&mem::global_arena!inside tasks: Callingmem::global_arena!,mem::escape,mem::escape_value, ormem::set_global!inside a worker resolves to that worker thread’s own base arena (@dva_arena_base_tls), never the main thread’s@global_arena. Scopedmem::with(req, ...)paired withmem::escape(...)inside parallel workers therefore runs lock-free without data races.- Handoff & adoption on
task::join:task::spawndeep-copies arguments and captured closure environments into the worker’s child arena before launching the thread.task::joinwaits on the worker (pthread_join), deep-copies the returned value (orError) into the joining thread’s ambient arena, adopts any surviving chunks from the worker’s base arena viadva_arena_adopt, and frees the worker’s descriptor. - Explicit handle ownership & synchronization:
ArenaandPooldescriptors contain unsynchronized mutable metadata (offset,num_chunks,free_stack, generation stacks). An explicitArenaorPoolmust be owned by one thread at a time or protected with external synchronization if shared across threads.
49.4 Fixed-capacity object pools
Pools manage uniform, fixed-size element allocations with \(O(1)\) allocation and deallocation.
#type Pool (buffer: Addr, free_stack: Addr, active: Addr, state: Addr,
elem_size: Int, capacity: Int)| Function | Signature | Description |
|---|---|---|
mem::pool |
Int, Int => Pool |
Creates pool: mem::pool(elem_size, capacity) |
mem::pool_alloc |
Pool => < Addr | > |
Allocates slot: <+ Addr +> or <--> on full |
mem::pool_free |
Pool, Addr => <> |
Frees slot: <+> on success, <-> on error |
mem::pool_count |
Pool => Int |
Number of currently active allocated slots |
mem::pool_capacity |
Pool => Int |
Maximum capacity of the pool |
mem::pool_for_each |
Pool, (Addr => ()) => () |
Iterates over each active allocated slot |
mem::pool_destroy |
Pool => () |
Releases pool memory buffer |
#use mem
#use io
// Create pool with element size 16 bytes and capacity of 4 slots:
p = mem::pool(16, 4)
io::out $ mem::pool_capacity(p) // 4
io::out $ mem::pool_count(p) // 0
slot = mem::pool_alloc(p)
slot
| addr =>
@[addr] = 42
io::out $ @[addr Int]
freed = mem::pool_free(p, addr)
freed | io::out("freed") | io::out("invalid")
| io::out("pool exhausted")
mem::pool_destroy(p)