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> EncodeError<E> {
14    pub fn as_write(&self) -> Option<&E> {
15        self.0.as_write()
16    }
17}
18
19impl<E> From<encode::Error<E>> for EncodeError<E> {
20    fn from(e: encode::Error<E>) -> Self {
21        Self(e)
22    }
23}
24
25impl From<decode::Error> for DecodeError {
26    fn from(e: decode::Error) -> Self {
27        Self(e)
28    }
29}
30
31impl fmt::Display for DecodeError {
32    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
33        self.0.fmt(f)
34    }
35}
36
37impl<E: fmt::Display> fmt::Display for EncodeError<E> {
38    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
39        self.0.fmt(f)
40    }
41}
42
43impl core::error::Error for DecodeError {
44    fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
45        self.0.source()
46    }
47}
48
49impl<E: core::error::Error + 'static> core::error::Error for EncodeError<E> {
50    fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
51        self.0.source()
52    }
53}
54
55impl<E: core::error::Error + 'static> serde::ser::Error for EncodeError<E> {
56    fn custom<T: fmt::Display>(_msg: T) -> Self {
57        #[cfg(feature = "alloc")]
58        return Self(encode::Error::message(_msg));
59        #[cfg(not(feature = "alloc"))]
60        Self(encode::Error::message("custom error"))
61    }
62}
63
64impl serde::de::Error for DecodeError {
65    fn custom<T: fmt::Display>(_msg: T) -> Self {
66        #[cfg(feature = "alloc")]
67        return Self(decode::Error::message(_msg));
68        #[cfg(not(feature = "alloc"))]
69        Self(decode::Error::message("custom error"))
70    }
71}