babbel_json 0.2.0

Fast, modular JSON toolkit with streaming parsers, JSON Pointer (RFC 6901), and Merge Patch
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
//! JSON validation without allocation
//!
//! Provides fast validation of JSON syntax without building a Node tree.
//! Useful for rejecting invalid data before attempting full parsing.

use crate::io::traits::ISource;
use crate::parser::config::ParserConfig;
use crate::parser::constants::*;

/// Validates JSON syntax without allocating memory for nodes
///
/// This is faster than full parsing and uses minimal memory.
/// Useful for:
/// - Early rejection of invalid data
/// - Security checks before processing
/// - Bandwidth verification before transmission
///
/// # Arguments
/// * `source` - Source to read JSON from
/// * `config` - Parser configuration for depth/size limits
///
/// # Returns
/// * `Ok(())` if JSON is valid
/// * `Err(String)` with error message if invalid
///
/// # Examples
/// ```
/// use babbel_json::{validate_json, BufferSource, ParserConfig};
///
/// let json = br#"{"valid": true}"#;
/// let mut source = BufferSource::new(json);
/// let config = ParserConfig::new();
///
/// assert!(validate_json(&mut source, &config).is_ok());
/// ```
pub fn validate_json(source: &mut dyn ISource, config: &ParserConfig) -> Result<(), String> {
    let mut depth = 0;
    validate_value(source, config, &mut depth)?;
    skip_whitespace(source);
    if let Some(c) = source.current() {
        return Err(format!("Unexpected character: {}", c));
    }
    Ok(())
}

fn validate_value(
    source: &mut dyn ISource,
    config: &ParserConfig,
    depth: &mut usize,
) -> Result<(), String> {
    skip_whitespace(source);

    match source.current() {
        Some(OBJECT_START) => validate_object(source, config, depth),
        Some(ARRAY_START) => validate_array(source, config, depth),
        Some(QUOTE) => validate_string(source, config),
        Some('t') | Some('f') => validate_boolean(source),
        Some('n') => validate_null(source),
        Some('-') | Some('0'..='9') => validate_number(source),
        Some(c) => Err(format!("Unexpected character: {}", c)),
        None => Err("Unexpected end of input".to_string()),
    }
}

fn validate_object(
    source: &mut dyn ISource,
    config: &ParserConfig,
    depth: &mut usize,
) -> Result<(), String> {
    *depth += 1;
    if let Some(max_depth) = config.max_depth {
        if *depth > max_depth {
            return Err(format!("Maximum nesting depth of {} exceeded", max_depth));
        }
    }

    source.next(); // skip {
    skip_whitespace(source);

    let mut size = 0;

    // Empty object
    if source.current() == Some(OBJECT_END) {
        source.next();
        *depth -= 1;
        return Ok(());
    }

    loop {
        size += 1;
        if let Some(max_size) = config.max_object_size {
            if size > max_size {
                return Err(format!("Maximum object size of {} exceeded", max_size));
            }
        }

        // Expect key (string)
        skip_whitespace(source);
        if source.current() != Some(QUOTE) {
            return Err("Expected string key in object".to_string());
        }
        validate_string(source, config)?;

        // Expect colon
        skip_whitespace(source);
        if source.current() != Some(COLON) {
            return Err("Expected ':' after object key".to_string());
        }
        source.next();

        // Expect value
        validate_value(source, config, depth)?;

        // Check for comma or end
        skip_whitespace(source);
        match source.current() {
            Some(COMMA) => {
                source.next();
                skip_whitespace(source);
                // Check for trailing comma
                if source.current() == Some(OBJECT_END) {
                    return Err("Trailing comma in object".to_string());
                }
            }
            Some(OBJECT_END) => {
                source.next();
                *depth -= 1;
                return Ok(());
            }
            _ => return Err("Expected ',' or '}' in object".to_string()),
        }
    }
}

