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
use crate::base::num::Step;
use crate::depot::{
    self,
    arena::slab::{
        self, Plane, entries, external,
        key::{self, cycle, cycle::Policy},
    },
    queue::links,
};
use std::{marker, mem, mem::MaybeUninit, ops, pin::Pin, ptr};
mod core;
mod entry;
mod free;
mod occupied;
mod position;
pub(in crate::depot) use core::Core;
pub(in crate::depot) use entry::Entry;
pub(in crate::depot::arena::slab) use free::Free;
pub use occupied::Occupied;
pub(in crate::depot) use position::Position;

type Split<'a, T, Tag, const MAX: u32, const N: usize> = position::Lookup<
    (
        Vacant<'a, T, Tag, MAX, entries::Exclusive, N, false>,
        Occupied<'a, T, Tag, MAX, entries::Exclusive, N, false>,
    ),
    Tag,
    MAX,
    entries::Exclusive,
>;

/// One unissued physical reservation.
pub struct Vacant<
    'a,
    T,
    Tag = (),
    const MAX: u32 = { u32::MAX },
    M: entries::Mode = entries::Exclusive,
    const N: usize = 1,
    const ROOT: bool = true,
    const ISSUED: bool = false,
> {
    pub(in crate::depot) entry: slab::raw::Entry<'a, T, MAX, M, N, slab::Heap, false, ISSUED>,
    tag: marker::PhantomData<fn() -> Tag>,
}

impl<
    'a,
    T,
    Tag,
    const MAX: u32,
    M: entries::Mode,
    const N: usize,
    const ROOT: bool,
    const ISSUED: bool,
> Vacant<'a, T, Tag, MAX, M, N, ROOT, ISSUED>
{
    pub(in crate::depot::arena::slab) fn new(
        entry: slab::raw::Entry<'a, T, MAX, M, N, slab::Heap, false, ISSUED>,
    ) -> Self {
        Self {
            entry,
            tag: marker::PhantomData,
        }
    }
    pub fn index(&self) -> links::Index {
        self.entry.index()
    }
}

impl<'a, T, Tag, const MAX: u32, M: entries::Mode, const N: usize, const ROOT: bool>
    Vacant<'a, T, Tag, MAX, M, N, ROOT>
{
    pub fn insert(mut self, value: T) -> key::Handle<Tag, MAX> {
        self.uninit().write(value);
        // SAFETY: this original reservation now holds the complete unborrowed value.
        unsafe { self.entry.publish_key() }.0
    }

    pub fn uninit(&mut self) -> &mut mem::MaybeUninit<T> {
        self.entry.uninit()
    }

    pub fn stage(self, value: T) -> Occupied<'a, T, Tag, MAX, M, N, ROOT, true> {
        Occupied::new(self.entry.install(value))
    }
}

impl<'a, T, Tag, const MAX: u32> Vacant<'a, T, Tag, MAX, entries::Interior> {
    pub fn reserve(self) -> Vacant<'a, T, Tag, MAX, entries::Interior, 1, true, true> {
        Vacant::new(self.entry.issue())
    }

    pub fn occupy(self, value: T) -> Occupied<'a, T, Tag, MAX, entries::Interior> {
        Occupied::new(self.entry.install(value))
    }
}

impl<'a, T, Tag, const MAX: u32, const N: usize> Vacant<'a, T, Tag, MAX, entries::Exclusive, N> {
    pub fn try_new(owner: &'a mut slab::Store<T, Tag, MAX, N>) -> Result<Self, slab::Vacancy> {
        Ok(Self::new(owner.core.try_free()?))
    }

    pub fn at(owner: &'a mut slab::Store<T, Tag, MAX, N>, index: u32) -> Option<Self> {
        Some(Self::new(owner.core.at(index)?))
    }

    pub fn in_range(
        owner: &'a mut slab::Store<T, Tag, MAX, N>,
        range: ops::Range<u32>,
    ) -> Option<Self> {
        Some(Self::new(owner.core.in_range(range)?))
    }

    pub fn try_split(self, key: key::Handle<Tag, MAX>) -> Split<'a, T, Tag, MAX, N> {
        let entry = slab::raw::Position::try_key(self.entry.core(), key)?;
        Ok((Vacant::new(self.entry), Occupied::new(entry.take())))
    }
}

impl<'a, T, Tag, const MAX: u32, M: entries::Mode, const N: usize, const ROOT: bool>
    Vacant<'a, T, Tag, MAX, M, N, ROOT, true>
{
    pub fn key(&self) -> key::Handle<Tag, MAX> {
        key::Handle::new(self.entry.index().raw(), self.entry.generation())
    }

    pub fn occupy(self, value: T) -> Occupied<'a, T, Tag, MAX, M, N, ROOT> {
        Occupied::new(self.entry.install(value))
    }
}

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

