roblib/text_format/
error.rs

1use serde::{de, ser};
2use std::fmt::{self, Display};
3
4pub type Result<T> = std::result::Result<T, Error>;
5
6#[derive(Debug)]
7pub enum Error {
8    // One or more variants that can be created by data structures through the
9    // `ser::Error` and `de::Error` traits. For example the Serialize impl for
10    // Mutex<T> might return an error because the mutex is poisoned, or the
11    // Deserialize impl for a struct may return an error because a required
12    // field is missing.
13    Message(String),
14    MissingArgument,
15    FormatterError(fmt::Error),
16    UnsizedSeq,
17    UnsizedMap,
18    DeserializeAny,
19    Parse(&'static str),
20    Trailing,
21    Empty,
22}
23
24impl ser::Error for Error {
25    fn custom<T: Display>(msg: T) -> Self {
26        Error::Message(msg.to_string())
27    }
28}
29
30impl de::Error for Error {
31    fn custom<T: Display>(msg: T) -> Self {
32        Error::Message(msg.to_string())
33    }
34}
35
36impl Display for Error {
37    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
38        match self {
39            Error::Message(msg) => formatter.write_str(msg),
40            Error::MissingArgument => formatter.write_str("missing argument"),
41            Error::FormatterError(e) => formatter.write_str(&e.to_string()),
42            Error::UnsizedSeq => formatter.write_str("sequence length not specified"),
43            Error::UnsizedMap => formatter.write_str("map length not specified"),
44            Error::DeserializeAny => formatter.write_str("can't deserialize arbitrary data"),
45            Error::Parse(ty) => formatter.write_fmt(format_args!("failed to parse {ty}")),
46            Error::Trailing => formatter.write_str("found trailing characters"),
47            Error::Empty => formatter.write_str("empty argument"),
48        }
49    }
50}
51
52impl std::error::Error for Error {}
53
54impl From<fmt::Error> for Error {
55    fn from(value: fmt::Error) -> Self {
56        Self::FormatterError(value)
57    }
58}