1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
//! When serializing or deserializing DAG-CBOR goes wrong.

use core::fmt;
use core::num::TryFromIntError;

#[cfg(not(feature = "std"))]
use alloc::string::{String, ToString};

use serde::{de, ser};

/// An encoding error.
#[derive(Debug)]
pub enum EncodeError<E> {
    /// Custom error message.
    Msg(String),
    /// IO Error.
    Write(E),
}

impl<E> From<E> for EncodeError<E> {
    fn from(err: E) -> EncodeError<E> {
        EncodeError::Write(err)
    }
}

#[cfg(feature = "std")]
impl<E: std::error::Error + 'static> ser::Error for EncodeError<E> {
    fn custom<T: fmt::Display>(msg: T) -> Self {
        EncodeError::Msg(msg.to_string())
    }
}

#[cfg(not(feature = "std"))]
impl<E: fmt::Debug> ser::Error for EncodeError<E> {
    fn custom<T: fmt::Display>(msg: T) -> Self {
        EncodeError::Msg(msg.to_string())
    }
}

#[cfg(feature = "std")]
impl<E: std::error::Error + 'static> std::error::Error for EncodeError<E> {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            EncodeError::Msg(_) => None,
            EncodeError::Write(err) => Some(err),
        }
    }
}

#[cfg(not(feature = "std"))]
impl<E: fmt::Debug> ser::StdError for EncodeError<E> {}

impl<E: fmt::Debug> fmt::Display for EncodeError<E> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        fmt::Debug::fmt(self, f)
    }
}

impl<E: fmt::Debug> From<cbor4ii::EncodeError<E>> for EncodeError<E> {
    fn from(err: cbor4ii::EncodeError<E>) -> EncodeError<E> {
        match err {
            cbor4ii::EncodeError::Write(e) => EncodeError::Write(e),
            // Needed as `cbor4ii::EncodeError` is markes as non_exhaustive
            _ => EncodeError::Msg(err.to_string()),
        }
    }
}

/// A decoding error.
#[derive(Debug)]
pub enum DecodeError<E> {
    /// Custom error message.
    Msg(String),
    /// IO error.
    Read(E),
    /// End of file.
    Eof,
    /// Unexpected byte.
    Mismatch {
        /// Expected CBOR major type.
        expect_major: u8,
        /// Unexpected byte.
        byte: u8,
    },
    /// Unexpected type.
    TypeMismatch {
        /// Type name.
        name: &'static str,
        /// Type byte.
        byte: u8,
    },
    /// Too large integer.
    CastOverflow(TryFromIntError),
    /// Overflowing 128-bit integers.
    Overflow {
        /// Type of integer.
        name: &'static str,
    },
    /// Decoding bytes/strings might require a borrow.
    RequireBorrowed {
        /// Type name (e.g. "bytes", "str").
        name: &'static str,
    },
    /// Length wasn't large enough.
    RequireLength {
        /// Type name.
        name: &'static str,
        /// Required length.
        expect: usize,
        /// Given length.
        value: usize,
    },
    /// Invalid UTF-8.
    InvalidUtf8(core::str::Utf8Error),
    /// Unsupported byte.
    Unsupported {
        /// Unsupported bute.
        byte: u8,
    },
    /// Recursion limit reached.
    DepthLimit,
    /// Trailing data.
    TrailingData,
    /// Indefinite sized item was encountered.
    IndefiniteSize,
}

impl<E> From<E> for DecodeError<E> {
    fn from(err: E) -> DecodeError<E> {
        DecodeError::Read(err)
    }
}

#[cfg(feature = "std")]
impl<E: std::error::Error + 'static> de::Error for DecodeError<E> {
    fn custom<T: fmt::Display>(msg: T) -> Self {
        DecodeError::Msg(msg.to_string())
    }
}

#[cfg(not(feature = "std"))]
impl<E: fmt::Debug> de::Error for DecodeError<E> {
    fn custom<T: fmt::Display>(msg: T) -> Self {
        DecodeError::Msg(msg.to_string())
    }
}

#[cfg(feature = "std")]
impl<E: std::error::Error + 'static> std::error::Error for DecodeError<E> {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            DecodeError::Msg(_) => None,
            DecodeError::Read(err) => Some(err),
            _ => None,
        }
    }
}

#[cfg(not(feature = "std"))]
impl<E: fmt::Debug> ser::StdError for DecodeError<E> {}

impl<E: fmt::Debug> fmt::Display for DecodeError<E> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        fmt::Debug::fmt(self, f)
    }
}

impl<E: fmt::Debug> From<cbor4ii::DecodeError<E>> for DecodeError<E> {
    fn from(err: cbor4ii::DecodeError<E>) -> DecodeError<E> {
        match err {
            cbor4ii::DecodeError::Read(read) => DecodeError::Read(read),
            cbor4ii::DecodeError::Eof => DecodeError::Eof,
            cbor4ii::DecodeError::Mismatch { expect_major, byte } => {
                DecodeError::Mismatch { expect_major, byte }
            }
            cbor4ii::DecodeError::TypeMismatch { name, byte } => {
                DecodeError::TypeMismatch { name, byte }
            }
            cbor4ii::DecodeError::CastOverflow(overflow) => DecodeError::CastOverflow(overflow),
            cbor4ii::DecodeError::Overflow { name } => DecodeError::Overflow { name },
            cbor4ii::DecodeError::RequireBorrowed { name } => DecodeError::RequireBorrowed { name },
            cbor4ii::DecodeError::RequireLength {
                name,
                expect,
                value,
            } => DecodeError::RequireLength {
                name,
                expect,
                value,
            },
            cbor4ii::DecodeError::InvalidUtf8(invalid) => DecodeError::InvalidUtf8(invalid),
            cbor4ii::DecodeError::Unsupported { byte } => DecodeError::Unsupported { byte },
            cbor4ii::DecodeError::DepthLimit => DecodeError::DepthLimit,
            // Needed as `cbor4ii::EncodeError` is markes as non_exhaustive
            _ => DecodeError::Msg(err.to_string()),
        }
    }
}