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
#![cfg(feature = "alloc")]
use alloc::{format, string::String};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NeedSize {
bits: usize,
}
impl NeedSize {
pub fn new(bits: usize) -> Self {
Self { bits }
}
pub fn bit_size(&self) -> usize {
self.bits
}
pub fn byte_size(&self) -> usize {
(self.bits + 7) / 8
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum DekuError {
Incomplete(NeedSize),
Parse(String),
InvalidParam(String),
Unexpected(String),
Assertion(String),
IdVariantNotFound,
}
impl From<core::num::TryFromIntError> for DekuError {
fn from(e: core::num::TryFromIntError) -> DekuError {
DekuError::Parse(format!("error parsing int: {}", e))
}
}
impl From<core::array::TryFromSliceError> for DekuError {
fn from(e: core::array::TryFromSliceError) -> DekuError {
DekuError::Parse(format!("error parsing from slice: {}", e))
}
}
impl From<core::convert::Infallible> for DekuError {
fn from(_e: core::convert::Infallible) -> DekuError {
unreachable!();
}
}
impl core::fmt::Display for DekuError {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
match *self {
DekuError::Incomplete(ref size) => write!(
f,
"Not enough data, need {} bits (or {} bytes)",
size.bit_size(),
size.byte_size()
),
DekuError::Parse(ref err) => write!(f, "Parse error: {}", err),
DekuError::InvalidParam(ref err) => write!(f, "Invalid param error: {}", err),
DekuError::Unexpected(ref err) => write!(f, "Unexpected error: {}", err),
DekuError::Assertion(ref err) => write!(f, "Assertion error: {}", err),
DekuError::IdVariantNotFound => write!(f, "Could not resolve `id` for variant"),
}
}
}
#[cfg(feature = "std")]
impl std::error::Error for DekuError {
fn cause(&self) -> Option<&dyn std::error::Error> {
Some(self)
}
}