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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#![feature(allocator_api)]
#![feature(alloc_error_hook)]
#![feature(try_reserve_kind)]
use std::alloc::Layout;
use std::collections::TryReserveError;
use std::error::Error;
use std::fmt;
mod sealed {
pub trait Sealed {}
}
mod oom;
mod vec_ext;
pub use crate::oom::catch_oom;
pub use crate::vec_ext::{VecAllocExt, VecExt};
#[derive(Copy, Clone)]
#[repr(transparent)]
pub struct AllocError(Layout);
impl AllocError {
#[must_use]
#[inline]
pub const fn new(layout: Layout) -> Self {
AllocError(layout)
}
#[must_use]
#[inline]
pub const fn layout(self) -> Layout {
self.0
}
}
impl fmt::Debug for AllocError {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("AllocError")
.field("size", &self.0.size())
.field("align", &self.0.align())
.finish()
}
}
impl fmt::Display for AllocError {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"failed to allocate memory by required layout {{size: {}, align: {}}}",
self.0.size(),
self.0.align()
)
}
}
impl Error for AllocError {}
impl From<TryReserveError> for AllocError {
#[inline]
fn from(e: TryReserveError) -> Self {
use std::collections::TryReserveErrorKind;
match e.kind() {
TryReserveErrorKind::AllocError { layout, .. } => AllocError::new(layout),
TryReserveErrorKind::CapacityOverflow => {
unreachable!("unexpected capacity overflow")
}
}
}
}