Skip to main content

liver_shot/
error.rs

1use core::{
2    error::Error as StdError,
3    fmt::{Debug, Display, Formatter, Result as FmtResult},
4};
5
6pub struct Error {
7    kind: Kind,
8}
9
10enum Kind {
11    NotFound,
12    InvalidJson,
13    UnterminatedString,
14    UnmatchedBracket,
15    UnsupportedArray,
16}
17
18impl Error {
19    pub fn is_not_found(&self) -> bool {
20        matches!(self.kind, Kind::NotFound)
21    }
22
23    pub fn is_invalid_json(&self) -> bool {
24        matches!(
25            self.kind,
26            Kind::InvalidJson | Kind::UnterminatedString | Kind::UnmatchedBracket
27        )
28    }
29
30    pub fn is_unsupported_array(&self) -> bool {
31        matches!(self.kind, Kind::UnsupportedArray)
32    }
33
34    pub(crate) fn not_found() -> Self {
35        Self {
36            kind: Kind::NotFound,
37        }
38    }
39
40    pub(crate) fn invalid_json() -> Self {
41        Self {
42            kind: Kind::InvalidJson,
43        }
44    }
45
46    pub(crate) fn unterminated_string() -> Self {
47        Self {
48            kind: Kind::UnterminatedString,
49        }
50    }
51
52    pub(crate) fn unmatched_bracket() -> Self {
53        Self {
54            kind: Kind::UnmatchedBracket,
55        }
56    }
57
58    pub(crate) fn unsupported_array() -> Self {
59        Self {
60            kind: Kind::UnsupportedArray,
61        }
62    }
63}
64
65impl Display for Error {
66    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
67        write!(f, "[liver-shot] {}", self.kind)
68    }
69}
70
71impl Debug for Error {
72    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
73        Display::fmt(self, f)
74    }
75}
76
77impl StdError for Error {}
78
79impl Display for Kind {
80    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
81        match self {
82            Self::NotFound => f.write_str("field not found"),
83            Self::InvalidJson => f.write_str("invalid JSON"),
84            Self::UnterminatedString => f.write_str("unterminated string"),
85            Self::UnmatchedBracket => f.write_str("unmatched bracket"),
86            Self::UnsupportedArray => f.write_str("unsupported array"),
87        }
88    }
89}