Skip to main content

cel_runtime/
array.rs

1//! Concrete, contiguous ownership for homogeneous CEL arrays.
2//!
3//! Transfers to and from vectors preserve their allocations. Nested arrays use
4//! `Array<Array<T>>`, so each outer element is itself a typed array owner.
5//! Its outer allocation transfers to `Vec<Array<T>>`, not `Vec<Vec<T>>`;
6//! explicitly converting each inner owner builds a new outer vector. Borrowing
7//! exposes `&[Array<T>]` without consuming the outer or inner owners.
8//!
9//! ```
10//! use cel_runtime::Array;
11//!
12//! let rows = Array::from_vec(vec![Array::from_vec(vec![1_i32, 2])]);
13//! assert_eq!(rows.as_slice()[0].as_slice(), &[1, 2]);
14//! ```
15
16use std::fmt;
17use std::marker::PhantomData;
18use std::mem::ManuallyDrop;
19use std::ptr::NonNull;
20
21/// Stores an array's pointer, element count, and element capacity, in that order.
22///
23/// The pointer is non-null and aligned for the concrete element type, including empty and
24/// zero-sized arrays. Length and capacity count elements, not bytes; length does
25/// not exceed capacity. The first `len` elements are initialized. For non-zero-sized
26/// elements with nonzero capacity, the pointer uniquely owns a global-allocator
27/// allocation compatible with `Vec<T>` at exactly this capacity and element type.
28///
29/// The header owns its member destruction operation. Erased arrays additionally
30/// own an element descriptor; typed arrays bind concrete drop glue without one.
31/// This layout is independent of Rust's unspecified `Vec<T>` header layout.
32#[repr(C)]
33pub(crate) struct RawArray {
34    /// Points to the owned element allocation, or an aligned dangling address for ZSTs.
35    pub(crate) ptr: NonNull<()>,
36    /// Counts initialized logical elements, including ZSTs.
37    pub(crate) len: usize,
38    /// Retains the original vector capacity for allocation reconstruction.
39    pub(crate) capacity: usize,
40    /// Destroys the initialized members using their bound concrete or erased type.
41    drop_members: unsafe fn(&mut RawArray),
42    /// Retains recursive element ownership metadata for an erased array.
43    pub(crate) element_type: Option<crate::ValueType>,
44}
45
46impl RawArray {
47    /// Adopts an erased array allocation with its live element destruction metadata.
48    ///
49    /// # Safety
50    /// The raw parts must uniquely own `len` initialized elements of `element_type`,
51    /// using its layout and the global allocator at exactly `capacity`.
52    pub(crate) unsafe fn from_erased(
53        ptr: NonNull<()>,
54        len: usize,
55        capacity: usize,
56        element_type: crate::ValueType,
57    ) -> Self {
58        Self {
59            ptr,
60            len,
61            capacity,
62            drop_members: drop_erased_members,
63            element_type: Some(element_type),
64        }
65    }
66}
67
68impl Drop for RawArray {
69    /// Destroys live members in reverse order and releases their allocation.
70    ///
71    /// - Complexity: O(n) member destructions for n live members.
72    fn drop(&mut self) {
73        // SAFETY: Each constructor binds destruction to the allocation's exact layout.
74        unsafe { (self.drop_members)(self) };
75    }
76}
77
78/// Destroys concrete members and frees their original vector allocation.
79///
80/// # Safety
81/// The header must uniquely own the raw parts of a `Vec<T>`.
82/// - Complexity: O(n) member destructions for n live members.
83unsafe fn drop_typed_members<T>(raw: &mut RawArray) {
84    let mut guard = ReverseDrop(unsafe {
85        Vec::from_raw_parts(raw.ptr.cast::<T>().as_ptr(), raw.len, raw.capacity)
86    });
87    raw.len = 0;
88    while let Some(value) = guard.0.pop() {
89        drop(value);
90    }
91}
92
93/// Destroys erased members using metadata owned by their array header.
94///
95/// # Safety
96/// The header's descriptor must match every initialized element and its allocation.
97/// - Complexity: O(n) member destructions plus recursive member destruction.
98unsafe fn drop_erased_members(raw: &mut RawArray) {
99    let element = raw
100        .element_type
101        .as_ref()
102        .expect("erased element descriptor");
103    let layout = std::alloc::Layout::from_size_align(
104        element
105            .size()
106            .checked_mul(raw.capacity)
107            .expect("valid array capacity"),
108        element.align(),
109    )
110    .expect("valid array layout");
111    let _allocation = crate::owned_value::Allocation {
112        pointer: raw.ptr.cast(),
113        layout,
114    };
115    let mut prefix = crate::owned_value::Prefix {
116        base: raw.ptr.as_ptr().cast(),
117        children: crate::owned_value::Children::Elements(element),
118        initialized: raw.len,
119    };
120    raw.len = 0;
121    unsafe { prefix.destroy() };
122}
123
124/// Owns homogeneous, contiguous elements without bounds on the element type.
125///
126/// The transparent representation is an owning `RawArray` header, including
127/// member destruction dispatch. Its elements have the concrete layout of `T`.
128/// Nested arrays use `Array<Array<T>>`, not nested vectors.
129///
130/// Dropping an array destroys its elements exactly once in reverse index order,
131/// then releases its allocation. Remaining elements also receive reverse-order
132/// cleanup if a destructor unwinds; a second destructor panic during unwinding
133/// aborts as usual. After [`Self::into_vec`], the vector instead follows Rust's
134/// vector destruction behavior.
135///
136/// - Complexity: Destruction takes O(n) time and O(1) auxiliary space, excluding
137///   element destructor costs.
138///
139/// # Examples
140///
141/// ```
142/// use cel_runtime::Array;
143///
144/// let array = Array::from_vec(vec![String::from("leaf")]);
145/// assert_eq!(array.as_slice(), &["leaf"]);
146/// ```
147///
148/// Elements that are not `Send` cannot become transferable through an array:
149///
150/// ```compile_fail
151/// use cel_runtime::Array;
152/// use std::rc::Rc;
153///
154/// fn require_send<T: Send>() {}
155/// require_send::<Array<Rc<()>>>();
156/// ```
157///
158/// Elements that are not `Sync` cannot become shareable through an array:
159///
160/// ```compile_fail
161/// use cel_runtime::Array;
162/// use std::cell::Cell;
163///
164/// fn require_sync<T: Sync>() {}
165/// require_sync::<Array<Cell<i32>>>();
166/// ```
167#[repr(transparent)]
168pub struct Array<T> {
169    /// Owns the allocation and exactly the initialized `T` elements.
170    pub(crate) raw: RawArray,
171    /// Associates the erased header with its concrete element type.
172    marker: PhantomData<T>,
173}
174
175// SAFETY: The header uniquely owns T elements and never exposes untyped access
176// publicly. Moving ownership between threads is valid exactly when T is Send.
177unsafe impl<T: Send> Send for Array<T> {}
178// SAFETY: Shared access exposes only &[T], which is shareable exactly when T is Sync.
179unsafe impl<T: Sync> Sync for Array<T> {}
180
181impl<T> Array<T> {
182    /// Takes ownership of a vector without moving elements or allocating.
183    ///
184    /// - Postcondition: Contents, allocation pointer, length, and capacity are
185    ///   unchanged. Empty and zero-sized vectors retain their raw parts.
186    ///
187    /// # Examples
188    ///
189    /// ```
190    /// use cel_runtime::Array;
191    /// let values = vec![3_i32, 5];
192    /// let pointer = values.as_ptr();
193    /// let array = Array::from_vec(values);
194    /// assert_eq!(array.as_slice().as_ptr(), pointer);
195    /// ```
196    #[must_use]
197    pub fn from_vec(values: Vec<T>) -> Self {
198        let (ptr, len, capacity) = values.into_raw_parts();
199        Self {
200            raw: RawArray {
201                // SAFETY: Vec raw parts always provide a non-null aligned pointer.
202                ptr: unsafe { NonNull::new_unchecked(ptr.cast()) },
203                len,
204                capacity,
205                drop_members: drop_typed_members::<T>,
206                element_type: None,
207            },
208            marker: PhantomData,
209        }
210    }
211
212    /// Transfers ownership into a vector without moving elements or allocating.
213    ///
214    /// - Postcondition: Contents, allocation pointer, length, and capacity are
215    ///   unchanged; this array runs no element destructors.
216    ///
217    /// # Examples
218    ///
219    /// ```
220    /// use cel_runtime::Array;
221    /// let array = Array::from_vec(vec![3_i32, 5]);
222    /// let pointer = array.as_slice().as_ptr();
223    /// let values = array.into_vec();
224    /// assert_eq!(values.as_ptr(), pointer);
225    /// assert_eq!(values, [3, 5]);
226    /// ```
227    #[must_use]
228    pub fn into_vec(self) -> Vec<T> {
229        let mut owner = ManuallyDrop::new(self);
230        drop(owner.raw.element_type.take());
231        // SAFETY: The header preserves Vec<T>'s raw parts, and ManuallyDrop
232        // prevents the old owner from destroying the transferred allocation.
233        unsafe {
234            Vec::from_raw_parts(
235                owner.raw.ptr.cast::<T>().as_ptr(),
236                owner.raw.len,
237                owner.raw.capacity,
238            )
239        }
240    }
241
242    /// Borrows the contiguous elements without copying or allocating.
243    ///
244    /// # Examples
245    ///
246    /// ```
247    /// use cel_runtime::Array;
248    /// let array = Array::from_vec(vec![3_i32, 5]);
249    /// let values: &[i32] = array.as_slice();
250    /// assert_eq!(values, &[3, 5]);
251    /// ```
252    #[must_use]
253    pub fn as_slice(&self) -> &[T] {
254        // SAFETY: The typed owner guarantees an aligned non-null pointer and
255        // len initialized T elements, alive for the lifetime of this borrow.
256        unsafe { std::slice::from_raw_parts(self.raw.ptr.cast::<T>().as_ptr(), self.raw.len) }
257    }
258
259    /// Returns the number of initialized elements.
260    ///
261    /// # Examples
262    ///
263    /// ```
264    /// use cel_runtime::Array;
265    /// assert_eq!(Array::from_vec(vec![3_i32, 5]).len(), 2);
266    /// ```
267    #[must_use]
268    pub fn len(&self) -> usize {
269        self.raw.len
270    }
271
272    /// Returns the allocation capacity in elements, as reported by the source vector.
273    ///
274    /// Zero-sized elements retain the vector's capacity of `usize::MAX`.
275    ///
276    /// # Examples
277    ///
278    /// ```
279    /// use cel_runtime::Array;
280    /// let values = Vec::<i32>::with_capacity(8);
281    /// let capacity = values.capacity();
282    /// assert_eq!(Array::from_vec(values).capacity(), capacity);
283    /// ```
284    #[must_use]
285    pub fn capacity(&self) -> usize {
286        self.raw.capacity
287    }
288
289    /// Returns whether the array contains no elements.
290    ///
291    /// # Examples
292    ///
293    /// ```
294    /// use cel_runtime::Array;
295    /// assert!(Array::from_vec(Vec::<i32>::new()).is_empty());
296    /// ```
297    #[must_use]
298    pub fn is_empty(&self) -> bool {
299        self.raw.len == 0
300    }
301}
302
303/// Owns remaining elements during cleanup and frees storage even during unwinding.
304struct ReverseDrop<T>(Vec<T>);
305
306impl<T> Drop for ReverseDrop<T> {
307    /// Drops remaining elements in reverse order in O(n) time and O(1) space.
308    fn drop(&mut self) {
309        while let Some(value) = self.0.pop() {
310            drop(value);
311        }
312    }
313}
314
315impl<T: Clone> Clone for Array<T> {
316    /// Clones elements into a new array without sharing owned storage.
317    ///
318    /// - Complexity: O(n) time and space, excluding element clone costs.
319    ///
320    /// # Examples
321    ///
322    /// ```
323    /// use cel_runtime::Array;
324    /// let array = Array::from_vec(vec![String::from("leaf")]);
325    /// assert_eq!(array.clone().as_slice(), array.as_slice());
326    /// ```
327    fn clone(&self) -> Self {
328        Self::from_vec(self.as_slice().to_vec())
329    }
330}
331
332impl<T: PartialEq> PartialEq for Array<T> {
333    /// Compares lengths and corresponding elements using element equality.
334    ///
335    /// - Complexity: O(n) time in the worst case, excluding element comparison
336    ///   costs, and O(1) auxiliary space.
337    ///
338    /// # Examples
339    ///
340    /// ```
341    /// use cel_runtime::Array;
342    /// assert_eq!(Array::from_vec(vec![1_i32]), Array::from_vec(vec![1_i32]));
343    /// ```
344    fn eq(&self, other: &Self) -> bool {
345        self.as_slice() == other.as_slice()
346    }
347}
348
349impl<T: fmt::Debug> fmt::Debug for Array<T> {
350    /// Formats the array as `Array([elements])` using element debug formatting.
351    ///
352    /// - Complexity: O(n) element formatting calls, excluding element formatting
353    ///   costs and output storage.
354    ///
355    /// # Errors
356    ///
357    /// Returns an error if the formatter fails to write the representation.
358    ///
359    /// # Examples
360    ///
361    /// ```
362    /// use cel_runtime::Array;
363    /// assert_eq!(format!("{:?}", Array::from_vec(vec![1_i32])), "Array([1])");
364    /// ```
365    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
366        formatter
367            .debug_tuple("Array")
368            .field(&self.as_slice())
369            .finish()
370    }
371}
372
373#[cfg(test)]
374mod ownership_tests {
375    use super::*;
376    use std::cell::Cell;
377    use std::rc::Rc;
378
379    /// Preserves vector ownership and exposes exactly the initialized elements.
380    #[test]
381    fn vector_transfers_preserve_raw_parts() {
382        let mut values = Vec::with_capacity(8);
383        values.push(String::from("owned"));
384        values.push(String::from("second"));
385        let pointer = values.as_ptr();
386        let capacity = values.capacity();
387        let array = Array::from_vec(values);
388        assert_eq!(array.len(), 2);
389        assert!(!array.is_empty());
390        assert_eq!(array.capacity(), capacity);
391        assert_eq!(array.as_slice().as_ptr(), pointer);
392        assert_eq!(array.as_slice(), ["owned", "second"]);
393        assert_eq!(format!("{array:?}"), "Array([\"owned\", \"second\"])");
394        let values = array.into_vec();
395        assert_eq!(values.as_ptr(), pointer);
396        assert_eq!(values.capacity(), capacity);
397        assert_eq!(values, ["owned", "second"]);
398
399        assert!(Array::from_vec(Vec::<String>::new()).is_empty());
400        let zero_sized = Array::from_vec(vec![(); 3]);
401        assert_eq!(zero_sized.len(), 3);
402        assert_eq!(zero_sized.into_vec(), [(); 3]);
403    }
404
405    /// Preserves value equality while keeping cloned mutable values independent.
406    #[test]
407    fn clone_and_equality_laws() {
408        let first = Array::from_vec(vec![String::from("first")]);
409        let second = first.clone();
410        let third = second.clone();
411        assert!(first == first);
412        assert_eq!(first, second);
413        assert_eq!(second, first);
414        assert_eq!(second, third);
415        assert_eq!(first, third);
416        assert!(!(first != second));
417        let mut original = first.into_vec();
418        let mut cloned = second.into_vec();
419        original[0].push_str(" changed");
420        assert_eq!(cloned, ["first"]);
421        cloned[0].push_str(" copied");
422        assert_eq!(original, ["first changed"]);
423        assert_eq!(third.as_slice(), ["first"]);
424    }
425
426    /// Releases members when only the erased owning header remains.
427    #[test]
428    fn raw_header_owns_its_members() {
429        /// Records the destruction of one member.
430        struct Tracked(Rc<Cell<usize>>);
431
432        impl Drop for Tracked {
433            /// Records release of this member.
434            fn drop(&mut self) {
435                self.0.set(self.0.get() + 1);
436            }
437        }
438
439        let drops = Rc::new(Cell::new(0));
440        let array = ManuallyDrop::new(Array::from_vec(vec![
441            Tracked(drops.clone()),
442            Tracked(drops.clone()),
443        ]));
444        // SAFETY: The suppressed typed owner transfers its header exactly once.
445        let raw = unsafe { std::ptr::read(&array.raw) };
446        drop(raw);
447        assert_eq!(drops.get(), 2);
448    }
449}