Skip to main content

cel_runtime/
raw_stack.rs

1//! Owns aligned heterogeneous values and supports explicit raw ownership transfer.
2//!
3//! Push typed values and pop them with their matching type and padding flag.
4//! Before raw movement, release affected owners with [`RawStack::release_top`]
5//! and separately manage the released values.
6//! Ownership release is unsafe: restore the retained physical frame before
7//! owner-based operations or any possible unwinding.
8//!
9//! ```
10//! use cel_runtime::RawStack;
11//! let mut stack = RawStack::with_base_alignment(align_of::<String>());
12//! let padding = stack.push(String::from("owned"));
13//! let value = unsafe { stack.pop::<String>(padding) };
14//! assert_eq!(value, "owned");
15//! assert_eq!(stack.len(), 0);
16//! ```
17
18use crate::memory::align_index;
19use crate::raw_vec::RawVec;
20use crate::value_type::ValueType;
21use std::mem::MaybeUninit;
22use std::mem::size_of;
23
24/// A simple raw stack that stores values as raw bytes. Each value is naturally aligned given the
25/// base alignment of the stack, which is the maximum alignment of any value stored in the stack.
26/// Live values are owned until popped, explicitly released, or destroyed in reverse push order.
27///
28/// # Examples
29/// See the [module example](crate::raw_stack) for typed ownership transfer.
30#[derive(Debug)]
31/// # Thread confinement
32///
33/// The erased owners may contain non-`Send` values, so the stack remains on its
34/// creating thread.
35///
36/// ```compile_fail
37/// let mut stack = cel_runtime::RawStack::with_base_alignment(4096);
38/// stack.push(std::rc::Rc::new(()));
39/// std::thread::spawn(move || drop(stack));
40/// ```
41pub struct RawStack {
42    /// Owns the aligned bytes occupied by live stack values.
43    buffer: RawVec,
44    /// Destroys one initialized logical slot per entry, in reverse order.
45    owners: Vec<fn(&mut RawStack)>,
46    /// Retains layout and destruction metadata for erased raw slots.
47    raw_owners: Vec<RawOwner>,
48    /// Prevents erased non-`Send`/non-`Sync` owners from crossing thread boundaries.
49    thread_bound: std::marker::PhantomData<std::rc::Rc<()>>,
50}
51
52/// Records layout and optional erased destruction only for a raw-byte slot.
53#[derive(Debug)]
54struct RawOwner {
55    /// Identifies this raw slot's logical position among all owners.
56    depth: usize,
57    /// Marks the byte prefix before this slot's alignment padding.
58    before: usize,
59    /// Records the slot's required alignment.
60    align: usize,
61    /// Records the initialized value's byte size.
62    size: usize,
63    /// Supplies recursive destruction when the raw slot owns a canonical value.
64    ty: Option<ValueType>,
65}
66
67/// Restores a stack checkpoint unless explicitly disarmed.
68struct UnwindGuard<'a> {
69    /// Exclusively borrows the stack whose suffix this guard owns.
70    stack: &'a mut RawStack,
71    /// Marks the byte prefix preserved by cleanup.
72    byte_origin: usize,
73    /// Marks the logical owner prefix preserved by cleanup.
74    depth: usize,
75    /// Distinguishes rollback cleanup from a committed successful call.
76    armed: bool,
77}
78
79impl Drop for UnwindGuard<'_> {
80    /// Resumes suffix cleanup, including while another destructor unwinds.
81    ///
82    /// - Complexity: O(n + b + p) plus destruction for n suffix slots,
83    ///   b moved value bytes, and p scanned padding bytes.
84    fn drop(&mut self) {
85        if self.armed {
86            self.stack.unwind_to(self.byte_origin, self.depth);
87        }
88    }
89}
90
91impl Drop for RawStack {
92    /// Destroys every live owner in reverse order.
93    ///
94    /// - Complexity: O(n + b + p) plus destruction for n live slots,
95    ///   b moved value bytes, and p scanned padding bytes.
96    fn drop(&mut self) {
97        self.unwind_to(0, 0);
98    }
99}
100
101impl RawStack {
102    /// Creates a new `RawStack` with base alignment.
103    ///
104    /// - Precondition: `base_alignment` is a power of two.
105    ///
106    /// # Examples
107    ///
108    /// ```
109    /// use cel_runtime::raw_stack::RawStack;
110    /// let stack = RawStack::with_base_alignment(align_of::<u32>());
111    /// ```
112    #[must_use]
113    pub fn with_base_alignment(base_alignment: usize) -> Self {
114        RawStack {
115            buffer: RawVec::with_base_alignment(base_alignment),
116            owners: Vec::new(),
117            raw_owners: Vec::new(),
118            thread_bound: std::marker::PhantomData,
119        }
120    }
121
122    /// Returns the logical slot count, including zero-sized values.
123    pub(crate) fn depth(&self) -> usize {
124        self.owners.len()
125    }
126
127    /// Destroys the top owner after removing its ownership and preceding padding.
128    ///
129    /// - Precondition: The stack has at least one logical slot.
130    /// - Postcondition: The preceding prefix retains its bytes and ownership,
131    ///   including when the top value is zero-sized or its destructor panics.
132    /// - Complexity: O(p) for p padding bytes, plus destructor costs.
133    pub(crate) fn drop_top(&mut self) {
134        debug_assert!(self.depth() > 0);
135        let destroy = *self.owners.last().expect("top owner exists");
136        destroy(self);
137    }
138
139    /// Removes the latest ownership entries without destroying or changing their bytes.
140    ///
141    /// - Precondition: `count` does not exceed the logical depth.
142    /// - Postcondition: The caller owns the released values' destruction obligations.
143    /// - Complexity: O(count), excluding descriptor destruction.
144    ///
145    /// # Safety
146    ///
147    /// Removing entries can leave released bytes above the retained owners.
148    /// Before any owner-based stack operation or stack destruction, including
149    /// unwinding, the buffer's length, values, and padding must again match all
150    /// retained ownership entries. The caller must not permit unwinding while
151    /// that physical frame is invalid; complete its raw repair before invoking
152    /// user code or another potentially panicking operation.
153    /// If no owners remain, unowned bytes may remain in the buffer without
154    /// invalidating its destruction.
155    ///
156    /// Released values remain the caller's responsibility. If transferred or
157    /// destroyed, their abandoned representations must not be used again.
158    /// Intentionally forgetting a released value is permitted; leaking resources
159    /// alone does not violate memory safety.
160    ///
161    /// # Examples
162    /// See [`Self::drop_at`] for releasing a value before destroying it in place.
163    ///
164    /// Unguarded calls are rejected even when no owners would be removed:
165    /// ```compile_fail,E0133
166    /// let mut stack = cel_runtime::RawStack::with_base_alignment(1);
167    /// stack.release_top(0);
168    /// ```
169    pub unsafe fn release_top(&mut self, count: usize) {
170        debug_assert!(count <= self.depth());
171        let depth = self.depth() - count;
172        while self
173            .raw_owners
174            .last()
175            .is_some_and(|owner| owner.depth > depth)
176        {
177            self.raw_owners.pop();
178        }
179        self.owners.truncate(depth);
180    }
181
182    /// Installs erased destruction for the latest raw-byte slot.
183    ///
184    /// - Precondition: The top slot is raw, has no erased owner yet, and contains a
185    ///   valid value with the shape and layout described by `ty`.
186    pub(crate) fn own_top(&mut self, ty: ValueType) {
187        let depth = self.depth();
188        let owner = self.raw_owners.last_mut().expect("top slot must be raw");
189        debug_assert_eq!(owner.depth, depth);
190        debug_assert!(owner.ty.is_none());
191        debug_assert_eq!(owner.size, ty.size());
192        debug_assert_eq!(owner.align, ty.align());
193        owner.ty = Some(ty);
194    }
195
196    /// Destroys the suffix after `depth` and restores its preceding byte origin.
197    ///
198    /// Remaining destruction resumes if one destructor panics.
199    ///
200    /// - Precondition: `(byte_origin, depth)` identifies a live prefix checkpoint.
201    /// - Complexity: O(n + b + p) plus destructor costs for n removed slots,
202    ///   b moved value bytes, and p scanned padding bytes.
203    pub(crate) fn unwind_to(&mut self, byte_origin: usize, depth: usize) {
204        debug_assert!(depth <= self.depth());
205        debug_assert!(byte_origin <= self.len());
206        let mut guard = UnwindGuard {
207            stack: self,
208            byte_origin,
209            depth,
210            armed: true,
211        };
212        while guard.stack.depth() > depth {
213            guard.stack.drop_top();
214        }
215        guard.stack.buffer.truncate(byte_origin);
216        guard.armed = false;
217    }
218
219    /// Runs a callback, restoring a live prefix checkpoint on error or panic.
220    ///
221    /// - Precondition: `(byte_origin, depth)` identifies a live prefix that the
222    ///   callback preserves.
223    /// - Postcondition: Success retains all callback changes.
224    /// - Complexity: Callback costs, plus suffix destruction on failure.
225    ///
226    /// # Errors
227    ///
228    /// Returns the callback's error after destroying its suffix.
229    pub(crate) fn with_unwind<R>(
230        &mut self,
231        byte_origin: usize,
232        depth: usize,
233        callback: impl FnOnce(&mut RawStack) -> anyhow::Result<R>,
234    ) -> anyhow::Result<R> {
235        debug_assert!(depth <= self.depth());
236        debug_assert!(byte_origin <= self.len());
237        let mut guard = UnwindGuard {
238            stack: self,
239            byte_origin,
240            depth,
241            armed: true,
242        };
243        let result = callback(guard.stack);
244        if result.is_ok() {
245            guard.armed = false;
246        }
247        result
248    }
249
250    /// Pops and then destroys a typed owner with its statically known padding.
251    ///
252    /// - Complexity: O(s + p) plus destruction, for s value bytes and p padding bytes.
253    fn destroy_typed<T, const PADDING: bool>(&mut self) {
254        drop(unsafe { self.pop::<T>(PADDING) });
255    }
256
257    /// Removes raw ownership and bytes before invoking any erased destructor.
258    ///
259    /// - Complexity: The erased value and descriptor destruction costs.
260    fn destroy_raw(&mut self) {
261        let owner = self.raw_owners.pop().expect("raw owner exists");
262        debug_assert_eq!(owner.depth, self.depth());
263        self.owners.pop();
264        let offset = align_index(owner.align, owner.before);
265        let pointer = unsafe { self.buffer.as_mut_ptr().add(offset).cast::<u8>() };
266        self.buffer.truncate(owner.before);
267        if let Some(ty) = owner.ty {
268            unsafe { crate::owned_value::drop_raw(&ty, pointer) };
269        }
270    }
271
272    /// Returns the number of bytes currently on the stack.
273    ///
274    /// # Examples
275    /// ```
276    /// use cel_runtime::RawStack;
277    /// let mut stack = RawStack::with_base_alignment(1);
278    /// stack.push(7u8);
279    /// assert_eq!(stack.len(), 1);
280    /// ```
281    #[must_use]
282    #[allow(clippy::len_without_is_empty)]
283    pub fn len(&self) -> usize {
284        self.buffer.len()
285    }
286
287    /// Pushes a value of type `T` onto the stack.
288    ///
289    /// The stack owns the value until it is popped using the correct type or destroyed.
290    /// `T: 'static` prevents owned destructors from retaining nonstatic borrows;
291    /// borrowed inputs must instead use explicitly borrowed adapters.
292    ///
293    /// - Precondition: `T` requires no greater alignment than this stack's base alignment.
294    ///   This requirement is checked in release builds to preserve memory safety.
295    ///
296    /// # Type Parameters
297    ///
298    /// * `T`: The type of the value to push.
299    ///
300    /// # Examples
301    ///
302    /// ```
303    /// use cel_runtime::raw_stack::RawStack;
304    /// let mut stack = RawStack::with_base_alignment(align_of::<u32>());
305    /// let _ = stack.push(42u32);
306    /// ```
307    ///
308    /// A value whose destructor borrows nonstatic data cannot enter this owning stack:
309    ///
310    /// ```compile_fail,E0597
311    /// use cel_runtime::raw_stack::RawStack;
312    ///
313    /// /// Borrows text that must remain live until destruction.
314    /// struct BorrowedDrop<'a>(&'a str);
315    /// impl Drop for BorrowedDrop<'_> {
316    ///     /// Reads the borrowed text during destruction.
317    ///     fn drop(&mut self) {
318    ///         assert!(!self.0.is_empty());
319    ///     }
320    /// }
321    ///
322    /// let mut stack = RawStack::with_base_alignment(align_of::<BorrowedDrop<'static>>());
323    /// {
324    ///     let text = String::from("borrowed");
325    ///     stack.push(BorrowedDrop(&text));
326    /// }
327    /// drop(stack);
328    /// ```
329    ///
330    /// - Complexity: Amortized O(1 + s + p) time and storage, for s value bytes
331    ///   and p inserted padding bytes. Growth may copy existing bytes and owner entries.
332    pub fn push<T: 'static>(&mut self, value: T) -> bool {
333        assert!(align_of::<T>() <= self.buffer.base_alignment());
334        let len = self.buffer.len();
335        let aligned_index = align_index(align_of::<T>(), len);
336        let new_len = aligned_index
337            .checked_add(size_of::<T>())
338            .expect("stack size overflow");
339
340        self.owners.reserve(1);
341        self.buffer.reserve((new_len - len).max(1));
342        unsafe {
343            self.buffer.set_len(new_len);
344            if aligned_index - len > 0 {
345                // write a 1 in the first padding byte and 0 in the rest
346                self.buffer[len].write(1);
347                self.buffer[len + 1..aligned_index].fill(MaybeUninit::new(0));
348            }
349
350            std::ptr::write(
351                self.buffer.as_mut_ptr().add(aligned_index).cast::<T>(),
352                value,
353            );
354        }
355        let padding = aligned_index - len > 0;
356        self.owners.push(if padding {
357            Self::destroy_typed::<T, true>
358        } else {
359            Self::destroy_typed::<T, false>
360        });
361        padding
362    }
363
364    /// Pushes `size` raw bytes from `src`, aligned to `align`, using the same
365    /// padding/marker-byte bookkeeping as [`push`](Self::push).
366    ///
367    /// `src` is typed as `MaybeUninit<u8>` rather than `u8` because the bytes
368    /// being copied may include a source value's interior padding, which is
369    /// itself uninitialized — reading it through a `u8` pointer instead would
370    /// be undefined behavior even though this function never inspects the
371    /// bytes' values.
372    ///
373    /// - Precondition: `align` is a power of two no greater than the stack's base alignment.
374    /// - Postcondition: A raw-byte slot is registered; its bytes are not destroyed
375    ///   as a typed value unless upgraded with `own_top`.
376    /// - Complexity: Amortized O(1 + size + p) time and storage for p inserted
377    ///   padding bytes; growth may copy existing bytes and owner entries.
378    ///
379    /// # Examples
380    /// ```
381    /// use cel_runtime::RawStack;
382    /// let mut stack = RawStack::with_base_alignment(1);
383    /// let value = 7u8;
384    /// let padding = unsafe { stack.push_raw(1, 1, std::ptr::from_ref(&value).cast()) };
385    /// assert_eq!(unsafe { stack.pop::<u8>(padding) }, 7);
386    /// ```
387    ///
388    /// # Safety
389    /// `src` must be valid for reads of `size` bytes, and must not overlap the
390    /// stack's internal buffer.
391    pub unsafe fn push_raw(
392        &mut self,
393        align: usize,
394        size: usize,
395        src: *const MaybeUninit<u8>,
396    ) -> bool {
397        debug_assert!(align.is_power_of_two());
398        assert!(align <= self.buffer.base_alignment());
399        let len = self.buffer.len();
400        let aligned_index = align_index(align, len);
401        let new_len = aligned_index + size;
402
403        self.owners.reserve(1);
404        self.raw_owners.reserve(1);
405        self.buffer.reserve((new_len - len).max(1));
406        unsafe {
407            self.buffer.set_len(new_len);
408            if aligned_index - len > 0 {
409                self.buffer[len].write(1);
410                self.buffer[len + 1..aligned_index].fill(MaybeUninit::new(0));
411            }
412            std::ptr::copy_nonoverlapping(src, self.buffer.as_mut_ptr().add(aligned_index), size);
413        }
414        self.owners.push(Self::destroy_raw);
415        self.raw_owners.push(RawOwner {
416            depth: self.depth(),
417            before: len,
418            align,
419            size,
420            ty: None,
421        });
422        aligned_index - len > 0
423    }
424
425    /// Reserves aligned space for `size` bytes (using the same padding/marker
426    /// bookkeeping as [`push`](Self::push)) and calls `write` with a pointer
427    /// to that space instead of copying from a source buffer.
428    ///
429    /// - Precondition: `align` is a power of two no greater than the stack's base alignment.
430    /// - Postcondition: `write` is called exactly once, before this method
431    ///   returns, with a pointer to `size` freshly-reserved bytes.
432    /// - Postcondition: Normal return registers a raw-byte slot; a panicking
433    ///   initializer registers no slot, leaving byte restoration to its caller.
434    /// - Complexity: Amortized O(1 + size + p) plus initializer costs for p
435    ///   inserted padding bytes; growth may copy existing bytes and owner entries.
436    ///
437    /// # Examples
438    /// ```
439    /// use cel_runtime::RawStack;
440    /// let mut stack = RawStack::with_base_alignment(1);
441    /// let padding = unsafe { stack.reserve_and_write(1, 1, |ptr| ptr.write(7)) };
442    /// assert_eq!(unsafe { stack.pop::<u8>(padding) }, 7);
443    /// ```
444    ///
445    /// # Safety
446    /// `write` must fully initialize all `size` bytes at the pointer it's
447    /// given before returning, except interior padding. If it panics, the caller
448    /// must guard partially initialized resources.
449    pub unsafe fn reserve_and_write(
450        &mut self,
451        align: usize,
452        size: usize,
453        write: impl FnOnce(*mut u8),
454    ) -> bool {
455        debug_assert!(align.is_power_of_two());
456        assert!(align <= self.buffer.base_alignment());
457        let len = self.buffer.len();
458        let aligned_index = align_index(align, len);
459        let new_len = aligned_index + size;
460
461        self.owners.reserve(1);
462        self.raw_owners.reserve(1);
463        self.buffer.reserve((new_len - len).max(1));
464        unsafe {
465            self.buffer.set_len(new_len);
466            if aligned_index - len > 0 {
467                self.buffer[len].write(1);
468                self.buffer[len + 1..aligned_index].fill(MaybeUninit::new(0));
469            }
470            write(self.buffer.as_mut_ptr().add(aligned_index).cast::<u8>());
471        }
472        self.owners.push(Self::destroy_raw);
473        self.raw_owners.push(RawOwner {
474            depth: self.depth(),
475            before: len,
476            align,
477            size,
478            ty: None,
479        });
480        aligned_index - len > 0
481    }
482
483    /// Copies `size` bytes starting at absolute buffer offset `offset` into `dst`.
484    ///
485    /// `dst` is typed as `MaybeUninit<u8>` rather than `u8` because the bytes
486    /// being copied may be a value's interior padding, which is itself
487    /// uninitialized — reading it through a `u8` pointer instead would be
488    /// undefined behavior even though this function never inspects the
489    /// bytes' values.
490    ///
491    /// - Complexity: O(size) time and O(1) additional space.
492    ///
493    /// # Examples
494    /// See [`Self::repack`] for copying a repacked byte array into caller storage.
495    ///
496    /// # Safety
497    /// `offset..offset + size` must be within the current logical buffer;
498    /// `dst` must be valid for writes of `size` bytes and must not overlap the
499    /// stack's internal buffer.
500    pub unsafe fn copy_from(&self, offset: usize, size: usize, dst: *mut MaybeUninit<u8>) {
501        debug_assert!(offset + size <= self.buffer.len());
502        unsafe {
503            std::ptr::copy_nonoverlapping(self.buffer.as_ptr().add(offset), dst, size);
504        }
505    }
506
507    /// Drops a value in place at absolute buffer offset `offset`, without
508    /// altering the stack's tracked length.
509    ///
510    /// - Complexity: The destructor's cost; O(1) additional storage.
511    ///
512    /// # Examples
513    /// ```
514    /// use cel_runtime::RawStack;
515    /// let mut stack = RawStack::with_base_alignment(align_of::<String>());
516    /// stack.push(String::from("owned"));
517    /// // SAFETY: Releasing the sole owner leaves no retained value to destroy.
518    /// unsafe {
519    ///     stack.release_top(1);
520    ///     stack.drop_at(0, |ptr| ptr.cast::<String>().drop_in_place());
521    ///     stack.truncate_to(0, false);
522    /// }
523    /// assert_eq!(stack.len(), 0);
524    /// ```
525    ///
526    /// # Safety
527    /// `offset` must point to a live, valid value; `run_drop` must correctly
528    /// run that value's destructor given a pointer to its start. Its ownership
529    /// entry must already have been removed with `release_top`.
530    pub unsafe fn drop_at(&mut self, offset: usize, run_drop: impl FnOnce(*mut u8)) {
531        unsafe { run_drop(self.buffer.as_mut_ptr().add(offset).cast::<u8>()) };
532    }
533
534    /// Reads a value at absolute buffer offset `offset`, given a callback that
535    /// receives a pointer to its bytes.
536    ///
537    /// - Complexity: The callback's cost; O(1) additional storage.
538    ///
539    /// # Examples
540    /// ```
541    /// use cel_runtime::RawStack;
542    /// let mut stack = RawStack::with_base_alignment(align_of::<String>());
543    /// stack.push(String::from("borrowed"));
544    /// let before = stack.len();
545    /// let length = unsafe { stack.read_at(0, |ptr| (&*ptr.cast::<String>()).len()) };
546    /// assert_eq!(length, 8);
547    /// assert_eq!(stack.len(), before);
548    /// ```
549    ///
550    /// # Safety
551    /// `offset` must point to a live, valid, properly-aligned value for the type the
552    /// caller will reinterpret it as; `read` must not retain the pointer beyond the
553    /// call. This byte operation does not transfer ownership; a caller moving out
554    /// a value must explicitly release its ownership entry before destruction or
555    /// stack cleanup can occur.
556    pub unsafe fn read_at<R>(&self, offset: usize, read: impl FnOnce(*const u8) -> R) -> R {
557        unsafe { read(self.buffer.as_ptr().add(offset).cast::<u8>()) }
558    }
559
560    /// Truncates the stack back to `new_len`, additionally stripping `padding`
561    /// bytes that preceded the removed region (scanned the same way
562    /// [`pop`](Self::pop) does).
563    ///
564    /// - Complexity: O(p) time for p preceding padding bytes when `padding`
565    ///   is true, otherwise O(1); O(1) additional space.
566    ///
567    /// # Examples
568    /// See [`Self::drop_at`] for releasing, destroying, and truncating a value.
569    ///
570    /// # Safety
571    /// No live (undropped) value may exist at or above `new_len`; the caller must
572    /// explicitly release all removed ownership entries first. This byte operation
573    /// does not infer ownership transfer, including for zero-sized values.
574    pub unsafe fn truncate_to(&mut self, new_len: usize, padding: bool) {
575        debug_assert!(new_len <= self.buffer.len());
576        let padding_count = if padding {
577            self.buffer[..new_len]
578                .iter()
579                .rev()
580                .take_while(|&x| unsafe { x.assume_init() == 0 })
581                .count()
582                + 1
583        } else {
584            0
585        };
586        self.buffer.truncate(new_len - padding_count);
587    }
588
589    /// Removes the top owner's bytes and metadata, then destroys its value in place.
590    ///
591    /// - Complexity: O(p) padding-scan time plus the destructor's cost;
592    ///   O(1) additional storage, excluding the destructor.
593    ///
594    /// # Examples
595    /// ```
596    /// use cel_runtime::RawStack;
597    /// let mut stack = RawStack::with_base_alignment(align_of::<String>());
598    /// let padding = stack.push(String::from("owned"));
599    /// unsafe {
600    ///     stack.drop_sized(size_of::<String>(), padding, |ptr| {
601    ///         ptr.cast::<String>().drop_in_place()
602    ///     });
603    /// }
604    /// assert_eq!(stack.len(), 0);
605    /// ```
606    ///
607    /// # Safety
608    /// The top `size` bytes (plus padding if `padding` is true) must be a
609    /// live, valid value; `run_drop` must correctly run its destructor given a
610    /// pointer to its start. The value must have a registered top ownership entry.
611    pub unsafe fn drop_sized(
612        &mut self,
613        size: usize,
614        padding: bool,
615        run_drop: impl FnOnce(*mut u8),
616    ) {
617        debug_assert!(size <= self.buffer.len());
618        let p = self.buffer.len() - size;
619        let pointer = unsafe { self.buffer.as_mut_ptr().add(p).cast::<u8>() };
620        // SAFETY: Restore the retained prefix before calling the user's destructor.
621        unsafe {
622            self.release_top(1);
623            self.truncate_to(p, padding);
624            run_drop(pointer);
625        }
626    }
627
628    /// Repacks `sizes.len()` already-pushed values (currently at the absolute
629    /// byte offsets in `src_offsets`) into one contiguous, self-contained
630    /// region of `total_size` bytes starting at `dest_base`, placing element
631    /// `i` at `dest_base + dest_offsets[i]`. Adjusts the tracked length to
632    /// `dest_base + total_size` and returns whether leading padding was
633    /// inserted between `ambient_start` and `dest_base`.
634    ///
635    /// Preserves bytes below `ambient_start`. Source and destination fields may
636    /// move left, right, or remain in place, including self-overlapping moves.
637    /// Interior padding bytes need not be initialized.
638    ///
639    /// - Complexity: O(n + b + p + r) time for n fields, b moved bytes,
640    ///   p leading padding bytes, and r existing buffer bytes if growth relocates
641    ///   the allocation. O(1) auxiliary space beyond any buffer growth.
642    ///
643    /// # Examples
644    /// ```
645    /// use cel_runtime::RawStack;
646    /// let mut stack = RawStack::with_base_alignment(1);
647    /// stack.push([11u8, 22, 33]);
648    /// let mut bytes = [0u8; 3];
649    /// // SAFETY: All owners are released; the byte array needs no destruction.
650    /// unsafe {
651    ///     stack.release_top(1);
652    ///     assert!(stack.repack(0, 1, 3, &[0], &[0], &[3]));
653    ///     stack.copy_from(1, 3, bytes.as_mut_ptr().cast());
654    ///     stack.truncate_to(0, false);
655    /// }
656    /// assert_eq!(bytes, [11, 22, 33]);
657    /// ```
658    ///
659    /// # Safety
660    /// The slices must have equal lengths. Source ranges must lie within the
661    /// current buffer, and destination ranges within `0..total_size`.
662    /// Both layouts must have monotonically ordered, nonoverlapping fields;
663    /// corresponding fields have the same size from `sizes`.
664    /// Each field's end must be at or before the next field's start,
665    /// including zero-sized fields.
666    /// `ambient_start` must lie within the current buffer, `dest_base` must be
667    /// at least `ambient_start`, and `dest_base + total_size` must fit in `usize`.
668    /// The caller must release ownership entries for every moved value before
669    /// repacking and separately register or dispose of the resulting values.
670    /// No unrelated live value may occupy overwritten or truncated bytes.
671    /// This byte operation never infers ownership transfer.
672    pub unsafe fn repack(
673        &mut self,
674        ambient_start: usize,
675        dest_base: usize,
676        total_size: usize,
677        src_offsets: &[usize],
678        dest_offsets: &[usize],
679        sizes: &[usize],
680    ) -> bool {
681        debug_assert!(dest_base >= ambient_start);
682        debug_assert_eq!(src_offsets.len(), sizes.len());
683        debug_assert_eq!(dest_offsets.len(), sizes.len());
684
685        let current_len = self.buffer.len();
686        debug_assert!(ambient_start <= current_len);
687        debug_assert!(
688            src_offsets
689                .iter()
690                .zip(sizes)
691                .all(|(&offset, &size)| { offset <= current_len && size <= current_len - offset })
692        );
693        debug_assert!(
694            dest_offsets
695                .iter()
696                .zip(sizes)
697                .all(|(&offset, &size)| { offset <= total_size && size <= total_size - offset })
698        );
699        debug_assert!(
700            src_offsets.windows(2).zip(sizes).all(|(pair, &size)| {
701                pair[0].checked_add(size).is_some_and(|end| end <= pair[1])
702            })
703        );
704        debug_assert!(
705            dest_offsets.windows(2).zip(sizes).all(|(pair, &size)| {
706                pair[0].checked_add(size).is_some_and(|end| end <= pair[1])
707            })
708        );
709        let target_len = dest_base
710            .checked_add(total_size)
711            .expect("repacked region exceeds addressable size");
712        let grown_len = current_len.max(target_len);
713        unsafe {
714            if grown_len > current_len {
715                self.buffer.reserve(grown_len - current_len);
716                self.buffer.set_len(grown_len);
717            }
718            // Left moves cannot reach later sources. Earlier right-moving
719            // sources end before these destinations because destination fields
720            // are ordered and disjoint.
721            for (i, &size) in sizes.iter().enumerate() {
722                let source = src_offsets[i];
723                let destination = dest_base + dest_offsets[i];
724                if destination < source {
725                    self.buffer[0..grown_len].copy_within(source..source + size, destination);
726                }
727            }
728            // Reverse right moves preserve earlier unread sources. Previously
729            // moved left fields occupy disjoint destination ranges.
730            for (i, &size) in sizes.iter().enumerate().rev() {
731                let source = src_offsets[i];
732                let destination = dest_base + dest_offsets[i];
733                if destination > source {
734                    self.buffer[0..grown_len].copy_within(source..source + size, destination);
735                }
736            }
737            if dest_base > ambient_start {
738                self.buffer[ambient_start].write(1);
739                self.buffer[ambient_start + 1..dest_base].fill(MaybeUninit::new(0));
740            }
741            self.buffer.set_len(target_len);
742        }
743        dest_base > ambient_start
744    }
745
746    /// Pops a value of type `T` from the stack. Does not change the stack capacity.
747    ///
748    /// - Complexity: O(s + p) time for s value bytes and p preceding padding bytes;
749    ///   O(s) result storage and O(1) other additional space.
750    ///
751    /// # Safety
752    ///
753    /// The type `T` must be the same type as the value on the top of the stack.
754    /// `padding` must match its push result, and the value must have a registered
755    /// ownership entry. Incorrect usage can lead to undefined behavior.
756    ///
757    /// # Type Parameters
758    ///
759    /// * `T`: The type of the value to pop.
760    ///
761    /// # Examples
762    ///
763    /// ```
764    /// use cel_runtime::raw_stack::RawStack;
765    /// let mut stack = RawStack::with_base_alignment(align_of::<u32>());
766    /// let padding = stack.push(100u32);
767    /// let value: u32 = unsafe { stack.pop(padding) };
768    /// ```
769    pub unsafe fn pop<T>(&mut self, padding: bool) -> T {
770        let p: usize = self.buffer.len() - size_of::<T>();
771        let result = unsafe { std::ptr::read(self.buffer.as_ptr().add(p).cast::<T>()) };
772        // count the number of trailing 0s in the buffer before the result
773        let padding_count = if padding {
774            self.buffer[..p]
775                .iter()
776                .rev()
777                .take_while(|&x| unsafe { x.assume_init() == 0 })
778                .count()
779                + 1
780        } else {
781            0
782        };
783        self.buffer.truncate(p - padding_count);
784        // SAFETY: The result was moved out and the byte prefix already restored;
785        // removing its matching entry reconciles metadata before any cleanup.
786        unsafe { self.release_top(1) };
787        result
788    }
789
790    /// Pops a value of type `T` from the stack and drops it.
791    ///
792    /// - Complexity: O(s + p) time plus destruction, for s value bytes and p
793    ///   preceding padding bytes; O(s) temporary value storage.
794    ///
795    /// # Examples
796    /// ```
797    /// use cel_runtime::RawStack;
798    /// let mut stack = RawStack::with_base_alignment(align_of::<String>());
799    /// let padding = stack.push(String::from("owned"));
800    /// unsafe { stack.drop::<String>(padding) };
801    /// assert_eq!(stack.len(), 0);
802    /// ```
803    ///
804    /// # Safety
805    ///
806    /// The type, padding flag, and top ownership entry must satisfy
807    /// [`Self::pop`]'s safety requirements.
808    ///
809    /// Removes ownership and bytes before invoking the value's destructor.
810    pub unsafe fn drop<T>(&mut self, padding: bool) {
811        unsafe { self.pop::<T>(padding) };
812    }
813}
814
815/* Test module */
816#[cfg(test)]
817mod tests {
818    use super::*;
819    use std::cell::RefCell;
820    use std::cmp::max;
821    use std::rc::Rc;
822
823    /// Records destruction order and optionally panics after recording its identifier.
824    struct Tracked {
825        /// Identifies this value in the destruction log.
826        id: usize,
827        /// Shares the observable destruction log with the test.
828        drops: Rc<RefCell<Vec<usize>>>,
829        /// Selects the destructor-panic contract case.
830        panic: bool,
831    }
832
833    impl Drop for Tracked {
834        /// Records this owner's destruction before optionally panicking.
835        fn drop(&mut self) {
836            self.drops.borrow_mut().push(self.id);
837            assert!(!self.panic, "destructor panic");
838        }
839    }
840
841    /// Pushes a tracked owner onto the stack.
842    fn track(
843        stack: &mut RawStack,
844        drops: &Rc<RefCell<Vec<usize>>>,
845        id: usize,
846        panic: bool,
847    ) -> bool {
848        stack.push(Tracked {
849            id,
850            drops: drops.clone(),
851            panic,
852        })
853    }
854
855    #[test]
856    /// Destroys live typed owners in reverse order across mixed alignments.
857    fn live_owners_drop_in_reverse_order() {
858        let drops = Rc::new(RefCell::new(Vec::new()));
859        {
860            let mut stack = RawStack::with_base_alignment(align_of::<Tracked>());
861            track(&mut stack, &drops, 1, false);
862            stack.push(1u8);
863            track(&mut stack, &drops, 2, false);
864        }
865        assert_eq!(*drops.borrow(), [2, 1]);
866    }
867
868    #[test]
869    /// Transfers a popped owner's destruction obligation to its caller.
870    fn popped_owner_is_not_dropped_twice() {
871        let drops = Rc::new(RefCell::new(Vec::new()));
872        let mut stack = RawStack::with_base_alignment(align_of::<Tracked>());
873        let padding = track(&mut stack, &drops, 1, false);
874        let value: Tracked = unsafe { stack.pop(padding) };
875        drop(stack);
876        assert!(drops.borrow().is_empty());
877        drop(value);
878        assert_eq!(*drops.borrow(), [1]);
879    }
880
881    #[test]
882    /// Destroys the top owner and restores its preceding byte boundary, including ZSTs.
883    fn drop_top_preserves_prefix_and_padding() {
884        ZST_DROPS.with(|count| count.set(0));
885        let drops = Rc::new(RefCell::new(Vec::new()));
886        let mut stack = RawStack::with_base_alignment(align_of::<Tracked>());
887        stack.push(42u8);
888        track(&mut stack, &drops, 1, false);
889        stack.push(ZeroSized);
890        let before_zero = stack.len();
891        stack.drop_top();
892        assert_eq!(stack.len(), before_zero);
893        assert_eq!(stack.depth(), 2);
894        ZST_DROPS.with(|count| assert_eq!(count.get(), 1));
895        stack.drop_top();
896        assert_eq!(stack.len(), 1);
897        assert_eq!(stack.depth(), 1);
898        assert_eq!(*drops.borrow(), [1]);
899        let prefix: u8 = unsafe { stack.pop(false) };
900        assert_eq!(prefix, 42);
901        drop(stack);
902        assert_eq!(*drops.borrow(), [1]);
903    }
904
905    #[test]
906    /// Removes a top owner's obligation before its destructor panics.
907    fn drop_top_panic_does_not_repeat_destruction() {
908        let drops = Rc::new(RefCell::new(Vec::new()));
909        let mut stack = RawStack::with_base_alignment(align_of::<Tracked>());
910        track(&mut stack, &drops, 1, false);
911        let origin = stack.len();
912        track(&mut stack, &drops, 2, true);
913        let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
914            stack.drop_top();
915        }));
916        assert!(result.is_err());
917        assert_eq!(stack.len(), origin);
918        assert_eq!(stack.depth(), 1);
919        assert_eq!(*drops.borrow(), [2]);
920        drop(stack);
921        assert_eq!(*drops.borrow(), [2, 1]);
922    }
923
924    thread_local! {
925        /// Counts zero-sized owners destroyed on the current test thread.
926        static ZST_DROPS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
927    }
928
929    /// Counts destruction of a value that occupies no stack bytes.
930    struct ZeroSized;
931
932    impl Drop for ZeroSized {
933        /// Increments the thread-local destruction count.
934        fn drop(&mut self) {
935            ZST_DROPS.with(|count| count.set(count.get() + 1));
936        }
937    }
938
939    #[test]
940    /// Distinguishes zero-sized owners by depth and preserves the caller's prefix.
941    fn scoped_unwind_preserves_zero_sized_prefix() {
942        ZST_DROPS.with(|count| count.set(0));
943        let mut stack = RawStack::with_base_alignment(align_of::<usize>());
944        stack.push(42usize);
945        stack.push(ZeroSized);
946        let origin = stack.len();
947        let depth = stack.depth();
948        let result: anyhow::Result<()> = stack.with_unwind(origin, depth, |stack| {
949            stack.push(ZeroSized);
950            stack.push(ZeroSized);
951            anyhow::bail!("callback failed")
952        });
953        assert!(result.is_err());
954        assert_eq!(stack.len(), origin);
955        assert_eq!(stack.depth(), depth);
956        ZST_DROPS.with(|count| assert_eq!(count.get(), 2));
957        drop(stack);
958        ZST_DROPS.with(|count| assert_eq!(count.get(), 3));
959    }
960
961    #[test]
962    /// Cleans a panicking callback's suffix without destroying the caller's owner.
963    fn callback_panic_cleans_suffix() {
964        let drops = Rc::new(RefCell::new(Vec::new()));
965        let mut stack = RawStack::with_base_alignment(align_of::<Tracked>());
966        track(&mut stack, &drops, 1, false);
967        let origin = stack.len();
968        let depth = stack.depth();
969        let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
970            let _: anyhow::Result<()> = stack.with_unwind(origin, depth, |stack| {
971                track(stack, &drops, 2, false);
972                panic!("callback panic")
973            });
974        }));
975        assert!(result.is_err());
976        assert_eq!(*drops.borrow(), [2]);
977        assert_eq!(stack.depth(), depth);
978        assert_eq!(stack.len(), origin);
979        drop(stack);
980        assert_eq!(*drops.borrow(), [2, 1]);
981    }
982
983    #[test]
984    /// Resumes remaining destruction after one destructor panics.
985    fn destructor_panic_resumes_cleanup() {
986        let drops = Rc::new(RefCell::new(Vec::new()));
987        let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
988            let mut stack = RawStack::with_base_alignment(align_of::<Tracked>());
989            track(&mut stack, &drops, 1, false);
990            track(&mut stack, &drops, 2, true);
991            track(&mut stack, &drops, 3, false);
992        }));
993        assert!(result.is_err());
994        assert_eq!(*drops.borrow(), [3, 2, 1]);
995    }
996
997    #[test]
998    /// Upgrades copied raw storage into an erased destruction obligation.
999    fn raw_bytes_become_erased_owner() {
1000        let drops = Rc::new(RefCell::new(Vec::new()));
1001        let value = std::mem::ManuallyDrop::new(Tracked {
1002            id: 1,
1003            drops: drops.clone(),
1004            panic: false,
1005        });
1006        let mut stack = RawStack::with_base_alignment(align_of::<Tracked>());
1007        unsafe {
1008            stack.push_raw(
1009                align_of::<Tracked>(),
1010                size_of::<Tracked>(),
1011                (&*value as *const Tracked).cast(),
1012            );
1013        }
1014        stack.own_top(crate::value_type::ValueType::leaf::<Tracked>());
1015        drop(stack);
1016        assert_eq!(*drops.borrow(), [1]);
1017    }
1018
1019    #[test]
1020    /// Destroys an erased top owner without retaining its layout at the call site.
1021    fn drop_top_destroys_erased_owner_and_padding() {
1022        let drops = Rc::new(RefCell::new(Vec::new()));
1023        let mut stack = RawStack::with_base_alignment(align_of::<Tracked>());
1024        stack.push(42u8);
1025        unsafe {
1026            stack.reserve_and_write(align_of::<Tracked>(), size_of::<Tracked>(), |pointer| {
1027                pointer.cast::<Tracked>().write(Tracked {
1028                    id: 1,
1029                    drops: drops.clone(),
1030                    panic: false,
1031                });
1032            });
1033        }
1034        stack.own_top(ValueType::leaf::<Tracked>());
1035        stack.drop_top();
1036        assert_eq!(stack.len(), 1);
1037        assert_eq!(stack.depth(), 1);
1038        assert_eq!(*drops.borrow(), [1]);
1039        drop(stack);
1040        assert_eq!(*drops.borrow(), [1]);
1041    }
1042
1043    #[test]
1044    /// Retains successful callback pushes until normal stack destruction.
1045    fn successful_scope_keeps_owners() {
1046        let drops = Rc::new(RefCell::new(Vec::new()));
1047        let mut stack = RawStack::with_base_alignment(align_of::<Tracked>());
1048        let value = stack
1049            .with_unwind(0, 0, |stack| {
1050                track(stack, &drops, 1, false);
1051                Ok(42)
1052            })
1053            .unwrap();
1054        assert_eq!(value, 42);
1055        assert_eq!(stack.depth(), 1);
1056        assert!(drops.borrow().is_empty());
1057        drop(stack);
1058        assert_eq!(*drops.borrow(), [1]);
1059    }
1060
1061    #[test]
1062    /// Removes erased side metadata when transferring the top value to typed code.
1063    fn typed_pop_transfers_erased_owner() {
1064        let drops = Rc::new(RefCell::new(Vec::new()));
1065        let mut stack = RawStack::with_base_alignment(align_of::<Tracked>());
1066        let padding = unsafe {
1067            stack.reserve_and_write(align_of::<Tracked>(), size_of::<Tracked>(), |pointer| {
1068                pointer.cast::<Tracked>().write(Tracked {
1069                    id: 1,
1070                    drops: drops.clone(),
1071                    panic: false,
1072                });
1073            })
1074        };
1075        stack.own_top(ValueType::leaf::<Tracked>());
1076        let value: Tracked = unsafe { stack.pop(padding) };
1077        assert_eq!(stack.depth(), 0);
1078        track(&mut stack, &drops, 2, false);
1079        drop(stack);
1080        assert_eq!(*drops.borrow(), [2]);
1081        drop(value);
1082        assert_eq!(*drops.borrow(), [2, 1]);
1083    }
1084
1085    #[test]
1086    /// Leaves no valid owner registered when raw initialization panics.
1087    fn initializer_panic_registers_no_owner() {
1088        let mut stack = RawStack::with_base_alignment(align_of::<Tracked>());
1089        let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| unsafe {
1090            stack.reserve_and_write(align_of::<Tracked>(), size_of::<Tracked>(), |_| {
1091                panic!("uninitialized")
1092            });
1093        }));
1094        assert!(result.is_err());
1095        assert_eq!(stack.depth(), 0);
1096        stack.unwind_to(0, 0);
1097        assert_eq!(stack.len(), 0);
1098    }
1099
1100    #[test]
1101    /// Releases zero-sized ownership without destroying values or changing bytes.
1102    fn release_top_preserves_bytes_and_releases_zero_sized_owner() {
1103        ZST_DROPS.with(|count| count.set(0));
1104        let mut stack = RawStack::with_base_alignment(align_of::<usize>());
1105        stack.push(42usize);
1106        stack.push(ZeroSized);
1107        let origin = stack.len();
1108        // SAFETY: This unpadded ZST leaves the retained usize at the physical top.
1109        // Its destruction is intentionally omitted.
1110        unsafe { stack.release_top(1) };
1111        assert_eq!(stack.len(), origin);
1112        assert_eq!(stack.depth(), 1);
1113        let value: usize = unsafe { stack.pop(false) };
1114        assert_eq!(value, 42);
1115        drop(stack);
1116        ZST_DROPS.with(|count| assert_eq!(count.get(), 0));
1117    }
1118
1119    /// Completes suffix transfer before normal or unwinding destruction of an owned prefix.
1120    #[test]
1121    fn released_suffix_transfer_preserves_owned_prefix() {
1122        for unwind in [false, true] {
1123            let drops = Rc::new(RefCell::new(Vec::new()));
1124            let mut stack = RawStack::with_base_alignment(align_of::<Box<Tracked>>());
1125            stack.push(Box::new(Tracked {
1126                id: 1,
1127                drops: drops.clone(),
1128                panic: false,
1129            }));
1130            let origin = stack.len();
1131            stack.push(Box::new(Tracked {
1132                id: 2,
1133                drops: drops.clone(),
1134                panic: false,
1135            }));
1136            // SAFETY: The suffix is an aligned Box<Tracked>. No operation can
1137            // unwind between moving it, releasing its entry, and restoring the
1138            // retained prefix's physical end.
1139            let transferred = unsafe {
1140                let value = stack.read_at(origin, |ptr| ptr.cast::<Box<Tracked>>().read());
1141                stack.release_top(1);
1142                stack.truncate_to(origin, false);
1143                value
1144            };
1145            assert_eq!(stack.len(), origin);
1146            let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(move || {
1147                let _retained = stack;
1148                drop(transferred);
1149                assert!(
1150                    !unwind,
1151                    "unwind after completing the raw ownership protocol"
1152                );
1153            }));
1154            assert_eq!(result.is_err(), unwind);
1155            assert_eq!(*drops.borrow(), [2, 1]);
1156        }
1157    }
1158
1159    #[test]
1160    /// Restores the caller's prefix after a suffix destructor panics.
1161    fn scoped_destructor_panic_restores_prefix() {
1162        let drops = Rc::new(RefCell::new(Vec::new()));
1163        let mut stack = RawStack::with_base_alignment(align_of::<Tracked>());
1164        track(&mut stack, &drops, 1, false);
1165        let origin = stack.len();
1166        let depth = stack.depth();
1167        track(&mut stack, &drops, 2, false);
1168        track(&mut stack, &drops, 3, true);
1169        let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
1170            stack.unwind_to(origin, depth);
1171        }));
1172        assert!(result.is_err());
1173        assert_eq!(*drops.borrow(), [3, 2]);
1174        assert_eq!(stack.len(), origin);
1175        assert_eq!(stack.depth(), depth);
1176        drop(stack);
1177        assert_eq!(*drops.borrow(), [3, 2, 1]);
1178    }
1179
1180    /// Transfers a pushed scalar back to its caller without changing its value.
1181    #[test]
1182    fn push_pop_u32() {
1183        let mut stack = RawStack::with_base_alignment(align_of::<u32>());
1184        let padding = stack.push(10u32);
1185        let result: u32 = unsafe { stack.pop(padding) };
1186        assert_eq!(result, 10);
1187    }
1188
1189    /// Returns several scalar values in last-in-first-out order.
1190    #[test]
1191    fn multiple_push_pop() {
1192        let mut stack = RawStack::with_base_alignment(align_of::<u32>());
1193        let padding1 = stack.push(1u32);
1194        let padding2 = stack.push(2u32);
1195        let padding3 = stack.push(3u32);
1196        let v3: u32 = unsafe { stack.pop(padding3) };
1197        let v2: u32 = unsafe { stack.pop(padding2) };
1198        let v1: u32 = unsafe { stack.pop(padding1) };
1199        assert_eq!(v1, 1);
1200        assert_eq!(v2, 2);
1201        assert_eq!(v3, 3);
1202    }
1203
1204    /// Preserves mixed scalar types across alignment padding and reverse extraction.
1205    #[test]
1206    fn push_pop_different_types() {
1207        let mut stack = RawStack::with_base_alignment(max(align_of::<u32>(), align_of::<f64>()));
1208        let padding1 = stack.push(42u32);
1209        let padding2 = stack.push(42.14f64);
1210        let value_f: f64 = unsafe { stack.pop(padding2) };
1211        let value_u: u32 = unsafe { stack.pop(padding1) };
1212        assert_eq!(value_f, 42.14);
1213        assert_eq!(value_u, 42);
1214    }
1215
1216    /// Accounts for the initialized bytes of a pushed scalar.
1217    #[test]
1218    fn len_reflects_pushed_bytes() {
1219        let mut stack = RawStack::with_base_alignment(align_of::<u32>());
1220        assert_eq!(stack.len(), 0);
1221        let _ = stack.push(7u32);
1222        assert_eq!(stack.len(), size_of::<u32>());
1223    }
1224
1225    /// Extracts a copied raw scalar while preserving the preceding typed value.
1226    #[test]
1227    fn push_raw_round_trips_like_push() {
1228        let mut stack = RawStack::with_base_alignment(align_of::<f64>());
1229        let padding1 = stack.push(1u8);
1230        let value = 42.14f64;
1231        let padding2 = unsafe {
1232            stack.push_raw(
1233                align_of::<f64>(),
1234                size_of::<f64>(),
1235                (&value as *const f64).cast::<MaybeUninit<u8>>(),
1236            )
1237        };
1238        let popped: f64 = unsafe { stack.pop(padding2) };
1239        assert_eq!(popped, 42.14);
1240        let popped_u8: u8 = unsafe { stack.pop(padding1) };
1241        assert_eq!(popped_u8, 1);
1242    }
1243
1244    /// Uses the same alignment-padding contract for raw and typed writes.
1245    #[test]
1246    fn push_raw_padding_matches_typed_push() {
1247        let mut stack_a = RawStack::with_base_alignment(align_of::<f64>());
1248        let _ = stack_a.push(1u8);
1249        let padding_typed = stack_a.push(2.5f64);
1250
1251        let mut stack_b = RawStack::with_base_alignment(align_of::<f64>());
1252        let _ = stack_b.push(1u8);
1253        let value = 2.5f64;
1254        let padding_raw = unsafe {
1255            stack_b.push_raw(
1256                align_of::<f64>(),
1257                size_of::<f64>(),
1258                (&value as *const f64).cast::<MaybeUninit<u8>>(),
1259            )
1260        };
1261        assert_eq!(padding_typed, padding_raw);
1262    }
1263
1264    /// Preserves equivalent padding and values through callback and copying writes.
1265    #[test]
1266    fn reserve_and_write_matches_push_raw_padding_and_bytes() {
1267        let mut stack_a = RawStack::with_base_alignment(align_of::<f64>());
1268        let _ = stack_a.push(1u8);
1269        let value = 2.5f64;
1270        let padding_a = unsafe {
1271            stack_a.push_raw(
1272                align_of::<f64>(),
1273                size_of::<f64>(),
1274                (&value as *const f64).cast::<MaybeUninit<u8>>(),
1275            )
1276        };
1277
1278        let mut stack_b = RawStack::with_base_alignment(align_of::<f64>());
1279        let _ = stack_b.push(1u8);
1280        let padding_b = unsafe {
1281            stack_b.reserve_and_write(align_of::<f64>(), size_of::<f64>(), |dst| {
1282                std::ptr::write(dst.cast::<f64>(), 2.5f64);
1283            })
1284        };
1285
1286        assert_eq!(padding_a, padding_b);
1287        let popped_a: f64 = unsafe { stack_a.pop(padding_a) };
1288        let popped_b: f64 = unsafe { stack_b.pop(padding_b) };
1289        assert_eq!(popped_a, popped_b);
1290    }
1291
1292    /// Invokes the initializing writer once and returns its complete scalar value.
1293    #[test]
1294    fn reserve_and_write_runs_write_exactly_once_with_correct_size() {
1295        let mut stack = RawStack::with_base_alignment(align_of::<u32>());
1296        let mut call_count = 0;
1297        let padding = unsafe {
1298            stack.reserve_and_write(align_of::<u32>(), size_of::<u32>(), |dst| {
1299                call_count += 1;
1300                std::ptr::write(dst.cast::<u32>(), 42);
1301            })
1302        };
1303        assert_eq!(call_count, 1);
1304        let result: u32 = unsafe { stack.pop(padding) };
1305        assert_eq!(result, 42);
1306    }
1307
1308    /// Copies the requested byte range into independent caller-owned storage.
1309    #[test]
1310    fn copy_from_reads_bytes_at_offset() {
1311        let mut stack = RawStack::with_base_alignment(align_of::<u32>());
1312        let _ = stack.push(10u32);
1313        let _ = stack.push(20u32);
1314        let mut buf = [0u8; 4];
1315        unsafe { stack.copy_from(0, 4, buf.as_mut_ptr().cast::<MaybeUninit<u8>>()) };
1316        assert_eq!(u32::from_ne_bytes(buf), 10);
1317    }
1318
1319    /// Reads distinct initialized values at their absolute byte positions.
1320    #[test]
1321    fn read_at_gives_a_pointer_to_the_value_without_copying() {
1322        let mut stack = RawStack::with_base_alignment(align_of::<u32>());
1323        let _ = stack.push(10u32);
1324        let _ = stack.push(20u32);
1325        let first: u32 = unsafe { stack.read_at(0, |ptr| *ptr.cast::<u32>()) };
1326        let second: u32 = unsafe { stack.read_at(4, |ptr| *ptr.cast::<u32>()) };
1327        assert_eq!(first, 10);
1328        assert_eq!(second, 20);
1329    }
1330
1331    /// Destroys a released value once without changing the stack's byte length.
1332    #[test]
1333    fn drop_at_runs_destructor_without_changing_length() {
1334        use std::sync::Arc;
1335        use std::sync::atomic::{AtomicUsize, Ordering};
1336
1337        /// Shares an observable count of completed value destructions.
1338        struct DropCounter(Arc<AtomicUsize>);
1339        impl Drop for DropCounter {
1340            /// Records exactly one destruction in the shared counter.
1341            fn drop(&mut self) {
1342                self.0.fetch_add(1, Ordering::SeqCst);
1343            }
1344        }
1345
1346        let count = Arc::new(AtomicUsize::new(0));
1347        let mut stack = RawStack::with_base_alignment(align_of::<DropCounter>());
1348        let _ = stack.push(DropCounter(count.clone()));
1349        let len_before = stack.len();
1350        // SAFETY: No retained owner remains, including if this destructor panics.
1351        unsafe {
1352            stack.release_top(1);
1353            stack.drop_at(0, |ptr| std::ptr::drop_in_place(ptr.cast::<DropCounter>()));
1354        }
1355        assert_eq!(count.load(Ordering::SeqCst), 1);
1356        assert_eq!(stack.len(), len_before);
1357    }
1358
1359    /// Removes released bytes and their leading padding while preserving the prefix.
1360    #[test]
1361    fn truncate_to_strips_recorded_padding() {
1362        let mut stack = RawStack::with_base_alignment(align_of::<f64>());
1363        let _ = stack.push(1u8);
1364        let padding = stack.push(2.5f64); // padding == true: 7 bytes inserted before the f64
1365        let len_with_value = stack.len();
1366        // SAFETY: The released scalar needs no destruction. Restore the exact
1367        // retained prefix immediately, before any assertion can unwind.
1368        unsafe {
1369            stack.release_top(1);
1370            stack.truncate_to(len_with_value - size_of::<f64>(), padding);
1371        }
1372        assert_eq!(stack.len(), 1); // back to just the u8
1373    }
1374
1375    /// Destroys the top value once and restores the preceding byte boundary.
1376    #[test]
1377    fn drop_sized_combines_drop_at_and_truncate_to() {
1378        use std::sync::Arc;
1379        use std::sync::atomic::{AtomicUsize, Ordering};
1380
1381        /// Shares an observable count of completed value destructions.
1382        struct DropCounter(Arc<AtomicUsize>);
1383        impl Drop for DropCounter {
1384            /// Records exactly one destruction in the shared counter.
1385            fn drop(&mut self) {
1386                self.0.fetch_add(1, Ordering::SeqCst);
1387            }
1388        }
1389
1390        let count = Arc::new(AtomicUsize::new(0));
1391        let mut stack = RawStack::with_base_alignment(align_of::<DropCounter>());
1392        let _ = stack.push(1u8);
1393        let padding = stack.push(DropCounter(count.clone()));
1394        unsafe {
1395            stack.drop_sized(size_of::<DropCounter>(), padding, |ptr| {
1396                std::ptr::drop_in_place(ptr.cast::<DropCounter>())
1397            });
1398        }
1399        assert_eq!(count.load(Ordering::SeqCst), 1);
1400        assert_eq!(stack.len(), 1);
1401    }
1402
1403    /// Preserves all values when compacting differently padded source slots.
1404    #[test]
1405    fn repack_compacts_without_overwriting_unread_sources() {
1406        let mut stack = RawStack::with_base_alignment(128);
1407        stack.push(11u8);
1408        unsafe {
1409            stack.reserve_and_write(2, 1, |dst| dst.write(22));
1410            stack.reserve_and_write(128, 1, |dst| dst.write(33));
1411        }
1412        // SAFETY: All owners are released and these bytes require no destruction.
1413        unsafe { stack.release_top(3) };
1414
1415        assert!(!unsafe { stack.repack(0, 0, 3, &[0, 2, 128], &[0, 1, 2], &[1, 1, 1]) });
1416        let mut bytes = [0u8; 3];
1417        unsafe { stack.copy_from(0, 3, bytes.as_mut_ptr().cast()) };
1418        assert_eq!(bytes, [11, 22, 33]);
1419        assert_eq!(stack.len(), 3);
1420    }
1421
1422    /// Preserves mixed left/right moves, ambient bytes, and leading padding during growth.
1423    #[test]
1424    fn repack_mixes_directions_without_losing_ambient_values() {
1425        let mut stack = RawStack::with_base_alignment(128);
1426        stack.push(0xAAu8);
1427        stack.push(11u8);
1428        unsafe {
1429            stack.reserve_and_write(2, 1, |dst| dst.write(22));
1430            stack.reserve_and_write(128, 1, |dst| dst.write(33));
1431            stack.reserve_and_write(2, 1, |dst| dst.write(44));
1432            stack.reserve_and_write(128, 1, |dst| dst.write(55));
1433        }
1434        // SAFETY: This fixed layout and byte reads cannot unwind. Restore the
1435        // retained prefix before assertions or any owner-based operation.
1436        let (padding, values, length) = unsafe {
1437            stack.release_top(5);
1438            let padding = stack.repack(
1439                1,
1440                2,
1441                4095,
1442                &[1, 2, 128, 130, 256],
1443                &[0, 1, 2, 126, 4094],
1444                &[1; 5],
1445            );
1446            let values = [2, 3, 4, 128, 4096].map(|offset| stack.read_at(offset, |ptr| ptr.read()));
1447            let snapshot = (padding, values, stack.len());
1448            stack.truncate_to(2, true);
1449            snapshot
1450        };
1451        assert!(padding);
1452        assert_eq!(values, [11, 22, 33, 44, 55]);
1453        assert_eq!(length, 4097);
1454        assert_eq!(stack.depth(), 1);
1455        assert_eq!(unsafe { stack.pop::<u8>(false) }, 0xAA);
1456    }
1457
1458    /// Preserves a field whose destination overlaps its own source range.
1459    #[test]
1460    fn repack_preserves_self_overlapping_field_bytes() {
1461        let mut stack = RawStack::with_base_alignment(1);
1462        stack.push([11u8, 22, 33, 44]);
1463        // SAFETY: No retained owner remains; the released byte array is trivial.
1464        unsafe { stack.release_top(1) };
1465        assert!(unsafe { stack.repack(0, 1, 4, &[0], &[0], &[4]) });
1466        let mut bytes = [0u8; 4];
1467        unsafe { stack.copy_from(1, 4, bytes.as_mut_ptr().cast()) };
1468        assert_eq!(bytes, [11, 22, 33, 44]);
1469        assert_eq!(stack.len(), 5);
1470    }
1471
1472    /// Preserves empty layouts and fields that occupy no bytes during compaction.
1473    #[test]
1474    fn repack_handles_empty_and_zero_sized_fields() {
1475        let mut stack = RawStack::with_base_alignment(8);
1476        assert!(!unsafe { stack.repack(0, 0, 0, &[], &[], &[]) });
1477        assert_eq!(stack.len(), 0);
1478        stack.push(11u8);
1479        unsafe { stack.reserve_and_write(8, 0, |_| {}) };
1480        stack.push(22u8);
1481        // SAFETY: No retained owner remains; these scalar/ZST fields are trivial.
1482        unsafe { stack.release_top(3) };
1483        assert!(!unsafe { stack.repack(0, 0, 2, &[0, 8, 8], &[0, 1, 1], &[1, 0, 1]) });
1484        let mut bytes = [0u8; 2];
1485        unsafe { stack.copy_from(0, 2, bytes.as_mut_ptr().cast()) };
1486        assert_eq!(bytes, [11, 22]);
1487        assert_eq!(stack.len(), 2);
1488    }
1489
1490    /// Preserves values and final length when source and destination layouts coincide.
1491    #[test]
1492    fn repack_moves_elements_to_ideal_offsets_and_reports_padding() {
1493        // Ambient layout: [u8 @0][pad][u32 @4][u8 @8] — u8 then u32 then u8, each
1494        // pushed with ordinary alignment relative to a 1-byte ambient start.
1495        let mut stack = RawStack::with_base_alignment(align_of::<u32>());
1496        let ambient_start = stack.len(); // 0
1497        let _ = stack.push(0xAAu8); // element 0: ambient offset 0
1498        let _p1 = stack.push(0xBBBB_BBBBu32); // element 1: ambient offset 4 (1 byte padded to 4)
1499        let _p2 = stack.push(0xCCu8); // element 2: ambient offset 8
1500
1501        // Ideal (self-contained) layout for (u8, u32, u8) from a zero base:
1502        // offset 0 (u8), offset 4 (u32, aligned up from 1), offset 8 (u8) -> total 9,
1503        // rounded to the tuple's own max align (4) -> total_size 12.
1504        let src_offsets = [0usize, 4, 8];
1505        let dest_offsets = [0usize, 4, 8];
1506        let sizes = [1usize, 4, 1];
1507        let total_size = 12usize;
1508        let dest_base = 0usize; // ambient_start (0) is already 4-aligned
1509
1510        // SAFETY: No retained owner remains; these scalar fields are trivial.
1511        unsafe { stack.release_top(3) };
1512        let padding = unsafe {
1513            stack.repack(
1514                ambient_start,
1515                dest_base,
1516                total_size,
1517                &src_offsets,
1518                &dest_offsets,
1519                &sizes,
1520            )
1521        };
1522        assert!(
1523            !padding,
1524            "ambient_start was already aligned; no leading pad expected"
1525        );
1526        assert_eq!(stack.len(), dest_base + total_size);
1527
1528        let mut a = [0u8; 1];
1529        let mut b = [0u8; 4];
1530        let mut c = [0u8; 1];
1531        unsafe {
1532            stack.copy_from(dest_base, 1, a.as_mut_ptr().cast::<MaybeUninit<u8>>());
1533            stack.copy_from(dest_base + 4, 4, b.as_mut_ptr().cast::<MaybeUninit<u8>>());
1534            stack.copy_from(dest_base + 8, 1, c.as_mut_ptr().cast::<MaybeUninit<u8>>());
1535        }
1536        assert_eq!(a[0], 0xAA);
1537        assert_eq!(u32::from_ne_bytes(b), 0xBBBB_BBBB);
1538        assert_eq!(c[0], 0xCC);
1539    }
1540
1541    /// Preserves ordered values and ambient bytes when leading alignment shifts fields right.
1542    #[test]
1543    fn repack_shifts_right_without_corrupting_unread_source_bytes() {
1544        // A misaligned ambient_start forces dest_base > ambient_start, which
1545        // means the destination of the *first* tuple element can land inside
1546        // the *source* range of a *later*, not-yet-copied element. Processing
1547        // elements low-index-first would silently corrupt that later element's
1548        // bytes before they're read; this test fails under that ordering and
1549        // passes under the correct (reverse) ordering.
1550        let mut stack = RawStack::with_base_alignment(align_of::<u32>());
1551        let _ = stack.push(0xFFu8); // sentinel, ambient offset 0, before the tuple
1552        let ambient_start = stack.len(); // 1: misaligned relative to u32's 4-byte align
1553        let _ = stack.push(0xDDu8); // element 0: ambient offset 1
1554        let _ = stack.push(0x1122_3344u32); // element 1: ambient offset 4 (3 bytes padded)
1555
1556        // Ideal (u8, u32) layout from zero: offset 0 (u8), offset 4 (u32) -> total 8.
1557        let src_offsets = [1usize, 4];
1558        let dest_offsets = [0usize, 4];
1559        let sizes = [1usize, 4];
1560        let total_size = 8usize;
1561        let dest_base = 4usize; // align_index(4, ambient_start=1) == 4, so this shifts right
1562
1563        let mut sentinel = [0u8; 1];
1564        let mut a = [0u8; 1];
1565        let mut b = [0u8; 4];
1566        // SAFETY: The fixed copy layout cannot unwind. Remove the released
1567        // suffix and padding before assertions can expose the retained owner.
1568        let (padding, length) = unsafe {
1569            stack.release_top(2);
1570            let padding = stack.repack(
1571                ambient_start,
1572                dest_base,
1573                total_size,
1574                &src_offsets,
1575                &dest_offsets,
1576                &sizes,
1577            );
1578            let length = stack.len();
1579            stack.copy_from(0, 1, sentinel.as_mut_ptr().cast::<MaybeUninit<u8>>());
1580            stack.copy_from(dest_base, 1, a.as_mut_ptr().cast::<MaybeUninit<u8>>());
1581            stack.copy_from(dest_base + 4, 4, b.as_mut_ptr().cast::<MaybeUninit<u8>>());
1582            stack.truncate_to(dest_base, true);
1583            (padding, length)
1584        };
1585        assert!(
1586            padding,
1587            "ambient_start (1) is not 4-aligned; a leading pad is expected"
1588        );
1589        assert_eq!(length, dest_base + total_size);
1590        assert_eq!(
1591            sentinel[0], 0xFF,
1592            "bytes before the tuple must be untouched"
1593        );
1594        assert_eq!(a[0], 0xDD);
1595        assert_eq!(
1596            u32::from_ne_bytes(b),
1597            0x1122_3344,
1598            "the u32's bytes must survive the repack uncorrupted"
1599        );
1600    }
1601}