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
//! Error handling with `NcError`, `NcResult` & `NcResult_i32`

/// The result type for the Rust methods API.
pub type NcResult<T> = Result<T, NcError>;

/// The error type for the Rust methods API.
#[derive(Debug, Clone, Default)]
pub struct NcError {
    pub int: c_api::NcResult_i32,
    pub msg: String,
}

/// # Methods
impl NcError {
    /// New NcError with default [`NCRESULT_ERR`][c_api::NCRESULT_ERR]
    /// error number, and no message.
    pub fn new() -> Self {
        Self { int: c_api::NCRESULT_ERR, ..Default::default() }
    }

    /// New NcError with custom error number, and without message.
    pub fn new_err(int: c_api::NcResult_i32) -> Self {
        Self { int, ..Default::default() }
    }

    /// New NcError with default [`NCRESULT_ERR`][c_api::NCRESULT_ERR]
    /// error number and a custom message.
    pub fn new_msg(msg: &str) -> Self {
        Self { int: c_api::NCRESULT_ERR, msg: msg.to_string() }
    }

    /// New NcError with both a custom error number and a custom message.
    pub fn with_msg(int: c_api::NcResult_i32, msg: &str) -> Self {
        Self { int, msg: msg.to_string() }
    }
}

mod std_impls {
    use super::NcError;
    use std::{self, error, fmt};

    impl fmt::Display for NcError {
        fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
            write!(f, "NcError {}: {}", self.int, self.msg)
        }
    }

    impl error::Error for NcError {
        fn description(&self) -> &str {
            &self.msg
        }
    }
}

pub(crate) mod c_api {
    /// The int value used to return errors.
    ///
    /// A value < 0 means error, (usually -1).
    ///
    /// It's recommended to use [`NcResult`][crate::NcResult] instead.
    ///
    /// # Defined constants:
    /// - [`NCRESULT_OK`]
    /// - [`NCRESULT_ERR`]
    /// - [`NCRESULT_MAX`]
    pub type NcResult_i32 = i32;

    /// [`NcResult_i32`] OK value.
    pub const NCRESULT_OK: i32 = 0;

    /// [`NcResult_i32`] ERROR value.
    pub const NCRESULT_ERR: i32 = -1;

    /// [`NcResult_i32`] MAX value.
    pub const NCRESULT_MAX: i32 = i32::MAX;
}