Skip to main content

BumpArena

Struct BumpArena 

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

A fixed‑capacity, single‑threaded bump allocator backed by lazy‑committed virtual memory.

BumpArena provides mutable slices of MaybeUninit<u8> that are logically uninitialised. The caller must initialise the memory before reading from it. The backing store is a reserved virtual‑memory region whose total capacity is set once at construction and never changes. Physical memory is committed on demand as the bump pointer advances, so the arena can be created with a very large capacity without immediately consuming physical memory.

§Memory commitment strategy

The arena uses incremental commitment: the initial physical footprint is tiny, and pages are committed in chunks as allocations request more memory. Committed memory is never decommitted until the entire arena is dropped. Raw bump allocations keep stable addresses, while allocator API resize operations may return a relocated block. This gives predictable performance and minimal upfront resource usage.

§Thread safety

BumpArena is !Send and !Sync – it contains a raw‑pointer marker that prevents the value from leaving the thread where it was created. The arena is therefore safe to use in single‑threaded contexts only.

§Examples

use core::alloc::Layout;

use linalloc::BumpArena;

let bump = BumpArena::new(1024);

// Allocate space for a `u64`.
let layout = Layout::new::<u64>();
let slice = bump.try_alloc_uninit(layout).expect("out of memory");
let ptr = slice.as_mut_ptr().cast::<u64>();
unsafe { ptr.write(42) };
let val = unsafe { &*ptr };
assert_eq!(*val, 42);

// Memory is freed when `bump` goes out of scope.

Implementations§

Source§

impl BumpArena

Source

pub fn new(capacity: usize) -> Self

Creates a bump allocator that can grow up to capacity bytes.

The memory is reserved but not committed – physical pages are allocated only when needed, as the bump pointer moves forward. If capacity is zero, the arena is empty and will reject all non‑zero allocations.

§Panics

Panics if the operating system cannot reserve the requested address range. A zero‑capacity arena never panics.

§Examples
use linalloc::BumpArena;

let arena = BumpArena::new(1024);
assert_eq!(arena.capacity(), 1024);
assert_eq!(arena.used(), 0);
Source

pub fn try_new(capacity: usize) -> Result<Self, i32>

Like new, but with no panic behaviour.

§Errors

Returns OS error code if reservation fails.

Source

pub fn alloc_uninit(&self, layout: Layout) -> &mut [MaybeUninit<u8>]

Allocates a mutable slice of MaybeUninit<u8> that satisfies layout, panicking if the allocation fails.

See BumpArena::try_alloc_uninit for fallible allocation semantics.

§Panics

Panics if the arena does not have enough free space after accounting for the requested size and alignment, or if a required memory commit fails.

Source

pub fn try_alloc_uninit(&self, layout: Layout) -> Option<&mut [MaybeUninit<u8>]>

Allocates a mutable slice of MaybeUninit<u8> that satisfies layout.

The returned memory is logically uninitialised – it must be initialised before any reads are performed (for example, using core::ptr::write).

The slice borrows the arena immutably (&self), so the arena cannot be dropped or moved while the slice is alive. This guarantees that multiple allocations can coexist without aliasing.

A zero‑size allocation returns a well‑aligned dangling slice and does not advance the bump pointer.

§Returns

None if the arena does not have enough free space after accounting for the requested size and alignment, or if a required memory commit fails.

Source

pub fn last_os_error_code(&self) -> Option<i32>

Returns the OS error code from the last failed allocation or commit operation, if any.

The returned value is the raw platform‑specific error code:

  • On Unix: the errno value (positive integer).
  • On Windows: the GetLastError code.

Returns None if no OS-backed reserve or commit failure has been recorded for this arena.

§Semantics

This method behaves analogously to std::io::Error::last_os_error at the point of the failed internal system call. The error code is stable until the next failure overwrites it.

Source

pub unsafe fn reset(&self)

Resets the bump pointer to the beginning, reusing already‑committed memory.

§Safety

All previously returned slices must no longer be in use. This method does not run any destructors – the caller is responsible for dropping all values placed in the arena before calling reset.

Source

pub fn capacity(&self) -> usize

Returns the total capacity of the backing memory, in bytes.

This is the value passed to new and never changes.

Source

pub fn used(&self) -> usize

Returns the number of bytes that have been allocated so far.

Trait Implementations§

Source§

impl Allocator for BumpArena

Available on crate feature nightly only.
Source§

fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError>

🔬This is a nightly-only experimental API. (allocator_api)
Attempts to allocate a block of memory. Read more
Source§

unsafe fn deallocate(&self, _ptr: NonNull<u8>, _layout: Layout)

🔬This is a nightly-only experimental API. (allocator_api)
Deallocates the memory referenced by ptr. Read more
Source§

unsafe fn grow( &self, ptr: NonNull<u8>, old_layout: Layout, new_layout: Layout, ) -> Result<NonNull<[u8]>, AllocError>

🔬This is a nightly-only experimental API. (allocator_api)
Attempts to extend the memory block. Read more
Source§

unsafe fn grow_zeroed( &self, ptr: NonNull<u8>, old_layout: Layout, new_layout: Layout, ) -> Result<NonNull<[u8]>, AllocError>

🔬This is a nightly-only experimental API. (allocator_api)
Behaves like grow, but also ensures that the new contents are set to zero before being returned. Read more
Source§

unsafe fn shrink( &self, ptr: NonNull<u8>, old_layout: Layout, new_layout: Layout, ) -> Result<NonNull<[u8]>, AllocError>

🔬This is a nightly-only experimental API. (allocator_api)
Attempts to shrink the memory block. Read more
Source§

fn allocate_zeroed(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError>

🔬This is a nightly-only experimental API. (allocator_api)
Behaves like allocate, but also ensures that the returned memory is zero-initialized. Read more
Source§

fn by_ref(&self) -> &Self
where Self: Sized,

🔬This is a nightly-only experimental API. (allocator_api)
Creates a “by reference” adapter for this instance of Allocator. Read more
Source§

impl Debug for BumpArena

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Drop for BumpArena

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more
Source§

fn pin_drop(self: Pin<&mut Self>)

🔬This is a nightly-only experimental API. (pin_ergonomics)
Execute the destructor for this type, but different to Drop::drop, it requires self to be pinned. Read more
Source§

impl UninitAllocator for BumpArena

Source§

fn try_alloc_uninit(&self, layout: Layout) -> Option<&mut [MaybeUninit<u8>]>

Allocates a mutable slice of core::mem::MaybeUninit that satisfies layout. Read more

Auto Trait Implementations§

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> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

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, 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.