1 // SPDX-License-Identifier: Apache-2.0
2 
3 use alloc::string::{String, ToString};
4 use core::fmt::{Debug, Display, Formatter, Result};
5 
6 use serde::de::{Error as DeError, StdError};
7 
8 /// An error occurred during deserialization
9 #[derive(Debug)]
10 pub enum Error<T> {
11     /// An error occurred while reading bytes
12     ///
13     /// Contains the underlying error returned 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 
34 impl<T> Error<T> {
35     /// A helper method for composing a semantic error
36     #[inline]
semantic(offset: impl Into<Option<usize>>, msg: impl Into<String>) -> Self37     pub fn semantic(offset: impl Into<Option<usize>>, msg: impl Into<String>) -> Self {
38         Self::Semantic(offset.into(), msg.into())
39     }
40 }
41 
42 impl<T> From<T> for Error<T> {
43     #[inline]
from(value: T) -> Self44     fn from(value: T) -> Self {
45         Error::Io(value)
46     }
47 }
48 
49 impl<T> From<ciborium_ll::Error<T>> for Error<T> {
50     #[inline]
from(value: ciborium_ll::Error<T>) -> Self51     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 
59 impl<T: Debug> Display for Error<T> {
60     #[inline]
fmt(&self, f: &mut Formatter<'_>) -> Result61     fn fmt(&self, f: &mut Formatter<'_>) -> Result {
62         write!(f, "{:?}", self)
63     }
64 }
65 
66 impl<T: Debug> StdError for Error<T> {}
67 
68 impl<T: Debug> DeError for Error<T> {
69     #[inline]
custom<U: Display>(msg: U) -> Self70     fn custom<U: Display>(msg: U) -> Self {
71         Self::Semantic(None, msg.to_string())
72     }
73 }
74