weavy 0.2.2

Shared lowered-program substrate for interpreters and copy-and-patch backends.
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
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
//! Runtime ownership helpers for typed-memory interpreters.
//!
//! This module stays deliberately below any format, schema, or reflection
//! model. It owns raw temporary storage and adoption state; callers decide what
//! values live there and which thunks move those values into final handles.

use std::alloc::{self, Layout};
use std::array;
use std::error::Error;
use std::fmt;
use std::mem::MaybeUninit;

/// Allocation/layout failures for raw typed-memory runtime buffers.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RawAllocError {
    /// `size` and `align` do not form a valid Rust allocation layout.
    InvalidLayout { size: usize, align: usize },
    /// `count * stride` overflowed while sizing an array buffer.
    SizeOverflow { count: usize, stride: usize },
}

impl fmt::Display for RawAllocError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match *self {
            Self::InvalidLayout { size, align } => {
                write!(f, "invalid raw memory layout: size={size}, align={align}")
            }
            Self::SizeOverflow { count, stride } => {
                write!(
                    f,
                    "raw array buffer size overflow: count={count}, stride={stride}"
                )
            }
        }
    }
}

impl Error for RawAllocError {}

/// Engine-owned raw scratch storage for one value.
///
/// Dropping a `RawScratch` frees the allocation without dropping the value. This
/// is the correct behavior after an interpreter moves the initialized value into
/// a caller handle through an init/push/insert thunk.
#[derive(Debug)]
pub struct RawScratch {
    ptr: *mut u8,
    layout: Option<Layout>,
}

impl RawScratch {
    /// Allocate scratch storage for a value with `size` and `align`.
    pub fn new(size: usize, align: usize) -> Result<Self, RawAllocError> {
        let layout = Layout::from_size_align(size, align)
            .map_err(|_| RawAllocError::InvalidLayout { size, align })?;
        Ok(Self::from_layout(layout))
    }

    /// Allocate scratch storage for a value with an already-validated layout.
    #[must_use]
    pub fn from_layout(layout: Layout) -> Self {
        let ptr = allocate_or_dangling(layout);
        let layout = (layout.size() != 0).then_some(layout);
        Self { ptr, layout }
    }

    /// The raw storage pointer.
    #[must_use]
    pub fn ptr(&self) -> *mut u8 {
        self.ptr
    }

    /// Free the scratch storage without dropping any value that may have lived
    /// in it.
    pub fn dealloc_uninit(&mut self) {
        if let Some(layout) = self.layout.take() {
            unsafe { alloc::dealloc(self.ptr, layout) };
        }
    }
}

impl Drop for RawScratch {
    fn drop(&mut self) {
        self.dealloc_uninit();
    }
}

/// Reusable scratch storage for one interpreter run.
///
/// A session keeps raw buffers around after a moved-out child value is released,
/// so repeated list elements or option/pointer payloads can reuse memory instead
/// of allocating for every child decode. Dropping the session frees all buffers
/// without dropping values.
#[derive(Debug, Default)]
pub struct ScratchSession {
    buffers: Vec<ScratchBuffer>,
}

#[derive(Debug)]
struct ScratchBuffer {
    ptr: *mut u8,
    layout: Layout,
    active: bool,
}

/// A checked-out scratch slot from [`ScratchSession`].
#[derive(Debug)]
pub struct ScratchSlot {
    index: usize,
    ptr: *mut u8,
}

impl ScratchSession {
    /// Create an empty scratch session.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Reserve scratch storage for `layout`.
    pub fn reserve(&mut self, layout: Layout) -> ScratchSlot {
        if let Some((index, buffer)) = self
            .buffers
            .iter_mut()
            .enumerate()
            .find(|(_, buffer)| !buffer.active && layout_fits(buffer.layout, layout))
        {
            buffer.active = true;
            return ScratchSlot {
                index,
                ptr: buffer.ptr,
            };
        }

        let ptr = allocate_or_dangling(layout);
        let index = self.buffers.len();
        self.buffers.push(ScratchBuffer {
            ptr,
            layout,
            active: true,
        });
        ScratchSlot { index, ptr }
    }

