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
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
use crate::{
    alloc::{self, tail},
    base::cell::region,
    buffer::{self, resident, storage::provided::view},
    mem::{self, Rejected, slot},
};
use std::{
    cell, marker,
    mem::{ManuallyDrop, MaybeUninit, align_of, needs_drop, offset_of, size_of},
    num::NonZeroU32,
    pin, ptr,
    slice::Iter,
};

mod domain;
mod layout;
mod owner;
mod slice;

pub use layout::Layout;
pub use owner::Owner;
pub use slice::Slice;
pub(super) type Loan<'d, L = cell::Cell<u32>> = Slice<&'d mut [u8], Owner<'d, L>>;

use domain::{Data, Phase};
pub(super) use domain::{Domain, Entry};

type Link<L> = ptr::NonNull<Entry<L>>;
struct Node<'d, L: Layout, const READY: bool> {
    entry: Link<L>,
    scope: marker::PhantomData<fn(&'d L) -> &'d L>,
}
type Empty<'d, L> = Node<'d, L, false>;
type Ready<'d, L> = Node<'d, L, true>;

/// Inactive allocation; no item or charge exists outside its private scope.
#[repr(transparent)]
pub struct Arena<T, C = (), L: Layout = cell::Cell<u32>> {
    entries: tail::raw::Block<InactiveHeader<C, L>, MaybeUninit<Slot<T, L>>, NonZeroU32>,
}

#[repr(C)]
struct Header<C, S> {
    state: S,
    context: C,
}

type InactiveHeader<C, L> = Header<C, MaybeUninit<State<L>>>;
type ActiveHeader<C, L> = Header<C, State<L>>;

pub struct Scope<'d, T, L: Layout> {
    scope: marker::PhantomData<fn(&'d ()) -> &'d ()>,
    slots: Iter<'d, Slot<T, L>>,
}

/// All slots are occupied or awaiting return to this arena's free list.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct Full {
    pub capacity: NonZeroU32,
}

pub struct Allocation<T, C, L: Layout> {
    memory: tail::raw::Uninit<InactiveHeader<C, L>, Slot<T, L>, NonZeroU32>,
}

impl<T, C, L: Layout> Arena<T, C, L> {
    /// Allocates the exact arena before its context is constructed.
    pub fn try_allocate(entries: NonZeroU32) -> Result<Allocation<T, C, L>, alloc::Error> {
        Ok(Allocation {
            memory: tail::Plan::try_new(entries)?.try_allocate()?,
        })
    }

    pub fn context(&self) -> &C {
        &tail::raw::View::new(&self.entries).header().context
    }
    pub fn capacity(&self) -> NonZeroU32 {
        self.entries.extent()
    }
    pub fn into_context(self) -> C {
        self.entries.into_header().context
    }

    fn scope_in<S, R>(
        &mut self,
        state: pin::Pin<&mut S>,
        resident: L::Shared,
        run: impl for<'d> FnOnce(
            region::Token<region::Identity<'d>>,
            Root<'d, T, C, L>,
            pin::Pin<&'d mut S>,
        ) -> R,
    ) -> R {
        let mut input = (self, state);
        region::Token::scope_pinned(pin::Pin::new(&mut input), |token, input| {
            let (arena, state) = input.get_mut();
            // SAFETY: the complete generative call borrows this inactive allocation;
            // the hidden scope reclaims every issued capability before it returns.
            let root = unsafe { arena.prepare(arena.capacity().get(), resident) };
            let scope = root.scope();
            let result = run(token, root, state.as_mut());
            for _item in scope {}
            result
        })
    }

    /// # Safety
    /// Retain this inactive arena until all issued access ends and the scope is fully consumed.
    /// Fixed `resident` equals this context's admitted ceiling; budgets outlive reclamation.
    unsafe fn prepare<'d>(&'d mut self, limit: u32, resident: L::Shared) -> Root<'d, T, C, L> {
        const {
            assert!(size_of::<InactiveHeader<C, L>>() == size_of::<ActiveHeader<C, L>>());
            assert!(align_of::<InactiveHeader<C, L>>() == align_of::<ActiveHeader<C, L>>());
            assert!(
                offset_of!(InactiveHeader<C, L>, context)
                    == offset_of!(ActiveHeader<C, L>, context)
            );
        }
        let capacity = self.entries.extent();
        let pointer = tail::raw::View::new(&self.entries).as_ptr();
        let (header, values) = self.entries.parts_mut();
        let mut free = None;
        for slot in values.iter_mut() {
            let entry = ptr::NonNull::from(slot).cast::<Entry<L>>();
            // SAFETY: this generation exclusively initializes each complete slot;
            // its item remains in UnsafeCell<MaybeUninit<T>> until insertion.
            unsafe {
                entry
                    .as_ptr()
                    .write(Entry::new(pointer.cast(), MaybeUninit::new(Data { free })))
            };
            free = Some(entry);
        }
        header.state.write(State {
            domain: Domain::new(resident, limit, capacity),
            free: cell::Cell::new(free),
        });
        Root {
            // SAFETY: every Entry is initialized; the remaining Slot fields admit
            // uninitialized bytes. This allocation retains its exact active layout.
            view: unsafe { tail::raw::View::from_raw(pointer) },
            slots: marker::PhantomData,
        }
    }
}