impl<'a, T, Tag, const MAX: u32, const N: usize>
    Vacant<'a, T, Tag, MAX, entries::Exclusive, N, false>
{
    /// # Safety
    /// No lookup may borrow this reservation or publish its key before it is consumed.
    pub unsafe fn try_reserve(
        owner: &'a slab::Store<T, Tag, MAX, N>,
    ) -> Result<Self, slab::Vacancy> {
        Ok(Self::new(owner.core.try_free()?))
    }
}
impl<'a, T, Tag, const MAX: u32> Vacant<'a, T, Tag, MAX, entries::Exclusive, 1, false> {
    /// # Safety
    /// This unchanged owner has a free slot; no lookup may borrow or publish the reservation.
    pub unsafe fn claim(owner: &'a slab::Store<T, Tag, MAX>) -> Self {
        let head = &owner.core.heads[0];
        // SAFETY: the original owner's nonempty head proves the index is not the sentinel.
        let index = unsafe { links::Index::new_raw(head.get()) };
        Self::new(unsafe { Free::take_head(&owner.core, head, index) })
    }
}
impl<'a, T, Tag, const MAX: u32, const N: usize, const ROOT: bool>
    Vacant<'a, T, Tag, MAX, entries::Exclusive, N, ROOT>
{
    /// # Safety
    /// This reservation contains a complete T without loans or another destruction or pin obligation.
    pub unsafe fn publish(self) -> (key::Handle<Tag, MAX>, &'a mut T) {
        let (key, entry) = unsafe { self.entry.publish_key() };
        (key, entry.into_mut())
    }
}

/// One initialized slot retaining its original pinned owner loan.
pub struct Anchored<
    'a,
    T,
    Tag = (),
    const MAX: u32 = { u32::MAX },
    const RECYCLE: bool = false,
    const N: usize = 1,
    S: slab::Storage = slab::Heap,
> where
    cycle::Mode<RECYCLE>: Policy,
{
    pub(in crate::depot) entry:
        slab::raw::Entry<'a, T, MAX, entries::Exclusive<RECYCLE>, N, S, true, false>,
    tag: marker::PhantomData<fn() -> Tag>,
}

impl<'a, T, Tag, const MAX: u32, const RECYCLE: bool, const N: usize, S>
    Anchored<'a, T, Tag, MAX, RECYCLE, N, S>
where
    cycle::Mode<RECYCLE>: Policy,
    S: slab::Storage,
{
    /// # Safety
    /// This initialized slot retains its original exclusive pinned store loan.
    pub(in crate::depot) unsafe fn pinned(
        entry: slab::raw::Entry<'a, T, MAX, entries::Exclusive<RECYCLE>, N, S, true, false>,
    ) -> Self {
        Self {
            entry,
            tag: marker::PhantomData,
        }
    }

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

    pub fn value(&mut self) -> Pin<&mut T> {
        // SAFETY: the occupied slot retains the value at its final address.
        unsafe { Pin::new_unchecked(self.entry.value_mut()) }
    }

    pub fn into_value(self) -> Pin<&'a mut T> {
        // SAFETY: the original exclusive pinned owner loan outlives this projection.
        unsafe { Pin::new_unchecked(self.entry.into_mut()) }
    }

    pub fn discard(self) {
        self.entry.issue();
    }

    /// # Safety
    /// This pinned value's destruction is complete and no value borrow remains.
    pub unsafe fn release(self) {
        unsafe { self.entry.release() };
    }
}

/// One reserved slot of a pinned store awaiting its first value.
pub struct Anchor<
    'a,
    T,
    Tag = (),
    const MAX: u32 = { u32::MAX },
    const RECYCLE: bool = false,
    const N: usize = 1,
    S: slab::Storage = slab::Heap,
> where
    cycle::Mode<RECYCLE>: Policy,
{
    pub(in crate::depot) entry:
        slab::raw::Entry<'a, T, MAX, entries::Exclusive<RECYCLE>, N, S, false, false>,
    tag: marker::PhantomData<fn() -> Tag>,
}

impl<'a, T, Tag, const MAX: u32, const RECYCLE: bool, const N: usize, S>
    Anchor<'a, T, Tag, MAX, RECYCLE, N, S>
