1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
use std::alloc::LayoutError;
use std::error::Error;
use std::fmt::{Display, Formatter};

#[derive(Debug, PartialEq)]
pub enum AllocationError {
    /// An allocation of zero bytes was attempted.
    EmptyAllocation,
    /// The generated memory layout was invalid.
    InvalidAlignment(LayoutError),
}

impl Error for AllocationError {}

impl From<LayoutError> for AllocationError {
    fn from(value: LayoutError) -> Self {
        Self::InvalidAlignment(value)
    }
}

impl Display for AllocationError {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            AllocationError::EmptyAllocation => write!(f, "zero-byte allocation"),
            AllocationError::InvalidAlignment(e) => write!(f, "invalid memory layout: {e}"),
        }
    }
}

impl Into<AllocResult> for AllocationError {
    fn into(self) -> AllocResult {
        match self {
            AllocationError::EmptyAllocation => AllocResult::Empty,
            AllocationError::InvalidAlignment(_) => AllocResult::InvalidAlignment,
        }
    }
}

#[repr(u32)]
#[derive(PartialEq, Eq, Copy, Clone, Debug)]
pub enum AllocResult {
    Ok = 0,
    Empty = 1 << 0,
    InvalidAlignment = 1 << 1,
}

impl From<u32> for AllocResult {
    fn from(value: u32) -> Self {
        match value {
            0 => AllocResult::Ok,
            1 => AllocResult::Empty,
            2 => AllocResult::InvalidAlignment,
            _ => panic!(),
        }
    }
}