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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
use nom::error::{ErrorKind as NomErrorKind, ParseError};
use std::fmt;
use std::fmt::Display;
use uuid::Uuid;

use serde::ser;

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

/// All possible Errors returned by this library
#[derive(Debug)]
pub enum Error {
    Message(String),
    ParseError(ErrorKind),
    IoError(std::io::Error),
    Eof,
}

impl Error {
    pub fn is_eof(&self) -> bool {
        matches!(self, Error::Eof)
    }

    pub fn parse_error(&self) -> Option<&ErrorKind> {
        match self {
            Error::ParseError(err) => Some(err),
            _ => None,
        }
    }
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Error::Message(msg) => write!(f, "Message: {}", msg),
            Error::ParseError(err) => write!(f, "{}", err),
            Error::IoError(err) => write!(f, "IoError: {}", err),
            Error::Eof => write!(
                f,
                "Tried to parse chunk but reached EOF before completely parsing the chunk"
            ),
        }
    }
}

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

impl From<std::io::Error> for Error {
    fn from(err: std::io::Error) -> Self {
        Error::IoError(err)
    }
}

impl From<ErrorKind> for Error {
    fn from(err: ErrorKind) -> Self {
        Error::ParseError(err)
    }
}

#[derive(Clone, Debug, PartialEq)]
pub enum ErrorKind {
    NotTeehistorian(Option<Uuid>),
    NomErrorKind(NomErrorKind),
    IncompleteHeader,
    NonZeroIntPadding,
    OverlongIntEncoding,
    NegativeBufLen(i32),
    UnknownTag(i32),
    TrailingBytes(&'static str, u32),
}

impl<I> ParseError<I> for ErrorKind {
    fn from_error_kind(_input: I, kind: NomErrorKind) -> Self {
        ErrorKind::NomErrorKind(kind)
    }

    /// combines an existing error with a new one created from the input
    /// position and an [ErrorKind]. This is useful when backtracking
    /// through a parse tree, accumulating error context on the way
    fn append(_input: I, _kind: NomErrorKind, other: Self) -> Self {
        other
    }
}

impl fmt::Display for ErrorKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ErrorKind::NotTeehistorian(None) => write!(f, "Not a teehistorian file (too small)"),
            ErrorKind::NotTeehistorian(Some(uuid)) => write!(f, "Not a teehistorian file (wrong uuid {})", uuid),
            ErrorKind::NomErrorKind(err) => write!(f, "{:?}", err),
            ErrorKind::IncompleteHeader => write!(f, "Header not found or not null terminated"),
            ErrorKind::NonZeroIntPadding => write!(f, "Non-zero int padding found while parsing twint"),
            ErrorKind::OverlongIntEncoding => write!(f, "Overlong twint encoding"),
            ErrorKind::NegativeBufLen(l) => write!(f, "Buffer with negative len '{}' found in NetMessage, ConsoleCommand or Extension Chunk", l),
            ErrorKind::UnknownTag(t) => write!(f, "Unknown Tag {}", t),
            ErrorKind::TrailingBytes(s, n) => write!(f, "{} trailing bytes while parsing {}", n, s),
        }
    }
}

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