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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
use core::alloc::Layout as StdLayout;
use core::mem;
pub(crate) fn abort() -> ! {
struct Panic;
impl Drop for Panic {
fn drop(&mut self) {
panic!("aborting the process");
}
}
let _panic = Panic;
panic!("aborting the process");
}
#[inline]
pub(crate) fn abort_on_panic<T>(f: impl FnOnce() -> T) -> T {
struct Bomb;
impl Drop for Bomb {
fn drop(&mut self) {
abort();
}
}
let bomb = Bomb;
let t = f();
mem::forget(bomb);
t
}
#[derive(Clone, Copy, Debug)]
pub(crate) struct Layout {
size: usize,
align: usize,
}
impl Layout {
#[inline]
pub(crate) const fn from_size_align(size: usize, align: usize) -> Self {
Self { size, align }
}
#[inline]
pub(crate) const fn new<T>() -> Self {
Self::from_size_align(mem::size_of::<T>(), mem::align_of::<T>())
}
#[inline]
pub(crate) const unsafe fn into_std(self) -> StdLayout {
StdLayout::from_size_align_unchecked(self.size, self.align)
}
#[inline]
pub(crate) const fn align(&self) -> usize {
self.align
}
#[inline]
pub(crate) const fn size(&self) -> usize {
self.size
}
#[inline]
pub(crate) const fn extend(self, other: Layout) -> Option<(Layout, usize)> {
let new_align = max(self.align(), other.align());
let pad = self.padding_needed_for(other.align());
let offset = leap!(self.size().checked_add(pad));
let new_size = leap!(offset.checked_add(other.size()));
if !new_align.is_power_of_two() || new_size > core::usize::MAX - (new_align - 1) {
return None;
}
let layout = Layout::from_size_align(new_size, new_align);
Some((layout, offset))
}
#[inline]
pub(crate) const fn padding_needed_for(self, align: usize) -> usize {
let len = self.size();
let len_rounded_up = len.wrapping_add(align).wrapping_sub(1) & !align.wrapping_sub(1);
len_rounded_up.wrapping_sub(len)
}
}
#[inline]
pub(crate) const fn max(left: usize, right: usize) -> usize {
if left > right {
left
} else {
right
}
}