o3 0.62.0

shared-nothing primitives
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
//! Shared storage proofs and operations that consume their exact owning capabilities.

use std::{cell, marker, mem, num::NonZero, ops};

use crate::alloc::array;

pub use proof::Proof;
pub(in crate::depot) use proof::{ChainCount, Domain, Numeric, Sealed};

/// # Safety
/// The output retains the source's ownership, lifetime, exact slot, state, and plane.
/// Borrowed outputs cannot create ownership or exclusivity absent from the retained source.
pub unsafe trait Project<K, P = ()> {
    type Output;
    /// # Safety
    /// This key names an initialized slot in this exact retained source and plane.
    /// All ownership and state invariants specified by P hold for the retained operation.
    unsafe fn project(self, key: K) -> Self::Output;
}

use crate::depot::{
    arena::{
        linked::{self, fifo, head},
        pool::shared,
    },
    capacity,
    index::{Initialized, Stored, bitmap, set},
    queue::{
        indexed::keyed,
        links::{Hook, Index},
        pool, tagged,
    },
};
mod proof;

impl crate::alloc::raw::Empty<capacity::Count> {
    // SAFETY: Count::EMPTY is zero and its Extent implementation preserves that count.
    pub const EMPTY: Self = unsafe { Self::assume(capacity::Count::EMPTY) };
}

/// # Safety
/// Copies and equality preserve the complete identity and its lifelong direct-address index.
/// `index` is total, numeric and non-reentrant, with no callbacks.
pub unsafe trait Address: Copy + Eq {
    fn index(self) -> usize;
}

pub(super) type KeyDomain<K> = marker::PhantomData<(K, fn(K) -> K)>;

/// # Safety
/// Encodings exactly round-trip live identities and indices, excluding `VACANT`.
/// Equality/conversions are total, callback-free and non-reentrant; `index` obeys [`Address`].
pub unsafe trait Key: Copy + Eq {
    type Raw: Copy + Eq;
    const VACANT: Self::Raw;
    fn index(self) -> usize;
    fn into_raw(self) -> Self::Raw;
    fn from_raw(raw: Stored<Self>) -> Self;
    /// # Safety
    /// The retained identity is live in this exact destination domain with unchanged identity.
    unsafe fn rebuild<K: Key<Raw = Self::Raw>>(stored: Stored<K>) -> Self {
        // SAFETY: the caller preserves the emitted identity in this destination domain.
        Self::from_raw(unsafe { Stored::new(stored.into_raw()) })
    }
}

/// Stored representation of one external forward link.
/// # Safety
/// `NONE` decodes to `None`; present links and live items round-trip exactly.
pub unsafe trait Link: Copy + Eq {
    type Item: Copy + Eq;
    const NONE: Self;
    fn item(self) -> Option<Self::Item>;
    /// Stores one live item without changing its identity.
    /// # Safety
    /// `item` must be live in this link's exact domain.
    unsafe fn some(item: Self::Item) -> Self;
}

pub(in crate::depot) fn inserted<L: Link, O, const FRONT: bool>(
    proof: fifo::Insertion<O, L::Item, FRONT>,
) -> (O, L, bool) {
    let (owner, item, previous) = proof.into_inner();
    // SAFETY: Insert retains this live item in its original link domain until publication.
    (owner, unsafe { L::some(item) }, previous.is_none())
}

unsafe impl<Tag> Link for linked::raw::Index<Tag> {
    type Item = Self;

    const NONE: Self = Self::NONE;

    fn item(self) -> Option<Self> {
        (self != Self::NONE).then_some(self)
    }

    unsafe fn some(item: Self) -> Self {
        item
    }
}

/// # Safety
/// The retained owner initializes this key and satisfies every ownership and state invariant of P.
/// Shared source loans preserve those obligations without creating exclusive authority.
pub unsafe trait Source<P = ()>: Sized {
    type Key: Copy;
    fn key(&self) -> Self::Key;
}

/// # Safety
/// Dense ordinal values bijectively map to `0..=MAX`; conversions are inverse and `ZERO` maps to zero.
/// In-domain conversions return normally without callbacks or storage reentry.
pub unsafe trait Word: Copy + Eq {
    const ZERO: Self;
    const MAX: NonZero<usize>;
    fn offset(self) -> usize;
    /// # Safety
    /// `offset` must not exceed [`Self::MAX`].
    unsafe fn from_offset(offset: usize) -> Self;
}

