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
use crate::string::StringError;
use crate::ReprC;
use std::ffi::CString;
use std::os::raw::c_char;
use std::ptr;
pub const FFI_RESULT_OK: &FfiResult = &FfiResult {
error_code: 0,
description: ptr::null(),
};
#[derive(Clone, Debug)]
pub struct NativeResult {
pub error_code: i32,
pub description: Option<String>,
}
impl NativeResult {
pub fn into_repr_c(self) -> Result<FfiResult, StringError> {
Ok(FfiResult {
error_code: self.error_code,
description: match self.description {
Some(description) => CString::new(description)
.map_err(StringError::from)?
.into_raw(),
None => ptr::null(),
},
})
}
}
impl ReprC for NativeResult {
type C = *const FfiResult;
type Error = StringError;
unsafe fn clone_from_repr_c(repr_c: Self::C) -> Result<Self, Self::Error> {
let FfiResult {
error_code,
description,
} = *repr_c;
Ok(Self {
error_code,
description: if description.is_null() {
None
} else {
Some(String::clone_from_repr_c(description).map_err(StringError::from)?)
},
})
}
}
#[repr(C)]
#[derive(Debug)]
pub struct FfiResult {
pub error_code: i32,
pub description: *const c_char,
}
impl Drop for FfiResult {
fn drop(&mut self) {
unsafe {
if !self.description.is_null() {
let _ = CString::from_raw(self.description as *mut _);
}
}
}
}