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
use std::cell::RefCell;
use std::error::Error;
use std::ffi::CString;
use std::fmt::{Display, Formatter, Result};
use std::os::raw::c_char;
thread_local! {
static LAST_ERROR: RefCell<Option<Box<dyn Error>>> = RefCell::new(None);
}
#[derive(Debug)]
struct HaystackErr {
details: String,
}
impl HaystackErr {
fn new(msg: &str) -> HaystackErr {
HaystackErr {
details: msg.to_string(),
}
}
}
impl Display for HaystackErr {
fn fmt(&self, f: &mut Formatter) -> Result {
write!(f, "{}", self.details)
}
}
impl Error for HaystackErr {
fn description(&self) -> &str {
&self.details
}
}
pub(super) fn update_last_error<E: Error + 'static>(err: E) {
LAST_ERROR.with(|prev| {
*prev.borrow_mut() = Some(Box::new(err));
});
}
pub(super) fn new_error(msg: &str) {
update_last_error(HaystackErr::new(msg))
}
fn take_last_error() -> Option<Box<dyn Error>> {
LAST_ERROR.with(|prev| prev.borrow_mut().take())
}
#[no_mangle]
pub unsafe extern "C" fn last_error_message() -> *const c_char {
match take_last_error() {
Some(err) => CString::new(err.to_string().as_bytes())
.expect("Invalid Str")
.into_raw(),
None => std::ptr::null(),
}
}