1// SPDX-License-Identifier: Apache-2.0
2
3use alloc::string::{String, ToString};
4use core::fmt::{Debug, Display, Formatter, Result};
5
6use serde::de::{Error as DeError, StdError};
7
8/// An error occurred during deserialization
9#[derive(Debug)]
10pub enum Error<T> {
11 /// An error occurred while reading bytes
12 ///
13 /// Contains the underlying error reaturned while reading.
14 Io(T),
15
16 /// An error occurred while parsing bytes
17 ///
18 /// Contains the offset into the stream where the syntax error occurred.
19 Syntax(usize),
20
21 /// An error occurred while processing a parsed value
22 ///
23 /// Contains a description of the error that occurred and (optionally)
24 /// the offset into the stream indicating the start of the item being
25 /// processed when the error occurred.
26 Semantic(Option<usize>, String),
27
28 /// The input caused serde to recurse too much
29 ///
30 /// This error prevents a stack overflow.
31 RecursionLimitExceeded,
32}
33
34impl<T> Error<T> {
35 /// A helper method for composing a semantic error
36 #[inline]
37 pub fn semantic(offset: impl Into<Option<usize>>, msg: impl Into<String>) -> Self {
38 Self::Semantic(offset.into(), msg.into())
39 }
40}
41
42impl<T> From<T> for Error<T> {
43 #[inline]
44 fn from(value: T) -> Self {
45 Error::Io(value)
46 }
47}
48
49impl<T> From<ciborium_ll::Error<T>> for Error<T> {
50 #[inline]
51 fn from(value: ciborium_ll::Error<T>) -> Self {
52 match value {
53 ciborium_ll::Error::Io(x) => Self::Io(x),
54 ciborium_ll::Error::Syntax(x) => Self::Syntax(x),
55 }
56 }
57}
58
59impl<T: Debug> Display for Error<T> {
60 #[inline]
61 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
62 write!(f, "{:?}", self)
63 }
64}
65
66impl<T: Debug> StdError for Error<T> {}
67
68impl<T: Debug> DeError for Error<T> {
69 #[inline]
70 fn custom<U: Display>(msg: U) -> Self {
71 Self::Semantic(None, msg.to_string())
72 }
73}
74