    /// Release a moved-out scratch slot for reuse.
    pub fn release(&mut self, slot: ScratchSlot) {
        let buffer = &mut self.buffers[slot.index];
        debug_assert!(buffer.active, "scratch slot released twice");
        debug_assert_eq!(buffer.ptr, slot.ptr, "scratch slot pointer mismatch");
        buffer.active = false;
    }
}

impl ScratchSlot {
    /// The raw storage pointer for this slot.
    #[must_use]
    pub fn ptr(&self) -> *mut u8 {
        self.ptr
    }
}

impl Drop for ScratchSession {
    fn drop(&mut self) {
        for buffer in self.buffers.drain(..) {
            if buffer.layout.size() != 0 {
                unsafe { alloc::dealloc(buffer.ptr, buffer.layout) };
            }
        }
    }
}

/// Engine-owned raw contiguous storage for a sequence of elements.
///
/// Dropping frees only the raw allocation. Call [`adopt`](Self::adopt) after a
/// sequence handle takes ownership of the buffer.
#[derive(Debug)]
pub struct RawArrayBuffer {
    ptr: *mut u8,
    cap: usize,
    stride: usize,
    layout: Option<Layout>,
}

impl RawArrayBuffer {
    /// Allocate storage for `count` elements with `stride` bytes and
    /// `elem_align` alignment.
    pub fn new(count: usize, stride: usize, elem_align: usize) -> Result<Self, RawAllocError> {
        let layout = if count == 0 || stride == 0 {
            Layout::from_size_align(0, elem_align).map_err(|_| RawAllocError::InvalidLayout {
                size: 0,
                align: elem_align,
            })?
        } else {
            let size = count
                .checked_mul(stride)
                .ok_or(RawAllocError::SizeOverflow { count, stride })?;
            Layout::from_size_align(size, elem_align).map_err(|_| RawAllocError::InvalidLayout {
                size,
                align: elem_align,
            })?
        };

        let ptr = allocate_or_dangling(layout);
        let layout = (layout.size() != 0).then_some(layout);
        Ok(Self {
            ptr,
            cap: count,
            stride,
            layout,
        })
    }

    /// The start of the raw element storage.
    #[must_use]
    pub fn ptr(&self) -> *mut u8 {
        self.ptr
    }

    /// The number of elements this buffer can hold.
    #[must_use]
    pub fn cap(&self) -> usize {
        self.cap
    }

    /// The byte stride between elements.
    #[must_use]
    pub fn stride(&self) -> usize {
        self.stride
    }

    /// Return the element slot for `index` when it is within capacity.
    #[must_use]
    pub fn slot(&self, index: usize) -> Option<*mut u8> {
        if index >= self.cap {
            return None;
        }
        Some(unsafe { self.slot_unchecked(index) })
    }

    /// Return the element slot for `index` without bounds checks.
    ///
    /// # Safety
    ///
    /// `index` must be less than [`cap`](Self::cap). If `stride` is non-zero,
    /// the allocation created by [`new`](Self::new) guarantees the offset cannot
    /// overflow for in-bounds indices.
    pub unsafe fn slot_unchecked(&self, index: usize) -> *mut u8 {
        unsafe { self.ptr.add(index * self.stride) }
    }

    /// Mark the allocation as adopted by the caller.
    pub fn adopt(&mut self) {
        self.layout = None;
    }
}

impl Drop for RawArrayBuffer {
    fn drop(&mut self) {
        if let Some(layout) = self.layout.take() {
            unsafe { alloc::dealloc(self.ptr, layout) };
        }
    }
}

/// Caller-supplied drop hook for an initialized handle/value.
pub type DropThunk = unsafe fn(ctx: *const (), ptr: *mut u8);

