Arena

Struct Arena 

Source
pub struct Arena { /* private fields */ }
Expand description

AST arena allocator.

Implementations§

Source§

impl Arena

Source

pub fn new() -> Arena

Creates a new AST arena.

Source

pub fn bump(&self) -> &Bump

Returns a reference to the arena’s bump allocator.

Source

pub fn bump_mut(&mut self) -> &mut Bump

Returns a mutable reference to the arena’s bump allocator.

Source

pub fn allocated_bytes(&self) -> usize

Calculates the number of bytes currently allocated in the entire arena.

Source

pub fn used_bytes(&self) -> usize

Returns the number of bytes currently in use.

Methods from Deref<Target = Bump>§

Source

pub fn min_align(&self) -> usize

Get this bump arena’s minimum alignment.

All objects allocated in this arena get aligned to this value.

§Example
let bump2 = bumpalo::Bump::<2>::with_min_align();
assert_eq!(bump2.min_align(), 2);

let bump4 = bumpalo::Bump::<4>::with_min_align();
assert_eq!(bump4.min_align(), 4);
Source

pub fn allocation_limit(&self) -> Option<usize>

The allocation limit for this arena in bytes.

§Example
let bump = bumpalo::Bump::with_capacity(0);

assert_eq!(bump.allocation_limit(), None);

bump.set_allocation_limit(Some(6));

assert_eq!(bump.allocation_limit(), Some(6));

bump.set_allocation_limit(None);

assert_eq!(bump.allocation_limit(), None);
Source

pub fn set_allocation_limit(&self, limit: Option<usize>)

Set the allocation limit in bytes for this arena.

The allocation limit is only enforced when allocating new backing chunks for a Bump. Updating the allocation limit will not affect existing allocations or any future allocations within the Bump’s current chunk.

§Example
let bump = bumpalo::Bump::with_capacity(0);

bump.set_allocation_limit(Some(0));

assert!(bump.try_alloc(5).is_err());
Source

pub fn alloc<T>(&self, val: T) -> &mut T

Allocate an object in this Bump and return an exclusive reference to it.

§Panics

Panics if reserving space for T fails.

§Example
let bump = bumpalo::Bump::new();
let x = bump.alloc("hello");
assert_eq!(*x, "hello");
Source

pub fn try_alloc<T>(&self, val: T) -> Result<&mut T, AllocErr>

Try to allocate an object in this Bump and return an exclusive reference to it.

§Errors

Errors if reserving space for T fails.

§Example
let bump = bumpalo::Bump::new();
let x = bump.try_alloc("hello");
assert_eq!(x, Ok(&mut "hello"));
Source

pub fn alloc_with<F, T>(&self, f: F) -> &mut T
where F: FnOnce() -> T,

Pre-allocate space for an object in this Bump, initializes it using the closure, then returns an exclusive reference to it.

See The _with Method Suffix for a discussion on the differences between the _with suffixed methods and those methods without it, their performance characteristics, and when you might or might not choose a _with suffixed method.

§Panics

Panics if reserving space for T fails.

§Example
let bump = bumpalo::Bump::new();
let x = bump.alloc_with(|| "hello");
assert_eq!(*x, "hello");
Source

pub fn try_alloc_with<F, T>(&self, f: F) -> Result<&mut T, AllocErr>
where F: FnOnce() -> T,

Tries to pre-allocate space for an object in this Bump, initializes it using the closure, then returns an exclusive reference to it.

See The _with Method Suffix for a discussion on the differences between the _with suffixed methods and those methods without it, their performance characteristics, and when you might or might not choose a _with suffixed method.

§Errors

Errors if reserving space for T fails.

§Example
let bump = bumpalo::Bump::new();
let x = bump.try_alloc_with(|| "hello");
assert_eq!(x, Ok(&mut "hello"));
Source

pub fn alloc_try_with<F, T, E>(&self, f: F) -> Result<&mut T, E>
where F: FnOnce() -> Result<T, E>,

Pre-allocates space for a Result in this Bump, initializes it using the closure, then returns an exclusive reference to its T if Ok.

Iff the allocation fails, the closure is not run.

Iff Err, an allocator rewind is attempted and the E instance is moved out of the allocator to be consumed or dropped as normal.

See The _with Method Suffix for a discussion on the differences between the _with suffixed methods and those methods without it, their performance characteristics, and when you might or might not choose a _with suffixed method.

For caveats specific to fallible initialization, see The _try_with Method Suffix.

§Errors

Iff the allocation succeeds but f fails, that error is forwarded by value.

§Panics

Panics if reserving space for Result<T, E> fails.

§Example
let bump = bumpalo::Bump::new();
let x = bump.alloc_try_with(|| Ok("hello"))?;
assert_eq!(*x, "hello");
Source

