o3 0.61.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
//! Allocation-neutral lifecycle for lazily initialized linked slots.

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

use crate::{
    alloc,
    base::num::bounded,
    depot::{
        arena::linked::{self, fifo, slots},
        capacity,
    },
};

/// Access to one exact linked-slot region without owning its allocation.
#[derive(Debug)]
pub struct Store<T> {
    slots: ptr::NonNull<mem::MaybeUninit<slots::Node<T>>>,
    capacity: slots::Capacity<T>,
    initialized: cell::Cell<u32>,
    free: cell::Cell<u32>,
    pub(in crate::depot) available: cell::Cell<u32>,
    ownership: marker::PhantomData<T>,
}

/// Moving the descriptor preserves its region pointer and resident addresses.
impl<T> Unpin for Store<T> {}

impl<T> Store<T> {
    pub(crate) const END: u32 = u32::MAX;

    /// # 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 new(
        base: ptr::NonNull<slots::Node<T>>,
        capacity: slots::Capacity<T>,
    ) -> Self {
        Self {
            slots: base.cast(),
            capacity,
            initialized: cell::Cell::new(0),
            free: cell::Cell::new(Self::END),
            available: cell::Cell::new(capacity.get()),
            ownership: marker::PhantomData,
        }
    }

    pub const fn capacity(&self) -> slots::Capacity<T> {
        self.capacity
    }

    pub const fn pointer(&self) -> ptr::NonNull<Node<T>> {
        self.slots.cast()
    }

    /// # Safety
    /// `index` is below this region's initialized prefix.
    pub(crate) unsafe fn slot(&self, index: u32) -> &slots::Node<T> {
        unsafe { (&*self.slots.as_ptr().add(index as usize)).assume_init_ref() }
    }

    pub(crate) fn available(&self) -> usize {
        self.available.get() as usize
    }

    /// Returns this store's already-debited slot credits.
    pub(super) fn refund(&self, count: u32) {
        self.available.set(self.available.get().wrapping_add(count));
    }

    pub(crate) fn check(&self, count: capacity::Count) -> Result<(), capacity::Shortage> {
        let room = self.available.get();
        if count.raw() > room {
            return Err(capacity::Shortage {
                // SAFETY: demand exceeding the available count is nonzero.
                requested: unsafe { NonZero::new_unchecked(count.get()) },
                available: room as usize,
            });
        }
        Ok(())
    }

    pub(in crate::depot::arena::linked) fn debit(&self, count: capacity::Count) {
        self.available
            .set(self.available.get().wrapping_sub(count.raw()));
    }

    /// # Safety
    /// One slot was debited. A supplied link names the final successor in this store
    /// or its end. In that case initialize the returned slot immediately.
    #[inline(always)]
    pub(in crate::depot::arena::linked) unsafe fn claim<Tag>(
        &self,
        successor: Option<slots::Index<Tag>>,
    ) -> (slots::Index<Tag>, *mut mem::MaybeUninit<T>) {
        let successor = successor.map(slots::Index::raw);
        let free = self.free.get();
        let (index, node) = if free == Self::END {
            let index = self.initialized.get();
            let node = unsafe { self.slots.as_ptr().add(index as usize) };
            unsafe {
                node.write(mem::MaybeUninit::new(slots::Node::vacant(
                    successor.unwrap_or(index),
                )))
            };
            self.initialized.set(index + 1);
            (index, unsafe { (&*node).assume_init_ref() })
        } else {
            let node = unsafe { self.slot(free) };
            self.free.set(node.next.replace(successor.unwrap_or(free)));
            (free, node)
        };
        (slots::Index::new(index), node.value.get())
    }

    pub(super) fn recycle(&self, index: u32, node: &slots::Node<T>, refund: bool) {
        node.next.set(self.free.replace(index));
        if refund {
            self.refund(1);
        }
    }

    /// # Safety
    /// The caller solely owns this detached live slot with this exact TRACK policy.
    pub(crate) unsafe fn take<Tag, const TRACK: bool>(&self, index: slots::Index<Tag>) -> T {
        let node = unsafe { self.slot(index.raw()) };
        let value = unsafe { (&*node.value.get()).assume_init_read() };
        self.recycle(index.raw(), node, TRACK);
        value
    }

    pub(crate) fn vacant<Tag>(&self) -> Option<slots::Vacant<T, &'_ slots::Store<T>, Tag>> {
        // SAFETY: this store borrow uses tracked admission and return.
        unsafe { slots::Vacant::try_reserve(self) }
    }

    /// Returns one live slot's successor.
    /// # Safety
    /// `index` belongs to the calling topology in this region.
    pub(crate) unsafe fn next<Tag>(&self, index: slots::Index<Tag>) -> slots::Index<Tag> {
        unsafe { self.slot(index.raw()) }.next()
    }

    /// Replaces one live slot's successor.
    /// # Safety
    /// `index` is live and `next` is empty or live in the same topology domain.
    pub(crate) unsafe fn set_next<Tag>(&self, index: slots::Index<Tag>, next: slots::Index<Tag>) {
        unsafe { self.slot(index.raw()) }.next.set(next.raw());
    }

    /// Borrows one live value.
    /// # Safety
    /// The owner borrow prevents mutation or release of `index`.
    pub(crate) unsafe fn value<Tag>(&self, index: slots::Index<Tag>) -> &T {
        unsafe { &*self.value_ptr(index) }
    }

    /// Projects the address of one live value without creating a reference.
    /// # Safety
    /// `index` is live; reference aliases must derive from its exact owner.
    pub(crate) unsafe fn value_ptr<Tag>(&self, index: slots::Index<Tag>) -> *mut T {
        unsafe { self.slot(index.raw()) }.value_ptr()
    }

    /// Binds the sole detached live slot ownership to this store.
    /// # Safety
    /// `index` is absent from every owner topology and outstanding capability.
    pub(crate) unsafe fn detached<Tag>(
        &self,
        index: slots::Index<Tag>,
    ) -> slots::Live<T, &'_ slots::Store<T>, Tag> {
        unsafe { slots::Live::detached(self, index) }
    }

    /// # Safety
    /// Every live value is solely owned and every region loan has ended.
    /// Do not access any value through this store after this terminal operation.
    pub unsafe fn drop_values(&mut self) {
        if !mem::needs_drop::<T>() {
            return;
        }
        let mut free = self.free.get();
        while free != Self::END {
            let slot = unsafe { self.slot(free) };
            free = slot.next.replace(free);
        }
        for offset in 0..self.initialized.get() {
            let slot =
                unsafe { (&mut *self.slots.as_ptr().add(offset as usize)).assume_init_mut() };
            if slot.next.get() != offset {
                unsafe { (&mut *slot.value.get()).assume_init_drop() };
            }
        }
    }
}