/// # Safety
/// Planes stay stationary and initialized with exact shapes, zero tail bits, and exact nonzero-child summaries.
/// Mutation preserves this; projections return normally without mutation or reentry.
pub unsafe trait Words<W: bitmap::Width = usize> {
    type Plane: Copy;
    type Size: Copy + Into<u32>;

    fn shape(&self) -> bitmap::Shape<Self::Size, W>;
    fn words(&self, plane: Self::Plane) -> &[bitmap::Word<W>];

    fn row(entry: bitmap::raw::Row<&Self, (), (), W>, plane: Self::Plane) -> &[bitmap::Word<W>]
    where
        Self: Sized,
    {
        (*entry.source()).words(plane)
    }
}

mod hooks;
pub use hooks::Hooks;

/// An immutable u32 count retaining its original domain proof.
/// # Safety
/// Every copy reports the same count within MIN..=MAX; count is zero or count - 1 is at most I::MAX.
pub unsafe trait Count<I: Compact = u32>: Copy {
    const MIN: u32 = 0;
    const MAX: u32 = u32::MAX;
    fn count(self) -> capacity::Count;
}

/// A retained capability for one stationary set owner.
/// # Safety
/// Projections are pure; every projection and move retains the same live owner, extent, and lifetime.
pub unsafe trait SetSource<Tag, Raw, const N: usize> {
    type Mode;

    fn planes(&self) -> &set::State<Tag, Raw, N, Self::Mode>;
}

/// A storage owner whose exclusive borrow excludes every other plane access.
/// # Safety
/// No independent handle may access these words while this owner is exclusively borrowed.
pub unsafe trait Bitmap<W: bitmap::Width = usize>: Words<W> {}

/// # Safety
/// Words select initialized nodes or retained `u32::MAX - lane` heads in fixed disjoint domains.
/// `is_node`/projections are pure and non-reentrant; tagged operations own mutation exclusively.
pub unsafe trait TagStore {
    type Head: tagged::raw::Head;
    type Heads: AsRef<[Self::Head]> + ?Sized;
    fn heads(&self) -> &Self::Heads;
    fn is_node(&self, word: u32) -> bool {
        (u32::MAX - word) as usize >= self.heads().as_ref().len()
    }
    /// # Safety
    /// The index names an initialized node in this exact owner.
    unsafe fn hook(&self, index: Index) -> &tagged::raw::Hook;
}

/// Detaches one exact external head slot.
/// # Safety
/// Returns that item's stored successor after detaching the supplied live item.
pub unsafe trait HeadPop<L: Link, I = ()>: Sized {
    type Output;
    /// # Safety
    /// `item` is the exact live slot owned by this transition.
    unsafe fn pop(self, item: L::Item, input: I) -> (L, Self::Output);
    /// # Safety
    /// This transition owns this exact current front and cannot reenter its head.
    unsafe fn apply(self, front: head::Front<'_, L>, input: I) -> Self::Output {
        unsafe { front.pop(self, input) }
    }
}

/// Publishes one exact detached external slot.
/// # Safety
/// Stores `head` in that detached slot before returning its exact live identity.
pub unsafe trait HeadPush<L: Link, I = ()>: Sized {
    /// # Safety
    /// This transition and `input` own the exact detached slot returned.
    unsafe fn push(self, input: I, head: L) -> L::Item;
    /// # Safety
    /// This transition owns a detached slot in this exact head's storage and cannot reenter it.
    unsafe fn apply(self, head: &head::Cell<L>, input: I) {
        let item = unsafe { self.push(input, head.raw()) };
        head.0.set(unsafe { L::some(item) });
    }
}

