dope-core 0.75.0

Owned native I/O and completion driver for dope
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
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
use std::{alloc::Layout, cell, marker, mem, num, ptr};

use o3::{
    alloc::{self, raw::LayoutExt},
    depot::arena::slab,
    mem::slot,
};

use crate::driver::retained::flight::{
    self, GENERATION_BITS, INDEX_BITS, Target,
    storage::{Echo, Slots, generation_max, index_limit},
};

const ATTACHED: usize = 1;
const PENDING: usize = 2;
const BOUND: usize = 4;
const FLAGS: usize = ATTACHED | PENDING | BOUND;
const RETIRED: usize = ATTACHED | BOUND;
const LEASED: u64 = 1 << 63;
const EMPTY: u64 = 1 << 62;

#[repr(C, align(8))]
pub(in crate::driver::retained::flight) struct State<T: Copy, const I: u32, const G: u32> {
    value: cell::Cell<mem::MaybeUninit<T>>,
    word: cell::UnsafeCell<Word<T, I, G>>,
    index: u32,
    generation: cell::Cell<num::NonZero<u32>>,
}

union Word<T: Copy, const I: u32, const G: u32> {
    free: mem::ManuallyDrop<Option<Link<T, I, G>>>,
    occupied: *mut Header<T, I, G>,
}

#[repr(transparent)]
struct Link<T: Copy, const I: u32, const G: u32>(ptr::NonNull<State<T, I, G>>);

#[repr(align(8))]
pub(super) struct Header<T: Copy, const I: u32, const G: u32> {
    free: cell::Cell<Option<Link<T, I, G>>>,
    admission: cell::Cell<u64>,
}

#[repr(C)]
pub(in crate::driver::retained::flight) struct Cell<T: Copy, B, const I: u32, const G: u32> {
    native: State<T, I, G>,
    backing: cell::UnsafeCell<mem::MaybeUninit<B>>,
}

#[repr(C)]
pub(super) struct Group<T: Copy, const I: u32, const G: u32> {
    header: Header<T, I, G>,
    next: Option<Allocation<T, I, G>>,
    layout: Layout,
    extent: usize,
}

pub(super) struct Allocation<T: Copy, const I: u32, const G: u32>(
    pub(super) ptr::NonNull<Group<T, I, G>>,
);

#[repr(C)]
struct Inline<T: Copy, B, const I: u32, const G: u32> {
    group: Group<T, I, G>,
    cells: [Cell<T, B, I, G>; 0],
}

#[repr(C)]
pub(super) struct Vacant<'a, T: Copy, const I: u32, const G: u32> {
    entry: ptr::NonNull<State<T, I, G>>,
    owner: &'a Header<T, I, G>,
}

pub(in crate::driver::retained::flight) struct Front<
    'slot,
    'owner,
    T: Copy,
    const I: u32,
    const G: u32,
> {
    vacancy: Vacant<'owner, T, I, G>,
    slots: marker::PhantomData<&'slot Slots<'owner, T, I, G>>,
}

#[repr(transparent)]
pub(super) struct Live<'a, T: Copy, const I: u32, const G: u32> {
    entry: ptr::NonNull<State<T, I, G>>,
    invariant: marker::PhantomData<fn(&'a ()) -> &'a ()>,
}

#[repr(transparent)]
pub(super) struct Bound<'a, T: Copy, const I: u32, const G: u32> {
    live: Live<'a, T, I, G>,
}

impl<T: Copy, const I: u32, const G: u32> State<T, I, G> {
    const fn new(index: u32) -> Self {
        Self {
            value: cell::Cell::new(mem::MaybeUninit::uninit()),
            word: cell::UnsafeCell::new(Word {
                free: mem::ManuallyDrop::new(None),
            }),
            index,
            generation: cell::Cell::new(num::NonZero::<u32>::MIN),
        }
    }

    fn pointer(&self) -> *mut Header<T, I, G> {
        // SAFETY: both union fields have the nullable-pointer representation.
        unsafe { (*self.word.get()).occupied }
    }

    fn set(&self, pointer: *mut Header<T, I, G>) {
        // SAFETY: the live capability owns this occupied union variant.
        unsafe { (*self.word.get()).occupied = pointer };
    }

