#[cfg(not(feature = "std"))]
use alloc::string::ToString;
use babbel_core::{BabbelError, ErrorCode};
use core::fmt;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CborError {
UnexpectedEof { expected: usize, available: usize },
InvalidInitialByte(u8),
InvalidUtf8,
RecursionLimitExceeded(usize),
SizeLimitExceeded { size: usize, limit: usize },
UnsupportedSimpleValue(u8),
UnexpectedBreak,
InvalidMapKey,
Custom(&'static str),
}
impl fmt::Display for CborError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::UnexpectedEof {
expected,
available,
} => {
write!(
f,
"unexpected end of input: expected {} bytes, but only {} available",
expected, available
)
}
Self::InvalidInitialByte(byte) => {
write!(f, "invalid CBOR initial byte: 0x{:02x}", byte)
}
Self::InvalidUtf8 => {
write!(f, "invalid UTF-8 sequence in CBOR text string")
}
Self::RecursionLimitExceeded(depth) => {
write!(f, "recursion depth limit exceeded: {}", depth)
}
Self::SizeLimitExceeded { size, limit } => {
write!(f, "payload size {} exceeds limit of {} bytes", size, limit)
}
Self::UnsupportedSimpleValue(v) => {
write!(f, "unsupported CBOR simple value: {}", v)
}
Self::UnexpectedBreak => {
write!(f, "unexpected CBOR break stop code")
}
Self::InvalidMapKey => {
write!(f, "map key must be a string or convertible scalar")
}
Self::Custom(msg) => {
write!(f, "{}", msg)
}
}
}
}
#[cfg(feature = "std")]
impl std::error::Error for CborError {}
impl From<CborError> for BabbelError {
fn from(err: CborError) -> Self {
match err {
CborError::InvalidUtf8 => BabbelError::encoding(err.to_string()).with_format("cbor"),
CborError::UnexpectedEof { .. } => {
BabbelError::eof(err.to_string()).with_format("cbor")
}
CborError::RecursionLimitExceeded(_) | CborError::SizeLimitExceeded { .. } => {
BabbelError::new(ErrorCode::Custom, err.to_string()).with_format("cbor")
}
_ => BabbelError::syntax(err.to_string()).with_format("cbor"),
}
}
}