blob: cb9b65e33e233c7038d64562d512e4c544faebb5 [file] [log] [blame]
Stjepan Glavina921e8a02020-01-06 14:31:28 -06001use core::alloc::Layout;
2use core::mem;
Stjepan Glavina1479e862019-08-12 20:18:51 +02003
Stjepan Glavina7e7d19c2020-01-07 22:45:13 +01004/// Aborts the process.
5///
6/// To abort, this function simply panics while panicking.
7pub(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
Stjepan Glavina1479e862019-08-12 20:18:51 +020020/// 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 {
25 struct Bomb;
26
27 impl Drop for Bomb {
28 fn drop(&mut self) {
Stjepan Glavina7e7d19c2020-01-07 22:45:13 +010029 abort();
Stjepan Glavina1479e862019-08-12 20:18:51 +020030 }
31 }
32
33 let bomb = Bomb;
34 let t = f();
35 mem::forget(bomb);
36 t
37}
38
39/// 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) {
45 let new_align = a.align().max(b.align());
46 let pad = padding_needed_for(a, b.align());
47
48 let offset = a.size().checked_add(pad).unwrap();
49 let new_size = offset.checked_add(b.size()).unwrap();
50
51 let layout = Layout::from_size_align(new_size, new_align).unwrap();
52 (layout, offset)
53}
54
55/// 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 {
61 let len = layout.size();
62 let len_rounded_up = len.wrapping_add(align).wrapping_sub(1) & !align.wrapping_sub(1);
63 len_rounded_up.wrapping_sub(len)
64}