succinctly 0.7.0

High-performance succinct data structures for Rust
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
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
//! Strict JSON validator according to RFC 8259.
//!
//! This module provides a fast, scalar JSON validator that performs strict
//! validation according to RFC 8259. Unlike the semi-indexing parser, this
//! validator checks all aspects of JSON validity including:
//!
//! - Structural syntax (braces, brackets, colons, commas)
//! - String escape sequences (including surrogate pairs)
//! - Number format (no leading zeros, no leading plus, etc.)
//! - UTF-8 validity
//! - No trailing content after root value
//!
//! # Example
//!
//! ```
//! use succinctly::json::validate::{Validator, ValidationError};
//!
//! let input = br#"{"name": "Alice", "age": 30}"#;
//! let mut validator = Validator::new(input);
//! assert!(validator.validate().is_ok());
//!
//! let invalid = br#"{"name": "Alice",}"#; // trailing comma
//! let mut validator = Validator::new(invalid);
//! assert!(validator.validate().is_err());
//! ```

#[cfg(not(test))]
use alloc::string::String;

use core::fmt;

/// Position information for error reporting.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Position {
    /// Byte offset (0-indexed).
    pub offset: usize,
    /// Line number (1-indexed).
    pub line: usize,
    /// Column number (1-indexed, in bytes not characters).
    pub column: usize,
}

impl fmt::Display for Position {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "line {}, column {} (offset {})",
            self.line, self.column, self.offset
        )
    }
}

/// Kinds of validation errors.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ValidationErrorKind {
    // Structural errors
    /// Expected a specific character but found something else.
    UnexpectedCharacter { expected: &'static str, found: char },
    /// Unexpected end of input.
    UnexpectedEof { expected: &'static str },
    /// Extra content after the root JSON value.
    TrailingContent,

    // String errors
    /// String was not closed before end of input.
    UnclosedString,
    /// Invalid escape sequence in string.
    InvalidEscape { sequence: char },
    /// Invalid unicode escape sequence.
    InvalidUnicodeEscape { reason: &'static str },
    /// Unpaired surrogate in unicode escape.
    UnpairedSurrogate { codepoint: u16 },
    /// Unescaped control character in string.
    ControlCharacter { byte: u8 },

    // Number errors
    /// Number has leading zero (e.g., 01, 007).
    LeadingZero,
    /// Number has leading plus sign.
    LeadingPlus,
    /// Invalid number format.
    InvalidNumber { reason: &'static str },

    // Other errors
    /// Invalid keyword (not null, true, or false).
    InvalidKeyword { found: String },
    /// Invalid UTF-8 sequence.
    InvalidUtf8,
}

impl fmt::Display for ValidationErrorKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::UnexpectedCharacter { expected, found } => {
                write!(f, "expected {}, found {:?}", expected, found)
            }
            Self::UnexpectedEof { expected } => {
                write!(f, "unexpected end of input, expected {}", expected)
            }
            Self::TrailingContent => write!(f, "trailing content after JSON value"),
            Self::UnclosedString => write!(f, "unclosed string"),
            Self::InvalidEscape { sequence } => {
                write!(f, "invalid escape sequence '\\{}'", sequence)
            }
            Self::InvalidUnicodeEscape { reason } => {
                write!(f, "invalid unicode escape: {}", reason)
            }
            Self::UnpairedSurrogate { codepoint } => {
                write!(f, "unpaired surrogate \\u{:04X}", codepoint)
            }
            Self::ControlCharacter { byte } => {
                write!(f, "unescaped control character 0x{:02X}", byte)
            }
            Self::LeadingZero => write!(f, "leading zeros not allowed in numbers"),
            Self::LeadingPlus => write!(f, "leading plus sign not allowed in numbers"),
            Self::InvalidNumber { reason } => write!(f, "invalid number: {}", reason),
            Self::InvalidKeyword { found } => {
                write!(
                    f,
                    "invalid keyword '{}' (expected null, true, or false)",
                    found
                )
            }
            Self::InvalidUtf8 => write!(f, "invalid UTF-8 sequence"),
        }
    }
}

/// A JSON validation error with position information.
#[derive(Debug, Clone)]
pub struct ValidationError {
    /// The kind of error.
    pub kind: ValidationErrorKind,
    /// Position where the error occurred.
    pub position: Position,
}

impl fmt::Display for ValidationError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{} at {}", self.kind, self.position)
    }
}

#[cfg(feature = "std")]
impl std::error::Error for ValidationError {}

/// A strict JSON validator with position tracking.
///
/// Uses recursive descent parsing to validate JSON according to RFC 8259.
pub struct Validator<'a> {
    input: &'a [u8],
    offset: usize,
    line: usize,
    column: usize,
}

impl<'a> Validator<'a> {
    /// Create a new validator for the given input.
    pub fn new(input: &'a [u8]) -> Self {
        Self {
            input,
            offset: 0,
            line: 1,
            column: 1,
        }
    }

