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
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
// microjson - a no_std json parser in rust
// Copyright (C) 2021  Robert Spencer
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.

#![doc = include_str!("../README.md")]
#![no_std]

/// Errors while parsing JSON
///
/// Due to the "scan once" philosophy of this crate, errors can either be returned when first
/// constructing a [`JSONValue`] or when trying to read it using one of the accessors.
#[derive(Copy, Clone, PartialEq, Eq)]
pub enum JSONParsingError {
    /// Attempt to parse an object that is not an array as an array
    CannotParseArray,
    /// Attempt to parse an object that is not a float as a float
    CannotParseFloat,
    /// Attempt to parse an object that is not an integer as an integer
    CannotParseInteger,
    /// Attempt to parse an object that is not an object as an object
    CannotParseObject,
    /// Attempt to parse an object that is not a string as an string
    CannotParseString,
    /// The key is not present in the object
    KeyNotFound,
    /// There was an unexpected token in the input stream
    UnexpectedToken,
    /// The input stream terminated while scanning a type
    EndOfStream,
}

impl core::fmt::Debug for JSONParsingError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match *self {
            Self::KeyNotFound => {
                write!(f, "Key not found")
            }
            Self::EndOfStream => {
                write!(f, "Stream ended while parsing JSON")
            }
            Self::UnexpectedToken => {
                write!(f, "Unexpected token")
            }
            Self::CannotParseArray => {
                write!(f, "Error parsing array")
            }
            Self::CannotParseFloat => {
                write!(f, "Error parsing float")
            }
            Self::CannotParseInteger => {
                write!(f, "Error parsing integer")
            }
            Self::CannotParseString => {
                write!(f, "Error parsing string")
            }
            Self::CannotParseObject => {
                write!(f, "Error parsing object")
            }
        }
    }
}

/// Denotes the different types of values JSON objects can have
///
/// ### Numbers
/// Both floats and integers have a value type of [`JSONValueType::Number`].
///
/// ### Example
/// ```
/// # use microjson::*;
/// let json_value = JSONValue::parse("[1,2,3]").unwrap();
/// assert_eq!(json_value.value_type, JSONValueType::Array);
/// ```
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub enum JSONValueType {
    String,
    Number,
    Object,
    Array,
    Bool,
    Null,
}

#[derive(Copy, Clone, Debug)]
pub struct JSONValue<'a> {
    contents: &'a str,
    pub value_type: JSONValueType,
}

fn trim_start(value: &str) -> (&str, usize) {
    let value_len = value.len();
    // NOTE(robert): This trims from the "start" which may be different for RTL languages.  What do
    // we do for JSON?
    let value = value.trim_start();
    (value, value_len - value.len())
}

impl<'a> JSONValue<'a> {
    pub fn parse(contents: &'a str) -> Result<JSONValue, JSONParsingError> {
        let (contents, _) = trim_start(contents);
        let value_type = JSONValue::peek_value_type(contents)?;
        Ok(JSONValue {
            contents,
            value_type,
        })
    }

    /// Guess the type of the JSON variable serialised in the input string
    ///
    /// This function will never give the _wrong_ type, though it may return a type even if the
    /// input string is not well formed.
    fn peek_value_type(contents: &'a str) -> Result<JSONValueType, JSONParsingError> {
        // The contents must be trimmed
        match contents.chars().next() {
            Some('{') => Ok(JSONValueType::Object),
            Some('[') => Ok(JSONValueType::Array),
            Some('"') => Ok(JSONValueType::String),
            Some('0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' | '-') => {
                Ok(JSONValueType::Number)
            }
            Some('t' | 'f') => Ok(JSONValueType::Bool),
            Some('n') => Ok(JSONValueType::Null),
            _ => Err(JSONParsingError::UnexpectedToken),
        }
    }

