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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
mod array;
mod rust_box;
use std::{ ptr, ffi::c_void };
pub use crate::{
rust_box::RustBox,
array::{ DataArray, ObjectArray, GenericArray }
};
pub struct FfiObject {
r#type: u64,
dealloc: Option<unsafe extern "C" fn(*mut FfiObject)>,
payload: *mut c_void
}
impl FfiObject {
pub const OPAQUE: u64 = 0x00;
pub const DATA_ARRAY: u64 = 0x01;
pub const OBJECT_ARRAY: u64 = 0x02;
pub const RUST_BOX: u64 = 0x10;
pub const CUSTOM_MASK: u64 = 1 << 63;
pub fn release(&mut self) {
if let Some(dealloc) = self.dealloc {
unsafe{ dealloc(self) }
}
self.dealloc = None;
self.payload = ptr::null_mut();
}
}
impl Drop for FfiObject {
fn drop(&mut self) {
self.release();
}
}
#[repr(C)]
pub struct FfiResult {
ok: FfiObject,
err: FfiObject
}
impl FfiResult {
pub fn new_ok(ok: FfiObject) -> Self {
let err = FfiObject{ r#type: FfiObject::OPAQUE, dealloc: None, payload: ptr::null_mut() };
Self{ ok, err }
}
pub fn new_err(err: FfiObject) -> Self {
let ok = FfiObject{ r#type: FfiObject::OPAQUE, dealloc: None, payload: ptr::null_mut() };
Self{ ok, err }
}
pub fn map(self) -> Result<FfiObject, FfiObject> {
match self.err.payload.is_null() {
false => Err(self.err),
true => Ok(self.ok),
}
}
pub fn map_ok<T>(self, f: impl Fn(FfiObject) -> T) -> Result<T, FfiObject> {
self.map().map(f)
}
pub fn map_err<T>(self, f: impl Fn(FfiObject) -> T) -> Result<FfiObject, T> {
self.map().map_err(f)
}
}