    pub(super) fn is_pending(&self) -> bool {
        self.pointer().addr() & PENDING != 0
    }

    fn is_attached(&self) -> bool {
        let address = self.pointer().addr();
        address != RETIRED && address & ATTACHED != 0
    }

    pub(super) unsafe fn finish(entry: ptr::NonNull<Self>) {
        // SAFETY: the arena retains this original allocation through finalization.
        let generation = unsafe { entry.as_ref() }.generation.get();
        if let Some(bound) = unsafe { Self::bind(entry, generation) } {
            bound.finish();
        }
    }

    pub(super) unsafe fn bind<'a>(
        entry: ptr::NonNull<Self>,
        expected: num::NonZero<u32>,
    ) -> Option<Bound<'a, T, I, G>> {
        // SAFETY: the directory retains the original cell allocation for 'a.
        let value = unsafe { entry.as_ref() };
        let pointer = value.pointer();
        let address = pointer.addr();
        if address & (PENDING | BOUND) != PENDING || value.generation.get() != expected {
            return None;
        }
        value.set(pointer.map_addr(|address| address | BOUND));
        Some(Bound {
            live: Live {
                entry,
                invariant: marker::PhantomData,
            },
        })
    }
}

impl<T: Copy, const I: u32, const G: u32> Group<T, I, G> {
    fn layout<B>(extent: usize) -> Result<Layout, alloc::Overflow> {
        let cells = Layout::array::<Cell<T, B, I, G>>(extent).map_err(|_| alloc::Overflow)?;
        let (layout, _) = Layout::new::<Self>()
            .extend(cells)
            .map_err(|_| alloc::Overflow)?;
        Ok(layout.pad_to_align())
    }

    pub(super) fn try_new<B>(
        start: usize,
        extent: usize,
    ) -> Result<Allocation<T, I, G>, alloc::Error> {
        let end = start.checked_add(extent).ok_or(alloc::Overflow)?;
        if end > index_limit::<I>() {
            return Err(alloc::Error::Overflow);
        }
        let layout = Self::layout::<B>(extent)?;
        let pointer = layout.try_allocate::<Self>()?;
        // SAFETY: the checked layout contains Group and exactly extent cells.
        // Only native metadata is initialized; backing is initialized on admission.
        unsafe {
            pointer.as_ptr().write(Self {
                header: Header {
                    free: cell::Cell::new(None),
                    admission: cell::Cell::new(0),
                },
                next: None,
                layout,
                extent,
            });
            let cells = Self::cells::<B>(pointer);
            for offset in 0..extent {
                cells.add(offset).write(Cell {
                    native: State::new((start + offset) as u32),
                    backing: cell::UnsafeCell::new(mem::MaybeUninit::uninit()),
                });
            }
        }
        Ok(Allocation(pointer))
    }

    unsafe fn cells<B>(base: ptr::NonNull<Self>) -> *mut Cell<T, B, I, G> {
        // SAFETY: typed acquisition admitted this layout. Keep the original
        // allocation pointer while projecting the disjoint cell tail.
        unsafe {
            base.cast::<u8>()
                .add(mem::offset_of!(Inline<T, B, I, G>, cells))
                .cast()
                .as_ptr()
        }
    }