pub fn try_alloc_try_with<F, T, E>( &self, f: F, ) -> Result<&mut T, AllocOrInitError<E>>
where F: FnOnce() -> Result<T, E>,

Tries to pre-allocates space for a Result in this Bump, initializes it using the closure, then returns an exclusive reference to its T if all Ok.

Iff the allocation fails, the closure is not run.

Iff the closure returns Err, an allocator rewind is attempted and the E instance is moved out of the allocator to be consumed or dropped as normal.

See The _with Method Suffix for a discussion on the differences between the _with suffixed methods and those methods without it, their performance characteristics, and when you might or might not choose a _with suffixed method.

For caveats specific to fallible initialization, see The _try_with Method Suffix.

§Errors

Errors with the Alloc variant iff reserving space for Result<T, E> fails.

Iff the allocation succeeds but f fails, that error is forwarded by value inside the Init variant.

§Example
let bump = bumpalo::Bump::new();
let x = bump.try_alloc_try_with(|| Ok("hello"))?;
assert_eq!(*x, "hello");
Source

pub fn alloc_slice_copy<T>(&self, src: &[T]) -> &mut [T]
where T: Copy,

Copy a slice into this Bump and return an exclusive reference to the copy.

§Panics

Panics if reserving space for the slice fails.

§Example
let bump = bumpalo::Bump::new();
let x = bump.alloc_slice_copy(&[1, 2, 3]);
assert_eq!(x, &[1, 2, 3]);
Source

pub fn try_alloc_slice_copy<T>(&self, src: &[T]) -> Result<&mut [T], AllocErr>
where T: Copy,

Like alloc_slice_copy, but does not panic in case of allocation failure.

§Example
let bump = bumpalo::Bump::new();
let x = bump.try_alloc_slice_copy(&[1, 2, 3]);
assert_eq!(x, Ok(&mut[1, 2, 3] as &mut [_]));


let bump = bumpalo::Bump::new();
bump.set_allocation_limit(Some(4));
let x = bump.try_alloc_slice_copy(&[1, 2, 3, 4, 5, 6]);
assert_eq!(x, Err(bumpalo::AllocErr)); // too big
Source

pub fn alloc_slice_clone<T>(&self, src: &[T]) -> &mut [T]
where T: Clone,

Clone a slice into this Bump and return an exclusive reference to the clone. Prefer alloc_slice_copy if T is Copy.

§Panics

Panics if reserving space for the slice fails.

§Example
#[derive(Clone, Debug, Eq, PartialEq)]
struct Sheep {
    name: String,
}

let originals = [
    Sheep { name: "Alice".into() },
    Sheep { name: "Bob".into() },
    Sheep { name: "Cathy".into() },
];

let bump = bumpalo::Bump::new();
let clones = bump.alloc_slice_clone(&originals);
assert_eq!(originals, clones);
Source

pub fn try_alloc_slice_clone<T>(&self, src: &[T]) -> Result<&mut [T], AllocErr>
where T: Clone,

Like alloc_slice_clone but does not panic on failure.

Source

pub fn alloc_str(&self, src: &str) -> &mut str

Copy a string slice into this Bump and return an exclusive reference to it.

§Panics

Panics if reserving space for the string fails.

§Example
let bump = bumpalo::Bump::new();
let hello = bump.alloc_str("hello world");
assert_eq!("hello world", hello);
Source

pub fn try_alloc_str(&self, src: &str) -> Result<&mut str, AllocErr>

Same as alloc_str but does not panic on failure.

§Example
let bump = bumpalo::Bump::new();
let hello = bump.try_alloc_str("hello world").unwrap();
assert_eq!("hello world", hello);


let bump = bumpalo::Bump::new();
bump.set_allocation_limit(Some(5));
let hello = bump.try_alloc_str("hello world");
assert_eq!(Err(bumpalo::AllocErr), hello);
Source

pub fn alloc_slice_fill_with<T, F>(&self, len: usize, f: F) -> &mut [T]
where F: FnMut(usize) -> T,

Allocates a new slice of size len into this Bump and returns an exclusive reference to the copy.

The elements of the slice are initialized using the supplied closure. The closure argument is the position in the slice.

§Panics

Panics if reserving space for the slice fails.

§Example
let bump = bumpalo::Bump::new();
let x = bump.alloc_slice_fill_with(5, |i| 5 * (i + 1));
assert_eq!(x, &[5, 10, 15, 20, 25]);
Source

pub fn alloc_slice_try_fill_with<T, F, E>( &self, len: usize, f: F, ) -> Result<&mut [T], E>
where F: FnMut(usize) -> Result<T, E>,

Allocates a new slice of size len into this Bump and returns an exclusive reference to the copy, failing if the closure return an Err.

The elements of the slice are initialized using the supplied closure. The closure argument is the position in the slice.

§Panics

Panics if reserving space for the slice fails.

