Skip to main content

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 mem

49.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 any mem::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 arena a is ambient acquires backing buffers in a unless growth runs inside mem::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 a String built inside a request arena a so it survives mem::reset(a) or mem::destroy(a), copy it inside mem::escape or mem::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 report E4012 and 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) or mem::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 inside mem::escape).
    • Capturing closures passed to mem::with / mem::with_value allocate 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 with mem::set_current (or mem::save and mem::restore_to on the outer arena).
  • 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 / &local inside an implicit top-level arena-restore block produces a block-scoped Addr. 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 String reads (E4010) and block-scoped Addr dereferences (E4011) across implicit save/restore scopes. Explicit mem::save, mem::restore_to, mem::reset, and mem::destroy bump the arena reset count and generation epoch (mem::provenance), and ownership can be queried in tests or debug builds via mem::owns_addr.
#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_arena serves as the persistent fallback base arena. Each task::spawn worker receives its own heap-allocated child Arena, 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: Calling mem::global_arena!, mem::escape, mem::escape_value, or mem::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. Scoped mem::with(req, ...) paired with mem::escape(...) inside parallel workers therefore runs lock-free without data races.
  • Handoff & adoption on task::join: task::spawn deep-copies arguments and captured closure environments into the worker’s child arena before launching the thread. task::join waits on the worker (pthread_join), deep-copies the returned value (or Error) into the joining thread’s ambient arena, adopts any surviving chunks from the worker’s base arena via dva_arena_adopt, and frees the worker’s descriptor.
  • Explicit handle ownership & synchronization: Arena and Pool descriptors contain unsynchronized mutable metadata (offset, num_chunks, free_stack, generation stacks). An explicit Arena or Pool must 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)