Skip to main content

Crate bstack_raii

Crate bstack_raii 

Source
Expand description

§bstack_raii

A typed, RAII-style ownership, lifetime, and on-disk-layout layer built on top of the mainline bstack alloc primitives (bstack::BStackRange, bstack::BStackSlice, bstack::BStackOwnedSlice). It decouples disk-level destruction (BStackDrop) from Rust’s process-scoped Drop, providing persistent-storage ownership with C++-style unique_ptr / shared_ptr / weak_ptr conveniences.

It is a separate crate (not a bstack feature) so that its large, not-yet-stable ABI surface never gates bstack’s ABI stability.

§Module map (bottom-up)

ModuleContents
layoutOn-disk primitives: EightCC, BlockHeader (both Pod).
referenceBStackRef: typed range wrapper + buffered OnDisk read.
teardownBStackDrop trait, AutoDrop RAII guard, dealloc_range.
handbackThe hand-back error family: ConstructError, ReplaceError, CastError, IntoLocalError + the HandBack trait.
blockBlock-type contracts: BStackCast, BStackBlock, BStackWeakable.
refcountLittle-endian atomic CAS ops over on-disk u64 counters.
bulkSequential fallbacks for BStackRaiiAllocator::alloc_many / free_many; bulk allocators override those trait methods.
cloneTryClone / TryCloneIn: fallible clone for handles that touch disk.
ownedBStackOwned + the OwnedRef without-allocator drop core.
sharedBStackRc / BStackWeak + the StrongRef / StrongWeakRef / WeakRef drop cores.
castTyped ↔ untyped handle conversion — the runtime behind bstack_cast!.
vecVecDesc-backed growable vectors reached through a fixed-size field.
[registry]Process-wide path↔FileId registry underlying Foreign<T>.
traits::foreign / compiled::foreign / io_core::foreignForeign<T> cross-file pointer, its ForeignOwned/ForeignRc/ForeignWeak handles, and the cross-file teardown/clone mechanism.
walWrite-ahead log for atomic multi-slice transactions and leak reclamation.
stdlibErgonomic handle/collection types built entirely on the above (e.g. BStackHashMap, BStackDeque, BStackCow).