    /// Confirm that this [`JSONValue`] is proper JSON
    ///
    /// This will scan through the entire JSON and confirm that it is properly formatted.
    /// See also [`JSONValue::parse_and_verify`]
    ///
    /// ## Example
    /// ```
    /// # use microjson::JSONValue;
    /// let value = JSONValue::parse("[1,{},\"foo\"]").unwrap();
    /// assert!(value.verify().is_ok());
    ///
    /// let value = JSONValue::parse("[,,{\"").unwrap(); // This will not error
    /// assert!(value.verify().is_err());
    /// ```
    pub fn verify(&self) -> Result<(), JSONParsingError> {
        JSONValue::parse_with_len(self.contents)?;
        Ok(())
    }

    pub fn parse_and_verify(contents: &'a str) -> Result<JSONValue, JSONParsingError> {
        let value = JSONValue::parse(contents)?;
        value.verify()?;
        Ok(value)
    }

    fn parse_with_len(contents: &'a str) -> Result<(JSONValue, usize), JSONParsingError> {
        let (contents, whitespace_trimmed) = trim_start(contents);
        let (value_type, value_len) = match contents.chars().next() {
            Some('{') => {
                let mut value_len = 1;
                let mut contents = &contents[value_len..];
                while !contents.is_empty() {
                    if contents.trim_start().starts_with('}') {
                        value_len += trim_start(contents).1 + 1;
                        break;
                    }
                    let (item, item_len) = JSONValue::parse_with_len(contents)?;
                    if item.value_type != JSONValueType::String {
                        return Err(JSONParsingError::CannotParseString);
                    }
                    let (new_contents, whitespace) = trim_start(&contents[item_len..]);
                    contents = new_contents;
                    value_len += item_len + whitespace;
                    if contents.is_empty() {
                        return Err(JSONParsingError::EndOfStream);
                    } else if contents.starts_with(':') {
                        value_len += 1;
                        contents = &contents[1..];
                    } else {
                        return Err(JSONParsingError::UnexpectedToken);
                    }

                    let (_, item_len) = JSONValue::parse_with_len(contents)?;
                    let (new_contents, whitespace) = trim_start(&contents[item_len..]);
                    contents = new_contents;
                    value_len += item_len + whitespace;
                    if contents.is_empty() {
                        return Err(JSONParsingError::EndOfStream);
                    } else if contents.starts_with(',') {
                        value_len += 1;
                        contents = &contents[1..];
                    } else if !contents.starts_with('}') {
                        return Err(JSONParsingError::UnexpectedToken);
                    }
                }
                (JSONValueType::Object, value_len)
            }
            Some('[') => {
                let mut value_len = 1;
                let mut contents = &contents[value_len..];
                while !contents.is_empty() {
                    if contents.trim_start().starts_with(']') {
                        value_len += trim_start(contents).1 + 1;
                        break;
                    }
                    let (_, item_len) = JSONValue::parse_with_len(contents)?;
                    let (new_contents, whitespace) = trim_start(&contents[item_len..]);
                    contents = new_contents;
                    value_len += item_len + whitespace;
                    if contents.is_empty() {
                        return Err(JSONParsingError::EndOfStream);
                    } else if contents.starts_with(',') {
                        value_len += 1;
                        contents = &contents[1..];
                    } else if !contents.starts_with(']') {
                        return Err(JSONParsingError::UnexpectedToken);
                    }
                }
                (JSONValueType::Array, value_len)
            }
            Some('"') => {
                let mut value_len = 1;
                let mut is_escaped = false;
                for chr in contents[1..].chars() {
                    value_len += chr.len_utf8();
                    if chr == '"' && !is_escaped {
                        break;
                    } else if chr == '\\' {
                        is_escaped = !is_escaped;
                    } else {
                        is_escaped = false;
                    }
                }
                (JSONValueType::String, value_len)
            }
            Some('0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' | '-') => {
                let mut value_len = 0;
                for chr in contents.chars() {
                    match chr {
                        '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' | '-' | 'e'
                        | 'E' | '.' => {
                            value_len += chr.len_utf8();
                        }
                        _ => {
                            break;
                        }
                    }
                }
                (JSONValueType::Number, value_len)
            }
            Some('t') => {
                if &contents[..4] != "true" {
                    return Err(JSONParsingError::UnexpectedToken);
                }
                (JSONValueType::Bool, 4)
            }
            Some('f') => {
                if &contents[..5] != "false" {
                    return Err(JSONParsingError::UnexpectedToken);
                }
                (JSONValueType::Bool, 5)
            }
            Some('n') => {
                if &contents[..4] != "null" {
                    return Err(JSONParsingError::UnexpectedToken);
                }
                (JSONValueType::Null, 4)
            }
            _ => {
                return Err(JSONParsingError::UnexpectedToken);
            }
        };
        Ok((
            JSONValue {
                contents: &contents[..value_len],
                value_type,
            },
            whitespace_trimmed + value_len,
        ))
    }

