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
67
68
69
70
71
72
73
74
75
76
77
78
79

use std::{ fmt, io, error };

#[derive(Debug)]
pub struct HaxeError(Box<ErrorKind>);

impl From<ErrorKind> for HaxeError {
    fn from(kind: ErrorKind) -> Self {
        HaxeError(Box::new(kind))
    }
}

impl From<io::Error> for HaxeError {
    fn from(err: io::Error) -> Self {
        ErrorKind::IoError(err).into()
    }
}

impl HaxeError {
    pub fn custom<T: fmt::Display>(msg: T) -> Self {
        ErrorKind::Custom(msg.to_string()).into()
    }

    pub(crate) fn unrepresentable<T: fmt::Display>(msg: T) -> Self {
        ErrorKind::UnrepresentableType(msg.to_string()).into()
    }

    pub(crate) fn invalid_input<T: fmt::Display>(msg: T) -> Self {
        ErrorKind::InvalidInput(msg.to_string()).into()
    }

    pub(crate) fn unexpected_input<T: fmt::Display, U: fmt::Display>(expected: T, got: U) -> Self {
        ErrorKind::InvalidInput(format!("expected {}, got {}", expected, got)).into()
    }
}

impl fmt::Display for HaxeError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        use ErrorKind::*;
        match self.0.as_ref() {
            IoError(err) => write!(f, "io error: {}", err),
            InvalidByte(byte) => write!(f, "invalid byte: {}", byte),
            InvalidNumber => write!(f, "invalid number"),
            InvalidString => write!(f, "invalid string"),
            InvalidDate => write!(f, "invalid date"),
            InvalidBase64 => write!(f, "invalid base64 data"),
            SeqTrailingValues => write!(f, "unexpected trailing values in sequence or map"),
            TrailingBytes => write!(f, "unexpected trailing bytes in input"),
            InvalidInput(msg) => write!(f, "invalid input: {}", msg),
            UnrepresentableType(msg) => write!(f, "unrepresentable type: {}", msg),
            Custom(msg) => write!(f, "{}", msg),
        }
    }
}

impl error::Error for HaxeError {
    fn source(&self) -> Option<&(dyn error::Error + 'static)> {
        use ErrorKind::*;
        match self.0.as_ref() {
            IoError(err) => Some(err),
            _ => None,
        }
    }
}

#[derive(Debug)]
pub enum ErrorKind {
    IoError(io::Error),
    InvalidByte(u8),
    InvalidNumber,
    InvalidString,
    InvalidDate,
    InvalidBase64,
    SeqTrailingValues,
    TrailingBytes,
    InvalidInput(String),
    UnrepresentableType(String),
    Custom(String),
}