1use 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#[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 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 pub const fn line(&self) -> u32 {
61 self.line
62 }
63
64 pub const fn module_path(&self) -> &str {
66 self.module_path
67 }
68
69 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#[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}