from 0.1.4

A procedural macro that generates custom parsing and validation code
Documentation
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
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
use std::ops::Range;

use super::{utils, SyntaxErr};

#[derive(Debug, PartialEq)]
pub enum ParseResult {
    Ok(String),
    Null,
    TypeMismatch(String),
    SyntaxErr(SyntaxErr),
}

impl ParseResult {
    #[inline]
    fn syntax_err(msg: &str, idx: &mut usize) -> Self {
        Self::SyntaxErr(SyntaxErr::new(msg, idx))
    }

    #[inline]
    fn unexpected_token(exp: &str, found: u8, idx: &mut usize) -> Self {
        Self::SyntaxErr(SyntaxErr::unexpected_token(exp, &[found], idx))
    }

    #[inline]
    fn type_mismatch(found: &str) -> Self {
        ParseResult::TypeMismatch(String::from(found))
    }
}

const TWO_BYTES: Range<u8> = 0b11000000..0b11100000;
const THREE_BYTES: Range<u8> = 0b11100000..0b11110000;
const FOUR_BYTES: Range<u8> = 0b11110000..0b11111000;

const MINION_BYTE: Range<u8> = 0b10000000..0b11000000;

pub fn parse(json: &[u8], idx: &mut usize) -> ParseResult {
    let mut byte = match utils::get_or_unexpected_end(json, idx) {
        Ok(byte) => byte,
        Err(e) => return ParseResult::SyntaxErr(e),
    };

    match byte {
        b'"' => {}

        // null
        b'n' => {
            return if let Err(e) = utils::skip_null(json, idx, "\"") {
                ParseResult::SyntaxErr(e)
            } else {
                ParseResult::Null
            }
        }

        b'f' => {
            return if let Err(e) = utils::skip_false(json, idx, "\"") {
                ParseResult::SyntaxErr(e)
            } else {
                ParseResult::type_mismatch("boolean")
            }
        }

        b't' => {
            return if let Err(e) = utils::skip_true(json, idx, "\"") {
                ParseResult::SyntaxErr(e)
            } else {
                ParseResult::type_mismatch("boolean")
            }
        }

        b'{' => {
            return if let Err(e) = utils::skip_object(json, idx) {
                ParseResult::SyntaxErr(e)
            } else {
                ParseResult::type_mismatch("object")
            }
        }

        b'[' => {
            return if let Err(e) = utils::skip_array(json, idx) {
                ParseResult::SyntaxErr(e)
            } else {
                ParseResult::type_mismatch("array")
            }
        }

        b'0'..=b'9' => {
            utils::skip_number(json, idx);
            return ParseResult::type_mismatch("number");
        }

        _ => {
            return ParseResult::unexpected_token("\"", byte, idx);
        }
    };

    let mut string = Vec::<u8>::new();

    macro_rules! get_next_byte {
        () => {
            *idx += 1;

            byte = match utils::get_or_unexpected_end(json, idx) {
                Ok(byte) => byte,
                Err(e) => return ParseResult::SyntaxErr(e),
            };
        };
    }

    let mut last_push = *idx + 1;

    // idx: 9, last_push: 10
    // idx: 10, last_push: 10
    // idx: 15, last_push: 10
    // idx: 15, last_push: 1
    loop {
        get_next_byte!();

        match byte {
            b'"' => {
                if last_push < *idx {
                    string.extend_from_slice(&json[last_push..*idx]);
                };
                *idx += 1;
                return ParseResult::Ok(unsafe { String::from_utf8_unchecked(string) });
            }

            b'\\' => {
                if last_push < *idx {
                    string.extend_from_slice(&json[last_push..*idx]);
                };
                get_next_byte!();

                match byte {
                    b'"' | b'\\' | b'/' => {
                        string.push(byte);
                        last_push = *idx + 1;
                    }

                    b'b' => {
                        string.push(8); // backspace
                        last_push = *idx + 1;
                    }

                    b'f' => {
                        string.push(12); // form feed
                        last_push = *idx + 1;
                    }

                    b't' => {
                        string.push(b'\t');
                        last_push = *idx + 1;
                    }

                    b'r' => {
                        string.push(b'\r');
                        last_push = *idx + 1;
                    }

                    b'n' => {
                        string.push(b'\n');
                        last_push = *idx + 1;
                    }

                    b'u' => {
                        // 4 hex + 1 required double quote
                        if json.len() < *idx + 5 {
                            return ParseResult::SyntaxErr(SyntaxErr::unexpected_end(
                                &mut json.len(),
                            ));
                        };

                        *idx += 1;

                        let mut hex;

                        byte = json[*idx];
                        match byte {
                            b'0'..=b'9' => hex = (byte - 48) as u16,

                            b'A'..=b'F' => hex = (byte - 55) as u16,

                            b'a'..=b'f' => hex = (byte - 87) as u16,

                            _ => return ParseResult::syntax_err("invalid hex digit", idx),
                        };

                        for _ in 0..3 {
                            *idx += 1;
                            byte = json[*idx];
                            hex *= 16;
                            match byte {
                                b'0'..=b'9' => hex += (byte - 48) as u16,

                                b'A'..=b'F' => hex += (byte - 55) as u16,

                                b'a'..=b'f' => hex += (byte - 87) as u16,

                                _ => return ParseResult::syntax_err("invalid hex digit", idx),
                            };
                        }

                        last_push = *idx + 1;

                        // 0XXXXXXX -> 0..=127
                        if hex < 128 {
                            string.push(hex as u8);
                            continue;
                        };

                        // 110XXXXX  10XX XXXX  -> 128..=2047
                        if hex < 2048 {
                            string.extend_from_slice(&[
                                (hex >> 6) as u8 | 0b1100_0000,
                                (hex as u8 & 0b0011_1111) | 0b1000_0000,
                            ]);

                            continue;
                        };

                        // 1110XXXX  10XX XXXX  10XX XXXX  -> 2048..=65535

                        // take first four bits to the right and set the
                        // remaining four bits at left to 1110
                        string.extend_from_slice(&[
                            (hex >> 12) as u8 | 0b1110_0000,
                            ((hex >> 6) as u8 & 0b0011_1111) | 0b1000_0000,
                            (hex as u8 & 0b0011_1111) | 0b1000_0000,
                        ]);
                    }

                    _ => return ParseResult::syntax_err("invalid control character", idx),
                }
            }

            _ => {
                // Byte -> 0XXX XXXX
                if byte < 128 {
                    continue;
                };

                //
                //
                //
                // 2 Bytes 110X XXXX  10XX XXXX
                if TWO_BYTES.contains(&byte) {
                    get_next_byte!();

                    if !MINION_BYTE.contains(&byte) {
                        return ParseResult::syntax_err("invalid UTF-8 byte", idx);
                    };
                    continue;
                };

                //
                //
                //
                //
                //
                // 3 Bytes 1110 XXXX  10XX XXXXX  10XX XXXX
                if THREE_BYTES.contains(&byte) {
                    for _ in 0..2 {
                        get_next_byte!();

                        if !MINION_BYTE.contains(&byte) {
                            return ParseResult::syntax_err("invalid UTF-8 byte", idx);
                        };
                    }

                    continue;
                }

                //
                //
                //
                //
                // 4 Bytes 1111 0XXX  10XX XXXX  10XX XXXX  10XX XXXX
                if FOUR_BYTES.contains(&byte) {
                    for _ in 0..3 {
                        get_next_byte!();

                        if !MINION_BYTE.contains(&byte) {
                            return ParseResult::syntax_err("invalid UTF-8 byte", idx);
                        };
                    }

                    continue;
                };

                //
                //
                // invalid must not be outside the previous ranges
                return ParseResult::syntax_err("invalid UTF-8 byte", idx);
            }
        }
    }
}