impl<T> linked::Sealed<T> for &Store<T> {}

impl<T, Tag> slots::Reserve<T, &Store<T>, Tag> {
    /// # Safety
    /// `links` owns a complete nonempty chain of exactly the reserved length in
    /// a distinct source store. No other owner can access these nodes during the move.
    /// Conversion returns normally without observing or changing either store.
    pub(crate) unsafe fn move_from(
        self,
        source: &Store<impl Into<T>>,
        links: fifo::ends::Exclusive<slots::Index<Tag>>,
    ) -> fifo::ends::Exclusive<slots::Index<Tag>> {
        let mut output = fifo::ends::Exclusive::empty();
        // SAFETY: the entire input is transferred before the empty destination.
        unsafe {
            self.move_through::<false>(source, links.head_raw(), links.tail_raw(), &mut output)
        };
        output
    }

    /// # Safety
    /// The caller owns the inclusive nonempty source run in a distinct store and retains
    /// its suffix independently. The reservation covers exactly the run. The
    /// following partition belongs to the destination and has a tail when NONEMPTY.
    /// Conversion returns normally without observing or changing either store.
    pub(crate) unsafe fn move_through<const NONEMPTY: bool>(
        self,
        source: &Store<impl Into<T>>,
        head: slots::Index<Tag>,
        stop: slots::Index<Tag>,
        following: &mut fifo::ends::Exclusive<slots::Index<Tag>>,
    ) {
        let reserve = mem::ManuallyDrop::new(self);
        let store = reserve.owner;
        let after = following.head_raw();
        // SAFETY: the reservation covers the run and this is the store's current fresh frontier.
        let (first, last) = unsafe {
            store.move_run::<false, _>(
                source,
                (head, stop),
                after.raw(),
                reserve.remaining,
                store.initialized.get(),
            )
        };
        let tail = if !NONEMPTY && after == slots::Index::NONE {
            last
        } else {
            following.tail_raw()
        };
        // SAFETY: these ends now cover the transferred run and its original suffix.
        *following = unsafe { fifo::ends::Exclusive::from_ends(first, tail) };
    }
}

