use std::error::Error as StdError;
use std::fmt;
pub type BoxError = Box<dyn StdError + Send + Sync + 'static>;
#[non_exhaustive]
#[derive(Debug)]
pub enum Error {
Empty,
Truncated {
needed: usize,
got: usize,
},
UnknownVersion {
found: u16,
known: Vec<u16>,
},
ForwardIncompatible {
found: u16,
current: u16,
},
TrailingBytes {
version: u16,
consumed: usize,
total: usize,
},
Decode {
version: u16,
source: BoxError,
},
Encode {
version: u16,
source: BoxError,
},
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Error::Empty => write!(f, "empty input: no version tag"),
Error::Truncated { needed, got } => {
write!(f, "truncated version tag: need {needed} bytes, got {got}")
}
Error::UnknownVersion { found, known } => {
write!(f, "unknown version {found} (reader handles ")?;
write_versions(f, known)?;
write!(f, ")")
}
Error::ForwardIncompatible { found, current } => write!(
f,
"version {found} is newer than this reader's current version {current}"
),
Error::TrailingBytes {
version,
consumed,
total,
} => {
if consumed <= total {
write!(
f,
"version {version} decoder consumed {consumed} of {total} \
payload bytes, leaving {} unconsumed",
total - consumed
)
} else {
write!(
f,
"version {version} decoder reported consuming {consumed} bytes \
of a {total}-byte payload"
)
}
}
Error::Decode { version, source } => {
write!(f, "version {version} failed to decode: {source}")
}
Error::Encode { version, source } => {
write!(f, "version {version} failed to encode: {source}")
}
}
}
}
impl StdError for Error {
fn source(&self) -> Option<&(dyn StdError + 'static)> {
match self {
Error::Decode { source, .. } | Error::Encode { source, .. } => {
Some(&**source as &(dyn StdError + 'static))
}
_ => None,
}
}
}
fn write_versions(f: &mut fmt::Formatter<'_>, versions: &[u16]) -> fmt::Result {
for (i, v) in versions.iter().enumerate() {
if i > 0 {
write!(f, ", ")?;
}
write!(f, "{v}")?;
}
Ok(())
}