fn validate_array(
    source: &mut dyn ISource,
    config: &ParserConfig,
    depth: &mut usize,
) -> Result<(), String> {
    *depth += 1;
    if let Some(max_depth) = config.max_depth {
        if *depth > max_depth {
            return Err(format!("Maximum nesting depth of {} exceeded", max_depth));
        }
    }

    source.next(); // skip [
    skip_whitespace(source);

    let mut size = 0;

    // Empty array
    if source.current() == Some(ARRAY_END) {
        source.next();
        *depth -= 1;
        return Ok(());
    }

    loop {
        size += 1;
        if let Some(max_size) = config.max_array_size {
            if size > max_size {
                return Err(format!("Maximum array size of {} exceeded", max_size));
            }
        }

        validate_value(source, config, depth)?;

        skip_whitespace(source);
        match source.current() {
            Some(COMMA) => {
                source.next();
                skip_whitespace(source);
                // Check for trailing comma
                if source.current() == Some(ARRAY_END) {
                    return Err("Trailing comma in array".to_string());
                }
            }
            Some(ARRAY_END) => {
                source.next();
                *depth -= 1;
                return Ok(());
            }
            _ => return Err("Expected ',' or ']' in array".to_string()),
        }
    }
}

fn validate_string(source: &mut dyn ISource, config: &ParserConfig) -> Result<(), String> {
    source.next(); // skip opening quote
    let mut length = 0;

    while let Some(c) = source.current() {
        if let Some(max_len) = config.max_string_length {
            if length >= max_len {
                return Err(format!(
                    "Maximum string length of {} bytes exceeded",
                    max_len
                ));
            }
        }

        match c {
            QUOTE => {
                source.next();
                return Ok(());
            }
            BACKSLASH => {
                source.next();
                match source.current() {
                    Some('"') | Some('\\') | Some('/') | Some('b') | Some('f') | Some('n')
                    | Some('r') | Some('t') => {
                        source.next();
                        length += 1;
                    }
                    Some('u') => {
                        // Validate unicode escape
                        source.next();
                        let mut hex = [0u8; 4];
                        for i in 0..4 {
                            match source.current() {
                                Some(d) if d.is_ascii_hexdigit() => {
                                    hex[i] = d as u8;
                                    source.next();
                                }
                                _ => return Err("Invalid unicode escape".to_string()),
                            }
                        }
                        if let Ok(hex_str) = core::str::from_utf8(&hex) {
                            if let Ok(code) = u32::from_str_radix(hex_str, 16) {
                                if (0xD800..=0xDBFF).contains(&code) {
                                    if source.current() == Some('\\') {
                                        source.next();
                                        if source.current() == Some('u') {
                                            source.next();
                                            let mut low_hex = [0u8; 4];
                                            for i in 0..4 {
                                                match source.current() {
                                                    Some(d) if d.is_ascii_hexdigit() => {
                                                        low_hex[i] = d as u8;
                                                        source.next();
                                                    }
                                                    _ => return Err("Invalid unicode escape".to_string()),
                                                }
                                            }
                                            if let Ok(low_hex_str) = core::str::from_utf8(&low_hex) {
                                                if let Ok(low_code) = u32::from_str_radix(low_hex_str, 16) {
                                                    if !(0xDC00..=0xDFFF).contains(&low_code) {
                                                        return Err("Invalid surrogate pair".to_string());
                                                    }
                                                } else {
                                                    return Err("Invalid unicode escape".to_string());
                                                }
                                            } else {
                                                return Err("Invalid unicode escape".to_string());
                                            }
                                        } else {
                                            return Err("Expected \\u after high surrogate".to_string());
                                        }
                                    } else {
                                        return Err("Unpaired high surrogate".to_string());
                                    }
                                } else if (0xDC00..=0xDFFF).contains(&code) {
                                    return Err("Unpaired low surrogate".to_string());
                                }
                            } else {
                                return Err("Invalid unicode escape".to_string());
                            }
                        } else {
                            return Err("Invalid unicode escape".to_string());
                        }
                        length += 1;
                    }
                    _ => return Err("Invalid escape sequence".to_string()),
                }
            }
            c if (c as u32) < 0x20 => {
                return Err("Unescaped control character in string".to_string());
            }
            _ => {
                source.next();
                length += 1;
            }
        }
    }

    Err("Unterminated string".to_string())
}

