Skip to main content

cel_runtime/
raw_sequence.rs

1//! Stores heterogeneous values whose caller tracks types and destruction.
2//!
3//! Push values in order, then traverse or destroy them using matching types.
4//! Dropping the sequence releases its byte buffer, not the stored values.
5
6use crate::memory::align_index;
7use crate::raw_vec::RawVec;
8use std::mem;
9
10/// A sequence that stores heterogeneous values with proper alignment.
11///
12/// The `RawSequence` provides a memory-efficient way to store heterogeneous values
13/// while maintaining proper alignment requirements for each type. It uses an
14/// internal buffer that raises its base alignment to satisfy each stored type.
15///
16/// The caller owns destruction of stored values, including before discarding
17/// the sequence. Zero-sized values occupy no logical bytes.
18///
19/// # Examples
20/// ```
21/// let mut values = cel_runtime::RawSequence::new();
22/// values.push(String::from("hello"));
23/// assert_eq!(unsafe { values.next::<String>(0) }.0, "hello");
24/// unsafe { values.drop_in_place::<String>(0) };
25/// ```
26pub struct RawSequence {
27    /// Owns aligned value bytes; callers retain responsibility for typed destruction.
28    buffer: RawVec,
29}
30
31impl Default for RawSequence {
32    /// Creates an empty sequence.
33    fn default() -> Self {
34        Self::new()
35    }
36}
37
38impl RawSequence {
39    /// Creates a new empty `RawSequence`.
40    /// The sequence initially requests 4096-byte base alignment and raises it
41    /// when a stored type requires a wider alignment.
42    ///
43    /// # Examples
44    /// ```
45    /// let values = cel_runtime::RawSequence::new();
46    /// assert!(values.is_empty());
47    /// ```
48    #[must_use]
49    pub fn new() -> Self {
50        RawSequence {
51            buffer: RawVec::with_base_alignment(4096),
52        }
53    }
54
55    /// Pushes a value onto the sequence.
56    ///
57    /// The value is stored at an address that satisfies its alignment requirements.
58    /// Automatically grows the internal buffer if needed.
59    ///
60    /// - Complexity: Amortized O(size of `T` + alignment of `T`) time and space
61    ///   at an existing base alignment. Raising the base alignment also moves
62    ///   O(n) stored bytes and replaces the buffer allocation.
63    ///
64    /// # Examples
65    /// ```
66    /// let mut values = cel_runtime::RawSequence::new();
67    /// values.push(42u32);
68    /// assert_eq!(*unsafe { values.next::<u32>(0) }.0, 42);
69    /// ```
70    pub fn push<T>(&mut self, value: T) {
71        let len = self.buffer.len();
72        if mem::align_of::<T>() > self.buffer.base_alignment() {
73            let mut buffer = RawVec::with_base_alignment_and_capacity(
74                mem::align_of::<T>(),
75                self.buffer.capacity(),
76            );
77            // SAFETY: Both allocations contain at least len bytes, and copying
78            // their representations transfers the caller-managed stored owners.
79            unsafe {
80                std::ptr::copy_nonoverlapping(self.buffer.as_ptr(), buffer.as_mut_ptr(), len);
81                buffer.set_len(len);
82            }
83            self.buffer = buffer;
84        }
85        let aligned: usize = align_index(mem::align_of::<T>(), len);
86        let new_len = aligned
87            .checked_add(mem::size_of::<T>())
88            .expect("sequence size overflow");
89
90        self.buffer.reserve((new_len - len).max(1));
91        unsafe {
92            self.buffer.set_len(new_len);
93            std::ptr::write(self.buffer.as_mut_ptr().add(aligned).cast::<T>(), value);
94        }
95    }
96
97    /// Destroys the next value after `p` and returns the position after it.
98    ///
99    /// # Safety
100    /// `p` must precede a live stored `T`, with only its alignment padding
101    /// between them. The value must not be used or destroyed again.
102    ///
103    /// # Examples
104    /// ```
105    /// let mut values = cel_runtime::RawSequence::new();
106    /// values.push(String::from("owned"));
107    /// unsafe { values.drop_in_place::<String>(0) };
108    /// ```
109    pub unsafe fn drop_in_place<T>(&mut self, p: usize) -> usize {
110        let mut next = p;
111        unsafe { self.drop_next::<T>(&mut next) };
112        next
113    }
114
115    /// Advances `p` past the next value before destroying it.
116    ///
117    /// - Postcondition: `p` advances even when the value's destructor panics.
118    ///
119    /// # Safety
120    /// `p` must precede a live stored `T`, with only its alignment padding
121    /// between them. The value must not be used or destroyed again.
122    pub(crate) unsafe fn drop_next<T>(&mut self, p: &mut usize) {
123        let aligned = align_index(mem::align_of::<T>(), *p);
124        *p = aligned + mem::size_of::<T>();
125        unsafe { std::ptr::drop_in_place(self.buffer.as_mut_ptr().add(aligned).cast::<T>()) };
126    }
127
128    /// Retrieves a reference to the next value at the specified position.
129    ///
130    /// # Safety
131    /// - The position must point to a valid value of type T
132    /// - The caller must ensure that the value is actually of type T
133    ///
134    /// Returns a tuple containing:
135    /// - A reference to the value
136    /// - The position immediately after the value
137    ///
138    /// # Examples
139    /// ```
140    /// let mut values = cel_runtime::RawSequence::new();
141    /// values.push(42u32);
142    /// let (value, next) = unsafe { values.next::<u32>(0) };
143    /// assert_eq!((*value, next), (42, 4));
144    /// ```
145    #[must_use]
146    pub unsafe fn next<T>(&self, p: usize) -> (&T, usize) {
147        let aligned: usize = align_index(mem::align_of::<T>(), p);
148        let ptr = unsafe { self.buffer.as_ptr().add(aligned).cast::<T>() };
149        unsafe { (&*ptr, aligned + mem::size_of::<T>()) }
150    }
151
152    /// Returns the number of bytes in the RawSequence, also referred to as its ‘length’.
153    ///
154    /// # Examples
155    /// ```
156    /// let mut values = cel_runtime::RawSequence::new();
157    /// values.push(42u32);
158    /// assert_eq!(values.len(), 4);
159    /// ```
160    #[must_use]
161    pub fn len(&self) -> usize {
162        self.buffer.len()
163    }
164
165    /// Returns true if no logical bytes are stored, including only zero-sized values.
166    ///
167    /// # Examples
168    /// ```
169    /// let mut values = cel_runtime::RawSequence::new();
170    /// values.push(());
171    /// assert!(values.is_empty());
172    /// ```
173    #[must_use]
174    pub fn is_empty(&self) -> bool {
175        self.buffer.is_empty()
176    }
177}
178
179#[cfg(test)]
180mod tests {
181    /// Test module for RawSequence.
182    ///
183    /// Contains tests that verify:
184    /// - Pushing different types of values
185    /// - Retrieving values in correct order
186    /// - Proper memory cleanup using drop_in_place
187    use super::*;
188
189    /// Traverses heterogeneous values and explicitly destroys each value.
190    #[test]
191    fn sequence_operations() {
192        let mut seq = RawSequence::new();
193
194        seq.push(100u32);
195        seq.push(200u32);
196        seq.push(42.0f64);
197        seq.push("Hello, world!");
198
199        let (value, p) = unsafe { seq.next::<u32>(0) };
200        assert_eq!(*value, 100);
201        let (value, p) = unsafe { seq.next::<u32>(p) };
202        assert_eq!(*value, 200);
203        let (value, p) = unsafe { seq.next::<f64>(p) };
204        assert_eq!(*value, 42.0);
205        let (value, _) = unsafe { seq.next::<&str>(p) };
206        assert_eq!(*value, "Hello, world!");
207
208        let p = unsafe { seq.drop_in_place::<u32>(0) };
209        let p = unsafe { seq.drop_in_place::<u32>(p) };
210        let p = unsafe { seq.drop_in_place::<f64>(p) };
211        let _ = unsafe { seq.drop_in_place::<&str>(p) };
212    }
213
214    /// Provides a correctly aligned address even for the first zero-sized value.
215    #[test]
216    fn aligned_zero_sized_value() {
217        /// Requires alignment without occupying logical bytes.
218        #[repr(align(4096))]
219        struct Aligned;
220
221        let mut seq = RawSequence::default();
222        seq.push(Aligned);
223        let (value, next) = unsafe { seq.next::<Aligned>(0) };
224        assert_eq!(value as *const Aligned as usize % 4096, 0);
225        assert_eq!(next, 0);
226        assert!(seq.is_empty());
227        unsafe { seq.drop_in_place::<Aligned>(0) };
228    }
229}