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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
use vasi::VirtualAddressSpaceIndependent;

#[derive(
    Copy,
    Clone,
    Debug,
    Default,
    PartialEq,
    Eq,
    PartialOrd,
    Ord,
    Hash,
    VirtualAddressSpaceIndependent,
)]
#[repr(C)]
pub enum FfiOption<T> {
    #[default]
    None,
    Some(T),
}

impl<T> FfiOption<T> {
    pub fn unwrap(self) -> T {
        match self {
            Self::Some(x) => x,
            Self::None => panic!("called `FfiOption::unwrap()` on a `None` value"),
        }
    }

    pub fn unwrap_or(self, default: T) -> T {
        match self {
            Self::Some(x) => x,
            Self::None => default,
        }
    }

    pub fn take(&mut self) -> Self {
        let mut other = Self::None;
        std::mem::swap(self, &mut other);
        other
    }

    pub fn replace(&mut self, value: T) -> Self {
        let mut other = Self::Some(value);
        std::mem::swap(self, &mut other);
        other
    }

    pub fn as_ref(&self) -> FfiOption<&T> {
        match *self {
            Self::Some(ref x) => FfiOption::Some(x),
            Self::None => FfiOption::None,
        }
    }

    pub fn as_mut(&mut self) -> FfiOption<&mut T> {
        match *self {
            Self::Some(ref mut x) => FfiOption::Some(x),
            Self::None => FfiOption::None,
        }
    }
}

impl<T> From<Option<T>> for FfiOption<T> {
    fn from(x: Option<T>) -> Self {
        match x {
            Some(x) => Self::Some(x),
            None => Self::None,
        }
    }
}