1use core::alloc::Layout as StdLayout;
2use core::mem;
3
4pub(crate) fn abort() -> ! {
8 struct Panic;
9
10 impl Drop for Panic {
11 fn drop(&mut self) {
12 panic!("aborting the process");
13 }
14 }
15
16 let _panic = Panic;
17 panic!("aborting the process");
18}
19
20#[inline]
24pub(crate) fn abort_on_panic<T>(f: impl FnOnce() -> T) -> T {
25 struct Bomb;
26
27 impl Drop for Bomb {
28 fn drop(&mut self) {
29 abort();
30 }
31 }
32
33 let bomb = Bomb;
34 let t = f();
35 mem::forget(bomb);
36 t
37}
38
39#[derive(Clone, Copy, Debug)]
42pub(crate) struct Layout {
43 size: usize,
44 align: usize,
45}
46
47impl Layout {
48 #[inline]
50 pub(crate) const fn from_size_align(size: usize, align: usize) -> Self {
51 Self { size, align }
52 }
53
54 #[inline]
56 pub(crate) const fn new<T>() -> Self {
57 Self::from_size_align(mem::size_of::<T>(), mem::align_of::<T>())
58 }
59
60 #[inline]
68 pub(crate) const unsafe fn into_std(self) -> StdLayout {
69 StdLayout::from_size_align_unchecked(self.size, self.align)
70 }
71
72 #[inline]
74 pub(crate) const fn align(&self) -> usize {
75 self.align
76 }
77
78 #[inline]
80 pub(crate) const fn size(&self) -> usize {
81 self.size
82 }
83
84 #[inline]
89 pub(crate) const fn extend(self, other: Layout) -> Option<(Layout, usize)> {
90 let new_align = max(self.align(), other.align());
91 let pad = self.padding_needed_for(other.align());
92
93 let offset = leap!(self.size().checked_add(pad));
94 let new_size = leap!(offset.checked_add(other.size()));
95
96 if !new_align.is_power_of_two() || new_size > isize::MAX as usize - (new_align - 1) {
101 return None;
102 }
103
104 let layout = Layout::from_size_align(new_size, new_align);
105 Some((layout, offset))
106 }
107
108 #[inline]
113 pub(crate) const fn padding_needed_for(self, align: usize) -> usize {
114 let len = self.size();
115 let len_rounded_up = len.wrapping_add(align).wrapping_sub(1) & !align.wrapping_sub(1);
116 len_rounded_up.wrapping_sub(len)
117 }
118}
119
120#[inline]
121pub(crate) const fn max(left: usize, right: usize) -> usize {
122 if left > right {
123 left
124 } else {
125 right
126 }
127}