trivet 3.1.0

The trivet Parser Library
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
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
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
// Trivet
// Copyright (c) 2025 by Stacy Prowell.  All rights reserved.
// https://gitlab.com/binary-tools/trivet

//! Define a simple JSON parser and JSON printer.
//!
//! - [`JSON`]: The JSON structure
//! - [`JSONParser`]: The JSON parser
//!
//! A simplified version of the parser code is presented in *The Trivet Parsing
//! Library*, which is available under the `doc` folder of the distribution.
//!
//! JavaScript Object Notation (JSON) is a moderately simple format for encoding data.
//! You can find a detailed description of it [here](https://www.json.org/json-en.html).
//!
//! JSON is officially defined by the [ECMA-404 JSON Data Interchange Syntax][JSON].
//!
//!
//! [JSON]: https://www.json.org/json-en.html
//! [JSON]: https://www.ecma-international.org/publications-and-standards/standards/ecma-404/

use crate::errors::syntax_error;
use crate::errors::unexpected_character_error;
use crate::errors::ParseResult;
use crate::numbers::NumberParser;
use crate::strings;
use crate::strings::StringParser;
use crate::strings::StringStandard;
use crate::Parser;
use std::collections::HashMap;
use std::fmt::Display;
use std::fmt::Formatter;
use std::mem;

/// Define the JSON structures.
///
/// ```rust
/// use trivet::parsers::json::JSON;
/// use trivet::parsers::json::json_to_string;
///
/// let jarray = JSON::Array(vec![JSON::Number(1.0), JSON::String("fred".to_string())]);
/// let jstr = json_to_string(&jarray);
/// assert_eq!(jstr, r#"[
///     1,
///     "fred"
/// ]"#);
/// ```
#[derive(Debug, PartialEq, Clone, Default)]
pub enum JSON {
    /// A JSON object maps strings to other JSON values.
    Object(HashMap<String, JSON>),
    /// A JSON array is a sequence of JSON values.
    Array(Vec<JSON>),
    /// A string value.
    String(String),
    /// A number value.  All numbers are floating point values.
    Number(f64),
    /// A Boolean value.
    Boolean(bool),
    /// The null value.
    #[default]
    Null,
}

impl Display for JSON {
    fn fmt(&self, form: &mut Formatter) -> std::fmt::Result {
        write!(form, "{}", json_to_string(self))
    }
}

/// Given a JSON value, encode it as a string and return it.  This encodes it as a JSON
/// string according to the JSON standard.
///
/// This method sorts the keys using `sort_unstable` to provide a consistent ordering.
///
/// ```rust
/// use trivet::parse_from_string;
/// use trivet::parsers::json::JSON;
/// use trivet::parsers::json::JSONParser;
/// use std::collections::HashMap;
///
/// let map = HashMap::from([
///     ("New Castle".to_string(), JSON::Number(575494.0)),
///     ("Sussex".to_string(), JSON::Number(255956.0)),
///     ("Kent".to_string(), JSON::Number(186946.0))
/// ]);
/// let jobj1 = JSON::Object(map);
///
/// let mut parser = parse_from_string(r#"
///     {   "New Castle": 575494,
///         "Sussex": 255956,
///         "Kent": 186946
///     }
/// "#);
/// let jobj2 = JSONParser::new().parse_value_ws(&mut parser).unwrap();
///
/// assert_eq!(jobj1, jobj2);
///
/// ```
pub fn json_to_string(json: &JSON) -> String {
    let mut strenc = strings::StringEncoder::new();
    strenc.set(strings::StringStandard::JSON);
    json_to_string_worker(json, &strenc, 0)
}