    /// Validate the entire input as JSON.
    ///
    /// Returns `Ok(())` if the input is valid JSON, or an error with position
    /// information if validation fails.
    pub fn validate(&mut self) -> Result<(), ValidationError> {
        self.skip_whitespace();

        if self.is_eof() {
            return Err(self.error(ValidationErrorKind::UnexpectedEof {
                expected: "JSON value",
            }));
        }

        self.validate_value()?;
        self.skip_whitespace();

        if !self.is_eof() {
            return Err(self.error(ValidationErrorKind::TrailingContent));
        }

        Ok(())
    }

    /// Validate a JSON value (object, array, string, number, or keyword).
    fn validate_value(&mut self) -> Result<(), ValidationError> {
        match self.peek() {
            Some(b'{') => self.validate_object(),
            Some(b'[') => self.validate_array(),
            Some(b'"') => self.validate_string(),
            Some(b'-') | Some(b'0'..=b'9') => self.validate_number(),
            Some(b't') | Some(b'f') | Some(b'n') => self.validate_keyword(),
            Some(b'+') => Err(self.error(ValidationErrorKind::LeadingPlus)),
            Some(c) => Err(self.error(ValidationErrorKind::UnexpectedCharacter {
                expected: "JSON value",
                found: c as char,
            })),
            None => Err(self.error(ValidationErrorKind::UnexpectedEof {
                expected: "JSON value",
            })),
        }
    }

    /// Validate a JSON object.
    fn validate_object(&mut self) -> Result<(), ValidationError> {
        self.advance(); // consume '{'
        self.skip_whitespace();

        // Empty object
        if self.peek() == Some(b'}') {
            self.advance();
            return Ok(());
        }

        loop {
            // Expect string key
            if self.peek() != Some(b'"') {
                return Err(self.error(ValidationErrorKind::UnexpectedCharacter {
                    expected: "string key",
                    found: self.peek().map(|b| b as char).unwrap_or('\0'),
                }));
            }
            self.validate_string()?;
            self.skip_whitespace();

            // Expect colon
            if self.peek() != Some(b':') {
                return Err(self.error(ValidationErrorKind::UnexpectedCharacter {
                    expected: "':'",
                    found: self.peek().map(|b| b as char).unwrap_or('\0'),
                }));
            }
            self.advance();
            self.skip_whitespace();

            // Expect value
            self.validate_value()?;
            self.skip_whitespace();

            // Expect comma or closing brace
            match self.peek() {
                Some(b',') => {
                    self.advance();
                    self.skip_whitespace();
                    // Check for trailing comma
                    if self.peek() == Some(b'}') {
                        return Err(self.error(ValidationErrorKind::UnexpectedCharacter {
                            expected: "string key",
                            found: '}',
                        }));
                    }
                }
                Some(b'}') => {
                    self.advance();
                    return Ok(());
                }
                Some(c) => {
                    return Err(self.error(ValidationErrorKind::UnexpectedCharacter {
                        expected: "',' or '}'",
                        found: c as char,
                    }));
                }
                None => {
                    return Err(self.error(ValidationErrorKind::UnexpectedEof {
                        expected: "',' or '}'",
                    }));
                }
            }
        }
    }

    /// Validate a JSON array.
    fn validate_array(&mut self) -> Result<(), ValidationError> {
        self.advance(); // consume '['
        self.skip_whitespace();

        // Empty array
        if self.peek() == Some(b']') {
            self.advance();
            return Ok(());
        }

        loop {
            self.validate_value()?;
            self.skip_whitespace();

            match self.peek() {
                Some(b',') => {
                    self.advance();
                    self.skip_whitespace();
                    // Check for trailing comma
                    if self.peek() == Some(b']') {
                        return Err(self.error(ValidationErrorKind::UnexpectedCharacter {
                            expected: "JSON value",
                            found: ']',
                        }));
                    }
                }
                Some(b']') => {
                    self.advance();
                    return Ok(());
                }
                Some(c) => {
                    return Err(self.error(ValidationErrorKind::UnexpectedCharacter {
                        expected: "',' or ']'",
                        found: c as char,
                    }));
                }
                None => {
                    return Err(self.error(ValidationErrorKind::UnexpectedEof {
                        expected: "',' or ']'",
                    }));
                }
            }
        }
    }

    /// Validate a JSON string.
    fn validate_string(&mut self) -> Result<(), ValidationError> {
        self.advance(); // consume opening quote

        loop {
            match self.peek() {
                Some(b'"') => {
                    self.advance();
                    return Ok(());
                }
                Some(b'\\') => {
                    self.validate_escape()?;
                }
                Some(b) if b < 0x20 => {
                    return Err(self.error(ValidationErrorKind::ControlCharacter { byte: b }));
                }
                Some(_) => {
                    // Validate UTF-8 sequence
                    self.validate_utf8_char()?;
                }
                None => {
                    return Err(self.error(ValidationErrorKind::UnclosedString));
                }
            }
        }
    }

