use crate::arena::ArenaExhausted;
#[non_exhaustive]
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum ErrorKind {
Truncated,
InvalidTag,
VarintOverflow,
InvalidWireType,
DepthLimitExceeded,
ArenaExhausted,
MissingRequired,
RepeatedSingularMessage,
InputTooLarge,
InvalidUtf8,
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct DecodeError {
kind: ErrorKind,
offset: usize,
field: Option<u32>,
}
impl DecodeError {
#[inline]
pub fn new(kind: ErrorKind, offset: usize) -> Self {
Self {
kind,
offset,
field: None,
}
}
#[doc(hidden)]
#[inline]
#[must_use]
pub fn with_field(mut self, field: u32) -> Self {
self.field = Some(field);
self
}
#[inline]
pub fn kind(&self) -> ErrorKind {
self.kind
}
#[inline]
pub fn offset(&self) -> usize {
self.offset
}
#[inline]
pub fn field_number(&self) -> Option<u32> {
self.field
}
}
impl core::fmt::Display for DecodeError {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
let what = match self.kind {
ErrorKind::InvalidUtf8 => {
return write!(f, "invalid UTF-8 at byte {} of a string", self.offset);
}
ErrorKind::Truncated => "truncated input",
ErrorKind::InvalidTag => "invalid field tag",
ErrorKind::VarintOverflow => "varint overflow",
ErrorKind::InvalidWireType => "invalid wire type",
ErrorKind::DepthLimitExceeded => "depth limit exceeded",
ErrorKind::ArenaExhausted => "arena exhausted",
ErrorKind::MissingRequired => "missing required field",
ErrorKind::RepeatedSingularMessage => "repeated singular message field",
ErrorKind::InputTooLarge => "input too large",
};
match self.field {
Some(field) => write!(f, "{what} (field {field}) at offset {}", self.offset),
None => write!(f, "{what} at offset {}", self.offset),
}
}
}
impl core::error::Error for DecodeError {}
impl From<ArenaExhausted> for DecodeError {
#[inline]
fn from(_: ArenaExhausted) -> Self {
DecodeError::new(ErrorKind::ArenaExhausted, 0)
}
}
impl From<core::str::Utf8Error> for DecodeError {
#[inline]
fn from(error: core::str::Utf8Error) -> Self {
DecodeError::new(ErrorKind::InvalidUtf8, error.valid_up_to())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn invalid_utf8_reports_its_position_in_the_string() {
let to_str = |bytes: &[u8]| -> Result<(), DecodeError> {
core::str::from_utf8(bytes)?;
Ok(())
};
let error = to_str(b"ab\xffc").unwrap_err();
assert_eq!((error.kind(), error.offset()), (ErrorKind::InvalidUtf8, 2));
assert_eq!(error.to_string(), "invalid UTF-8 at byte 2 of a string");
}
}