fn validate_number(source: &mut dyn ISource) -> Result<(), String> {
    // Handle negative
    if source.current() == Some('-') {
        source.next();
    }

    // Require at least one digit
    if !matches!(source.current(), Some('0'..='9')) {
        return Err("Expected digit in number".to_string());
    }

    // Integer part
    if source.current() == Some('0') {
        source.next();
        // Leading zero must be followed by . or e/E or end
        match source.current() {
            Some('.') | Some('e') | Some('E') | None => {}
            Some(c) if c.is_whitespace() || c == ',' || c == ']' || c == '}' => {}
            _ => return Err("Invalid number: leading zero".to_string()),
        }
    } else {
        while matches!(source.current(), Some('0'..='9')) {
            source.next();
        }
    }

    // Fractional part
    if source.current() == Some(DECIMAL_POINT) {
        source.next();
        if !matches!(source.current(), Some('0'..='9')) {
            return Err("Expected digit after decimal point".to_string());
        }
        while matches!(source.current(), Some('0'..='9')) {
            source.next();
        }
    }

    // Exponent part
    if matches!(source.current(), Some('e') | Some('E')) {
        source.next();
        if matches!(source.current(), Some('+') | Some('-')) {
            source.next();
        }
        if !matches!(source.current(), Some('0'..='9')) {
            return Err("Expected digit in exponent".to_string());
        }
        while matches!(source.current(), Some('0'..='9')) {
            source.next();
        }
    }

    Ok(())
}

fn validate_boolean(source: &mut dyn ISource) -> Result<(), String> {
    match source.current() {
        Some('t') => {
            for expected in ['t', 'r', 'u', 'e'] {
                if source.current() != Some(expected) {
                    return Err("Invalid boolean: expected 'true'".to_string());
                }
                source.next();
            }
            Ok(())
        }
        Some('f') => {
            for expected in ['f', 'a', 'l', 's', 'e'] {
                if source.current() != Some(expected) {
                    return Err("Invalid boolean: expected 'false'".to_string());
                }
                source.next();
            }
            Ok(())
        }
        _ => Err("Invalid boolean".to_string()),
    }
}

fn validate_null(source: &mut dyn ISource) -> Result<(), String> {
    for expected in ['n', 'u', 'l', 'l'] {
        if source.current() != Some(expected) {
            return Err("Invalid null value".to_string());
        }
        source.next();
    }
    Ok(())
}