/// Growable engine-owned raw storage for directly filling a sequence.
///
/// Callers reserve the next slot, initialize it, then mark it initialized. If
/// decoding fails before adoption, dropping the builder calls the supplied drop
/// thunk for initialized elements and frees the raw allocation. After a list
/// handle adopts the buffer through a `from_raw_parts`-style thunk, call
/// [`adopt`](Self::adopt) so the builder does not touch the values or buffer.
#[derive(Debug)]
pub struct RawArrayBuilder {
    ptr: *mut u8,
    len: usize,
    cap: usize,
    elem_layout: Layout,
    allocation: Option<Layout>,
    drop_ctx: *const (),
    drop: DropThunk,
}

impl RawArrayBuilder {
    /// Create an empty builder for elements with `elem_layout`.
    #[must_use]
    pub fn new(elem_layout: Layout, drop_ctx: *const (), drop: DropThunk) -> Self {
        let empty = empty_array_layout(elem_layout.align());
        Self {
            ptr: allocate_or_dangling(empty),
            len: 0,
            cap: 0,
            elem_layout,
            allocation: None,
            drop_ctx,
            drop,
        }
    }

    /// The start of the raw element storage.
    #[must_use]
    pub fn ptr(&self) -> *mut u8 {
        self.ptr
    }

    /// Number of initialized elements.
    #[must_use]
    pub fn len(&self) -> usize {
        self.len
    }

    /// Whether there are no initialized elements.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.len == 0
    }

    /// Number of element slots allocated.
    #[must_use]
    pub fn cap(&self) -> usize {
        self.cap
    }

    /// Byte stride between elements.
    #[must_use]
    pub fn stride(&self) -> usize {
        self.elem_layout.size()
    }

    /// Reserve and return the next uninitialized element slot.
    pub fn next_uninit_slot(&mut self) -> Result<*mut u8, RawAllocError> {
        let required = self.len.checked_add(1).ok_or(RawAllocError::SizeOverflow {
            count: self.len,
            stride: self.elem_layout.size(),
        })?;
        self.ensure_capacity(required)?;
        Ok(unsafe { self.slot_unchecked(self.len) })
    }

    /// Mark the current next slot as initialized after the caller wrote it.
    ///
    /// # Safety
    ///
    /// The caller must have just initialized the slot returned by
    /// [`next_uninit_slot`](Self::next_uninit_slot), and must call this at most
    /// once per reserved slot.
    pub unsafe fn mark_initialized(&mut self) {
        debug_assert!(self.len < self.cap, "marking beyond reserved capacity");
        self.len += 1;
    }

    /// Mark the allocation and initialized values as adopted by the caller.
    pub fn adopt(&mut self) {
        self.len = 0;
        self.cap = 0;
        self.allocation = None;
    }

    unsafe fn slot_unchecked(&self, index: usize) -> *mut u8 {
        unsafe { self.ptr.add(index * self.elem_layout.size()) }
    }

    fn ensure_capacity(&mut self, required: usize) -> Result<(), RawAllocError> {
        if required <= self.cap {
            return Ok(());
        }

        let doubled = self.cap.checked_mul(2).ok_or(RawAllocError::SizeOverflow {
            count: self.cap,
            stride: self.elem_layout.size(),
        })?;
        let next_cap = required.max(doubled).max(4);
        let new_layout = array_layout(next_cap, self.elem_layout)?;

        if self.elem_layout.size() == 0 {
            self.cap = next_cap;
            return Ok(());
        }

        let new_ptr = if let Some(old_layout) = self.allocation {
            unsafe { alloc::realloc(self.ptr, old_layout, new_layout.size()) }
        } else {
            unsafe { alloc::alloc(new_layout) }
        };
        if new_ptr.is_null() {
            alloc::handle_alloc_error(new_layout);
        }

        self.ptr = new_ptr;
        self.cap = next_cap;
        self.allocation = Some(new_layout);
        Ok(())
    }
}