    /// Validate a single UTF-8 character (may be multi-byte).
    fn validate_utf8_char(&mut self) -> Result<(), ValidationError> {
        let b = self.peek().unwrap();

        // Single byte ASCII (0x00-0x7F)
        if b < 0x80 {
            self.advance();
            return Ok(());
        }

        // Determine expected length and validate leading byte
        let (len, min_cp, max_cp) = if b & 0xE0 == 0xC0 {
            (2, 0x80u32, 0x7FFu32)
        } else if b & 0xF0 == 0xE0 {
            (3, 0x800u32, 0xFFFFu32)
        } else if b & 0xF8 == 0xF0 {
            (4, 0x10000u32, 0x10FFFFu32)
        } else {
            return Err(self.error(ValidationErrorKind::InvalidUtf8));
        };

        // Check we have enough bytes
        if self.offset + len > self.input.len() {
            return Err(self.error(ValidationErrorKind::InvalidUtf8));
        }

        // Validate continuation bytes
        for i in 1..len {
            let cont = self.input[self.offset + i];
            if cont & 0xC0 != 0x80 {
                return Err(self.error(ValidationErrorKind::InvalidUtf8));
            }
        }

        // Decode and validate codepoint
        let cp = match len {
            2 => ((b as u32 & 0x1F) << 6) | (self.input[self.offset + 1] as u32 & 0x3F),
            3 => {
                ((b as u32 & 0x0F) << 12)
                    | ((self.input[self.offset + 1] as u32 & 0x3F) << 6)
                    | (self.input[self.offset + 2] as u32 & 0x3F)
            }
            4 => {
                ((b as u32 & 0x07) << 18)
                    | ((self.input[self.offset + 1] as u32 & 0x3F) << 12)
                    | ((self.input[self.offset + 2] as u32 & 0x3F) << 6)
                    | (self.input[self.offset + 3] as u32 & 0x3F)
            }
            _ => unreachable!(),
        };

        // Check for overlong encoding
        if cp < min_cp || cp > max_cp {
            return Err(self.error(ValidationErrorKind::InvalidUtf8));
        }

        // Check for surrogate codepoints (invalid in UTF-8)
        if (0xD800..=0xDFFF).contains(&cp) {
            return Err(self.error(ValidationErrorKind::InvalidUtf8));
        }

        // Advance past all bytes
        for _ in 0..len {
            self.advance();
        }

        Ok(())
    }

    /// Validate an escape sequence.
    fn validate_escape(&mut self) -> Result<(), ValidationError> {
        self.advance(); // consume backslash

        match self.peek() {
            Some(b'"' | b'\\' | b'/' | b'b' | b'f' | b'n' | b'r' | b't') => {
                self.advance();
                Ok(())
            }
            Some(b'u') => {
                self.advance();
                let high = self.validate_unicode_escape()?;

                // Check for surrogate pair
                if (0xD800..=0xDBFF).contains(&high) {
                    // High surrogate - must be followed by \uXXXX low surrogate
                    if self.peek() != Some(b'\\') {
                        return Err(
                            self.error(ValidationErrorKind::UnpairedSurrogate { codepoint: high })
                        );
                    }
                    self.advance();
                    if self.peek() != Some(b'u') {
                        return Err(
                            self.error(ValidationErrorKind::UnpairedSurrogate { codepoint: high })
                        );
                    }
                    self.advance();

                    let low = self.validate_unicode_escape()?;
                    if !(0xDC00..=0xDFFF).contains(&low) {
                        return Err(
                            self.error(ValidationErrorKind::UnpairedSurrogate { codepoint: high })
                        );
                    }
                } else if (0xDC00..=0xDFFF).contains(&high) {
                    // Lone low surrogate
                    return Err(
                        self.error(ValidationErrorKind::UnpairedSurrogate { codepoint: high })
                    );
                }

                Ok(())
            }
            Some(c) => Err(self.error(ValidationErrorKind::InvalidEscape {
                sequence: c as char,
            })),
            None => Err(self.error(ValidationErrorKind::UnclosedString)),
        }
    }

    /// Validate a \uXXXX unicode escape and return the codepoint.
    fn validate_unicode_escape(&mut self) -> Result<u16, ValidationError> {
        let mut value: u16 = 0;

        for _ in 0..4 {
            match self.peek() {
                Some(b @ b'0'..=b'9') => {
                    value = value * 16 + (b - b'0') as u16;
                    self.advance();
                }
                Some(b @ b'a'..=b'f') => {
                    value = value * 16 + (b - b'a' + 10) as u16;
                    self.advance();
                }
                Some(b @ b'A'..=b'F') => {
                    value = value * 16 + (b - b'A' + 10) as u16;
                    self.advance();
                }
                Some(_) => {
                    return Err(self.error(ValidationErrorKind::InvalidUnicodeEscape {
                        reason: "expected 4 hex digits",
                    }));
                }
                None => {
                    return Err(self.error(ValidationErrorKind::InvalidUnicodeEscape {
                        reason: "unexpected end of input",
                    }));
                }
            }
        }

        Ok(value)
    }

