Skip to main content

toml_edit/ser/
error.rs

1/// Errors that can occur when deserializing a type.
2#[derive(Debug, Clone, PartialEq, Eq, Hash)]
3#[non_exhaustive]
4pub enum Error {
5    /// Type could not be serialized to TOML
6    UnsupportedType(Option<&'static str>),
7    /// Value was out of range for the given type
8    OutOfRange(Option<&'static str>),
9    /// `None` could not be serialized to TOML
10    UnsupportedNone,
11    /// Key was not convertible to `String` for serializing to TOML
12    KeyNotString,
13    /// A serialized date was invalid
14    DateInvalid,
15    /// Other serialization error
16    Custom(String),
17}
18
19impl Error {
20    pub(crate) fn custom<T>(msg: T) -> Self
21    where
22        T: std::fmt::Display,
23    {
24        Self::Custom(msg.to_string())
25    }
26
27    pub(crate) fn unsupported_type(t: Option<&'static str>) -> Self {
28        Self::UnsupportedType(t)
29    }
30
31    pub(crate) fn out_of_range(t: Option<&'static str>) -> Self {
32        Self::OutOfRange(t)
33    }
34
35    pub(crate) fn unsupported_none() -> Self {
36        Self::UnsupportedNone
37    }
38
39    pub(crate) fn key_not_string() -> Self {
40        Self::KeyNotString
41    }
42
43    pub(crate) fn date_invalid() -> Self {
44        Self::DateInvalid
45    }
46}
47
48impl serde_core::ser::Error for Error {
49    fn custom<T>(msg: T) -> Self
50    where
51        T: std::fmt::Display,
52    {
53        Self::custom(msg)
54    }
55}
56
57impl std::fmt::Display for Error {
58    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
59        match self {
60            Self::UnsupportedType(Some(t)) => write!(formatter, "unsupported {t} type"),
61            Self::UnsupportedType(None) => write!(formatter, "unsupported rust type"),
62            Self::OutOfRange(Some(t)) => write!(formatter, "out-of-range value for {t} type"),
63            Self::OutOfRange(None) => write!(formatter, "out-of-range value"),
64            Self::UnsupportedNone => "unsupported None value".fmt(formatter),
65            Self::KeyNotString => "map key was not a string".fmt(formatter),
66            Self::DateInvalid => "a serialized date was invalid".fmt(formatter),
67            Self::Custom(s) => s.fmt(formatter),
68        }
69    }
70}
71
72impl From<crate::TomlError> for Error {
73    fn from(e: crate::TomlError) -> Self {
74        Self::custom(e)
75    }
76}
77
78impl From<Error> for crate::TomlError {
79    fn from(e: Error) -> Self {
80        Self::custom(e.to_string(), None)
81    }
82}
83
84impl std::error::Error for Error {}