    pub(super) fn select<'a, B>(
        groups: &'a cell::UnsafeCell<Option<Allocation<T, I, G>>>,
        capacity: usize,
    ) -> Option<Slots<'a, T, I, G>> {
        // SAFETY: preparation exclusively owns topology and group admission.
        let mut next = unsafe { &*groups.get() }.as_ref().map(|group| group.0);
        let mut selected = None;
        let mut best = usize::MAX;
        'groups: while let Some(pointer) = next {
            // SAFETY: the arena owns each linked allocation until destruction.
            let group = unsafe { pointer.as_ref() };
            next = group.next.as_ref().map(|group| group.0);
            if group.extent < capacity
                || group.header.admission.get() & LEASED != 0
                || Self::layout::<B>(group.extent).ok() != Some(group.layout)
            {
                continue;
            }
            let mut count = 0;
            // SAFETY: the layout comparison proves this complete cell stride.
            let cells = unsafe { Self::cells::<B>(pointer) };
            for index in 0..group.extent {
                let address = unsafe { &(*cells.add(index)).native }.pointer().addr();
                if address & FLAGS == 0 {
                    count += 1;
                } else if address != RETIRED {
                    continue 'groups;
                }
            }
            if count >= capacity && count < best {
                selected = Some(pointer);
                best = count;
                if count == capacity {
                    break;
                }
            }
        }
        // SAFETY: selection admitted the exact layout, no live backing and capacity.
        Some(unsafe { Self::activate::<B>(selected?, capacity) })
    }

    unsafe fn activate<'a, B>(pointer: ptr::NonNull<Self>, capacity: usize) -> Slots<'a, T, I, G> {
        // SAFETY: preparation owns this original group's admission until published.
        let group = unsafe { pointer.as_ref() };
        let header = &group.header;
        let state = if capacity == 0 {
            EMPTY
        } else {
            capacity as u64
        };
        header.admission.set(LEASED | state);
        header.free.set(None);
        let mut left = capacity;
        let cells = unsafe { Self::cells::<B>(pointer) };
        for index in (0..group.extent).rev() {
            if left == 0 {
                break;
            }
            // SAFETY: retain the original allocation pointer, not a narrowed &State.
            let entry: ptr::NonNull<State<T, I, G>> =
                unsafe { ptr::NonNull::new_unchecked(cells.add(index).cast()) };
            if unsafe { entry.as_ref() }.pointer().addr() & FLAGS == 0 {
                Vacant {
                    entry,
                    owner: header,
                }
                .release();
                left -= 1;
            }
        }
        Slots {
            group: pointer,
            owner: marker::PhantomData,
        }
    }

    pub(super) fn publish<'a, B>(
        groups: &'a cell::UnsafeCell<Option<Allocation<T, I, G>>>,
        dir: &mut Vec<ptr::NonNull<State<T, I, G>>>,
        allocation: Allocation<T, I, G>,
        capacity: usize,
    ) -> Slots<'a, T, I, G> {
        let pointer = allocation.0;
        // SAFETY: preparation owns topology and reserved the entire directory
        // growth. Cells keep the original allocation provenance through every reuse.
        unsafe {
            let group = pointer.as_ptr();
            let extent = (*group).extent;
            (*group).next = (*groups.get()).take();
            *groups.get() = Some(allocation);
            let cells = Self::cells::<B>(pointer);
            let len = dir.len();
            for index in 0..extent {
                dir.as_mut_ptr()
                    .add(len + index)
                    .write(ptr::NonNull::new_unchecked(cells.add(index).cast()));
            }
            dir.set_len(len + extent);
            Self::activate::<B>(pointer, capacity)
        }
    }
}

impl<T: Copy, const I: u32, const G: u32> Drop for Allocation<T, I, G> {
    fn drop(&mut self) {
        // SAFETY: the arena unlinks next first; unpublished groups have no next.
        // Typed backing destruction precedes release of its owning group.
        unsafe {
            let layout = self.0.as_ref().layout;
            self.0.as_ptr().drop_in_place();
            layout.deallocate(self.0);
        }
    }
}

pub(super) fn drop_groups<T: Copy, const I: u32, const G: u32>(
    groups: &mut Option<Allocation<T, I, G>>,
) {
    while let Some(allocation) = groups.take() {
        // SAFETY: arena destruction exclusively owns each linked allocation.
        *groups = unsafe { &mut *allocation.0.as_ptr() }.next.take();
        drop(allocation);
    }
}

impl<T: Copy, const I: u32, const G: u32> Header<T, I, G> {
    pub(super) fn release(&self) {
        self.admission.set(self.admission.get() & !LEASED);
    }
}

impl<'owner, T: Copy, const I: u32, const G: u32> Slots<'owner, T, I, G> {
    pub(super) fn header(&self) -> &Header<T, I, G> {
        // SAFETY: the group lease retains this original allocation for 'owner.
        unsafe { &self.group.as_ref().header }
    }

    pub(in crate::driver::retained::flight) fn header_pointer(&self) -> *const () {
        self.group.as_ptr().cast()
    }

