use core::fmt;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[must_use]
pub struct Error {
kind: ErrorKind,
offset: usize,
}
impl Error {
#[inline]
pub(crate) const fn new(kind: ErrorKind, offset: usize) -> Self {
Self { kind, offset }
}
#[inline]
#[must_use]
pub const fn kind(&self) -> ErrorKind {
self.kind
}
#[inline]
#[must_use]
pub const fn offset(&self) -> usize {
self.offset
}
}
impl Error {
#[must_use]
pub fn line_col(&self, input: impl AsRef<[u8]>) -> (usize, usize) {
let at = locate(input.as_ref(), self.offset);
(at.line + 1, at.chars + 1)
}
#[must_use]
pub fn utf16_position(&self, input: impl AsRef<[u8]>) -> (usize, usize) {
let at = locate(input.as_ref(), self.offset);
(at.line, at.utf16)
}
}
pub(crate) struct Location {
pub(crate) line: usize,
pub(crate) chars: usize,
pub(crate) utf16: usize,
}
pub(crate) fn locate(input: &[u8], offset: usize) -> Location {
let head = input.get(..offset.min(input.len())).unwrap_or(input);
let mut line = 0;
let mut start = 0;
for (i, &b) in head.iter().enumerate() {
let ends = match b {
b'\n' => true,
b'\r' => input.get(i + 1) != Some(&b'\n'),
_ => false,
};
if ends {
line += 1;
start = i + 1;
}
}
let text = head.get(start..).unwrap_or(&[]);
let chars = text.iter().filter(|&&b| b & 0xC0 != 0x80).count();
let wide = text.iter().filter(|&&b| b >= 0xF0).count();
Location {
line,
chars,
utf16: chars + wide,
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{} at byte {}", self.kind, self.offset)
}
}
impl core::error::Error for Error {}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ErrorKind {
UnexpectedEnd,
ExpectedValue,
ExpectedColon,
ExpectedCommaOrBracket,
ExpectedCommaOrBrace,
ExpectedKey,
TrailingComma,
TrailingCharacters,
InvalidLiteral,
InvalidNumber,
InvalidEscape,
InvalidUnicodeEscape,
LoneSurrogate,
ControlCharacter,
InvalidUtf8,
DuplicateKey,
DepthLimitExceeded,
InputTooLarge,
StringTooLong,
NumberTooLong,
TooManyElements,
MemoryLimitExceeded,
InputAfterEnd,
}
impl ErrorKind {
#[must_use]
pub const fn is_budget(self) -> bool {
matches!(
self,
Self::DepthLimitExceeded
| Self::InputTooLarge
| Self::StringTooLong
| Self::NumberTooLong
| Self::TooManyElements
| Self::MemoryLimitExceeded
)
}
const fn message(self) -> &'static str {
match self {
Self::UnexpectedEnd => "unexpected end of input",
Self::ExpectedValue => "expected a value",
Self::ExpectedColon => "expected `:` after an object key",
Self::ExpectedCommaOrBracket => "expected `,` or `]` after an array element",
Self::ExpectedCommaOrBrace => "expected `,` or `}` after an object member",
Self::ExpectedKey => "expected a string key",
Self::TrailingComma => "trailing comma before `}` or `]`",
Self::TrailingCharacters => "unexpected input after the document's value",
Self::InvalidLiteral => "invalid literal (expected `true`, `false`, or `null`)",
Self::InvalidNumber => "invalid number",
Self::InvalidEscape => "invalid escape sequence",
Self::InvalidUnicodeEscape => "`\\u` must be followed by four hex digits",
Self::LoneSurrogate => "unpaired UTF-16 surrogate escape",
Self::ControlCharacter => "unescaped control character in a string",
Self::InvalidUtf8 => "invalid UTF-8",
Self::DuplicateKey => "duplicate object key",
Self::DepthLimitExceeded => "nesting depth limit exceeded",
Self::InputTooLarge => "input size limit exceeded",
Self::StringTooLong => "string length limit exceeded",
Self::NumberTooLong => "number length limit exceeded",
Self::TooManyElements => "element count limit exceeded",
Self::MemoryLimitExceeded => "memory limit exceeded",
Self::InputAfterEnd => "input fed after the end of input",
}
}
}
impl fmt::Display for ErrorKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.message())
}
}
#[cfg(test)]
mod tests {
use alloc::string::ToString;
use super::*;
#[test]
fn test_error_display_names_kind_and_offset() {
let e = Error::new(ErrorKind::ExpectedColon, 7);
assert_eq!(e.to_string(), "expected `:` after an object key at byte 7");
assert_eq!(e.kind(), ErrorKind::ExpectedColon);
assert_eq!(e.offset(), 7);
}
#[test]
fn test_locate_counts_lines_and_columns() {
let at = |text: &str, offset| {
let l = locate(text.as_bytes(), offset);
(l.line, l.chars, l.utf16)
};
assert_eq!(at("abc", 2), (0, 2, 2));
assert_eq!(at("a\nbc", 3), (1, 1, 1));
assert_eq!(at("a\r\nbc", 4), (1, 1, 1));
assert_eq!(at("a\rbc", 3), (1, 1, 1));
assert_eq!(at("a\r\n", 2), (0, 2, 2)); assert_eq!(at("\u{e9}\u{1f600}x", 6), (0, 2, 3));
assert_eq!(at("ab", 99), (0, 2, 2));
let e = Error::new(ErrorKind::ExpectedValue, 5);
assert_eq!(e.line_col("[\n ]x"), (2, 4));
assert_eq!(e.utf16_position(b"[\n ]x".as_slice()), (1, 3));
}
#[test]
fn test_error_kind_budget_classification_is_exact() {
let all = [
ErrorKind::UnexpectedEnd,
ErrorKind::ExpectedValue,
ErrorKind::ExpectedColon,
ErrorKind::ExpectedCommaOrBracket,
ErrorKind::ExpectedCommaOrBrace,
ErrorKind::ExpectedKey,
ErrorKind::TrailingComma,
ErrorKind::TrailingCharacters,
ErrorKind::InvalidLiteral,
ErrorKind::InvalidNumber,
ErrorKind::InvalidEscape,
ErrorKind::InvalidUnicodeEscape,
ErrorKind::LoneSurrogate,
ErrorKind::ControlCharacter,
ErrorKind::InvalidUtf8,
ErrorKind::DuplicateKey,
ErrorKind::DepthLimitExceeded,
ErrorKind::InputTooLarge,
ErrorKind::StringTooLong,
ErrorKind::NumberTooLong,
ErrorKind::TooManyElements,
ErrorKind::MemoryLimitExceeded,
ErrorKind::InputAfterEnd,
];
let budgets = all.iter().filter(|k| k.is_budget()).count();
assert_eq!(budgets, 6);
for kind in all {
assert!(!kind.to_string().is_empty());
}
}
}