Skip to main content

serde_structprop/
error.rs

1//! Error type used throughout `serde-structprop`.
2//!
3//! [`Error`] implements both [`serde::de::Error`] and [`serde::ser::Error`] so
4//! that it can be used as the single error type for all (de)serialization
5//! operations.
6
7use std::fmt;
8
9/// All errors that can arise during serialization or deserialization of a
10/// structprop document.
11#[derive(Debug)]
12pub enum Error {
13    /// A custom message forwarded from serde's own error machinery (e.g. type
14    /// mismatch messages generated by a `Deserialize` impl).
15    Message(String),
16
17    /// A syntax or structural error encountered while lexing or parsing the
18    /// input document.  The inner string describes the problem and, where
19    /// possible, the unexpected token.
20    Parse(String),
21
22    /// The caller asked to (de)serialize a Rust type that has no equivalent
23    /// representation in the structprop format (e.g. raw byte slices).
24    /// The inner `&str` names the unsupported type.
25    UnsupportedType(&'static str),
26
27    /// Map and struct keys must be plain strings.  This error is returned when
28    /// a serializer encounters a non-string key.
29    KeyMustBeString,
30}
31
32impl fmt::Display for Error {
33    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
34        match self {
35            Error::Message(msg) => write!(f, "{msg}"),
36            Error::Parse(msg) => write!(f, "parse error: {msg}"),
37            Error::UnsupportedType(t) => write!(f, "unsupported type: {t}"),
38            Error::KeyMustBeString => write!(f, "map keys must be strings"),
39        }
40    }
41}
42
43impl std::error::Error for Error {}
44
45impl serde::de::Error for Error {
46    fn custom<T: fmt::Display>(msg: T) -> Self {
47        Error::Message(msg.to_string())
48    }
49}
50
51impl serde::ser::Error for Error {
52    fn custom<T: fmt::Display>(msg: T) -> Self {
53        Error::Message(msg.to_string())
54    }
55}
56
57/// Convenience alias for `std::result::Result<T, `[`Error`]`>`.
58pub type Result<T> = std::result::Result<T, Error>;