#![deny(unsafe_code)]
#![allow(dead_code)]
use std::fmt;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Reason {
Eof,
Unexpected(u8),
Trailing(u8),
BadLiteral(&'static str),
BadNumber,
BadEscape(u8),
BadHex,
Control(u8),
TooDeep(usize),
}
impl fmt::Display for Reason {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match *self {
Reason::Eof => f.write_str("unexpected end of input"),
Reason::Unexpected(b) => write!(f, "unexpected {}", Byte(b)),
Reason::Trailing(b) => write!(f, "trailing {} after the value", Byte(b)),
Reason::BadLiteral(w) => write!(f, "expected `{w}`"),
Reason::BadNumber => f.write_str("invalid number"),
Reason::BadEscape(b) => write!(f, "invalid escape \\{}", b as char),
Reason::BadHex => f.write_str("invalid \\u escape"),
Reason::Control(b) => write!(f, "unescaped control character 0x{b:02x} in string"),
Reason::TooDeep(n) => write!(f, "nesting deeper than {n} levels"),
}
}
}
struct Byte(u8);
impl fmt::Display for Byte {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.0 {
0x20..=0x7e => write!(f, "{}", self.0 as char),
b => write!(f, "byte 0x{b:02x}"),
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Error {
pub offset: usize,
pub reason: Reason,
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{} at byte {}", self.reason, self.offset)
}
}
impl std::error::Error for Error {}
#[cfg(test)]
#[path = "error_tests.rs"]
mod tests;