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 std::{marker, mem::ManuallyDrop, num, ptr};

use crate::{
    alloc,
    buffer::{
        pool::{
            self,
            owners::{Edge, Header, Key, Plain, Resident, Shape, sealed},
            state,
        },
        resident, storage,
    },
    mem::rc,
};

/// The header and its initialized slot array. The resident account table is
/// unpublished until it receives its root debit.
pub(in crate::buffer::pool) struct Block<K: crate::buffer::raw::Backing, S> {
    base: ptr::NonNull<Header<K>>,
    tail: ptr::NonNull<Slot<K>>,
    state: marker::PhantomData<S>,
}

impl<K: crate::buffer::raw::Backing + Default, S: state::State> Block<K, S> {
    pub(super) fn allocate(shape: Shape<K>) -> Result<Self, alloc::Exhausted> {
        // SAFETY: Shape admits the complete nonempty allocation, header and slot array.
        let base = unsafe { alloc::raw::try_new::<Header<K>>(shape.allocation(), S::ZEROED) }?;
        let slots = shape.slots();
        // SAFETY: the allocation is exclusively held and still unpublished.
        let mut tail = unsafe {
            base.write(Header::new(shape));
            base.add(1).cast::<Slot<K>>()
        };
        for index in 0..slots {
            // SAFETY: each iteration initializes the next cell of the exact array.
            unsafe {
                tail.write(Slot {
                    prefix: storage::raw::Prefix::empty(sealed::link(index + 1, slots)),
                    backing: K::default(),
                });
                tail = tail.add(1);
            }
        }
        Ok(Self {
            base,
            tail,
            state: marker::PhantomData,
        })
    }
}

impl<L: Into<pool::Layout>, S: state::State> Block<Plain<L>, S>
where
    Plain<L>: crate::buffer::raw::Backing,
{
    pub(in crate::buffer::pool) fn try_new(
        layout: L,
    ) -> Result<Ptr<Plain<L>, S>, alloc::Exhausted> {
        let block = Self::allocate(Shape::new(layout))?;
        Ok(Ptr {
            raw: block.base,
            state: marker::PhantomData,
        })
    }
}

impl<S: state::State> Block<Plain<pool::Layout>, S> {
    pub(in crate::buffer::pool) fn try_seed(
        layout: pool::NonEmpty,
    ) -> Result<Seed<Plain<pool::Layout>, S>, alloc::Exhausted> {
        Ok(Seed(Self::try_new(layout.into_layout())?))
    }
}

impl<'d, S: state::State> Block<Resident<'d>, S> {
    pub(in crate::buffer::pool) fn try_seed(
        layout: pool::NonEmpty,
        budget: resident::Budget<'d>,
    ) -> Result<Seed<Resident<'d>, S>, resident::AllocError> {
        Ok(Seed(Self::try_new(layout.into(), budget)?))
    }

    pub(in crate::buffer::pool) fn try_new(
        tally: pool::Tally,
        budget: resident::Budget<'d>,
    ) -> Result<Ptr<Resident<'d>, S>, resident::AllocError> {
        let shape = Shape::<Resident<'d>>::try_new(tally).map_err(resident::AllocError::Layout)?;
        let (layout, limit) = tally.into_parts();
        let charge = budget
            .try_charge(layout.bytes())
            .map_err(resident::AllocError::Budget)?;
        let block = Self::allocate(shape).map_err(resident::AllocError::Exhausted)?;
        // SAFETY: the same tally supplied the account count, shape and complete debit.
        Ok(unsafe { block.account(charge, limit) })
    }

    /// # Safety
    /// The count and debit must be those admitted for this allocation.
    pub(super) unsafe fn account(
        self,
        charge: resident::Charge<'d>,
        limit: u32,
    ) -> Ptr<Resident<'d>, S> {
        // SAFETY: a resident shape places the account table immediately after the slots.
        unsafe {
            self.tail
                .cast::<super::Accounts<'d>>()
                .write(super::Accounts::new(charge, limit))
        };
        Ptr {
            raw: self.base,
            state: marker::PhantomData,
        }
    }
}

