Skip to main content

o3/depot/raw/
mod.rs

1//! Shared storage proofs and operations that consume their exact owning capabilities.
2
3use std::{cell, marker, mem, num::NonZero, ops};
4
5use crate::alloc::array;
6
7pub use proof::Proof;
8pub(in crate::depot) use proof::{ChainCount, Domain, Numeric, Sealed};
9
10/// # Safety
11/// The output retains the source's ownership, lifetime, exact slot, state, and plane.
12/// Borrowed outputs cannot create ownership or exclusivity absent from the retained source.
13pub unsafe trait Project<K, P = ()> {
14    type Output;
15    /// # Safety
16    /// This key names an initialized slot in this exact retained source and plane.
17    /// All ownership and state invariants specified by P hold for the retained operation.
18    unsafe fn project(self, key: K) -> Self::Output;
19}
20
21use crate::depot::{
22    arena::{
23        linked::{self, fifo, head},
24        pool::shared,
25    },
26    capacity,
27    index::{Initialized, Stored, bitmap, set},
28    queue::{
29        indexed::keyed,
30        links::{Hook, Index},
31        pool, tagged,
32    },
33};
34mod proof;
35
36impl crate::alloc::raw::Empty<capacity::Count> {
37    // SAFETY: Count::EMPTY is zero and its Extent implementation preserves that count.
38    pub const EMPTY: Self = unsafe { Self::assume(capacity::Count::EMPTY) };
39}
40
41/// # Safety
42/// Copies and equality preserve the complete identity and its lifelong direct-address index.
43/// `index` is total, numeric and non-reentrant, with no callbacks.
44pub unsafe trait Address: Copy + Eq {
45    fn index(self) -> usize;
46}
47
48pub(super) type KeyDomain<K> = marker::PhantomData<(K, fn(K) -> K)>;
49
50/// # Safety
51/// Encodings exactly round-trip live identities and indices, excluding `VACANT`.
52/// Equality/conversions are total, callback-free and non-reentrant; `index` obeys [`Address`].
53pub unsafe trait Key: Copy + Eq {
54    type Raw: Copy + Eq;
55    const VACANT: Self::Raw;
56    fn index(self) -> usize;
57    fn into_raw(self) -> Self::Raw;
58    fn from_raw(raw: Stored<Self>) -> Self;
59    /// # Safety
60    /// The retained identity is live in this exact destination domain with unchanged identity.
61    unsafe fn rebuild<K: Key<Raw = Self::Raw>>(stored: Stored<K>) -> Self {
62        // SAFETY: the caller preserves the emitted identity in this destination domain.
63        Self::from_raw(unsafe { Stored::new(stored.into_raw()) })
64    }
65}
66
67/// Stored representation of one external forward link.
68/// # Safety
69/// `NONE` decodes to `None`; present links and live items round-trip exactly.
70pub unsafe trait Link: Copy + Eq {
71    type Item: Copy + Eq;
72    const NONE: Self;
73    fn item(self) -> Option<Self::Item>;
74    /// Stores one live item without changing its identity.
75    /// # Safety
76    /// `item` must be live in this link's exact domain.
77    unsafe fn some(item: Self::Item) -> Self;
78}
79
80pub(in crate::depot) fn inserted<L: Link, O, const FRONT: bool>(
81    proof: fifo::Insertion<O, L::Item, FRONT>,
82) -> (O, L, bool) {
83    let (owner, item, previous) = proof.into_inner();
84    // SAFETY: Insert retains this live item in its original link domain until publication.
85    (owner, unsafe { L::some(item) }, previous.is_none())
86}
87
88unsafe impl<Tag> Link for linked::raw::Index<Tag> {
89    type Item = Self;
90
91    const NONE: Self = Self::NONE;
92
93    fn item(self) -> Option<Self> {
94        (self != Self::NONE).then_some(self)
95    }
96
97    unsafe fn some(item: Self) -> Self {
98        item
99    }
100}
101
102/// # Safety
103/// The retained owner initializes this key and satisfies every ownership and state invariant of P.
104/// Shared source loans preserve those obligations without creating exclusive authority.
105pub unsafe trait Source<P = ()>: Sized {
106    type Key: Copy;
107    fn key(&self) -> Self::Key;
108}
109
110/// # Safety
111/// Dense ordinal values bijectively map to `0..=MAX`; conversions are inverse and `ZERO` maps to zero.
112/// In-domain conversions return normally without callbacks or storage reentry.
113pub unsafe trait Word: Copy + Eq {
114    const ZERO: Self;
115    const MAX: NonZero<usize>;
116    fn offset(self) -> usize;
117    /// # Safety
118    /// `offset` must not exceed [`Self::MAX`].
119    unsafe fn from_offset(offset: usize) -> Self;
120}
121
122/// # Safety
123/// Planes stay stationary and initialized with exact shapes, zero tail bits, and exact nonzero-child summaries.
124/// Mutation preserves this; projections return normally without mutation or reentry.
125pub unsafe trait Words<W: bitmap::Width = usize> {
126    type Plane: Copy;
127    type Size: Copy + Into<u32>;
128
129    fn shape(&self) -> bitmap::Shape<Self::Size, W>;
130    fn words(&self, plane: Self::Plane) -> &[bitmap::Word<W>];
131
132    fn row(entry: bitmap::raw::Row<&Self, (), (), W>, plane: Self::Plane) -> &[bitmap::Word<W>]
133    where
134        Self: Sized,
135    {
136        (*entry.source()).words(plane)
137    }
138}
139
140mod hooks;
141pub use hooks::Hooks;
142
143/// An immutable u32 count retaining its original domain proof.
144/// # Safety
145/// Every copy reports the same count within MIN..=MAX; count is zero or count - 1 is at most I::MAX.
146pub unsafe trait Count<I: Compact = u32>: Copy {
147    const MIN: u32 = 0;
148    const MAX: u32 = u32::MAX;
149    fn count(self) -> capacity::Count;
150}
151
152/// A retained capability for one stationary set owner.
153/// # Safety
154/// Projections are pure; every projection and move retains the same live owner, extent, and lifetime.
155pub unsafe trait SetSource<Tag, Raw, const N: usize> {
156    type Mode;
157
158    fn planes(&self) -> &set::State<Tag, Raw, N, Self::Mode>;
159}
160
161/// A storage owner whose exclusive borrow excludes every other plane access.
162/// # Safety
163/// No independent handle may access these words while this owner is exclusively borrowed.
164pub unsafe trait Bitmap<W: bitmap::Width = usize>: Words<W> {}
165
166/// # Safety
167/// Words select initialized nodes or retained `u32::MAX - lane` heads in fixed disjoint domains.
168/// `is_node`/projections are pure and non-reentrant; tagged operations own mutation exclusively.
169pub unsafe trait TagStore {
170    type Head: tagged::raw::Head;
171    type Heads: AsRef<[Self::Head]> + ?Sized;
172    fn heads(&self) -> &Self::Heads;
173    fn is_node(&self, word: u32) -> bool {
174        (u32::MAX - word) as usize >= self.heads().as_ref().len()
175    }
176    /// # Safety
177    /// The index names an initialized node in this exact owner.
178    unsafe fn hook(&self, index: Index) -> &tagged::raw::Hook;
179}
180
181/// Detaches one exact external head slot.
182/// # Safety
183/// Returns that item's stored successor after detaching the supplied live item.
184pub unsafe trait HeadPop<L: Link, I = ()>: Sized {
185    type Output;
186    /// # Safety
187    /// `item` is the exact live slot owned by this transition.
188    unsafe fn pop(self, item: L::Item, input: I) -> (L, Self::Output);
189    /// # Safety
190    /// This transition owns this exact current front and cannot reenter its head.
191    unsafe fn apply(self, front: head::Front<'_, L>, input: I) -> Self::Output {
192        unsafe { front.pop(self, input) }
193    }
194}
195
196/// Publishes one exact detached external slot.
197/// # Safety
198/// Stores `head` in that detached slot before returning its exact live identity.
199pub unsafe trait HeadPush<L: Link, I = ()>: Sized {
200    /// # Safety
201    /// This transition and `input` own the exact detached slot returned.
202    unsafe fn push(self, input: I, head: L) -> L::Item;
203    /// # Safety
204    /// This transition owns a detached slot in this exact head's storage and cannot reenter it.
205    unsafe fn apply(self, head: &head::Cell<L>, input: I) {
206        let item = unsafe { self.push(input, head.raw()) };
207        head.0.set(unsafe { L::some(item) });
208    }
209}
210
211/// Consumes one exact keyed slot into its next membership phase.
212/// # Safety
213/// Output preserves or consumes this slot's original owner and root authority.
214pub unsafe trait KeyFinish<const LINKED: bool, P = ()>: Sized {
215    type Output;
216    /// # Safety
217    /// The selected slot is a member when LINKED and canonically detached otherwise.
218    unsafe fn finish(self) -> Self::Output;
219}
220/// # Safety
221/// This exclusive root retains the exact initialized slot/key/link/FIFO; its index excludes endpoint tags.
222/// Pure, non-reentrant projections and escaping loans preserve authority, membership and the exact plane.
223pub unsafe trait KeyOwner<P = ()>: Sized {
224    type Key: Address;
225    type Fifo;
226    fn parts(&self) -> (Self::Key, &keyed::Link<Self::Key, P>);
227    fn fifo(&self) -> &Self::Fifo;
228    fn link(live: Proof<(&Self, Index), Initialized<P>>) -> &keyed::Link<Self::Key, P>;
229}
230/// # Safety
231/// Routing preserves this exact live slot, vacancy and exclusive root in its destination FIFO.
232pub unsafe trait KeyRoute<P = ()>: KeyOwner<P> {
233    type Target: KeyOwner<P, Key = Self::Key, Fifo = Self::Fifo>;
234    /// # Safety
235    /// This slot must be detached before changing its eligible FIFO.
236    unsafe fn route(self) -> Self::Target;
237}
238/// # Safety
239/// Retaining this source preserves its paired initialized storage, live endpoints and link plane.
240pub unsafe trait KeySource<P = ()> {
241    type Key: Address;
242    fn fifo(&self) -> &keyed::Fifo<Self::Key, P>;
243}
244/// # Safety
245/// Shared traversal preserves membership, links and identities.
246/// Projection returns the exact initialized slot's link without changing or reentering the topology.
247pub unsafe trait KeyRead<P = ()>: KeySource<P> {
248    fn link(live: Proof<(&Self, Index), Initialized<P>>) -> &keyed::Link<Self::Key, P>;
249}
250/// # Safety
251/// Every FIFO edge is live in this exact owner; selection retains its exclusive authority.
252pub unsafe trait KeyPlane<P = ()>:
253    KeySource<P, Key = <Self::Slot as KeyOwner<P>>::Key> + Sized
254{
255    type Slot: KeyOwner<P, Fifo = keyed::Fifo<Self::Key, P>>;
256    fn select(slot: Proof<(Self, Index), Initialized<P>>) -> Self::Slot;
257}
258/// # Safety
259/// Both disjoint FIFOs retain their exact initialized storage, plane and membership exclusively.
260pub unsafe trait KeyJoin<P = ()>: KeySource<P> {
261    fn target(&self) -> &keyed::Fifo<Self::Key, P>;
262    fn link(live: Proof<(&Self, Index), Initialized<P>>) -> &keyed::Link<Self::Key, P>;
263}
264/// # Safety
265/// Encodings through `MAX` are complete, injective, and round-trip exactly.
266/// Both conversions are deterministic, non-panicking, and never invoke storage operations using this index domain.
267pub unsafe trait Compact: Copy {
268    const MAX: u32;
269    fn into_raw(self) -> u32;
270    /// Reconstructs an identity previously encoded by this domain.
271    /// # Safety
272    /// `raw <= Self::MAX` and belongs to this index domain.
273    unsafe fn from_raw(raw: u32) -> Self;
274}
275
276/// # Safety
277/// The exact lane retains one available slot under TRACK until insertion.
278/// The retained source stays initialized, immutable and disjoint from the claimed field.
279pub unsafe trait PoolInsert<'a, const TRACK: bool = true>: Sized {
280    type Item: Copy + 'a;
281    type State: 'a;
282    /// # Safety
283    /// The returned lane and source retain this admission through publication.
284    unsafe fn into_parts(
285        self,
286    ) -> (
287        pool::raw::Lane<'a, Self::Item, Self::State, TRACK>,
288        &'a Self::Item,
289    );
290}
291mod queues;
292pub(in crate::depot) use queues::{LaneStore, QueueBlock, QueueSlot};
293mod slabslot;
294pub(in crate::depot) use slabslot::{SlabCapacity, SlabLinks, SlabSlot};
295mod indexed;
296pub(in crate::depot) use indexed::{IndexedBlock, IndexedHook, IndexedMeta, IndexedState};
297mod arena;
298pub use arena::Arena;
299mod links;
300pub use links::Links;
301pub(in crate::depot) use links::{EndpointHook, Neighbor};
302
303/// A structurally pinned intrusive-list node and its caller-owned value.
304/// The list never moves or drops the value; remove it before owner movement.
305#[repr(C)]
306pub struct Entry<T> {
307    links: Links<T>,
308    value: T,
309    pinned: marker::PhantomPinned,
310}
311
312impl<T> Entry<T> {
313    pub const fn new(value: T) -> Self {
314        Self {
315            links: Links::new(),
316            value,
317            pinned: marker::PhantomPinned,
318        }
319    }
320
321    pub fn value(&self) -> &T {
322        &self.value
323    }
324}
325
326const _: () = {
327    assert!(mem::align_of::<Entry<usize>>() == mem::align_of::<usize>());
328    assert!(mem::size_of::<Entry<usize>>() == 3 * mem::size_of::<usize>());
329};
330
331/// Consumes a retained interior proof that already excludes live borrows.
332///
333/// The predicate carries the exclusivity obligation, so interior admission
334/// needs the same single check the predicate already performed at its source.
335pub trait Admit {
336    type Output;
337
338    fn admit(self) -> Self::Output;
339}
340
341/// One resident value paired with its stable compact hook.
342#[derive(Debug)]
343#[repr(C)]
344pub struct Node<T> {
345    value: T,
346    hook: Hook,
347}
348
349impl<T> Node<T> {
350    pub fn vacant(value: T, index: u32, next: u32) -> Self {
351        Self {
352            value,
353            hook: Hook::vacant(index, next),
354        }
355    }
356
357    pub const fn hook(&self) -> &Hook {
358        &self.hook
359    }
360}
361
362impl<T> ops::Deref for Node<T> {
363    type Target = T;
364
365    fn deref(&self) -> &Self::Target {
366        &self.value
367    }
368}
369
370#[derive(Clone, Copy)]
371pub enum StagedPhase {
372    Vacant,
373    Queued,
374    Parked,
375}
376
377/// Raw fields governed by the original slot's initialization and exclusive loans.
378#[repr(C)]
379pub struct StagedNode<K, Q, P> {
380    fields: queues::Fields<K, Q, P>,
381    pub hook: Hook,
382    pub phase: cell::Cell<StagedPhase>,
383}
384
385impl<K, Q, P> StagedNode<K, Q, P> {
386    pub fn init<S>(
387        mut block: array::raw::Block<mem::MaybeUninit<Self>, capacity::Count, S>,
388    ) -> array::raw::Block<Self, capacity::Count, S> {
389        for (index, node) in block.iter_mut().enumerate() {
390            Self::write(node, index as u32);
391        }
392        // SAFETY: Count bounds every index; the pass initialized the complete extent.
393        unsafe { block.assume_init() }
394    }
395
396    pub fn write(storage: &mut mem::MaybeUninit<Self>, index: u32) -> &mut Self {
397        let node = storage.as_mut_ptr();
398        // SAFETY: both payload fields permit uninitialized bytes; only hook and phase need initialization.
399        unsafe {
400            (&raw mut (*node).hook).write(Hook::vacant(index, Index::END));
401            (&raw mut (*node).phase).write(cell::Cell::new(StagedPhase::Vacant));
402            &mut *node
403        }
404    }
405
406    /// # Safety
407    /// This exclusive queued node retains K/Q; no observer intervenes before destination publication.
408    pub unsafe fn park(&self, value: P) -> Q {
409        let previous = unsafe { self.queued_ptr().read() };
410        unsafe { self.store_parked(value) };
411        previous
412    }
413
414    /// # Safety
415    /// This exclusive queued node retains K/Q through destination publication.
416    pub unsafe fn set_parked(&self, value: P)
417    where
418        Q: Copy,
419    {
420        unsafe { self.store_parked(value) };
421    }
422
423    unsafe fn store_parked(&self, value: P) {
424        unsafe { self.parked_ptr().write(value) };
425        self.phase.set(StagedPhase::Parked);
426    }
427
428    /// # Safety
429    /// This exclusive parked node retains K/P; no observer intervenes before destination publication.
430    pub unsafe fn queue(&self, value: Q) -> P {
431        let previous = unsafe { self.parked_ptr().read() };
432        unsafe { self.queued_ptr().write(value) };
433        self.phase.set(StagedPhase::Queued);
434        previous
435    }
436
437    /// Projects the key under the original slot loan.
438    pub fn key_ptr(&self) -> *mut K {
439        self.fields.key.get().cast()
440    }
441
442    /// Projects Q storage; reads require initialized Q under the original slot loan.
443    pub fn queued_ptr(&self) -> *mut Q {
444        self.fields.payload.get().cast()
445    }
446
447    /// Projects P storage; reads require initialized P under the original slot loan.
448    pub fn parked_ptr(&self) -> *mut P {
449        self.fields.payload.get().cast()
450    }
451
452    /// # Safety
453    /// The caller exclusively owns this initialized key and Q, and consumes them once.
454    pub unsafe fn drop_queued(&self) {
455        unsafe {
456            self.key_ptr().drop_in_place();
457            self.queued_ptr().drop_in_place();
458        }
459    }
460
461    /// # Safety
462    /// The caller exclusively owns this initialized key and P, and consumes them once.
463    pub unsafe fn drop_parked(&self) {
464        unsafe {
465            self.key_ptr().drop_in_place();
466            self.parked_ptr().drop_in_place();
467        }
468    }
469}
470
471/// # Safety
472/// The implementation updates only its original native endpoint owner.
473pub unsafe trait EndsPop<L: Link> {
474    /// # Safety
475    /// `next` is the stored successor of the just-detached current front.
476    unsafe fn advance(self, next: L);
477}
478
479// SAFETY: every resident slot owns exactly this reference domain while active.
480unsafe impl<T> crate::mem::raw::Edge for shared::Resident<T> {
481    fn count(&self) -> &crate::mem::raw::Count {
482        &self.references
483    }
484}