impl<T, C, L: Layout> Allocation<T, C, L> {
    pub fn initialize(self, context: C) -> Arena<T, C, L> {
        Arena {
            entries: self.memory.init(Header {
                state: MaybeUninit::uninit(),
                context,
            }),
        }
    }
}

impl<T, C: buffer::raw::Fixed<T>> Arena<T, C, ()> {
    /// # Safety
    /// Retain this inactive arena for one generative scope. End all native and
    /// issued access before reclaiming it, while every paying budget remains live.
    pub unsafe fn enter(&mut self, accounts: u32) -> Root<'_, T, C, ()> {
        let resident = self.context().resident();
        // SAFETY: the caller retains the generation; this exact context supplies its ceiling.
        unsafe { self.prepare(accounts, resident) }
    }

    /// # Safety
    /// Native completion ended every projection, account and root borrow from enter.
    /// Reclaim once before reentry or release, with the original paying budgets live.
    pub unsafe fn refund_ended(&mut self) {
        let pointer = tail::raw::View::new(&self.entries).as_ptr();
        let root: Root<'_, T, C, ()> = Root {
            // SAFETY: enter initialized this exact header and every slot; no access survives.
            view: unsafe { tail::raw::View::from_raw(pointer) },
            slots: marker::PhantomData,
        };
        for _item in root.scope() {}
    }

    pub fn scope<S, R>(
        &mut self,
        state: pin::Pin<&mut S>,
        run: impl for<'d> FnOnce(
            region::Token<region::Identity<'d>>,
            Root<'d, T, C, ()>,
            pin::Pin<&'d mut S>,
        ) -> R,
    ) -> R {
        let resident = self.context().resident();
        self.scope_in(state, resident, run)
    }
}

impl<'d, T, L: Layout> Iterator for Scope<'d, T, L> {
    type Item = slot::Occupied<'d, T>;

    fn next(&mut self) -> Option<Self::Item> {
        for slot in self.slots.by_ref() {
            // SAFETY: all issued access ended; original paying budgets remain live.
            if !matches!(unsafe { slot.entry.refund_ended() }, Phase::Empty) {
                // SAFETY: this ended generation owns the initialized item until its release.
                return Some(unsafe { slot.occupied() });
            }
        }
        None
    }
}

const _: () = {
    assert!(!needs_drop::<State<()>>());
    assert!(size_of::<Arena<(), (), ()>>() == size_of::<usize>());
    assert!(size_of::<Root<'_, (), (), ()>>() == size_of::<usize>());
};

impl<T, C> Arena<T, C> {
    /// # Safety
    /// End every issued access, then fully consume the returned scope while budgets remain live.
    pub unsafe fn enter_scope(&mut self) -> (Root<'_, T, C>, Scope<'_, T, cell::Cell<u32>>) {
        // SAFETY: the caller retains this inactive arena and executes the
        // returned terminal after all issued access ends, before releasing it.
        let root = unsafe { self.prepare(self.capacity().get(), ()) };
        (root, root.scope())
    }

    pub fn scope<S, R>(
        &mut self,
        state: pin::Pin<&mut S>,
        run: impl for<'d> FnOnce(
            region::Token<region::Identity<'d>>,
            Root<'d, T, C>,
            pin::Pin<&'d mut S>,
        ) -> R,
    ) -> R {
        self.scope_in(state, (), run)
    }
}

#[repr(C, align(8))]
struct Slot<T, L: Layout> {
    entry: Entry<L>,
    item: cell::UnsafeCell<MaybeUninit<T>>,
}

impl<T, L: Layout> Slot<T, L> {
    /// # Safety
    /// The caller exclusively owns the initialized item after all projections end.
    unsafe fn occupied(&self) -> slot::Occupied<'_, T> {
        // SAFETY: the slot retains this item at its final address for the exclusive loan.
        unsafe { slot::raw::Vacant::new(&mut *self.item.get()).assume_init() }
    }
}

