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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
use crate::error::{Code, Error, Result};
const NOT_ID_CHARS: &[u8] = b" '!:(),*@$";
pub enum Reference<'b, 'c, T: ?Sized> {
Borrowed(&'b T),
Copied(&'c T),
}
impl<'b, 'c, T: ?Sized> Reference<'b, 'c, T> {
fn map<O: ?Sized>(self, f: impl for<'r> FnOnce(&'r T) -> &'r O) -> Reference<'b, 'c, O> {
match self {
Reference::Borrowed(b) => Reference::Borrowed(f(b)),
Reference::Copied(c) => Reference::Copied(f(c)),
}
}
fn try_map<O: ?Sized, E>(
self,
f: impl for<'r> FnOnce(&'r T) -> std::result::Result<&'r O, E>,
) -> std::result::Result<Reference<'b, 'c, O>, E> {
Ok(match self {
Reference::Borrowed(b) => Reference::Borrowed(f(b)?),
Reference::Copied(c) => Reference::Copied(f(c)?),
})
}
}
pub trait Read<'de> {
fn next(&mut self) -> Result<Option<u8>> {
let next = self.peek()?;
if next.is_some() {
self.discard();
}
Ok(next)
}
fn peek(&mut self) -> Result<Option<u8>>;
fn discard(&mut self);
// TODO: scratch and zero-copy optimisations
fn parse_str<'s>(&'s mut self, scratch: &'s mut Vec<u8>) -> Result<Reference<'de, 's, str>>;
// TODO: scratch and zero-copy optimisations
fn parse_ident<'s>(&'s mut self, scratch: &'s mut Vec<u8>) -> Result<Reference<'de, 's, str>>;
fn position(&mut self) -> usize;
}
pub struct SliceRead<'a> {
slice: &'a [u8],
/// Index of the *next* byte that will be returned by next() or peek().
index: usize,
}
impl<'a> SliceRead<'a> {
/// Create a JSON input source to read from a slice of bytes.
pub fn new(slice: &'a [u8]) -> Self {
SliceRead { slice, index: 0 }
}
/// Parse a string from the input until a close-string delimiter
/// # Safety
/// Although this method is safe, and thus has no safety preconditions,
/// safety elsewhere relies on the guarantee provided by this method that
/// it will not transform the input stream such that valid utf-8 in the
/// input becomes invalid in the output.
fn parse_str_bytes<'s>(
&'s mut self,
scratch: &'s mut Vec<u8>,
) -> Result<Reference<'a, 's, [u8]>> {
let mut start = self.index;
loop {
if self.index == self.slice.len() {
return Err(Error {
code: Code::EofString,
position: self.position().into(),
});
}
match self.slice[self.index] {
b'\'' => {
if scratch.is_empty() {
let borrowed = &self.slice[start..self.index];
self.index += 1;
return Ok(Reference::Borrowed(borrowed));
} else {
scratch.extend_from_slice(&self.slice[start..self.index]);
self.index += 1;
return Ok(Reference::Copied(scratch));
}
}
b'!' => {
scratch.extend_from_slice(&self.slice[start..self.index]);
self.index += 1;
scratch.push(
match self.next()?.ok_or(Error {
code: Code::EofString,
position: self.position().into(),
})? {
c @ (b'!' | b'\'') => c,
_ => {
return Err(Error {
code: Code::InvalidEscape,
position: self.position().into(),
})
}
},
);
start = self.index;
}
_ => {
self.index += 1;
}
}
}
}
/// Parse an unquoted string from the input until a close-string delimiter
/// # Safety
/// Although this method is safe, and thus has no safety preconditions,
/// safety elsewhere relies on the guarantee provided by this method that
/// it will not transform the input stream such that valid utf-8 in the
/// input becomes invalid in the output.
fn parse_ident_bytes(&mut self) -> Result<&'a [u8]> {
let start = self.index;
while self.index < self.slice.len() && !NOT_ID_CHARS.contains(&self.slice[self.index]) {
self.index += 1;
}
Ok(&self.slice[start..self.index])
}
}
impl<'a> Read<'a> for SliceRead<'a> {
fn peek(&mut self) -> Result<Option<u8>> {
Ok(if self.index < self.slice.len() {
let b = self.slice[self.index];
Some(b)
} else {
None
})
}
fn discard(&mut self) {
self.index += 1;
}
fn parse_str<'s>(&'s mut self, scratch: &'s mut Vec<u8>) -> Result<Reference<'a, 's, str>> {
let start_position = self.position();
let bytes = self.parse_str_bytes(scratch)?;
bytes.try_map(std::str::from_utf8).map_err(|e| Error {
code: Code::InvalidUnicode,
position: (start_position + e.valid_up_to()).into(),
})
}
fn parse_ident<'s>(&'s mut self, _scratch: &'s mut Vec<u8>) -> Result<Reference<'a, 's, str>> {
let start_position = self.position();
let bytes = self.parse_ident_bytes()?;
std::str::from_utf8(bytes)
.map_err(|e| Error {
code: Code::InvalidUnicode,
position: (start_position + e.valid_up_to()).into(),
})
.map(Reference::Copied)
}
fn position(&mut self) -> usize {
self.index
}
}
pub struct StrRead<'a> {
delegate: SliceRead<'a>,
}
impl<'a> StrRead<'a> {
/// Create a JSON input source to read from a slice of bytes.
pub fn new(s: &'a str) -> Self {
StrRead {
delegate: SliceRead::new(s.as_bytes()),
}
}
}
impl<'a> Read<'a> for StrRead<'a> {
fn peek(&mut self) -> Result<Option<u8>> {
self.delegate.peek()
}
fn discard(&mut self) {
self.delegate.discard()
}
fn parse_str<'s>(&'s mut self, scratch: &'s mut Vec<u8>) -> Result<Reference<'a, 's, str>> {
let bytes = self.delegate.parse_str_bytes(scratch)?;
// # Safety
// `parse_str_bytes` guarantees it will not transform
// input such that valid utf-8 becomes invalid. StrRead's buffer
// is guaranteed to be valid utf-8 by construction. The resulting
// buffer is therefore valid utf-8, satisfying the safety preconditions
// of `String::from_utf8_unchecked`
Ok(bytes.map(|b| unsafe { std::str::from_utf8_unchecked(b) }))
}
fn parse_ident<'s>(&'s mut self, _scratch: &'s mut Vec<u8>) -> Result<Reference<'a, 's, str>> {
let bytes = self.delegate.parse_ident_bytes()?;
// # Safety
// `parse_ident_bytes` guarantees it will not transform
// input such that valid utf-8 becomes invalid. StrRead's buffer
// is guaranteed to be valid utf-8 by construction. The resulting
// buffer is therefore valid utf-8, satisfying the safety preconditions
// of `String::from_utf8_unchecked`.
Ok(Reference::Borrowed(unsafe {
std::str::from_utf8_unchecked(bytes)
}))
}
fn position(&mut self) -> usize {
self.delegate.position()
}
}
pub struct IoRead<I> {
io: std::io::Bytes<I>,
peeked: Option<u8>,
position: usize,
}
impl<I: std::io::Read> IoRead<I> {
pub fn new(reader: I) -> Self {
IoRead {
io: reader.bytes(),
peeked: None,
position: 0,
}
}
}
impl<'de, I> Read<'de> for IoRead<I>
where
I: std::io::Read,
{
fn peek(&mut self) -> Result<Option<u8>> {
if let Some(ch) = self.peeked {
return Ok(Some(ch));
}
let ch = self.io.next().transpose().map_err(|e| Error {
code: Code::Io(e),
position: self.position().into(),
})?;
self.peeked = ch;
Ok(ch)
}
fn discard(&mut self) {
self.peeked = None;
self.position += 1;
}
fn parse_str<'s>(&'s mut self, scratch: &'s mut Vec<u8>) -> Result<Reference<'de, 's, str>> {
let start_position = self.position();
loop {
let Some(ch) = self.peek()? else {
return Err(Error {
code: Code::EofString,
position: self.position().into(),
});
};
match ch {
b'\'' => {
self.discard();
return std::str::from_utf8(scratch)
.map_err(|e| Error {
code: Code::InvalidUnicode,
position: (start_position + e.valid_up_to()).into(),
})
.map(Reference::Copied);
}
b'!' => {
self.discard();
scratch.push(
match self.next()?.ok_or(Error {
code: Code::EofString,
position: self.position().into(),
})? {
c @ (b'!' | b'\'') => c,
_ => {
return Err(Error {
code: Code::InvalidMarker,
position: self.position().into(),
})
}
},
);
}
_ => {
scratch.push(ch);
self.discard();
}
}
}
}
fn parse_ident<'s>(&'s mut self, scratch: &'s mut Vec<u8>) -> Result<Reference<'de, 's, str>> {
let start_position = self.position();
while let Some(ch) = self.peek()? {
if NOT_ID_CHARS.contains(&ch) {
break;
}
scratch.push(ch);
self.discard();
}
std::str::from_utf8(scratch)
.map_err(|e| Error {
code: Code::InvalidUnicode,
position: (start_position + e.valid_up_to()).into(),
})
.map(Reference::Copied)
}
fn position(&mut self) -> usize {
self.position
}
}