/// One freshly initialized nonempty free list before its first acquisition.
#[repr(transparent)]
pub(in crate::buffer::pool) struct Seed<K, S>(Ptr<K, S>);

impl<K: crate::buffer::raw::Backing, S> Seed<K, S> {
    /// # Safety
    /// This is a newly initialized nonempty pool with no published slot.
    pub(super) unsafe fn from_ptr(core: Ptr<K, S>) -> Self {
        Self(core)
    }

    pub(in crate::buffer::pool) fn take(self) -> pool::Span<K, pool::Owned, S> {
        // SAFETY: the first slot of this nonempty fresh list is zero.
        unsafe { self.0.take(Key::FIRST, self.0.header().balance.get() - 1) }
    }

    pub(in crate::buffer::pool) fn into_span(self) -> pool::Span<K, pool::Owned, S> {
        // SAFETY: the nonempty seed transfers its root to its first and only live slot.
        unsafe { self.0.take(Key::FIRST, -1) }
    }
}

#[repr(transparent)]
#[derive(Debug)]
pub struct Ptr<K, S = state::Uninit> {
    raw: ptr::NonNull<Header<K>>,
    state: marker::PhantomData<(K, S)>,
}

impl<K, S> Clone for Ptr<K, S> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<K, S> Copy for Ptr<K, S> {}

impl<K, S> Ptr<K, S> {
    pub(super) fn header(&self) -> &Header<K> {
        // SAFETY: every issuer retains the published pool for this borrow.
        unsafe { self.raw.as_ref() }
    }

    pub(in crate::buffer::pool) fn available(self) -> usize {
        self.header().balance.get() as usize
    }

    pub(in crate::buffer::pool) const fn erase_state(self) -> Ptr<K, pool::Frozen> {
        Ptr {
            raw: self.raw,
            state: marker::PhantomData,
        }
    }
}

impl<'d, S> Ptr<Resident<'d>, S> {
    pub(super) fn accounts(self) -> ptr::NonNull<super::Accounts<'d>> {
        // SAFETY: the resident table follows its complete initialized slot array.
        unsafe {
            self.raw
                .add(1)
                .cast::<Slot<Resident<'d>>>()
                .add(self.header().slots() as usize)
                .cast()
        }
    }
}

impl<K: crate::buffer::raw::Backing, S> Ptr<K, S> {
    pub(in crate::buffer::pool) fn acquire(self) -> Option<pool::Span<K, pool::Owned, S>> {
        let key = self.header().free.head()?;
        // SAFETY: the free head is consumed immediately without reentry.
        Some(unsafe { self.take(key, self.header().balance.get() - 1) })
    }

    /// # Safety
    /// The caller owns this free head and supplies the balance after acquiring
    /// it, including whether the root remains live.
    unsafe fn take(self, key: Key, balance: i64) -> pool::Span<K, pool::Owned, S> {
        use crate::mem::raw::Edge;

        let slot = self.slot(key);
        let header = self.header();
        // SAFETY: the vacant slot has no aliases until the span is published.
        unsafe {
            key.occupy(&header.free, &slot.prefix);
            if K::COUNTED {
                slot.activate();
            }
        }
        header.balance.set(balance);
        pool::Span {
            slots: self,
            key,
            len: 0,
            root: pool::Owned,
        }
    }

    pub(in crate::buffer::pool) fn data(self, key: Key) -> *mut u8 {
        let offset = self.data_offset().get() + key.get() as usize * self.capacity().get() as usize;
        // SAFETY: the published allocation contains every byte of this slot.
        unsafe { self.raw.as_ptr().cast::<u8>().add(offset) }
    }

    pub(in crate::buffer) unsafe fn deallocate(self) {
        let layout = Shape::from_ptr(self).allocation();
        // SAFETY: the terminal owner exclusively holds the allocation with its original layout.
        unsafe { alloc::raw::dealloc(layout, self.raw) };
    }

