Skip to main content

cbor_core/
error.rs

1use std::{fmt, io, string::FromUtf8Error};
2
3use crate::DataType;
4
5/// Errors produced by this crate.
6///
7/// Errors fall into three categories:
8///
9/// **Decoding errors** are returned by [`Value::decode`](crate::Value::decode),
10/// [`Value::read_from`](crate::Value::read_from),
11/// and [`Value::read_hex_from`](crate::Value::read_hex_from) when the input is not valid deterministic
12/// CBOR: [`Malformed`](Self::Malformed), [`NonDeterministic`](Self::NonDeterministic),
13/// [`UnexpectedEof`](Self::UnexpectedEof), [`LengthTooLarge`](Self::LengthTooLarge),
14/// [`InvalidUtf8`](Self::InvalidUtf8), [`InvalidHex`](Self::InvalidHex).
15///
16/// **Accessor errors** are returned by the `to_*`, `as_*`, and `into_*`
17/// methods on [`Value`](crate::Value) when the value does not match the requested type:
18/// [`IncompatibleType`](Self::IncompatibleType), [`Overflow`](Self::Overflow),
19/// [`NegativeUnsigned`](Self::NegativeUnsigned), [`Precision`](Self::Precision),
20/// [`InvalidSimpleValue`](Self::InvalidSimpleValue).
21///
22/// **Validation errors** are returned during construction of typed helpers
23/// like [`DateTime`](crate::DateTime) and [`EpochTime`](crate::EpochTime):
24/// [`InvalidFormat`](Self::InvalidFormat), [`InvalidValue`](Self::InvalidValue).
25///
26/// `Error` is `Copy`, `Eq`, `Ord`, and `Hash`, so it can be matched,
27/// compared, and used as a map key without allocation. I/O errors are
28/// handled separately by [`IoError`], which wraps either an `Error` or
29/// a [`std::io::Error`]. This separation keeps `Error` small and
30/// `Copy`-able while still supporting streaming operations that can
31/// fail with I/O problems.
32#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
33#[non_exhaustive]
34pub enum Error {
35    // --- Decoding errors ---
36
37    /// Binary CBOR data is structurally broken.
38    Malformed,
39    /// CBOR encoding is valid but not deterministic (non-shortest form, unsorted map keys, etc.).
40    NonDeterministic,
41    /// Input ended before a complete data item was read.
42    UnexpectedEof,
43    /// Declared length exceeds addressable memory or reasonable size.
44    LengthTooLarge,
45    /// Text string contains invalid UTF-8.
46    InvalidUtf8,
47    /// Hex input contains invalid characters.
48    InvalidHex,
49
50    // --- Accessor errors ---
51
52    /// Accessor called on a value of the wrong CBOR type.
53    IncompatibleType(DataType),
54    /// Integer does not fit in the target type.
55    Overflow,
56    /// Attempted to read a negative integer as an unsigned type.
57    NegativeUnsigned,
58    /// Float conversion would lose precision.
59    Precision,
60    /// Simple value number is in the reserved range 24-31.
61    InvalidSimpleValue,
62
63    // --- Validation errors ---
64
65    /// A text field had invalid syntax for its expected format.
66    InvalidFormat,
67    /// A value violates semantic constraints.
68    InvalidValue,
69}
70
71impl fmt::Display for Error {
72    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
73        match self {
74            Self::Malformed => write!(f, "malformed CBOR encoding"),
75            Self::NonDeterministic => write!(f, "non-deterministic CBOR encoding"),
76            Self::UnexpectedEof => write!(f, "unexpected end of input"),
77            Self::LengthTooLarge => write!(f, "length exceeds reasonable size"),
78            Self::InvalidUtf8 => write!(f, "invalid UTF-8 in text string"),
79            Self::InvalidHex => write!(f, "invalid hex character"),
80            Self::IncompatibleType(t) => write!(f, "incompatible CBOR type {name}", name = t.name()),
81            Self::Overflow => write!(f, "integer overflow"),
82            Self::NegativeUnsigned => write!(f, "negative value for unsigned type"),
83            Self::Precision => write!(f, "float precision loss"),
84            Self::InvalidSimpleValue => write!(f, "invalid CBOR simple value"),
85            Self::InvalidFormat => write!(f, "invalid syntax for expected format"),
86            Self::InvalidValue => write!(f, "invalid value"),
87        }
88    }
89}
90
91impl std::error::Error for Error {}
92
93/// Convenience alias used throughout this crate.
94pub type Result<T> = std::result::Result<T, Error>;
95
96impl From<FromUtf8Error> for Error {
97    fn from(_error: FromUtf8Error) -> Self {
98        Self::InvalidUtf8
99    }
100}
101
102impl<T> From<Error> for Result<T> {
103    fn from(error: Error) -> Self {
104        Err(error)
105    }
106}
107
108/// Error type for IO related operations.
109///
110/// For streaming CBOR operations that may fail with either
111/// an I/O error or a data-level [`Error`].
112#[derive(Debug)]
113pub enum IoError {
114    /// Underlying I/O error from the reader or writer.
115    Io(io::Error),
116    /// CBOR-level error (malformed data, non-deterministic encoding, etc.).
117    Data(Error),
118}
119
120impl From<io::Error> for IoError {
121    fn from(error: io::Error) -> Self {
122        match error.kind() {
123            io::ErrorKind::UnexpectedEof => Error::UnexpectedEof.into(),
124            _other => Self::Io(error),
125        }
126    }
127}
128
129impl<E: Into<Error>> From<E> for IoError {
130    fn from(error: E) -> Self {
131        Self::Data(error.into())
132    }
133}
134
135impl<T> From<Error> for IoResult<T> {
136    fn from(error: Error) -> Self {
137        Err(IoError::Data(error))
138    }
139}
140
141/// Convenience alias for streaming CBOR operations.
142pub type IoResult<T> = std::result::Result<T, IoError>;