/// Consumes one exact keyed slot into its next membership phase.
/// # Safety
/// Output preserves or consumes this slot's original owner and root authority.
pub unsafe trait KeyFinish<const LINKED: bool, P = ()>: Sized {
    type Output;
    /// # Safety
    /// The selected slot is a member when LINKED and canonically detached otherwise.
    unsafe fn finish(self) -> Self::Output;
}
/// # Safety
/// This exclusive root retains the exact initialized slot/key/link/FIFO; its index excludes endpoint tags.
/// Pure, non-reentrant projections and escaping loans preserve authority, membership and the exact plane.
pub unsafe trait KeyOwner<P = ()>: Sized {
    type Key: Address;
    type Fifo;
    fn parts(&self) -> (Self::Key, &keyed::Link<Self::Key, P>);
    fn fifo(&self) -> &Self::Fifo;
    fn link(live: Proof<(&Self, Index), Initialized<P>>) -> &keyed::Link<Self::Key, P>;
}
/// # Safety
/// Routing preserves this exact live slot, vacancy and exclusive root in its destination FIFO.
pub unsafe trait KeyRoute<P = ()>: KeyOwner<P> {
    type Target: KeyOwner<P, Key = Self::Key, Fifo = Self::Fifo>;
    /// # Safety
    /// This slot must be detached before changing its eligible FIFO.
    unsafe fn route(self) -> Self::Target;
}
/// # Safety
/// Retaining this source preserves its paired initialized storage, live endpoints and link plane.
pub unsafe trait KeySource<P = ()> {
    type Key: Address;
    fn fifo(&self) -> &keyed::Fifo<Self::Key, P>;
}
/// # Safety
/// Shared traversal preserves membership, links and identities.
/// Projection returns the exact initialized slot's link without changing or reentering the topology.
pub unsafe trait KeyRead<P = ()>: KeySource<P> {
    fn link(live: Proof<(&Self, Index), Initialized<P>>) -> &keyed::Link<Self::Key, P>;
}
/// # Safety
/// Every FIFO edge is live in this exact owner; selection retains its exclusive authority.
pub unsafe trait KeyPlane<P = ()>:
    KeySource<P, Key = <Self::Slot as KeyOwner<P>>::Key> + Sized
{
    type Slot: KeyOwner<P, Fifo = keyed::Fifo<Self::Key, P>>;
    fn select(slot: Proof<(Self, Index), Initialized<P>>) -> Self::Slot;
}
/// # Safety
/// Both disjoint FIFOs retain their exact initialized storage, plane and membership exclusively.
pub unsafe trait KeyJoin<P = ()>: KeySource<P> {
    fn target(&self) -> &keyed::Fifo<Self::Key, P>;
    fn link(live: Proof<(&Self, Index), Initialized<P>>) -> &keyed::Link<Self::Key, P>;
}
/// # Safety
/// Encodings through `MAX` are complete, injective, and round-trip exactly.
/// Both conversions are deterministic, non-panicking, and never invoke storage operations using this index domain.
pub unsafe trait Compact: Copy {
    const MAX: u32;
    fn into_raw(self) -> u32;
    /// Reconstructs an identity previously encoded by this domain.
    /// # Safety
    /// `raw <= Self::MAX` and belongs to this index domain.
    unsafe fn from_raw(raw: u32) -> Self;
}

/// # Safety
/// The exact lane retains one available slot under TRACK until insertion.
/// The retained source stays initialized, immutable and disjoint from the claimed field.
pub unsafe trait PoolInsert<'a, const TRACK: bool = true>: Sized {
    type Item: Copy + 'a;
    type State: 'a;
    /// # Safety
    /// The returned lane and source retain this admission through publication.
    unsafe fn into_parts(
        self,
    ) -> (
        pool::raw::Lane<'a, Self::Item, Self::State, TRACK>,
        &'a Self::Item,
    );
}
mod queues;
pub(in crate::depot) use queues::{LaneStore, QueueBlock, QueueSlot};
mod slabslot;
pub(in crate::depot) use slabslot::{SlabCapacity, SlabLinks, SlabSlot};
mod indexed;
pub(in crate::depot) use indexed::{IndexedBlock, IndexedHook, IndexedMeta, IndexedState};
mod arena;
pub use arena::Arena;
mod links;
pub use links::Links;
pub(in crate::depot) use links::{EndpointHook, Neighbor};

/// A structurally pinned intrusive-list node and its caller-owned value.
/// The list never moves or drops the value; remove it before owner movement.
#[repr(C)]
pub struct Entry<T> {
    links: Links<T>,
    value: T,
    pinned: marker::PhantomPinned,
}

impl<T> Entry<T> {
    pub const fn new(value: T) -> Self {
        Self {
            links: Links::new(),
            value,
            pinned: marker::PhantomPinned,
        }
    }

    pub fn value(&self) -> &T {
        &self.value
    }
}

const _: () = {
    assert!(mem::align_of::<Entry<usize>>() == mem::align_of::<usize>());
    assert!(mem::size_of::<Entry<usize>>() == 3 * mem::size_of::<usize>());
};

/// Consumes a retained interior proof that already excludes live borrows.
///
/// The predicate carries the exclusivity obligation, so interior admission
/// needs the same single check the predicate already performed at its source.
pub trait Admit {
    type Output;

