1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
use crate::value::intermediate::Intermediate;
use std::fmt::Display;

pub type Result<T> = std::result::Result<T, Error>;

#[derive(Debug, Clone)]
pub enum Error {
    Message(String),
    ExpectedMapEntry,
    ExpectedStructField,
    ExpectedUnitVariant,
    ExpectedNewTypeVariant,
    ExpectedTupleVariant,
    ExpectedStructVariant,
    NotPartial(Intermediate),
    NotSeq(Intermediate),
    NotTuple(Intermediate),
    NotMap(Intermediate),
    NotStruct(Intermediate),
    CannotAdd(Intermediate),
    CannotRemove(Intermediate),
    /// (value, old size, new size)
    InvalidSize(Intermediate, usize, usize),
    NoNextTokens,
    InvalidTokens(String),
    CannotParse(String),
}

impl serde::ser::Error for Error {
    fn custom<T: Display>(msg: T) -> Self {
        Error::Message(msg.to_string())
    }
}

impl serde::de::Error for Error {
    fn custom<T: Display>(msg: T) -> Self {
        Error::Message(msg.to_string())
    }
}

impl Display for Error {
    fn fmt(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
        match self {
            Error::Message(msg) => formatter.write_str(msg),
            Error::ExpectedMapEntry => formatter.write_str("expected map entry"),
            Error::ExpectedStructField => formatter.write_str("expected struct field"),
            Error::ExpectedUnitVariant => formatter.write_str("expected unit variant"),
            Error::ExpectedNewTypeVariant => formatter.write_str("expected newtype variant"),
            Error::ExpectedTupleVariant => formatter.write_str("expected tuple variant"),
            Error::ExpectedStructVariant => formatter.write_str("expected struct variant"),
            Error::NotPartial(_) => formatter.write_str("value is not a partial"),
            Error::NotSeq(_) => formatter.write_str("value is not a sequence"),
            Error::NotTuple(_) => formatter.write_str("value is not a tuple"),
            Error::NotMap(_) => formatter.write_str("value is not a map"),
            Error::NotStruct(_) => formatter.write_str("value is not a struct"),
            Error::CannotAdd(_) => formatter.write_str("cannot add value here"),
            Error::CannotRemove(_) => formatter.write_str("cannot remove value here"),
            Error::InvalidSize(_, _, _) => formatter.write_str("invalid size here"),
            Error::NoNextTokens => formatter.write_str("no next tokens"),
            Error::InvalidTokens(_) => formatter.write_str("invalid tokens"),
            Error::CannotParse(_) => formatter.write_str("cannot parse"),
        }
    }
}

impl std::error::Error for Error {}