§Conventions fixed by the ABI

  • All on-disk multi-byte integers (refcounts, offsets) are little-endian, matching bstack’s own on-disk format.
  • Reads are buffer-based (read_into + bytemuck::from_bytes); there is no zero-copy path without mmap.
  • The whole layer speaks std::io::Result / std::io::Error, a consequence of binding allocators to bstack::BStackOwnedSliceAllocator (which pins Error = io::Error and Allocated<'a> = BStackOwnedSlice).

§Status

Feature-complete: the runtime primitives, the procedural macros (bstack_block, bstack_enum, bstack_move, bstack_cast), and the stdlib collection suite are all implemented and exercised by the test suite. The main open gap is Foreign<T> cross-file deep-clone/teardown dispatch, which is still deferred (a Foreign field is byte-copied on clone and freed by nobody on teardown regardless of its ownership annotation) — see the Foreign type’s module docs.

Re-exports§

pub use bytemuck;

Modules§

rtti
Runtime Type Information: a persisted, self-describing schema stack for interpreting bstack_raii structures on disk with no compiled-in types. Runtime Type Information (RTTI) — a persisted, self-describing schema stack.

Macros§

bstack_cast
bstack_cast!(expr as Target) — type-checked handle conversion. The target is given explicitly (a function-like macro can’t read a let annotation) and selects the direction:
bstack_move
bstack_move!(handle) / bstack_move!(owned, allocator) — transfer every field out of a block, freeing only the parent shell.
rtti_path
Build an RTTI field path from dotted field names for get / set / swap: rtti_path!(outer.inner.leaf) expands to &["outer", "inner", "leaf"], and a single name rtti_path!(field) to &["field"]. The result is a &[&str], so it drops straight into the path argument.

Structs§

AutoDrop
A guard that runs BStackDrop::bstack_drop on its inner handle when it goes out of scope, bridging fallible on-disk teardown to Rust’s Drop.
BStack
A persistent, fsync-durable binary stack backed by a single file.
BStackBTreeMap
An owned, ordered map backed by a copy-on-write B-tree.
BStackBTreeSet
An owned ordered set of Pod + Ord keys with an embedded Bloom filter.
BStackBinaryHeap
An owned binary min-heap of (K, V) entries.
BStackBlockVec
A persistent, growable vector of owned block children.
BStackBox
An owned, single-value block wrapping a plain Pod T.
BStackCountingBloomFilter
An owned counting Bloom filter over Pod keys.
BStackDeque
An owned double-ended queue of T blocks.
BStackHashMap
An owned open-addressing hash map from a Pod key to a block value.
BStackHashSet
An owned open-addressing set of Pod keys with an embedded Bloom filter.
BStackLinkedList
An owned, doubly-linked list of T blocks.
BStackOwned
A uniquely-owned handle to a block: an ownership marker over an inner BStackDrop handle whose teardown recursively frees the block on disk.
BStackRange
A raw (offset, len) coordinate pair with no backing reference.
BStackRc
A shared, refcounted, allocator-bound handle.
BStackRef
A typed reference to a block of type T.
BStackRefVec
A persistent, growable vector of raw references to block children.
BStackSlice
A borrowed, non-owning view of a contiguous region within a BStack payload.
BStackString
A standalone owned UTF-8 string block.
BStackStrongVec
A persistent, growable vector of strong references to shared block children ((rc) / (rc, weak) blocks).
BStackVec
A persistent, growable vector of POD elements. Backs un-annotated Vec<T> (T: Pod) / String fields.
BStackWeak
A non-owning weak handle to an (rc, weak) block’s control block.
BStackWeakVec
A persistent, growable vector of weak references to (rc, weak) block children.
BTreeMapIter
A lazy in-order iterator over a BStackBTreeMap, yielding io::Result<(K, V)> in ascending key order. Created by BStackBTreeMap::iter / BStackBTreeMap::range; borrows the BStack for its lifetime and reads nodes on demand.
BTreeSetIter
A lazy in-order iterator over a BStackBTreeSet, yielding io::Result<K> in ascending order. Created by BStackBTreeSet::iter / BStackBTreeSet::range.
BlockHeader
The header prefixing every on-disk block. 16 bytes.
BloomOnDisk
The on-disk image of a BStackCountingBloomFilter: header, counter-array pointer (0 = none), counter count m, hash count k, and inserted-item count n. #[repr(C)], u64 fields only — fixed-size, non-generic.
BoxOnDisk
The on-disk image of a BStackBox<T>: the standard BlockHeader followed by the boxed value. #[repr(C, packed)] (like every generated XOnDisk) so there is no padding between the header and value — a requirement for the hand-written Pod impl and for reading the whole image back with bytemuck.
ConstructError
The error a generated new constructor returns when a fallible construction step fails after it has already consumed the caller’s owned/strong/embedded children.
DequeIter
A front-to-back iterator over a BStackDeque, yielding io::Result<T> value handles. Created by BStackDeque::iter.
DequeOnDisk
The on-disk image of a BStackDeque: the block header, a pointer to the ring data block (0 = none), its capacity in slots, and the circular head/len. #[repr(C)] with only u64 fields after the header, so it is padding-free and non-generic — the same layout for every element type.
EightCC
An 8-byte type tag stored in every BlockHeader.
Foreign
A typed cross-file pointer to a T block in another bstack file — the self-qualifying counterpart of BStackRef (an in-file offset with no file identity); see the module docs for its on-disk wire form.
ForeignHostAllocator
An allocator adapter over a live foreign host — the bridge that lets the crate’s entirely generic teardown / clone machinery (OwnedRef, StrongRef, WeakRef, dealloc_range, __bstack_drop_children, …), all written against A: BStackRaiiAllocator, run against another file without duplicating any of it. A Foreign<T> field’s teardown resolves the target file’s host through the registry, wraps it here, and runs the same T teardown it would run locally — every read/write lands in the foreign file (via stack), and every free is tagged with the foreign [FileId] so the home file’s WAL reclaims it there.
ForeignOwned
The RAII dual of BStackOwned for a target owned through a Foreign pointer. bstack_drop deep-frees the target in its own file; into_foreign relinquishes ownership to re-store it.
ForeignRc
The RAII dual of BStackRc for a strong reference held through a Foreign pointer. bstack_drop decrements the target’s strong count in its own file (freeing at zero).
ForeignWeak
The RAII dual of BStackWeak for a weak reference held through a Foreign pointer (it stores the target’s control offset). bstack_drop decrements the weak count in its own file.
FreeManyError
The error a partial free_many returns: the first underlying failure, plus every range whose free did not cleanly complete.
HashMapIter
An unordered iterator over a BStackHashMap’s live entries, yielding io::Result<(K, V)>. Created by BStackHashMap::iter; scans the buckets.
HashSetIter
An unordered iterator over a BStackHashSet’s keys, yielding io::Result<K>. Created by BStackHashSet::iter; scans the buckets.
HashSetOnDisk
The on-disk image of a BStackHashSet: header, bucket-block pointer, bucket count cap, key count len, used (occupied + tombstone), and the embedded Bloom filter’s handle offset. #[repr(C)], u64 fields only.
HeapOnDisk
The on-disk image of a BStackBinaryHeap: header, array-block pointer (0 = none), capacity in slots, and element count. Non-generic.
IntoLocalError
The error ForeignOwned::into_local / ForeignRc::into_local / ForeignWeak::into_local returns.
ListIter
A front-to-back iterator over a BStackLinkedList, yielding io::Result<T> value handles. Created by BStackLinkedList::iter; walks the next links.
ListOnDisk
The on-disk image of a BStackLinkedList: the block header followed by the head/tail node offsets (0 = empty) and the element count. #[repr(C)] with only u64 fields after a 16-byte header, so it is naturally padding-free and non-generic — the same layout for every element type.
MapOnDisk
The on-disk image of a BStackHashMap: header, bucket-block pointer (0 = none), bucket count cap, live-entry count len, and used (occupied + tombstone). #[repr(C)], only u64 fields after the header — non-generic.
NodeOnDisk
The on-disk image of one list node: the block header followed by the prev/next node offsets (0 = none) and a single u64 reference to the value block. Non-generic: the same layout for every element type.
NonNullOffset
An Offset statically guaranteed non-null — a resolved, real target address (a control-block back-pointer, a live child, a refcount counter). Carries the not-null invariant in the type, so a consumer that needs a genuine target takes a NonNullOffset and the null check happens once, at the boundary, via Offset::to_non_null — not re-checked at every deref.
OccupiedEntry
An occupied Entry.
Offset
A byte address into a bstack file’s stack — the target half of a wide pointer, and the currency of every on-disk read/write.
OwnedRef
#[bstack_owned]: an exclusively-owned child — the without-allocator drop core a generated __bstack_drop_children mints for an owned field.
ReplaceError
The error a #[bstack_mut] replace_<field> mutator returns when the swap fails partway through.
SmallStringMap
An insertion-ordered map from String keys to T, backed by a Vec of pairs. See the module docs.
StringOnDisk
The on-disk image of a BStackString: header, a pointer to the UTF-8 bytes block (0 = empty), and the byte length. #[repr(C)], u64 fields only — fixed-size and non-generic, so the handle is a normal block.
StrongRef
#[bstack_strong] on a plain (rc) T: holds just the data ref; teardown decrements the inline refcount and frees at zero.
StrongWeakRef
#[bstack_strong] on an (rc, weak) T: holds the data ref and the control ref; teardown runs the two-phase strong-then-weak release. Not Copy — one strong-count debt, paid once.
TreeOnDisk
The on-disk image of a BStackBTreeMap: header, root node pointer (0 = empty), and entry count. Non-generic.
TreeSetOnDisk
The on-disk image of a BStackBTreeSet: header, root node pointer (0 = empty), key count, and the embedded Bloom filter’s handle offset.
VacantEntry
A vacant Entry, holding the key it would insert under.
VecDesc
The inline, fixed-size descriptor of a persistent vector: the current offset and byte size of its (reallocating) data block.
WeakRef
#[bstack_weak] on an (rc, weak) T: holds only the control ref; teardown decrements ctrl.weak and frees the control block at zero. The data block is never touched. Not Copy — one weak-count debt, paid once.
WidePtr
The crate’s wide pointer (a “fat pointer”): a persisted cross-file reference, assembled from its three orthogonal components — a [FileId] (which file), a TypeId (which type, or untyped), and an Offset (where in that file).

Enums§

BStackCow
Clone-on-write ownership of a block of type T.
CastError
The error a fallible downcast (BStackCastInto::cast_into) returns. It always hands the input slice back so an ownership-carrying BStackOwnedSlice is never dropped (and thus leaked) on a failed cast — the same hand-back contract as the crate’s other consuming operations (ReplaceError / ConstructError).
Entry
A view into a single entry of a SmallStringMap, present or not — the return of SmallStringMap::entry.

Constants§

STD_WAL_ANCHOR
Anchor offset for the bstack-provided freeing allocators: the second u64 word of the user-reserved region every one of them keeps at payload offset 0 and never hands out (FirstFit reserves 16 B there, GhostTree 32 B, Slab and CheckedSlab 24 B — all ≥ 16). Payload offset 0 is left as bstack_raii’s null niche, so the anchor is the next word, [8, 16).

Traits§

BStackAllocator
A trait for types that own a BStack and manage contiguous byte regions within its payload.
BStackBlock
A typed handle over a block: a newtype around a BStackRange that knows its on-disk representation and how to be recursively freed.
BStackCast
The downcast discriminant. The returned EightCC must match the tag in a block’s crate::BlockHeader for a safe downcast to succeed.
BStackCastAs
Downcast a borrowed slice to a typed handle by checking the block tag.
BStackCastInto
Downcast an owned slice to a typed (bare) owned handle by checking the block tag. The result carries no allocator; free it with owned.bstack_drop(alloc) or wrap it via owned.auto(alloc).
BStackDrop
The safe teardown protocol for an affine (non-Copy) owning handle: consume self and free the on-disk block(s) it owns.
BStackMove
The per-block field destructure behind bstack_move!: read every field, then free only the parent shell (the children stay live on disk). Ownership is transferred out — owned children as BStackOwned, strong as BStackRc, weak as Option<BStackWeak>, refs as BStackRef, POD by value.
BStackMoveExpr
The bstack_move! entry point, dispatched on the wrapper handle type.
BStackOwnedSliceAllocator
Convenience supertrait for the common case of a BStackAllocator whose handle type is BStackOwnedSlice and whose error type is io::Error.
BStackRaiiAllocator
The allocator every bstack_raii operation is bound on: a BStackOwnedSliceAllocator the layer can soundly build owning handles on top of. It is the crate-wide allocator capability — constructors, try_clone_in, bstack_drop, and every stdlib collection require it.
BStackShared
Implemented by refcounted blocks (#[bstack_block(rc)] and #[bstack_block(rc, weak)]), i.e. any block that can be the target of a #[bstack_strong] field.
BStackWeakable
Implemented only for blocks declared #[bstack_block(rc, weak)].
HandBack
The common surface of a hand-back error: it wraps an underlying io::Error.
Pod
Marker trait for “plain old data”.
TryClone
Duplicate self, performing any fallible I/O the duplication requires, without needing an allocator.
TryCloneIn
Deep-clone a whole block into a fresh, independent BStackOwned copy, allocating the copy with the supplied allocator.
Zeroable
Trait for types that can be safely created with zeroed.

Functions§

dealloc_range⚠
Free a raw block range by reconstructing an owned slice and delegating to the allocator. The central sink the generated bstack_drop code funnels through, since ranges carry no allocator of their own — a thin public entry over the sink-aware Sink::dealloc (kept a free function because generated bstack_drop code and every collection call it by this name).
finish
Complete a crash-left transaction in the allocator’s WAL block: reclaim the slices its outcome orphaned and mark the persistent block idle. Returns the number of slices reclaimed. This is what a caller runs once after open — a completion, not a leaky recovery. Acquires the file’s WAL lock. An allocator that opts out of reclamation (wal_anchor is None) has no WAL to complete, so this is a no-op returning 0.
get_u64
Read a little-endian u64 from the first 8 bytes of buf.
wal_teardown
Tear down handle (a whole owned subtree) as one crash-atomic batch of frees, so a crash mid-teardown is completed — not leaked — by finish on the next open. This is what BStackOwned::bstack_drop runs, so every owned teardown is automatically WAL-backed when the allocator names an anchor (BStackRaiiAllocator::wal_anchor returns Some); an allocator that returns None falls straight through to a plain BStackDrop::bstack_drop and behaves exactly as before (mid-teardown crash ⇒ orphan leak).

Attribute Macros§

bstack_block
#[bstack_block] — generate the on-disk layout and typed handle machinery.
bstack_class
#[bstack_class] — a #[bstack_block] that also persists RTTI.
bstack_enum
#[bstack_enum] — a tagged-union block.

Derive Macros§

Pod
Derive the Pod trait for a struct
Zeroable
Derive the Zeroable trait for a type.