summaryrefslogtreecommitdiffstats
path: root/third_party/rust/hyper/src/ffi/macros.rs
blob: 022711baaa53f2fc09077049281e519914a557bf (plain)
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
macro_rules! ffi_fn {
    ($(#[$doc:meta])* fn $name:ident($($arg:ident: $arg_ty:ty),*) -> $ret:ty $body:block ?= $default:expr) => {
        $(#[$doc])*
        #[no_mangle]
        pub extern fn $name($($arg: $arg_ty),*) -> $ret {
            use std::panic::{self, AssertUnwindSafe};

            match panic::catch_unwind(AssertUnwindSafe(move || $body)) {
                Ok(v) => v,
                Err(_) => {
                    $default
                }
            }
        }
    };

    ($(#[$doc:meta])* fn $name:ident($($arg:ident: $arg_ty:ty),*) -> $ret:ty $body:block) => {
        ffi_fn!($(#[$doc])* fn $name($($arg: $arg_ty),*) -> $ret $body ?= {
            eprintln!("panic unwind caught, aborting");
            std::process::abort()
        });
    };

    ($(#[$doc:meta])* fn $name:ident($($arg:ident: $arg_ty:ty),*) $body:block ?= $default:expr) => {
        ffi_fn!($(#[$doc])* fn $name($($arg: $arg_ty),*) -> () $body ?= $default);
    };

    ($(#[$doc:meta])* fn $name:ident($($arg:ident: $arg_ty:ty),*) $body:block) => {
        ffi_fn!($(#[$doc])* fn $name($($arg: $arg_ty),*) -> () $body);
    };
}

macro_rules! non_null {
    ($ptr:ident, $eval:expr, $err:expr) => {{
        debug_assert!(!$ptr.is_null(), "{:?} must not be null", stringify!($ptr));
        if $ptr.is_null() {
            return $err;
        }
        unsafe { $eval }
    }};
    (&*$ptr:ident ?= $err:expr) => {{
        non_null!($ptr, &*$ptr, $err)
    }};
    (&mut *$ptr:ident ?= $err:expr) => {{
        non_null!($ptr, &mut *$ptr, $err)
    }};
    (Box::from_raw($ptr:ident) ?= $err:expr) => {{
        non_null!($ptr, Box::from_raw($ptr), $err)
    }};
    (Arc::from_raw($ptr:ident) ?= $err:expr) => {{
        non_null!($ptr, Arc::from_raw($ptr), $err)
    }};
}