use std::cell::RefCell;
use std::ffi::CString;
use std::os::raw::c_char;
use std::ptr;
pub use super::types::CErrorCode;
thread_local! {
static LAST_ERROR: RefCell<Option<String>> = RefCell::new(None);
}
pub(crate) fn set_last_error(msg: String) {
LAST_ERROR.with(|e| *e.borrow_mut() = Some(msg));
}
#[no_mangle]
pub extern "C" fn wqa_get_last_error() -> *mut c_char {
LAST_ERROR.with(|e| {
match &*e.borrow() {
Some(msg) => {
match CString::new(msg.clone()) {
Ok(c_str) => c_str.into_raw(),
Err(_) => {
CString::new("Error message contains invalid characters")
.unwrap()
.into_raw()
}
}
}
None => ptr::null_mut(),
}
})
}
#[no_mangle]
pub extern "C" fn wqa_clear_error() {
LAST_ERROR.with(|e| *e.borrow_mut() = None);
}
#[no_mangle]
pub extern "C" fn wqa_free_string(s: *mut c_char) {
if !s.is_null() {
unsafe {
let _ = CString::from_raw(s);
}
}
}
pub(crate) fn set_error_from_result<T>(result: crate::models::models::Result<T>) -> Option<T> {
match result {
Ok(val) => Some(val),
Err(e) => {
set_last_error(format!("{}", e));
None
}
}
}