stack_arena/
error.rs

1use std::alloc::Layout;
2
3/// Error type for allocation failures.
4///
5/// This error is returned when an allocation operation fails, typically
6/// due to insufficient memory or other resource constraints.
7///
8/// # Examples
9///
10/// ```
11/// use stack_arena::{BufferArena, Allocator, AllocError};
12/// use std::alloc::Layout;
13///
14/// // Create a BufferArena with a small fixed size
15/// let mut arena = BufferArena::with_capacity(4096);
16///
17/// // First allocation succeeds
18/// let layout1 = Layout::from_size_align(4096, 1).unwrap();
19/// let ptr1 = unsafe { arena.allocate(layout1) }.unwrap();
20///
21/// // Second allocation fails due to insufficient space
22/// let layout2 = Layout::from_size_align(1, 1).unwrap();
23/// let result = unsafe { arena.allocate(layout2) };
24/// assert!(result.is_err());
25/// assert!(matches!(result, Err(AllocError::CapacityExceeded { requested: 1, remaining: 0 })));
26/// ```
27///
28/// Note: Unlike `BufferArena`, the `StackArena` will automatically allocate new chunks
29/// when the current chunk is full, so it rarely returns allocation errors.
30///
31/// # Implementation
32///
33/// This error implements the standard `Error` and `Display` traits,
34/// allowing it to be used with error handling utilities like `Result`.
35#[derive(Debug, PartialEq, Eq)]
36pub enum AllocError {
37    OutOfMemory,
38    InvalidLayout(Layout),
39    CapacityExceeded { requested: usize, remaining: usize },
40}
41
42impl std::fmt::Display for AllocError {
43    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
44        match self {
45            AllocError::OutOfMemory => write!(f, "out of memory"),
46            AllocError::InvalidLayout(layout) => write!(f, "invalid layout: {layout:?}"),
47            AllocError::CapacityExceeded {
48                requested,
49                remaining,
50            } => write!(
51                f,
52                "capacity exceeded: requested={requested}, remaining={remaining}"
53            ),
54        }
55    }
56}
57
58impl std::error::Error for AllocError {}