pub fn sanitize_xss(s: &mut String) {
    const QUOT: &[u8] = b"&#34;";
    const APOS: &[u8] = b"&#39;";
    const AMP: &[u8] = b"&amp;";
    const LT: &[u8] = b"&lt;";
    const GT: &[u8] = b"&gt;";
    const NULL: &[u8] = "\u{FFFD}".as_bytes();

    let bytes = s.as_bytes();
    let mut es: Vec<u8> = Vec::with_capacity(bytes.len());
    let mut last = 0usize;
    let mut idx = 0usize;

    while bytes.len() > idx {
        match bytes[idx] {
            b'\0' => {
                if last < idx {
                    es.extend_from_slice(&bytes[last..idx]);
                };
                es.extend_from_slice(NULL);
                last = idx + 1;
            }
            b'"' => {
                if last < idx {
                    es.extend_from_slice(&bytes[last..idx]);
                };
                es.extend_from_slice(QUOT);
                last = idx + 1;
            }
            b'\'' => {
                if last < idx {
                    es.extend_from_slice(&bytes[last..idx]);
                };
                es.extend_from_slice(APOS);
                last = idx + 1;
            }
            b'&' => {
                if last < idx {
                    es.extend_from_slice(&bytes[last..idx]);
                };
                es.extend_from_slice(AMP);
                last = idx + 1;
            }
            b'<' => {
                if last < idx {
                    es.extend_from_slice(&bytes[last..idx]);
                };
                es.extend_from_slice(LT);
                last = idx + 1;
            }
            b'>' => {
                if last < idx {
                    es.extend_from_slice(&bytes[last..idx]);
                };
                es.extend_from_slice(GT);
                last = idx + 1;
            }

            _ => {}
        }
        idx += 1;
    }

    if last < s.len() {
        es.extend_from_slice(&bytes[last..]);
    };

    *s = unsafe { String::from_utf8_unchecked(es) }
}