    /// # Safety
    /// No access to this group's free list may occur before the loan ends.
    pub(in crate::driver::retained::flight) unsafe fn front<'slot>(
        &'slot self,
    ) -> Result<Front<'slot, 'owner, T, I, G>, slab::Vacancy> {
        // SAFETY: the original group and header outlive the short exclusive claim.
        let owner = unsafe { &self.group.as_ref().header };
        let head = unsafe { &*owner.free.as_ptr() };
        let Some(Link(pointer)) = head.as_ref() else {
            return Err(if owner.admission.get() & !LEASED == 0 {
                slab::Vacancy::IdentityExhausted
            } else {
                slab::Vacancy::Full
            });
        };
        Ok(Front {
            vacancy: Vacant {
                entry: *pointer,
                owner,
            },
            slots: marker::PhantomData,
        })
    }

    pub(in crate::driver::retained::flight) unsafe fn tail<B>(
        &mut self,
    ) -> (*mut Cell<T, B, I, G>, usize) {
        // SAFETY: only the private matching typed Prepared creates this owner.
        let extent = unsafe { self.group.as_ref() }.extent;
        (unsafe { Group::cells::<B>(self.group) }, extent)
    }
}

impl<'slot, 'owner, T: Copy, const I: u32, const G: u32> Front<'slot, 'owner, T, I, G> {
    fn detach(self) -> Vacant<'owner, T, I, G> {
        let vacancy = self.vacancy;
        // SAFETY: front exclusively retains this original free head.
        let next =
            unsafe { mem::ManuallyDrop::take(&mut (*vacancy.entry.as_ref().word.get()).free) };
        vacancy.owner.free.set(next);
        vacancy
    }

    pub(in crate::driver::retained::flight) fn index(&self) -> u32 {
        // SAFETY: the original head is live and remains exclusively claimed.
        unsafe { self.vacancy.entry.as_ref() }.index
    }

    pub(in crate::driver::retained::flight) fn take(self) -> super::Vacant<'slot, 'owner, T, I, G> {
        super::Vacant {
            vacant: o3::mem::Lease::open(super::Release(self.detach(), marker::PhantomData), ()),
        }
    }

    pub(in crate::driver::retained::flight) fn reserve(
        self,
        value: T,
    ) -> super::Reserved<'owner, T, I, G> {
        super::Reserved {
            live: o3::mem::Lease::open(super::Release(self.detach().occupy(value), ()), ()),
        }
    }

    pub(in crate::driver::retained::flight) unsafe fn write<B>(
        self,
        value: T,
        backing: B,
    ) -> ptr::NonNull<State<T, I, G>> {
        let pointer = self.vacancy.entry;
        // SAFETY: the private typed group admitted this Cell layout. The original
        // free head grants exclusive initialization of its disjoint backing.
        unsafe {
            (*pointer.cast::<Cell<T, B, I, G>>().as_ptr())
                .backing
                .get()
                .write(mem::MaybeUninit::new(backing))
        };
        let _ = self.detach().occupy(value);
        pointer
    }
}

impl<'a, T: Copy, const I: u32, const G: u32> Vacant<'a, T, I, G> {
    pub(super) fn occupy(self, value: T) -> Live<'a, T, I, G> {
        // SAFETY: the original allocation remains exclusively vacant.
        let entry = unsafe { self.entry.as_ref() };
        entry.value.set(mem::MaybeUninit::new(value));
        entry.set(
            ptr::from_ref(self.owner)
                .cast_mut()
                .map_addr(|address| address | ATTACHED | PENDING),
        );
        Live {
            entry: self.entry,
            invariant: marker::PhantomData,
        }
    }

    pub(super) fn release(self) {
        let head = self.owner.free.as_ptr();
        // SAFETY: native metadata and header are disjoint. The original full-cell
        // pointer survives the free-list move without narrowing through &State.
        unsafe {
            self.entry.as_ref().word.get().write(Word {
                free: mem::ManuallyDrop::new(head.read()),
            });
            head.write(Some(Link(self.entry)));
        }
    }
}

impl<'a, T: Copy, const I: u32, const G: u32> Live<'a, T, I, G> {
    fn get(&self) -> &State<T, I, G> {
        // SAFETY: this capability retains the original stable native entry.
        unsafe { self.entry.as_ref() }
    }

    pub(super) fn is_pending(&self) -> bool {
        self.get().is_pending()
    }

