summaryrefslogtreecommitdiff
path: root/rust/libnewsboat-ffi/src/matchererror.rs
blob: 45de6eeb43cf88bc2c43cfb4e473d48f04a38426 (plain) (blame)
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
use crate::abort_on_panic;
use libc::c_char;
use libnewsboat::matchererror::MatcherError;
use std::ffi::CString;
use std::ptr;

// These constants MUST match numbers in `enum MatcherException::Type`, see include/matcherexception.h
const ATTRIB_UNAVAIL: u8 = 0;
const INVALID_REGEX: u8 = 1;

#[repr(C)]
pub struct MatcherErrorFfi {
    err_type: u8, // One of the constants defined above
    info: *mut c_char,
    info2: *mut c_char,
}

#[no_mangle]
pub fn matcher_error_to_ffi(error: MatcherError) -> MatcherErrorFfi {
    abort_on_panic(|| {
        match error {
            MatcherError::AttributeUnavailable { attr } => {
                // NUL bytes in filter expressions are disallowed by the parser, so attribute name is
                // safe and unwrap() here won't ever be triggered.
                let info = CString::new(attr).unwrap().into_raw();
                MatcherErrorFfi {
                    err_type: ATTRIB_UNAVAIL,
                    info,
                    info2: ptr::null_mut(),
                }
            }

            MatcherError::InvalidRegex { regex, errmsg } => {
                // NUL bytes in filter expressions are disallowed by the parser, so regex here is safe
                // and unwrap() won't be triggered.
                let info = CString::new(regex).unwrap().into_raw();
                // Error message comes from regerror, which is a C function. Since it returns
                // a C string, it's obvious that errmsg won't contain NUL bytes. Thus, unwrap() here
                // won't ever be triggered.
                let info2 = CString::new(errmsg).unwrap().into_raw();
                MatcherErrorFfi {
                    err_type: INVALID_REGEX,
                    info,
                    info2,
                }
            }
        }
    })
}

#[no_mangle]
pub unsafe extern "C" fn rs_get_test_attr_unavail_error() -> MatcherErrorFfi {
    matcher_error_to_ffi(MatcherError::AttributeUnavailable {
        attr: String::from("test_attribute"),
    })
}

#[no_mangle]
pub unsafe extern "C" fn rs_get_test_invalid_regex_error() -> MatcherErrorFfi {
    matcher_error_to_ffi(MatcherError::InvalidRegex {
        regex: String::from("?!"),
        errmsg: String::from("inconceivable happened!"),
    })
}