minicbor_serde/
error.rs

1use core::fmt;
2
3use minicbor::{decode, encode};
4
5/// Deserialisation error.
6#[derive(Debug)]
7pub struct DecodeError(decode::Error);
8
9/// Serialisation error.
10#[derive(Debug)]
11pub struct EncodeError<E>(encode::Error<E>);
12
13impl<E> From<encode::Error<E>> for EncodeError<E> {
14    fn from(e: encode::Error<E>) -> Self {
15        Self(e)
16    }
17}
18
19impl From<decode::Error> for DecodeError {
20    fn from(e: decode::Error) -> Self {
21        Self(e)
22    }
23}
24
25impl fmt::Display for DecodeError {
26    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
27        self.0.fmt(f)
28    }
29}
30
31impl<E: fmt::Display> fmt::Display for EncodeError<E> {
32    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
33        self.0.fmt(f)
34    }
35}
36
37impl core::error::Error for DecodeError {
38    fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
39        self.0.source()
40    }
41}
42
43impl<E: core::error::Error + 'static> core::error::Error for EncodeError<E> {
44    fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
45        self.0.source()
46    }
47}
48
49impl<E: core::error::Error + 'static> serde::ser::Error for EncodeError<E> {
50    fn custom<T: fmt::Display>(_msg: T) -> Self {
51        #[cfg(feature = "alloc")]
52        return Self(encode::Error::message(_msg));
53        #[cfg(not(feature = "alloc"))]
54        Self(encode::Error::message("custom error"))
55    }
56}
57
58impl serde::de::Error for DecodeError {
59    fn custom<T: fmt::Display>(_msg: T) -> Self {
60        #[cfg(feature = "alloc")]
61        return Self(decode::Error::message(_msg));
62        #[cfg(not(feature = "alloc"))]
63        Self(decode::Error::message("custom error"))
64    }
65}