libnotcurses_sys/
error.rs

1//! Error handling with `NcError`, `NcResult` & `NcResult_i32`
2
3#[cfg(not(feature = "std"))]
4use alloc::string::{String, ToString};
5
6/// The result type for the Rust methods API.
7pub type NcResult<T> = Result<T, NcError>;
8
9/// The error type for the Rust methods API.
10#[derive(Debug, Clone, Default)]
11pub struct NcError {
12    pub int: c_api::NcResult_i32,
13    pub msg: String,
14}
15
16/// # Methods
17impl NcError {
18    /// New NcError with default [`NCRESULT_ERR`][c_api::NCRESULT_ERR]
19    /// error number, and no message.
20    pub fn new() -> Self {
21        Self { int: c_api::NCRESULT_ERR, ..Default::default() }
22    }
23
24    /// New NcError with custom error number, and without message.
25    pub fn new_err(int: c_api::NcResult_i32) -> Self {
26        Self { int, ..Default::default() }
27    }
28
29    /// New NcError with default [`NCRESULT_ERR`][c_api::NCRESULT_ERR]
30    /// error number and a custom message.
31    pub fn new_msg(msg: &str) -> Self {
32        Self { int: c_api::NCRESULT_ERR, msg: msg.to_string() }
33    }
34
35    /// New NcError with both a custom error number and a custom message.
36    pub fn with_msg(int: c_api::NcResult_i32, msg: &str) -> Self {
37        Self { int, msg: msg.to_string() }
38    }
39}
40
41mod core_impls {
42    use super::NcError;
43    use core::fmt;
44
45    impl fmt::Display for NcError {
46        fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
47            write!(f, "NcError {}: {}", self.int, self.msg)
48        }
49    }
50}
51
52#[cfg(feature = "std")]
53mod std_impls {
54    use super::NcError;
55    use std::error::Error;
56
57    impl Error for NcError {
58        fn description(&self) -> &str {
59            &self.msg
60        }
61    }
62}
63
64pub(crate) mod c_api {
65    /// The int value used to return errors.
66    ///
67    /// A value < 0 means error, (usually -1).
68    ///
69    /// It's recommended to use [`NcResult`][crate::NcResult] instead.
70    ///
71    /// # Defined constants:
72    /// - [`NCRESULT_OK`]
73    /// - [`NCRESULT_ERR`]
74    /// - [`NCRESULT_MAX`]
75    pub type NcResult_i32 = i32;
76
77    /// [`NcResult_i32`] OK value.
78    pub const NCRESULT_OK: i32 = 0;
79
80    /// [`NcResult_i32`] ERROR value.
81    pub const NCRESULT_ERR: i32 = -1;
82
83    /// [`NcResult_i32`] MAX value.
84    pub const NCRESULT_MAX: i32 = i32::MAX;
85}