cbor_edn/
error.rs

1//! Error types
2
3/// Error type for conversions from EDN to CBOR
4///
5/// The conversion is generally fallible; see [crate level documentation](super).
6#[derive(Debug, Clone)]
7pub struct InconsistentEdn(pub(super) &'static str);
8
9impl From<core::num::TryFromIntError> for InconsistentEdn {
10    fn from(_: core::num::TryFromIntError) -> Self {
11        InconsistentEdn("Numeric range exceeded")
12    }
13}
14
15impl core::fmt::Display for InconsistentEdn {
16    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> Result<(), core::fmt::Error> {
17        f.write_str(self.0)
18    }
19}
20
21impl std::error::Error for InconsistentEdn {}
22
23/// Error type for parsing
24///
25/// This is not a re-export from `peg` to avoid a versioned dependency; it provides location in the
26/// EDN data, and a Display implementation.
27#[derive(Debug, Clone)]
28pub struct ParseError(pub(super) peg::error::ParseError<peg::str::LineCol>);
29
30impl ParseError {
31    /// Line number of the error (starting with 1)
32    pub fn line(&self) -> usize {
33        self.0.location.line
34    }
35    /// Column of the error inside the line given by [`.line()`](Self::line) (starting with 1)
36    pub fn column(&self) -> usize {
37        self.0.location.column
38    }
39    /// Byte at which the error occurred inside the parsed text (starting with 0)
40    pub fn offset(&self) -> usize {
41        self.0.location.offset
42    }
43}
44
45impl core::fmt::Display for ParseError {
46    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> Result<(), core::fmt::Error> {
47        writeln!(
48            f,
49            "Invalid EDN in line {} column {} (byte {}). Expected any of:",
50            self.line(),
51            self.column(),
52            self.offset()
53        )?;
54        for t in self.0.expected.tokens() {
55            writeln!(f, "* {}", t)?;
56        }
57        Ok(())
58    }
59}
60
61impl std::error::Error for ParseError {}
62
63/// Error of item accessors used when the queried type does not match the item
64#[derive(Debug, Clone)]
65pub struct TypeMismatch {
66    expected: &'static str,
67}
68
69impl TypeMismatch {
70    pub(crate) fn expecting(expected: &'static str) -> Self {
71        TypeMismatch { expected }
72    }
73}
74
75impl core::fmt::Display for TypeMismatch {
76    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> Result<(), core::fmt::Error> {
77        write!(f, "Expected {}", self.expected)
78    }
79}
80
81impl std::error::Error for TypeMismatch {}
82
83/// Error converting from CBOR
84#[derive(Debug, Clone)]
85pub struct CborError(pub(crate) &'static str);
86
87impl core::fmt::Display for CborError {
88    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> Result<(), core::fmt::Error> {
89        f.write_str(self.0)
90    }
91}
92
93impl std::error::Error for CborError {}