Expand description
SharedRegion<T> - cross-process typed arena with position-
independent OffsetPtr<T> references.
The foundational building block for cross-process pointer-bearing
data structures (BTree nodes, trie nodes, linked lists, any
pointer-graph). Pointers are OffsetPtr<T> { index: u32 } which
resolve via mmap_base + index * size_of::<T>() in any process.
§Layout
+----------------------------+
| RegionHeader (64B aligned) |
| magic, capacity |
| bump_next: AtomicU64 |
| free_head: AtomicU64 | (counter << 32 | index)
+----------------------------+
| next[capacity] | (free-list links, when slot free)
+----------------------------+
| slots[capacity] | (T payloads, size_of<T> each)
+----------------------------+Free-list links live in a separate next[capacity] array (not
union’d into T storage) because T need not be 4-byte aligned. The
cost is 4 * capacity extra bytes; the gain is layout simplicity
and zero overhead on the T storage.
§Concurrent allocation protocol
Allocate:
- Try to pop from
free_head(lock-free Treiber stack):- Load packed
(counter, index). - If
index == NIL_INDEX, free list is empty; fall through. - Read
next[index]; CASfree_headto(counter+1, next). - On success, return
OffsetPtr { index }.
- Load packed
- Bump alloc:
bump_next.fetch_add(1, AcqRel).- If the returned index >= capacity, rollback and return Full.
- Write
valueintoslots[index]; returnOffsetPtr { index }.
Free:
- Read current
(counter, head)fromfree_head. - Write
headintonext[ptr.index]. - CAS
free_headto(counter+1, ptr.index). - On CAS lose, retry from step 1.
§ABA safety
The 32-bit counter prevents ABA: every push bumps the counter, so the packed word is different even when an index repeats. 32 bits of counter span 4B operations, which is far beyond any realistic concrete race window.
§No drop semantics
T: Copy + Sized. Allocated T values are NOT dropped on free
(Copy types don’t need drop, and we can’t run drop glue on bytes
living in shared memory anyway). free returns the value as a
by-copy.
Structs§
- Offset
Ptr - Position-independent pointer to a slot in a SharedRegion. Stable
across processes because the underlying MMF is byte-identical;
adding
mmap_base + ptr.index * size_of::<T>()resolves in any process. - Region
Header - Shared
Region