1use core::{
4 fmt::{self, Debug, Display},
5 ops::Deref,
6};
7
8pub trait Read<'a> {
10 type Error: Debug + Display;
11
12 fn read_map<R, F>(&mut self, n: usize, f: F) -> Result<R, Self::Error>
16 where
17 F: FnOnce(Bytes<'a, '_>) -> R;
18
19 fn read_exact(&mut self, buf: &mut [u8]) -> Result<(), Self::Error> {
23 self.read_map(buf.len(), |bytes| {
24 buf.copy_from_slice(&bytes);
25 })
26 }
27}
28
29impl<'a, T: Read<'a> + ?Sized> Read<'a> for &'_ mut T {
30 type Error = T::Error;
31
32 fn read_map<R, F>(&mut self, n: usize, f: F) -> Result<R, Self::Error>
33 where
34 F: FnOnce(Bytes<'a, '_>) -> R,
35 {
36 (**self).read_map(n, f)
37 }
38
39 fn read_exact(&mut self, buf: &mut [u8]) -> Result<(), Self::Error> {
40 (**self).read_exact(buf)
41 }
42}
43
44impl<'a> Read<'a> for &'a [u8] {
45 type Error = EndOfInput;
46
47 fn read_map<R, F>(&mut self, n: usize, f: F) -> Result<R, Self::Error>
48 where
49 F: FnOnce(Bytes<'a, '_>) -> R,
50 {
51 if n > self.len() {
52 return Err(EndOfInput);
53 }
54 let (consumed, remaining) = self.split_at(n);
55 *self = remaining;
56 Ok(f(Bytes::Persistent(consumed)))
57 }
58}
59
60pub enum Bytes<'a, 'b> {
62 Persistent(&'a [u8]),
64 Temporary(&'b [u8]),
66}
67
68impl Deref for Bytes<'_, '_> {
69 type Target = [u8];
70
71 fn deref(&self) -> &[u8] {
72 match self {
73 Bytes::Persistent(b) => b,
74 Bytes::Temporary(b) => b,
75 }
76 }
77}
78
79#[derive(Debug)]
81pub struct EndOfInput;
82
83impl Display for EndOfInput {
84 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
85 f.write_str("EndOfInput")
86 }
87}
88
89#[cfg(feature = "std")]
90impl std::error::Error for EndOfInput {}