    fn admit(self) -> Self::Output;
}

/// One resident value paired with its stable compact hook.
#[derive(Debug)]
#[repr(C)]
pub struct Node<T> {
    value: T,
    hook: Hook,
}

impl<T> Node<T> {
    pub fn vacant(value: T, index: u32, next: u32) -> Self {
        Self {
            value,
            hook: Hook::vacant(index, next),
        }
    }

    pub const fn hook(&self) -> &Hook {
        &self.hook
    }
}

impl<T> ops::Deref for Node<T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        &self.value
    }
}

#[derive(Clone, Copy)]
pub enum StagedPhase {
    Vacant,
    Queued,
    Parked,
}

/// Raw fields governed by the original slot's initialization and exclusive loans.
#[repr(C)]
pub struct StagedNode<K, Q, P> {
    fields: queues::Fields<K, Q, P>,
    pub hook: Hook,
    pub phase: cell::Cell<StagedPhase>,
}

impl<K, Q, P> StagedNode<K, Q, P> {
    pub fn init<S>(
        mut block: array::raw::Block<mem::MaybeUninit<Self>, capacity::Count, S>,
    ) -> array::raw::Block<Self, capacity::Count, S> {
        for (index, node) in block.iter_mut().enumerate() {
            Self::write(node, index as u32);
        }
        // SAFETY: Count bounds every index; the pass initialized the complete extent.
        unsafe { block.assume_init() }
    }

    pub fn write(storage: &mut mem::MaybeUninit<Self>, index: u32) -> &mut Self {
        let node = storage.as_mut_ptr();
        // SAFETY: both payload fields permit uninitialized bytes; only hook and phase need initialization.
        unsafe {
            (&raw mut (*node).hook).write(Hook::vacant(index, Index::END));
            (&raw mut (*node).phase).write(cell::Cell::new(StagedPhase::Vacant));
            &mut *node
        }
    }

    /// # Safety
    /// This exclusive queued node retains K/Q; no observer intervenes before destination publication.
    pub unsafe fn park(&self, value: P) -> Q {
        let previous = unsafe { self.queued_ptr().read() };
        unsafe { self.store_parked(value) };
        previous
    }

    /// # Safety
    /// This exclusive queued node retains K/Q through destination publication.
    pub unsafe fn set_parked(&self, value: P)
    where
        Q: Copy,
    {
        unsafe { self.store_parked(value) };
    }

    unsafe fn store_parked(&self, value: P) {
        unsafe { self.parked_ptr().write(value) };
        self.phase.set(StagedPhase::Parked);
    }

    /// # Safety
    /// This exclusive parked node retains K/P; no observer intervenes before destination publication.
    pub unsafe fn queue(&self, value: Q) -> P {
        let previous = unsafe { self.parked_ptr().read() };
        unsafe { self.queued_ptr().write(value) };
        self.phase.set(StagedPhase::Queued);
        previous
    }

    /// Projects the key under the original slot loan.
    pub fn key_ptr(&self) -> *mut K {
        self.fields.key.get().cast()
    }

    /// Projects Q storage; reads require initialized Q under the original slot loan.
    pub fn queued_ptr(&self) -> *mut Q {
        self.fields.payload.get().cast()
    }

    /// Projects P storage; reads require initialized P under the original slot loan.
    pub fn parked_ptr(&self) -> *mut P {
        self.fields.payload.get().cast()
    }

    /// # Safety
    /// The caller exclusively owns this initialized key and Q, and consumes them once.
    pub unsafe fn drop_queued(&self) {
        unsafe {
            self.key_ptr().drop_in_place();
            self.queued_ptr().drop_in_place();
        }
    }

    /// # Safety
    /// The caller exclusively owns this initialized key and P, and consumes them once.
    pub unsafe fn drop_parked(&self) {
        unsafe {
            self.key_ptr().drop_in_place();
            self.parked_ptr().drop_in_place();
        }
    }
}

/// # Safety
/// The implementation updates only its original native endpoint owner.
pub unsafe trait EndsPop<L: Link> {
    /// # Safety
    /// `next` is the stored successor of the just-detached current front.
    unsafe fn advance(self, next: L);
}

// SAFETY: every resident slot owns exactly this reference domain while active.
unsafe impl<T> crate::mem::raw::Edge for shared::Resident<T> {
    fn count(&self) -> &crate::mem::raw::Count {
        &self.references
    }
}