impl<T> Store<T> {
    /// # Safety
    /// The distinct source owns this inclusive run of exactly `count` live slots. The target
    /// has admitted the run and its successor. In a private build `fresh` is its next unwritten
    /// slot and the caller publishes the prefix. Otherwise the reservation has debited the store.
    /// Conversion returns normally without observing or changing either store.
    #[inline]
    pub(crate) unsafe fn move_run<const PRIVATE: bool, Tag>(
        &self,
        source: &Store<impl Into<T>>,
        (head, stop): (slots::Index<Tag>, slots::Index<Tag>),
        after: u32,
        count: u32,
        fresh: u32,
    ) -> (slots::Index<Tag>, slots::Index<Tag>) {
        let end = Self::END;
        let input = source.slots.as_ptr();
        let output = self.slots.as_ptr().cast::<Node<T>>();
        let mut free = if PRIVATE { end } else { self.free.get() };
        let first = if free == end { fresh } else { free };
        let head = head.raw();
        let stop = stop.raw();
        let mut read = head;
        let (last, tail) = 'moved: {
            if free != end {
                loop {
                    // SAFETY: these distinct live and free partitions own the two slots.
                    let from = unsafe { (&*input.add(read as usize)).assume_init_ref() };
                    let to = unsafe { &*output.add(free as usize) };
                    unsafe { to.value_ptr().write(from.value_ptr().read().into()) };
                    let next = to.next.get();
                    if read == stop {
                        if next != after {
                            to.next.set(after);
                        }
                        self.free.set(next);
                        break 'moved (free, &from.next);
                    }
                    read = from.next.get();
                    if next == end {
                        to.next.set(fresh);
                        self.free.set(end);
                        break;
                    }
                    free = next;
                }
            }
            let mut index = fresh;
            loop {
                // SAFETY: each remaining source slot owns one value and the reservation
                // covers the same number of uninitialized destination slots.
                let from = unsafe { (&*input.add(read as usize)).assume_init_ref() };
                let next = index + 1;
                unsafe {
                    Node::write(
                        output.add(index as usize),
                        from.value_ptr().read().into(),
                        if read == stop { after } else { next },
                    )
                };
                if read == stop {
                    if !PRIVATE {
                        self.initialized.set(next);
                    }
                    break 'moved (index, &from.next);
                }
                read = from.next.get();
                index = next;
            }
        };
        // The emptied source chain is already linked in reusable order.
        tail.set(source.free.replace(head));
        source.refund(count);
        (slots::Index::new(first), slots::Index::new(last))
    }
}

impl<T> linked::Source<T> for &Store<T> {
    fn store(&self) -> &Store<T> {
        self
    }
}

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

#[repr(C)]
pub struct Node<T> {
    pub(super) value: cell::UnsafeCell<mem::MaybeUninit<T>>,
    pub(super) 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) -> slots::Index<Tag> {
        slots::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.
    #[inline]
    pub(crate) unsafe fn parts(node: *mut Self) -> (*mut T, *mut u32) {
        // Both cells and MaybeUninit are transparent over their contents.
        unsafe {
            (
                (&raw mut (*node).value).cast(),
                (&raw mut (*node).next).cast(),
            )
        }
    }

    /// # Safety
    /// The caller owns this uninitialized slot and establishes its successor before publication.
    #[inline]
    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::U32<0, { u32::MAX - 1 }>,
    value: marker::PhantomData<fn(T) -> T>,
}

impl<T> Capacity<T> {
    pub fn new(capacity: usize) -> Result<Self, alloc::Overflow> {
        let raw = bounded::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>());

impl<T> Store<T> {
    pub(in crate::depot) fn permit<Tag>(&mut self) -> Option<slots::Permit<'_, T, Tag>> {
        if self.available() == 0 {
            return None;
        }
        Some(slots::Permit::new(self))
    }
}

impl<T> Store<T> {
    /// # Safety
    /// `back` remains live in this exact exclusively borrowed node set.
    pub(in crate::depot) unsafe fn back_mut<Tag>(&mut self, back: fifo::Back<Tag>) -> &mut T {
        unsafe { &mut *self.value_ptr(back.into_index()) }
    }
}