    pub(in crate::buffer::pool) fn capacity(self) -> num::NonZero<u32> {
        match K::CAPACITY {
            Some(capacity) => capacity,
            None => self.header().capacity(),
        }
    }

    pub(in crate::buffer::pool) fn slots(self) -> usize {
        match K::SLOTS {
            Some(slots) => slots as usize,
            None => self.header().slots() as usize,
        }
    }

    pub(super) fn data_offset(self) -> num::NonZero<usize> {
        match K::SLOTS {
            Some(slots) => pool::Layout::offset(slots),
            None => self.header().data_offset(),
        }
    }

    pub(in crate::buffer::pool) fn ptr(self, key: Key) -> ptr::NonNull<Slot<K>> {
        // SAFETY: this key was issued from the slot array after this exact header.
        unsafe { self.raw.add(1).cast::<Slot<K>>().add(key.get() as usize) }
    }

    pub(in crate::buffer::pool) fn slot(&self, key: Key) -> &Slot<K> {
        // SAFETY: the capability borrow retains this initialized slot.
        unsafe { self.ptr(key).as_ref() }
    }

    /// Detaches the root with a balance equal to the negated occupied count.
    pub(in crate::buffer::pool) fn release_root(self) {
        let balance = self.header().balance.get() - self.slots() as i64;
        // SAFETY: only the retiring Pool root issues this transition.
        unsafe { self.retire(balance) };
    }

    /// # Safety
    /// The retiring edge supplies the new balance. Zero retires the allocation.
    unsafe fn retire(self, balance: i64) {
        if balance == 0 {
            unsafe { K::release(self) };
        } else {
            self.header().balance.set(balance);
        }
    }
}

#[derive(Debug)]
#[repr(C, align(8))]
pub(in crate::buffer) struct Slot<K: crate::buffer::raw::Backing = Plain> {
    pub(super) prefix: storage::raw::Prefix,
    pub(super) backing: K,
}

impl<K: crate::buffer::raw::Backing> Slot<K> {
    /// # Safety
    /// This address is an active slot belonging to a published pool of this kind.
    pub(super) unsafe fn locate(pointer: ptr::NonNull<Self>) -> (Ptr<K, ()>, Key) {
        // SAFETY: the live prefix holds its exact slot index.
        let key = unsafe { Key::new(pointer.as_ref().prefix.word()) };
        let offset = size_of::<Header<K>>() + key.get() as usize * size_of::<Self>();
        // SAFETY: reversing this slot's actual offset retains the allocation's provenance.
        let raw = unsafe { pointer.cast::<u8>().sub(offset).cast() };
        (
            Ptr {
                raw,
                state: marker::PhantomData,
            },
            key,
        )
    }

    /// # Safety
    /// The prefix belongs to an active slot in the exact published backing.
    pub(in crate::buffer) unsafe fn capacity(pointer: ptr::NonNull<Self>) -> num::NonZero<u32> {
        unsafe { Self::locate(pointer) }.0.capacity()
    }

    /// # Safety
    /// The caller transfers one live edge at `core.ptr(key)`, the supplied slot.
    pub(in crate::buffer::pool) unsafe fn release<S>(
        slot: ptr::NonNull<Self>,
        core: Ptr<K, S>,
        key: Key,
    ) {
        use crate::mem::raw::Edge;

        // SAFETY: the caller owns this edge; only a counted backing can have aliases.
        if K::COUNTED && unsafe { slot.as_ref().release() } != rc::Release::Last {
            return;
        }
        // SAFETY: all counted aliases are gone or the span was already exclusive.
        unsafe { Self::recycle(slot, core, key) };
    }

