use crate::{_impl_init, InvalidUtf8, TextCursor, impl_trait};
#[doc = crate::_tags!(text error)]
#[doc = crate::_doc_location!("text/parse")]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum TextParseErrorKind {
UnexpectedEof,
UnexpectedByte {
expected: u8,
found: Option<u8>,
},
InvalidUtf8(InvalidUtf8),
InvalidDigit,
InvalidEscape,
BufferTooSmall,
Overflow,
UnterminatedQuote,
UnexpectedAfterQuote,
}
_impl_init![ConstInit: Self::UnexpectedEof => TextParseErrorKind];
impl_trait![fmt::Display for TextParseErrorKind |self, f| {
use TextParseErrorKind as K;
match self {
K::UnexpectedEof => f.write_str("unexpected EOF"),
K::UnexpectedByte { expected, found } => match found {
Some(found) => write!(f, "unexpected byte: found {found:?}, expected {expected:?}"),
None => write!(f, "unexpected EOF: expected byte {expected:?}"),
},
K::InvalidUtf8(err) => write!(f, "invalid UTF-8 ({err})"),
K::InvalidDigit => f.write_str("invalid digit"),
K::BufferTooSmall => f.write_str("buffer too small"),
K::Overflow => f.write_str("overflow"),
K::UnterminatedQuote => f.write_str("unterminated quoted string"),
K::UnexpectedAfterQuote => f.write_str("unexpected data after closing quote"),
K::InvalidEscape => f.write_str("invalid escape"),
}
}];
#[doc = crate::_tags!(text error)]
#[doc = crate::_doc_location!("text/parse")]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct TextParseError {
pub at: TextCursor,
pub kind: TextParseErrorKind,
}
_impl_init![ConstInit:
Self { at: TextCursor::INIT, kind: TextParseErrorKind::INIT } => TextParseError];
impl_trait![fmt::Display+Error for TextParseError |self, f|
write!(f, "text parse error at: {:?}, {}", self.at.index, self.kind)
];
impl TextParseError {
pub const fn new(at: TextCursor, kind: TextParseErrorKind) -> Self {
Self { at, kind }
}
pub const fn unexpected_eof(at: TextCursor) -> Self {
Self::new(at, TextParseErrorKind::UnexpectedEof)
}
pub const fn unexpected_byte(at: TextCursor, expected: u8, found: Option<u8>) -> Self {
Self::new(at, TextParseErrorKind::UnexpectedByte { expected, found })
}
pub const fn invalid_utf8(at: TextCursor, err: InvalidUtf8) -> Self {
Self::new(at, TextParseErrorKind::InvalidUtf8(err))
}
pub const fn invalid_digit(at: TextCursor) -> Self {
Self::new(at, TextParseErrorKind::InvalidDigit)
}
pub const fn invalid_escape(at: TextCursor) -> Self {
Self::new(at, TextParseErrorKind::InvalidEscape)
}
pub const fn buffer_too_small(at: TextCursor) -> Self {
Self::new(at, TextParseErrorKind::BufferTooSmall)
}
pub const fn overflow(at: TextCursor) -> Self {
Self::new(at, TextParseErrorKind::Overflow)
}
pub const fn unterminated_quote(at: TextCursor) -> Self {
Self::new(at, TextParseErrorKind::UnterminatedQuote)
}
pub const fn unexpected_after_quote(at: TextCursor) -> Self {
Self::new(at, TextParseErrorKind::UnexpectedAfterQuote)
}
}