libhaystack/c_api/
err.rs

1// Copyright (C) 2020 - 2022, J2 Innovations
2
3//!
4//! C API for dealing with error handling.
5//!
6
7use std::cell::RefCell;
8use std::error::Error;
9use std::ffi::CString;
10use std::fmt::{Display, Formatter, Result};
11use std::os::raw::c_char;
12
13thread_local! {
14    /// Last error
15    static LAST_ERROR: RefCell<Option<Box<dyn Error>>> = RefCell::new(None);
16}
17
18#[derive(Debug)]
19struct HaystackErr {
20    details: String,
21}
22
23impl HaystackErr {
24    fn new(msg: &str) -> HaystackErr {
25        HaystackErr {
26            details: msg.to_string(),
27        }
28    }
29}
30
31impl Display for HaystackErr {
32    fn fmt(&self, f: &mut Formatter) -> Result {
33        write!(f, "{}", self.details)
34    }
35}
36
37impl Error for HaystackErr {
38    fn description(&self) -> &str {
39        &self.details
40    }
41}
42
43/// Update the most recent error, clearing whatever may have been there before.
44pub(super) fn update_last_error<E: Error + 'static>(err: E) {
45    LAST_ERROR.with(|prev| {
46        *prev.borrow_mut() = Some(Box::new(err));
47    });
48}
49
50/// Register new error.
51pub(super) fn new_error(msg: &str) {
52    update_last_error(HaystackErr::new(msg))
53}
54
55/// Retrieve the most recent error, clearing it in the process.
56fn take_last_error() -> Option<Box<dyn Error>> {
57    LAST_ERROR.with(|prev| prev.borrow_mut().take())
58}
59
60/// Retrieves last error message if any
61/// # Example
62/// ```rust
63/// # use crate::libhaystack::val::Value;
64/// # use crate::libhaystack::c_api::value::*;
65/// # use crate::libhaystack::c_api::err::*;
66/// # unsafe {
67/// let val = haystack_value_make_str(std::ptr::null());
68/// assert!(val.is_none());
69/// assert_ne!(last_error_message(), std::ptr::null())
70/// # }
71/// ```
72/// # Safety
73/// Panics on invalid input data
74#[no_mangle]
75pub unsafe extern "C" fn last_error_message() -> *const c_char {
76    match take_last_error() {
77        Some(err) => CString::new(err.to_string().as_bytes())
78            .expect("Invalid Str")
79            .into_raw(),
80        None => std::ptr::null(),
81    }
82}