jiff/shared/util/
error.rs

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
macro_rules! err {
    ($($tt:tt)*) => {{
        crate::shared::util::error::Error::from_args(format_args!($($tt)*))
    }}
}

pub(crate) use err;

/// An error that can be returned when parsing.
#[derive(Clone, Debug)]
pub struct Error {
    #[cfg(feature = "alloc")]
    message: alloc::boxed::Box<str>,
    // only-jiff-start
    #[cfg(not(feature = "alloc"))]
    message: &'static str,
    // only-jiff-end
}

impl Error {
    pub(crate) fn from_args<'a>(message: core::fmt::Arguments<'a>) -> Error {
        #[cfg(feature = "alloc")]
        {
            use alloc::string::ToString;

            let message = message.to_string().into_boxed_str();
            Error { message }
        }
        // only-jiff-start
        #[cfg(not(feature = "alloc"))]
        {
            let message = message.as_str().unwrap_or(
                "unknown Jiff error (better error messages require \
                 enabling the `alloc` feature for the `jiff` crate)",
            );
            Error { message }
        }
        // only-jiff-end
    }
}

impl core::fmt::Display for Error {
    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
        core::fmt::Display::fmt(&self.message, f)
    }
}