    /// Validate a JSON number.
    fn validate_number(&mut self) -> Result<(), ValidationError> {
        // Optional minus sign
        if self.peek() == Some(b'-') {
            self.advance();
        }

        // Integer part
        match self.peek() {
            Some(b'0') => {
                self.advance();
                // Check for leading zero (e.g., 01, 007)
                if matches!(self.peek(), Some(b'0'..=b'9')) {
                    return Err(self.error(ValidationErrorKind::LeadingZero));
                }
            }
            Some(b'1'..=b'9') => {
                self.advance();
                while matches!(self.peek(), Some(b'0'..=b'9')) {
                    self.advance();
                }
            }
            Some(_) | None => {
                return Err(self.error(ValidationErrorKind::InvalidNumber {
                    reason: "expected digit after minus sign",
                }));
            }
        }

        // Optional fractional part
        if self.peek() == Some(b'.') {
            self.advance();

            // Must have at least one digit after decimal point
            if !matches!(self.peek(), Some(b'0'..=b'9')) {
                return Err(self.error(ValidationErrorKind::InvalidNumber {
                    reason: "expected digit after decimal point",
                }));
            }

            while matches!(self.peek(), Some(b'0'..=b'9')) {
                self.advance();
            }
        }

        // Optional exponent
        if matches!(self.peek(), Some(b'e' | b'E')) {
            self.advance();

            // Optional sign
            if matches!(self.peek(), Some(b'+' | b'-')) {
                self.advance();
            }

            // Must have at least one digit
            if !matches!(self.peek(), Some(b'0'..=b'9')) {
                return Err(self.error(ValidationErrorKind::InvalidNumber {
                    reason: "expected digit in exponent",
                }));
            }

            while matches!(self.peek(), Some(b'0'..=b'9')) {
                self.advance();
            }
        }

        Ok(())
    }

    /// Validate a keyword (null, true, false).
    fn validate_keyword(&mut self) -> Result<(), ValidationError> {
        let start = self.offset;

        // Collect alphabetic characters
        while matches!(self.peek(), Some(b'a'..=b'z')) {
            self.advance();
        }

        let keyword = &self.input[start..self.offset];

        match keyword {
            b"null" | b"true" | b"false" => Ok(()),
            _ => {
                let found = String::from_utf8_lossy(keyword).into_owned();
                // Reset position to start for error reporting
                let err_pos = Position {
                    offset: start,
                    line: self.line,
                    column: self.column - (self.offset - start),
                };
                Err(ValidationError {
                    kind: ValidationErrorKind::InvalidKeyword { found },
                    position: err_pos,
                })
            }
        }
    }

    /// Skip whitespace characters (space, tab, newline, carriage return).
    fn skip_whitespace(&mut self) {
        while let Some(b) = self.peek() {
            match b {
                b' ' | b'\t' => {
                    self.offset += 1;
                    self.column += 1;
                }
                b'\n' => {
                    self.offset += 1;
                    self.line += 1;
                    self.column = 1;
                }
                b'\r' => {
                    self.offset += 1;
                    // Handle CRLF
                    if self.peek() == Some(b'\n') {
                        self.offset += 1;
                    }
                    self.line += 1;
                    self.column = 1;
                }
                _ => break,
            }
        }
    }

    /// Peek at the current byte without advancing.
    #[inline]
    fn peek(&self) -> Option<u8> {
        self.input.get(self.offset).copied()
    }

    /// Advance to the next byte.
    #[inline]
    fn advance(&mut self) -> Option<u8> {
        if self.offset >= self.input.len() {
            return None;
        }
        let b = self.input[self.offset];
        self.offset += 1;
        self.column += 1;
        Some(b)
    }

    /// Check if we're at end of input.
    #[inline]
    fn is_eof(&self) -> bool {
        self.offset >= self.input.len()
    }

    /// Get current position.
    fn position(&self) -> Position {
        Position {
            offset: self.offset,
            line: self.line,
            column: self.column,
        }
    }

    /// Create an error at current position.
    fn error(&self, kind: ValidationErrorKind) -> ValidationError {
        ValidationError {
            kind,
            position: self.position(),
        }
    }
}

/// Validate JSON input.
///
/// Convenience function that creates a validator and runs it.
///
/// # Example
///
/// ```
/// use succinctly::json::validate::validate;
///
/// assert!(validate(br#"{"key": "value"}"#).is_ok());
/// assert!(validate(br#"{"key": }"#).is_err());
/// ```
pub fn validate(input: &[u8]) -> Result<(), ValidationError> {
    Validator::new(input).validate()
}

#[cfg(test)]
mod tests {
    use super::*;

    // ========================================================================
    // Valid JSON tests
    // ========================================================================

    #[test]
    fn test_valid_null() {
        assert!(validate(b"null").is_ok());
    }

    #[test]
    fn test_valid_true() {
        assert!(validate(b"true").is_ok());
    }

    #[test]
    fn test_valid_false() {
        assert!(validate(b"false").is_ok());
    }

    #[test]
    fn test_valid_empty_object() {
        assert!(validate(b"{}").is_ok());
    }

    #[test]
    fn test_valid_empty_array() {
        assert!(validate(b"[]").is_ok());
    }

