rune_alloc/
error.rs

1//! Error types used by rune alloc.
2
3use core::fmt;
4
5use crate::alloc::AllocError;
6
7/// An error type returned when a custom error is available alongside an allocation error.
8#[derive(Debug)]
9pub enum CustomError<E> {
10    /// Custom error being returned.
11    Custom(E),
12    /// Try reserve error being returned.
13    Error(Error),
14}
15
16impl<E> From<Error> for CustomError<E> {
17    fn from(error: Error) -> Self {
18        CustomError::Error(error)
19    }
20}
21
22impl<E> From<AllocError> for CustomError<E> {
23    fn from(error: AllocError) -> Self {
24        CustomError::Error(Error::from(error))
25    }
26}
27
28/// The error type for methods which allocate or reserve.
29#[derive(Debug, Clone, Copy, PartialEq, Eq)]
30#[non_exhaustive]
31pub enum Error {
32    /// Error due to the computed capacity exceeding the collection's maximum
33    /// (usually `isize::MAX` bytes).
34    #[doc(hidden)]
35    CapacityOverflow,
36
37    /// Error when computing layout.
38    #[doc(hidden)]
39    LayoutError,
40
41    /// Error during internal formatting.
42    #[doc(hidden)]
43    FormatError,
44
45    /// The memory allocator returned an error
46    #[doc(hidden)]
47    AllocError {
48        /// The layout of the allocation request that failed.
49        error: AllocError,
50    },
51}
52
53impl From<AllocError> for Error {
54    #[inline]
55    fn from(error: AllocError) -> Self {
56        Error::AllocError { error }
57    }
58}
59
60impl fmt::Display for Error {
61    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
62        match self {
63            Error::CapacityOverflow => write!(f, "Capacity overflow"),
64            Error::LayoutError => write!(f, "Layout error"),
65            Error::FormatError => write!(f, "Format error"),
66            Error::AllocError { error } => error.fmt(f),
67        }
68    }
69}
70
71#[cfg(feature = "std")]
72impl ::std::error::Error for Error {
73    fn source(&self) -> Option<&(dyn ::std::error::Error + 'static)> {
74        match self {
75            Error::AllocError { error } => Some(error),
76            _ => None,
77        }
78    }
79}