Skip to main content

bcur/
error.rs

1//! Unified error type for the `bcur` crate.
2
3#[cfg(feature = "dcbor")]
4use alloc::sync::Arc;
5use alloc::vec::Vec;
6
7use crate::ur::UrType;
8
9/// Which decoder/encoder budget was exceeded.
10#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
11#[non_exhaustive]
12pub enum Limit {
13    /// Original payload length (`max_message_length` or `u32` wire field).
14    MessageLength,
15    /// Fragment count `K` (`max_fragment_count` or `u32` wire field).
16    FragmentCount,
17    /// Part payload length (`max_fragment_length`).
18    FragmentLength,
19    /// UR string length (`max_uri_length`).
20    UriLength,
21}
22
23impl core::fmt::Display for Limit {
24    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
25        f.write_str(match self {
26            Self::MessageLength => "message length",
27            Self::FragmentCount => "fragment count",
28            Self::FragmentLength => "fragment length",
29            Self::UriLength => "URI length",
30        })
31    }
32}
33
34/// The category of an [`Error`], for matching and diagnostics.
35#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
36#[non_exhaustive]
37pub enum ErrorKind {
38    /// The input contained non-ASCII characters.
39    NonAscii,
40    /// An unrecognized or malformed byteword token was encountered.
41    InvalidWord,
42    /// The bytewords string length is inconsistent with the selected style.
43    InvalidBytewordsLength,
44    /// The CRC-32 checksum appended to a bytewords payload did not match.
45    InvalidBytewordsChecksum,
46    /// The URI did not start with the `ur:` scheme.
47    InvalidScheme,
48    /// No type token was present after the scheme.
49    TypeUnspecified,
50    /// The UR type token is empty or contains illegal characters.
51    InvalidType,
52    /// Multi-part sequence indices were missing or inconsistent with the part.
53    InvalidIndices,
54    /// The UR type did not match the expected type.
55    UnexpectedType,
56    /// The fountain part CBOR was malformed for our schema.
57    InvalidPartCbor,
58    /// A fountain part had zero/empty fields or inconsistent padding.
59    InvalidPart,
60    /// A part is inconsistent with previously received parts.
61    InconsistentPart,
62    /// A configured resource limit was exceeded.
63    ResourceLimit,
64    /// Joined fragments had non-zero padding past the message length.
65    InvalidPadding,
66    /// Joined fountain payload failed its CRC-32 check.
67    InvalidMessageChecksum,
68    /// The fountain encoder was given an empty message.
69    EmptyMessage,
70    /// Fragment length bounds are not positive or `min > max`.
71    InvalidFragmentLength,
72    /// The message exceeds the `u32` wire length field.
73    MessageTooLong,
74    /// A single-part API was used on a multi-part UR.
75    NotSinglePart,
76    /// A consuming completion call (`into_*`) was made on a decoder that
77    /// has not completed.
78    NotComplete,
79    /// The payload is not well-formed deterministic CBOR.
80    CborDecode,
81    /// Well-formed CBOR that cannot become the requested type.
82    CborType,
83    /// An internal invariant was broken.
84    Internal,
85}
86
87impl ErrorKind {
88    /// Display text for kinds without detail.
89    const fn message(self) -> &'static str {
90        match self {
91            Self::NonAscii => "bytewords string is not ASCII",
92            Self::InvalidWord => "invalid bytewords word",
93            Self::InvalidBytewordsLength => "invalid bytewords length",
94            Self::InvalidBytewordsChecksum => "invalid bytewords checksum",
95            Self::InvalidScheme => "invalid UR scheme",
96            Self::TypeUnspecified => "UR type unspecified",
97            Self::InvalidType => "invalid UR type",
98            Self::InvalidIndices => "invalid multi-part indices",
99            Self::UnexpectedType => "unexpected UR type",
100            Self::InvalidPartCbor => "invalid fountain part CBOR",
101            Self::InvalidPart => "invalid fountain part",
102            Self::InconsistentPart => "fountain part inconsistent with previous parts",
103            Self::ResourceLimit => "resource limit exceeded",
104            Self::InvalidPadding => "invalid fountain part padding",
105            Self::InvalidMessageChecksum => "invalid fountain message checksum",
106            Self::EmptyMessage => "empty message",
107            Self::InvalidFragmentLength => "invalid fragment length",
108            Self::MessageTooLong => "message too long",
109            Self::NotSinglePart => "expected single-part UR",
110            Self::NotComplete => "decoder is not complete",
111            Self::CborDecode => "dCBOR decode failed",
112            Self::CborType => "dCBOR type mismatch",
113            Self::Internal => "internal error",
114        }
115    }
116}
117
118#[derive(Debug, Clone)]
119enum Detail {
120    None,
121    Limit(Limit),
122    UnexpectedType {
123        expected: Vec<UrType>,
124        found: UrType,
125    },
126    #[cfg(feature = "dcbor")]
127    Cbor {
128        source: Arc<dcbor::Error>,
129    },
130}
131
132/// Errors that can occur while encoding or decoding Uniform Resources.
133///
134/// Opaque: match on [`Self::kind`] (a `#[non_exhaustive]` [`ErrorKind`]) and
135/// read details through [`Self::limit`], [`Self::expected_types`], and
136/// [`Self::found_type`].
137#[derive(Debug, Clone)]
138pub struct Error {
139    kind: ErrorKind,
140    detail: Detail,
141}
142
143impl Error {
144    /// Error kind.
145    #[must_use]
146    pub const fn kind(&self) -> ErrorKind {
147        self.kind
148    }
149
150    /// Whether this error is session-fatal for a decoder (the decoder enters
151    /// the failed state).
152    #[must_use]
153    pub const fn is_fatal(&self) -> bool {
154        matches!(
155            self.kind,
156            ErrorKind::ResourceLimit
157                | ErrorKind::InvalidPadding
158                | ErrorKind::InvalidMessageChecksum
159                | ErrorKind::Internal
160        )
161    }
162
163    /// The exceeded budget, for [`ErrorKind::ResourceLimit`].
164    #[must_use]
165    pub const fn limit(&self) -> Option<Limit> {
166        match &self.detail {
167            Detail::Limit(limit) => Some(*limit),
168            _ => None,
169        }
170    }
171
172    /// Accepted types, for [`ErrorKind::UnexpectedType`]; empty otherwise.
173    #[must_use]
174    pub fn expected_types(&self) -> &[UrType] {
175        match &self.detail {
176            Detail::UnexpectedType { expected, .. } => expected,
177            _ => &[],
178        }
179    }
180
181    /// The mismatched type, for [`ErrorKind::UnexpectedType`].
182    #[must_use]
183    pub const fn found_type(&self) -> Option<&UrType> {
184        match &self.detail {
185            Detail::UnexpectedType { found, .. } => Some(found),
186            _ => None,
187        }
188    }
189
190    pub(crate) const fn new(kind: ErrorKind) -> Self {
191        Self {
192            kind,
193            detail: Detail::None,
194        }
195    }
196
197    pub(crate) const fn internal() -> Self {
198        Self::new(ErrorKind::Internal)
199    }
200
201    pub(crate) const fn resource_limit(limit: Limit) -> Self {
202        Self {
203            kind: ErrorKind::ResourceLimit,
204            detail: Detail::Limit(limit),
205        }
206    }
207
208    pub(crate) const fn unexpected_type(expected: Vec<UrType>, found: UrType) -> Self {
209        Self {
210            kind: ErrorKind::UnexpectedType,
211            detail: Detail::UnexpectedType { expected, found },
212        }
213    }
214
215    /// `kind` must be [`ErrorKind::CborDecode`] or [`ErrorKind::CborType`].
216    #[cfg(feature = "dcbor")]
217    pub(crate) fn cbor(kind: ErrorKind, source: dcbor::Error) -> Self {
218        Self {
219            kind,
220            detail: Detail::Cbor {
221                source: Arc::new(source),
222            },
223        }
224    }
225}
226
227impl PartialEq for Error {
228    fn eq(&self, other: &Self) -> bool {
229        if self.kind != other.kind {
230            return false;
231        }
232        match (&self.detail, &other.detail) {
233            (Detail::None, Detail::None) => true,
234            (Detail::Limit(a), Detail::Limit(b)) => a == b,
235            (
236                Detail::UnexpectedType {
237                    expected: ae,
238                    found: af,
239                },
240                Detail::UnexpectedType {
241                    expected: be,
242                    found: bf,
243                },
244            ) => ae == be && af == bf,
245            #[cfg(feature = "dcbor")]
246            (Detail::Cbor { .. }, Detail::Cbor { .. }) => true,
247            #[allow(unreachable_patterns, reason = "dcbor-gated variants")]
248            _ => false,
249        }
250    }
251}
252
253impl Eq for Error {}
254
255impl core::fmt::Display for Error {
256    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
257        match &self.detail {
258            Detail::Limit(limit) => {
259                write!(f, "{}: {limit}", self.kind.message())
260            }
261            Detail::UnexpectedType { expected, found } => {
262                let expected = expected
263                    .iter()
264                    .map(UrType::as_str)
265                    .collect::<Vec<_>>()
266                    .join(", ");
267                write!(
268                    f,
269                    "{}: expected {expected}, found {}",
270                    self.kind.message(),
271                    found.as_str()
272                )
273            }
274            Detail::None => f.write_str(self.kind.message()),
275            #[cfg(feature = "dcbor")]
276            Detail::Cbor { .. } => f.write_str(self.kind.message()),
277        }
278    }
279}
280
281impl core::error::Error for Error {
282    fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
283        match &self.detail {
284            #[cfg(feature = "dcbor")]
285            Detail::Cbor { source } => Some(&**source),
286            _ => None,
287        }
288    }
289}
290
291/// Result alias for `bcur` operations.
292pub type Result<T> = core::result::Result<T, Error>;