    /// Reads the [`JSONValue`] as an integer
    ///
    /// If the type is not a [`JSONValueType::Number`], returns an `Err`.
    ///
    /// ### Example
    /// ```
    /// # use microjson::{JSONValue, JSONParsingError};
    /// let value = JSONValue::parse("-24").unwrap();
    /// assert_eq!(value.read_integer(), Ok(-24));
    ///
    /// let value = JSONValue::parse("5pi").unwrap();
    /// assert_eq!(value.read_integer(), Err(JSONParsingError::CannotParseInteger));
    /// ```
    pub fn read_integer(&self) -> Result<isize, JSONParsingError> {
        if self.value_type != JSONValueType::Number {
            return Err(JSONParsingError::CannotParseInteger);
        }
        let contents = self.contents.trim_end();
        str::parse(contents).map_err(|_| JSONParsingError::CannotParseInteger)
    }

    /// Reads the [`JSONValue`] as a float
    ///
    /// If the type is not a [`JSONValueType::Number`], returns an `Err`.
    ///
    /// ### Example
    /// ```
    /// # use microjson::{JSONValue, JSONParsingError};
    /// let value = JSONValue::parse("2.4").unwrap();
    /// assert_eq!(value.read_float(), Ok(2.4));
    ///
    /// let value = JSONValue::parse("5pi").unwrap();
    /// assert_eq!(value.read_float(), Err(JSONParsingError::CannotParseFloat));
    /// ```
    pub fn read_float(&self) -> Result<f32, JSONParsingError> {
        if self.value_type != JSONValueType::Number {
            return Err(JSONParsingError::CannotParseFloat);
        }
        let contents = self.contents.trim_end();
        str::parse(contents).map_err(|_| JSONParsingError::CannotParseFloat)
    }

    /// Read the [`JSONValue`] as a string
    ///
    /// This returns an unescaped string (actually a slice into the underlying bytes). If you need
    /// escape sequences to be handled, use [`JSONValue::iter_string`].
    ///
    /// ## Example
    /// ```
    /// # use microjson::JSONValue;
    /// let value = JSONValue::parse("\"this is a string\"").unwrap();
    /// assert_eq!(value.read_string(), Ok("this is a string"));
    /// ```
    pub fn read_string(&self) -> Result<&str, JSONParsingError> {
        let (_, length) = JSONValue::parse_with_len(self.contents)?;
        if self.value_type != JSONValueType::String {
            return Err(JSONParsingError::CannotParseString);
        }
        Ok(&self.contents[1..length - 1])
    }