#[cfg(test)]
mod test {

    use crate::json::SyntaxErr;

    use super::{parse, sanitize_xss, ParseResult};

    #[test]
    fn valid() {
        assert_eq!(
            parse(r#""hello\n\t\u00c2\b\f\uf977\r\"""#.as_bytes(), &mut 0),
            ParseResult::Ok(String::from("hello\n\tÂ亮\r\""))
        );
    }

    #[test]
    fn null() {
        assert_eq!(parse("null".as_bytes(), &mut 0), ParseResult::Null);
    }

    #[test]
    fn type_mismatch_false() {
        assert_eq!(
            parse("false,".as_bytes(), &mut 0),
            ParseResult::type_mismatch("boolean")
        );
    }

    #[test]
    fn type_mismatch_true() {
        assert_eq!(
            parse("true}".as_bytes(), &mut 0),
            ParseResult::type_mismatch("boolean")
        );
    }

    #[test]
    fn type_mismatch_object() {
        assert_eq!(
            parse("{}".as_bytes(), &mut 0),
            ParseResult::type_mismatch("object")
        );
    }

    #[test]
    fn type_mismatch_array() {
        assert_eq!(
            parse("[]".as_bytes(), &mut 0),
            ParseResult::type_mismatch("array")
        );
    }

    #[test]
    fn type_mismatch_number() {
        // if the first character is a decimal digit then the
        // parser assums that the value is of type number
        // and will skip the following bytes without validate
        // them until it found a possible end:
        // [",", "}", "]", " ", "\t", "\n", end_of_input]
        assert_eq!(
            parse("4sadqwd.asdqwe".as_bytes(), &mut 0),
            ParseResult::type_mismatch("number")
        );
    }

    #[test]
    fn syntax_err() {
        assert_eq!(
            parse("fcvsd".as_bytes(), &mut 0),
            ParseResult::SyntaxErr(SyntaxErr::unexpected_token("\"", "f".as_bytes(), &mut 0))
        );

        assert_eq!(
            parse("nula".as_bytes(), &mut 0),
            ParseResult::SyntaxErr(SyntaxErr::unexpected_token("\"", "n".as_bytes(), &mut 0))
        );

        assert_eq!(
            parse("truee".as_bytes(), &mut 0),
            ParseResult::SyntaxErr(SyntaxErr::unexpected_token("\"", "t".as_bytes(), &mut 0))
        );

        assert_eq!(
            parse("asda".as_bytes(), &mut 0),
            ParseResult::SyntaxErr(SyntaxErr::unexpected_token("\"", "a".as_bytes(), &mut 0))
        );

        assert_eq!(
            parse(r#""aswq"#.as_bytes(), &mut 0),
            ParseResult::SyntaxErr(SyntaxErr::unexpected_end(&mut 5))
        );
    }

    #[test]
    fn invalid_utf8_byte() {
        // minion byte must be greater than 127 not 17
        assert_eq!(
            parse(&[b'"', 192, 17, b'"'], &mut 0),
            ParseResult::syntax_err("invalid UTF-8 byte", &mut 2)
        );

        // leading byte must be covered by one of valid ranges
        assert_eq!(
            parse(&[b'"', 182, b'"'], &mut 0),
            ParseResult::syntax_err("invalid UTF-8 byte", &mut 1)
        );

        // must have extra byte before "
        assert_eq!(
            parse(&[b'"', 192, b'"'], &mut 0),
            ParseResult::syntax_err("invalid UTF-8 byte", &mut 2)
        );

        // must have extra byte before "
        assert_eq!(
            parse(&[b'"', 244, 128, b'"'], &mut 0),
            ParseResult::syntax_err("invalid UTF-8 byte", &mut 3)
        );
    }

    #[test]
    fn invalid_control_character() {
        assert_eq!(
            parse(r#""\h""#.as_bytes(), &mut 0),
            ParseResult::syntax_err("invalid control character", &mut 2)
        );
    }

    #[test]
    fn xss_sanitize() {
        let mut s = String::from("<h1>hello & nice \" ' \u{0000}</h1>");
        sanitize_xss(&mut s);
        assert_eq!(
            s,
            String::from("&lt;h1&gt;hello &amp; nice &#34; &#39; \u{FFFD}&lt;/h1&gt;")
        );
    }
}