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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
use std::alloc::Layout;
use std::collections::TryReserveError;
use std::error::Error;
use std::fmt;
use std::panic::{PanicInfo, UnwindSafe};
use std::sync::atomic::{AtomicBool, Ordering};
#[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")
}
}
}
}
fn alloc_error_hook(layout: Layout) {
std::panic::panic_any(AllocError(layout))
}
type PanicHook = Box<dyn Fn(&PanicInfo<'_>) + 'static + Sync + Send>;
fn panic_hook(panic_info: &PanicInfo<'_>) {
if !panic_info.payload().is::<AllocError>() {
std::process::abort();
}
}
#[inline]
pub fn catch_alloc_error<F: FnOnce() -> R + UnwindSafe, R>(f: F) -> Result<R, AllocError> {
static SET_HOOK: AtomicBool = AtomicBool::new(false);
if !SET_HOOK.load(Ordering::Acquire) {
let hook: PanicHook =
Box::try_new(panic_hook).map_err(|_| AllocError::new(Layout::new::<PanicHook>()))?;
std::panic::set_hook(hook);
std::alloc::set_alloc_error_hook(alloc_error_hook);
SET_HOOK.store(true, Ordering::Release);
}
let result = std::panic::catch_unwind(f);
match result {
Ok(r) => Ok(r),
Err(e) => match e.downcast_ref::<AllocError>() {
None => {
unreachable!()
}
Some(e) => Err(*e),
},
}
}