    pub(super) fn value(&self) -> T {
        // SAFETY: occupancy retains initialized metadata until consuming release.
        unsafe { self.get().value.get().assume_init() }
    }

    pub(super) fn echo(&self) -> Echo<T, I, G> {
        Echo::from_parts(self.get().index, self.get().generation.get())
    }

    pub(super) fn detach(self) {
        let pointer = self.get().pointer();
        if pointer.addr() & FLAGS == ATTACHED {
            self.recycle();
        } else {
            self.get()
                .set(pointer.map_addr(|address| address & !ATTACHED));
        }
    }

    pub(super) fn release(self) {
        let pointer = self.get().pointer();
        if pointer.addr() & BOUND != 0 {
            self.get()
                .set(pointer.map_addr(|address| address & !(ATTACHED | PENDING)));
        } else {
            self.recycle();
        }
    }

    fn recycle(self) {
        let owner = self.get().pointer().map_addr(|address| address & !FLAGS);
        // SAFETY: this consuming capability retains its aligned owner until release.
        let owner: &Header<T, I, G> = unsafe { &*owner };
        let next = self.get().generation.get().checked_add(1);
        let Some(next) = next.filter(|next| next.get() <= generation_max::<G>()) else {
            self.get().set(ptr::without_provenance_mut(RETIRED));
            owner.admission.set(owner.admission.get() - 1);
            return;
        };
        self.get().generation.set(next);
        Vacant {
            entry: self.entry,
            owner,
        }
        .release();
    }
}

impl<T: Copy, const I: u32, const G: u32> Bound<'_, T, I, G> {
    pub(super) fn echo(&self) -> Echo<T, I, G> {
        self.live.echo()
    }
    pub(super) fn value(&self) -> T {
        self.live.value()
    }

    pub(super) fn mark_terminal(&self) {
        let pointer = self.live.get().pointer();
        self.live
            .get()
            .set(pointer.map_addr(|address| address & !PENDING));
    }

    pub(super) fn header_matches(&self, header: *const ()) -> bool {
        self.live
            .get()
            .pointer()
            .map_addr(|address| address & !FLAGS)
            .cast_const()
            .cast::<()>()
            == header
    }

    pub(super) fn is_attached(&self) -> bool {
        self.live.get().is_attached()
    }

    pub(super) fn into_pointer(self) -> ptr::NonNull<State<T, I, G>> {
        self.live.entry
    }

    pub(super) fn finish(self) {
        let live = self.live;
        let pointer = live.get().pointer();
        if pointer.addr() & ATTACHED == 0 {
            live.recycle();
        } else {
            live.get()
                .set(pointer.map_addr(|address| address & !(PENDING | BOUND)));
        }
    }

    pub(super) fn retain(self) {
        let pointer = self.live.get().pointer();
        if pointer.addr() & PENDING == 0 {
            self.live.recycle();
        } else {
            self.live
                .get()
                .set(pointer.map_addr(|address| address & !BOUND));
        }
    }
}

/// Owns an initialized backing and its native entry's final destruction.
#[repr(C)]
pub struct Retiring<B, const COMPLETE: bool> {
    native: State<Target, INDEX_BITS, GENERATION_BITS>,
    backing: mem::ManuallyDrop<B>,
}

