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
use crate::{
    alloc,
    base::num::bounded,
    depot::{
        self,
        arena::linked::{self, fifo, head},
    },
};
use std::{cell, marker, mem, ptr};

mod batch;
mod fixed;
mod index;
mod live;
mod reserve;
mod store;
mod vacant;

pub use batch::Batch;
pub use fixed::Fixed;
pub use index::Index;
pub use live::Live;
pub use reserve::Reserve;
pub use store::Store;
pub use vacant::Vacant;

pub struct Released;

#[repr(C)]
pub struct Node<T> {
    pub(in crate::depot::arena::linked) value: cell::UnsafeCell<mem::MaybeUninit<T>>,
    pub(in crate::depot::arena::linked) next: cell::Cell<u32>,
}

impl<T> Node<T> {
    pub(crate) fn value_ptr(&self) -> *mut T {
        self.value.get().cast()
    }

    pub(crate) fn next<Tag>(&self) -> Index<Tag> {
        Index::new(self.next.get())
    }

    /// # Safety
    /// The caller exclusively initializes this unpublished slot. Its value and link
    /// must both be initialized before extending the live prefix.
    pub(crate) unsafe fn parts(node: *mut Self) -> (*mut T, *mut u32) {
        unsafe {
            (
                (&raw mut (*node).value).cast(),
                (&raw mut (*node).next).cast(),
            )
        }
    }

    /// # Safety
    /// The caller owns this uninitialized slot and establishes its next before publication.
    pub(crate) unsafe fn write(node: *mut Self, value: T, next: u32) {
        let (slot, link) = unsafe { Self::parts(node) };
        unsafe {
            slot.write(value);
            link.write(next);
        }
    }

    pub(crate) const fn vacant(index: u32) -> Self {
        Self {
            value: cell::UnsafeCell::new(mem::MaybeUninit::uninit()),
            next: cell::Cell::new(index),
        }
    }
}

/// A slot count whose exact allocation layout has been validated.
#[repr(transparent)]
#[derive(Debug)]
pub struct Capacity<T> {
    /// The absent-link sentinel is excluded from every admitted extent.
    raw: bounded::raw::U32<0, { u32::MAX - 1 }>,
    value: marker::PhantomData<fn(T) -> T>,
}

impl<T> Capacity<T> {
    /// # Safety
    /// The base owns this admitted uninitialized extent and outlives every store loan.
    /// Destroy its live values before returning the allocation.
    pub const unsafe fn bind(self, base: ptr::NonNull<Node<T>>) -> Store<T> {
        Store {
            slots: base.cast(),
            capacity: self,
            initialized: cell::Cell::new(0),
            free: cell::Cell::new(Store::<T>::END),
            available: cell::Cell::new(self.get()),
            ownership: marker::PhantomData,
        }
    }

    pub fn new(capacity: usize) -> Result<Self, alloc::Overflow> {
        let raw = bounded::raw::U32::from_usize(capacity).ok_or(alloc::Overflow)?;
        alloc::raw::Layout::<Node<T>>::try_layout(raw.into_usize())?;
        Ok(Self {
            raw,
            value: marker::PhantomData,
        })
    }

    pub(crate) const fn get(self) -> u32 {
        self.raw.get()
    }

    pub(crate) const fn len(self) -> usize {
        self.raw.get() as usize
    }

    pub fn bundle(self) -> alloc::raw::Bundle<alloc::raw::Layout<Node<T>>> {
        use alloc::raw::Bundle;

        unsafe { Bundle::root::<Node<T>>(self.len()) }
    }
}

impl<T> Clone for Capacity<T> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<T> Copy for Capacity<T> {}

const _: () = assert!(mem::size_of::<Capacity<u64>>() == mem::size_of::<u32>());
const _: () = assert!(mem::size_of::<Node<u64>>() == 2 * mem::size_of::<u64>());

#[must_use = "a detached slot retains its sole return entitlement"]
struct Slot<T, H: linked::Source<T>, Tag, const LIVE: bool> {
    owner: H,
    index: Index<Tag>,
    value: marker::PhantomData<T>,
}

impl<T, H: linked::Source<T>, Tag, const LIVE: bool> Slot<T, H, Tag, LIVE> {
    /// # Safety
    /// The owner retains one debit without loans and a vacant or initialized node.
    unsafe fn new(owner: H, index: Index<Tag>) -> Self {
        Self {
            owner,
            index,
            value: marker::PhantomData,
        }
    }