/// Re-entrant recursive worker to print a JSON string.
fn json_to_string_worker(json: &JSON, strenc: &strings::StringEncoder, indent: usize) -> String {
    match json {
        // Encode a JSON object.  This has an opening curly brace, then a series of
        // key, value pairs with the key given as a string and the value being another
        // JSON value.  The key and value are separated by a colon.  Finally, there is
        // a closing curly brace.  This is all mandatory in the format.
        JSON::Object(map) => {
            let mut first = true;
            let mut buf = "{\n".to_string();
            let mut keys: Vec<_> = map.keys().collect();
            keys.sort_unstable();
            buf.extend(std::iter::repeat("    ").take(indent + 1));
            for key in keys {
                if first {
                    first = false;
                } else {
                    buf.push(',');
                    buf.push('\n');
                    buf.extend(std::iter::repeat("    ").take(indent + 1));
                }
                let value = map.get(key).unwrap();
                buf.push_str(&encode_string(key, strenc));
                buf.push(':');
                buf.push(' ');
                buf.push_str(&json_to_string_worker(value, strenc, indent + 1));
            }
            buf.push('\n');
            buf.extend(std::iter::repeat("    ").take(indent));
            buf.push('}');
            buf
        }

        // Encode a JSON array.  A JSON array starts with an opening square bracket and
        // is then a series of comma-separated values, ending with a closing square
        // bracket.
        JSON::Array(array) => {
            let mut first = true;
            let mut buf = "[\n".to_string();
            for _ in 0..indent + 1 {
                buf.push_str("    ");
            }
            for value in array {
                if first {
                    first = false;
                } else {
                    buf.push(',');
                    buf.push('\n');
                    for _ in 0..indent + 1 {
                        buf.push_str("    ");
                    }
                }
                buf.push_str(&json_to_string_worker(value, strenc, indent + 1));
            }
            buf.push('\n');
            for _ in 0..indent {
                buf.push_str("    ");
            }
            buf.push(']');
            buf
        }

        JSON::String(value) => encode_string(value, strenc),
        JSON::Number(value) => value.to_string(),
        JSON::Boolean(value) => value.to_string(),
        JSON::Null => "null".to_string(),
    }
}

/// Encode a JSON string.
fn encode_string(string: &str, strenc: &strings::StringEncoder) -> String {
    let mut buf = "\"".to_string();
    buf.push_str(&strenc.encode(string));
    buf.push('"');
    buf
}

/// The current parsing context.
#[derive(Debug)]
enum JSONContext {
    /// At the top of the parse.
    Top,
    /// In an array.
    InArray,
    /// In an object.
    InObject,
}

/// Define a parser for JSON values.  An instance of this can only be used to parse one
/// JSON stream at a time.  To parse multiple streams simultaneously, you need to create
/// multiple instances.
///
/// The important methods are `parse_value_ws` and `parse_value_unstandard_ws`.  See those
/// methods for more information.
pub struct JSONParser {
    /// A stack holding prior context information.
    context_stack: Vec<JSONContext>,
    /// A stack for array contexts.
    array_stack: Vec<Vec<JSON>>,
    /// A stack for object contexts.
    object_stack: Vec<HashMap<String, JSON>>,
    /// A stack for keys.
    key_stack: Vec<String>,
    /// The current parsing context.
    context: JSONContext,
    /// The current map.
    map: HashMap<String, JSON>,
    /// The current array.
    array: Vec<JSON>,
    /// The key for an enclosing object.
    key: String,
    /// Our own number parser.
    numpar: NumberParser,
    /// Our own string parser.
    strpar: StringParser,
}

impl JSONParser {
    /// Make a new JSON parser instance.
    pub fn new() -> Self {
        // JSON uses its own parsing rules for numbers, comments, and strings.  In order to correctly
        // parse JSON, we have to override these rules in the parse we have been given, and then restore
        // them later.  This is tricky.

        // Get correct component parsers.
        let mut strpar = StringParser::new();
        strpar.set(StringStandard::JSON);
        let mut numpar = NumberParser::new();
        numpar.settings.permit_binary = false;
        numpar.settings.permit_hexadecimal = false;
        numpar.settings.permit_octal = false;
        numpar.settings.permit_underscores = false;
        numpar.settings.decimal_only_floats = true;
        numpar.settings.permit_plus = false;
        numpar.settings.permit_leading_zero = false;
        numpar.settings.permit_empty_whole = false;
        numpar.settings.permit_empty_fraction = false;

        // Make the object.
        Self {
            context_stack: Vec::with_capacity(10),
            array_stack: Vec::with_capacity(10),
            object_stack: Vec::with_capacity(10),
            key_stack: Vec::with_capacity(10),
            context: JSONContext::Top,
            map: HashMap::new(),
            array: vec![],
            key: String::new(),
            numpar,
            strpar,
        }
    }

