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
use std::{self, fmt};
#[derive(Debug, PartialEq, Eq)]
pub enum Error {
Insufficient,
Overflow,
#[doc(hidden)]
__Nonexhaustive
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Error::Insufficient => f.write_str("not enough input bytes"),
Error::Overflow => f.write_str("input bytes exceed maximum"),
Error::__Nonexhaustive => f.write_str("__Nonexhaustive")
}
}
}
impl std::error::Error for Error {}
macro_rules! decode {
($buf:expr, $max_bytes:expr, $typ:ident) => {{
let mut n = 0;
for (i, b) in $buf.iter().cloned().enumerate() {
let k = $typ::from(b & 0x7F);
n |= k << (i * 7);
if b & 0x80 == 0 {
return Ok((n, &$buf[i+1..]))
}
if i == $max_bytes {
return Err(Error::Overflow)
}
}
Err(Error::Insufficient)
}}
}
#[inline]
pub fn u8(buf: &[u8]) -> Result<(u8, &[u8]), Error> {
decode!(buf, 1, u8)
}
#[inline]
pub fn u16(buf: &[u8]) -> Result<(u16, &[u8]), Error> {
decode!(buf, 2, u16)
}
#[inline]
pub fn u32(buf: &[u8]) -> Result<(u32, &[u8]), Error> {
decode!(buf, 4, u32)
}
#[inline]
pub fn u64(buf: &[u8]) -> Result<(u64, &[u8]), Error> {
decode!(buf, 9, u64)
}
#[inline]
pub fn u128(buf: &[u8]) -> Result<(u128, &[u8]), Error> {
decode!(buf, 18, u128)
}
#[inline]
#[cfg(target_pointer_width = "64")]
pub fn usize(buf: &[u8]) -> Result<(usize, &[u8]), Error> {
u64(buf).map(|(n, i)| (n as usize, i))
}
#[inline]
#[cfg(target_pointer_width = "32")]
pub fn usize(buf: &[u8]) -> Result<(usize, &[u8]), Error> {
u32(buf).map(|(n, i)| (n as usize, i))
}