/// Borrowed access to the exact active header and slot layout.
#[repr(transparent)]
pub struct Root<'d, T, C = (), L: Layout = cell::Cell<u32>> {
    view: tail::raw::View<'d, ActiveHeader<C, L>, Slot<T, L>, NonZeroU32>,
    slots: SlotDomain<'d, T, L>,
}

impl<'d, T, C, L: Layout> Root<'d, T, C, L> {
    fn scope(self) -> Scope<'d, T, L> {
        Scope {
            scope: marker::PhantomData,
            slots: self.view.as_slice().iter(),
        }
    }

    pub fn context(&self) -> &'d C {
        &self.view.header().context
    }
    pub fn capacity(&self) -> NonZeroU32 {
        self.view.len_proof().extent()
    }
    fn next_free<X: Copy>(&self, context: X) -> Option<Vacant<'d, T, L, X>> {
        let state = &self.view.header().state;
        let entry = state.free.get()?;
        // SAFETY: the free head is the complete slot from this typed arena.
        let slot = unsafe { entry.cast::<Slot<T, L>>().as_ref() };
        // SAFETY: a free slot contains its original free successor.
        state
            .free
            .set(unsafe { slot.entry.data.get().assume_init().free });
        Some(Vacant { slot, context })
    }
    pub fn pop_returned(&self) -> Option<T> {
        let state = &self.view.header().state;
        let head = state.domain.returned.pop()?;
        // SAFETY: this domain contains only complete slots of this arena.
        let slot = unsafe { head.cast::<Slot<T, L>>().as_ref() };
        // SAFETY: the detached slot owns its item after every external and account edge ended.
        let value = unsafe { slot.occupied() }.into_inner();
        state.push_free(Empty {
            entry: head,
            scope: marker::PhantomData,
        });
        Some(value)
    }
    pub fn has_returned(&self) -> bool {
        self.view.header().state.domain.returned.has_items()
    }
}

impl<T, C, L: Layout> Clone for Root<'_, T, C, L> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<T, C, L: Layout> Copy for Root<'_, T, C, L> {}

impl<'d, T, C> Root<'d, T, C> {
    pub fn vacant(&self) -> Option<Vacant<'d, T>> {
        self.next_free(())
    }
}

impl<'d, T, C> Root<'d, T, C, ()> {
    pub fn try_vacant(&self) -> Result<Vacant<'d, T, (), &'d C>, Full> {
        self.next_free(self.context()).ok_or(Full {
            capacity: self.capacity(),
        })
    }
}

/// Free slots and fixed extent belong to the inactive-item arena.
#[repr(C)]
struct State<L: Layout> {
    domain: Domain<L>,
    free: cell::Cell<Option<Link<L>>>,
}

impl<L: Layout> State<L> {
    fn push_free(&self, node: Empty<'_, L>) {
        // SAFETY: this affine vacancy retains its exact detached slot.
        unsafe { node.entry.as_ref() }
            .data
            .set(MaybeUninit::new(Data {
                free: self.free.get(),
            }));
        self.free.set(Some(node.entry));
    }

    /// # Safety
    /// This domain is the first field of the original owning item arena.
    unsafe fn from_domain<'d>(domain: ptr::NonNull<Domain<L>>) -> &'d Self {
        // SAFETY: this pointer retains the original header allocation and State is its first field.
        unsafe { domain.cast::<Self>().as_ref() }
    }
}

type SlotDomain<'d, T, L> = marker::PhantomData<fn(&'d Slot<T, L>) -> &'d Slot<T, L>>;

pub struct Vacant<'d, T, L: Layout = cell::Cell<u32>, C: Copy = ()> {
    slot: &'d Slot<T, L>,
    context: C,
}

impl<T, L: Layout, C: Copy> Drop for Vacant<'_, T, L, C> {
    fn drop(&mut self) {
        // SAFETY: this typed vacancy originates in the owning item arena.
        unsafe { State::from_domain(self.slot.entry.domain) }.push_free(Empty {
            entry: ptr::NonNull::from(self.slot).cast(),
            scope: marker::PhantomData,
        });
    }
}

impl<'d, T, L: Layout, C: Copy> Vacant<'d, T, L, C> {
    fn publish(self, view: buffer::raw::Projection<'d, '_>) -> Loan<'d, L> {
        let slot = ManuallyDrop::new(self).slot;
        // SAFETY: consuming this initialized vacancy transfers its sole external edge.
        unsafe { Slice::publish(&slot.entry, view.into_inner()) }
    }
}

