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
use core::str;
#[cfg(feature = "std")]
use std::error::Error as StdError;
pub trait CoreRead<'a> {
type Error: core::fmt::Debug;
fn fill(&mut self, buffer: &mut [u8]) -> Result<(), Self::Error>;
fn forward_str<V>(&mut self, len: usize, visitor: V) -> Result<V::Value, Self::Error>
where
V: serde::de::Visitor<'a>;
fn forward_bytes<V>(&mut self, len: usize, visitor: V) -> Result<V::Value, Self::Error>
where
V: serde::de::Visitor<'a>;
}
impl<'a> CoreRead<'a> for &'a [u8] {
type Error = SliceReadError;
fn fill(&mut self, buffer: &mut [u8]) -> Result<(), Self::Error> {
if buffer.len() > self.len() {
return Err(SliceReadError::EndOfSlice);
}
buffer.copy_from_slice(&self[..buffer.len()]);
*self = &self[buffer.len()..];
Ok(())
}
fn forward_bytes<V>(&mut self, len: usize, visitor: V) -> Result<V::Value, Self::Error>
where
V: serde::de::Visitor<'a>,
{
if len > self.len() {
return Err(SliceReadError::EndOfSlice);
}
let result = &self[..len];
*self = &self[len..];
visitor.visit_borrowed_bytes(result)
}
fn forward_str<V>(&mut self, len: usize, visitor: V) -> Result<V::Value, Self::Error>
where
V: serde::de::Visitor<'a>,
{
if len > self.len() {
return Err(SliceReadError::EndOfSlice);
}
let result = &self[..len];
*self = &self[len..];
let string = match str::from_utf8(result) {
Ok(s) => s,
Err(_) => return Err(SliceReadError::InvalidUtf8),
};
visitor.visit_borrowed_str(string)
}
}
#[derive(Debug)]
pub enum SliceReadError {
EndOfSlice,
InvalidUtf8,
}
impl serde::de::Error for SliceReadError {
fn custom<T: core::fmt::Display>(_cause: T) -> Self {
panic!("Custom error thrown: {}", _cause);
}
}
impl core::fmt::Display for SliceReadError {
fn fmt(&self, fmt: &mut core::fmt::Formatter) -> core::fmt::Result {
write!(fmt, "{:?}", self)
}
}
#[cfg(feature = "std")]
impl StdError for SliceReadError {}