stable_alloc_shim/
collections.rs

1use core::fmt::Display;
2use std_alloc::alloc::{Layout, LayoutError};
3
4/// The error type for `try_reserve` methods.
5#[derive(Clone, PartialEq, Eq, Debug)]
6pub struct TryReserveError {
7    kind: TryReserveErrorKind,
8}
9
10impl TryReserveError {
11    /// Details about the allocation that caused the error
12    #[inline]
13    #[must_use]
14    pub fn kind(&self) -> TryReserveErrorKind {
15        self.kind.clone()
16    }
17}
18
19/// Details of the allocation that caused a `TryReserveError`
20#[derive(Clone, PartialEq, Eq, Debug)]
21pub enum TryReserveErrorKind {
22    /// Error due to the computed capacity exceeding the collection's maximum
23    /// (usually `isize::MAX` bytes).
24    CapacityOverflow,
25
26    /// The memory allocator returned an error
27    AllocError {
28        /// The layout of allocation request that failed
29        layout: Layout,
30
31        #[doc(hidden)]
32        non_exhaustive: (),
33    },
34}
35
36impl From<TryReserveErrorKind> for TryReserveError {
37    #[inline]
38    fn from(kind: TryReserveErrorKind) -> Self {
39        Self { kind }
40    }
41}
42
43impl From<LayoutError> for TryReserveErrorKind {
44    /// Always evaluates to [`TryReserveErrorKind::CapacityOverflow`].
45    #[inline]
46    fn from(_: LayoutError) -> Self {
47        TryReserveErrorKind::CapacityOverflow
48    }
49}
50
51impl Display for TryReserveError {
52    fn fmt(
53        &self,
54        fmt: &mut core::fmt::Formatter<'_>,
55    ) -> core::result::Result<(), core::fmt::Error> {
56        fmt.write_str("memory allocation failed")?;
57        let reason = match self.kind {
58            TryReserveErrorKind::CapacityOverflow => {
59                " because the computed capacity exceeded the collection's maximum"
60            }
61            TryReserveErrorKind::AllocError { .. } => {
62                " because the memory allocator returned a error"
63            }
64        };
65        fmt.write_str(reason)
66    }
67}