use std::{fmt, io, string::FromUtf8Error};
use crate::DataType;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[non_exhaustive]
pub enum Error {
Malformed,
NonDeterministic,
UnexpectedEof,
LengthTooLarge,
InvalidUtf8,
InvalidHex,
IncompatibleType(DataType),
Overflow,
NegativeUnsigned,
Precision,
InvalidSimpleValue,
InvalidFormat,
InvalidValue,
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Malformed => write!(f, "malformed CBOR encoding"),
Self::NonDeterministic => write!(f, "non-deterministic CBOR encoding"),
Self::UnexpectedEof => write!(f, "unexpected end of input"),
Self::LengthTooLarge => write!(f, "length exceeds reasonable size"),
Self::InvalidUtf8 => write!(f, "invalid UTF-8 in text string"),
Self::InvalidHex => write!(f, "invalid hex character"),
Self::IncompatibleType(t) => write!(f, "incompatible CBOR type {name}", name = t.name()),
Self::Overflow => write!(f, "integer overflow"),
Self::NegativeUnsigned => write!(f, "negative value for unsigned type"),
Self::Precision => write!(f, "float precision loss"),
Self::InvalidSimpleValue => write!(f, "invalid CBOR simple value"),
Self::InvalidFormat => write!(f, "invalid syntax for expected format"),
Self::InvalidValue => write!(f, "invalid value"),
}
}
}
impl std::error::Error for Error {}
pub type Result<T> = std::result::Result<T, Error>;
impl From<FromUtf8Error> for Error {
fn from(_error: FromUtf8Error) -> Self {
Self::InvalidUtf8
}
}
impl<T> From<Error> for Result<T> {
fn from(error: Error) -> Self {
Err(error)
}
}
#[derive(Debug)]
pub enum IoError {
Io(io::Error),
Data(Error),
}
impl From<io::Error> for IoError {
fn from(error: io::Error) -> Self {
match error.kind() {
io::ErrorKind::UnexpectedEof => Error::UnexpectedEof.into(),
_other => Self::Io(error),
}
}
}
impl<E: Into<Error>> From<E> for IoError {
fn from(error: E) -> Self {
Self::Data(error.into())
}
}
impl<T> From<Error> for IoResult<T> {
fn from(error: Error) -> Self {
Err(IoError::Data(error))
}
}
pub type IoResult<T> = std::result::Result<T, IoError>;