pub struct Bump<A = Global, const MIN_ALIGN: usize = 1, const UP: bool = true, const GUARANTEED_ALLOCATED: bool = true>where
MinimumAlignment<MIN_ALIGN>: SupportedMinimumAlignment,
A: BaseAllocator<GUARANTEED_ALLOCATED>,{ /* private fields */ }Expand description
A bump allocator.
§Overview
All of the methods mentioned here that do allocations, panic if the base allocator returned an error.
For every such panicking method, there is a corresponding try_-prefixed version that returns a Result instead.
§Creation
- with a default size hint:
new(_in)/default - provide a size hint:
with_size(_in) - provide a minimum capacity:
with_capacity(_in) - create a bump without allocation:
unallocated
§Allocation methods
-
sized values:
alloc,alloc_with,alloc_default,alloc_zeroed -
strings:
alloc_str,alloc_fmt,alloc_fmt_mut -
slices:
alloc_slice_clone,alloc_slice_copy,alloc_slice_fill,alloc_slice_fill_with,alloc_zeroed_slice -
slices from an iterator:
alloc_iter,alloc_iter_exact,alloc_iter_mut,alloc_iter_mut_rev -
uninitialized values:
alloc_uninit,alloc_uninit_slice,alloc_uninit_slice_forwhich can then be conveniently initialized by the
init*methods ofBumpBox. -
fixed collections:
alloc_fixed_vec,alloc_fixed_string -
results:
alloc_try_with,alloc_try_with_mut
§Collections
A Bump (and BumpScope) can be used to allocate collections of this crate…
use bump_scope::{ Bump, BumpString };
let bump: Bump = Bump::new();
let mut string = BumpString::new_in(&bump);
string.push_str("Hello");
string.push_str(" world!");… and collections from crates that use allocator_api2’s Allocator like hashbrown’s HashMap:
use bump_scope::{ Bump, BumpString };
use hashbrown::HashMap;
let bump: Bump = Bump::new();
let mut map = HashMap::new_in(&bump);
map.insert("tau", 6.283);On nightly and with the feature "nightly-allocator-api" you can also bump allocate collections from std that have an allocator parameter:
#![feature(allocator_api, btreemap_alloc)]
use bump_scope::Bump;
use std::collections::{ VecDeque, BTreeMap, LinkedList };
let bump: Bump = Bump::new();
let vec = Vec::new_in(&bump);
let queue = VecDeque::new_in(&bump);
let map = BTreeMap::new_in(&bump);
let list = LinkedList::new_in(&bump);§Scopes and Checkpoints
§Gotchas
Allocating directly on a Bump is not compatible with entering bump scopes at the same time:
let mut bump: Bump = Bump::new();
let one = bump.alloc(1);
bump.scoped(|bump| {
// whatever
});Instead convert it to a BumpScope first:
let mut bump: Bump = Bump::new();
let bump = bump.as_mut_scope();
let one = bump.alloc(1);
bump.scoped(|bump| {
// whatever
});Implementations§
Source§impl<A, const MIN_ALIGN: usize, const UP: bool> Bump<A, MIN_ALIGN, UP, false>
impl<A, const MIN_ALIGN: usize, const UP: bool> Bump<A, MIN_ALIGN, UP, false>
Sourcepub const fn unallocated() -> Self
pub const fn unallocated() -> Self
Constructs a new Bump without doing any allocations.
The resulting Bump will have its GUARANTEED_ALLOCATED parameter set to false.
Such a Bump is unable to create a scope with scoped or scope_guard.
It has to first be converted into a guaranteed allocated Bump using guaranteed_allocated, guaranteed_allocated_ref or guaranteed_allocated_mut.
This function is const starting from rust version 1.83.
Source§impl<A, const MIN_ALIGN: usize, const UP: bool, const GUARANTEED_ALLOCATED: bool> Bump<A, MIN_ALIGN, UP, GUARANTEED_ALLOCATED>where
MinimumAlignment<MIN_ALIGN>: SupportedMinimumAlignment,
A: BaseAllocator<GUARANTEED_ALLOCATED> + Default,
impl<A, const MIN_ALIGN: usize, const UP: bool, const GUARANTEED_ALLOCATED: bool> Bump<A, MIN_ALIGN, UP, GUARANTEED_ALLOCATED>where
MinimumAlignment<MIN_ALIGN>: SupportedMinimumAlignment,
A: BaseAllocator<GUARANTEED_ALLOCATED> + Default,
Sourcepub fn with_size(size: usize) -> Self
pub fn with_size(size: usize) -> Self
Constructs a new Bump with a size hint for the first chunk.
If you want to ensure a specific capacity, use with_capacity instead.
The size of the chunk allocation will be the provided size rounded up and with a small size subtracted to account for base allocator metadata.
The resulting chunk size may be larger still if the base allocator returned a bigger memory block than requested.
Disclaimer: The way in which the chunk layout is calculated might change. Such a change is not considered semver breaking.
§Panics
Panics if the allocation fails.
Sourcepub fn with_capacity(layout: Layout) -> Self
pub fn with_capacity(layout: Layout) -> Self
Sourcepub fn try_new() -> Result<Self, AllocError>
pub fn try_new() -> Result<Self, AllocError>
Sourcepub fn try_with_size(size: usize) -> Result<Self, AllocError>
pub fn try_with_size(size: usize) -> Result<Self, AllocError>
Constructs a new Bump with a size hint for the first chunk.
If you want to ensure a specific capacity, use try_with_capacity instead.
The size of the chunk allocation will be the provided size rounded up and with a small size subtracted to account for base allocator metadata.
The resulting chunk size may be larger still if the base allocator returned a bigger memory block than requested.
Disclaimer: The way in which the chunk layout is calculated might change. Such a change is not considered semver breaking.
§Errors
Errors if the allocation fails.
Sourcepub fn try_with_capacity(layout: Layout) -> Result<Self, AllocError>
pub fn try_with_capacity(layout: Layout) -> Result<Self, AllocError>
Constructs a new Bump with at least enough space for layout.
To construct a Bump with a size hint use try_with_size instead.
§Errors
Errors if the allocation fails.
Source§impl<A, const MIN_ALIGN: usize, const UP: bool> Bump<A, MIN_ALIGN, UP>
impl<A, const MIN_ALIGN: usize, const UP: bool> Bump<A, MIN_ALIGN, UP>
These functions are only available if the Bump is guaranteed allocated.
Sourcepub fn scoped<R>(
&mut self,
f: impl FnOnce(BumpScope<'_, A, MIN_ALIGN, UP>) -> R,
) -> R
pub fn scoped<R>( &mut self, f: impl FnOnce(BumpScope<'_, A, MIN_ALIGN, UP>) -> R, ) -> R
Calls f with a new child scope.
§Examples
let mut bump: Bump = Bump::new();
bump.scoped(|bump| {
bump.alloc_str("Hello world!");
assert_eq!(bump.stats().allocated(), 12);
});
assert_eq!(bump.stats().allocated(), 0);Sourcepub fn scoped_aligned<const NEW_MIN_ALIGN: usize, R>(
&mut self,
f: impl FnOnce(BumpScope<'_, A, MIN_ALIGN, UP>) -> R,
) -> Rwhere
MinimumAlignment<NEW_MIN_ALIGN>: SupportedMinimumAlignment,
pub fn scoped_aligned<const NEW_MIN_ALIGN: usize, R>(
&mut self,
f: impl FnOnce(BumpScope<'_, A, MIN_ALIGN, UP>) -> R,
) -> Rwhere
MinimumAlignment<NEW_MIN_ALIGN>: SupportedMinimumAlignment,
Calls f with a new child scope of a new minimum alignment.
Sourcepub fn scope_guard(&mut self) -> BumpScopeGuardRoot<'_, A, MIN_ALIGN, UP>
pub fn scope_guard(&mut self) -> BumpScopeGuardRoot<'_, A, MIN_ALIGN, UP>
Creates a new BumpScopeGuardRoot.
This allows for creation of child scopes.
§Examples
let mut bump: Bump = Bump::new();
{
let mut guard = bump.scope_guard();
let bump = guard.scope();
bump.alloc_str("Hello world!");
assert_eq!(bump.stats().allocated(), 12);
}
assert_eq!(bump.stats().allocated(), 0);Sourcepub fn aligned<const NEW_MIN_ALIGN: usize, R>(
&mut self,
f: impl FnOnce(BumpScope<'_, A, NEW_MIN_ALIGN, UP>) -> R,
) -> Rwhere
MinimumAlignment<NEW_MIN_ALIGN>: SupportedMinimumAlignment,
pub fn aligned<const NEW_MIN_ALIGN: usize, R>(
&mut self,
f: impl FnOnce(BumpScope<'_, A, NEW_MIN_ALIGN, UP>) -> R,
) -> Rwhere
MinimumAlignment<NEW_MIN_ALIGN>: SupportedMinimumAlignment,
Calls f with this scope but with a new minimum alignment.
Sourcepub fn checkpoint(&self) -> Checkpoint
pub fn checkpoint(&self) -> Checkpoint
Creates a checkpoint of the current bump position.
§Examples
let checkpoint = bump.checkpoint();
{
let hello = bump.alloc_str("hello");
assert_eq!(bump.stats().allocated(), 5);
}
unsafe { bump.reset_to(checkpoint); }
assert_eq!(bump.stats().allocated(), 0);Sourcepub unsafe fn reset_to(&self, checkpoint: Checkpoint)
pub unsafe fn reset_to(&self, checkpoint: Checkpoint)
Resets the bump position to a previously created checkpoint. The memory that has been allocated since then will be reused by future allocations.
§Safety
- the checkpoint must have been created by this bump allocator
- the bump allocator must not have been
resetsince creation of this checkpoint - there must be no references to allocations made since creation of this checkpoint
Source§impl<A, const MIN_ALIGN: usize, const UP: bool, const GUARANTEED_ALLOCATED: bool> Bump<A, MIN_ALIGN, UP, GUARANTEED_ALLOCATED>where
MinimumAlignment<MIN_ALIGN>: SupportedMinimumAlignment,
A: BaseAllocator<GUARANTEED_ALLOCATED>,
impl<A, const MIN_ALIGN: usize, const UP: bool, const GUARANTEED_ALLOCATED: bool> Bump<A, MIN_ALIGN, UP, GUARANTEED_ALLOCATED>where
MinimumAlignment<MIN_ALIGN>: SupportedMinimumAlignment,
A: BaseAllocator<GUARANTEED_ALLOCATED>,
Sourcepub fn with_size_in(size: usize, allocator: A) -> Self
pub fn with_size_in(size: usize, allocator: A) -> Self
Constructs a new Bump with a size hint for the first chunk.
If you want to ensure a specific capacity, use with_capacity_in instead.
The size of the chunk allocation will be the provided size rounded up and with a small size subtracted to account for base allocator metadata.
The resulting chunk size may be larger still if the base allocator returned a bigger memory block than requested.
Disclaimer: The way in which the chunk layout is calculated might change. Such a change is not considered semver breaking.
§Panics
Panics if the allocation fails.
Sourcepub fn with_capacity_in(layout: Layout, allocator: A) -> Self
pub fn with_capacity_in(layout: Layout, allocator: A) -> Self
Constructs a new Bump with at least enough space for layout.
To construct a Bump with a size hint use with_size_in instead.
§Panics
Panics if the allocation fails.
Sourcepub fn try_new_in(allocator: A) -> Result<Self, AllocError>
pub fn try_new_in(allocator: A) -> Result<Self, AllocError>
Sourcepub fn try_with_size_in(size: usize, allocator: A) -> Result<Self, AllocError>
pub fn try_with_size_in(size: usize, allocator: A) -> Result<Self, AllocError>
Constructs a new Bump with a size hint for the first chunk.
If you want to ensure a specific capacity, use try_with_capacity_in instead.
The size of the chunk allocation will be the provided size rounded up and with a small size subtracted to account for base allocator metadata.
The resulting chunk size may be larger still if the base allocator returned a bigger memory block than requested.
Disclaimer: The way in which the chunk layout is calculated might change. Such a change is not considered semver breaking.
§Errors
Errors if the allocation fails.
Sourcepub fn try_with_capacity_in(
layout: Layout,
allocator: A,
) -> Result<Self, AllocError>
pub fn try_with_capacity_in( layout: Layout, allocator: A, ) -> Result<Self, AllocError>
Constructs a new Bump with at least enough space for layout.
To construct a Bump with a size hint use try_with_size_in instead.
§Errors
Errors if the allocation fails.
Sourcepub fn stats(&self) -> Stats<'_, GUARANTEED_ALLOCATED>
pub fn stats(&self) -> Stats<'_, GUARANTEED_ALLOCATED>
Returns a type which provides statistics about the memory usage of the bump allocator.
Sourcepub fn as_scope(&self) -> &BumpScope<'_, A, MIN_ALIGN, UP, GUARANTEED_ALLOCATED>
pub fn as_scope(&self) -> &BumpScope<'_, A, MIN_ALIGN, UP, GUARANTEED_ALLOCATED>
Returns this &Bump as a &BumpScope.
Sourcepub fn as_mut_scope(
&mut self,
) -> &mut BumpScope<'_, A, MIN_ALIGN, UP, GUARANTEED_ALLOCATED>
pub fn as_mut_scope( &mut self, ) -> &mut BumpScope<'_, A, MIN_ALIGN, UP, GUARANTEED_ALLOCATED>
Returns this &mut Bump as a &mut BumpScope.
Sourcepub fn into_aligned<const NEW_MIN_ALIGN: usize>(
self,
) -> Bump<A, NEW_MIN_ALIGN, UP, GUARANTEED_ALLOCATED>where
MinimumAlignment<NEW_MIN_ALIGN>: SupportedMinimumAlignment,
pub fn into_aligned<const NEW_MIN_ALIGN: usize>(
self,
) -> Bump<A, NEW_MIN_ALIGN, UP, GUARANTEED_ALLOCATED>where
MinimumAlignment<NEW_MIN_ALIGN>: SupportedMinimumAlignment,
Converts this Bump into a Bump with a new minimum alignment.
Sourcepub fn as_aligned_mut<const NEW_MIN_ALIGN: usize>(
&mut self,
) -> &mut Bump<A, NEW_MIN_ALIGN, UP, GUARANTEED_ALLOCATED>where
MinimumAlignment<NEW_MIN_ALIGN>: SupportedMinimumAlignment,
pub fn as_aligned_mut<const NEW_MIN_ALIGN: usize>(
&mut self,
) -> &mut Bump<A, NEW_MIN_ALIGN, UP, GUARANTEED_ALLOCATED>where
MinimumAlignment<NEW_MIN_ALIGN>: SupportedMinimumAlignment,
Mutably borrows Bump with a new minimum alignment.
This can not decrease the alignment. Trying to decrease alignment will result in a compile error.
You can use aligned or scoped_aligned to decrease the alignment.“
To decrease alignment we need to ensure that we return to our original alignment. That can only be guaranteed by a function taking a closure like the ones mentioned above.
Sourcepub fn guaranteed_allocated(self) -> Bump<A, MIN_ALIGN, UP>
pub fn guaranteed_allocated(self) -> Bump<A, MIN_ALIGN, UP>
Sourcepub fn try_guaranteed_allocated(
self,
) -> Result<Bump<A, MIN_ALIGN, UP>, AllocError>
pub fn try_guaranteed_allocated( self, ) -> Result<Bump<A, MIN_ALIGN, UP>, AllocError>
Sourcepub fn guaranteed_allocated_ref(&self) -> &Bump<A, MIN_ALIGN, UP>
pub fn guaranteed_allocated_ref(&self) -> &Bump<A, MIN_ALIGN, UP>
Sourcepub fn try_guaranteed_allocated_ref(
&self,
) -> Result<&Bump<A, MIN_ALIGN, UP>, AllocError>
pub fn try_guaranteed_allocated_ref( &self, ) -> Result<&Bump<A, MIN_ALIGN, UP>, AllocError>
Sourcepub fn guaranteed_allocated_mut(&mut self) -> &mut Bump<A, MIN_ALIGN, UP>
pub fn guaranteed_allocated_mut(&mut self) -> &mut Bump<A, MIN_ALIGN, UP>
Sourcepub fn try_guaranteed_allocated_mut(
&mut self,
) -> Result<&mut Bump<A, MIN_ALIGN, UP>, AllocError>
pub fn try_guaranteed_allocated_mut( &mut self, ) -> Result<&mut Bump<A, MIN_ALIGN, UP>, AllocError>
Sourcepub fn not_guaranteed_allocated(self) -> Bump<A, MIN_ALIGN, UP, false>where
A: Default,
pub fn not_guaranteed_allocated(self) -> Bump<A, MIN_ALIGN, UP, false>where
A: Default,
Converts this BumpScope into a not guaranteed allocated Bump.
Sourcepub fn not_guaranteed_allocated_ref(&self) -> &Bump<A, MIN_ALIGN, UP, false>where
A: Default,
pub fn not_guaranteed_allocated_ref(&self) -> &Bump<A, MIN_ALIGN, UP, false>where
A: Default,
Borrows Bump as a not guaranteed allocated Bump.
Note that it’s not possible to mutably borrow as a not guaranteed allocated bump allocator. That’s because
a user could mem::swap it with an actual unallocated bump allocator which in turn would make &mut self
unallocated.
Source§impl<A, const MIN_ALIGN: usize, const UP: bool, const GUARANTEED_ALLOCATED: bool> Bump<A, MIN_ALIGN, UP, GUARANTEED_ALLOCATED>where
MinimumAlignment<MIN_ALIGN>: SupportedMinimumAlignment,
A: BaseAllocator<GUARANTEED_ALLOCATED>,
impl<A, const MIN_ALIGN: usize, const UP: bool, const GUARANTEED_ALLOCATED: bool> Bump<A, MIN_ALIGN, UP, GUARANTEED_ALLOCATED>where
MinimumAlignment<MIN_ALIGN>: SupportedMinimumAlignment,
A: BaseAllocator<GUARANTEED_ALLOCATED>,
Sourcepub fn alloc_zeroed<T>(&self) -> BumpBox<'_, T> ⓘwhere
T: FromZeros,
Available on crate feature zerocopy only.
pub fn alloc_zeroed<T>(&self) -> BumpBox<'_, T> ⓘwhere
T: FromZeros,
zerocopy only.Sourcepub fn alloc_zeroed_slice<T>(&self, len: usize) -> BumpBox<'_, [T]> ⓘwhere
T: FromZeros,
Available on crate feature zerocopy only.
pub fn alloc_zeroed_slice<T>(&self, len: usize) -> BumpBox<'_, [T]> ⓘwhere
T: FromZeros,
zerocopy only.Sourcepub fn try_alloc_zeroed<T>(&self) -> Result<BumpBox<'_, T>, AllocError>where
T: FromZeros,
Available on crate feature zerocopy only.
pub fn try_alloc_zeroed<T>(&self) -> Result<BumpBox<'_, T>, AllocError>where
T: FromZeros,
zerocopy only.Sourcepub fn try_alloc_zeroed_slice<T>(
&self,
len: usize,
) -> Result<BumpBox<'_, [T]>, AllocError>where
T: FromZeros,
Available on crate feature zerocopy only.
pub fn try_alloc_zeroed_slice<T>(
&self,
len: usize,
) -> Result<BumpBox<'_, [T]>, AllocError>where
T: FromZeros,
zerocopy only.Source§impl<A, const MIN_ALIGN: usize, const UP: bool, const GUARANTEED_ALLOCATED: bool> Bump<A, MIN_ALIGN, UP, GUARANTEED_ALLOCATED>where
MinimumAlignment<MIN_ALIGN>: SupportedMinimumAlignment,
A: BaseAllocator<GUARANTEED_ALLOCATED>,
impl<A, const MIN_ALIGN: usize, const UP: bool, const GUARANTEED_ALLOCATED: bool> Bump<A, MIN_ALIGN, UP, GUARANTEED_ALLOCATED>where
MinimumAlignment<MIN_ALIGN>: SupportedMinimumAlignment,
A: BaseAllocator<GUARANTEED_ALLOCATED>,
Functions to allocate. Available as fallible or infallible.
These require a guaranteed allocated bump allocator.
Sourcepub fn alloc_with<T>(&self, f: impl FnOnce() -> T) -> BumpBox<'_, T> ⓘ
pub fn alloc_with<T>(&self, f: impl FnOnce() -> T) -> BumpBox<'_, T> ⓘ
Pre-allocate space for an object. Once space is allocated f will be called to create the value to be put at that place.
In some situations this can help the compiler realize that T can be constructed at the allocated space instead of having to copy it over.
§Panics
Panics if the allocation fails.
§Examples
let allocated = bump.alloc_with(|| 123);
assert_eq!(allocated, 123);Sourcepub fn alloc_default<T: Default>(&self) -> BumpBox<'_, T> ⓘ
pub fn alloc_default<T: Default>(&self) -> BumpBox<'_, T> ⓘ
Allocate an object with its default value.
This is equivalent to alloc_with(T::default).
§Panics
Panics if the allocation fails.
§Examples
let allocated = bump.alloc_default::<i32>();
assert_eq!(allocated, 0);Sourcepub fn alloc_slice_fill_with<T>(
&self,
len: usize,
f: impl FnMut() -> T,
) -> BumpBox<'_, [T]> ⓘ
pub fn alloc_slice_fill_with<T>( &self, len: usize, f: impl FnMut() -> T, ) -> BumpBox<'_, [T]> ⓘ
Allocates a slice by fill it with elements returned by calling a closure repeatedly.
This method uses a closure to create new values. If you’d rather
Clone a given value, use alloc_slice_fill. If you want to use the Default
trait to generate values, you can pass Default::default as the
argument.
§Panics
Panics if the allocation fails.
§Examples
let allocated = bump.alloc_slice_fill_with::<i32>(3, Default::default);
assert_eq!(allocated, [0, 0, 0]);Sourcepub fn alloc_fmt(&self, args: Arguments<'_>) -> BumpBox<'_, str> ⓘ
pub fn alloc_fmt(&self, args: Arguments<'_>) -> BumpBox<'_, str> ⓘ
Allocate a str from format arguments.
If you have a &mut self you can use alloc_fmt_mut instead for better performance.
§Panics
Panics if the allocation fails.
Panics if a formatting trait implementation returned an error.
§Examples
let one = 1;
let two = 2;
let string = bump.alloc_fmt(format_args!("{one} + {two} = {}", one + two));
assert_eq!(string, "1 + 2 = 3");Sourcepub fn alloc_fmt_mut(&mut self, args: Arguments<'_>) -> BumpBox<'_, str> ⓘ
pub fn alloc_fmt_mut(&mut self, args: Arguments<'_>) -> BumpBox<'_, str> ⓘ
Allocate a str from format arguments.
This function is designed as a performance improvement over alloc_fmt. By taking self as &mut, it can use the entire remaining chunk space as the capacity for its string buffer. As a result, the string buffer rarely needs to grow.
§Panics
Panics if the allocation fails.
Panics if a formatting trait implementation returned an error.
§Examples
let one = 1;
let two = 2;
let string = bump.alloc_fmt_mut(format_args!("{one} + {two} = {}", one + two));
assert_eq!(string, "1 + 2 = 3");Sourcepub fn alloc_cstr(&self, src: &CStr) -> &CStr
pub fn alloc_cstr(&self, src: &CStr) -> &CStr
Sourcepub fn alloc_cstr_from_str(&self, src: &str) -> &CStr
pub fn alloc_cstr_from_str(&self, src: &str) -> &CStr
Allocate a CStr from a str.
If src contains a '\0' then the CStr will stop there.
§Panics
Panics if the allocation fails.
§Examples
let allocated = bump.alloc_cstr_from_str("Hello world!");
assert_eq!(allocated, c"Hello world!");
let allocated = bump.alloc_cstr_from_str("abc\0def");
assert_eq!(allocated, c"abc");Sourcepub fn alloc_cstr_fmt(&self, args: Arguments<'_>) -> &CStr
pub fn alloc_cstr_fmt(&self, args: Arguments<'_>) -> &CStr
Allocate a CStr from format arguments.
If the string contains a '\0' then the CStr will stop there.
If you have a &mut self you can use alloc_cstr_fmt_mut instead for better performance.
§Panics
Panics if the allocation fails.
Panics if a formatting trait implementation returned an error.
§Examples
let one = 1;
let two = 2;
let string = bump.alloc_cstr_fmt(format_args!("{one} + {two} = {}", one + two));
assert_eq!(string, c"1 + 2 = 3");
let one = bump.alloc_cstr_fmt(format_args!("{one}\0{two}"));
assert_eq!(one, c"1");Sourcepub fn alloc_cstr_fmt_mut(&mut self, args: Arguments<'_>) -> &CStr
pub fn alloc_cstr_fmt_mut(&mut self, args: Arguments<'_>) -> &CStr
Allocate a CStr from format arguments.
If the string contains a '\0' then the CStr will stop there.
This function is designed as a performance improvement over alloc_cstr_fmt. By taking self as &mut, it can use the entire remaining chunk space as the capacity for its string buffer. As a result, the string buffer rarely needs to grow.
§Panics
Panics if the allocation fails.
Panics if a formatting trait implementation returned an error.
§Examples
let one = 1;
let two = 2;
let string = bump.alloc_cstr_fmt_mut(format_args!("{one} + {two} = {}", one + two));
assert_eq!(string, c"1 + 2 = 3");
let one = bump.alloc_cstr_fmt_mut(format_args!("{one}\0{two}"));
assert_eq!(one, c"1");Sourcepub fn alloc_iter<T>(
&self,
iter: impl IntoIterator<Item = T>,
) -> BumpBox<'_, [T]> ⓘ
pub fn alloc_iter<T>( &self, iter: impl IntoIterator<Item = T>, ) -> BumpBox<'_, [T]> ⓘ
Allocate elements of an iterator into a slice.
If you have an impl ExactSizeIterator then you can use alloc_iter_exact instead for better performance.
If iter is not an ExactSizeIterator but you have a &mut self you can still get somewhat better performance by using alloc_iter_mut.
§Panics
Panics if the allocation fails.
§Examples
let slice = bump.alloc_iter([1, 2, 3]);
assert_eq!(slice, [1, 2, 3]);Sourcepub fn alloc_iter_exact<T, I>(
&self,
iter: impl IntoIterator<Item = T, IntoIter = I>,
) -> BumpBox<'_, [T]> ⓘwhere
I: ExactSizeIterator<Item = T>,
pub fn alloc_iter_exact<T, I>(
&self,
iter: impl IntoIterator<Item = T, IntoIter = I>,
) -> BumpBox<'_, [T]> ⓘwhere
I: ExactSizeIterator<Item = T>,
Sourcepub fn alloc_iter_mut<T>(
&mut self,
iter: impl IntoIterator<Item = T>,
) -> BumpBox<'_, [T]> ⓘ
pub fn alloc_iter_mut<T>( &mut self, iter: impl IntoIterator<Item = T>, ) -> BumpBox<'_, [T]> ⓘ
Allocate elements of an iterator into a slice.
This function is designed as a performance improvement over alloc_iter. By taking self as &mut, it can use the entire remaining chunk space as the capacity for its vector. As a result, the vector rarely needs to grow.
When bumping downwards, prefer alloc_iter_mut_rev instead.
§Panics
Panics if the allocation fails.
§Examples
let slice = bump.alloc_iter_mut([1, 2, 3]);
assert_eq!(slice, [1, 2, 3]);Sourcepub fn alloc_iter_mut_rev<T>(
&mut self,
iter: impl IntoIterator<Item = T>,
) -> BumpBox<'_, [T]> ⓘ
pub fn alloc_iter_mut_rev<T>( &mut self, iter: impl IntoIterator<Item = T>, ) -> BumpBox<'_, [T]> ⓘ
Allocate elements of an iterator into a slice in reverse order.
Compared to alloc_iter_mut this function is more performant
for downwards bumping allocators as the allocation for the vector can be shrunk in place
without any ptr::copy.
The reverse is true when upwards allocating. In that case it’s better to use alloc_iter_mut to prevent
the ptr::copy.
§Panics
Panics if the allocation fails.
§Examples
let slice = bump.alloc_iter_mut_rev([1, 2, 3]);
assert_eq!(slice, [3, 2, 1]);Sourcepub fn alloc_uninit<T>(&self) -> BumpBox<'_, MaybeUninit<T>> ⓘ
pub fn alloc_uninit<T>(&self) -> BumpBox<'_, MaybeUninit<T>> ⓘ
Allocate an unitialized object.
You can safely initialize the object with init or unsafely with assume_init.
§Panics
Panics if the allocation fails.
§Examples
Safely:
let five = bump.alloc_uninit();
let five = five.init(5);
assert_eq!(*five, 5)Unsafely:
let mut five = bump.alloc_uninit();
let five = unsafe {
five.write(5);
five.assume_init()
};
assert_eq!(*five, 5)Sourcepub fn alloc_uninit_slice<T>(&self, len: usize) -> BumpBox<'_, [MaybeUninit<T>]> ⓘ
pub fn alloc_uninit_slice<T>(&self, len: usize) -> BumpBox<'_, [MaybeUninit<T>]> ⓘ
Allocate an unitialized object slice.
You can safely initialize the object with
init_fill,
init_fill_with,
init_copy,
init_clone or unsafely with
assume_init.
§Panics
Panics if the allocation fails.
§Examples
Safely:
let values = bump.alloc_uninit_slice(3);
let values = values.init_copy(&[1, 2, 3]);
assert_eq!(values, [1, 2, 3])Unsafely:
let mut values = bump.alloc_uninit_slice(3);
let values = unsafe {
values[0].write(1);
values[1].write(2);
values[2].write(3);
values.assume_init()
};
assert_eq!(values, [1, 2, 3]);Sourcepub fn alloc_uninit_slice_for<T>(
&self,
slice: &[T],
) -> BumpBox<'_, [MaybeUninit<T>]> ⓘ
pub fn alloc_uninit_slice_for<T>( &self, slice: &[T], ) -> BumpBox<'_, [MaybeUninit<T>]> ⓘ
Allocate an unitialized object slice.
You can safely initialize the object with
init_fill,
init_fill_with,
init_copy,
init_clone or unsafely with
assume_init.
This is just like alloc_uninit_slice but uses a slice to provide the len.
This avoids a check for a valid layout. The elements of slice are irrelevant.
§Panics
Panics if the allocation fails.
§Examples
let slice = &[1, 2, 3];
let other_slice = bump.alloc_uninit_slice_for(slice);
assert_eq!(other_slice.len(), 3);Sourcepub fn alloc_fixed_vec<T>(&self, capacity: usize) -> FixedBumpVec<'_, T>
pub fn alloc_fixed_vec<T>(&self, capacity: usize) -> FixedBumpVec<'_, T>
Allocate a FixedBumpVec with the given capacity.
§Panics
Panics if the allocation fails.
§Examples
let mut values = bump.alloc_fixed_vec(3);
values.push(1);
values.push(2);
values.push(3);
assert_eq!(values, [1, 2, 3])Sourcepub fn alloc_fixed_string(&self, capacity: usize) -> FixedBumpString<'_>
pub fn alloc_fixed_string(&self, capacity: usize) -> FixedBumpString<'_>
Allocate a FixedBumpString with the given capacity in bytes.
§Panics
Panics if the allocation fails.
§Examples
let mut string = bump.alloc_fixed_string(12);
string.push_str("Hello");
string.push_str(" world!");
assert_eq!(string, "Hello world!");Sourcepub fn alloc_layout(&self, layout: Layout) -> NonNull<u8>
pub fn alloc_layout(&self, layout: Layout) -> NonNull<u8>
Sourcepub fn reserve_bytes(&self, additional: usize)
pub fn reserve_bytes(&self, additional: usize)
Reserves capacity for at least additional more bytes to be bump allocated.
The bump allocator may reserve more space to avoid frequent reallocations.
After calling reserve_bytes, self.stats().remaining() will be greater than or equal to
additional. Does nothing if the capacity is already sufficient.
§Panics
Panics if the allocation fails.
§Examples
let bump: Bump = Bump::new();
assert!(bump.stats().capacity() < 4096);
bump.reserve_bytes(4096);
assert!(bump.stats().capacity() >= 4096);Sourcepub fn try_alloc<T>(&self, value: T) -> Result<BumpBox<'_, T>, AllocError>
pub fn try_alloc<T>(&self, value: T) -> Result<BumpBox<'_, T>, AllocError>
Sourcepub fn try_alloc_with<T>(
&self,
f: impl FnOnce() -> T,
) -> Result<BumpBox<'_, T>, AllocError>
pub fn try_alloc_with<T>( &self, f: impl FnOnce() -> T, ) -> Result<BumpBox<'_, T>, AllocError>
Pre-allocate space for an object. Once space is allocated f will be called to create the value to be put at that place.
In some situations this can help the compiler realize that T can be constructed at the allocated space instead of having to copy it over.
§Errors
Errors if the allocation fails.
§Examples
let allocated = bump.try_alloc_with(|| 123)?;
assert_eq!(allocated, 123);Sourcepub fn try_alloc_default<T: Default>(
&self,
) -> Result<BumpBox<'_, T>, AllocError>
pub fn try_alloc_default<T: Default>( &self, ) -> Result<BumpBox<'_, T>, AllocError>
Allocate an object with its default value.
This is equivalent to try_alloc_with(T::default).
§Errors
Errors if the allocation fails.
§Examples
let allocated = bump.try_alloc_default()?;
assert_eq!(allocated, 0);Sourcepub fn try_alloc_slice_copy<T: Copy>(
&self,
slice: &[T],
) -> Result<BumpBox<'_, [T]>, AllocError>
pub fn try_alloc_slice_copy<T: Copy>( &self, slice: &[T], ) -> Result<BumpBox<'_, [T]>, AllocError>
Sourcepub fn try_alloc_slice_clone<T: Clone>(
&self,
slice: &[T],
) -> Result<BumpBox<'_, [T]>, AllocError>
pub fn try_alloc_slice_clone<T: Clone>( &self, slice: &[T], ) -> Result<BumpBox<'_, [T]>, AllocError>
Sourcepub fn try_alloc_slice_fill<T: Clone>(
&self,
len: usize,
value: T,
) -> Result<BumpBox<'_, [T]>, AllocError>
pub fn try_alloc_slice_fill<T: Clone>( &self, len: usize, value: T, ) -> Result<BumpBox<'_, [T]>, AllocError>
Sourcepub fn try_alloc_slice_fill_with<T>(
&self,
len: usize,
f: impl FnMut() -> T,
) -> Result<BumpBox<'_, [T]>, AllocError>
pub fn try_alloc_slice_fill_with<T>( &self, len: usize, f: impl FnMut() -> T, ) -> Result<BumpBox<'_, [T]>, AllocError>
Allocates a slice by fill it with elements returned by calling a closure repeatedly.
This method uses a closure to create new values. If you’d rather
Clone a given value, use try_alloc_slice_fill. If you want to use the Default
trait to generate values, you can pass Default::default as the
argument.
§Errors
Errors if the allocation fails.
§Examples
let allocated = bump.try_alloc_slice_fill_with::<i32>(3, Default::default)?;
assert_eq!(allocated, [0, 0, 0]);Sourcepub fn try_alloc_str(&self, src: &str) -> Result<BumpBox<'_, str>, AllocError>
pub fn try_alloc_str(&self, src: &str) -> Result<BumpBox<'_, str>, AllocError>
Sourcepub fn try_alloc_fmt(
&self,
args: Arguments<'_>,
) -> Result<BumpBox<'_, str>, AllocError>
pub fn try_alloc_fmt( &self, args: Arguments<'_>, ) -> Result<BumpBox<'_, str>, AllocError>
Allocate a str from format arguments.
If you have a &mut self you can use try_alloc_fmt_mut instead for better performance.
§Errors
Errors if the allocation fails.
Errors if a formatting trait implementation returned an error.
§Examples
let one = 1;
let two = 2;
let string = bump.try_alloc_fmt(format_args!("{one} + {two} = {}", one + two))?;
assert_eq!(string, "1 + 2 = 3");Sourcepub fn try_alloc_fmt_mut(
&mut self,
args: Arguments<'_>,
) -> Result<BumpBox<'_, str>, AllocError>
pub fn try_alloc_fmt_mut( &mut self, args: Arguments<'_>, ) -> Result<BumpBox<'_, str>, AllocError>
Allocate a str from format arguments.
This function is designed as a performance improvement over try_alloc_fmt. By taking self as &mut, it can use the entire remaining chunk space as the capacity for its string buffer. As a result, the string buffer rarely needs to grow.
§Errors
Errors if the allocation fails.
Errors if a formatting trait implementation returned an error.
§Examples
let one = 1;
let two = 2;
let string = bump.try_alloc_fmt_mut(format_args!("{one} + {two} = {}", one + two))?;
assert_eq!(string, "1 + 2 = 3");Sourcepub fn try_alloc_cstr(&self, src: &CStr) -> Result<&CStr, AllocError>
pub fn try_alloc_cstr(&self, src: &CStr) -> Result<&CStr, AllocError>
Sourcepub fn try_alloc_cstr_from_str(&self, src: &str) -> Result<&CStr, AllocError>
pub fn try_alloc_cstr_from_str(&self, src: &str) -> Result<&CStr, AllocError>
Allocate a CStr from a str.
If src contains a '\0' then the CStr will stop there.
§Errors
Errors if the allocation fails.
§Examples
let allocated = bump.try_alloc_cstr_from_str("Hello world!")?;
assert_eq!(allocated, c"Hello world!");
let allocated = bump.try_alloc_cstr_from_str("abc\0def")?;
assert_eq!(allocated, c"abc");Sourcepub fn try_alloc_cstr_fmt(
&self,
args: Arguments<'_>,
) -> Result<&CStr, AllocError>
pub fn try_alloc_cstr_fmt( &self, args: Arguments<'_>, ) -> Result<&CStr, AllocError>
Allocate a CStr from format arguments.
If the string contains a '\0' then the CStr will stop there.
If you have a &mut self you can use try_alloc_cstr_fmt_mut instead for better performance.
§Errors
Errors if the allocation fails.
Errors if a formatting trait implementation returned an error.
§Examples
let one = 1;
let two = 2;
let string = bump.try_alloc_cstr_fmt(format_args!("{one} + {two} = {}", one + two))?;
assert_eq!(string, c"1 + 2 = 3");
let one = bump.try_alloc_cstr_fmt(format_args!("{one}\0{two}"))?;
assert_eq!(one, c"1");Sourcepub fn try_alloc_cstr_fmt_mut(
&mut self,
args: Arguments<'_>,
) -> Result<&CStr, AllocError>
pub fn try_alloc_cstr_fmt_mut( &mut self, args: Arguments<'_>, ) -> Result<&CStr, AllocError>
Allocate a CStr from format arguments.
If the string contains a '\0' then the CStr will stop there.
This function is designed as a performance improvement over try_alloc_cstr_fmt. By taking self as &mut, it can use the entire remaining chunk space as the capacity for its string buffer. As a result, the string buffer rarely needs to grow.
§Errors
Errors if the allocation fails.
Errors if a formatting trait implementation returned an error.
§Examples
let one = 1;
let two = 2;
let string = bump.try_alloc_cstr_fmt_mut(format_args!("{one} + {two} = {}", one + two))?;
assert_eq!(string, c"1 + 2 = 3");
let one = bump.try_alloc_cstr_fmt_mut(format_args!("{one}\0{two}"))?;
assert_eq!(one, c"1");Sourcepub fn try_alloc_iter<T>(
&self,
iter: impl IntoIterator<Item = T>,
) -> Result<BumpBox<'_, [T]>, AllocError>
pub fn try_alloc_iter<T>( &self, iter: impl IntoIterator<Item = T>, ) -> Result<BumpBox<'_, [T]>, AllocError>
Allocate elements of an iterator into a slice.
If you have an impl ExactSizeIterator then you can use try_alloc_iter_exact instead for better performance.
If iter is not an ExactSizeIterator but you have a &mut self you can still get somewhat better performance by using try_alloc_iter_mut.
§Errors
Errors if the allocation fails.
§Examples
let slice = bump.try_alloc_iter([1, 2, 3])?;
assert_eq!(slice, [1, 2, 3]);Sourcepub fn try_alloc_iter_exact<T, I>(
&self,
iter: impl IntoIterator<Item = T, IntoIter = I>,
) -> Result<BumpBox<'_, [T]>, AllocError>where
I: ExactSizeIterator<Item = T>,
pub fn try_alloc_iter_exact<T, I>(
&self,
iter: impl IntoIterator<Item = T, IntoIter = I>,
) -> Result<BumpBox<'_, [T]>, AllocError>where
I: ExactSizeIterator<Item = T>,
Sourcepub fn try_alloc_iter_mut<T>(
&mut self,
iter: impl IntoIterator<Item = T>,
) -> Result<BumpBox<'_, [T]>, AllocError>
pub fn try_alloc_iter_mut<T>( &mut self, iter: impl IntoIterator<Item = T>, ) -> Result<BumpBox<'_, [T]>, AllocError>
Allocate elements of an iterator into a slice.
This function is designed as a performance improvement over try_alloc_iter. By taking self as &mut, it can use the entire remaining chunk space as the capacity for its vector. As a result, the vector rarely needs to grow.
When bumping downwards, prefer try_alloc_iter_mut_rev instead.
§Errors
Errors if the allocation fails.
§Examples
let slice = bump.try_alloc_iter_mut([1, 2, 3])?;
assert_eq!(slice, [1, 2, 3]);Sourcepub fn try_alloc_iter_mut_rev<T>(
&mut self,
iter: impl IntoIterator<Item = T>,
) -> Result<BumpBox<'_, [T]>, AllocError>
pub fn try_alloc_iter_mut_rev<T>( &mut self, iter: impl IntoIterator<Item = T>, ) -> Result<BumpBox<'_, [T]>, AllocError>
Allocate elements of an iterator into a slice in reverse order.
Compared to try_alloc_iter_mut this function is more performant
for downwards bumping allocators as the allocation for the vector can be shrunk in place
without any ptr::copy.
The reverse is true when upwards allocating. In that case it’s better to use try_alloc_iter_mut to prevent
the ptr::copy.
§Errors
Errors if the allocation fails.
§Examples
let slice = bump.try_alloc_iter_mut_rev([1, 2, 3])?;
assert_eq!(slice, [3, 2, 1]);Sourcepub fn try_alloc_uninit<T>(
&self,
) -> Result<BumpBox<'_, MaybeUninit<T>>, AllocError>
pub fn try_alloc_uninit<T>( &self, ) -> Result<BumpBox<'_, MaybeUninit<T>>, AllocError>
Allocate an unitialized object.
You can safely initialize the object with init or unsafely with assume_init.
§Errors
Errors if the allocation fails.
§Examples
Safely:
let five = bump.try_alloc_uninit()?;
let five = five.init(5);
assert_eq!(*five, 5);Unsafely:
let mut five = bump.try_alloc_uninit()?;
let five = unsafe {
five.write(5);
five.assume_init()
};
assert_eq!(*five, 5);Sourcepub fn try_alloc_uninit_slice<T>(
&self,
len: usize,
) -> Result<BumpBox<'_, [MaybeUninit<T>]>, AllocError>
pub fn try_alloc_uninit_slice<T>( &self, len: usize, ) -> Result<BumpBox<'_, [MaybeUninit<T>]>, AllocError>
Allocate an unitialized object slice.
You can safely initialize the object with
init_fill,
init_fill_with,
init_copy,
init_clone or unsafely with
assume_init.
§Errors
Errors if the allocation fails.
§Examples
Safely:
let values = bump.try_alloc_uninit_slice(3)?;
let values = values.init_copy(&[1, 2, 3]);
assert_eq!(values, [1, 2, 3]);Unsafely:
let mut values = bump.try_alloc_uninit_slice(3)?;
let values = unsafe {
values[0].write(1);
values[1].write(2);
values[2].write(3);
values.assume_init()
};
assert_eq!(values, [1, 2, 3]);Sourcepub fn try_alloc_uninit_slice_for<T>(
&self,
slice: &[T],
) -> Result<BumpBox<'_, [MaybeUninit<T>]>, AllocError>
pub fn try_alloc_uninit_slice_for<T>( &self, slice: &[T], ) -> Result<BumpBox<'_, [MaybeUninit<T>]>, AllocError>
Allocate an unitialized object slice.
You can safely initialize the object with
init_fill,
init_fill_with,
init_copy,
init_clone or unsafely with
assume_init.
This is just like try_alloc_uninit_slice but uses a slice to provide the len.
This avoids a check for a valid layout. The elements of slice are irrelevant.
§Errors
Errors if the allocation fails.
§Examples
let slice = &[1, 2, 3];
let other_slice = bump.try_alloc_uninit_slice_for(slice)?;
assert_eq!(other_slice.len(), 3);Sourcepub fn try_alloc_fixed_vec<T>(
&self,
capacity: usize,
) -> Result<FixedBumpVec<'_, T>, AllocError>
pub fn try_alloc_fixed_vec<T>( &self, capacity: usize, ) -> Result<FixedBumpVec<'_, T>, AllocError>
Allocate a FixedBumpVec with the given capacity.
§Errors
Errors if the allocation fails.
§Examples
let mut values = bump.try_alloc_fixed_vec(3)?;
values.push(1);
values.push(2);
values.push(3);
assert_eq!(values, [1, 2, 3]);Sourcepub fn try_alloc_fixed_string(
&self,
capacity: usize,
) -> Result<FixedBumpString<'_>, AllocError>
pub fn try_alloc_fixed_string( &self, capacity: usize, ) -> Result<FixedBumpString<'_>, AllocError>
Allocate a FixedBumpString with the given capacity in bytes.
§Errors
Errors if the allocation fails.
§Examples
let mut string = bump.try_alloc_fixed_string(12)?;
string.push_str("Hello");
string.push_str(" world!");
assert_eq!(string, "Hello world!");Sourcepub fn try_alloc_layout(
&self,
layout: Layout,
) -> Result<NonNull<u8>, AllocError>
pub fn try_alloc_layout( &self, layout: Layout, ) -> Result<NonNull<u8>, AllocError>
Sourcepub fn try_reserve_bytes(&self, additional: usize) -> Result<(), AllocError>
pub fn try_reserve_bytes(&self, additional: usize) -> Result<(), AllocError>
Reserves capacity for at least additional more bytes to be bump allocated.
The bump allocator may reserve more space to avoid frequent reallocations.
After calling reserve_bytes, self.stats().remaining() will be greater than or equal to
additional. Does nothing if the capacity is already sufficient.
§Errors
Errors if the allocation fails.
§Examples
let bump: Bump = Bump::try_new()?;
assert!(bump.stats().capacity() < 4096);
bump.try_reserve_bytes(4096)?;
assert!(bump.stats().capacity() >= 4096);Source§impl<A, const MIN_ALIGN: usize, const UP: bool> Bump<A, MIN_ALIGN, UP>
impl<A, const MIN_ALIGN: usize, const UP: bool> Bump<A, MIN_ALIGN, UP>
Functions to allocate. Available as fallible or infallible.
These require a guaranteed allocated bump allocator.
Sourcepub fn alloc_try_with<T, E>(
&self,
f: impl FnOnce() -> Result<T, E>,
) -> Result<BumpBox<'_, T>, E>
pub fn alloc_try_with<T, E>( &self, f: impl FnOnce() -> Result<T, E>, ) -> Result<BumpBox<'_, T>, E>
Allocates the result of f in the bump allocator, then moves E out of it and deallocates the space it took up.
This can be more performant than allocating T after the fact, as Result<T, E> may be constructed in the bump allocators memory instead of on the stack and then copied over.
There is also alloc_try_with_mut, optimized for a mutable reference.
§Panics
Panics if the allocation fails.
§Examples
let result = bump.alloc_try_with(|| -> Result<i32, i32> { Ok(123) });
assert_eq!(result.unwrap(), 123);
assert_eq!(bump.stats().allocated(), offset_of!(Result<i32, i32>, Ok.0) + size_of::<i32>());let result = bump.alloc_try_with(|| -> Result<i32, i32> { Err(123) });
assert_eq!(result.unwrap_err(), 123);
assert_eq!(bump.stats().allocated(), 0);Sourcepub fn alloc_try_with_mut<T, E>(
&mut self,
f: impl FnOnce() -> Result<T, E>,
) -> Result<BumpBox<'_, T>, E>
pub fn alloc_try_with_mut<T, E>( &mut self, f: impl FnOnce() -> Result<T, E>, ) -> Result<BumpBox<'_, T>, E>
Allocates the result of f in the bump allocator, then moves E out of it and deallocates the space it took up.
This can be more performant than allocating T after the fact, as Result<T, E> may be constructed in the bump allocators memory instead of on the stack and then copied over.
This is just like alloc_try_with, but optimized for a mutable reference.
§Panics
Panics if the allocation fails.
§Examples
let result = bump.alloc_try_with_mut(|| -> Result<i32, i32> { Ok(123) });
assert_eq!(result.unwrap(), 123);
assert_eq!(bump.stats().allocated(), offset_of!(Result<i32, i32>, Ok.0) + size_of::<i32>());let result = bump.alloc_try_with_mut(|| -> Result<i32, i32> { Err(123) });
assert_eq!(result.unwrap_err(), 123);
assert_eq!(bump.stats().allocated(), 0);Sourcepub fn try_alloc_try_with<T, E>(
&self,
f: impl FnOnce() -> Result<T, E>,
) -> Result<Result<BumpBox<'_, T>, E>, AllocError>
pub fn try_alloc_try_with<T, E>( &self, f: impl FnOnce() -> Result<T, E>, ) -> Result<Result<BumpBox<'_, T>, E>, AllocError>
Allocates the result of f in the bump allocator, then moves E out of it and deallocates the space it took up.
This can be more performant than allocating T after the fact, as Result<T, E> may be constructed in the bump allocators memory instead of on the stack and then copied over.
There is also try_alloc_try_with_mut, optimized for a mutable reference.
§Errors
Errors if the allocation fails.
§Examples
let result = bump.try_alloc_try_with(|| -> Result<i32, i32> { Ok(123) })?;
assert_eq!(result.unwrap(), 123);
assert_eq!(bump.stats().allocated(), offset_of!(Result<i32, i32>, Ok.0) + size_of::<i32>());let result = bump.try_alloc_try_with(|| -> Result<i32, i32> { Err(123) })?;
assert_eq!(result.unwrap_err(), 123);
assert_eq!(bump.stats().allocated(), 0);Sourcepub fn try_alloc_try_with_mut<T, E>(
&mut self,
f: impl FnOnce() -> Result<T, E>,
) -> Result<Result<BumpBox<'_, T>, E>, AllocError>
pub fn try_alloc_try_with_mut<T, E>( &mut self, f: impl FnOnce() -> Result<T, E>, ) -> Result<Result<BumpBox<'_, T>, E>, AllocError>
Allocates the result of f in the bump allocator, then moves E out of it and deallocates the space it took up.
This can be more performant than allocating T after the fact, as Result<T, E> may be constructed in the bump allocators memory instead of on the stack and then copied over.
This is just like try_alloc_try_with, but optimized for a mutable reference.
§Errors
Errors if the allocation fails.
§Examples
let result = bump.try_alloc_try_with_mut(|| -> Result<i32, i32> { Ok(123) })?;
assert_eq!(result.unwrap(), 123);
assert_eq!(bump.stats().allocated(), offset_of!(Result<i32, i32>, Ok.0) + size_of::<i32>());let result = bump.try_alloc_try_with_mut(|| -> Result<i32, i32> { Err(123) })?;
assert_eq!(result.unwrap_err(), 123);
assert_eq!(bump.stats().allocated(), 0);Trait Implementations§
Source§impl<A, const MIN_ALIGN: usize, const UP: bool, const GUARANTEED_ALLOCATED: bool> Allocator for &mut Bump<A, MIN_ALIGN, UP, GUARANTEED_ALLOCATED>where
MinimumAlignment<MIN_ALIGN>: SupportedMinimumAlignment,
A: BaseAllocator<GUARANTEED_ALLOCATED>,
impl<A, const MIN_ALIGN: usize, const UP: bool, const GUARANTEED_ALLOCATED: bool> Allocator for &mut Bump<A, MIN_ALIGN, UP, GUARANTEED_ALLOCATED>where
MinimumAlignment<MIN_ALIGN>: SupportedMinimumAlignment,
A: BaseAllocator<GUARANTEED_ALLOCATED>,
Source§fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError>
fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError>
allocator_api)Source§unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout)
unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout)
allocator_api)ptr. Read moreSource§unsafe fn grow(
&self,
ptr: NonNull<u8>,
old_layout: Layout,
new_layout: Layout,
) -> Result<NonNull<[u8]>, AllocError>
unsafe fn grow( &self, ptr: NonNull<u8>, old_layout: Layout, new_layout: Layout, ) -> Result<NonNull<[u8]>, AllocError>
allocator_api)Source§unsafe fn grow_zeroed(
&self,
ptr: NonNull<u8>,
old_layout: Layout,
new_layout: Layout,
) -> Result<NonNull<[u8]>, AllocError>
unsafe fn grow_zeroed( &self, ptr: NonNull<u8>, old_layout: Layout, new_layout: Layout, ) -> Result<NonNull<[u8]>, AllocError>
allocator_api)grow, but also ensures that the new contents are set to zero before being
returned. Read moreSource§unsafe fn shrink(
&self,
ptr: NonNull<u8>,
old_layout: Layout,
new_layout: Layout,
) -> Result<NonNull<[u8]>, AllocError>
unsafe fn shrink( &self, ptr: NonNull<u8>, old_layout: Layout, new_layout: Layout, ) -> Result<NonNull<[u8]>, AllocError>
allocator_api)Source§fn allocate_zeroed(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError>
fn allocate_zeroed(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError>
allocator_api)allocate, but also ensures that the returned memory is zero-initialized. Read moreSource§impl<A, const MIN_ALIGN: usize, const UP: bool, const GUARANTEED_ALLOCATED: bool> Allocator for Bump<A, MIN_ALIGN, UP, GUARANTEED_ALLOCATED>where
MinimumAlignment<MIN_ALIGN>: SupportedMinimumAlignment,
A: BaseAllocator<GUARANTEED_ALLOCATED>,
impl<A, const MIN_ALIGN: usize, const UP: bool, const GUARANTEED_ALLOCATED: bool> Allocator for Bump<A, MIN_ALIGN, UP, GUARANTEED_ALLOCATED>where
MinimumAlignment<MIN_ALIGN>: SupportedMinimumAlignment,
A: BaseAllocator<GUARANTEED_ALLOCATED>,
Source§fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError>
fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError>
allocator_api)Source§unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout)
unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout)
allocator_api)ptr. Read moreSource§unsafe fn grow(
&self,
ptr: NonNull<u8>,
old_layout: Layout,
new_layout: Layout,
) -> Result<NonNull<[u8]>, AllocError>
unsafe fn grow( &self, ptr: NonNull<u8>, old_layout: Layout, new_layout: Layout, ) -> Result<NonNull<[u8]>, AllocError>
allocator_api)Source§unsafe fn grow_zeroed(
&self,
ptr: NonNull<u8>,
old_layout: Layout,
new_layout: Layout,
) -> Result<NonNull<[u8]>, AllocError>
unsafe fn grow_zeroed( &self, ptr: NonNull<u8>, old_layout: Layout, new_layout: Layout, ) -> Result<NonNull<[u8]>, AllocError>
allocator_api)grow, but also ensures that the new contents are set to zero before being
returned. Read moreSource§unsafe fn shrink(
&self,
ptr: NonNull<u8>,
old_layout: Layout,
new_layout: Layout,
) -> Result<NonNull<[u8]>, AllocError>
unsafe fn shrink( &self, ptr: NonNull<u8>, old_layout: Layout, new_layout: Layout, ) -> Result<NonNull<[u8]>, AllocError>
allocator_api)Source§fn allocate_zeroed(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError>
fn allocate_zeroed(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError>
allocator_api)allocate, but also ensures that the returned memory is zero-initialized. Read more