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
199
200
201
use core::fmt;
use core::convert::TryFrom;


/// Static String
///
/// Use `&&str` instead of `&str` to reduce type size.
pub type StaticStr = &'static &'static str;

/// Never type
pub type Never = core::convert::Infallible;

/// Length type
#[derive(Debug)]
pub enum Len {
    /// Indefinite length
    Indefinite,
    /// Small length
    Small(u16),
    /// Big length
    Big
}

#[derive(Debug)]
pub enum ArithmeticOverflow {
    Overflow,
    Underflow
}

/// Decode Error
#[derive(Debug)]
#[non_exhaustive]
pub enum DecodeError<E> {
    Read(E),
    Mismatch {
        name: StaticStr,
        found: u8
    },
    Unsupported {
        name: StaticStr,
        found: u8
    },
    Eof {
        name: StaticStr,
        expect: Len,
    },
    RequireLength {
        name: StaticStr,
        found: Len,
    },
    RequireBorrowed {
        name: StaticStr,
    },
    RequireUtf8 {
        name: StaticStr,
    },
    LengthOverflow {
        name: StaticStr,
        found: Len
    },
    CastOverflow {
        name: StaticStr
    },
    ArithmeticOverflow {
        name: StaticStr,
        ty: ArithmeticOverflow
    },
    DepthOverflow {
        name: StaticStr
    },
}

impl Len {
    #[inline]
    pub fn new(len: usize) -> Len {
        match u16::try_from(len) {
            Ok(len) => Len::Small(len),
            Err(_) => Len::Big
        }
    }
}

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

impl<E> DecodeError<E> {
    #[cold]
    pub(crate) fn mismatch(name: StaticStr, found: u8) -> DecodeError<E> {
        DecodeError::Mismatch { name, found }
    }

    #[cold]
    pub(crate) fn unsupported(name: StaticStr, found: u8) -> DecodeError<E> {
        DecodeError::Unsupported { name, found }
    }

    #[cold]
    pub(crate) fn eof(name: StaticStr, expect: usize) -> DecodeError<E> {
        DecodeError::Eof { name, expect: Len::new(expect) }
    }

    #[cold]
    pub(crate) fn require_length(name: StaticStr, found: Option<usize>) -> DecodeError<E> {
        let found = match found {
            Some(len) => Len::new(len),
            None => Len::Indefinite
        };
        DecodeError::RequireLength { name, found }
    }

    #[cold]
    pub(crate) fn require_borrowed(name: StaticStr) -> DecodeError<E> {
        DecodeError::RequireBorrowed { name }
    }

    #[cold]
    pub(crate) fn require_utf8(name: StaticStr) -> DecodeError<E> {
        DecodeError::RequireUtf8 { name }
    }

    #[cold]
    pub(crate) fn length_overflow(name: StaticStr, found: usize) -> DecodeError<E> {
        DecodeError::LengthOverflow { name, found: Len::new(found) }
    }

    #[cold]
    pub(crate) fn cast_overflow(name: StaticStr) -> DecodeError<E> {
        DecodeError::CastOverflow { name }
    }

    #[cold]
    pub(crate) fn arithmetic_overflow(name: StaticStr, ty: ArithmeticOverflow) -> DecodeError<E> {
        DecodeError::ArithmeticOverflow { name, ty }
    }

    #[cold]
    pub(crate) fn depth_overflow(name: StaticStr) -> DecodeError<E> {
        DecodeError::DepthOverflow { name }
    }
}

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

#[cfg(feature = "use_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::Read(err) => Some(err),
            _ => None
        }
    }
}

/// Encode Error
#[derive(Debug)]
#[non_exhaustive]
pub enum EncodeError<E> {
    Write(E)
}

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

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

#[cfg(feature = "use_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::Write(err) => Some(err),
        }
    }
}

#[test]
fn test_error_type_size() {
    // bottom type
    assert_eq!(core::mem::size_of::<DecodeError<Never>>(), 16);

    // unit type
    assert_eq!(core::mem::size_of::<DecodeError<()>>(), 16);

    // a word type
    assert_eq!(core::mem::size_of::<DecodeError<&'static ()>>(), 16);
}