1use core::alloc::Layout;
2use core::mem;
34/// Aborts the process.
5///
6/// To abort, this function simply panics while panicking.
7pub(crate) fn abort() -> ! {
8struct Panic;
910impl Drop for Panic {
11fn drop(&mut self) {
12panic!("aborting the process");
13 }
14 }
1516let _panic = Panic;
17panic!("aborting the process");
18}
1920/// Calls a function and aborts if it panics.
21///
22/// This is useful in unsafe code where we can't recover from panics.
23#[inline]
24pub(crate) fn abort_on_panic<T>(f: impl FnOnce() -> T) -> T {
25struct Bomb;
2627impl Drop for Bomb {
28fn drop(&mut self) {
29 abort();
30 }
31 }
3233let bomb = Bomb;
34let t = f();
35 mem::forget(bomb);
36 t
37}
3839/// Returns the layout for `a` followed by `b` and the offset of `b`.
40///
41/// This function was adapted from the currently unstable `Layout::extend()`:
42/// https://doc.rust-lang.org/nightly/std/alloc/struct.Layout.html#method.extend
43#[inline]
44pub(crate) fn extend(a: Layout, b: Layout) -> (Layout, usize) {
45let new_align = a.align().max(b.align());
46let pad = padding_needed_for(a, b.align());
4748let offset = a.size().checked_add(pad).unwrap();
49let new_size = offset.checked_add(b.size()).unwrap();
5051let layout = Layout::from_size_align(new_size, new_align).unwrap();
52 (layout, offset)
53}
5455/// Returns the padding after `layout` that aligns the following address to `align`.
56///
57/// This function was adapted from the currently unstable `Layout::padding_needed_for()`:
58/// https://doc.rust-lang.org/nightly/std/alloc/struct.Layout.html#method.padding_needed_for
59#[inline]
60pub(crate) fn padding_needed_for(layout: Layout, align: usize) -> usize {
61let len = layout.size();
62let len_rounded_up = len.wrapping_add(align).wrapping_sub(1) & !align.wrapping_sub(1);
63 len_rounded_up.wrapping_sub(len)
64}