    /// Reset the parser by cleaning the context to start a new parse.  This
    /// may be slightly cheaper than building a new parser.
    fn reset(&mut self) {
        self.context_stack.clear();
        self.array_stack.clear();
        self.object_stack.clear();
        self.key_stack.clear();
        self.map.clear();
        self.array.clear();
        self.key = String::new();
        self.context = JSONContext::Top;
    }

    /// Push the current context onto the stack and move to the new context.
    fn push(&mut self, new_context: JSONContext) {
        match self.context {
            JSONContext::Top => {}
            JSONContext::InArray => {
                let array = mem::take(&mut self.array);
                self.array_stack.push(array);
            }
            JSONContext::InObject => {
                let map = mem::take(&mut self.map);
                let key = mem::take(&mut self.key);
                self.map = HashMap::new();
                self.key = String::new();
                self.key_stack.push(key);
                self.object_stack.push(map);
            }
        }
        self.context_stack
            .push(mem::replace(&mut self.context, new_context));
    }

    /// Pop the prior context off the stack.
    #[cfg(not(tarpaulin_include))] // Ignore this because we shouldn't be able to cover the internal error conditions.
    fn pop(&mut self) {
        self.context = match self.context_stack.pop() {
            None => return,
            Some(value) => value,
        };
        match self.context {
            JSONContext::Top => {}
            JSONContext::InArray => {
                // The array stack being empty is an internal error, and we want to panic.
                self.array = match self.array_stack.pop() {
                    None => panic!("Internal error: array stack is empty!"),
                    Some(value) => value,
                };
            }
            JSONContext::InObject => {
                // The object stack being empty is an internal error, and we want to panic.
                self.map = match self.object_stack.pop() {
                    None => panic!("Internal error: object stack is empty!"),
                    Some(value) => value,
                };
                self.key = match self.key_stack.pop() {
                    None => panic!("Internal error: key stack is empty!"),
                    Some(value) => value,
                };
            }
        }
    }

    /// Parse a JSON value.  On entry whitespace is consumed.  Trailing whitespace is consumed on
    /// successful exit.
    ///
    /// This operation temporarily replaces the string, number, and whitespace parsers to conform
    /// to the JSON standard.  If you do not want that (but want to use your own configured parsers
    /// and flaut the JSON standard) then you should use the (intentionally) awkwardly-named
    /// `parse_value_unstandard_ws`.
    ///
    ///
    /// ```rust
    /// use trivet::parse_from_string;
    /// use trivet::parsers::json::JSON;
    /// use trivet::parsers::json::JSONParser;
    ///
    /// let mut parser = parse_from_string(r#"
    ///
    ///     {
    ///         "Wilmington city":71569,
    ///         "Dover city":38594,
    ///         "Newark city":30453,
    ///         "Middletown town":24698
    ///     }
    ///
    /// "#);
    /// let mut jp = JSONParser::new();
    /// let jobj = jp.parse_value_ws(&mut parser).unwrap();
    ///
    /// if let JSON::Object(map) = jobj {
    ///     assert_eq!(map.get("Newark city").unwrap(), &JSON::Number(30453.0));
    /// } else {
    ///     panic!("Expected an object!");
    /// }
    /// ```
    pub fn parse_value_ws(&mut self, parser: &mut Parser) -> ParseResult<JSON> {
        // Install new settings.
        let allow_comments = parser.parse_comments;
        parser.parse_comments = false;
        let old_strpar = parser.replace_string_parser(self.strpar.clone());
        let old_numpar = parser.replace_number_parser(self.numpar.clone());
        let old_wspace = parser
            .borrow_core()
            .replace_whitespace_test(Box::new(|ch| [' ', '\n', '\r', '\t'].contains(&ch)));

        // Perform the parse.
        parser.consume_ws();
        let result = self.parse_value_worker_ws(parser);

        // Restore the prior settings.
        parser.parse_comments = allow_comments;
        let _ = parser.replace_string_parser(old_strpar);
        let _ = parser.replace_number_parser(old_numpar);
        let _ = parser.borrow_core().replace_whitespace_test(old_wspace);

        // Reset the context.
        self.reset();

        // Done.
        result
    }