§Example
let bump = bumpalo::Bump::new();
let x: Result<&mut [usize], ()> = bump.alloc_slice_try_fill_with(5, |i| Ok(5 * i));
assert_eq!(x, Ok(bump.alloc_slice_copy(&[0, 5, 10, 15, 20])));
let bump = bumpalo::Bump::new();
let x: Result<&mut [usize], ()> = bump.alloc_slice_try_fill_with(
   5,
   |n| if n == 2 { Err(()) } else { Ok(n) }
);
assert_eq!(x, Err(()));
Source

pub fn try_alloc_slice_fill_with<T, F>( &self, len: usize, f: F, ) -> Result<&mut [T], AllocErr>
where F: FnMut(usize) -> T,

Allocates a new slice of size len into this Bump and returns an exclusive reference to the copy.

The elements of the slice are initialized using the supplied closure. The closure argument is the position in the slice.

§Example
let bump = bumpalo::Bump::new();
let x = bump.try_alloc_slice_fill_with(5, |i| 5 * (i + 1));
assert_eq!(x, Ok(&mut[5usize, 10, 15, 20, 25] as &mut [_]));


let bump = bumpalo::Bump::new();
bump.set_allocation_limit(Some(4));
let x = bump.try_alloc_slice_fill_with(10, |i| 5 * (i + 1));
assert_eq!(x, Err(bumpalo::AllocErr));
Source

pub fn alloc_slice_fill_copy<T>(&self, len: usize, value: T) -> &mut [T]
where T: Copy,

Allocates a new slice of size len into this Bump and returns an exclusive reference to the copy.

All elements of the slice are initialized to value.

§Panics

Panics if reserving space for the slice fails.

§Example
let bump = bumpalo::Bump::new();
let x = bump.alloc_slice_fill_copy(5, 42);
assert_eq!(x, &[42, 42, 42, 42, 42]);
Source

pub fn try_alloc_slice_fill_copy<T>( &self, len: usize, value: T, ) -> Result<&mut [T], AllocErr>
where T: Copy,

Same as alloc_slice_fill_copy but does not panic on failure.

Source

pub fn alloc_slice_fill_clone<T>(&self, len: usize, value: &T) -> &mut [T]
where T: Clone,

Allocates a new slice of size len slice into this Bump and return an exclusive reference to the copy.

All elements of the slice are initialized to value.clone().

§Panics

Panics if reserving space for the slice fails.

§Example
let bump = bumpalo::Bump::new();
let s: String = "Hello Bump!".to_string();
let x: &[String] = bump.alloc_slice_fill_clone(2, &s);
assert_eq!(x.len(), 2);
assert_eq!(&x[0], &s);
assert_eq!(&x[1], &s);
Source

pub fn try_alloc_slice_fill_clone<T>( &self, len: usize, value: &T, ) -> Result<&mut [T], AllocErr>
where T: Clone,

Like alloc_slice_fill_clone but does not panic on failure.

Source

pub fn alloc_slice_fill_iter<T, I>(&self, iter: I) -> &mut [T]
where I: IntoIterator<Item = T>, <I as IntoIterator>::IntoIter: ExactSizeIterator,

Allocates a new slice of size len slice into this Bump and return an exclusive reference to the copy.

The elements are initialized using the supplied iterator.

§Panics

Panics if reserving space for the slice fails, or if the supplied iterator returns fewer elements than it promised.

§Example
let bump = bumpalo::Bump::new();
let x: &[i32] = bump.alloc_slice_fill_iter([2, 3, 5].iter().cloned().map(|i| i * i));
assert_eq!(x, [4, 9, 25]);
Source

pub fn alloc_slice_try_fill_iter<T, I, E>(&self, iter: I) -> Result<&mut [T], E>
where I: IntoIterator<Item = Result<T, E>>, <I as IntoIterator>::IntoIter: ExactSizeIterator,

Allocates a new slice of size len slice into this Bump and return an exclusive reference to the copy, failing if the iterator returns an Err.

The elements are initialized using the supplied iterator.

§Panics

Panics if reserving space for the slice fails, or if the supplied iterator returns fewer elements than it promised.

§Examples
let bump = bumpalo::Bump::new();
let x: Result<&mut [i32], ()> = bump.alloc_slice_try_fill_iter(
   [2, 3, 5].iter().cloned().map(|i| Ok(i * i))
);
assert_eq!(x, Ok(bump.alloc_slice_copy(&[4, 9, 25])));
let bump = bumpalo::Bump::new();
let x: Result<&mut [i32], ()> = bump.alloc_slice_try_fill_iter(
   [Ok(2), Err(()), Ok(5)].iter().cloned()
);
assert_eq!(x, Err(()));
Source