    /// Constructs an iterator over this array value
    ///
    /// If the value is not an [`JSONValueType::Array`], returns an error.
    pub fn iter_array(&self) -> Result<JSONArrayIterator<'a>, JSONParsingError> {
        if self.value_type != JSONValueType::Array {
            return Err(JSONParsingError::CannotParseArray);
        }
        Ok(JSONArrayIterator {
            contents: &self.contents[1..],
        })
    }

    /// Constructs an iterator over this string
    ///
    /// If the value is not an [`JSONValueType::String`], returns an error.
    ///
    /// The iterator returns [`Result<char, JSONParsingError>`]s and handles escape sequences.
    /// You can convert this into a `Result<String, _>` using `collect`.
    ///
    /// ### Example
    /// ```
    /// # use microjson::JSONValue;
    /// let value = JSONValue::parse(r#" "\u27FC This is a string with unicode \u27FB""#).unwrap();
    /// let string : Result<String, _> = value.iter_string().unwrap().collect::<Result<String, _>>();
    /// assert_eq!(string.unwrap(), "⟼ This is a string with unicode ⟻")
    /// ```
    pub fn iter_string(&self) -> Result<EscapedStringIterator<'a>, JSONParsingError> {
        if self.value_type != JSONValueType::String {
            return Err(JSONParsingError::CannotParseString);
        }
        Ok(EscapedStringIterator {
            contents: self.contents[1..].chars(),
            done: false,
        })
    }

    /// Constructs an iterator over this object
    ///
    /// If the value is not an [`JSONValueType::Object`], returns an error.
    pub fn iter_object(&self) -> Result<JSONObjectIterator<'a>, JSONParsingError> {
        if self.value_type != JSONValueType::Object {
            return Err(JSONParsingError::CannotParseObject);
        }
        Ok(JSONObjectIterator {
            contents: &self.contents[1..],
        })
    }

    /// Searches this object for a key and returns it's value
    ///
    /// Like the function [`Iterator::nth`], this searches linearly through all the keys in the
    /// object to find the desired one. If parsing the entire object in an arbitrary order, then,
    /// prefer using [`JSONValue::iter_object`].
    ///
    /// Will return `Err(JSONParsingError::KeyNotFound)` if the key is not present.
    pub fn get_key_value(&self, key: &str) -> Result<JSONValue, JSONParsingError> {
        self.iter_object()?
            .find(|item| matches!(item, Ok((k, _)) if k == &key))
            .map(|item| item.unwrap().1)
            .ok_or(JSONParsingError::KeyNotFound)
    }
}

/// An iterator through a JSON object
///
/// Usually constructed with [`JSONValue::iter_object`].
///
/// The iterator items are `Result<(key, value), JSONParsingError>`, but the key is not escaped
pub struct JSONObjectIterator<'a> {
    contents: &'a str,
}

impl<'a> Iterator for JSONObjectIterator<'a> {
    type Item = Result<(&'a str, JSONValue<'a>), JSONParsingError>;

    fn next(&mut self) -> Option<Self::Item> {
        self.contents = self.contents.trim_start();
        if self.contents.is_empty() {
            None
        } else {
            if !self.contents.starts_with('\"') {
                self.contents = &self.contents[..0];
                return None;
            }
            // We expect this to be a string value for the key
            match JSONValue::parse_with_len(self.contents) {
                Ok((_, key_len)) => {
                    let this_key = &self.contents[1..key_len - 1];
                    self.contents = &self.contents[key_len..].trim_start()[1..];

                    match JSONValue::parse_with_len(self.contents) {
                        Ok((this_value, value_len)) => {
                            self.contents = &self.contents[value_len..].trim_start();
                            if !self.contents.is_empty() {
                                self.contents = &self.contents[1..];
                            }
                            Some(Ok((this_key, this_value)))
                        }
                        Err(e) => {
                            self.contents = &self.contents[..0];
                            Some(Err(e))
                        }
                    }
                }
                Err(e) => {
                    self.contents = &self.contents[..0];
                    Some(Err(e))
                }
            }
        }
    }
}

/// An iterator through a JSON array value
///
/// Usually constructed with [`JSONValue::iter_array`].
pub struct JSONArrayIterator<'a> {
    contents: &'a str,
}

impl<'a> Iterator for JSONArrayIterator<'a> {
    type Item = JSONValue<'a>;

