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
use crate::alloc;
use crate::depot::{
    arena::slab::{self, key::cycle},
    capacity,
    index::{Initialized, Unborrowed},
    queue::links,
};
use crate::mem::Rejected;
use std::{array, cell, marker, mem, slice};

mod pinned;
mod store;
pub use pinned::Pinned;
pub use store::Store;

pub mod entries;
pub mod external;
pub mod key;
pub mod lookup;
pub mod raw;

/// Why no identity can currently be reserved from a slab.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Vacancy {
    /// Usable slots are occupied or reserved, or the physical capacity is zero.
    Full,
    /// The admitted non-wrapping identity domain is permanently exhausted.
    IdentityExhausted,
}

const _: () = {
    assert!(size_of::<raw::Occupied<'_, u64>>() == 2 * size_of::<usize>());
    assert!(size_of::<Option<raw::Occupied<'_, u64>>>() == 2 * size_of::<usize>());
    assert!(size_of::<Option<slab::raw::Vacant<'_, u64>>>() == 2 * size_of::<usize>());
    assert!(
        size_of::<
            Option<raw::Occupied<'_, u64, (), { u32::MAX }, entries::Exclusive, 1, true, true>>,
        >() == 2 * size_of::<usize>()
    );
    assert!(
        size_of::<raw::Occupied<'_, u64, (), { u32::MAX }, entries::Exclusive, 1, false>>()
            == size_of::<raw::Occupied<'_, u64>>()
    );
};

#[derive(Clone, Copy, PartialEq, Eq)]
pub enum State<B, R> {
    Free,
    Reserved,
    Occupied,
    Busy(B),
    Retired(R),
}

impl<B, R> State<B, R> {
    /// Classifies one admitted slot, retaining the live-borrow witness for its caller.
    fn classify<const MAX: u32, C>(
        self,
        actual: key::Generation<MAX>,
        expected: key::Generation<MAX>,
    ) -> Result<(), key::Observation<MAX, B, R, C>> {
        use key::Observation;

        match self {
            Self::Free => Err(Observation::Free { actual }),
            Self::Reserved => Err(Observation::Reserved { actual }),
            Self::Retired(retired) => Err(Observation::Retired { actual, retired }),
            Self::Busy(borrow) => Err(Observation::Busy { actual, borrow }),
            Self::Occupied if actual != expected => Err(Observation::Generation { actual }),
            Self::Occupied => Ok(()),
        }
    }
}

/// One distinct physical slot retained by exclusive iteration.
pub enum Entry<'a, T, Tag = (), const MAX: u32 = { u32::MAX }> {
    Vacant(slab::raw::Vacant<'a, T, Tag, MAX, entries::Exclusive, 1, false>),
    Occupied(raw::Occupied<'a, T, Tag, MAX, entries::Exclusive, 1, false>),
}

impl<T, Tag, const MAX: u32> slab::Cell<T, Tag, MAX> {
    /// Reserves every slot and dense index entry transactionally.
    pub fn try_new(cap: capacity::Count) -> Result<Self, crate::alloc::Error> {
        Ok(Self {
            core: raw::Core::try_new(cap)?,
            tag: marker::PhantomData,
        })
    }

    pub fn capacity(&self) -> usize {
        self.core.slots.capacity()
    }

    /// Nonretired slots, including occupied slots and unpublished reservations.
    pub fn remaining(&self) -> capacity::Count {
        self.core.slots.remaining()
    }

    pub fn len(&self) -> capacity::Count {
        self.core.len()
    }

    pub fn is_empty(&self) -> bool {
        self.len() == capacity::Count::EMPTY
    }

    pub fn is_full(&self) -> bool {
        self.core.is_full()
    }

    pub fn vacancy(&self) -> Option<slab::raw::Vacant<'_, T, Tag, MAX, entries::Interior>> {
        Some(slab::raw::Vacant::new(self.core.free()?))
    }

    /// Reserves a slot or preserves the exact temporary or permanent refusal.
    pub fn try_vacancy(
        &self,
    ) -> Result<slab::raw::Vacant<'_, T, Tag, MAX, entries::Interior>, slab::Vacancy> {
        Ok(slab::raw::Vacant::new(self.core.try_free()?))
    }
}

impl<'a, T, Tag, const MAX: u32> slab::Cell<T, Tag, MAX> {
    pub fn entry(
        &'a self,
        parts: key::Parts<MAX>,
    ) -> Option<raw::Occupied<'a, T, Tag, MAX, entries::Interior>> {
        let entry = slab::raw::Position::key(&self.core, parts.index(), parts.generation())?;
        Some(raw::Occupied::new(entry.take()))
    }

    pub fn try_entry(&'a self, key: key::Handle<Tag, MAX>) -> Lookup<'a, T, Tag, MAX> {
        Ok(raw::Occupied::new(
            slab::raw::Position::try_key(&self.core, key)?.take(),
        ))
    }

    pub fn entry_at(
        &'a self,
        index: u32,
    ) -> Option<raw::Occupied<'a, T, Tag, MAX, entries::Interior>> {
        let entry = slab::raw::Position::at(&self.core, index)?;
        Some(raw::Occupied::new(entry.take()))
    }
}