pub fn try_alloc_slice_fill_iter<T, I>( &self, iter: I, ) -> Result<&mut [T], AllocErr>
where I: IntoIterator<Item = T>, <I as IntoIterator>::IntoIter: ExactSizeIterator,

Allocates a new slice of size iter.len() slice into this Bump and return an exclusive reference to the copy. Does not panic on failure.

The elements are initialized using the supplied iterator.

§Example
let bump = bumpalo::Bump::new();
let x: &[i32] = bump.try_alloc_slice_fill_iter([2, 3, 5]
    .iter().cloned().map(|i| i * i)).unwrap();
assert_eq!(x, [4, 9, 25]);
Source

pub fn alloc_slice_fill_default<T>(&self, len: usize) -> &mut [T]
where T: Default,

Allocates a new slice of size len slice into this Bump and return an exclusive reference to the copy.

All elements of the slice are initialized to T::default().

§Panics

Panics if reserving space for the slice fails.

§Example
let bump = bumpalo::Bump::new();
let x = bump.alloc_slice_fill_default::<u32>(5);
assert_eq!(x, &[0, 0, 0, 0, 0]);
Source

pub fn try_alloc_slice_fill_default<T>( &self, len: usize, ) -> Result<&mut [T], AllocErr>
where T: Default,

Like alloc_slice_fill_default but does not panic on failure.

Source

pub fn alloc_layout(&self, layout: Layout) -> NonNull<u8>

Allocate space for an object with the given Layout.

The returned pointer points at uninitialized memory, and should be initialized with std::ptr::write.

§Panics

Panics if reserving space matching layout fails.

Source

pub fn try_alloc_layout(&self, layout: Layout) -> Result<NonNull<u8>, AllocErr>

Attempts to allocate space for an object with the given Layout or else returns an Err.

The returned pointer points at uninitialized memory, and should be initialized with std::ptr::write.

§Errors

Errors if reserving space matching layout fails.

Source

pub fn chunk_capacity(&self) -> usize

Gets the remaining capacity in the current chunk (in bytes).

§Example
use bumpalo::Bump;

let bump = Bump::with_capacity(100);

let capacity = bump.chunk_capacity();
assert!(capacity >= 100);
Source

pub unsafe fn iter_allocated_chunks_raw(&self) -> ChunkRawIter<'_, MIN_ALIGN>

Returns an iterator over raw pointers to chunks of allocated memory that this arena has bump allocated into.

This is an unsafe version of iter_allocated_chunks(), with the caller responsible for safe usage of the returned pointers as well as ensuring that the iterator is not invalidated by new allocations.

§Safety

Allocations from this arena must not be performed while the returned iterator is alive. If reading the chunk data (or casting to a reference) the caller must ensure that there exist no mutable references to previously allocated data.

In addition, all of the caveats when reading the chunk data from iter_allocated_chunks() still apply.

Source

pub fn allocated_bytes(&self) -> usize

Calculates the number of bytes currently allocated across all chunks in this bump arena.

If you allocate types of different alignments or types with larger-than-typical alignment in the same arena, some padding bytes might get allocated in the bump arena. Note that those padding bytes will add to this method’s resulting sum, so you cannot rely on it only counting the sum of the sizes of the things you’ve allocated in the arena.

The allocated bytes do not include the size of bumpalo’s metadata, so the amount of memory requested from the Rust allocator is higher than the returned value.

§Example
let bump = bumpalo::Bump::new();
let _x = bump.alloc_slice_fill_default::<u32>(5);
let bytes = bump.allocated_bytes();
assert!(bytes >= core::mem::size_of::<u32>() * 5);
Source

pub fn allocated_bytes_including_metadata(&self) -> usize

Calculates the number of bytes requested from the Rust allocator for this Bump.

This number is equal to the allocated_bytes() plus the size of the bump metadata.

Trait Implementations§

Source§

impl Default for Arena

Source§

fn default() -> Arena

Returns the “default value” for a type. Read more
Source§

impl Deref for Arena

Source§

type Target = Bump

The resulting type after dereferencing.
Source§

fn deref(&self) -> &<Arena as Deref>::Target

Dereferences the value.

Auto Trait Implementations§

§

impl !Freeze for Arena

§

impl !RefUnwindSafe for Arena

§

impl Send for Arena

§

impl !Sync for Arena

§

impl Unpin for Arena

§

impl !UnwindSafe for Arena

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T, R> CollectAndApply<T, R> for T

Source§

fn collect_and_apply<I, F>(iter: I, f: F) -> R
where I: Iterator<Item = T>, F: FnOnce(&[T]) -> R,

Equivalent to f(&iter.collect::<Vec<_>>()).

Source§

type Output = R

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<P, T> Receiver for P
where P: Deref<Target = T> + ?Sized, T: ?Sized,

Source§

type Target = T

🔬This is a nightly-only experimental API. (arbitrary_self_types)
The target type on which the method may be called.
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more