    /// Parse a JSON value.  On entry whitespace is consumed.  Trailing whitespace is consumed on
    /// successful exit.
    ///
    /// This operation uses the currently-configured string, number, and whitespace parsers of the
    /// provided parser.  These may not conform to the JSON standard.  If you need to conform to
    /// the standard, use `parser_value_ws` instead.
    ///
    /// Please note that if you use `parser_value_ws` first it will replace the configured component
    /// parsers.  For that reason you should use either this method or `parser_value_ws`, but not
    /// try to use both interchangeably.
    ///
    /// ```rust
    /// use trivet::parse_from_string;
    /// use trivet::parsers::json::JSON;
    /// use trivet::parsers::json::JSONParser;
    ///
    /// let mut parser = parse_from_string(r#"
    ///
    ///     {
    ///         "Wilmington city":71569,
    ///         "Dover city":38594,
    ///         "Newark city":30453,
    ///         "Middletown town":24698
    ///     }
    ///
    /// "#);
    /// let mut jp = JSONParser::new();
    /// let jobj = jp.parse_value_unstandard_ws(&mut parser).unwrap();
    ///
    /// if let JSON::Object(map) = jobj {
    ///     assert_eq!(map.get("Newark city").unwrap(), &JSON::Number(30453.0));
    /// } else {
    ///     panic!("Expected an object!");
    /// }
    /// ```
    pub fn parse_value_unstandard_ws(&mut self, parser: &mut Parser) -> ParseResult<JSON> {
        // Reset the context.
        self.reset();

        // Perform the parse.
        parser.consume_ws();
        self.parse_value_worker_ws(parser)
    }