    #[test]
    fn test_valid_simple_object() {
        assert!(validate(br#"{"key": "value"}"#).is_ok());
    }

    #[test]
    fn test_valid_simple_array() {
        assert!(validate(b"[1, 2, 3]").is_ok());
    }

    #[test]
    fn test_valid_nested() {
        assert!(validate(br#"{"arr": [1, {"nested": true}]}"#).is_ok());
    }

    #[test]
    fn test_valid_string_escapes() {
        assert!(validate(br#""hello\nworld""#).is_ok());
        assert!(validate(br#""tab\there""#).is_ok());
        assert!(validate(br#""quote\"here""#).is_ok());
        assert!(validate(br#""backslash\\here""#).is_ok());
        assert!(validate(br#""slash\/here""#).is_ok());
        assert!(validate(br#""controls\b\f\r""#).is_ok());
    }

    #[test]
    fn test_valid_unicode_escape() {
        assert!(validate(br#""\u0041""#).is_ok()); // 'A'
        assert!(validate(br#""\u00e9""#).is_ok()); // 'é'
        assert!(validate(br#""\u4e2d""#).is_ok()); // '中'
    }

    #[test]
    fn test_valid_surrogate_pair() {
        // U+1F600 (😀) encoded as surrogate pair
        assert!(validate(br#""\uD83D\uDE00""#).is_ok());
    }

    #[test]
    fn test_valid_numbers() {
        assert!(validate(b"0").is_ok());
        assert!(validate(b"123").is_ok());
        assert!(validate(b"-456").is_ok());
        assert!(validate(b"3.14159").is_ok());
        assert!(validate(b"-0.5").is_ok());
        assert!(validate(b"1e10").is_ok());
        assert!(validate(b"1E10").is_ok());
        assert!(validate(b"1e+10").is_ok());
        assert!(validate(b"1e-10").is_ok());
        assert!(validate(b"2.5e3").is_ok());
        assert!(validate(b"-1.23e-45").is_ok());
    }

    #[test]
    fn test_valid_whitespace() {
        assert!(validate(b"  null  ").is_ok());
        assert!(validate(b"\t\n\r null \t\n\r ").is_ok());
        assert!(validate(b"{ \"key\" : \"value\" }").is_ok());
        assert!(validate(b"[ 1 , 2 , 3 ]").is_ok());
    }

    #[test]
    fn test_valid_utf8() {
        assert!(validate("\"日本語\"".as_bytes()).is_ok());
        assert!(validate("\"émoji: 😀\"".as_bytes()).is_ok());
    }

    // ========================================================================
    // Invalid JSON tests
    // ========================================================================

    #[test]
    fn test_invalid_empty() {
        let err = validate(b"").unwrap_err();
        assert!(matches!(
            err.kind,
            ValidationErrorKind::UnexpectedEof { .. }
        ));
    }

    #[test]
    fn test_invalid_whitespace_only() {
        let err = validate(b"   ").unwrap_err();
        assert!(matches!(
            err.kind,
            ValidationErrorKind::UnexpectedEof { .. }
        ));
    }

    #[test]
    fn test_invalid_trailing_content() {
        let err = validate(b"null extra").unwrap_err();
        assert!(matches!(err.kind, ValidationErrorKind::TrailingContent));
    }

    #[test]
    fn test_invalid_trailing_comma_object() {
        let err = validate(br#"{"key": "value",}"#).unwrap_err();
        assert!(matches!(
            err.kind,
            ValidationErrorKind::UnexpectedCharacter { found: '}', .. }
        ));
    }

    #[test]
    fn test_invalid_trailing_comma_array() {
        let err = validate(b"[1, 2, 3,]").unwrap_err();
        assert!(matches!(
            err.kind,
            ValidationErrorKind::UnexpectedCharacter { found: ']', .. }
        ));
    }

    #[test]
    fn test_invalid_leading_zero() {
        let err = validate(b"01").unwrap_err();
        assert!(matches!(err.kind, ValidationErrorKind::LeadingZero));

        let err = validate(b"007").unwrap_err();
        assert!(matches!(err.kind, ValidationErrorKind::LeadingZero));
    }

    #[test]
    fn test_invalid_leading_plus() {
        let err = validate(b"+1").unwrap_err();
        assert!(matches!(err.kind, ValidationErrorKind::LeadingPlus));
    }

    #[test]
    fn test_invalid_number_trailing_dot() {
        let err = validate(b"1.").unwrap_err();
        assert!(matches!(
            err.kind,
            ValidationErrorKind::InvalidNumber { .. }
        ));
    }

    #[test]
    fn test_invalid_number_leading_dot() {
        let err = validate(b".5").unwrap_err();
        assert!(matches!(
            err.kind,
            ValidationErrorKind::UnexpectedCharacter { .. }
        ));
    }

    #[test]
    fn test_invalid_number_empty_exponent() {
        let err = validate(b"1e").unwrap_err();
        assert!(matches!(
            err.kind,
            ValidationErrorKind::InvalidNumber { .. }
        ));

        let err = validate(b"1e+").unwrap_err();
        assert!(matches!(
            err.kind,
            ValidationErrorKind::InvalidNumber { .. }
        ));
    }

    #[test]
    fn test_invalid_escape_sequence() {
        let err = validate(br#""\q""#).unwrap_err();
        assert!(matches!(
            err.kind,
            ValidationErrorKind::InvalidEscape { sequence: 'q' }
        ));
    }

    #[test]
    fn test_invalid_unicode_escape_short() {
        let err = validate(br#""\u00""#).unwrap_err();
        assert!(matches!(
            err.kind,
            ValidationErrorKind::UnclosedString | ValidationErrorKind::InvalidUnicodeEscape { .. }
        ));
    }

    #[test]
    fn test_invalid_unicode_escape_bad_hex() {
        let err = validate(br#""\u00GG""#).unwrap_err();
        assert!(matches!(
            err.kind,
            ValidationErrorKind::InvalidUnicodeEscape { .. }
        ));
    }

    #[test]
    fn test_invalid_lone_high_surrogate() {
        let err = validate(br#""\uD83D""#).unwrap_err();
        assert!(matches!(
            err.kind,
            ValidationErrorKind::UnpairedSurrogate { .. }
        ));
    }

    #[test]
    fn test_invalid_lone_low_surrogate() {
        let err = validate(br#""\uDE00""#).unwrap_err();
        assert!(matches!(
            err.kind,
            ValidationErrorKind::UnpairedSurrogate { .. }
        ));
    }

    #[test]
    fn test_invalid_bad_surrogate_pair() {
        // High surrogate followed by non-surrogate
        let err = validate(br#""\uD83D\u0041""#).unwrap_err();
        assert!(matches!(
            err.kind,
            ValidationErrorKind::UnpairedSurrogate { .. }
        ));
    }

    #[test]
    fn test_invalid_control_character() {
        let err = validate(b"\"hello\x00world\"").unwrap_err();
        assert!(matches!(
            err.kind,
            ValidationErrorKind::ControlCharacter { byte: 0x00 }
        ));

        let err = validate(b"\"hello\x1Fworld\"").unwrap_err();
        assert!(matches!(
            err.kind,
            ValidationErrorKind::ControlCharacter { byte: 0x1F }
        ));
    }

    #[test]
    fn test_invalid_unclosed_string() {
        let err = validate(br#""unclosed"#).unwrap_err();
        assert!(matches!(err.kind, ValidationErrorKind::UnclosedString));
    }

    #[test]
    fn test_invalid_unclosed_object() {
        let err = validate(br#"{"key": "value""#).unwrap_err();
        assert!(matches!(
            err.kind,
            ValidationErrorKind::UnexpectedEof { .. }
        ));
    }

    #[test]
    fn test_invalid_unclosed_array() {
        let err = validate(b"[1, 2, 3").unwrap_err();
        assert!(matches!(
            err.kind,
            ValidationErrorKind::UnexpectedEof { .. }
        ));
    }

    #[test]
    fn test_invalid_keyword() {
        let err = validate(b"nul").unwrap_err();
        assert!(matches!(
            err.kind,
            ValidationErrorKind::InvalidKeyword { .. }
        ));

        let err = validate(b"tru").unwrap_err();
        assert!(matches!(
            err.kind,
            ValidationErrorKind::InvalidKeyword { .. }
        ));

        let err = validate(b"fals").unwrap_err();
        assert!(matches!(
            err.kind,
            ValidationErrorKind::InvalidKeyword { .. }
        ));

        // "undefined" starts with 'u' which is not a valid JSON value start
        let err = validate(b"undefined").unwrap_err();
        assert!(matches!(
            err.kind,
            ValidationErrorKind::UnexpectedCharacter { .. }
        ));
    }

    #[test]
    fn test_invalid_utf8() {
        // Invalid UTF-8 sequence
        let err = validate(b"\"hello\xFF\xFEworld\"").unwrap_err();
        assert!(matches!(err.kind, ValidationErrorKind::InvalidUtf8));
    }

    // ========================================================================
    // Position accuracy tests
    // ========================================================================

    #[test]
    fn test_error_position_single_line() {
        let err = validate(br#"{"key": "value",}"#).unwrap_err();
        assert_eq!(err.position.line, 1);
        assert_eq!(err.position.column, 17); // position of '}'
    }

    #[test]
    fn test_error_position_multiline() {
        let input = b"{\n  \"key\": \"value\",\n}";
        let err = validate(input).unwrap_err();
        assert_eq!(err.position.line, 3);
        assert_eq!(err.position.column, 1); // position of '}' on line 3
    }

    #[test]
    fn test_error_position_crlf() {
        let input = b"{\r\n  \"key\": \"value\",\r\n}";
        let err = validate(input).unwrap_err();
        assert_eq!(err.position.line, 3);
    }

    // ========================================================================
    // RFC 8259 comprehensive coverage tests
    // ========================================================================

    /// RFC 8259 Section 7: All control characters (U+0000 through U+001F) must be escaped.
    #[test]
    fn test_all_control_characters_rejected() {
        for byte in 0x00u8..=0x1F {
            let input = format!("\"hello{}world\"", byte as char);
            let err = validate(input.as_bytes()).unwrap_err();
            assert!(
                matches!(err.kind, ValidationErrorKind::ControlCharacter { byte: b } if b == byte),
                "Control char 0x{:02X} should be rejected",
                byte
            );
        }
    }

    /// RFC 8259 Section 6: -0 is a valid number.
    #[test]
    fn test_negative_zero() {
        assert!(validate(b"-0").is_ok());
        assert!(validate(b"[-0]").is_ok());
        assert!(validate(br#"{"value": -0}"#).is_ok());
    }

    /// RFC 8259 Section 6: Zero with exponent is valid.
    #[test]
    fn test_zero_with_exponent() {
        assert!(validate(b"0e0").is_ok());
        assert!(validate(b"0E0").is_ok());
        assert!(validate(b"0e+0").is_ok());
        assert!(validate(b"0e-0").is_ok());
        assert!(validate(b"0.0e0").is_ok());
    }

    /// RFC 8259 Section 4: Empty string keys are valid.
    #[test]
    fn test_empty_string_key() {
        assert!(validate(br#"{"": 1}"#).is_ok());
        assert!(validate(br#"{"": ""}"#).is_ok());
        assert!(validate(br#"{"": null, "a": 1}"#).is_ok());
    }

    /// RFC 8259: High surrogate followed by non-\u escape should error.
    #[test]
    fn test_high_surrogate_followed_by_regular_escape() {
        // \uD83D followed by \n (not another \uXXXX)
        let err = validate(br#""\uD83D\n""#).unwrap_err();
        assert!(matches!(
            err.kind,
            ValidationErrorKind::UnpairedSurrogate { .. }
        ));

        // \uD83D followed by \t
        let err = validate(br#""\uD83D\t""#).unwrap_err();
        assert!(matches!(
            err.kind,
            ValidationErrorKind::UnpairedSurrogate { .. }
        ));
    }

    /// RFC 8259: High surrogate at end of string should error.
    #[test]
    fn test_high_surrogate_at_string_end() {
        let err = validate(br#""\uD83D""#).unwrap_err();
        assert!(matches!(
            err.kind,
            ValidationErrorKind::UnpairedSurrogate { .. }
        ));
    }

    /// UTF-8: Standalone continuation bytes (0x80-0xBF) are invalid.
    #[test]
    fn test_invalid_utf8_standalone_continuation() {
        let err = validate(b"\"hello\x80world\"").unwrap_err();
        assert!(matches!(err.kind, ValidationErrorKind::InvalidUtf8));

        let err = validate(b"\"hello\xBFworld\"").unwrap_err();
        assert!(matches!(err.kind, ValidationErrorKind::InvalidUtf8));
    }

    /// UTF-8: Overlong encodings are invalid (C0, C1 lead bytes).
    #[test]
    fn test_invalid_utf8_overlong_2byte() {
        // C0 80 is overlong encoding of NUL
        let err = validate(b"\"hello\xC0\x80world\"").unwrap_err();
        assert!(matches!(err.kind, ValidationErrorKind::InvalidUtf8));

        // C1 BF is overlong encoding of U+007F
        let err = validate(b"\"hello\xC1\xBFworld\"").unwrap_err();
        assert!(matches!(err.kind, ValidationErrorKind::InvalidUtf8));
    }

    /// UTF-8: Invalid lead bytes F5-FF are rejected.
    #[test]
    fn test_invalid_utf8_f5_and_above() {
        for lead in 0xF5u8..=0xFF {
            let input = [b'"', b'x', lead, 0x80, 0x80, 0x80, b'"'];
            let err = validate(&input).unwrap_err();
            assert!(
                matches!(err.kind, ValidationErrorKind::InvalidUtf8),
                "Lead byte 0x{:02X} should be rejected",
                lead
            );
        }
    }

    /// UTF-8: Truncated multi-byte sequences are invalid.
    #[test]
    fn test_invalid_utf8_truncated() {
        // 2-byte sequence truncated (missing continuation)
        let err = validate(b"\"hello\xC2\"").unwrap_err();
        assert!(matches!(
            err.kind,
            ValidationErrorKind::UnclosedString | ValidationErrorKind::InvalidUtf8
        ));

        // 3-byte sequence truncated (missing 1 continuation)
        let err = validate(b"\"hello\xE0\xA0\"").unwrap_err();
        assert!(matches!(
            err.kind,
            ValidationErrorKind::UnclosedString | ValidationErrorKind::InvalidUtf8
        ));

        // 4-byte sequence truncated (missing 2 continuations)
        let err = validate(b"\"hello\xF0\x90\"").unwrap_err();
        assert!(matches!(
            err.kind,
            ValidationErrorKind::UnclosedString | ValidationErrorKind::InvalidUtf8
        ));
    }

    /// UTF-8: Surrogate codepoints encoded directly in UTF-8 (ED A0 80 - ED BF BF) are invalid.
    #[test]
    fn test_invalid_utf8_surrogate_codepoints() {
        // U+D800 encoded as UTF-8: ED A0 80
        let err = validate(b"\"hello\xED\xA0\x80world\"").unwrap_err();
        assert!(matches!(err.kind, ValidationErrorKind::InvalidUtf8));

        // U+DFFF encoded as UTF-8: ED BF BF
        let err = validate(b"\"hello\xED\xBF\xBFworld\"").unwrap_err();
        assert!(matches!(err.kind, ValidationErrorKind::InvalidUtf8));
    }

    /// UTF-8: Codepoints above U+10FFFF are invalid.
    #[test]
    fn test_invalid_utf8_above_max_codepoint() {
        // F4 90 80 80 would encode U+110000 (above max)
        let err = validate(b"\"hello\xF4\x90\x80\x80world\"").unwrap_err();
        assert!(matches!(err.kind, ValidationErrorKind::InvalidUtf8));
    }

    /// RFC 8259 Section 7: All valid escape sequences.
    #[test]
    fn test_all_valid_escapes() {
        assert!(validate(br#""\"""#).is_ok()); // quotation mark
        assert!(validate(br#""\\""#).is_ok()); // reverse solidus
        assert!(validate(br#""\/""#).is_ok()); // solidus
        assert!(validate(br#""\b""#).is_ok()); // backspace
        assert!(validate(br#""\f""#).is_ok()); // form feed
        assert!(validate(br#""\n""#).is_ok()); // line feed
        assert!(validate(br#""\r""#).is_ok()); // carriage return
        assert!(validate(br#""\t""#).is_ok()); // tab
        assert!(validate(br#""\u0000""#).is_ok()); // unicode escape
    }

    /// RFC 8259: Invalid escape sequences.
    #[test]
    fn test_invalid_escapes() {
        // Common mistakes
        let err = validate(br#""\a""#).unwrap_err();
        assert!(matches!(
            err.kind,
            ValidationErrorKind::InvalidEscape { sequence: 'a' }
        ));

        let err = validate(br#""\v""#).unwrap_err();
        assert!(matches!(
            err.kind,
            ValidationErrorKind::InvalidEscape { sequence: 'v' }
        ));

        let err = validate(br#""\x00""#).unwrap_err();
        assert!(matches!(
            err.kind,
            ValidationErrorKind::InvalidEscape { sequence: 'x' }
        ));

        let err = validate(br#""\0""#).unwrap_err();
        assert!(matches!(
            err.kind,
            ValidationErrorKind::InvalidEscape { sequence: '0' }
        ));
    }

    /// RFC 8259 Section 6: Number edge cases.
    #[test]
    fn test_number_edge_cases() {
        // Valid edge cases
        assert!(validate(b"0").is_ok());
        assert!(validate(b"-0").is_ok());
        assert!(validate(b"0.0").is_ok());
        assert!(validate(b"-0.0").is_ok());
        assert!(validate(b"1e1").is_ok());
        assert!(validate(b"1E1").is_ok());
        assert!(validate(b"1e+1").is_ok());
        assert!(validate(b"1e-1").is_ok());
        assert!(validate(b"0.1e1").is_ok());
        assert!(validate(b"123456789012345678901234567890").is_ok()); // large integer

        // Invalid: multiple leading zeros
        let err = validate(b"00").unwrap_err();
        assert!(matches!(err.kind, ValidationErrorKind::LeadingZero));

        // Invalid: leading zero before digit
        let err = validate(b"01").unwrap_err();
        assert!(matches!(err.kind, ValidationErrorKind::LeadingZero));

        // Invalid: negative with leading zero
        let err = validate(b"-01").unwrap_err();
        assert!(matches!(err.kind, ValidationErrorKind::LeadingZero));
    }

    /// RFC 8259: Structural edge cases.
    #[test]
    fn test_structural_edge_cases() {
        // Deeply nested (but valid)
        let deep_array = "[".repeat(100) + &"]".repeat(100);
        assert!(validate(deep_array.as_bytes()).is_ok());

        let deep_object = r#"{"a":"#.repeat(50) + "1" + &"}".repeat(50);
        assert!(validate(deep_object.as_bytes()).is_ok());

        // Empty containers
        assert!(validate(b"{}").is_ok());
        assert!(validate(b"[]").is_ok());
        assert!(validate(b"[[]]").is_ok());
        assert!(validate(b"{{}}").is_err()); // invalid - key required
        assert!(validate(br#"{"a":{}}"#).is_ok());
    }

    /// RFC 8259 Section 2: Whitespace handling.
    #[test]
    fn test_whitespace_edge_cases() {
        // All valid whitespace characters
        assert!(validate(b" null").is_ok());
        assert!(validate(b"\tnull").is_ok());
        assert!(validate(b"\nnull").is_ok());
        assert!(validate(b"\rnull").is_ok());
        assert!(validate(b" \t\n\r null \t\n\r ").is_ok());

        // Whitespace in structures
        assert!(validate(b"{ }").is_ok());
        assert!(validate(b"[ ]").is_ok());
        assert!(validate(br#"{ "a" : 1 }"#).is_ok());
        assert!(validate(b"[ 1 , 2 , 3 ]").is_ok());
    }

    /// RFC 8259: Unicode escape edge cases.
    #[test]
    fn test_unicode_escape_edge_cases() {
        // Lowercase hex
        assert!(validate(br#""\u00ff""#).is_ok());
        // Uppercase hex
        assert!(validate(br#""\u00FF""#).is_ok());
        // Mixed case
        assert!(validate(br#""\u00Ff""#).is_ok());

        // Valid surrogate pair (U+1F600 GRINNING FACE)
        assert!(validate(br#""\uD83D\uDE00""#).is_ok());

        // Multiple surrogate pairs
        assert!(validate(br#""\uD83D\uDE00\uD83D\uDE01""#).is_ok());
    }

    /// RFC 8259: String with all printable ASCII.
    #[test]
    fn test_printable_ascii_in_string() {
        // All printable ASCII (0x20-0x7E) except quote and backslash
        let mut s = String::from("\"");
        for c in 0x20u8..=0x7E {
            if c != b'"' && c != b'\\' {
                s.push(c as char);
            }
        }
        s.push('"');
        assert!(validate(s.as_bytes()).is_ok());
    }
}