Skip to main content

serde_kv/
error.rs

1use std::fmt::{self, Display};
2
3/// The error type for serializing and deserializing the key/value format.
4#[derive(Debug, Clone, PartialEq, Eq)]
5pub enum Error {
6    /// A custom message produced by serde (missing field, unknown variant, etc.).
7    Message(String),
8    /// A token was missing its `=` separator.
9    ExpectedEquals,
10    /// A quoted value opened with `"` but never closed.
11    UnterminatedQuote,
12    /// A backslash was followed by something other than `"` or `\`.
13    InvalidEscape(char),
14    /// A token could not be parsed as the requested integer type.
15    ParseInt(String),
16    /// A token could not be parsed as the requested float type.
17    ParseFloat(String),
18    /// A token was not `true` or `false` for a bool field.
19    ParseBool(String),
20    /// A token was not exactly one character for a char field.
21    ParseChar(String),
22    /// A scalar/sequence was (de)serialized at the top level; only structs/maps are allowed.
23    TopLevelNotMap,
24    /// A nested struct, sequence, map, or enum value was encountered (unsupported).
25    Unsupported(&'static str),
26}
27
28/// A specialized [`Result`] for this crate.
29pub type Result<T> = std::result::Result<T, Error>;
30
31impl Display for Error {
32    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
33        match self {
34            Error::Message(msg) => f.write_str(msg),
35            Error::ExpectedEquals => f.write_str("expected `=` separator in key/value pair"),
36            Error::UnterminatedQuote => f.write_str("unterminated quoted value"),
37            Error::InvalidEscape(c) => write!(f, "invalid escape sequence `\\{c}`"),
38            Error::ParseInt(t) => write!(f, "invalid integer `{t}`"),
39            Error::ParseFloat(t) => write!(f, "invalid float `{t}`"),
40            Error::ParseBool(t) => write!(f, "invalid bool `{t}` (expected `true` or `false`)"),
41            Error::ParseChar(t) => write!(f, "invalid char `{t}` (expected a single character)"),
42            Error::TopLevelNotMap => {
43                f.write_str("top level value must be a struct or map of key/value pairs")
44            }
45            Error::Unsupported(what) => write!(f, "unsupported value type: {what}"),
46        }
47    }
48}
49
50impl std::error::Error for Error {}
51
52impl serde::ser::Error for Error {
53    fn custom<T: Display>(msg: T) -> Self {
54        Error::Message(msg.to_string())
55    }
56}
57
58impl serde::de::Error for Error {
59    fn custom<T: Display>(msg: T) -> Self {
60        Error::Message(msg.to_string())
61    }
62}