zeros/
error.rs

1/*
2==--==--==--==--==--==--==--==--==--==--==--==--==--==--==--==--
3
4Zeros
5
6Copyright (C) 2019-2025  Anonymous
7
8There are several releases over multiple years,
9they are listed as ranges, such as: "2019-2025".
10
11This program is free software: you can redistribute it and/or modify
12it under the terms of the GNU Lesser General Public License as published by
13the Free Software Foundation, either version 3 of the License, or
14(at your option) any later version.
15
16This program is distributed in the hope that it will be useful,
17but WITHOUT ANY WARRANTY; without even the implied warranty of
18MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19GNU Lesser General Public License for more details.
20
21You should have received a copy of the GNU Lesser General Public License
22along with this program.  If not, see <https://www.gnu.org/licenses/>.
23
24::--::--::--::--::--::--::--::--::--::--::--::--::--::--::--::--
25*/
26
27//! # Error
28
29use alloc::{
30    borrow::Cow,
31    fmt::{self, Display, Formatter},
32};
33
34#[cfg(feature="std")]
35use {
36    alloc::string::ToString,
37    std::io,
38};
39
40/// # Error
41#[derive(Debug)]
42pub struct Error {
43    line: u32,
44    module_path: &'static str,
45    msg: Option<Cow<'static, str>>,
46}
47
48impl Error {
49
50    /// # Makes new instance
51    pub (crate) const fn new(line: u32, module_path: &'static str, msg: Option<Cow<'static, str>>) -> Self {
52        Self {
53            line,
54            module_path,
55            msg,
56        }
57    }
58
59    /// # Line
60    pub const fn line(&self) -> u32 {
61        self.line
62    }
63
64    /// # Module path
65    pub const fn module_path(&self) -> &str {
66        self.module_path
67    }
68
69    /// # Error message
70    pub fn msg(&self) -> Option<&str> {
71        self.msg.as_deref()
72    }
73
74}
75
76impl Display for Error {
77
78    fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
79        match self.msg.as_ref() {
80            Some(msg) => write!(
81                f, "[{tag}][{module_path}-{line}] {msg}", tag=crate::TAG, line=self.line, module_path=self.module_path, msg=msg,
82            ),
83            None => write!(f, "[{tag}][{module_path}-{line}]", tag=crate::TAG, line=self.line, module_path=self.module_path),
84        }
85    }
86
87}
88
89#[cfg(feature="std")]
90#[doc(cfg(feature="std"))]
91impl From<Error> for io::Error {
92
93    fn from(err: Error) -> Self {
94        io::Error::new(io::ErrorKind::Other, err.to_string())
95    }
96
97}
98
99/// # Makes new Error from io::Error
100#[cfg(feature="std")]
101#[doc(cfg(feature="std"))]
102macro_rules! from_io_err {
103    ($e: ident) => {
104        $crate::Error::new(line!(), module_path!(), Some(alloc::borrow::Cow::Owned(alloc::format!("{kind}: {e}", kind=$e.kind(), e=$e))))
105    };
106    ($f: expr) => {
107        $f.map_err(|e| from_io_err!(e))
108    };
109}