impl Drop for RawArrayBuilder {
    fn drop(&mut self) {
        for index in (0..self.len).rev() {
            let slot = unsafe { self.slot_unchecked(index) };
            unsafe { (self.drop)(self.drop_ctx, slot) };
        }

        if let Some(layout) = self.allocation.take() {
            unsafe { alloc::dealloc(self.ptr, layout) };
        }
    }
}

/// Guard for an initialized handle that must be dropped unless disarmed.
#[derive(Debug)]
pub struct HandleGuard {
    ptr: *mut u8,
    ctx: *const (),
    drop: DropThunk,
    active: bool,
}

impl HandleGuard {
    /// Track `ptr` as initialized and owned by this guard.
    #[must_use]
    pub fn new(ptr: *mut u8, ctx: *const (), drop: DropThunk) -> Self {
        Self {
            ptr,
            ctx,
            drop,
            active: true,
        }
    }

    /// The initialized handle/value pointer.
    #[must_use]
    pub fn ptr(&self) -> *mut u8 {
        self.ptr
    }

    /// Prevent this guard from dropping the handle/value.
    pub fn disarm(&mut self) {
        self.active = false;
    }
}

impl Drop for HandleGuard {
    fn drop(&mut self) {
        if self.active {
            unsafe { (self.drop)(self.ctx, self.ptr) };
        }
    }
}

/// Bookkeeping for initialized child slots.
pub struct InitializedLedger<Mark, const INLINE: usize = 8> {
    storage: LedgerStorage<Mark, INLINE>,
}

enum LedgerStorage<Mark, const INLINE: usize> {
    Inline {
        len: usize,
        initialized: u64,
        marks: [MaybeUninit<Mark>; INLINE],
    },
    Heap(Vec<Option<Mark>>),
}

impl<Mark, const INLINE: usize> InitializedLedger<Mark, INLINE> {
    /// Create a ledger with `len` uninitialized slots.
    #[must_use]
    pub fn new(len: usize) -> Self {
        let storage = if len <= INLINE && len <= u64::BITS as usize {
            LedgerStorage::Inline {
                len,
                initialized: 0,
                marks: array::from_fn(|_| MaybeUninit::uninit()),
            }
        } else {
            LedgerStorage::Heap((0..len).map(|_| None).collect())
        };
        Self { storage }
    }

    fn len(&self) -> usize {
        match &self.storage {
            LedgerStorage::Inline { len, .. } => *len,
            LedgerStorage::Heap(marks) => marks.len(),
        }
    }

    /// Return whether `index` is initialized.
    #[must_use]
    pub fn is_initialized(&self, index: usize) -> bool {
        match &self.storage {
            LedgerStorage::Inline {
                len, initialized, ..
            } => {
                assert!(index < *len, "ledger index out of bounds");
                (*initialized & initialized_bit(index)) != 0
            }
            LedgerStorage::Heap(marks) => marks[index].is_some(),
        }
    }

    /// Return the mark for `index` when initialized.
    #[must_use]
    pub fn get(&self, index: usize) -> Option<&Mark> {
        match &self.storage {
            LedgerStorage::Inline {
                len,
                initialized,
                marks,
            } => {
                assert!(index < *len, "ledger index out of bounds");
                ((*initialized & initialized_bit(index)) != 0)
                    .then(|| unsafe { marks[index].assume_init_ref() })
            }
            LedgerStorage::Heap(marks) => marks[index].as_ref(),
        }
    }

    /// Mark `index` initialized.
    pub fn mark(&mut self, index: usize, mark: Mark) {
        match &mut self.storage {
            LedgerStorage::Inline {
                len,
                initialized,
                marks,
            } => {
                assert!(index < *len, "ledger index out of bounds");
                let bit = initialized_bit(index);
                if (*initialized & bit) != 0 {
                    unsafe {
                        marks[index].assume_init_drop();
                    }
                }
                marks[index].write(mark);
                *initialized |= bit;
            }
            LedgerStorage::Heap(marks) => {
                marks[index] = Some(mark);
            }
        }
    }