    /// # Safety
    /// Transfer the slot, its initialization state and its sole return right to
    /// the original topology or reservation before exposing it to another caller.
    unsafe fn into_parts(self) -> (H, Index<Tag>) {
        let slot = mem::ManuallyDrop::new(self);
        (unsafe { ptr::read(&slot.owner) }, slot.index)
    }
}

impl<T, H: linked::Source<T>, Tag, const LIVE: bool> Drop for Slot<T, H, Tag, LIVE> {
    fn drop(&mut self) {
        let store = self.owner.store();
        let index = self.index.raw();
        let node = unsafe { store.slot(index) };
        if LIVE {
            // SAFETY: this slot retains the value and its address throughout destruction.
            unsafe { (&mut *node.value.get()).assume_init_drop() };
        }
        store.recycle(index, node, H::TRACK);
    }
}

/// Exclusive proof that one exact node set has insertion capacity.
#[must_use]
pub struct Permit<'a, T, Tag> {
    pub(in crate::depot::arena::linked) store: &'a mut Store<T>,
    domain: marker::PhantomData<fn(Tag) -> Tag>,
}

impl<'a, T, Tag> Permit<'a, T, Tag> {
    pub(in crate::depot) fn try_new(store: &'a mut Store<T>) -> Option<Self> {
        if store.available() == 0 {
            return None;
        }
        Some(Self {
            store,
            domain: marker::PhantomData,
        })
    }

    /// Initializes the slot proved available by this permit.
    pub fn claim(self, value: T) -> Live<T, &'a Store<T>, Tag> {
        unsafe { Vacant::insert_one::<0>(&*self.store, value) }
    }
}

const _: () = {
    assert!(mem::size_of::<Permit<'_, u64, ()>>() == mem::size_of::<usize>());
    assert!(mem::size_of::<Option<Permit<'_, u64, ()>>>() == mem::size_of::<usize>());
    assert!(mem::size_of::<Vacant<u64, &'_ Store<u64>, ()>>() == 2 * mem::size_of::<usize>());
    assert!(mem::size_of::<Live<u64, &'_ Store<u64>, ()>>() == 2 * mem::size_of::<usize>());
};

/// A store borrow whose accounting is fixed by its exclusive topology owner.
pub struct Borrow<'a, T, const TRACK: bool>(pub(crate) &'a Store<T>);

// SAFETY: topology owners keep this fixed policy from insertion through removal.
impl<T, const TRACK: bool> linked::Sealed<T> for Borrow<'_, T, TRACK> {}

impl<T, const TRACK: bool> linked::Source<T> for Borrow<'_, T, TRACK> {
    const TRACK: bool = TRACK;

    fn store(&self) -> &Store<T> {
        self.0
    }
}

pub struct Bound<'a, T, Tag = (), const TRACK: bool = true> {
    store: &'a Store<T>,
    state: &'a mut fifo::Fifo<Tag>,
}

impl<'a, T, Tag, const TRACK: bool> Bound<'a, T, Tag, TRACK> {
    /// # Safety
    /// The state owns this store's live partition under its unchanged TRACK policy.
    pub unsafe fn new(state: &'a mut fifo::Fifo<Tag>, store: &'a Store<T>) -> Self {
        Self { store, state }
    }
}

impl<T, Tag, const TRACK: bool> linked::Sealed<T> for Bound<'_, T, Tag, TRACK> {}

impl<T, Tag, const TRACK: bool> linked::Source<T> for Bound<'_, T, Tag, TRACK> {
    const TRACK: bool = TRACK;

    fn store(&self) -> &Store<T> {
        self.store
    }
}

impl<T, Tag, const TRACK: bool> Bound<'_, T, Tag, TRACK> {
    pub fn pop_front(&mut self) -> Option<T> {
        let index = self.state.links.head()?;
        Some(unsafe { index.pop::<_, TRACK>(self.state, self.store) })
    }
}

impl<'a, T, Tag> Bound<'a, T, Tag> {
    /// # Safety
    /// `index` is the unchanged front of this bound queue.
    pub(in crate::depot) unsafe fn detach(self, index: Index<Tag>) -> Live<T, Self, Tag> {
        unsafe { index.unlink(self.state, self.store) };
        unsafe { Live::detached(self, index) }
    }

    pub fn front_entry(self) -> Option<Front<'a, T, Tag>> {
        let index = self.state.links.head()?;
        Some(Front { owner: self, index })
    }
}

pub struct Front<'a, T, Tag> {
    owner: Bound<'a, T, Tag>,
    index: Index<Tag>,
}

