jppe/parser/
errors.rs

1#[cfg(not(feature = "std"))]
2pub use thiserror_no_std::Error as ThisError;
3#[cfg(feature = "std")]
4pub use thiserror::Error as ThisError;
5
6
7pub type JResult<I, O, E = Error<I>> = Result<(I, O), E>;
8
9
10#[derive(Debug, PartialEq, Eq)]
11pub struct Error<I> {
12    pub input: I,
13    pub code: ErrorKind,
14}
15
16
17impl<I> Error<I> {
18    pub fn new(input: I, kind: ErrorKind) -> Self {
19        Self { input, code: kind }
20    }
21}
22
23
24pub trait ParseError<I> {
25    fn from_error_kind(input: I, kind: ErrorKind) -> Self;
26}
27
28
29impl<I> ParseError<I> for Error<I> {
30    fn from_error_kind(input: I, kind: ErrorKind) -> Self {
31        Error { input, code: kind }
32    }
33}
34
35
36#[derive(Debug, PartialEq, Eq, ThisError)]
37pub enum ErrorKind {
38    #[error("invalid byte length: `{offset}`")]
39    InvalidByteLength {
40        offset: usize,
41    },
42    #[error("find subsequence failure: `{offset}`")]
43    SubSequence {
44        offset: usize,
45    },
46    #[error("parse byte failure: `{offset}`")]
47    Fail {
48        offset: usize,
49    }
50}
51
52
53impl ErrorKind {
54    #[inline]
55    pub fn get_offset(&self) -> Option<usize> {
56        match self {
57            Self::InvalidByteLength { offset } => Some(*offset),
58            Self::SubSequence { offset } => Some(*offset),
59            Self::Fail { offset } => Some(*offset),
60        }
61    }
62}
63
64
65#[inline]
66pub fn make_error<I, E: ParseError<I>>(input: I, kind: ErrorKind) -> E {
67    E::from_error_kind(input, kind)
68}