    unsafe fn recycle<S>(slot: ptr::NonNull<Self>, core: Ptr<K, S>, key: Key) {
        let header = core.header();
        let balance = header.balance.get() + 1;
        if balance > 0 {
            // SAFETY: the root can acquire again only in this case. The last
            // edge owns this prefix until it is published on the free list.
            unsafe { key.recycle(&header.free, &slot.as_ref().prefix) };
        }
        // SAFETY: an attached pool has a positive balance after this return.
        // For a detached pool, zero means the last occupied slot has returned.
        unsafe { core.retire(balance) };
    }
}

// SAFETY: each slot retains the count embedded in its prefix.
unsafe impl<K: crate::buffer::raw::Backing> crate::mem::raw::Edge for Slot<K> {
    fn count(&self) -> &crate::mem::raw::Count {
        crate::mem::raw::Edge::count(&self.prefix)
    }
}

// SAFETY: the last edge retains its exact allocation through slot recycling.
unsafe impl<K: crate::buffer::raw::Backing> crate::mem::raw::Target for Slot<K> {
    unsafe fn destroy(slot: ptr::NonNull<Self>) {
        // SAFETY: the transferred terminal slot still contains its published key.
        unsafe {
            let (core, key) = Self::locate(slot);
            Self::recycle(slot, core, key);
        }
    }
}

// SAFETY: the cloned owner retains this slot with the same backing and root mode.
unsafe impl<K: crate::buffer::raw::Backing, M> crate::buffer::raw::Retain for Edge<K, M> {
    fn try_retain(&self) -> Result<Self, rc::Error> {
        Ok(Self {
            slot: self.slot.try_clone()?,
            mode: marker::PhantomData,
        })
    }
}

impl<K: crate::buffer::raw::Backing> Slot<K> {
    pub(super) fn resident<M>(edge: &Edge<K, M>) -> usize {
        // SAFETY: this owner retains the original published slot pointer.
        unsafe { Self::capacity(edge.slot.as_ptr()) }.get() as usize
    }

    pub(super) fn share<M, S>(span: pool::Span<K, M, S>) -> Edge<K, M> {
        use crate::mem::raw::Edge as _;

        let span = ManuallyDrop::new(span);
        let slot = span.slots.ptr(span.key);
        // SAFETY: a counted span transfers its live edge. An exclusive uncounted
        // span establishes that edge before publishing the same slot and root mode.
        unsafe {
            if !K::COUNTED {
                slot.as_ref().activate();
            }
            Edge {
                slot: crate::mem::raw::Owner::from_raw(slot),
                mode: marker::PhantomData,
            }
        }
    }
}

const _: () = {
    assert!(size_of::<Plain>() == 0);
    assert!(size_of::<Resident<'_>>() == size_of::<u32>());
    assert!(size_of::<Option<Edge>>() == size_of::<usize>());
    assert!(size_of::<Option<Edge<Plain, pool::Borrowed<'_>>>>() == size_of::<usize>());
    assert!(size_of::<Option<Edge<Resident<'_>>>>() == size_of::<usize>());
    assert!(size_of::<Slot>() == 8);
    assert!(size_of::<Slot<Resident<'static>>>() == 16);
    assert!(align_of::<Slot>() == 8);
    assert!(size_of::<Seed<Plain, state::Uninit>>() == size_of::<usize>());
    assert!(size_of::<(Ptr<Plain, ()>, Key)>() == 2 * size_of::<usize>());
    assert!(size_of::<(Ptr<Resident<'_>, ()>, Key)>() == 2 * size_of::<usize>());
    assert!(size_of::<Block<Plain<pool::Fixed<1, 1>>, state::Uninit>>() == 2 * size_of::<usize>());
    assert!(size_of::<Block<Plain<pool::Layout>, state::Uninit>>() == 2 * size_of::<usize>());
    assert!(size_of::<Block<Plain<pool::Width<1>>, state::Uninit>>() == 2 * size_of::<usize>());
    assert!(size_of::<Block<Resident<'_>, state::Uninit>>() == 2 * size_of::<usize>());
    assert!(size_of::<Ptr<Plain>>() == size_of::<usize>());
    assert!(size_of::<Ptr<Resident<'static>>>() == size_of::<usize>());
};