musli_common/context/
error.rs

1//! Trait governing what error types associated with the encoding framework must
2//! support.
3//!
4//! The most important component in here is `Error::custom` which allows custom
5//! encoding implementations to raise custom errors based on types that
6//! implement [Display][core::fmt::Display].
7
8use core::fmt;
9
10use musli::context::StdError;
11
12#[cfg(feature = "alloc")]
13use alloc::string::{String, ToString};
14
15/// Trait governing errors raised during encodeing or decoding.
16pub trait Error: Sized + 'static + Send + Sync + fmt::Display + fmt::Debug {
17    /// Construct a custom error.
18    fn custom<T>(error: T) -> Self
19    where
20        T: 'static + Send + Sync + StdError;
21
22    /// Collect an error from something that can be displayed.
23    ///
24    /// This is made available to format custom error messages in `no_std`
25    /// environments. The error message is to be collected by formatting `T`.
26    fn message<T>(message: T) -> Self
27    where
28        T: fmt::Display;
29}
30
31#[cfg(all(feature = "std", feature = "alloc"))]
32impl Error for std::io::Error {
33    fn custom<T>(message: T) -> Self
34    where
35        T: 'static + Send + Sync + fmt::Display + fmt::Debug,
36    {
37        std::io::Error::new(std::io::ErrorKind::Other, message.to_string())
38    }
39
40    fn message<T>(message: T) -> Self
41    where
42        T: fmt::Display,
43    {
44        std::io::Error::new(std::io::ErrorKind::Other, message.to_string())
45    }
46}
47
48#[cfg(feature = "alloc")]
49impl Error for String {
50    #[inline]
51    fn custom<T>(message: T) -> Self
52    where
53        T: fmt::Display,
54    {
55        message.to_string()
56    }
57
58    #[inline]
59    fn message<T>(message: T) -> Self
60    where
61        T: fmt::Display,
62    {
63        message.to_string()
64    }
65}