impl<B, const COMPLETE: bool> Retiring<B, COMPLETE> {
    pub(in crate::driver::retained::flight) unsafe fn occupy<'a>(
        pointer: ptr::NonNull<State<Target, INDEX_BITS, GENERATION_BITS>>,
    ) -> slot::Occupied<'a, Self> {
        const {
            assert!(
                mem::size_of::<Self>()
                    == mem::size_of::<Cell<Target, B, INDEX_BITS, GENERATION_BITS>>()
            );
            assert!(
                mem::align_of::<Self>()
                    == mem::align_of::<Cell<Target, B, INDEX_BITS, GENERATION_BITS>>()
            );
            assert!(
                mem::offset_of!(Self, backing)
                    == mem::offset_of!(Cell<Target, B, INDEX_BITS, GENERATION_BITS>, backing)
            );
        }
        // SAFETY: the same group admitted layout and initialized backing; its
        // sole terminal or pre-submit authority transfers the original cell.
        unsafe {
            slot::Vacant::new(&mut *pointer.cast::<mem::MaybeUninit<Self>>().as_ptr()).assume_init()
        }
    }

    fn release(pointer: ptr::NonNull<State<Target, INDEX_BITS, GENERATION_BITS>>) {
        let live = Live {
            entry: pointer,
            invariant: marker::PhantomData,
        };
        if COMPLETE {
            live.recycle();
        } else {
            live.detach();
        }
    }

    pub fn take(mut owner: slot::Occupied<'_, Self>) -> B {
        let value = owner.get_mut();
        let pointer = ptr::NonNull::from(&mut *value).cast();
        // SAFETY: this occupied owner consumes the one initialized backing.
        let backing = unsafe { mem::ManuallyDrop::take(&mut value.backing) };
        let _ = owner.into_uninit();
        Self::release(pointer);
        backing
    }

    pub fn backing(&mut self) -> &mut B {
        &mut self.backing
    }

    pub fn echo(&self) -> flight::raw::Echo {
        flight::raw::Echo::from_inner(Echo::from_parts(
            self.native.index,
            self.native.generation.get(),
        ))
    }

    pub fn slot(&self) -> crate::driver::route::indices::SlotIndex {
        // SAFETY: this live cell owns initialized native metadata.
        unsafe { self.native.value.get().assume_init() }.slot
    }

    pub fn epoch(&self) -> crate::driver::route::Epoch {
        // SAFETY: this live cell owns initialized native metadata.
        unsafe { self.native.value.get().assume_init() }.epoch
    }
}

impl<B, const COMPLETE: bool> Drop for Retiring<B, COMPLETE> {
    fn drop(&mut self) {
        let pointer = ptr::NonNull::from(&mut *self).cast();
        // SAFETY: the occupied owner destroys backing before its native entry.
        unsafe { mem::ManuallyDrop::drop(&mut self.backing) };
        Self::release(pointer);
    }
}

pub struct RetainedDrain<'a, B> {
    next: *mut Cell<Target, B, INDEX_BITS, GENERATION_BITS>,
    end: *mut Cell<Target, B, INDEX_BITS, GENERATION_BITS>,
    owner: marker::PhantomData<&'a mut B>,
}

impl<'a, B> RetainedDrain<'a, B> {
    pub(in crate::driver::retained::flight) unsafe fn new(
        slots: &'a mut Slots<'_, Target, INDEX_BITS, GENERATION_BITS>,
    ) -> Self {
        // SAFETY: the typed owner holds this layout and quiescent destruction.
        let (next, extent) = unsafe { slots.tail::<B>() };
        Self {
            next,
            end: unsafe { next.add(extent) },
            owner: marker::PhantomData,
        }
    }
}

impl<'a, B> Iterator for RetainedDrain<'a, B> {
    type Item = slot::Occupied<'a, Retiring<B, false>>;

    fn next(&mut self) -> Option<Self::Item> {
        while self.next != self.end {
            let pointer = self.next;
            // SAFETY: the range contains disjoint cells in this original allocation.
            self.next = unsafe { self.next.add(1) };
            if unsafe { &(*pointer).native }.is_attached() {
                return Some(unsafe {
                    Retiring::occupy(ptr::NonNull::new_unchecked(pointer.cast()))
                });
            }
        }
        None
    }
}

const _: () = {
    assert!(mem::size_of::<State<u64, 32, 32>>() == 3 * mem::size_of::<usize>());
    assert!(mem::size_of::<Header<u64, 32, 32>>() == 2 * mem::size_of::<usize>());
    assert!(mem::align_of::<State<u64, 32, 32>>() == 8);
    assert!(mem::align_of::<Header<u64, 32, 32>>() == 8);
    assert!(mem::size_of::<Vacant<'static, u64, 32, 32>>() == 2 * mem::size_of::<usize>());
    assert!(mem::size_of::<Live<'static, u64, 32, 32>>() == mem::size_of::<usize>());
    assert!(mem::size_of::<Option<Live<'static, u64, 32, 32>>>() == mem::size_of::<usize>());
    assert!(mem::size_of::<Bound<'static, u64, 32, 32>>() == mem::size_of::<usize>());
};