impl<T, Tag> Front<'_, T, Tag> {
    pub fn get_mut(&mut self) -> &mut T {
        // SAFETY: this entry's exclusive owner borrow is the capability for
        // the unchanged front slot; the returned borrow cannot outlive `self`.
        unsafe { &mut *self.owner.store.value_ptr(self.index) }
    }

    pub fn discard(self) {
        drop(unsafe { self.owner.detach(self.index) });
    }
}

const _: () = assert!(mem::size_of::<Front<'_, u64, ()>>() == 3 * mem::size_of::<usize>());

/// Insertion cursor with only predecessor and current positions.
pub struct Cursor<'a, T, Tag> {
    store: &'a Store<T>,
    state: &'a mut head::List<Tag>,
    previous: Index<Tag>,
    current: Index<Tag>,
}

impl<'a, T, Tag> Cursor<'a, T, Tag> {
    /// # Safety
    /// The state owns one acyclic live partition in this exact store.
    pub(in crate::depot::arena::linked) const unsafe fn new(
        store: &'a Store<T>,
        state: &'a mut head::List<Tag>,
    ) -> Self {
        Self {
            store,
            current: state.head,
            state,
            previous: Index::NONE,
        }
    }

    pub fn current(&self) -> Option<&T> {
        let current = self.current;
        if current == Index::NONE {
            return None;
        }
        Some(unsafe { self.store.value(current) })
    }

    pub fn advance(&mut self) {
        let current = self.current;
        if current.get().is_none() {
            return;
        }
        self.previous = current;
        self.current = unsafe { self.store.next(current) };
    }

    /// Publishes the initialized detached claim into its proved original node set.
    pub fn insert(proof: Member<'_, 'a, Self, T, Tag>) {
        let (cursor, claim) = proof.into_inner();
        let inserted = unsafe { claim.into_index() };
        unsafe { cursor.store.set_next(inserted, cursor.current) };
        if cursor.previous.get().is_none() {
            cursor.state.head = inserted;
        } else {
            unsafe { cursor.store.set_next(cursor.previous, inserted) };
        }
        cursor.previous = inserted;
    }
}

const _: () = assert!(mem::size_of::<Cursor<'_, u64, ()>>() == 3 * mem::size_of::<usize>());

type Member<'s, 'a, S, T, Tag> =
    depot::raw::Proof<(&'s mut S, Live<T, &'a Store<T>, Tag>), linked::Same>;

pub(crate) struct Drain<'a, T, Tag = ()> {
    store: &'a Store<T>,
    next: Index<Tag>,
}

impl<'a, T, Tag> Drain<'a, T, Tag> {
    /// # Safety
    /// Transfer the complete, disjoint, tracked partition starting at `next` in this store.
    pub(crate) unsafe fn new(store: &'a Store<T>, next: Index<Tag>) -> Self {
        Self { store, next }
    }
}

impl<'a, T, Tag> Iterator for Drain<'a, T, Tag> {
    type Item = Live<T, &'a Store<T>, Tag>;

    fn next(&mut self) -> Option<Self::Item> {
        let head = self.next;
        head.get()?;
        // SAFETY: keep the next before transferring this initialized slot and its return right.
        self.next = unsafe { self.store.next(head) };
        Some(unsafe { Live::detached(self.store, head) })
    }
}

impl<T, Tag> Drop for Drain<'_, T, Tag> {
    fn drop(&mut self) {
        for _ in self {}
    }
}

/// The unchanged list front tied to its store and owner borrows.
#[must_use]
pub struct Entry<'a, 'b, T, Tag> {
    store: &'a Store<T>,
    state: &'b mut head::List<Tag>,
}

impl<'a, 'b, T, Tag> Entry<'a, 'b, T, Tag> {
    /// # Safety
    /// The state owns a nonempty acyclic live partition in this exact store.
    pub(in crate::depot::arena::linked) const unsafe fn new(
        store: &'a Store<T>,
        state: &'b mut head::List<Tag>,
    ) -> Self {
        Self { store, state }
    }

    pub fn get(&self) -> &T {
        unsafe { self.store.value(self.state.head) }
    }

    fn unlink(&mut self) -> Index<Tag> {
        let index = self.state.head;
        self.state.head = unsafe { self.store.next(index) };
        index
    }

    pub fn pop(mut self) -> T {
        let index = self.unlink();
        // SAFETY: this detached list head owns its value and its tracked credit.
        unsafe { self.store.take::<_, true>(index) }
    }

    pub fn take(mut self) -> (T, Vacant<T, &'a Store<T>, Tag>) {
        let index = self.unlink();
        unsafe { Live::detached(self.store, index) }.take()
    }
}

const _: () = assert!(mem::size_of::<Entry<'_, '_, u64, ()>>() == 2 * mem::size_of::<usize>());