    /// Initialized slots in reverse index order.
    pub fn iter_initialized_rev(&self) -> impl Iterator<Item = (usize, &Mark)> {
        (0..self.len())
            .rev()
            .filter_map(|index| self.get(index).map(|mark| (index, mark)))
    }
}

impl<Mark: Clone, const INLINE: usize> Clone for InitializedLedger<Mark, INLINE> {
    fn clone(&self) -> Self {
        Self {
            storage: self.storage.clone(),
        }
    }
}

impl<Mark: fmt::Debug, const INLINE: usize> fmt::Debug for InitializedLedger<Mark, INLINE> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_map().entries(self.iter_initialized_rev()).finish()
    }
}

impl<Mark: PartialEq, const INLINE: usize> PartialEq for InitializedLedger<Mark, INLINE> {
    fn eq(&self, other: &Self) -> bool {
        self.len() == other.len()
            && (0..self.len()).all(|index| self.get(index) == other.get(index))
    }
}

impl<Mark: Eq, const INLINE: usize> Eq for InitializedLedger<Mark, INLINE> {}

impl<Mark: Clone, const INLINE: usize> Clone for LedgerStorage<Mark, INLINE> {
    fn clone(&self) -> Self {
        match self {
            Self::Inline {
                len,
                initialized,
                marks,
            } => {
                let mut cloned = InitializedLedger::<Mark, INLINE>::new(*len);
                for (index, mark) in marks.iter().enumerate().take(*len) {
                    if (*initialized & initialized_bit(index)) != 0 {
                        cloned.mark(index, unsafe { mark.assume_init_ref() }.clone());
                    }
                }
                cloned.storage
            }
            Self::Heap(marks) => Self::Heap(marks.clone()),
        }
    }
}

impl<Mark, const INLINE: usize> Drop for LedgerStorage<Mark, INLINE> {
    fn drop(&mut self) {
        if let Self::Inline {
            len,
            initialized,
            marks,
        } = self
        {
            for (index, mark) in marks.iter_mut().enumerate().take(*len) {
                if (*initialized & initialized_bit(index)) != 0 {
                    unsafe {
                        mark.assume_init_drop();
                    }
                }
            }
        }
    }
}

fn initialized_bit(index: usize) -> u64 {
    1u64 << index
}

/// Neutral "initialize handle from scratch value" target.
#[derive(Clone, Copy, Debug)]
pub struct InitTarget {
    /// Opaque per-type context.
    pub ctx: *const (),
    /// Destination handle to initialize.
    pub handle: *mut u8,
    /// Move `*value` into `handle`.
    pub init: unsafe extern "C" fn(ctx: *const (), handle: *mut u8, value: *mut u8),
    /// Whether the initialized handle borrows from `value` instead of consuming it.
    pub retain_value: bool,
    /// Drop a retained `value` before its backing storage is freed.
    pub drop_value: Option<unsafe extern "C" fn(ctx: *const (), value: *mut u8)>,
}

impl InitTarget {
    /// Initialize the destination handle by moving from `value`.
    ///
    /// # Safety
    ///
    /// `value` must point to an initialized value of the type expected by this
    /// target, and `handle` must point to uninitialized storage for the handle.
    pub unsafe fn initialize(self, value: *mut u8) {
        unsafe { (self.init)(self.ctx, self.handle, value) };
    }
}

fn allocate_or_dangling(layout: Layout) -> *mut u8 {
    if layout.size() == 0 {
        layout.align() as *mut u8
    } else {
        let ptr = unsafe { alloc::alloc(layout) };
        if ptr.is_null() {
            alloc::handle_alloc_error(layout);
        }
        ptr
    }
}

fn empty_array_layout(align: usize) -> Layout {
    Layout::from_size_align(0, align).expect("alignment came from a valid element layout")
}

