Skip to main content

alloc_madvise/
alloc_result.rs

1//! Provides the [`AllocationError`] type.
2
3use std::alloc::LayoutError;
4use std::error::Error;
5use std::fmt::{Display, Formatter};
6
7/// Errors that can occur during memory allocation.
8#[derive(Debug, PartialEq)]
9pub enum AllocationError {
10    /// An allocation of zero bytes was attempted.
11    EmptyAllocation,
12    /// The generated memory layout was invalid.
13    InvalidAlignment(LayoutError),
14}
15
16impl Error for AllocationError {}
17
18impl From<LayoutError> for AllocationError {
19    fn from(value: LayoutError) -> Self {
20        Self::InvalidAlignment(value)
21    }
22}
23
24impl Display for AllocationError {
25    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
26        match self {
27            AllocationError::EmptyAllocation => f.write_str("zero-byte allocation"),
28            AllocationError::InvalidAlignment(e) => write!(f, "invalid memory layout: {e}"),
29        }
30    }
31}
32
33impl From<AllocationError> for AllocResult {
34    fn from(val: AllocationError) -> Self {
35        match val {
36            AllocationError::EmptyAllocation => AllocResult::Empty,
37            AllocationError::InvalidAlignment(_) => AllocResult::InvalidAlignment,
38        }
39    }
40}
41
42#[repr(u32)]
43#[derive(PartialEq, Eq, Copy, Clone, Debug)]
44pub enum AllocResult {
45    Ok = 0,
46    Empty = 1 << 0,
47    InvalidAlignment = 1 << 1,
48}
49
50impl From<u32> for AllocResult {
51    fn from(value: u32) -> Self {
52        match value {
53            0 => AllocResult::Ok,
54            1 => AllocResult::Empty,
55            2 => AllocResult::InvalidAlignment,
56            _ => panic!("Unknown AllocResult value: {value}"),
57        }
58    }
59}