/// A branded slab owner with dynamically checked interior access.
pub struct Cell<T, Tag = (), const MAX: u32 = { u32::MAX }> {
    pub(in crate::depot) core: raw::Core<T, MAX, entries::Interior>,
    tag: marker::PhantomData<fn() -> Tag>,
}

impl<T, Tag, const MAX: u32> Cell<T, Tag, MAX> {
    pub fn value_ptr<P>(
        proof: crate::depot::raw::Proof<(&Self, links::Index), Initialized<P>>,
    ) -> *mut T {
        let (owner, index) = proof.into_inner();
        let slots = owner.core.slots.as_ref();
        // SAFETY: the original initialized proof retains this slot in the same owner.
        unsafe { slots.get_unchecked(index.get()).value_ptr() }
    }
}

type Lookup<'a, T, Tag, const MAX: u32> = Result<
    raw::Occupied<'a, T, Tag, MAX, entries::Interior>,
    Rejected<key::Handle<Tag, MAX>, key::Observation<MAX, (), ()>>,
>;

impl<'a, T, Tag, const MAX: u32> slab::Cell<T, Tag, MAX> {
    /// Admits the original unborrowed slot.
    pub fn from_live<P>(
        live: crate::depot::raw::Proof<(&'a Self, links::Index), Unborrowed<P>>,
    ) -> raw::Occupied<'a, T, Tag, MAX, entries::Interior> {
        let (owner, index) = live.into_inner();
        // SAFETY: the retained unborrowed predicate names this exact initialized slot.
        let entry = unsafe { raw::Position::new(&owner.core, index) };
        raw::Occupied::new(entry.take())
    }
}

/// Heap-allocated slot storage constructed eagerly; the default policy.
pub struct Heap;

/// Slot storage carried inline by its owner with a const slot count.
pub struct Inline<const N: usize>;

/// Heap-allocated slot storage constructed on first use.
pub struct Lazy;

/// Where and when one slab constructs its slots.
pub trait Storage: entries::Sealed {
    const LAZY: bool = false;

    /// The slot plane of this storage policy.
    type Plane<T, const MAX: u32, M: entries::Mode>: Plane<T, MAX, M>;
}

impl Storage for Heap {
    type Plane<T, const MAX: u32, M: entries::Mode> = HeapEager<T, MAX, M>;
}

impl<const N: usize> Storage for Inline<N> {
    type Plane<T, const MAX: u32, M: entries::Mode> = InlineEager<N, T, MAX, M>;
}

impl entries::Sealed for Heap {}

impl<const N: usize> entries::Sealed for Inline<N> {}

impl Storage for Lazy {
    const LAZY: bool = true;

    type Plane<T, const MAX: u32, M: entries::Mode> = HeapLazy<T, MAX, M>;
}

impl entries::Sealed for Lazy {}

type Slot<T, const MAX: u32, M> = crate::depot::raw::SlabSlot<
    T,
    <<M as entries::Mode>::Cycle as cycle::Policy>::Stored<MAX>,
    <M as entries::Mode>::Busy,
    <<M as entries::Mode>::Cycle as cycle::Policy>::Retired,
>;