    fn next(&mut self) -> Option<Self::Item> {
        match JSONValue::parse_with_len(self.contents) {
            Ok((value, value_len)) => {
                self.contents = &self.contents[value_len..].trim_start()[1..];
                Some(value)
            }
            _ => None,
        }
    }
}

/// Iterator over a JSON-escaped string
///
/// See [`JSONValue::iter_string`] for further documentation.
pub struct EscapedStringIterator<'a> {
    contents: core::str::Chars<'a>,
    done: bool,
}

impl<'a> Iterator for EscapedStringIterator<'a> {
    type Item = Result<char, JSONParsingError>;

    fn next(&mut self) -> Option<Self::Item> {
        if self.done {
            None
        } else {
            let chr = self.contents.next();
            match chr {
                Some('\\') => {
                    let chr = self.contents.next();
                    match chr {
                        Some('"' | '\\' | '/') => chr.map(Ok),
                        Some('b') => Some(Ok('\x08')),
                        Some('f') => Some(Ok('\x0c')),
                        Some('n') => Some(Ok('\n')),
                        Some('t') => Some(Ok('\t')),
                        Some('r') => Some(Ok('\r')),
                        Some('u') => {
                            let mut get_digit = || {
                                self.contents
                                    .next()
                                    .ok_or(JSONParsingError::CannotParseString)?
                                    .to_digit(16)
                                    .ok_or(JSONParsingError::CannotParseString)
                            };
                            let mut parse_unicode = || {
                                let code = [get_digit()?, get_digit()?, get_digit()?, get_digit()?];
                                let code =
                                    (code[0] << 12) | (code[1] << 8) | (code[2] << 4) | code[3];
                                char::from_u32(code).ok_or(JSONParsingError::CannotParseString)
                            };
                            match parse_unicode() {
                                Ok(chr) => Some(Ok(chr)),
                                Err(e) => {
                                    self.done = true;
                                    Some(Err(e))
                                }
                            }
                        }
                        Some(_) => {
                            self.done = true;
                            Some(Err(JSONParsingError::CannotParseString))
                        }
                        None => None,
                    }
                }
                Some('"') => {
                    self.done = true;
                    None
                }
                None => {
                    self.done = true;
                    Some(Err(JSONParsingError::CannotParseString))
                }
                _ => chr.map(Ok),
            }
        }
    }
}

#[cfg(test)]
mod test {
    use super::*;
    extern crate std;

    #[test]
    fn integer() {
        let (value, value_len) = JSONValue::parse_with_len("42").unwrap();
        assert_eq!(value.value_type, JSONValueType::Number);
        assert_eq!(value_len, 2);
        assert_eq!(value.read_integer(), Ok(42));
        assert!(value.read_string().is_err());

        assert_eq!(JSONValue::parse("-98").unwrap().read_integer(), Ok(-98));
        assert_eq!(JSONValue::parse("-99 ").unwrap().read_integer(), Ok(-99));
    }

    #[test]
    fn float() {
        let (value, value_len) = JSONValue::parse_with_len("3.141592").unwrap();
        assert_eq!(value.value_type, JSONValueType::Number);
        assert_eq!(value_len, "3.141592".len());
        assert_eq!(
            value.read_integer(),
            Err(JSONParsingError::CannotParseInteger)
        );
        assert_eq!(
            value.read_string(),
            Err(JSONParsingError::CannotParseString)
        );
        assert!((value.read_float().unwrap() - 3.141592).abs() < 0.0001);

        assert_eq!(
            JSONValue::parse("-3.43w").unwrap().read_float(),
            Err(JSONParsingError::CannotParseFloat)
        );
    }

    #[test]
    fn string() {
        let (value, value_len) = JSONValue::parse_with_len("\"hello world\"").unwrap();
        assert_eq!(value.value_type, JSONValueType::String);
        assert_eq!(value_len, "\"hello world\"".len());
        assert!(value.read_integer().is_err());
        assert_eq!(value.read_string(), Ok("hello world"));

        let value = JSONValue::parse("\"hello world\"   ").unwrap();
        assert_eq!(value.read_string(), Ok("hello world"));
    }

