Skip to main content

ploidy_core/
arena.rs

1use bumpalo::{
2    Bump,
3    collections::{CollectIn, Vec as BumpVec},
4};
5
6/// An allocation arena.
7///
8/// Objects allocated in an arena live as long as the arena itself.
9/// The underlying allocator is an implementation detail.
10#[derive(Debug, Default)]
11pub struct Arena(Bump);
12
13impl Arena {
14    /// Creates a new, empty arena.
15    #[inline]
16    pub fn new() -> Self {
17        Self::default()
18    }
19
20    /// Allocates and returns a mutable reference to a value.
21    #[inline]
22    pub(crate) fn alloc<T: Copy>(&self, value: T) -> &mut T {
23        self.0.alloc(value)
24    }
25
26    /// Copies and returns a mutable reference to a slice.
27    #[inline]
28    pub(crate) fn alloc_slice_copy<T: Copy>(&self, slice: &[T]) -> &mut [T] {
29        self.0.alloc_slice_copy(slice)
30    }
31
32    /// Allocates and fills a slice with items from an iterator of known length.
33    #[inline]
34    pub(crate) fn alloc_slice_exact<I>(&self, iter: I) -> &mut [I::Item]
35    where
36        I: IntoIterator,
37        I::IntoIter: ExactSizeIterator,
38        I::Item: Copy,
39    {
40        self.0.alloc_slice_fill_iter(iter)
41    }
42
43    /// Allocates and fills a slice with items from an iterator. Unlike
44    /// [`alloc_slice_exact`][Self::alloc_slice_exact], the iterator
45    /// doesn't need to know its exact length.
46    #[inline]
47    pub(crate) fn alloc_slice<I: IntoIterator>(&self, iter: I) -> &mut [I::Item]
48    where
49        I::Item: Copy,
50    {
51        iter.into_iter()
52            .collect_in::<BumpVec<_>>(&self.0)
53            .into_bump_slice_mut()
54    }
55
56    /// Allocates and returns a mutable reference to a string slice.
57    #[inline]
58    pub(crate) fn alloc_str(&self, s: &str) -> &mut str {
59        self.0.alloc_str(s)
60    }
61}