Skip to main content

solar_data_structures/
bump_ext.rs

1use crate::RawThinSlice;
2use bumpalo::Bump;
3use smallvec::SmallVec;
4
5/// Extension trait for [`Bump`].
6///
7/// The arena never runs destructors, so the safe allocation methods reject element types that need
8/// drop at compile time, since their owned memory would leak. Use [`DropArena`](crate::DropArena)
9/// for such values.
10#[expect(clippy::mut_from_ref)] // Arena.
11pub trait BumpExt {
12    /// Returns the number of bytes currently in use.
13    fn used_bytes(&self) -> usize;
14
15    /// Allocates a value as a slice of length 1.
16    fn alloc_as_slice<T>(&self, value: T) -> &mut [T];
17
18    /// Allocates an iterator by first collecting it into a (possibly stack-allocated) vector.
19    ///
20    /// Does not collect if the iterator is exact size, meaning `size_hint` returns equal values.
21    fn alloc_from_iter<T>(&self, iter: impl Iterator<Item = T>) -> &mut [T];
22
23    /// Allocates a vector of items on the arena.
24    fn alloc_vec<T>(&self, values: Vec<T>) -> &mut [T];
25
26    /// Allocates a `SmallVector` of items on the arena.
27    fn alloc_smallvec<A: smallvec::Array>(&self, values: SmallVec<A>) -> &mut [A::Item];
28
29    /// Allocates an array of items on the arena.
30    fn alloc_array<T, const N: usize>(&self, values: [T; N]) -> &mut [T];
31
32    /// Allocates a slice of items on the arena and copies them in.
33    ///
34    /// # Safety
35    ///
36    /// If `T: Drop`, the resulting slice must not be wrapped in [`bumpalo::boxed::Box`], unless
37    /// ownership is moved as well, such as through [`alloc_vec`](Self::alloc_vec) and the other
38    /// methods in this trait.
39    unsafe fn alloc_slice_unchecked<'a, T>(&'a self, slice: &[T]) -> &'a mut [T];
40
41    // `RawThinSlice` methods
42
43    /// See [`alloc_as_slice`](Self::alloc_as_slice).
44    fn alloc_as_thin_slice<H, T>(&self, header: H, value: T) -> &mut RawThinSlice<H, T>;
45
46    /// See [`alloc_from_iter`](Self::alloc_from_iter).
47    fn alloc_from_iter_thin<H, T>(
48        &self,
49        header: H,
50        iter: impl Iterator<Item = T>,
51    ) -> &mut RawThinSlice<H, T>;
52
53    /// See [`alloc_vec`](Self::alloc_vec).
54    fn alloc_vec_thin<H, T>(&self, header: H, values: Vec<T>) -> &mut RawThinSlice<H, T>;
55
56    /// See [`alloc_smallvec`](Self::alloc_smallvec).
57    fn alloc_smallvec_thin<H, A: smallvec::Array>(
58        &self,
59        header: H,
60        values: SmallVec<A>,
61    ) -> &mut RawThinSlice<H, A::Item>;
62
63    /// Like [`alloc_smallvec_thin`](Self::alloc_smallvec_thin), but moves the elements out of
64    /// `values` and leaves it empty, instead of moving `values` itself, which would copy its
65    /// inline buffer.
66    fn alloc_smallvec_drain_thin<H, A: smallvec::Array>(
67        &self,
68        header: H,
69        values: &mut SmallVec<A>,
70    ) -> &mut RawThinSlice<H, A::Item>;
71
72    /// See [`alloc_array`](Self::alloc_array).
73    fn alloc_array_thin<H, T, const N: usize>(
74        &self,
75        header: H,
76        values: [T; N],
77    ) -> &mut RawThinSlice<H, T>;
78
79    /// See [`alloc_slice_copy`](Bump::alloc_slice_copy).
80    fn alloc_thin_slice_copy<'a, H, T: Copy>(
81        &'a self,
82        header: H,
83        src: &[T],
84    ) -> &'a mut RawThinSlice<H, T> {
85        // SAFETY: `T` is `Copy`.
86        unsafe { self.alloc_thin_slice_unchecked(header, src) }
87    }
88
89    /// See [`alloc_slice_unchecked`](Self::alloc_slice_unchecked).
90    #[expect(clippy::missing_safety_doc)]
91    unsafe fn alloc_thin_slice_unchecked<'a, H, T>(
92        &'a self,
93        header: H,
94        src: &[T],
95    ) -> &'a mut RawThinSlice<H, T>;
96}
97
98impl BumpExt for Bump {
99    fn used_bytes(&self) -> usize {
100        // SAFETY: The data is not read, and the arena is not used during the iteration.
101        unsafe { self.iter_allocated_chunks_raw().map(|(_ptr, len)| len).sum::<usize>() }
102    }
103
104    #[inline]
105    fn alloc_as_slice<T>(&self, value: T) -> &mut [T] {
106        assert_no_drop::<T>();
107        std::slice::from_mut(self.alloc(value))
108    }
109
110    #[inline]
111    fn alloc_from_iter<T>(&self, mut iter: impl Iterator<Item = T>) -> &mut [T] {
112        assert_no_drop::<T>();
113        match iter.size_hint() {
114            (min, Some(max)) if min == max => self.alloc_slice_fill_with(min, |_| {
115                iter.next().expect("Iterator supplied too few elements")
116            }),
117            _ => self.alloc_smallvec(SmallVec::<[T; 8]>::from_iter(iter)),
118        }
119    }
120
121    #[inline]
122    fn alloc_vec<T>(&self, mut values: Vec<T>) -> &mut [T] {
123        assert_no_drop::<T>();
124        if values.is_empty() {
125            return &mut [];
126        }
127
128        // SAFETY: The `Vec` is deallocated, but the elements are not dropped.
129        unsafe {
130            let r = self.alloc_slice_unchecked(values.as_slice());
131            values.set_len(0);
132            r
133        }
134    }
135
136    #[inline]
137    fn alloc_smallvec<A: smallvec::Array>(&self, mut values: SmallVec<A>) -> &mut [A::Item] {
138        assert_no_drop::<A::Item>();
139        if values.is_empty() {
140            return &mut [];
141        }
142
143        // SAFETY: See `alloc_vec`.
144        unsafe {
145            let r = self.alloc_slice_unchecked(values.as_slice());
146            values.set_len(0);
147            r
148        }
149    }
150
151    #[inline]
152    fn alloc_array<T, const N: usize>(&self, values: [T; N]) -> &mut [T] {
153        assert_no_drop::<T>();
154        if values.is_empty() {
155            return &mut [];
156        }
157
158        let values = std::mem::ManuallyDrop::new(values);
159        // SAFETY: The values are not dropped.
160        unsafe { self.alloc_slice_unchecked(values.as_slice()) }
161    }
162
163    #[inline]
164    unsafe fn alloc_slice_unchecked<'a, T>(&'a self, src: &[T]) -> &'a mut [T] {
165        // Copied from `alloc_slice_copy`.
166        let layout = std::alloc::Layout::for_value(src);
167        let dst = self.alloc_layout(layout).cast::<T>();
168        unsafe {
169            std::ptr::copy_nonoverlapping(src.as_ptr(), dst.as_ptr(), src.len());
170            std::slice::from_raw_parts_mut(dst.as_ptr(), src.len())
171        }
172    }
173
174    #[inline]
175    fn alloc_as_thin_slice<H, T>(&self, header: H, value: T) -> &mut RawThinSlice<H, T> {
176        assert_no_drop::<T>();
177        let value = std::mem::ManuallyDrop::new(value);
178        unsafe { self.alloc_thin_slice_unchecked(header, std::slice::from_ref(&*value)) }
179    }
180
181    #[inline]
182    fn alloc_from_iter_thin<H, T>(
183        &self,
184        header: H,
185        mut iter: impl Iterator<Item = T>,
186    ) -> &mut RawThinSlice<H, T> {
187        assert_no_drop::<T>();
188        match iter.size_hint() {
189            (min, Some(max)) if min == max => {
190                RawThinSlice::<H, T>::from_arena_with(self, header, min, |_| {
191                    iter.next().expect("Iterator supplied too few elements")
192                })
193            }
194            _ => self.alloc_smallvec_thin(header, SmallVec::<[T; 8]>::from_iter(iter)),
195        }
196    }
197
198    #[inline]
199    fn alloc_vec_thin<H, T>(&self, header: H, mut values: Vec<T>) -> &mut RawThinSlice<H, T> {
200        assert_no_drop::<T>();
201        // SAFETY: The `Vec` is deallocated, but the elements are not dropped.
202        unsafe {
203            let r = self.alloc_thin_slice_unchecked(header, values.as_slice());
204            values.set_len(0);
205            r
206        }
207    }
208
209    #[inline]
210    fn alloc_smallvec_thin<H, A: smallvec::Array>(
211        &self,
212        header: H,
213        mut values: SmallVec<A>,
214    ) -> &mut RawThinSlice<H, A::Item> {
215        self.alloc_smallvec_drain_thin(header, &mut values)
216    }
217
218    #[inline]
219    fn alloc_smallvec_drain_thin<H, A: smallvec::Array>(
220        &self,
221        header: H,
222        values: &mut SmallVec<A>,
223    ) -> &mut RawThinSlice<H, A::Item> {
224        assert_no_drop::<A::Item>();
225        // SAFETY: See `alloc_vec_thin`.
226        unsafe {
227            let r = self.alloc_thin_slice_unchecked(header, values.as_slice());
228            values.set_len(0);
229            r
230        }
231    }
232
233    #[inline]
234    fn alloc_array_thin<H, T, const N: usize>(
235        &self,
236        header: H,
237        values: [T; N],
238    ) -> &mut RawThinSlice<H, T> {
239        assert_no_drop::<T>();
240        let values = std::mem::ManuallyDrop::new(values);
241        // SAFETY: The values are not dropped.
242        unsafe { self.alloc_thin_slice_unchecked(header, values.as_slice()) }
243    }
244
245    #[inline]
246    unsafe fn alloc_thin_slice_unchecked<'a, H, T>(
247        &'a self,
248        header: H,
249        src: &[T],
250    ) -> &'a mut RawThinSlice<H, T> {
251        RawThinSlice::from_arena(self, header, src)
252    }
253}
254
255/// Rejects at compile time types whose owned memory would leak in the arena.
256#[inline(always)]
257fn assert_no_drop<T>() {
258    const { assert!(!std::mem::needs_drop::<T>(), "arena values must not need drop") };
259}
260
261#[cfg(test)]
262mod tests {
263    use super::*;
264
265    #[test]
266    fn test_alloc_vec() {
267        let bump = Bump::new();
268        let slice = bump.alloc_vec(vec!["a", "b", "c"]);
269        assert_eq!(slice, ["a", "b", "c"]);
270    }
271
272    #[test]
273    fn test_alloc_vec_thin() {
274        let bump = Bump::new();
275        let raw_slice = bump.alloc_vec_thin(69usize, vec!["a", "b", "c"]);
276        assert_eq!(*raw_slice.header(), 69usize);
277        assert_eq!(raw_slice.as_slice(), ["a", "b", "c"]);
278    }
279
280    #[test]
281    fn test_alloc_thin_empty() {
282        let bump = Bump::new();
283        let data = Vec::<&'static str>::new();
284        let raw_slice = bump.alloc_vec_thin(69usize, data);
285        assert_eq!(*raw_slice.header(), 69usize);
286        assert!(raw_slice.as_slice().is_empty());
287    }
288}