1use std::{error, fmt, io};
2
3#[derive(Debug)]
4pub struct HaxeError(Box<ErrorKind>);
5
6impl From<ErrorKind> for HaxeError {
7 fn from(kind: ErrorKind) -> Self {
8 HaxeError(Box::new(kind))
9 }
10}
11
12impl From<io::Error> for HaxeError {
13 fn from(err: io::Error) -> Self {
14 ErrorKind::IoError(err).into()
15 }
16}
17
18impl HaxeError {
19 pub fn custom<T: fmt::Display>(msg: T) -> Self {
20 ErrorKind::Custom(msg.to_string()).into()
21 }
22
23 pub(crate) fn unrepresentable<T: fmt::Display>(msg: T) -> Self {
24 ErrorKind::UnrepresentableType(msg.to_string()).into()
25 }
26
27 pub(crate) fn invalid_input<T: fmt::Display>(msg: T) -> Self {
28 ErrorKind::InvalidInput(msg.to_string()).into()
29 }
30
31 pub(crate) fn unexpected_input<T: fmt::Display, U: fmt::Display>(expected: T, got: U) -> Self {
32 ErrorKind::InvalidInput(format!("expected {}, got {}", expected, got)).into()
33 }
34}
35
36impl fmt::Display for HaxeError {
37 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
38 use ErrorKind::*;
39 match self.0.as_ref() {
40 IoError(err) => write!(f, "io error: {}", err),
41 InvalidByte(byte) => write!(f, "invalid byte: {}", byte),
42 InvalidNumber => write!(f, "invalid number"),
43 InvalidString => write!(f, "invalid string"),
44 InvalidDate => write!(f, "invalid date"),
45 InvalidBase64 => write!(f, "invalid base64 data"),
46 SeqTrailingValues => write!(f, "unexpected trailing values in sequence or map"),
47 TrailingBytes => write!(f, "unexpected trailing bytes in input"),
48 InvalidInput(msg) => write!(f, "invalid input: {}", msg),
49 UnrepresentableType(msg) => write!(f, "unrepresentable type: {}", msg),
50 Custom(msg) => write!(f, "{}", msg),
51 }
52 }
53}
54
55impl error::Error for HaxeError {
56 fn source(&self) -> Option<&(dyn error::Error + 'static)> {
57 use ErrorKind::*;
58 match self.0.as_ref() {
59 IoError(err) => Some(err),
60 _ => None,
61 }
62 }
63}
64
65#[derive(Debug)]
66pub enum ErrorKind {
67 IoError(io::Error),
68 InvalidByte(u8),
69 InvalidNumber,
70 InvalidString,
71 InvalidDate,
72 InvalidBase64,
73 SeqTrailingValues,
74 TrailingBytes,
75 InvalidInput(String),
76 UnrepresentableType(String),
77 Custom(String),
78}