musli/storage/
error.rs

1use core::fmt;
2
3#[cfg(feature = "alloc")]
4use rust_alloc::boxed::Box;
5#[cfg(feature = "alloc")]
6use rust_alloc::string::ToString;
7
8use crate::context::ContextError;
9
10/// Error raised during storage encoding.
11#[derive(Debug)]
12pub struct Error {
13    err: ErrorImpl,
14}
15
16impl fmt::Display for Error {
17    #[inline]
18    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
19        self.err.fmt(f)
20    }
21}
22
23#[derive(Debug)]
24enum ErrorImpl {
25    #[cfg(feature = "alloc")]
26    Message(Box<str>),
27    #[cfg(not(feature = "alloc"))]
28    Empty,
29}
30
31impl fmt::Display for ErrorImpl {
32    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
33        match self {
34            #[cfg(feature = "alloc")]
35            ErrorImpl::Message(message) => message.fmt(f),
36            #[cfg(not(feature = "alloc"))]
37            ErrorImpl::Empty => write!(f, "Message error (see diagnostics)"),
38        }
39    }
40}
41
42impl core::error::Error for Error {}
43
44impl ContextError for Error {
45    #[inline]
46    fn custom<T>(error: T) -> Self
47    where
48        T: fmt::Display,
49    {
50        Self::message(error)
51    }
52
53    #[inline]
54    #[allow(unused_variables)]
55    fn message<T>(message: T) -> Self
56    where
57        T: fmt::Display,
58    {
59        Self {
60            #[cfg(feature = "alloc")]
61            err: ErrorImpl::Message(message.to_string().into()),
62            #[cfg(not(feature = "alloc"))]
63            err: ErrorImpl::Empty,
64        }
65    }
66}