type Shape<T, const MAX: u32, M> = crate::depot::raw::SlabCapacity<
    T,
    <<M as entries::Mode>::Cycle as cycle::Policy>::Stored<MAX>,
    <M as entries::Mode>::Busy,
    <<M as entries::Mode>::Cycle as cycle::Policy>::Retired,
>;

type Prepared<T, const MAX: u32, M> = crate::alloc::raw::Block<
    Shape<T, MAX, M>,
    cell::Cell<u32>,
    (),
    mem::MaybeUninit<Slot<T, MAX, M>>,
>;

type Ready<T, const MAX: u32, M> =
    crate::alloc::raw::Block<Shape<T, MAX, M>, cell::Cell<u32>, (), Slot<T, MAX, M>>;

/// One allocated extent whose every slot is constructed with the storage.
pub struct HeapEager<T, const MAX: u32, M: entries::Mode> {
    block: Ready<T, MAX, M>,
}

impl<T, const MAX: u32, M: entries::Mode> HeapEager<T, MAX, M> {
    fn remaining(&self) -> capacity::Count {
        capacity::Count::new(self.count().raw().wrapping_sub(self.block.state.get()))
    }

    fn refusal(&self) -> Vacancy {
        let retired = self.block.state.get();
        if retired != 0 && retired == self.count().raw() {
            Vacancy::IdentityExhausted
        } else {
            Vacancy::Full
        }
    }
}

impl<T, const MAX: u32, M: entries::Mode> HeapPlane<T, MAX, M> for HeapEager<T, MAX, M> {
    fn try_alloc<const N: usize>(cap: capacity::Count) -> Result<Self, alloc::Error> {
        const { assert!(!mem::needs_drop::<Slot<T, MAX, M>>()) };
        let _ = const { key::Generation::<MAX>::MIN };
        let epoch: <M::Cycle as cycle::Policy>::Stored<MAX> = Default::default();
        let extent = crate::depot::raw::SlabCapacity::new(cap)?;
        Ok(Self {
            block: crate::alloc::raw::Uninit::try_from_fn(
                extent,
                cell::Cell::new(0),
                |index| raw::Core::<T, MAX, M, N>::slot(index, cap.get(), epoch),
                |_| cell::Cell::new(mem::MaybeUninit::uninit()),
            )?,
        })
    }
}

impl<T, const MAX: u32, M: entries::Mode> Plane<T, MAX, M> for HeapEager<T, MAX, M> {
    fn retired(&self) -> Option<&cell::Cell<u32>> {
        Some(&self.block.state)
    }

    fn count(&self) -> capacity::Count {
        self.block.extent().count
    }

    fn tail(&self) -> &[cell::Cell<mem::MaybeUninit<u32>>] {
        self.block.tail()
    }

    fn as_ref(&self) -> &[Slot<T, MAX, M>] {
        self.block.as_ref()
    }
}

/// One allocated extent whose slots are constructed on first use.
pub struct HeapLazy<T, const MAX: u32, M: entries::Mode> {
    block: Prepared<T, MAX, M>,
    built: cell::Cell<u32>,
}

impl<T, const MAX: u32, M: entries::Mode> HeapPlane<T, MAX, M> for HeapLazy<T, MAX, M> {
    fn try_alloc<const N: usize>(cap: capacity::Count) -> Result<Self, alloc::Error> {
        let _ = const { key::Generation::<MAX>::MIN };
        let extent = crate::depot::raw::SlabCapacity::new(cap)?;
        Ok(Self {
            block: crate::alloc::raw::Uninit::try_fill(extent, cell::Cell::new(0), |_| {
                (
                    mem::MaybeUninit::uninit(),
                    cell::Cell::new(mem::MaybeUninit::uninit()),
                )
            })?,
            built: cell::Cell::new(0),
        })
    }
}

impl<T, const MAX: u32, M: entries::Mode> Plane<T, MAX, M> for HeapLazy<T, MAX, M> {
    fn retired(&self) -> Option<&cell::Cell<u32>> {
        Some(&self.block.state)
    }

    fn count(&self) -> capacity::Count {
        self.block.extent().count
    }

    fn tail(&self) -> &[cell::Cell<mem::MaybeUninit<u32>>] {
        self.block.tail()
    }

