Expand description
§Melinoe — branded, multi-token phantom capabilities
melinoe provides zero-sized, brand-parameterised capability tokens that
encode data-access permissions and thread-synchronisation invariants in the
type system. It is a generalised evolution of the GhostCell pattern: where
GhostCell has one token per brand, Melinoe offers a family of tokens that
share a unified permit interface yet differ in cardinality and thread-safety
posture. The crate ships no allocator, arena, or GlobalAlloc—only the
compile-time machinery on which such systems can be built.
It is designed for the Mnemosyne memory ecosystem, complementing its
ZST AllocPolicy, heap branding, and Branded* evidence types with a more
expressive, multi-token proof system for cross-thread handoff, branded heap
access, and lock-free interior mutability on validated hot paths.
§The model in one paragraph
A brand_scope mints a unique ExclusiveToken<'brand>
over a fresh, invariant lifetime. MelinoeCell<'brand, T>s
created under that brand reveal their contents only to a matching
ReadPermit (&token) or WritePermit (&mut token). Because the
whole brand is policed by the borrow checker’s aliasing rules on that single
token, exclusive and shared access are mutually excluded across every cell
in the region with zero runtime cost—no flags, no atomics, no locks.
§Token families
| Token | Cardinality | Send/Sync | Role |
|---|---|---|---|
ExclusiveToken | one per brand | both | sole owner; read + write |
SharedReadToken | many (Copy) | both | fan-out read capability |
ThreadLocalToken | one per brand | neither | thread-confined owner |
SyncRegionToken | one per brand | both | thread-portable owner |
§Multi-token composition
Brands compose; melinoe exposes one primitive per axis and composes them rather than shipping arity-specific variants:
- Multi-XOR — nest
brand_scopefor several independent exclusion domains at once. Each nested scope is a fresh, non-unifiable brand, so a&mutinto one region and a&mutinto another are held simultaneously, disjointness proven at compile time. Composition gives any arity for free — nobrand_scopeN. region::WriterShard— split one brand into disjoint sub-regions for concurrent writers;SyncRegionTokenmoves a whole brand’s write capability across threads.reentrant::GuardedCell/reentrant::ReentrancyCell— gate ambient (thread-lifetime) exclusive state: one runtime check at the boundary yields a borrow-checked&mut T(or a fresh-brand token), with re-entry refused rather than aliased.atomic::BrandedAtomic— conditional atomics: plain non-atomic access under aWritePermit(proven-exclusive phase), atomic access under aReadPermit(shared phase). The capability selects the cost, so you pay for synchronization only while sharing.Relaxed,AcqRel, andSeqCstare ZST ordering policies for monomorphized atomic call sites.CellCowExt— conditionalCowat the ownership boundary:Borrowedreturns a zero-copy borrowed slice,Retainedclones exactly once, andRetainDecisioncovers data-dependent retain decisions through the same sealed policy bodies.
§Quick start
use melinoe::{brand_scope, MelinoeCell};
brand_scope(|mut token| {
let a = MelinoeCell::new(1_i32);
let b = MelinoeCell::new(2_i32);
// Exclusive write: needs `&mut token`.
*a.borrow_mut(&mut token) += 10;
// Shared reads: `&token` (or a copied `SharedReadToken`) reads any cell.
let snap = token.share();
assert_eq!(*a.borrow(snap) + *b.borrow(snap), 13);
});A borrow guard can be projected onto a component of its payload without
copying and without re-presenting the permit—the branded analogue of
Ref::map. MelinoeMut::map_split further yields
two disjoint &mut projections from a single write permit:
use melinoe::{brand_scope, MelinoeCell, MelinoeMut};
brand_scope(|mut token| {
let cell = MelinoeCell::new((0_u32, 0_u32));
// One write permit, two disjoint field writers, live at once.
let (mut a, mut b) =
MelinoeMut::map_split(cell.borrow_mut(&mut token), |t| (&mut t.0, &mut t.1));
*a = 1;
*b = 2;
drop((a, b));
assert_eq!(*cell.borrow(&token), (1, 2));
});At an ownership boundary, CellCowExt makes the retain decision explicit.
A ZST policy gives compile-time branch elimination when the decision is
static:
#[cfg(feature = "alloc")]
{
use std::borrow::Cow;
use melinoe::{brand_scope, Borrowed, CellCowExt, MelinoeCell, Retained};
brand_scope(|token| {
let cells: Vec<MelinoeCell<'_, u8>> = (0..4).map(MelinoeCell::new).collect();
assert!(matches!(cells.borrow_cow_with(&token, Borrowed), Cow::Borrowed(_)));
assert!(matches!(cells.borrow_cow_with(&token, Retained), Cow::Owned(_)));
});
}Conditional atomics use the same idea on the synchronization side: a write permit selects plain access, while a read permit selects atomic access. ZST ordering policies keep common ordering contracts at the type level:
use core::sync::atomic::AtomicU64;
use melinoe::{brand_scope, BrandedAtomic, Relaxed};
brand_scope(|mut token| {
let counter: BrandedAtomic<'_, AtomicU64> = BrandedAtomic::new(0);
counter.store_exclusive(10, &mut token);
let snap = token.share();
assert_eq!(counter.fetch_add_with(5, snap, Relaxed), 10);
assert_eq!(counter.load_with(snap, Relaxed), 15);
});With std, sync::PartitionPlan drives scoped, disjoint multithreaded
writes by fixed part count, current hardware parallelism, or fixed chunk
size. Each worker receives one WriterShard and no runtime lock protects
the write path:
#[cfg(feature = "std")]
{
use melinoe::sync::{partition_for_each_with, PartitionPlan};
use melinoe::{brand_scope, MelinoeCell};
brand_scope(|token| {
let mut cells: Vec<MelinoeCell<'_, usize>> =
(0..8).map(|_| MelinoeCell::new(0)).collect();
partition_for_each_with(&mut cells, PartitionPlan::chunk_size(2), |start, mut shard| {
for (j, slot) in shard.iter_mut().enumerate() {
*slot = start + j;
}
});
let snap = token.share();
for (index, cell) in cells.iter().enumerate() {
assert_eq!(*cell.borrow(snap), index);
}
});
}The borrow checker rejects the unsound interleavings at compile time:
use melinoe::{brand_scope, MelinoeCell};
brand_scope(|mut token| {
let cell = MelinoeCell::new(0_i32);
let w = cell.borrow_mut(&mut token); // exclusive borrow of `token`
let r = cell.borrow(&token); // ERROR: `token` already mutably borrowed
let _ = (w, r);
});Tokens of different brands never mix. A cell’s brand is inferred from use, so the first access pins it; a later access with a foreign token is rejected:
use melinoe::{brand_scope, MelinoeCell};
brand_scope(|t1| {
let cell = MelinoeCell::new(0_i32);
let _ = cell.borrow(&t1); // pins the cell's brand to `t1`'s region
brand_scope(|t2| {
let _ = cell.borrow(&t2); // ERROR: `t2`'s brand ≠ the cell's brand
});
});§Cargo features
std(default) — superset ofalloc; enablessync::scope_exclusiveand otherstd::thread::scope-based demonstrations.alloc— links thealloccrate for heap-payload examples/tests.nightly— enablesdoc_cfgfor precise feature-gated docs (requires a nightly toolchain); reserved for futuregeneric_const_exprscapability sets.
The crate is #![no_std] by default and uses no global allocator of its own.
Modules§
- atomic
BrandedAtomic— conditional atomics: plain access when exclusivity is proven, atomic access only when sharing.- cell
MelinoeCell— branded interior mutability with token-mediated access.- collections
alloc - Branded collection adapters backed by Melinoe primitives.
- reentrant
- Re-entrancy-guarded access to ambient, thread-confined exclusive state.
- region
- Region partitioning: sound, zero-cost concurrent writes over disjoint slices.
- sync
- Thread-synchronisation tokens and the cross-thread access model.
- thread_
cached - Per-thread value caching, consolidated from the duplicated
nightly-
#[thread_local]/ stable-thread_local!patterns that themis (CACHED_NODE) and mnemosyne (CACHED_CPU_ID) carried independently. - token
- The Melinoe token system: zero-sized, branded capability evidence.
Macros§
- thread_
cached - Declares a per-thread cached value with
get_or_init/set/get/clearaccessors.
Structs§
- AcqRel
- Acquire load / release store / acquire-release RMW ordering policy.
- Borrowed
alloc - Borrow the branded slice; no allocation and no element clone.
- Branded
Atomic - A branded atomic whose access cost is conditional on the capability presented: plain in the exclusive phase, atomic in the shared phase.
- Branded
Drain alloc - A draining iterator for
BrandedVec. - Branded
Vec alloc - A branded vector backed by
Vec<MelinoeCell<'brand, T>>. - Branded
VecDeque alloc - A branded double-ended queue backed by
VecDeque<MelinoeCell<'brand, T>>. - Branded
VecDeque Drain alloc - A draining iterator for
BrandedVecDeque. - Exclusive
Token - The single, un-clonable owner of a brand’s access rights.
- Executor
std - A validated, process-global parallel executor.
- Guarded
Cell - A thread-confined cell that hands out one exclusive
&mut Tat a time. - Melinoe
Cell - A cell whose interior mutability is unlocked only by a brand-matching token.
- Melinoe
Mut - An exclusive, branded view of a cell’s contents (
Deref/DerefMuttoT). - Melinoe
Ref - A shared, branded view of a cell’s contents (
DereftoT). - ParChunks
- Indexed, random-access view over the disjoint
chunk_size-cell partitions of a branded region — the indexed counterpart to the sequentialShardChunkslending iterator. - Reentrancy
Cell - A thread-confined gate yielding at most one exclusive branded token at a time.
- Relaxed
- Relaxed atomic ordering policy.
- Retained
alloc - Clone the branded slice into an owned buffer so it may outlive the brand.
- SeqCst
- Sequentially consistent ordering policy.
- Shared
Read Token - A freely-copyable, read-only permit for a brand.
- Writer
Shard - A move-only,
Sendwrite capability over a disjoint partition of a branded region.
Enums§
- Retain
Decision alloc - Runtime retain decision for
CellCowExt::borrow_cow_if.
Traits§
- Atomic
Order - ZST ordering policy for atomic load/store/swap/fetch operations.
- Cell
CowExt alloc - Conditional
Cowviews over[MelinoeCell<'brand, T>], gated by a read permit. - Cell
Slice Ext - Zero-copy slice views over
[MelinoeCell<'brand, T>], gated by a capability permit. - CowPolicy
alloc - Compile-time retain policy for
CellCowExt::borrow_cow_with. - Parallel
Executor std - A scheduler that can run a partition’s independent tasks.
- Read
Permit - Evidence that the bearer may obtain a shared (
&T) view of anyMelinoeCellcarrying the matching'brand. - Write
Permit - Evidence that the bearer may obtain an exclusive (
&mut T) view of anyMelinoeCellcarrying the matching'brand.
Functions§
- brand_
scope - Open a fresh branding scope and hand its unique
ExclusiveTokentof. - clear_
parallel_ executor std - Clear the registered parallel executor, restoring the default scoped-thread partition driver.
- register_
parallel_ executor std - Register a global parallel executor to run partition tasks.
- with_
generated alloc - Generate a branded vector and run a closure while its fresh brand is live.
Type Aliases§
- Invariant
Lifetime - A zero-sized marker that is invariant in
'brandand unconditionallySend + Sync.