    /// Perform the work of parsing a JSON value.
    fn parse_value_worker_ws(&mut self, parser: &mut Parser) -> ParseResult<JSON> {
        let mut optvalue = Some(JSON::Null);
        let mut need_value = true;
        loop {
            // We arrive here expecting to parse a value.  The following things can happen.
            //
            // First, we can get a value.  If we are in the top context, return it.  If we are not
            // in the top context, handle it appropriately and continue.
            //
            // Second, we can get an error.  This causes the method to return immediately, so we don't
            // have to worry about that.
            //
            // Third, we can get None.  If that happens, then we just go around the loop again because
            // we don't yet have a value.
            //
            // After each iteration all trailing whitespace is consumed.  This is handled in each arm
            // of the match.
            if need_value {
                if parser.is_at_eof() {
                    return Err(syntax_error(parser.loc(), "Unexpected end of file."));
                }
                optvalue = match parser.peek() {
                    '[' => {
                        parser.consume();
                        parser.consume_ws();

                        // If this is an empty array, yield that.
                        // Otherwise push the current context onto the stack and then require a value (go around
                        // the loop again).
                        if parser.peek_and_consume_ws(']') {
                            Some(JSON::Array(vec![]))
                        } else {
                            self.push(JSONContext::InArray);
                            None
                        }
                    }
                    ']' => {
                        // This is an error.  Generate the correct error message depending on the context.
                        return Err(syntax_error(
                            parser.loc(),
                            "Found a closing square bracket but expected a value that must be provided here."
                        ));
                    }
                    '{' => {
                        parser.consume();
                        parser.consume_ws();

                        // If this is an empty object, yield that.
                        // Otherwise push the current context onto the stack, read a key and colon, and then
                        // require a value (go around the loop again).
                        if parser.peek_and_consume_ws('}') {
                            Some(JSON::Object(HashMap::new()))
                        } else {
                            self.push(JSONContext::InObject);
                            // The next thing must be a string, so parse that now.
                            if parser.peek_and_consume('"') {
                                self.key = parser.parse_string_until_delimiter_ws('"')?;
                                if parser.peek_and_consume_ws(':') {
                                    // Great; we are correct.  Go around again to get a value.
                                    None
                                } else {
                                    // Missing colon.
                                    return Err(syntax_error(
                                        parser.loc(),
                                        "Missing a colon following the key string.",
                                    ));
                                }
                            } else {
                                // Key needs to be a string.
                                return Err(syntax_error(
                                    parser.loc(),
                                    "A string is required here for an object key, but was not found."
                                ));
                            }
                        }
                    }
                    '}' => {
                        // This is an error.  Generate the correct error message depending on the context.
                        return Err(syntax_error(
                            parser.loc(),
                            "Found a closing brace but expected a value that must be provided here."
                        ));
                    }
                    ':' => {
                        // This is an error.  Generate the correct error message depending on the context.
                        return Err(syntax_error(
                            parser.loc(),
                            "Found a colon but expected a value that must be provided here.",
                        ));
                    }
                    ',' => {
                        // This is an error.  Generate the correct error message depending on the context.
                        return Err(syntax_error(
                            parser.loc(),
                            "Found a comma but expected a value that must be provided here.",
                        ));
                    }
                    '"' => {
                        parser.consume();

                        // Parse a string and yield that.
                        Some(JSON::String(parser.parse_string_until_delimiter_ws('"')?))
                    }
                    'n' if parser.peek_and_consume_chars_ws(&['n', 'u', 'l', 'l']) => {
                        // Yield a null.
                        Some(JSON::Null)
                    }
                    't' if parser.peek_and_consume_chars_ws(&['t', 'r', 'u', 'e']) => {
                        // Yield a true.
                        Some(JSON::Boolean(true))
                    }
                    'f' if parser.peek_and_consume_chars_ws(&['f', 'a', 'l', 's', 'e']) => {
                        // Yield a false.
                        Some(JSON::Boolean(false))
                    }
                    ch if ch == '-' || ch.is_ascii_digit() => {
                        // Parse a number and yield that.
                        Some(JSON::Number(parser.parse_f64_decimal_ws()?))
                    }
                    ch => {
                        // This is an error.  Generate an unexpected character error.
                        return Err(unexpected_character_error(parser.loc(), "a JSON value", ch));
                    }
                };
            }

            // If we do not yet have a value, go around again.
            if optvalue.is_none() {
                continue;
            }

            // Reset need value.
            need_value = true;

            // Decide what to do with this value based on the context.
            let value = optvalue.take().unwrap();
            match self.context {
                JSONContext::Top => {
                    // This is the final value.  Return it.
                    return Ok(value);
                }
                JSONContext::InArray => {
                    // Add this to the array.
                    self.array.push(value);

                    // Look for a comma.
                    if parser.peek_and_consume_ws(',') {
                        // We go around again and look for a new value to add to the array.
                        continue;
                    } else if parser.peek_and_consume_ws(']') {
                        // This is the end of the array.  We need to pop and then yield this value.
                        let array = mem::take(&mut self.array);
                        optvalue = Some(JSON::Array(array));
                        need_value = false;
                        self.pop();
                        continue;
                    } else {
                        // This is an error.
                        return Err(unexpected_character_error(
                            parser.loc(),
                            "a comma and the next value or a closing bracket",
                            parser.peek(),
                        ));
                    }
                }
                JSONContext::InObject => {
                    // Add this mapping to the object.
                    self.map.insert(mem::take(&mut self.key), value);

                    // Look for a comma.
                    if parser.peek_and_consume_ws(',') {
                        // The next thing must be a string, so parse that now.
                        if parser.peek_and_consume('"') {
                            self.key = parser.parse_string_until_delimiter_ws('"')?;
                            if parser.peek_and_consume_ws(':') {
                                // Great; we are correct.  Go around again to get a value.
                                continue;
                            } else {
                                // Missing colon.
                                return Err(syntax_error(
                                    parser.loc(),
                                    "Missing a colon following the key string.",
                                ));
                            }
                        } else {
                            // Key needs to be a string.
                            return Err(syntax_error(
                                parser.loc(),
                                "A string is required here for an object key, but was not found.",
                            ));
                        }
                    } else if parser.peek_and_consume_ws('}') {
                        // This is the end of the object.  We need to pop and then yield this value.
                        let map = mem::take(&mut self.map);
                        optvalue = Some(JSON::Object(map));
                        need_value = false;
                        self.pop();
                        continue;
                    } else {
                        // This is an error.
                        return Err(unexpected_character_error(
                            parser.loc(),
                            "a comma and the next key and value pair or a closing brace",
                            parser.peek(),
                        ));
                    }
                }
            };
        }
    }
}

