Skip to main content

Crate melinoe

Crate melinoe 

Source
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

TokenCardinalitySend/SyncRole
ExclusiveTokenone per brandbothsole owner; read + write
SharedReadTokenmany (Copy)bothfan-out read capability
ThreadLocalTokenone per brandneitherthread-confined owner
SyncRegionTokenone per brandboththread-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_scope for several independent exclusion domains at once. Each nested scope is a fresh, non-unifiable brand, so a &mut into one region and a &mut into another are held simultaneously, disjointness proven at compile time. Composition gives any arity for free — no brand_scopeN.
  • region::WriterShard — split one brand into disjoint sub-regions for concurrent writers; SyncRegionToken moves 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 a WritePermit (proven-exclusive phase), atomic access under a ReadPermit (shared phase). The capability selects the cost, so you pay for synchronization only while sharing. Relaxed, AcqRel, and SeqCst are ZST ordering policies for monomorphized atomic call sites.
  • CellCowExt — conditional Cow at the ownership boundary: Borrowed returns a zero-copy borrowed slice, Retained clones exactly once, and RetainDecision covers 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 of alloc; enables sync::scope_exclusive and other std::thread::scope-based demonstrations.
  • alloc — links the alloc crate for heap-payload examples/tests.
  • nightly — enables doc_cfg for precise feature-gated docs (requires a nightly toolchain); reserved for future generic_const_exprs capability 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.
collectionsalloc
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 / clear accessors.

Structs§

AcqRel
Acquire load / release store / acquire-release RMW ordering policy.
Borrowedalloc
Borrow the branded slice; no allocation and no element clone.
BrandedAtomic
A branded atomic whose access cost is conditional on the capability presented: plain in the exclusive phase, atomic in the shared phase.
BrandedDrainalloc
A draining iterator for BrandedVec.
BrandedVecalloc
A branded vector backed by Vec<MelinoeCell<'brand, T>>.
BrandedVecDequealloc
A branded double-ended queue backed by VecDeque<MelinoeCell<'brand, T>>.
BrandedVecDequeDrainalloc
A draining iterator for BrandedVecDeque.
ExclusiveToken
The single, un-clonable owner of a brand’s access rights.
Executorstd
A validated, process-global parallel executor.
GuardedCell
A thread-confined cell that hands out one exclusive &mut T at a time.
MelinoeCell
A cell whose interior mutability is unlocked only by a brand-matching token.
MelinoeMut
An exclusive, branded view of a cell’s contents (Deref/DerefMut to T).
MelinoeRef
A shared, branded view of a cell’s contents (Deref to T).
ParChunks
Indexed, random-access view over the disjoint chunk_size-cell partitions of a branded region — the indexed counterpart to the sequential ShardChunks lending iterator.
ReentrancyCell
A thread-confined gate yielding at most one exclusive branded token at a time.
Relaxed
Relaxed atomic ordering policy.
Retainedalloc
Clone the branded slice into an owned buffer so it may outlive the brand.
SeqCst
Sequentially consistent ordering policy.
SharedReadToken
A freely-copyable, read-only permit for a brand.
WriterShard
A move-only, Send write capability over a disjoint partition of a branded region.

Enums§

RetainDecisionalloc
Runtime retain decision for CellCowExt::borrow_cow_if.

Traits§

AtomicOrder
ZST ordering policy for atomic load/store/swap/fetch operations.
CellCowExtalloc
Conditional Cow views over [MelinoeCell<'brand, T>], gated by a read permit.
CellSliceExt
Zero-copy slice views over [MelinoeCell<'brand, T>], gated by a capability permit.
CowPolicyalloc
Compile-time retain policy for CellCowExt::borrow_cow_with.
ParallelExecutorstd
A scheduler that can run a partition’s independent tasks.
ReadPermit
Evidence that the bearer may obtain a shared (&T) view of any MelinoeCell carrying the matching 'brand.
WritePermit
Evidence that the bearer may obtain an exclusive (&mut T) view of any MelinoeCell carrying the matching 'brand.

Functions§

brand_scope
Open a fresh branding scope and hand its unique ExclusiveToken to f.
clear_parallel_executorstd
Clear the registered parallel executor, restoring the default scoped-thread partition driver.
register_parallel_executorstd
Register a global parallel executor to run partition tasks.
with_generatedalloc
Generate a branded vector and run a closure while its fresh brand is live.

Type Aliases§

InvariantLifetime
A zero-sized marker that is invariant in 'brand and unconditionally Send + Sync.