    fn as_ref(&self) -> &[Slot<T, MAX, M>] {
        // SAFETY: construction wrote every slot below the built prefix of this
        // allocation, which stays live for this shared borrow.
        unsafe { slice::from_raw_parts(self.block.as_ptr().cast(), self.built() as usize) }
    }

    fn built(&self) -> u32 {
        self.built.get()
    }

    fn push(&self, slot: Slot<T, MAX, M>) -> Option<links::Index> {
        let index = self.built();
        if index as usize >= self.capacity() {
            return None;
        }
        // SAFETY: this new slot is in bounds and outside every published prefix.
        // The allocation pointer writes only this slot without borrowing its neighbors.
        unsafe { (&mut *self.block.as_ptr().add(index as usize)).write(slot) };
        self.built.set(index + 1);
        // SAFETY: index is strictly below this u32 capacity.
        Some(unsafe { links::Index::new_raw(index) })
    }
}

/// One inline extent whose every slot is constructed with the storage.
pub struct InlineEager<const N: usize, T, const MAX: u32, M: entries::Mode> {
    slots: [Slot<T, MAX, M>; N],
    cells: [cell::Cell<mem::MaybeUninit<u32>>; N],
}

impl<const N: usize, T, const MAX: u32, M: entries::Mode> InlineEager<N, T, MAX, M> {
    pub(in crate::depot::arena::slab) fn inline<const PARTITIONS: usize>() -> Self {
        const { assert!(N <= u32::MAX as usize, "inline slot count") };
        let _ = const { key::Generation::<MAX>::MIN };
        let epoch: <M::Cycle as cycle::Policy>::Stored<MAX> = Default::default();
        Self {
            slots: array::from_fn(|index| {
                raw::Core::<T, MAX, M, PARTITIONS>::slot(index, N, epoch)
            }),
            cells: [const { cell::Cell::new(mem::MaybeUninit::uninit()) }; N],
        }
    }
}

impl<const N: usize, T, const MAX: u32, M: entries::Mode> Plane<T, MAX, M>
    for InlineEager<N, T, MAX, M>
{
    fn count(&self) -> capacity::Count {
        capacity::Count::new(N as u32)
    }

    fn tail(&self) -> &[cell::Cell<mem::MaybeUninit<u32>>] {
        &self.cells
    }

    fn as_ref(&self) -> &[Slot<T, MAX, M>] {
        &self.slots
    }
}

/// The exact slots and construction state retained by one sealed storage policy.
pub trait Plane<T, const MAX: u32, M: entries::Mode>: Sized + entries::Sealed {
    fn count(&self) -> capacity::Count;

    /// Heap planes retain their permanent retirement count in allocation metadata.
    fn retired(&self) -> Option<&cell::Cell<u32>> {
        None
    }

    /// The dense position plane; only the owner's live prefix is guaranteed initialized.
    fn tail(&self) -> &[cell::Cell<mem::MaybeUninit<u32>>];

    /// Every constructed slot of this plane, in storage order.
    fn as_ref(&self) -> &[Slot<T, MAX, M>];

    /// The number of slots constructed so far.
    fn built(&self) -> u32 {
        self.count().raw()
    }

    /// Constructs the next lazy slot; returns `None` for a complete or eager plane.
    fn push(&self, _: Slot<T, MAX, M>) -> Option<links::Index> {
        None
    }

    fn capacity(&self) -> usize {
        self.count().get()
    }

    fn get(&self, index: u32) -> Option<&Slot<T, MAX, M>> {
        self.as_ref().get(index as usize)
    }
}

/// The slot operations of one heap plane: an extent allocated before its slots.
pub trait HeapPlane<T, const MAX: u32, M: entries::Mode>: Plane<T, MAX, M> {
    /// Allocates the complete extent under its fixed slot construction policy.
    fn try_alloc<const N: usize>(cap: capacity::Count) -> Result<Self, alloc::Error>;
}

impl<T, const MAX: u32, M: entries::Mode> entries::Sealed for HeapEager<T, MAX, M> {}
impl<T, const MAX: u32, M: entries::Mode> entries::Sealed for HeapLazy<T, MAX, M> {}
impl<const N: usize, T, const MAX: u32, M: entries::Mode> entries::Sealed
    for InlineEager<N, T, MAX, M>
{
}