    #[test]
    fn array() {
        let (value, value_len) = JSONValue::parse_with_len("[1,2,3]").unwrap();
        assert_eq!(value.value_type, JSONValueType::Array);
        assert_eq!(value_len, "[1,2,3]".len());
        let (value, value_len) = JSONValue::parse_with_len("[]").unwrap();
        assert_eq!(value.value_type, JSONValueType::Array);
        assert_eq!(value_len, "[]".len());
        let (value, value_len) = JSONValue::parse_with_len("  [\n  ]").unwrap();
        assert_eq!(value.value_type, JSONValueType::Array);
        assert_eq!(value_len, "  [\n  ]".len());
        let (value, value_len) = JSONValue::parse_with_len("[1  ,  2\t,\r3\n]").unwrap();
        assert_eq!(value.value_type, JSONValueType::Array);
        assert_eq!(value_len, "[1  ,  2\t,\r3\n]".len());

        assert!(value.read_integer().is_err());
        assert!(value.read_string().is_err());
        assert_eq!(
            value.iter_array().unwrap().nth(0).unwrap().read_integer(),
            Ok(1)
        );
        assert_eq!(
            value.iter_array().unwrap().nth(1).unwrap().read_integer(),
            Ok(2)
        );
        assert_eq!(
            value.iter_array().unwrap().nth(2).unwrap().read_integer(),
            Ok(3)
        );
    }

    #[test]
    fn object() {
        let input = "{
        \"id\": 0,
        \"name\": \"Ginger Fuller\"}";
        let (value, value_len) = JSONValue::parse_with_len(input).unwrap();
        assert_eq!(value.value_type, JSONValueType::Object);
        assert_eq!(value_len, input.len());

        assert!(value.read_integer().is_err());
        assert!(value.read_string().is_err());
        assert_eq!(value.get_key_value("id").unwrap().read_integer(), Ok(0));
        assert_eq!(
            value.get_key_value("name").unwrap().read_string(),
            Ok("Ginger Fuller")
        );
        assert_eq!(
            value.get_key_value("surname").err(),
            Some(JSONParsingError::KeyNotFound)
        );

        assert!(JSONValue::parse("{\"foo\":[{}]}").is_ok());
        assert!(JSONValue::parse("[{\"foo\":{}}]").is_ok());
    }
    #[test]

    fn this_broke_once() {
        assert!(JSONValue::parse(
            r##"
[{"a":{"email":"d@"},"m":"#20\n\n.\n"}]
    "##
        )
        .is_ok());
    }

    #[test]
    fn integer_whitespace() {
        let (value, value_len) = JSONValue::parse_with_len("  42	").unwrap();
        assert_eq!(value.value_type, JSONValueType::Number);
        assert_eq!(value_len, "  42".len());
        let (value, value_len) = JSONValue::parse_with_len("\n 42\r").unwrap();
        assert_eq!(value.value_type, JSONValueType::Number);
        assert_eq!(value_len, "\n 42".len());
    }

    #[test]
    fn string_whitespace() {
        let (value, value_len) = JSONValue::parse_with_len("  \"foo me a bar\"	").unwrap();
        assert_eq!(value.value_type, JSONValueType::String);
        assert_eq!(value_len, "  \"foo me a bar\"".len());
        let (value, value_len) = JSONValue::parse_with_len("\n \"a bar\n I said.\"\r").unwrap();
        assert_eq!(value.value_type, JSONValueType::String);
        assert_eq!(value_len, "\n \"a bar\n I said.\"".len());
    }

