cel_runtime/raw_vec.rs
1//! Aligned byte storage without ownership of values placed in its buffer.
2//!
3//! Reserve storage before writing bytes, then expose them with [`RawVec::set_len`].
4//! The caller remains responsible for destroying any values stored in the bytes.
5
6use crate::memory::align_index;
7use std::cmp::max;
8use std::mem::MaybeUninit;
9use std::ops::{Index, IndexMut};
10use std::slice::SliceIndex;
11
12/// Stores bytes at a fixed power-of-two alignment after allocation.
13///
14/// The logical length excludes leading alignment padding. Moving or reserving
15/// storage preserves the logical bytes but invalidates pointers into the buffer.
16///
17/// # Examples
18/// ```
19/// use cel_runtime::RawVec;
20/// let mut bytes = RawVec::with_base_alignment(64);
21/// bytes.reserve(8);
22/// assert!(bytes.capacity() >= 8);
23/// assert!(bytes.is_empty());
24/// ```
25#[derive(Debug)]
26pub struct RawVec {
27 /// Owns raw storage including bytes preceding its aligned logical origin.
28 buffer: Vec<MaybeUninit<u8>>,
29 /// Retains the nonzero power-of-two alignment required at the logical origin.
30 base_alignment: usize,
31 /// Locates the aligned logical origin within the allocation.
32 start_offset: usize,
33}
34
35impl<I> Index<I> for RawVec
36where
37 I: SliceIndex<[MaybeUninit<u8>]>,
38{
39 type Output = I::Output;
40
41 /// Borrows bytes at an index within the logical length.
42 fn index(&self, index: I) -> &Self::Output {
43 let slice = &self.buffer[self.start_offset..];
44 &slice[index]
45 }
46}
47
48impl<I> IndexMut<I> for RawVec
49where
50 I: SliceIndex<[MaybeUninit<u8>]>,
51{
52 /// Mutably borrows bytes at an index within the logical length.
53 fn index_mut(&mut self, index: I) -> &mut Self::Output {
54 let slice = &mut self.buffer[self.start_offset..];
55 &mut slice[index]
56 }
57}
58
59impl RawVec {
60 /// Creates a new `RawVec` with base alignment.
61 ///
62 /// - Precondition: `base_alignment` is a power of two.
63 ///
64 /// # Examples
65 ///
66 /// ```
67 /// use cel_runtime::RawVec;
68 /// use std::mem::align_of;
69 /// let vec = RawVec::with_base_alignment(align_of::<u32>());
70 /// ```
71 #[must_use]
72 pub fn with_base_alignment(base_alignment: usize) -> Self {
73 assert!(base_alignment.is_power_of_two());
74 RawVec {
75 base_alignment,
76 start_offset: 0,
77 buffer: Vec::new(),
78 }
79 }
80
81 /// Creates a new `RawVec` with base alignment and initial capacity.
82 ///
83 /// - Precondition: `base_alignment` is a power of two.
84 /// - Complexity: Allocates O(`capacity + base_alignment`) bytes.
85 ///
86 /// # Examples
87 /// ```
88 /// let bytes = cel_runtime::RawVec::with_base_alignment_and_capacity(64, 8);
89 /// assert!(bytes.capacity() >= 8);
90 /// assert!(bytes.is_empty());
91 /// ```
92 #[must_use]
93 pub fn with_base_alignment_and_capacity(base_alignment: usize, capacity: usize) -> Self {
94 assert!(base_alignment.is_power_of_two());
95 let allocation_size = capacity
96 .checked_add(base_alignment.checked_sub(1).expect("invalid alignment"))
97 .expect("capacity overflow");
98 let mut buffer = Vec::with_capacity(allocation_size);
99 let ptr_as_index = buffer.as_ptr() as usize;
100 let start_offset = align_index(base_alignment, ptr_as_index) - ptr_as_index;
101 unsafe { buffer.set_len(start_offset) };
102 RawVec {
103 buffer,
104 base_alignment,
105 start_offset,
106 }
107 }
108
109 /// Returns the capacity of the vector in bytes.
110 ///
111 /// # Examples
112 /// ```
113 /// let bytes = cel_runtime::RawVec::with_base_alignment_and_capacity(8, 16);
114 /// assert!(bytes.capacity() >= 16);
115 /// ```
116 #[must_use]
117 pub fn capacity(&self) -> usize {
118 self.buffer.capacity() - self.start_offset
119 }
120
121 /// Returns the alignment guaranteed after allocating storage.
122 pub(crate) fn base_alignment(&self) -> usize {
123 self.base_alignment
124 }
125
126 /// Returns the current length of the vector in bytes.
127 ///
128 /// # Examples
129 /// ```
130 /// let bytes = cel_runtime::RawVec::with_base_alignment(8);
131 /// assert_eq!(bytes.len(), 0);
132 /// ```
133 #[must_use]
134 pub fn len(&self) -> usize {
135 self.buffer.len() - self.start_offset
136 }
137
138 /// Returns true if the vector contains no bytes.
139 ///
140 /// # Examples
141 /// ```
142 /// assert!(cel_runtime::RawVec::with_base_alignment(8).is_empty());
143 /// ```
144 #[must_use]
145 pub fn is_empty(&self) -> bool {
146 self.len() == 0
147 }
148
149 /// Reserves capacity for at least additional more elements. The collection may reserve more
150 /// space to guarantee amortized constant time growth. After calling reserve, capacity will be
151 /// greater than or equal to `self.len() + additional`. Does nothing if capacity is already
152 /// sufficient.
153 ///
154 /// - Postcondition: The logical length and existing bytes remain unchanged.
155 /// - Complexity: O(`self.len()`) time when growing; allocates O(new capacity
156 /// + base alignment) bytes.
157 ///
158 /// # Panics
159 ///
160 /// Panics if the new capacity exceeds `isize::MAX` bytes.
161 ///
162 /// # Examples
163 /// ```
164 /// let mut bytes = cel_runtime::RawVec::with_base_alignment(8);
165 /// bytes.reserve(16);
166 /// assert!(bytes.capacity() >= 16);
167 /// assert!(bytes.is_empty());
168 /// ```
169 pub fn reserve(&mut self, addition: usize) {
170 let capacity = self.len().checked_add(addition).expect("capacity overflow");
171 if capacity > self.capacity() {
172 let mut new_buffer = Self::with_base_alignment_and_capacity(
173 self.base_alignment,
174 max(capacity, self.capacity().saturating_mul(2)),
175 );
176 unsafe {
177 std::ptr::copy_nonoverlapping(self.as_ptr(), new_buffer.as_mut_ptr(), self.len());
178 new_buffer.set_len(self.len());
179 }
180 *self = new_buffer;
181 }
182 }
183
184 /// Sets the length of the vector.
185 ///
186 /// # Safety
187 ///
188 /// `len` must not exceed the capacity. The elements are `MaybeUninit<u8>`;
189 /// their payload bytes need not be initialized.
190 ///
191 /// # Examples
192 /// ```
193 /// let mut bytes = cel_runtime::RawVec::with_base_alignment_and_capacity(8, 1);
194 /// unsafe { bytes.set_len(1) };
195 /// bytes[0].write(42);
196 /// assert_eq!(unsafe { bytes[0].assume_init() }, 42);
197 /// ```
198 pub unsafe fn set_len(&mut self, len: usize) {
199 assert!(len <= self.capacity());
200 unsafe { self.buffer.set_len(self.start_offset + len) };
201 }
202
203 /// Returns a raw mutable pointer to the vector's buffer, or a dangling raw pointer valid for
204 /// zero sized reads if the vector didn't allocate.
205 ///
206 /// This method guarantees that for the purpose of the aliasing model, this method does not
207 /// materialize a reference to the underlying slice, and thus the returned pointer will remain
208 /// valid when mixed with other calls to [`Self::as_ptr`], [`Self::as_mut_ptr`]. Note
209 /// that calling other methods that materialize references to the slice, or references to
210 /// specific elements you are planning on accessing through this pointer, may still invalidate
211 /// this pointer.
212 ///
213 /// # Safety
214 ///
215 /// The pointer is valid until the vector buffer is reallocated or the vector's lifetime ends.
216 ///
217 /// # Examples
218 /// ```
219 /// let mut bytes = cel_runtime::RawVec::with_base_alignment_and_capacity(64, 1);
220 /// assert_eq!(unsafe { bytes.as_mut_ptr() } as usize % 64, 0);
221 /// ```
222 pub unsafe fn as_mut_ptr(&mut self) -> *mut MaybeUninit<u8> {
223 unsafe { self.buffer.as_mut_ptr().add(self.start_offset) }
224 }
225
226 /// Returns a raw pointer to the vector's buffer, or a dangling raw pointer valid for zero sized
227 /// reads if the vector didn't allocate.
228 ///
229 /// The caller must also ensure that the memory the pointer (non-transitively) points to is
230 /// never written to (except inside an `UnsafeCell`) using this pointer or any pointer derived
231 /// from it. If you need to mutate the contents of the slice, use [`Self::as_mut_ptr`].
232 ///
233 /// This method guarantees that for the purpose of the aliasing model, this method does not
234 /// materialize a reference to the underlying slice, and thus the returned pointer will remain
235 /// valid when mixed with other calls to [`Self::as_ptr`], [`Self::as_mut_ptr`]. Note
236 /// that calling other methods that materialize mutable references to the slice, or mutable
237 /// references to specific elements you are planning on accessing through this pointer, as well
238 /// as writing to those elements, may still invalidate this pointer.
239 ///
240 /// # Safety
241 ///
242 /// The pointer is valid until the vector buffer is reallocated or the vector's lifetime ends.
243 ///
244 /// # Examples
245 /// ```
246 /// let bytes = cel_runtime::RawVec::with_base_alignment_and_capacity(64, 1);
247 /// assert_eq!(unsafe { bytes.as_ptr() } as usize % 64, 0);
248 /// ```
249 #[must_use]
250 pub unsafe fn as_ptr(&self) -> *const MaybeUninit<u8> {
251 unsafe { self.buffer.as_ptr().add(self.start_offset) }
252 }
253
254 /// Shortens the vector, keeping the first `len` elements and dropping
255 /// the rest.
256 ///
257 /// If `len` is greater or equal to the vector's current length, this has
258 /// no effect.
259 ///
260 /// # Examples
261 /// ```
262 /// let mut bytes = cel_runtime::RawVec::with_base_alignment_and_capacity(8, 2);
263 /// unsafe { bytes.set_len(2) };
264 /// bytes.truncate(1);
265 /// assert_eq!(bytes.len(), 1);
266 /// ```
267 pub fn truncate(&mut self, len: usize) {
268 if len < self.len() {
269 self.buffer.truncate(self.start_offset + len);
270 }
271 }
272}
273
274/* Test module */
275#[cfg(test)]
276mod tests {
277 use super::*;
278
279 /// Preserves the logical length and initialized bytes when capacity grows.
280 #[test]
281 fn reserve_preserves_contents() {
282 let mut vec = RawVec::with_base_alignment_and_capacity(64, 3);
283 unsafe { vec.set_len(3) };
284 for (byte, value) in vec[..].iter_mut().zip([11, 22, 33]) {
285 byte.write(value);
286 }
287 let addition = vec.capacity() + 1;
288 vec.reserve(addition);
289 assert_eq!(vec.len(), 3);
290 assert!(vec.capacity() >= 3 + addition);
291 assert_eq!(unsafe { vec.as_ptr() as usize } % 64, 0);
292 assert_eq!(
293 vec[..]
294 .iter()
295 .map(|byte| unsafe { byte.assume_init() })
296 .collect::<Vec<_>>(),
297 [11, 22, 33]
298 );
299 }
300
301 /// Leaves the logical bytes unchanged when the requested length is larger.
302 #[test]
303 fn truncate_large_length_is_noop() {
304 let mut vec = RawVec::with_base_alignment_and_capacity(4096, 1);
305 unsafe { vec.set_len(1) };
306 vec[0].write(42);
307 vec.truncate(usize::MAX);
308 assert_eq!(vec.len(), 1);
309 assert_eq!(unsafe { vec[0].assume_init() }, 42);
310 }
311
312 /// Creates empty, unallocated storage.
313 #[test]
314 fn with_base_alignment() {
315 let vec = RawVec::with_base_alignment(align_of::<u32>());
316 assert_eq!(vec.base_alignment(), align_of::<u32>());
317 assert_eq!(vec.capacity(), 0);
318 assert_eq!(vec.len(), 0);
319 }
320
321 /// Reserves aligned storage without exposing logical bytes.
322 #[test]
323 fn with_base_alignment_and_capacity() {
324 let vec = RawVec::with_base_alignment_and_capacity(align_of::<u32>(), 10);
325 assert!(vec.capacity() >= 10);
326 assert_eq!(vec.len(), 0);
327 assert_eq!(unsafe { vec.as_ptr() as usize } % align_of::<u32>(), 0);
328 }
329
330 /// Grows empty storage while preserving its alignment.
331 #[test]
332 fn reserve() {
333 let mut vec = RawVec::with_base_alignment(align_of::<u32>());
334 vec.reserve(10);
335 assert!(vec.capacity() >= 10);
336 assert_eq!(vec.len(), 0);
337 assert_eq!(unsafe { vec.as_ptr() as usize } % align_of::<u32>(), 0);
338 }
339
340 /// Exposes the requested number of bytes within capacity.
341 #[test]
342 fn set_len() {
343 let mut vec = RawVec::with_base_alignment_and_capacity(align_of::<u32>(), 10);
344 unsafe { vec.set_len(10) };
345 assert_eq!(vec.len(), 10);
346 assert_eq!(unsafe { vec.as_ptr() as usize } % align_of::<u32>(), 0);
347 }
348
349 /// Reads and writes logical bytes through indexing.
350 #[test]
351 fn index() {
352 let mut vec = RawVec::with_base_alignment_and_capacity(align_of::<u32>(), 10);
353 unsafe { vec.set_len(1) };
354 vec[0].write(42);
355 assert_eq!(unsafe { vec[0].assume_init() }, 42);
356 }
357}