impl<'d, T: AsMut<[u8]>> Vacant<'d, T> {
    pub fn try_insert(
        self,
        item: T,
        resident: u32,
    ) -> Result<Loan<'d>, Rejected<T, view::LengthError>> {
        let slot = self.slot;
        // SAFETY: this vacancy exclusively owns the detached slot throughout projection.
        let item = unsafe { (*slot.item.get()).write(item) };
        buffer::raw::Limit::scope(resident, |limit| {
            let view = match limit.try_project(item.as_mut()) {
                Ok(view) => view,
                Err(error) => {
                    // SAFETY: the rejected projection ended its borrow. Move the item
                    // back before the vacancy returns its original slot to the free list.
                    let item = unsafe { (*slot.item.get()).assume_init_read() };
                    return Err(Rejected::new(item, error));
                }
            };
            slot.entry.resident.set(MaybeUninit::new(resident));
            Ok(self.publish(view))
        })
    }
}

impl<'d, T, C> Vacant<'d, T, (), &'d C> {
    pub fn context(&self) -> &'d C {
        self.context
    }

    /// # Safety
    /// Own this context's completed item with its initialized prefix and exact fixed layout.
    pub(in crate::buffer) unsafe fn insert_fixed(self, item: T) -> Loan<'d, ()>
    where
        C: buffer::raw::Fixed<T>,
    {
        // SAFETY: the fixed arena initialized every slot with its admitted resident ceiling.
        let resident = unsafe { self.slot.entry.capacity() };
        let context = self.context;
        buffer::raw::Limit::scope(resident, |limit| {
            // SAFETY: the detached vacancy exclusively owns this final item address for 'd.
            let item = unsafe { (*self.slot.item.get()).write(item) };
            // SAFETY: the native admission and this vacancy retain the same context and layout.
            self.publish(unsafe { context.project(item, limit) })
        })
    }
}

const _: () = {
    assert!(offset_of!(Slot<u8, ()>, item) == size_of::<Entry<()>>());
    assert!(offset_of!(Slot<u64, cell::Cell<u32>>, item) == size_of::<Entry>());
    assert!(size_of::<Vacant<'_, ()>>() == size_of::<usize>());
    assert!(size_of::<Vacant<'_, (), (), &'_ ()>>() == 2 * size_of::<usize>());
};

/// A live edge retains the slot and its paying budget.
#[derive(Debug)]
#[repr(transparent)]
pub struct Registration<'d, L: Layout = cell::Cell<u32>> {
    count: mem::raw::Count,
    scope: marker::PhantomData<fn(&'d L) -> &'d L>,
}

impl<'d, L: Layout> Registration<'d, L> {
    pub(in crate::buffer) fn payer(owner: &mem::raw::Owner<Self>) -> resident::Budget<'d> {
        // SAFETY: this live owner retains the original entry allocation and budget for its generation.
        unsafe { owner.as_ptr().cast::<Entry<L>>().as_ref().payer() }
    }

    pub(in crate::buffer) fn resident(owner: &mem::raw::Owner<Self>) -> usize {
        // SAFETY: this live owner retains the original entry and its admitted resident ceiling.
        unsafe { owner.as_ptr().cast::<Entry<L>>().as_ref().capacity() as usize }
    }
}

// SAFETY: every account edge retains this exact slot and embedded count.
unsafe impl<L: Layout> mem::raw::Edge for Registration<'_, L> {
    fn count(&self) -> &mem::raw::Count {
        &self.count
    }
}

// SAFETY: account edges retain the initialized debit; its finalizer owns both
// refunds before returning the slot, without callbacks or premature reuse.
unsafe impl<'d, L: Layout> mem::raw::Target for Registration<'d, L> {
    unsafe fn destroy(pointer: ptr::NonNull<Self>) {
        // SAFETY: activation issued this pointer from the complete repr(C) entry.
        let pointer = pointer.cast::<Entry<L>>();
        // SAFETY: the last counted edge ended and set this registration's count to zero.
        let entry = unsafe { pointer.as_ref() };
        let domain = unsafe { entry.domain.as_ref() };
        domain.accounted.set(domain.accounted.get() - 1);
        // SAFETY: this last live edge owns the registration's remaining debit.
        unsafe { entry.refund() };
        if matches!(entry.state.get(), Phase::ReturnOnLastAccount) {
            domain.returned.finish(Ready {
                entry: pointer,
                scope: marker::PhantomData,
            });
        }
    }
}

impl<L: Layout> buffer::Residency for Option<mem::raw::Owner<Registration<'_, L>>> {
    fn resident(&self) -> usize {
        self.as_ref().map_or(0, Registration::resident)
    }
}