use core::fmt;
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum CodecErrorKind {
UnexpectedEof,
InvalidValue,
LengthOverflow,
TrailingBytes,
WriteFailed,
ReadFailed,
}
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub struct CodecError {
kind: CodecErrorKind,
message: &'static str,
}
impl CodecError {
pub const fn new(kind: CodecErrorKind, message: &'static str) -> Self {
Self { kind, message }
}
pub const fn kind(&self) -> CodecErrorKind {
self.kind
}
pub const fn message(&self) -> &'static str {
self.message
}
pub const fn unexpected_eof() -> Self {
Self::new(
CodecErrorKind::UnexpectedEof,
"input ended before the requested bytes could be read",
)
}
pub const fn invalid_value(message: &'static str) -> Self {
Self::new(CodecErrorKind::InvalidValue, message)
}
pub const fn length_overflow(message: &'static str) -> Self {
Self::new(CodecErrorKind::LengthOverflow, message)
}
pub const fn trailing_bytes() -> Self {
Self::new(
CodecErrorKind::TrailingBytes,
"decode completed but trailing bytes remain",
)
}
pub const fn write_failed() -> Self {
Self::new(CodecErrorKind::WriteFailed, "failed to write encoded bytes")
}
pub const fn read_failed() -> Self {
Self::new(CodecErrorKind::ReadFailed, "failed to read encoded bytes")
}
}
impl fmt::Display for CodecError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.message)
}
}
#[cfg(feature = "std")]
impl std::error::Error for CodecError {}