Skip to main content

cel_runtime/
owned_value.rs

1//! Owns an erased whole value together with its frozen ownership descriptor.
2//!
3//! Checked host conversion validates the complete representation before moving:
4//!
5//! ```
6//! use cel_runtime::owned_value::OwnedValue;
7//! use cel_runtime::value_type::{ArrayOf, Leaf};
8//! use cel_runtime::Array;
9//! let array = Array::from_vec(vec![String::from("owned")]);
10//! let pointer = array.as_slice().as_ptr();
11//! let owner = OwnedValue::new::<ArrayOf<Leaf<String>>>(array);
12//! let array = owner.try_into_typed::<ArrayOf<Leaf<String>>>().unwrap();
13//! assert_eq!(array.as_slice().as_ptr(), pointer);
14//! ```
15
16use std::alloc::{Layout, alloc, dealloc, handle_alloc_error};
17use std::mem::MaybeUninit;
18use std::ptr::{self, NonNull};
19
20use crate::array::RawArray;
21use crate::value_type::{AssociatedType, ValueKind, ValueRepr, ValueType};
22
23#[cfg(test)]
24thread_local! {
25    /// Counts nonzero canonical owner allocations on the current test thread.
26    pub(crate) static ALLOCATIONS: std::cell::Cell<usize> = const {
27        std::cell::Cell::new(0)
28    };
29}
30
31/// Owns one aligned allocation, including an aligned dangling pointer for ZSTs.
32///
33/// This owner deallocates storage but does not destroy its contents.
34pub(crate) struct Allocation {
35    /// Points to the allocation or a layout-aligned dangling address for a ZST.
36    pub(crate) pointer: NonNull<u8>,
37    /// Retains the exact layout required to release this allocation.
38    pub(crate) layout: Layout,
39}
40
41impl Allocation {
42    /// Allocates uninitialized storage or an aligned dangling pointer for a ZST.
43    pub(crate) fn new(layout: Layout) -> Self {
44        let pointer = if layout.size() == 0 {
45            NonNull::new(ptr::without_provenance_mut(layout.align())).unwrap()
46        } else {
47            #[cfg(test)]
48            ALLOCATIONS.with(|count| count.set(count.get() + 1));
49            // SAFETY: Layout is nonzero and valid; allocation failure aborts.
50            NonNull::new(unsafe { alloc(layout) }).unwrap_or_else(|| handle_alloc_error(layout))
51        };
52        Self { pointer, layout }
53    }
54}
55
56impl Drop for Allocation {
57    /// Releases nonzero storage after its live contents have been destroyed.
58    fn drop(&mut self) {
59        if self.layout.size() != 0 {
60            // SAFETY: This owner holds the unique allocation with this exact layout.
61            unsafe { dealloc(self.pointer.as_ptr(), self.layout) };
62        }
63    }
64}
65
66/// Owns exactly one live erased value and its complete immutable descriptor.
67///
68/// No clone, equality, formatting, or thread-safety bounds are imposed on the
69/// stored value. Consuming errors destroy the original value exactly once;
70/// borrowed capability errors leave the original value unchanged.
71///
72/// - Complexity: Destruction visits every contained value in reverse logical
73///   field/element order, using O(d) call space for nesting depth d.
74///
75/// # Examples
76///
77/// ```
78/// use cel_runtime::{owned_value::OwnedValue, value_type::Leaf};
79/// let owner = OwnedValue::new::<Leaf<String>>(String::from("hello"));
80/// assert_eq!(owner.try_into_typed::<Leaf<String>>().unwrap(), "hello");
81/// ```
82pub struct OwnedValue {
83    /// Owns storage matching the frozen value layout.
84    allocation: Allocation,
85    /// Binds complete representation, ownership, and optional capability plans.
86    value_type: ValueType,
87    /// Records whether this allocation currently contains an initialized owner.
88    live: bool,
89}
90
91/// Binds recursive debug capabilities independently of a value's ownership.
92///
93/// The formatter never clones or consumes a value. Each checked formatting
94/// boundary validates the complete shape before invoking any leaf hook.
95///
96/// # Examples
97/// ```
98/// use cel_runtime::{Leaf, OwnedValue, ValueType};
99/// let value = OwnedValue::new::<Leaf<i32>>(7)
100///     .with_value_type(ValueType::leaf::<i32>().with_debug::<Leaf<i32>>().unwrap()).unwrap();
101/// let formatter = value.prepare_debug().unwrap();
102/// assert_eq!(formatter.format(&value).unwrap(), "7");
103/// ```
104#[derive(Clone)]
105pub struct ValueFormatter {
106    /// Retains the exact shape and recursive formatting capabilities checked at preparation.
107    value_type: ValueType,
108}
109
110impl ValueFormatter {
111    /// Formats a matching live value using this previously prepared debug capability.
112    ///
113    /// # Errors
114    /// Rejects a complete shape mismatch before invoking any formatter.
115    /// - Complexity: O(n + v + s) for n type nodes, v values and s output bytes,
116    ///   excluding leaf formatting costs.
117    ///
118    /// # Examples
119    /// See [`OwnedValue::prepare_debug`].
120    pub fn format(&self, value: &OwnedValue) -> anyhow::Result<String> {
121        anyhow::ensure!(
122            self.value_type.same_shape(value.value_type()),
123            "formatter value shape mismatch"
124        );
125        let mut output = String::new();
126        // SAFETY: Preparation checks every debug hook; the boundary checks full shape.
127        unsafe { debug_raw(&self.value_type, value.as_ptr(), &mut output) };
128        Ok(output)
129    }
130}
131
132impl OwnedValue {
133    /// Prepares an independent reusable formatter without consuming or formatting this value.
134    ///
135    /// # Errors
136    /// Rejects absent debug capability at any recursive node.
137    ///
138    /// # Examples
139    /// ```
140    /// use cel_runtime::{Leaf, OwnedValue, ValueType};
141    /// let value = OwnedValue::new::<Leaf<i32>>(7)
142    ///     .with_value_type(ValueType::leaf::<i32>().with_debug::<Leaf<i32>>().unwrap()).unwrap();
143    /// assert_eq!(value.prepare_debug().unwrap().format(&value).unwrap(), "7");
144    /// ```
145    pub fn prepare_debug(&self) -> anyhow::Result<ValueFormatter> {
146        anyhow::ensure!(self.value_type.can_debug(), "debug capability unavailable");
147        Ok(ValueFormatter {
148            value_type: self.value_type.clone(),
149        })
150    }
151
152    /// Moves one bound array element and destroys every unselected element.
153    ///
154    /// # Safety
155    /// This owner must have the canonical array descriptor bound by the caller.
156    /// # Errors
157    /// Returns an error for an out-of-bounds index, destroying the consumed array.
158    /// - Complexity: O(n) sibling destruction for n array elements plus one raw move.
159    pub(crate) unsafe fn take_array_element(mut self, index: usize) -> anyhow::Result<Self> {
160        let ValueKind::Array(element) = self.value_type.kind() else {
161            unreachable!("validated canonical array projection")
162        };
163        let raw = unsafe { &*self.as_ptr().cast::<RawArray>() };
164        anyhow::ensure!(
165            index < raw.len,
166            "array index {index} is out of bounds for length {}",
167            raw.len
168        );
169        let allocation = Allocation::new(element.layout());
170        unsafe {
171            std::ptr::copy_nonoverlapping(
172                raw.ptr.as_ptr().cast::<u8>().add(index * element.size()),
173                allocation.pointer.as_ptr(),
174                element.size(),
175            );
176        }
177        let result = unsafe { Self::from_allocation(allocation, element.clone()) };
178        let _payload = Allocation {
179            pointer: raw.ptr.cast(),
180            layout: array_layout(element, raw.capacity),
181        };
182        /// Destroys the still-owned array elements during normal and unwinding cleanup.
183        struct Siblings<'a> {
184            base: *mut u8,
185            element: &'a ValueType,
186            remaining: usize,
187            skip: usize,
188        }
189        impl Siblings<'_> {
190            /// Destroys unselected elements in reverse index order.
191            fn destroy(&mut self) {
192                while self.remaining != 0 {
193                    self.remaining -= 1;
194                    if self.remaining != self.skip {
195                        unsafe {
196                            drop_raw(
197                                self.element,
198                                self.base.add(self.remaining * self.element.size()),
199                            )
200                        };
201                    }
202                }
203            }
204        }
205        impl Drop for Siblings<'_> {
206            /// Continues remaining element destruction after a sibling panics.
207            fn drop(&mut self) {
208                self.destroy();
209            }
210        }
211        let mut siblings = Siblings {
212            base: raw.ptr.as_ptr().cast(),
213            element,
214            remaining: raw.len,
215            skip: index,
216        };
217        self.live = false;
218        // The element allocation is handled below; release the header's metadata separately.
219        drop(
220            unsafe { &mut *self.allocation.pointer.as_ptr().cast::<RawArray>() }
221                .element_type
222                .take(),
223        );
224        siblings.destroy();
225        Ok(result)
226    }
227
228    /// Splits a canonical tuple into independent source-ordered field owners.
229    ///
230    /// Nested arrays retain their payload allocations; no leaf is cloned.
231    /// # Errors
232    /// Rejects a nontuple owner without transferring any field ownership.
233    /// - Complexity: O(n + s) field allocations and raw moves for n fields and s bytes.
234    ///
235    /// # Examples
236    /// ```
237    /// use cel_runtime::{OwnedValue, Cons, Leaf, Nil, IntoCStackList};
238    /// let tuple = OwnedValue::new::<Cons<Leaf<i32>, Nil>>((7,).into_c_stack_list());
239    /// let fields = tuple.into_fields().unwrap();
240    /// assert_eq!(fields.len(), 1);
241    /// ```
242    pub fn into_fields(mut self) -> anyhow::Result<Vec<Self>> {
243        let crate::value_type::ValueKind::Tuple(fields) = self.value_type.kind() else {
244            anyhow::bail!("canonical tuple owner required");
245        };
246        let destinations: Vec<_> = fields
247            .iter()
248            .map(|field| {
249                (
250                    Allocation::new(field.value_type.layout()),
251                    field.offset,
252                    field.value_type.clone(),
253                )
254            })
255            .collect();
256        let mut result = Vec::with_capacity(destinations.len());
257        let source = self.as_ptr();
258        // Every allocation precedes the first transfer; no callback, allocation,
259        // or fallible operation follows disarming this enclosing owner.
260        self.live = false;
261        for (allocation, offset, value_type) in destinations {
262            unsafe {
263                std::ptr::copy_nonoverlapping(
264                    source.add(offset),
265                    allocation.pointer.as_ptr(),
266                    value_type.size(),
267                );
268                result.push(Self::from_allocation(allocation, value_type));
269            }
270        }
271        Ok(result)
272    }
273
274    /// Moves a previously validated tuple field and destroys the remaining fields.
275    ///
276    /// # Safety
277    /// This owner must be a canonical tuple and `index` must be in range.
278    /// The caller must bind the returned field's full descriptor before execution.
279    /// - Complexity: O(n) destruction calls for n fields plus one field move.
280    pub(crate) unsafe fn take_field(mut self, index: usize) -> Self {
281        let crate::value_type::ValueKind::Tuple(fields) = self.value_type.kind() else {
282            unreachable!("validated tuple projection")
283        };
284        let selected = &fields[index];
285        let allocation = Allocation::new(selected.value_type.layout());
286        unsafe {
287            std::ptr::copy_nonoverlapping(
288                self.as_ptr().add(selected.offset),
289                allocation.pointer.as_ptr(),
290                selected.value_type.size(),
291            );
292        }
293        let result = unsafe { Self::from_allocation(allocation, selected.value_type.clone()) };
294        self.live = false;
295        /// Continues sibling destruction if one sibling destructor unwinds.
296        struct Siblings<'a> {
297            pointer: *mut u8,
298            fields: &'a [crate::value_type::AssociatedType],
299            remaining: usize,
300            skip: usize,
301        }
302        impl Siblings<'_> {
303            /// Destroys unselected fields in reverse source order.
304            fn destroy(&mut self) {
305                while self.remaining != 0 {
306                    self.remaining -= 1;
307                    if self.remaining != self.skip {
308                        let field = &self.fields[self.remaining];
309                        unsafe { drop_raw(&field.value_type, self.pointer.add(field.offset)) };
310                    }
311                }
312            }
313        }
314        impl Drop for Siblings<'_> {
315            /// Continues cleanup after the first destructor panic.
316            fn drop(&mut self) {
317                self.destroy();
318            }
319        }
320        let mut siblings = Siblings {
321            pointer: self.allocation.pointer.as_ptr(),
322            fields,
323            remaining: fields.len(),
324            skip: index,
325        };
326        siblings.destroy();
327        result
328    }
329    /// Adopts an allocation containing one fully initialized canonical value.
330    ///
331    /// # Safety
332    ///
333    /// The allocation must uniquely own one live value of exactly `value_type`,
334    /// including all nested allocations, with no other destruction responsibility.
335    pub(crate) unsafe fn from_allocation(allocation: Allocation, value_type: ValueType) -> Self {
336        debug_assert_eq!(allocation.layout, value_type.layout());
337        Self {
338            allocation,
339            value_type,
340            live: true,
341        }
342    }
343
344    /// Takes ownership using the sealed witness's canonical descriptor.
345    ///
346    /// Moving an array copies only its header and preserves its element allocation.
347    ///
348    /// - Complexity: O(n) descriptor construction plus one concrete value move,
349    ///   for n witness nodes; no contained values are cloned.
350    ///
351    /// # Examples
352    ///
353    /// ```
354    /// use cel_runtime::{owned_value::OwnedValue, value_type::Leaf};
355    /// let _ = OwnedValue::new::<Leaf<String>>(String::from("owned"));
356    /// ```
357    pub fn new<R: ValueRepr>(value: R::Value) -> Self {
358        let value_type = R::value_type();
359        debug_assert_eq!(value_type.layout(), Layout::new::<R::Value>());
360        let allocation = Allocation::new(value_type.layout());
361        // SAFETY: The sealed witness supplies precisely R::Value's layout.
362        unsafe { allocation.pointer.as_ptr().cast::<R::Value>().write(value) };
363        Self {
364            allocation,
365            value_type,
366            live: true,
367        }
368    }
369
370    /// Borrows this whole value's frozen descriptor.
371    ///
372    /// # Examples
373    ///
374    /// ```
375    /// use cel_runtime::{owned_value::OwnedValue, value_type::{Leaf, ValueType}};
376    /// let owner = OwnedValue::new::<Leaf<i32>>(1);
377    /// assert!(owner.value_type().same_shape(&ValueType::leaf::<i32>()));
378    /// ```
379    pub fn value_type(&self) -> &ValueType {
380        &self.value_type
381    }
382
383    /// Attaches independently configured capabilities after complete shape validation.
384    ///
385    /// The live representation and allocation do not change.
386    ///
387    /// - Complexity: O(n) comparison time and O(d) call space for n type nodes
388    ///   and nesting depth d.
389    ///
390    /// # Errors
391    ///
392    /// Returns an error if any identity or physical layout differs. On error the
393    /// consumed original is destroyed exactly once using its original descriptor;
394    /// none of the supplied descriptor's value hooks execute.
395    ///
396    /// # Examples
397    ///
398    /// ```
399    /// use cel_runtime::{owned_value::OwnedValue, value_type::{Leaf, ValueType}};
400    /// let owner = OwnedValue::new::<Leaf<String>>(String::from("clone me"))
401    ///     .with_value_type(ValueType::cloneable_leaf::<String>()).unwrap();
402    /// assert!(owner.try_clone().is_ok());
403    /// ```
404    pub fn with_value_type(mut self, value_type: ValueType) -> anyhow::Result<Self> {
405        anyhow::ensure!(
406            self.value_type.same_shape(&value_type),
407            "value representation mismatch"
408        );
409        self.value_type = value_type;
410        Ok(self)
411    }
412
413    /// Moves into the concrete witness type after checking the entire descriptor.
414    ///
415    /// - Postcondition: Success preserves contained allocations and transfers
416    ///   ownership without cloning or running value destructors.
417    /// - Complexity: O(n) witness construction and comparison for n type nodes,
418    ///   plus a move of the concrete representation.
419    ///
420    /// # Errors
421    ///
422    /// Returns an error on any identity or physical layout mismatch. The consumed
423    /// original is then destroyed exactly once; no unrelated typed access occurs.
424    ///
425    /// # Examples
426    ///
427    /// ```
428    /// use cel_runtime::{owned_value::OwnedValue, value_type::Leaf};
429    /// assert_eq!(OwnedValue::new::<Leaf<i32>>(7)
430    ///     .try_into_typed::<Leaf<i32>>().unwrap(), 7);
431    /// ```
432    pub fn try_into_typed<R: ValueRepr>(mut self) -> anyhow::Result<R::Value> {
433        self.value_type.validate::<R>()?;
434        let mut destination = MaybeUninit::<R::Value>::uninit();
435        // SAFETY: Complete validation established the exact destination type.
436        unsafe {
437            self.move_into(destination.as_mut_ptr().cast());
438            Ok(destination.assume_init())
439        }
440    }
441
442    /// Moves into an exact previously bound concrete representation.
443    ///
444    /// # Safety
445    /// This owner's complete descriptor must match `R`, not merely its carrier.
446    /// - Complexity: O(s) for s representation bytes.
447    ///
448    /// # Examples
449    /// Prefer [`Self::try_into_typed`] at checked host boundaries.
450    pub unsafe fn into_typed_bound<R: ValueRepr>(mut self) -> R::Value {
451        let mut destination = MaybeUninit::<R::Value>::uninit();
452        unsafe {
453            self.move_into(destination.as_mut_ptr().cast());
454            destination.assume_init()
455        }
456    }
457
458    /// Clones through the frozen plan without consuming or mutating this value.
459    ///
460    /// If a leaf clone panics, every completed cloned prefix is destroyed and
461    /// its storage released; this original remains live.
462    ///
463    /// - Complexity: O(v) traversal time, O(d) call space, and storage for the
464    ///   cloned values, excluding leaf clone costs; v counts contained values.
465    ///
466    /// # Errors
467    ///
468    /// Returns an error before cloning anything if cloning is unavailable.
469    ///
470    /// # Examples
471    ///
472    /// ```
473    /// use cel_runtime::{owned_value::OwnedValue, value_type::{Leaf, ValueType}};
474    /// let original = OwnedValue::new::<Leaf<String>>(String::from("leaf"))
475    ///     .with_value_type(ValueType::cloneable_leaf::<String>()).unwrap();
476    /// assert_eq!(original.try_clone().unwrap()
477    ///     .try_into_typed::<Leaf<String>>().unwrap(), "leaf");
478    /// ```
479    pub fn try_clone(&self) -> anyhow::Result<Self> {
480        anyhow::ensure!(self.value_type.can_clone(), "clone capability unavailable");
481        let mut cloned = Self {
482            allocation: Allocation::new(self.value_type.layout()),
483            value_type: self.value_type.clone(),
484            live: false,
485        };
486        // SAFETY: The frozen plan is cloneable and both allocations match it.
487        unsafe {
488            clone_raw(
489                &self.value_type,
490                self.as_ptr(),
491                cloned.allocation.pointer.as_ptr(),
492            )
493        };
494        cloned.live = true;
495        Ok(cloned)
496    }
497
498    /// Compares same-shaped values through this owner's independent equality plan.
499    ///
500    /// The other owner's capability configuration need not match this one's.
501    ///
502    /// - Complexity: O(n + v) worst-case traversal time and O(d) call space,
503    ///   excluding leaf equality costs, for n type nodes and v contained values.
504    ///
505    /// # Errors
506    ///
507    /// Returns an error without invoking equality if shapes differ or this
508    /// owner's equality capability is absent. Neither owner is consumed.
509    ///
510    /// # Examples
511    ///
512    /// ```
513    /// use cel_runtime::{owned_value::OwnedValue, value_type::{Leaf, ValueType}};
514    /// let a = OwnedValue::new::<Leaf<i32>>(1)
515    ///     .with_value_type(ValueType::leaf::<i32>().with_equality::<Leaf<i32>>().unwrap())
516    ///     .unwrap();
517    /// assert!(a.try_eq(&OwnedValue::new::<Leaf<i32>>(1)).unwrap());
518    /// ```
519    pub fn try_eq(&self, other: &Self) -> anyhow::Result<bool> {
520        anyhow::ensure!(
521            self.value_type.same_shape(&other.value_type),
522            "value representation mismatch"
523        );
524        anyhow::ensure!(
525            self.value_type.can_compare(),
526            "equality capability unavailable"
527        );
528        // SAFETY: Both live values match this prevalidated comparable plan.
529        Ok(unsafe { equal_raw(&self.value_type, self.as_ptr(), other.as_ptr()) })
530    }
531
532    /// Formats through the independent debug plan without consuming the value.
533    ///
534    /// Structural arrays use brackets; tuples use parentheses in source order.
535    ///
536    /// - Complexity: O(v + s) time, O(d) call space, and O(s) output storage,
537    ///   excluding leaf formatting costs, for v values and s output bytes.
538    ///
539    /// # Errors
540    ///
541    /// Returns an error before formatting anything if debug support is absent.
542    ///
543    /// # Examples
544    ///
545    /// ```
546    /// use cel_runtime::{owned_value::OwnedValue, value_type::{Leaf, ValueType}};
547    /// let owner = OwnedValue::new::<Leaf<i32>>(7)
548    ///     .with_value_type(ValueType::leaf::<i32>().with_debug::<Leaf<i32>>().unwrap())
549    ///     .unwrap();
550    /// assert_eq!(owner.try_debug().unwrap(), "7");
551    /// ```
552    pub fn try_debug(&self) -> anyhow::Result<String> {
553        anyhow::ensure!(self.value_type.can_debug(), "debug capability unavailable");
554        let mut output = String::new();
555        // SAFETY: This live value matches its prevalidated debug plan.
556        unsafe { debug_raw(&self.value_type, self.as_ptr(), &mut output) };
557        Ok(output)
558    }
559
560    /// Borrows the raw representation for trusted, already validated execution.
561    ///
562    /// The pointer remains live only while this owner remains borrowed.
563    ///
564    /// # Examples
565    /// ```
566    /// let owner = cel_runtime::OwnedValue::new::<cel_runtime::Leaf<i32>>(1);
567    /// assert!(!owner.as_ptr().is_null());
568    /// ```
569    pub fn as_ptr(&self) -> *const u8 {
570        debug_assert!(self.live);
571        self.allocation.pointer.as_ptr()
572    }
573
574    /// Compares values whose complete identity has already been bound by a host.
575    ///
576    /// # Safety
577    /// Both owners must have exactly the same complete shape, and this owner's
578    /// descriptor must support equality.
579    /// - Complexity: O(v) for v contained values, excluding leaf comparison costs.
580    ///
581    /// # Examples
582    /// Use [`Self::try_eq`] at checked host boundaries.
583    pub unsafe fn eq_bound(&self, other: &Self) -> bool {
584        unsafe { equal_raw(&self.value_type, self.as_ptr(), other.as_ptr()) }
585    }
586
587    /// Transfers the representation without any runtime identity checks.
588    ///
589    /// - Postcondition: This owner no longer destroys the transferred value.
590    /// - Complexity: O(s) bytes copied for representation size s.
591    ///
592    /// # Safety
593    ///
594    /// The caller must have prevalidated the full identity and layout. The
595    /// destination must be aligned, disjoint uninitialized storage for exactly
596    /// this representation, and must assume unique destruction responsibility.
597    pub(crate) unsafe fn move_into(&mut self, destination: *mut u8) {
598        debug_assert!(self.live);
599        // SAFETY: The caller guarantees disjoint storage of the validated size.
600        // Byte copying preserves potentially uninitialized padding without reading it.
601        unsafe {
602            ptr::copy_nonoverlapping(self.as_ptr(), destination, self.value_type.layout().size());
603        }
604        self.live = false;
605    }
606}
607
608impl Drop for OwnedValue {
609    /// Destroys the live value before its allocation is automatically released.
610    fn drop(&mut self) {
611        if self.live {
612            self.live = false;
613            // SAFETY: This owner uniquely owns one initialized value of this plan.
614            unsafe { drop_raw(&self.value_type, self.allocation.pointer.as_ptr()) };
615        }
616    }
617}
618
619/// Describes initialized children without per-element descriptors or allocations.
620pub(crate) enum Children<'a> {
621    /// Source-ordered tuple fields at canonical offsets.
622    Fields(&'a [AssociatedType]),
623    /// Homogeneous elements at their concrete stride.
624    Elements(&'a ValueType),
625}
626
627impl Children<'_> {
628    /// Locates one initialized child relative to the aggregate base.
629    fn child(&self, index: usize) -> (&ValueType, usize) {
630        match self {
631            Self::Fields(fields) => (&fields[index].value_type, fields[index].offset),
632            Self::Elements(element) => (element, index * element.layout().size()),
633        }
634    }
635}
636
637/// Destroys a live child prefix backwards, including remaining children on unwind.
638pub(crate) struct Prefix<'a> {
639    /// Points to the caller-owned tuple or element allocation.
640    pub(crate) base: *mut u8,
641    /// Supplies source-ordered child layouts and ownership operations.
642    pub(crate) children: Children<'a>,
643    /// Counts the live child prefix still requiring destruction.
644    pub(crate) initialized: usize,
645}
646
647impl Prefix<'_> {
648    /// Destroys remaining initialized children in reverse logical order.
649    ///
650    /// Decrements the live prefix before each destructor so this guard's own
651    /// destructor resumes at the next child if the first destructor unwinds.
652    ///
653    /// - Complexity: O(n) child destructions and O(1) local space.
654    ///
655    /// # Safety
656    ///
657    /// The prefix must uniquely own exactly `initialized` live children matching
658    /// `children`, at their validated offsets from `base`.
659    pub(crate) unsafe fn destroy(&mut self) {
660        while self.initialized != 0 {
661            self.initialized -= 1;
662            let (value_type, offset) = self.children.child(self.initialized);
663            unsafe { drop_raw(value_type, self.base.add(offset)) };
664        }
665    }
666}
667
668impl Drop for Prefix<'_> {
669    /// Destroys any initialized children not yet transferred or destroyed.
670    fn drop(&mut self) {
671        // SAFETY: Private construction and prefix updates maintain live ownership.
672        unsafe { self.destroy() };
673    }
674}
675
676/// Returns the exact global-allocation layout for a concrete array capacity.
677///
678/// - Precondition: Capacity comes from a valid array header of this element type.
679fn array_layout(element: &ValueType, capacity: usize) -> Layout {
680    Layout::from_size_align(
681        element
682            .layout()
683            .size()
684            .checked_mul(capacity)
685            .expect("valid array capacity"),
686        element.layout().align(),
687    )
688    .expect("valid array allocation layout")
689}
690
691/// Destroys a prevalidated live representation and all its owned allocations.
692///
693/// - Complexity: O(v) traversal time and O(d) call space for v values and depth d.
694///
695/// # Safety
696///
697/// `pointer` must uniquely own one aligned live value matching `value_type`.
698pub(crate) unsafe fn drop_raw(value_type: &ValueType, pointer: *mut u8) {
699    if let Some(dropper) = value_type.leaf_drop() {
700        unsafe { dropper(pointer) };
701        return;
702    }
703    match value_type.kind() {
704        ValueKind::Tuple(fields) => {
705            let mut prefix = Prefix {
706                base: pointer,
707                children: Children::Fields(fields),
708                initialized: fields.len(),
709            };
710            unsafe { prefix.destroy() };
711        }
712        ValueKind::Array(_) => unsafe { pointer.cast::<RawArray>().drop_in_place() },
713        // No public constructor supplies callable storage before its carrier exists.
714        ValueKind::Leaf(_) | ValueKind::Callable { .. } => unreachable!("missing ownership plan"),
715    }
716}
717
718/// Clones through a frozen, prevalidated plan with panic-safe prefix ownership.
719///
720/// - Complexity: O(v) traversal time, O(d) call space, and cloned value storage.
721///
722/// # Safety
723///
724/// The plan must support cloning. Source must be live and aligned; destination
725/// must be disjoint, aligned uninitialized storage of the same complete shape.
726/// A panic leaves no initialized value in the destination.
727pub(crate) unsafe fn clone_raw(value_type: &ValueType, source: *const u8, destination: *mut u8) {
728    debug_assert!(value_type.can_clone());
729    if let Some(cloner) = value_type.clone_hook() {
730        unsafe { cloner(source, destination) };
731        return;
732    }
733    match value_type.kind() {
734        ValueKind::Tuple(fields) => {
735            let mut prefix = Prefix {
736                base: destination,
737                children: Children::Fields(fields),
738                initialized: 0,
739            };
740            for field in fields {
741                unsafe {
742                    clone_raw(
743                        &field.value_type,
744                        source.add(field.offset),
745                        destination.add(field.offset),
746                    );
747                }
748                prefix.initialized += 1;
749            }
750            prefix.initialized = 0;
751        }
752        ValueKind::Array(element) => {
753            let source = unsafe { &*source.cast::<RawArray>() };
754            let capacity = if element.layout().size() == 0 {
755                usize::MAX
756            } else {
757                source.len
758            };
759            let allocation = Allocation::new(array_layout(element, capacity));
760            let mut prefix = Prefix {
761                base: allocation.pointer.as_ptr(),
762                children: Children::Elements(element),
763                initialized: 0,
764            };
765            for index in 0..source.len {
766                let offset = index * element.layout().size();
767                unsafe {
768                    clone_raw(
769                        element,
770                        source.ptr.as_ptr().cast::<u8>().add(offset),
771                        allocation.pointer.as_ptr().add(offset),
772                    );
773                }
774                prefix.initialized += 1;
775            }
776            unsafe {
777                destination.cast::<RawArray>().write(RawArray::from_erased(
778                    allocation.pointer.cast(),
779                    source.len,
780                    capacity,
781                    element.clone(),
782                ));
783            }
784            prefix.initialized = 0;
785            std::mem::forget(allocation);
786        }
787        ValueKind::Leaf(_) | ValueKind::Callable { .. } => unreachable!("missing clone plan"),
788    }
789}
790
791/// Compares live values using a prevalidated complete equality plan.
792///
793/// - Complexity: O(v) traversal time and O(d) call space, excluding leaf costs.
794///
795/// # Safety
796///
797/// Both live values must match the complete comparable descriptor.
798unsafe fn equal_raw(value_type: &ValueType, left: *const u8, right: *const u8) -> bool {
799    if let Some(equal) = value_type.equality_hook() {
800        return unsafe { equal(left, right) };
801    }
802    match value_type.kind() {
803        ValueKind::Tuple(fields) => fields.iter().all(|field| unsafe {
804            equal_raw(
805                &field.value_type,
806                left.add(field.offset),
807                right.add(field.offset),
808            )
809        }),
810        ValueKind::Array(element) => {
811            let left = unsafe { &*left.cast::<RawArray>() };
812            let right = unsafe { &*right.cast::<RawArray>() };
813            left.len == right.len
814                && (0..left.len).all(|index| unsafe {
815                    let offset = index * element.layout().size();
816                    equal_raw(
817                        element,
818                        left.ptr.as_ptr().cast::<u8>().add(offset),
819                        right.ptr.as_ptr().cast::<u8>().add(offset),
820                    )
821                })
822        }
823        ValueKind::Leaf(_) | ValueKind::Callable { .. } => unreachable!("missing equality plan"),
824    }
825}
826
827/// Formats live values in source order using a prevalidated debug plan.
828///
829/// - Complexity: O(v + s) time and O(d + s) space, excluding leaf costs.
830///
831/// # Safety
832///
833/// The live value must match the complete debug-capable descriptor.
834unsafe fn debug_raw(value_type: &ValueType, pointer: *const u8, output: &mut String) {
835    if let Some(debug) = value_type.debug_hook() {
836        unsafe { debug(pointer, output) };
837        return;
838    }
839    match value_type.kind() {
840        ValueKind::Tuple(fields) => {
841            output.push('(');
842            for (index, field) in fields.iter().enumerate() {
843                if index != 0 {
844                    output.push_str(", ");
845                }
846                unsafe { debug_raw(&field.value_type, pointer.add(field.offset), output) };
847            }
848            if fields.len() == 1 {
849                output.push(',');
850            }
851            output.push(')');
852        }
853        ValueKind::Array(element) => {
854            output.push('[');
855            let raw = unsafe { &*pointer.cast::<RawArray>() };
856            for index in 0..raw.len {
857                if index != 0 {
858                    output.push_str(", ");
859                }
860                unsafe {
861                    debug_raw(
862                        element,
863                        raw.ptr
864                            .as_ptr()
865                            .cast::<u8>()
866                            .add(index * element.layout().size()),
867                        output,
868                    )
869                };
870            }
871            output.push(']');
872        }
873        ValueKind::Leaf(_) | ValueKind::Callable { .. } => unreachable!("missing debug plan"),
874    }
875}
876
877#[cfg(test)]
878mod tests {
879    /// Reuses prepared formatting for matching owners and rejects unavailable or mismatched shapes.
880    #[test]
881    fn prepared_formatter_contract() -> anyhow::Result<()> {
882        let plain = super::OwnedValue::new::<crate::Leaf<String>>(String::from("first"));
883        assert!(plain.prepare_debug().is_err());
884        let owner = plain.with_value_type(
885            crate::ValueType::leaf::<String>().with_debug::<crate::Leaf<String>>()?,
886        )?;
887        let formatter = owner.prepare_debug()?;
888        let other = super::OwnedValue::new::<crate::Leaf<String>>(String::from("second"));
889        assert_eq!(formatter.format(&owner)?, "\"first\"");
890        assert_eq!(formatter.clone().format(&other)?, "\"second\"");
891        let mismatch = super::OwnedValue::new::<crate::Leaf<u32>>(7);
892        assert!(formatter.format(&mismatch).is_err());
893        assert_eq!(formatter.format(&owner)?, "\"first\"");
894        assert_eq!(mismatch.try_into_typed::<crate::Leaf<u32>>()?, 7);
895        Ok(())
896    }
897
898    use super::*;
899    use crate::{Array, ArrayOf, Cons, IntoCStackList, IntoRustTuple, Leaf, Nil};
900    use std::{cell::Cell, rc::Rc};
901
902    /// Preserves recursive equality and isolates cloned mutable leaf storage.
903    #[test]
904    fn recursive_clone_is_an_independent_equal_value() {
905        type Row = Cons<ArrayOf<Leaf<String>>, Nil>;
906        let descriptor = ValueType::tuple(vec![AssociatedType {
907            offset: 0,
908            value_type: ValueType::array(
909                ValueType::cloneable_leaf::<String>()
910                    .with_equality::<Leaf<String>>()
911                    .unwrap()
912                    .with_debug::<Leaf<String>>()
913                    .unwrap(),
914            ),
915        }])
916        .unwrap();
917        let original = OwnedValue::new::<Row>(
918            (Array::from_vec(vec![String::from("leaf")]),).into_c_stack_list(),
919        )
920        .with_value_type(descriptor)
921        .unwrap();
922        let cloned = original.try_clone().unwrap();
923        assert!(original.try_eq(&cloned).unwrap());
924        assert!(cloned.try_eq(&original).unwrap());
925        assert!(original.try_eq(&original).unwrap());
926        let formatter = original.prepare_debug().unwrap();
927        assert_eq!(formatter.format(&cloned).unwrap(), "([\"leaf\"],)");
928        assert_eq!(original.try_debug().unwrap(), "([\"leaf\"],)");
929        let (original,) = original.try_into_typed::<Row>().unwrap().into_rust_tuple();
930        let (cloned,) = cloned.try_into_typed::<Row>().unwrap().into_rust_tuple();
931        let mut original = original.into_vec();
932        let mut cloned = cloned.into_vec();
933        original[0].push_str(" original");
934        assert_eq!(cloned, ["leaf"]);
935        cloned[0].push_str(" clone");
936        assert_eq!(original, ["leaf original"]);
937    }
938
939    /// Leaves a borrowed original available when optional capabilities are absent.
940    #[test]
941    fn missing_capabilities_preserve_value() {
942        let original = OwnedValue::new::<Leaf<String>>(String::from("owned"));
943        assert!(original.try_clone().is_err());
944        assert!(original.try_eq(&original).is_err());
945        assert!(original.try_debug().is_err());
946        assert!(original.prepare_debug().is_err());
947        assert_eq!(original.try_into_typed::<Leaf<String>>().unwrap(), "owned");
948    }
949
950    /// Destroys the consumed owner exactly once after a checked conversion mismatch.
951    #[test]
952    fn consuming_shape_error_releases_original() {
953        /// Records the release of a move-only leaf.
954        struct Tracked(Rc<Cell<usize>>);
955        impl Drop for Tracked {
956            /// Records this leaf's release.
957            fn drop(&mut self) {
958                self.0.set(self.0.get() + 1);
959            }
960        }
961        let drops = Rc::new(Cell::new(0));
962        let owner = OwnedValue::new::<Leaf<Tracked>>(Tracked(drops.clone()));
963        assert!(owner.try_into_typed::<Leaf<u8>>().is_err());
964        assert_eq!(drops.get(), 1);
965    }
966
967    /// Splits tuple fields in source order without reallocating nested payloads.
968    #[test]
969    fn tuple_split_preserves_nested_allocation() {
970        type Row = Cons<Leaf<u8>, Cons<ArrayOf<Leaf<String>>, Nil>>;
971        let array = Array::from_vec(vec![String::from("owned")]);
972        let pointer = array.as_slice().as_ptr();
973        let owner = OwnedValue::new::<Row>((7u8, array).into_c_stack_list());
974        let mut fields = owner.into_fields().unwrap().into_iter();
975        assert_eq!(
976            fields.next().unwrap().try_into_typed::<Leaf<u8>>().unwrap(),
977            7
978        );
979        let array = fields
980            .next()
981            .unwrap()
982            .try_into_typed::<ArrayOf<Leaf<String>>>()
983            .unwrap();
984        assert_eq!(array.as_slice().as_ptr(), pointer);
985        assert_eq!(array.as_slice(), ["owned"]);
986        assert!(fields.next().is_none());
987        assert!(
988            OwnedValue::new::<Nil>(().into_c_stack_list())
989                .into_fields()
990                .unwrap()
991                .is_empty()
992        );
993        assert!(OwnedValue::new::<Leaf<u8>>(7).into_fields().is_err());
994    }
995}