impl Default for JSONParser {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod test {
    use std::collections::HashMap;

    use crate::{
        parse_from_string, parsers::json::json_to_string, parsers::json::JSONParser,
        parsers::json::JSON,
    };

    #[test]
    fn simple_test() {
        let mut jp = JSONParser::new();
        let tests = &[
            ("", ""),
            ("{", ""),
            ("{}", "{\n    \n}"),
            ("-154.2", "-154.2"),
            ("0", "0"),
            (r#""This is a string.""#, r#""This is a string.""#),
            (
                r#""\nThis has \"stringiness\"""#,
                r#""\nThis has \"stringiness\"""#,
            ),
            ("true", "true"),
            ("false", "false"),
            ("null", "null"),
            (
                "[true, true, false, true, false]",
                "[\n    true,\n    true,\n    false,\n    true,\n    false\n]",
            ),
            (r#"{"Jimmy": "McGill"}"#, "{\n    \"Jimmy\": \"McGill\"\n}"),
            ("[5 6]", ""),
            ("{\"tom\" \"jones\"}", ""),
            ("{\"tom\":\"jones\" \"glen\":\"campbell\"", ""),
            ("{joe:\"satriani\"}", ""),
            ("{\"joe\" \"satriani\"}", ""),
            ("{\"joe\":\"dart\",joe:\"satriani\"}", ""),
            ("{\"joe\":\"dart\",\"joe\" \"satriani\"}", ""),
            (
                "{\"tom\":[\"jones\",\"glen\",{\"campbell\":1.0}]}",
                "{\n    \"tom\": [\n        \"jones\",\n        \"glen\",\n        {\n            \"campbell\": 1\n        }\n    ]\n}"
            ),
            ("{\"tom\":}", ""),
            ("{\"tom\"}", ""),
            ("[,]", ""),
            ("[:]", ""),
            ("[}", ""),
            ("{]", ""),
            ("-12.5", "-12.5"),
            ("^", ""),
            ("[]", "[\n    \n]"),
            ("{}", "{\n    \n}"),
            ("{\"a\":}", ""),
            ("[\"a\",]", ""),
            ("{\"a\":-12}", "{\n    \"a\": -12\n}"),
            ("[-12,-12]", "[\n    -12,\n    -12\n]"),
        ];
        for (in_str, out_str) in tests {
            println!("Testing {}", in_str);
            let mut parser = parse_from_string(in_str);
            if out_str.is_empty() {
                assert!(jp.parse_value_ws(&mut parser).is_err());
            } else {
                let result = json_to_string(&jp.parse_value_ws(&mut parser).unwrap());
                println!("Result {}", &result);
                assert_eq!(result, *out_str);
            }
        }
    }

    #[test]
    fn unstandard_test() {
        println!();
        let mut std_jp = JSONParser::default();
        let mut unstd_jp = JSONParser::new();
        // Test cases are triples.
        // The input string, the parsed value for unstandard, the parsed value for standard.
        // Use empty strings to indicate that the value should fail parsing.
        let tests = &[
            ("1.21", "1.21", "1.21"),
            ("{\"gigawats\":1.21}", "{\n    \"gigawats\": 1.21\n}", "{\n    \"gigawats\": 1.21\n}"),
            ("\"Cory Wong\"", "\"Cory Wong\"", "\"Cory Wong\""),
            (
                "[\"High On You\", \"Diana\", \"Perfect Way\", \"1000 Julys\"]",
                "[\n    \"High On You\",\n    \"Diana\",\n    \"Perfect Way\",\n    \"1000 Julys\"\n]",
                "[\n    \"High On You\",\n    \"Diana\",\n    \"Perfect Way\",\n    \"1000 Julys\"\n]",
            ),
            ("\"Städ\"", "\"Städ\"", "\"Städ\""),
            ("//Comment\n12", "12", ""),
            ("\"St\\U{Combining Diaeresis}ad\"", "\"St\\\\U{Combining Diaeresis}ad\"", ""),
            ("\"St.\\u{20}Lucia\"", "\"St. Lucia\"", ""),
            ("\"St.\\x20Lucia\"", "\"St. Lucia\"", ""),
            ("5e3", "5000", "5000"),
            ("5e", "", ""),
        ];
        for (in_str, unstd_str, std_str) in tests {
            println!("Testing {}", in_str);
            let mut parser = parse_from_string(in_str);
            if unstd_str.is_empty() {
                assert!(unstd_jp.parse_value_unstandard_ws(&mut parser).is_err());
            } else {
                let result =
                    json_to_string(&unstd_jp.parse_value_unstandard_ws(&mut parser).unwrap());
                println!("Unstandard Result {}", &result);
                assert_eq!(result, *unstd_str);
            }
            let mut parser = parse_from_string(in_str);
            if std_str.is_empty() {
                assert!(std_jp.parse_value_ws(&mut parser).is_err());
            } else {
                let result = json_to_string(&std_jp.parse_value_ws(&mut parser).unwrap());
                println!("Standard Result {}", &result);
                assert_eq!(result, *std_str);
            }
        }
    }

    #[test]
    fn object_test() {
        println!();
        let mut jp = JSONParser::new();
        let json = r#"{
            "A": {
                "name": ["Wexler", "Kim"],
                "actor": ["Seehorn", "Rhea"],
                "prison": false,
                "age": 34
            },
            "B": {
                "name": ["McGill", "Jimmy"],
                "actor": ["Odenkirk", "Bob"],
                "prison": true,
                "age": 41
            }
        }"#;
        let json2 = JSON::Object(HashMap::from([
            (
                "B".to_string(),
                JSON::Object(HashMap::from([
                    (
                        "name".to_string(),
                        JSON::Array(vec![
                            JSON::String("McGill".to_string()),
                            JSON::String("Jimmy".to_string()),
                        ]),
                    ),
                    (
                        "actor".to_string(),
                        JSON::Array(vec![
                            JSON::String("Odenkirk".to_string()),
                            JSON::String("Bob".to_string()),
                        ]),
                    ),
                    ("prison".to_string(), JSON::Boolean(true)),
                    ("age".to_string(), JSON::Number(41.0)),
                ])),
            ),
            (
                "A".to_string(),
                JSON::Object(HashMap::from([
                    (
                        "name".to_string(),
                        JSON::Array(vec![
                            JSON::String("Wexler".to_string()),
                            JSON::String("Kim".to_string()),
                        ]),
                    ),
                    (
                        "actor".to_string(),
                        JSON::Array(vec![
                            JSON::String("Seehorn".to_string()),
                            JSON::String("Rhea".to_string()),
                        ]),
                    ),
                    ("prison".to_string(), JSON::Boolean(false)),
                    ("age".to_string(), JSON::Number(34.0)),
                ])),
            ),
        ]));
        let mut parser = parse_from_string(json);
        let value1 = jp.parse_value_ws(&mut parser).unwrap();
        parser = parse_from_string(&json_to_string(&value1));
        let value2 = jp.parse_value_ws(&mut parser).unwrap();
        parser = parse_from_string(&json_to_string(&value2));
        let value3 = jp.parse_value_ws(&mut parser).unwrap();
        assert_eq!(value1, value2);
        assert_eq!(value2, value3);
        assert_eq!(value3, json2);
    }
}