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
use core::{
fmt::{self, Debug, Display},
ops::Deref,
};
pub trait Read<'a> {
type Error: Debug + Display;
fn read_map<R, F>(&mut self, n: usize, f: F) -> Result<R, Self::Error>
where
F: FnOnce(Bytes<'a, '_>) -> R;
fn read_exact(&mut self, buf: &mut [u8]) -> Result<(), Self::Error> {
self.read_map(buf.len(), |bytes| {
buf.copy_from_slice(&bytes);
})
}
}
impl<'a, T: Read<'a> + ?Sized> Read<'a> for &'_ mut T {
type Error = T::Error;
fn read_map<R, F>(&mut self, n: usize, f: F) -> Result<R, Self::Error>
where
F: FnOnce(Bytes<'a, '_>) -> R,
{
(**self).read_map(n, f)
}
fn read_exact(&mut self, buf: &mut [u8]) -> Result<(), Self::Error> {
(**self).read_exact(buf)
}
}
impl<'a> Read<'a> for &'a [u8] {
type Error = EndOfInput;
fn read_map<R, F>(&mut self, n: usize, f: F) -> Result<R, Self::Error>
where
F: FnOnce(Bytes<'a, '_>) -> R,
{
if n > self.len() {
return Err(EndOfInput);
}
let (consumed, remaining) = self.split_at(n);
*self = remaining;
Ok(f(Bytes::Persistent(consumed)))
}
}
pub enum Bytes<'a, 'b> {
Persistent(&'a [u8]),
Temporary(&'b [u8]),
}
impl Deref for Bytes<'_, '_> {
type Target = [u8];
fn deref(&self) -> &[u8] {
match self {
Bytes::Persistent(b) => b,
Bytes::Temporary(b) => b,
}
}
}
#[derive(Debug)]
pub struct EndOfInput;
impl Display for EndOfInput {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("EndOfInput")
}
}
#[cfg(feature = "std")]
impl std::error::Error for EndOfInput {}