    #[test]
    fn peeking_value_type() {
        assert_eq!(JSONValue::peek_value_type("123"), Ok(JSONValueType::Number));
        assert_eq!(
            JSONValue::peek_value_type("12.3"),
            Ok(JSONValueType::Number)
        );
        assert_eq!(
            JSONValue::peek_value_type("12.3e10"),
            Ok(JSONValueType::Number)
        );
        assert_eq!(JSONValue::peek_value_type("-3"), Ok(JSONValueType::Number));
        assert_eq!(
            JSONValue::peek_value_type("-3.5"),
            Ok(JSONValueType::Number)
        );
        assert_eq!(JSONValue::peek_value_type("null"), Ok(JSONValueType::Null));
        assert_eq!(JSONValue::peek_value_type("true"), Ok(JSONValueType::Bool));
        assert_eq!(JSONValue::peek_value_type("false"), Ok(JSONValueType::Bool));
        assert_eq!(JSONValue::peek_value_type("[]"), Ok(JSONValueType::Array));
        assert_eq!(JSONValue::peek_value_type("[12]"), Ok(JSONValueType::Array));
        assert_eq!(
            JSONValue::peek_value_type("[1,2]"),
            Ok(JSONValueType::Array)
        );
        assert_eq!(JSONValue::peek_value_type("[[]]"), Ok(JSONValueType::Array));
        assert_eq!(
            JSONValue::peek_value_type("\"foo\""),
            Ok(JSONValueType::String)
        );
        assert_eq!(JSONValue::peek_value_type("{}"), Ok(JSONValueType::Object));
        assert_eq!(
            JSONValue::peek_value_type("{\"a\":2}"),
            Ok(JSONValueType::Object)
        );
        assert!(JSONValue::peek_value_type("<").is_err());
        assert!(JSONValue::peek_value_type("bar").is_err());
    }

    #[test]
    fn verifying() {
        assert!(JSONValue::parse_and_verify(" 123 ").is_ok());
        assert!(JSONValue::parse_and_verify("[123]").is_ok());
        assert!(JSONValue::parse_and_verify("\"foo\"").is_ok());
    }

    #[test]
    fn string_iterator() {
        let try_parse_string = |s| {
            JSONValue::parse(s)
                .unwrap()
                .iter_string()
                .unwrap()
                .collect::<Result<std::string::String, _>>()
        };
        let value = try_parse_string("\"I have a dream\"").unwrap();
        assert_eq!(value, "I have a dream");

        let value = try_parse_string("\"\\\"I have a dream\\\"\"").unwrap();
        assert_eq!(value, "\"I have a dream\"");

        let value = try_parse_string(r#" "\"I\n\thave\b\fa\\dream\/\"\u00a3" "#).unwrap();
        assert_eq!(value, "\"I\n\thave\x08\x0ca\\dream/\"£");

        let value = try_parse_string(r#" " "#);
        assert!(matches!(value, Err(JSONParsingError::CannotParseString)));
        let value = try_parse_string(r#" "foo\" "#);
        assert!(matches!(value, Err(JSONParsingError::CannotParseString)));
        let value = try_parse_string(r#" "foo\" "#);
        assert!(matches!(value, Err(JSONParsingError::CannotParseString)));
        let value = try_parse_string(r#" "Odd escape: \?" "#);
        assert!(matches!(value, Err(JSONParsingError::CannotParseString)));
        let value = try_parse_string(r#" "\uwxyz" "#);
        assert!(matches!(value, Err(JSONParsingError::CannotParseString)));
        let value = try_parse_string(r#" "\uxyz" "#);
        assert!(matches!(value, Err(JSONParsingError::CannotParseString)));
        // This is not a single character codepoint under utf-16
        let value = try_parse_string(r#" "\ud834" "#);
        assert!(matches!(value, Err(JSONParsingError::CannotParseString)));
    }

    #[test]
    fn object_iterator() {
        let json_value = JSONValue::parse("{\"foo\" : [], \"bar\":{\"baz\": 2}}").unwrap();
        let keys = ["foo", "bar"];
        for (item, expected_key) in json_value.iter_object().unwrap().zip(&keys) {
            assert_eq!(item.unwrap().0, *expected_key);
        }
    }
}