#[inline]
fn skip_whitespace(source: &mut dyn ISource) {
    while let Some(c) = source.current() {
        if is_json_whitespace(c) {
            source.next();
        } else {
            break;
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::io::sources::buffer::Buffer;

    #[test]
    fn test_validate_simple_object() {
        let json = br#"{"key": "value"}"#;
        let mut source = Buffer::new(json);
        let config = ParserConfig::new();

        assert!(validate_json(&mut source, &config).is_ok());
    }

    #[test]
    fn test_validate_nested() {
        let json = br#"{"a": {"b": {"c": 123}}}"#;
        let mut source = Buffer::new(json);
        let config = ParserConfig::new();

        assert!(validate_json(&mut source, &config).is_ok());
    }

    #[test]
    fn test_validate_array() {
        let json = br#"[1, 2, 3, "test", true, null]"#;
        let mut source = Buffer::new(json);
        let config = ParserConfig::new();

        assert!(validate_json(&mut source, &config).is_ok());
    }

    #[test]
    fn test_validate_invalid_json() {
        let json = br#"{"key": }"#;
        let mut source = Buffer::new(json);
        let config = ParserConfig::new();

        assert!(validate_json(&mut source, &config).is_err());
    }

    #[test]
    fn test_validate_depth_limit() {
        let json = br#"{"a":{"b":{"c":{"d":1}}}}"#;
        let mut source = Buffer::new(json);
        let config = ParserConfig::new().with_max_depth(Some(3));

        assert!(validate_json(&mut source, &config).is_err());
    }

    #[test]
    fn test_validate_numbers() {
        let test_cases: Vec<(&[u8], bool)> = vec![
            (b"123", true),
            (b"-456", true),
            (b"3.14", true),
            (b"1e10", true),
            (b"2.5e-3", true),
            (b"01", false),  // Leading zero
            (b"-.5", false), // No digit before decimal
        ];

        for (json, should_pass) in test_cases {
            let mut source = Buffer::new(json);
            let config = ParserConfig::new();
            let result = validate_json(&mut source, &config);

            if should_pass {
                assert!(result.is_ok(), "Expected {:?} to be valid", json);
            } else {
                assert!(result.is_err(), "Expected {:?} to be invalid", json);
            }
        }
    }

    // Primitive value validation
    #[test]
    fn test_validate_true() {
        let mut source = Buffer::new(b"true");
        assert!(validate_json(&mut source, &ParserConfig::new()).is_ok());
    }

    #[test]
    fn test_validate_false() {
        let mut source = Buffer::new(b"false");
        assert!(validate_json(&mut source, &ParserConfig::new()).is_ok());
    }

    #[test]
    fn test_validate_null() {
        let mut source = Buffer::new(b"null");
        assert!(validate_json(&mut source, &ParserConfig::new()).is_ok());
    }

    #[test]
    fn test_validate_string() {
        let mut source = Buffer::new(b"\"hello world\"");
        assert!(validate_json(&mut source, &ParserConfig::new()).is_ok());
    }

    #[test]
    fn test_validate_empty_string() {
        let mut source = Buffer::new(b"\"\"");
        assert!(validate_json(&mut source, &ParserConfig::new()).is_ok());
    }

    #[test]
    fn test_validate_empty_object() {
        let mut source = Buffer::new(b"{}");
        assert!(validate_json(&mut source, &ParserConfig::new()).is_ok());
    }

    #[test]
    fn test_validate_empty_array() {
        let mut source = Buffer::new(b"[]");
        assert!(validate_json(&mut source, &ParserConfig::new()).is_ok());
    }

    // String escape sequences
    #[test]
    fn test_validate_string_escape_sequences() {
        for escaped in [
            br#""\"""# as &[u8],
            br#""\\""#,
            br#""\/""#,
            b"\"\\b\"",
            b"\"\\f\"",
            b"\"\\n\"",
            b"\"\\r\"",
            b"\"\\t\"",
        ] {
            let mut source = Buffer::new(escaped);
            assert!(
                validate_json(&mut source, &ParserConfig::new()).is_ok(),
                "Expected escape {:?} to be valid",
                escaped
            );
        }
    }

    #[test]
    fn test_validate_unicode_escape() {
        let mut source = Buffer::new(b"\"\\u0041\"");
        assert!(validate_json(&mut source, &ParserConfig::new()).is_ok());
    }

    #[test]
    fn test_validate_invalid_unicode_escape_short() {
        let mut source = Buffer::new(b"\"\\u00\"");
        assert!(validate_json(&mut source, &ParserConfig::new()).is_err());
    }

    #[test]
    fn test_validate_invalid_unicode_escape_non_hex() {
        let mut source = Buffer::new(b"\"\\u00zz\"");
        assert!(validate_json(&mut source, &ParserConfig::new()).is_err());
    }

    #[test]
    fn test_validate_invalid_escape_char() {
        let mut source = Buffer::new(b"\"\\x\"");
        assert!(validate_json(&mut source, &ParserConfig::new()).is_err());
    }

    #[test]
    fn test_validate_unterminated_string() {
        let mut source = Buffer::new(b"\"unterminated");
        assert!(validate_json(&mut source, &ParserConfig::new()).is_err());
    }

    // Number edge cases
    #[test]
    fn test_validate_zero() {
        let mut source = Buffer::new(b"0");
        assert!(validate_json(&mut source, &ParserConfig::new()).is_ok());
    }

    #[test]
    fn test_validate_negative_float() {
        let mut source = Buffer::new(b"-3.14");
        assert!(validate_json(&mut source, &ParserConfig::new()).is_ok());
    }

    #[test]
    fn test_validate_exponent_uppercase() {
        let mut source = Buffer::new(b"1E5");
        assert!(validate_json(&mut source, &ParserConfig::new()).is_ok());
    }

    #[test]
    fn test_validate_exponent_with_plus() {
        let mut source = Buffer::new(b"1.5e+3");
        assert!(validate_json(&mut source, &ParserConfig::new()).is_ok());
    }

    #[test]
    fn test_validate_minus_only_invalid() {
        let mut source = Buffer::new(b"-");
        assert!(validate_json(&mut source, &ParserConfig::new()).is_err());
    }

    #[test]
    fn test_validate_decimal_no_trailing_digit_invalid() {
        let mut source = Buffer::new(b"1.");
        assert!(validate_json(&mut source, &ParserConfig::new()).is_err());
    }

    #[test]
    fn test_validate_exponent_no_digit_invalid() {
        let mut source = Buffer::new(b"1e");
        assert!(validate_json(&mut source, &ParserConfig::new()).is_err());
    }

    // Object structure errors
    #[test]
    fn test_validate_trailing_comma_object() {
        let mut source = Buffer::new(b"{\"a\":1,}");
        assert!(validate_json(&mut source, &ParserConfig::new()).is_err());
    }

    #[test]
    fn test_validate_missing_colon() {
        let mut source = Buffer::new(b"{\"k\" 1}");
        assert!(validate_json(&mut source, &ParserConfig::new()).is_err());
    }

    #[test]
    fn test_validate_non_string_key() {
        let mut source = Buffer::new(b"{1: \"val\"}");
        assert!(validate_json(&mut source, &ParserConfig::new()).is_err());
    }

    #[test]
    fn test_validate_missing_object_close() {
        let mut source = Buffer::new(b"{\"k\":1");
        assert!(validate_json(&mut source, &ParserConfig::new()).is_err());
    }

    // Array structure errors
    #[test]
    fn test_validate_trailing_comma_array() {
        let mut source = Buffer::new(b"[1,2,]");
        assert!(validate_json(&mut source, &ParserConfig::new()).is_err());
    }

    #[test]
    fn test_validate_missing_array_close() {
        let mut source = Buffer::new(b"[1,2,3");
        assert!(validate_json(&mut source, &ParserConfig::new()).is_err());
    }

    #[test]
    fn test_validate_empty_input() {
        let mut source = Buffer::new(b"");
        assert!(validate_json(&mut source, &ParserConfig::new()).is_err());
    }

    #[test]
    fn test_validate_unexpected_char() {
        let mut source = Buffer::new(b"@");
        assert!(validate_json(&mut source, &ParserConfig::new()).is_err());
    }

    // Whitespace handling
    #[test]
    fn test_validate_whitespace_around_value() {
        let mut source = Buffer::new(b"  \t\n  42  ");
        assert!(validate_json(&mut source, &ParserConfig::new()).is_ok());
    }

    #[test]
    fn test_validate_whitespace_in_object() {
        let mut source = Buffer::new(b"{ \"key\" : \"value\" }");
        assert!(validate_json(&mut source, &ParserConfig::new()).is_ok());
    }

    #[test]
    fn test_validate_whitespace_in_array() {
        let mut source = Buffer::new(b"[ 1 , 2 , 3 ]");
        assert!(validate_json(&mut source, &ParserConfig::new()).is_ok());
    }

    // Config limit tests
    #[test]
    fn test_validate_depth_exactly_at_limit() {
        // depth 2: outer object (depth 1), inner value parsed at depth 1 incremented
        let json = b"{\"a\":{\"b\":1}}";
        let mut source = Buffer::new(json);
        let config = ParserConfig::new().with_max_depth(Some(2));
        assert!(validate_json(&mut source, &config).is_ok());
    }

    #[test]
    fn test_validate_depth_exceeded_error_message() {
        let json = b"[[[[1]]]]";
        let mut source = Buffer::new(json);
        let config = ParserConfig::new().with_max_depth(Some(2));
        let err = validate_json(&mut source, &config).unwrap_err();
        assert!(err.contains("depth"));
    }

    #[test]
    fn test_validate_string_length_exceeded() {
        let mut source = Buffer::new(b"\"toolong\"");
        let config = ParserConfig::new().with_max_string_length(Some(4));
        let err = validate_json(&mut source, &config).unwrap_err();
        assert!(err.contains("string length"));
    }

    #[test]
    fn test_validate_string_length_at_limit() {
        // Limit of 4: "abcd" has 4 chars — check passes before reading closing quote
        let mut source = Buffer::new(b"\"abc\"");
        let config = ParserConfig::new().with_max_string_length(Some(4));
        assert!(validate_json(&mut source, &config).is_ok());
    }

    #[test]
    fn test_validate_array_size_exceeded() {
        let mut source = Buffer::new(b"[1,2,3,4]");
        let config = ParserConfig::new().with_max_array_size(Some(3));
        let err = validate_json(&mut source, &config).unwrap_err();
        assert!(err.contains("array size"));
    }

    #[test]
    fn test_validate_array_size_at_limit() {
        let mut source = Buffer::new(b"[1,2,3]");
        let config = ParserConfig::new().with_max_array_size(Some(3));
        assert!(validate_json(&mut source, &config).is_ok());
    }

    #[test]
    fn test_validate_object_size_exceeded() {
        let mut source = Buffer::new(b"{\"a\":1,\"b\":2,\"c\":3}");
        let config = ParserConfig::new().with_max_object_size(Some(2));
        let err = validate_json(&mut source, &config).unwrap_err();
        assert!(err.contains("object size"));
    }

    #[test]
    fn test_validate_object_size_at_limit() {
        let mut source = Buffer::new(b"{\"a\":1,\"b\":2}");
        let config = ParserConfig::new().with_max_object_size(Some(2));
        assert!(validate_json(&mut source, &config).is_ok());
    }

    #[test]
    fn test_validate_unlimited_config_deep_nesting() {
        let json = b"[[[[[[[[[[1]]]]]]]]]]";
        let mut source = Buffer::new(json);
        assert!(validate_json(&mut source, &ParserConfig::unlimited()).is_ok());
    }

    #[test]
    fn test_validate_strict_config_rejects_deep() {
        let json = b"[[[[[[[[[[[[[[[[[[[[1]]]]]]]]]]]]]]]]]]]]";
        let mut source = Buffer::new(json);
        assert!(validate_json(&mut source, &ParserConfig::strict()).is_err());
    }

    // Complex / mixed structures
    #[test]
    fn test_validate_nested_arrays_and_objects() {
        let json = br#"{"items":[{"id":1},{"id":2}],"count":2}"#;
        let mut source = Buffer::new(json);
        assert!(validate_json(&mut source, &ParserConfig::new()).is_ok());
    }

    #[test]
    fn test_validate_all_types_in_array() {
        let json = b"[true, false, null, 42, 3.14, \"str\", {}, []]";
        let mut source = Buffer::new(json);
        assert!(validate_json(&mut source, &ParserConfig::new()).is_ok());
    }

    #[test]
    fn test_validate_invalid_true_typo() {
        let mut source = Buffer::new(b"treu");
        assert!(validate_json(&mut source, &ParserConfig::new()).is_err());
    }

    #[test]
    fn test_validate_invalid_false_typo() {
        let mut source = Buffer::new(b"flase");
        assert!(validate_json(&mut source, &ParserConfig::new()).is_err());
    }

    #[test]
    fn test_validate_invalid_null_typo() {
        let mut source = Buffer::new(b"nul");
        assert!(validate_json(&mut source, &ParserConfig::new()).is_err());
    }
}