where
    cycle::Mode<RECYCLE>: Policy,
    S: slab::Storage,
{
    /// # Safety
    /// The original exclusive store loan remains pinned for this lifetime.
    pub(in crate::depot) unsafe fn pinned(
        entry: slab::raw::Entry<'a, T, MAX, entries::Exclusive<RECYCLE>, N, S, false, false>,
    ) -> Self {
        Self {
            entry,
            tag: marker::PhantomData,
        }
    }

    pub fn index(&self) -> u32 {
        self.entry.index().raw()
    }

    pub fn insert(self, value: T) -> key::Handle<Tag, MAX> {
        self.occupy(value).0
    }

    pub fn uninit(&mut self) -> &mut mem::MaybeUninit<T> {
        self.entry.uninit()
    }

    pub fn occupy(
        mut self,
        value: T,
    ) -> (
        key::Handle<Tag, MAX>,
        Anchored<'a, T, Tag, MAX, RECYCLE, N, S>,
    ) {
        self.uninit().write(value);
        // SAFETY: this exact reserved value is initialized without outstanding loans.
        unsafe { self.publish() }
    }

    /// # Safety
    /// This exact reservation is initialized, unborrowed, and was not previously pinned.
    pub unsafe fn publish(
        self,
    ) -> (
        key::Handle<Tag, MAX>,
        Anchored<'a, T, Tag, MAX, RECYCLE, N, S>,
    ) {
        // SAFETY: the initialized reservation retains its original pinned owner.
        let (key, entry) = unsafe { self.entry.publish_key() };
        (key, unsafe { Anchored::pinned(entry) })
    }
}

/// The admitted physical row, its dense prefix and the free-list owner.
pub struct Retirement<
    'a,
    T,
    const MAX: u32,
    M: entries::Mode,
    const N: usize,
    S: slab::Storage,
    const LIVE: bool,
> {
    core: &'a Core<T, MAX, M, N, S>,
    index: links::Index,
    slot: &'a slab::Slot<T, MAX, M>,
}

impl<'a, T, const MAX: u32, M: entries::Mode, const N: usize, S: slab::Storage, const LIVE: bool>
    Retirement<'a, T, MAX, M, N, S, LIVE>
{
    pub(in crate::depot::arena::slab) fn new(
        position: &Position<'a, T, MAX, M, N, S, LIVE>,
    ) -> Self {
        Self {
            core: position.core(),
            index: position.index(),
            slot: position.slot(),
        }
    }

    // SAFETY: this member is live and this operation owns its removal.
    pub(super) unsafe fn unlink(&self) {
        let core = self.core;
        let plane = &core.slots;
        let pos = self.slot.metadata.position.get();
        let tail = core.live.get().wrapping_sub(1);
        if pos != tail {
            let dense = plane.tail();
            // SAFETY: both positions belong to the initialized prefix; last is its original slot.
            unsafe {
                let last = dense.get_unchecked(tail as usize).get().assume_init();
                dense
                    .get_unchecked(pos as usize)
                    .set(MaybeUninit::new(last));
                plane
                    .as_ref()
                    .get_unchecked(last as usize)
                    .metadata
                    .position
                    .set(pos);
            }
        }
        core.live.set(tail);
    }

    // SAFETY: this operation owns retirement; the payload and its loans have ended.
    pub(super) unsafe fn recycle<const ISSUED: bool>(self) {
        let slot = self.slot;
        if ISSUED {
            if LIVE {
                unsafe { self.unlink() };
            }
            match <M::Cycle as Policy>::next::<MAX>(slot.metadata.generation.get()) {
                Ok(epoch) => slot.metadata.generation.set(epoch),
                Err(retired) => {
                    slot.metadata.state.set(slab::State::Retired(retired));
                    if let Some(count) = self.core.slots.retired() {
                        count.set(count.get().wrapping_add(1));
                    }
                    return;
                }
            }
        }
        let index = self.index.raw();
        let head = self.core.partition(index).replace(index);
        // SAFETY: this non-value slot and the previous free head belong to this chain.
        unsafe {
            slot.set_links(depot::raw::SlabLinks {
                next: head,
                prev: links::Index::END,
            });
            slot.metadata.state.set(slab::State::Free);
            if head != links::Index::END {
                self.core
                    .slots
                    .as_ref()
                    .get_unchecked(head as usize)
                    .set_prev(index);
            }
        }
    }
}

impl<T, G: Step>
    Retirement<'_, external::Stamped<T, G>, 1, entries::Exclusive<true>, 1, slab::Lazy, true>
{
    pub(in crate::depot::arena::slab) fn payload(
        slot: &slab::Slot<external::Stamped<T, G>, 1, entries::Exclusive<true>>,
    ) -> *mut T {
        // SAFETY: the original pinned allocation retains the complete stamped payload.
        unsafe { ptr::addr_of_mut!((*slot.value_ptr()).value) }
    }

    pub fn as_mut_ptr(&mut self) -> *mut T {
        Self::payload(self.slot)
    }

    /// # Safety
    /// T's destruction is complete and no value borrow or pin obligation remains.
    pub unsafe fn release(self) {
        unsafe { self.recycle::<true>() };
    }
}