fn array_layout(count: usize, element: Layout) -> Result<Layout, RawAllocError> {
    if count == 0 || element.size() == 0 {
        return Layout::from_size_align(0, element.align()).map_err(|_| {
            RawAllocError::InvalidLayout {
                size: 0,
                align: element.align(),
            }
        });
    }

    let size = count
        .checked_mul(element.size())
        .ok_or(RawAllocError::SizeOverflow {
            count,
            stride: element.size(),
        })?;
    Layout::from_size_align(size, element.align()).map_err(|_| RawAllocError::InvalidLayout {
        size,
        align: element.align(),
    })
}

fn layout_fits(buffer: Layout, requested: Layout) -> bool {
    buffer.size() >= requested.size() && buffer.align() >= requested.align()
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::ptr;
    use std::sync::atomic::{AtomicUsize, Ordering};

    struct CountedDrop<'a>(&'a AtomicUsize);

    impl Drop for CountedDrop<'_> {
        fn drop(&mut self) {
            self.0.fetch_add(1, Ordering::SeqCst);
        }
    }

    unsafe fn count_drop(ctx: *const (), _ptr: *mut u8) {
        let drops = unsafe { &*(ctx as *const AtomicUsize) };
        drops.fetch_add(1, Ordering::SeqCst);
    }

    unsafe fn counted_drop_in_place(ctx: *const (), ptr: *mut u8) {
        let _drops = unsafe { &*(ctx as *const AtomicUsize) };
        unsafe {
            ptr::drop_in_place(ptr.cast::<CountedDrop<'_>>());
        }
    }

    #[test]
    fn raw_scratch_handles_zero_sized_storage() {
        let mut scratch = RawScratch::new(0, 8).unwrap();
        assert_eq!(scratch.ptr() as usize, 8);
        scratch.dealloc_uninit();
        scratch.dealloc_uninit();
    }

    #[test]
    fn scratch_session_reuses_released_slots() {
        let mut session = ScratchSession::new();
        let first = session.reserve(Layout::from_size_align(16, 8).unwrap());
        let first_ptr = first.ptr();
        session.release(first);

        let second = session.reserve(Layout::from_size_align(8, 4).unwrap());
        assert_eq!(second.ptr(), first_ptr);
        session.release(second);
    }

    #[test]
    fn scratch_session_keeps_active_slots_distinct() {
        let mut session = ScratchSession::new();
        let first = session.reserve(Layout::from_size_align(16, 8).unwrap());
        let second = session.reserve(Layout::from_size_align(16, 8).unwrap());
        assert_ne!(second.ptr(), first.ptr());
        session.release(second);
        session.release(first);
    }

    #[test]
    fn raw_array_buffer_checks_slots() {
        let buffer = RawArrayBuffer::new(3, 4, 4).unwrap();
        assert_eq!(buffer.cap(), 3);
        assert_eq!(buffer.stride(), 4);
        assert!(buffer.slot(3).is_none());
        let base = buffer.ptr() as usize;
        assert_eq!(buffer.slot(2).unwrap() as usize, base + 8);
    }

    #[test]
    fn raw_array_builder_grows_and_drops_initialized_elements() {
        let drops = AtomicUsize::new(0);
        let ctx = &drops as *const AtomicUsize as *const ();
        {
            let mut builder =
                RawArrayBuilder::new(Layout::new::<CountedDrop<'_>>(), ctx, counted_drop_in_place);
            for _ in 0..5 {
                let slot = builder.next_uninit_slot().unwrap();
                unsafe {
                    slot.cast::<CountedDrop<'_>>().write(CountedDrop(&drops));
                    builder.mark_initialized();
                }
            }
            assert_eq!(builder.len(), 5);
            assert!(builder.cap() >= 5);
        }
        assert_eq!(drops.load(Ordering::SeqCst), 5);
    }

    #[test]
    fn raw_array_builder_adopt_disarms_values_and_allocation() {
        let drops = AtomicUsize::new(0);
        let ctx = &drops as *const AtomicUsize as *const ();
        let element = Layout::new::<u64>();
        let mut builder = RawArrayBuilder::new(element, ctx, count_drop);
        let slot = builder.next_uninit_slot().unwrap();
        unsafe {
            slot.cast::<u64>().write(42);
            builder.mark_initialized();
        }
        assert_eq!(builder.len(), 1);
        let ptr = builder.ptr();
        let cap = builder.cap();

        builder.adopt();
        drop(builder);

        assert_eq!(drops.load(Ordering::SeqCst), 0);
        unsafe {
            alloc::dealloc(ptr, array_layout(cap, element).unwrap());
        }
    }

    #[test]
    fn raw_array_builder_handles_zero_sized_elements() {
        let drops = AtomicUsize::new(0);
        let ctx = &drops as *const AtomicUsize as *const ();
        {
            let mut builder = RawArrayBuilder::new(Layout::new::<()>(), ctx, count_drop);

            let first = builder.next_uninit_slot().unwrap();
            unsafe {
                first.cast::<()>().write(());
                builder.mark_initialized();
            }
            let second = builder.next_uninit_slot().unwrap();
            unsafe {
                second.cast::<()>().write(());
                builder.mark_initialized();
            }

            assert_eq!(builder.len(), 2);
            assert_eq!(builder.stride(), 0);
            assert_eq!(first, second);
        }
        assert_eq!(drops.load(Ordering::SeqCst), 2);
    }

    #[test]
    fn handle_guard_drops_unless_disarmed() {
        let drops = AtomicUsize::new(0);
        let ctx = &drops as *const AtomicUsize as *const ();

        {
            let value = 0u8;
            let _guard = HandleGuard::new(&value as *const u8 as *mut u8, ctx, count_drop);
        }
        assert_eq!(drops.load(Ordering::SeqCst), 1);

        {
            let value = 0u8;
            let mut guard = HandleGuard::new(&value as *const u8 as *mut u8, ctx, count_drop);
            guard.disarm();
        }
        assert_eq!(drops.load(Ordering::SeqCst), 1);
    }

    #[test]
    fn initialized_ledger_reports_reverse_order() {
        let mut ledger: InitializedLedger<&str> = InitializedLedger::new(4);
        assert!(!ledger.is_initialized(2));
        ledger.mark(1, "one");
        ledger.mark(3, "three");

        assert_eq!(ledger.get(1), Some(&"one"));
        let initialized = ledger
            .iter_initialized_rev()
            .map(|(index, mark)| (index, *mark))
            .collect::<Vec<_>>();
        assert_eq!(initialized, vec![(3, "three"), (1, "one")]);
    }

    #[test]
    fn initialized_ledger_drops_replaced_and_live_inline_marks() {
        let drops = AtomicUsize::new(0);
        {
            let mut ledger: InitializedLedger<CountedDrop<'_>> = InitializedLedger::new(1);
            ledger.mark(0, CountedDrop(&drops));
            assert_eq!(drops.load(Ordering::SeqCst), 0);

            ledger.mark(0, CountedDrop(&drops));
            assert_eq!(drops.load(Ordering::SeqCst), 1);
        }
        assert_eq!(drops.load(Ordering::SeqCst), 2);
    }

    #[test]
    fn initialized_ledger_reports_reverse_order_from_heap_storage() {
        let mut ledger: InitializedLedger<&str, 2> = InitializedLedger::new(4);
        ledger.mark(0, "zero");
        ledger.mark(2, "two");

        assert_eq!(ledger.get(2), Some(&"two"));
        let initialized = ledger
            .iter_initialized_rev()
            .map(|(index, mark)| (index, *mark))
            .collect::<Vec<_>>();
        assert_eq!(initialized, vec![(2, "two"), (0, "zero")]);
    }
}