async_task/
utils.rs

1use core::alloc::Layout;
2use core::mem;
3
4/// 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
20/// 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) {
29            abort();
30        }
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}