nextjson 0.1.3

A dependency-free, no_std JSON and CBOR library with a schema-driven, visitor-free design.
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
//! TOML codec (v1.0 subset).
//!
//! The decoder parses a TOML document into a [`Value`] and serves the
//! unified event interface from it: `key = value` pairs, dotted keys,
//! `[table]` and `[[array-of-table]]` headers, basic and literal strings,
//! multi-line (`"""`/`'''`) strings with `\` continuation, decimal / hex /
//! octal / binary integers (with `_` separators), floats, booleans, arrays
//! (multi-line, trailing commas), inline tables, and date-times (strictly
//! validated, preserved as strings). `inf`/`nan` have no TOML literal form
//! and are rejected. The encoder collects the event stream into a [`Value`]
//! and emits TOML when the root closes, because TOML is document-shaped
//! (tables must be emitted after their keys).

use alloc::string::{String, ToString};
use alloc::vec;
use alloc::vec::Vec;

use crate::de::NsonDeserialize;
use crate::error::{Error, Result};
use crate::formats::tree;
use crate::formats::Format;
use crate::map::Map;
use crate::ser::NsonSerialize;
use crate::value::Value;
use crate::write::Write;

/// TOML format marker.
#[derive(Clone, Copy, Debug)]
pub struct Toml;

impl Format for Toml {
    const NAME: &'static str = "toml";
    const MIME: &'static str = "application/toml";
    const EXTENSIONS: &'static [&'static str] = &["toml"];
    const BINARY: bool = false;

    fn encode<T: NsonSerialize + ?Sized>(self, value: &T) -> Result<Vec<u8>> {
        let mut encoder = TomlEncoder::new(Vec::new());
        let mut checked = crate::ser::CheckedEncoder::new(&mut encoder);
        T::nextencode(value, &mut checked)?;
        checked.finish()?;
        encoder.finish()
    }

    fn decode<'de, T: NsonDeserialize<'de>>(self, input: &'de [u8]) -> Result<T> {
        let value = parse_toml(input)?;
        let mut decoder = tree::TreeDecoder::new(tree::value_to_tokens(&value));
        let out = T::nextdecode(&mut decoder)?;
        decoder.end()?;
        Ok(out)
    }
}

// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------
// Encoder (collect into Value, emit at the end)
// ---------------------------------------------------------------------------

/// TOML encoder that collects one event stream and emits it on [`finish`](Self::finish).
pub struct TomlEncoder<W: Write> {
    writer: W,
    collector: tree::CollectEncoder,
}

impl<W: Write> TomlEncoder<W> {
    /// Create a TOML encoder over `writer`.
    pub fn new(writer: W) -> Self {
        Self {
            writer,
            collector: tree::CollectEncoder::new(),
        }
    }

    /// Emit the collected document, flush, and return the writer.
    pub fn finish(mut self) -> Result<W> {
        let root = self.collector.take_root()?;
        let mut out = Vec::with_capacity(256);
        emit_toml(&root, &mut out, &mut Vec::new())?;
        self.writer.write_all(&out)?;
        self.writer.flush()?;
        Ok(self.writer)
    }
}

tree::impl_collecting_format_encoder!(TomlEncoder);

/// Emit a [`Value`] as TOML.
///
/// TOML is document-shaped: a valid document is a sequence of `key = value`
/// pairs (and table headers), so a bare scalar or array at the root has no
/// wire representation. Like BSON's "requires a top-level document", this is
/// rejected honestly instead of emitting bytes no conforming parser accepts.
fn emit_toml(value: &Value, out: &mut Vec<u8>, path: &mut Vec<String>) -> Result<()> {
    match value {
        Value::Object(map) => emit_table(map, out, path),
        _ => Err(Error::custom("toml: requires a top-level table")),
    }
}

fn emit_table(map: &Map, out: &mut Vec<u8>, path: &mut Vec<String>) -> Result<()> {
    // Split into scalar keys and sub-tables.
    let mut scalars: Vec<(String, Value)> = Vec::new();
    let mut tables: Vec<(String, Value)> = Vec::new();
    let mut arrays_of_tables: Vec<(String, Value)> = Vec::new();
    for (k, v) in map.iter() {
        match v {
            Value::Object(_) => tables.push((k.to_string(), v.clone())),
            Value::Array(items) if items.iter().all(|i| matches!(i, Value::Object(_))) => {
                arrays_of_tables.push((k.to_string(), v.clone()));
            }
            _ => scalars.push((k.to_string(), v.clone())),
        }
    }
    // Emit scalar keys first.
    for (k, v) in &scalars {
        out.extend_from_slice(basic_key(k).as_bytes());
        out.extend_from_slice(b" = ");
        emit_scalar(v, out)?;
        out.push(b'\n');
    }
    if !scalars.is_empty() && (!tables.is_empty() || !arrays_of_tables.is_empty()) {
        out.push(b'\n');
    }
    // Sub-tables.
    for (k, v) in &tables {
        path.push(k.clone());
        out.push(b'[');
        out.extend_from_slice(join_path(path).as_bytes());
        out.extend_from_slice(b"]\n");
        if let Value::Object(m) = v {
            emit_table(m, out, path)?
        }
        out.push(b'\n');
        path.pop();
    }
    for (k, v) in &arrays_of_tables {
        if let Value::Array(items) = v {
            for item in items {
                path.push(k.clone());
                out.extend_from_slice(b"[[");
                out.extend_from_slice(join_path(path).as_bytes());
                out.extend_from_slice(b"]]\n");
                if let Value::Object(m) = item {
                    emit_table(m, out, path)?;
                }
                out.push(b'\n');
                path.pop();
            }
        }
    }
    Ok(())
}

fn join_path(path: &[String]) -> String {
    path.iter()
        .map(|p| basic_key(p))
        .collect::<Vec<_>>()
        .join(".")
}

fn basic_key(key: &str) -> String {
    // Bare keys must be alphanumeric + `-`/`_`; otherwise quote.
    if !key.is_empty()
        && key
            .bytes()
            .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
    {
        key.to_string()
    } else {
        let mut out = String::with_capacity(key.len() + 2);
        out.push('"');
        for c in key.chars() {
            match c {
                '"' => out.push_str("\\\""),
                '\\' => out.push_str("\\\\"),
                '\n' => out.push_str("\\n"),
                '\t' => out.push_str("\\t"),
                _ => out.push(c),
            }
        }
        out.push('"');
        out
    }
}

fn emit_scalar(value: &Value, out: &mut Vec<u8>) -> Result<()> {
    match value {
        Value::Null => Err(Error::custom("toml: no null type")),
        Value::Bool(b) => {
            out.extend_from_slice(if *b { b"true" } else { b"false" });
            Ok(())
        }
        Value::Number(n) => {
            out.extend_from_slice(tree::number_string(n).as_bytes());
            Ok(())
        }
        Value::String(s) => {
            out.push(b'"');
            for c in s.chars() {
                match c {
                    '"' => out.extend_from_slice(b"\\\""),
                    '\\' => out.extend_from_slice(b"\\\\"),
                    '\n' => out.extend_from_slice(b"\\n"),
                    '\t' => out.extend_from_slice(b"\\t"),
                    '\r' => out.extend_from_slice(b"\\r"),
                    c if (c as u32) < 0x20 => {
                        out.extend_from_slice(&alloc::format!("\\u{:04X}", c as u32).into_bytes());
                    }
                    _ => {
                        let mut buf = [0u8; 4];
                        out.extend_from_slice(c.encode_utf8(&mut buf).as_bytes());
                    }
                }
            }
            out.push(b'"');
            Ok(())
        }
        Value::Array(items) => {
            out.push(b'[');
            for (i, item) in items.iter().enumerate() {
                if i > 0 {
                    out.extend_from_slice(b", ");
                }
                emit_scalar(item, out)?;
            }
            out.push(b']');
            Ok(())
        }
        Value::Object(m) => {
            out.push(b'{');
            for (i, (k, v)) in m.iter().enumerate() {
                if i > 0 {
                    out.extend_from_slice(b", ");
                }
                out.extend_from_slice(basic_key(k).as_bytes());
                out.extend_from_slice(b" = ");
                emit_scalar(v, out)?;
            }
            out.push(b'}');
            Ok(())
        }
    }
}

// ---------------------------------------------------------------------------
// Decoder (TOML -> Value -> tokens)
// ---------------------------------------------------------------------------

/// TOML decoder serving the unified interface from a parsed [`Value`].
///
/// The parsed document is replayed through the shared
/// [`crate::formats::TreeDecoder`].
pub type TomlDecoder<'de> = tree::TreeDecoder<'de>;

// ---------------------------------------------------------------------------
// TOML parser
// ---------------------------------------------------------------------------

/// Parse a TOML document into a [`Value`] (root is always an object).
fn parse_toml(input: &[u8]) -> Result<Value> {
    let text = core::str::from_utf8(input).map_err(|_| Error::custom("toml: invalid utf-8"))?;
    let mut p = Parser {
        text,
        pos: 0,
        root: Map::new(),
        current: None, // (path segments, table)
        depth: 0,
    };
    p.parse_document()?;
    Ok(Value::Object(p.root))
}

/// Reference to the current table during TOML parsing.
#[derive(Clone)]
enum TableRef {
    /// A regular table at a dotted path.
    Path(Vec<String>),
    /// The newest element of an array of tables at a dotted path.
    ArrayElement(Vec<String>),
}

struct Parser<'a> {
    text: &'a str,
    pos: usize,
    root: Map,
    current: Option<TableRef>,
    depth: u32,
}

impl<'a> Parser<'a> {
    fn parse_document(&mut self) -> Result<()> {
        loop {
            self.skip_ws_and_comments()?;
            // Skip statement separators (leading newlines, blank lines).
            while self.pos < self.text.len()
                && matches!(self.text.as_bytes()[self.pos], b'\n' | b'\r')
            {
                self.pos += 1;
            }
            self.skip_ws_and_comments()?;
            if self.pos >= self.text.len() {
                break;
            }
            let c = self.text.as_bytes()[self.pos];
            if c == b'[' {
                self.parse_table_header()?;
            } else {
                self.parse_key_value()?;
            }
            // Expect a newline or end.
            self.skip_ws_and_comments()?;
            if self.pos < self.text.len() {
                let b = self.text.as_bytes()[self.pos];
                if b != b'\n' && b != b'\r' {
                    return Err(Error::custom("toml: expected newline after statement"));
                }
                while self.pos < self.text.len()
                    && matches!(self.text.as_bytes()[self.pos], b'\n' | b'\r')
                {
                    self.pos += 1;
                }
            }
        }
        Ok(())
    }

    fn skip_ws_and_comments(&mut self) -> Result<()> {
        loop {
            while self.pos < self.text.len()
                && matches!(self.text.as_bytes()[self.pos], b' ' | b'\t' | b'\r')
            {
                self.pos += 1;
            }
            if self.pos < self.text.len() && self.text.as_bytes()[self.pos] == b'#' {
                while self.pos < self.text.len() && self.text.as_bytes()[self.pos] != b'\n' {
                    self.pos += 1;
                }
                continue;
            }
            break;
        }
        Ok(())
    }

    fn parse_table_header(&mut self) -> Result<()> {
        let array = self.text.as_bytes().get(self.pos + 1) == Some(&b'[');
        self.pos += if array { 2 } else { 1 };
        let mut segments = Vec::new();
        loop {
            self.skip_ws_and_comments()?;
            segments.push(self.parse_key_segment()?);
            self.skip_ws_and_comments()?;
            match self.text.as_bytes().get(self.pos) {
                Some(b'.') => {
                    self.pos += 1;
                }
                Some(b']') if !array => {
                    self.pos += 1;
                    break;
                }
                Some(b']') if array && self.text.as_bytes().get(self.pos + 1) == Some(&b']') => {
                    self.pos += 2;
                    break;
                }
                _ => return Err(Error::custom("toml: malformed table header")),
            }
        }
        if array {
            self.table_at_array(&segments)?;
            self.current = Some(TableRef::ArrayElement(segments));
        } else {
            self.table_at(&segments, true)?;
            self.current = Some(TableRef::Path(segments));
        }
        Ok(())
    }

    /// Navigate to (and optionally create) the table at `path`.
    ///
    /// An array-of-tables segment descends into its newest element, matching
    /// TOML's `[a.b]` after `[[a]]`. Redefining a table (`[a]` twice, or
    /// `[a]` after `a = 1`) is an error per the TOML spec.
    fn table_at(&mut self, path: &[String], create: bool) -> Result<&mut Map> {
        let mut map = &mut self.root;
        for (i, seg) in path.iter().enumerate() {
            let is_last = i + 1 == path.len();
            if is_last && create && map.contains_key(seg) {
                return Err(Error::custom(alloc::format!(
                    "toml: table `{}` is already defined",
                    path.join(".")
                )));
            }
            if map.get(seg).is_none() && create {
                map.insert(seg.to_string(), Value::Object(Map::new()));
            }
            map = match map.get_mut(seg) {
                Some(Value::Object(m)) => m,
                Some(Value::Array(arr)) => match arr.last_mut() {
                    Some(Value::Object(m)) => m,
                    _ => return Err(Error::custom("toml: not a table in array")),
                },
                _ => return Err(Error::custom("toml: key is not a table")),
            };
        }
        Ok(map)
    }

    /// Navigate to the array at `path`, appending a fresh table element, and
    /// return its map.
    fn table_at_array(&mut self, path: &[String]) -> Result<&mut Map> {
        let mut map = &mut self.root;
        for (i, seg) in path.iter().enumerate() {
            if i + 1 == path.len() {
                if map.get(seg).is_none() {
                    map.insert(seg.to_string(), Value::Array(Vec::new()));
                }
                let arr = match map.get_mut(seg) {
                    Some(Value::Array(a)) => a,
                    _ => return Err(Error::custom("toml: not an array of tables")),
                };
                arr.push(Value::Object(Map::new()));
                return match arr.last_mut() {
                    Some(Value::Object(m)) => Ok(m),
                    _ => Err(Error::custom("toml: not a table")),
                };
            }
            if map.get(seg).is_none() {
                map.insert(seg.to_string(), Value::Object(Map::new()));
            }
            map = match map.get_mut(seg) {
                Some(Value::Object(m)) => m,
                _ => return Err(Error::custom("toml: not a table")),
            };
        }
        Err(Error::custom("toml: empty array-of-tables path"))
    }

    /// Return the map of the newest element of the array at `path`.
    fn table_at_array_last(&mut self, path: &[String]) -> Result<&mut Map> {
        let mut map = &mut self.root;
        for (i, seg) in path.iter().enumerate() {
            if i + 1 == path.len() {
                let arr = match map.get_mut(seg) {
                    Some(Value::Array(a)) => a,
                    _ => return Err(Error::custom("toml: not an array of tables")),
                };
                return match arr.last_mut() {
                    Some(Value::Object(m)) => Ok(m),
                    _ => Err(Error::custom("toml: empty array of tables")),
                };
            }
            map = match map.get_mut(seg) {
                Some(Value::Object(m)) => m,
                _ => return Err(Error::custom("toml: not a table")),
            };
        }
        Err(Error::custom("toml: empty array-of-tables path"))
    }

    fn parse_key_value(&mut self) -> Result<()> {
        let key = self.parse_dotted_key()?;
        self.skip_ws_and_comments()?;
        if self.text.as_bytes().get(self.pos) != Some(&b'=') {
            return Err(Error::custom("toml: expected '=' after key"));
        }
        self.pos += 1;
        self.skip_ws_and_comments()?;
        let value = self.parse_value()?;
        // Insert into the current table (path cloned to end the borrow).
        let current = self.current.clone();
        match current {
            Some(TableRef::Path(path)) => {
                let map = self.table_at(&path, false)?;
                insert_dotted(map, &key, value)
            }
            Some(TableRef::ArrayElement(path)) => {
                let map = self.table_at_array_last(&path)?;
                insert_dotted(map, &key, value)
            }
            None => {
                let map = &mut self.root;
                insert_dotted(map, &key, value)
            }
        }
    }

    fn parse_dotted_key(&mut self) -> Result<Vec<String>> {
        let mut parts = vec![self.parse_key_segment()?];
        loop {
            self.skip_ws_and_comments()?;
            if self.text.as_bytes().get(self.pos) == Some(&b'.') {
                self.pos += 1;
                parts.push(self.parse_key_segment()?);
            } else {
                break;
            }
        }
        Ok(parts)
    }

    fn parse_key_segment(&mut self) -> Result<String> {
        self.skip_ws_and_comments()?;
        let b = self.text.as_bytes().get(self.pos).copied();
        match b {
            Some(b'"') => self.parse_basic_string(),
            Some(b'\'') => self.parse_literal_string(),
            _ => {
                let start = self.pos;
                while self.pos < self.text.len() {
                    let c = self.text.as_bytes()[self.pos];
                    if c.is_ascii_alphanumeric() || c == b'-' || c == b'_' {
                        self.pos += 1;
                    } else {
                        break;
                    }
                }
                if self.pos == start {
                    return Err(Error::custom("toml: empty key"));
                }
                Ok(self.text[start..self.pos].to_string())
            }
        }
    }

    fn parse_value(&mut self) -> Result<Value> {
        self.skip_ws_and_comments()?;
        let b = self.text.as_bytes().get(self.pos).copied().unwrap_or(0);
        match b {
            b'"' => {
                if self.text.as_bytes().get(self.pos + 1) == Some(&b'"')
                    && self.text.as_bytes().get(self.pos + 2) == Some(&b'"')
                {
                    Ok(Value::from(self.parse_multi_basic_string()?))
                } else {
                    Ok(Value::from(self.parse_basic_string()?))
                }
            }
            b'\'' => {
                if self.text.as_bytes().get(self.pos + 1) == Some(&b'\'')
                    && self.text.as_bytes().get(self.pos + 2) == Some(&b'\'')
                {
                    Ok(Value::from(self.parse_multi_literal_string()?))
                } else {
                    Ok(Value::from(self.parse_literal_string()?))
                }
            }
            b'[' | b'{' => {
                if self.depth >= 128 {
                    return Err(Error::custom("toml: nesting limit exceeded"));
                }
                self.depth += 1;
                let value = if b == b'[' {
                    self.parse_array()
                } else {
                    self.parse_inline_table()
                };
                self.depth -= 1;
                value
            }
            b't' => {
                self.expect_lit(b"true")?;
                Ok(Value::from(true))
            }
            b'f' => {
                self.expect_lit(b"false")?;
                Ok(Value::from(false))
            }
            b'+' | b'-' | b'0'..=b'9' => self.parse_number_or_date(),
            _ => Err(Error::custom("toml: unexpected value")),
        }
    }

    fn parse_number_or_date(&mut self) -> Result<Value> {
        let start = self.pos;
        while self.pos < self.text.len() {
            let c = self.text.as_bytes()[self.pos];
            if c.is_ascii_alphanumeric()
                || matches!(
                    c,
                    b'+' | b'-' | b'.' | b'_' | b':' | b'T' | b't' | b'Z' | b'z' | b' '
                )
            {
                self.pos += 1;
            } else {
                break;
            }
        }
        let raw = self.text[start..self.pos].trim_end();
        if is_toml_datetime(raw) {
            return Ok(Value::from(raw.to_string()));
        }
        let clean = raw.replace('_', "");
        if let Some(digits) = clean
            .strip_prefix("0x")
            .or_else(|| clean.strip_prefix("0X"))
        {
            let v = u64::from_str_radix(digits, 16)
                .map_err(|_| Error::custom("toml: invalid hexadecimal integer"))?;
            return Ok(Value::from(v));
        }
        if let Some(digits) = clean
            .strip_prefix("0o")
            .or_else(|| clean.strip_prefix("0O"))
        {
            let v = u64::from_str_radix(digits, 8)
                .map_err(|_| Error::custom("toml: invalid octal integer"))?;
            return Ok(Value::from(v));
        }
        if let Some(digits) = clean
            .strip_prefix("0b")
            .or_else(|| clean.strip_prefix("0B"))
        {
            let v = u64::from_str_radix(digits, 2)
                .map_err(|_| Error::custom("toml: invalid binary integer"))?;
            return Ok(Value::from(v));
        }
        if let Ok(v) = clean.parse::<i64>() {
            return Ok(Value::from(v));
        }
        if let Ok(v) = clean.parse::<u64>() {
            return Ok(Value::from(v));
        }
        if let Ok(v) = clean.parse::<f64>() {
            return Ok(Value::from(v));
        }
        Err(Error::custom(alloc::format!(
            "toml: invalid number {raw:?}"
        )))
    }

    fn parse_array(&mut self) -> Result<Value> {
        self.pos += 1; // '['
        let mut items = Vec::new();
        loop {
            self.skip_ws_and_comments()?;
            match self.text.as_bytes().get(self.pos) {
                Some(b']') => {
                    self.pos += 1;
                    break;
                }
                Some(b'\n') | Some(b'\r') => {
                    self.pos += 1;
                    continue;
                }
                None => return Err(Error::custom("toml: unterminated array")),
                _ => {
                    items.push(self.parse_value()?);
                    self.skip_ws_and_comments()?;
                    match self.text.as_bytes().get(self.pos) {
                        Some(b',') => {
                            self.pos += 1;
                        }
                        Some(b']') => {}
                        _ => return Err(Error::custom("toml: expected ',' or ']'")),
                    }
                }
            }
        }
        Ok(Value::Array(items))
    }

    fn parse_inline_table(&mut self) -> Result<Value> {
        self.pos += 1; // '{'
        let mut map = Map::new();
        loop {
            self.skip_ws_and_comments()?;
            match self.text.as_bytes().get(self.pos) {
                Some(b'}') => {
                    self.pos += 1;
                    break;
                }
                None => return Err(Error::custom("toml: unterminated inline table")),
                _ => {
                    let key = self.parse_dotted_key()?;
                    self.skip_ws_and_comments()?;
                    if self.text.as_bytes().get(self.pos) != Some(&b'=') {
                        return Err(Error::custom("toml: expected '=' in inline table"));
                    }
                    self.pos += 1;
                    let value = self.parse_value()?;
                    map.insert(key.join("."), value);
                    self.skip_ws_and_comments()?;
                    match self.text.as_bytes().get(self.pos) {
                        Some(b',') => {
                            self.pos += 1;
                        }
                        Some(b'}') => {}
                        _ => return Err(Error::custom("toml: expected ',' or '}'")),
                    }
                }
            }
        }
        Ok(Value::Object(map))
    }

    fn parse_basic_string(&mut self) -> Result<String> {
        self.pos += 1; // opening quote
        let mut out = String::new();
        loop {
            if self.pos >= self.text.len() {
                return Err(Error::custom("toml: unterminated string"));
            }
            let b = self.text.as_bytes()[self.pos];
            match b {
                b'"' => {
                    self.pos += 1;
                    return Ok(out);
                }
                b'\\' => {
                    self.pos += 1;
                    if self.pos >= self.text.len() {
                        return Err(Error::custom("toml: unterminated escape"));
                    }
                    match self.text.as_bytes()[self.pos] {
                        b'n' => out.push('\n'),
                        b't' => out.push('\t'),
                        b'r' => out.push('\r'),
                        b'"' => out.push('"'),
                        b'\\' => out.push('\\'),
                        b'b' => out.push('\u{8}'),
                        b'f' => out.push('\u{c}'),
                        b'u' => {
                            let cp = self.read_hex(4)?;
                            out.push(
                                char::from_u32(cp)
                                    .ok_or_else(|| Error::custom("toml: invalid unicode escape"))?,
                            );
                        }
                        b'U' => {
                            let cp = self.read_hex(8)?;
                            out.push(
                                char::from_u32(cp)
                                    .ok_or_else(|| Error::custom("toml: invalid unicode escape"))?,
                            );
                        }
                        other => {
                            return Err(Error::custom(alloc::format!(
                                "toml: invalid escape '\\{}'",
                                other as char
                            )))
                        }
                    }
                    self.pos += 1;
                }
                b'\n' => return Err(Error::custom("toml: newline in basic string")),
                _ => {
                    let len = utf8_len(b).ok_or_else(|| Error::custom("toml: invalid utf-8"))?;
                    let chunk = &self.text[self.pos..self.pos + len];
                    out.push_str(chunk);
                    self.pos += len;
                }
            }
        }
    }

    fn parse_literal_string(&mut self) -> Result<String> {
        self.pos += 1;
        let start = self.pos;
        while self.pos < self.text.len() && self.text.as_bytes()[self.pos] != b'\'' {
            self.pos += 1;
        }
        if self.pos >= self.text.len() {
            return Err(Error::custom("toml: unterminated literal string"));
        }
        let s = self.text[start..self.pos].to_string();
        self.pos += 1;
        Ok(s)
    }

    /// Multi-line basic string (`"""..."""`), TOML 1.0.
    ///
    /// The newline immediately following the opening delimiter is trimmed;
    /// a backslash at the end of a line trims that newline plus all following
    /// whitespace (line-ending backslash); escapes behave like basic strings;
    /// trailing whitespace before the closing delimiter is trimmed.
    fn parse_multi_basic_string(&mut self) -> Result<String> {
        self.pos += 3; // opening `"""`
        self.skip_crlf();
        let mut out = String::new();
        loop {
            if self.pos + 3 <= self.text.len()
                && &self.text.as_bytes()[self.pos..self.pos + 3] == b"\"\"\""
            {
                self.pos += 3;
                break;
            }
            if self.pos >= self.text.len() {
                return Err(Error::custom("toml: unterminated multi-line string"));
            }
            let b = self.text.as_bytes()[self.pos];
            if b == b'\\' {
                self.pos += 1;
                if self.pos >= self.text.len() {
                    return Err(Error::custom("toml: unterminated escape"));
                }
                // Line-ending backslash: trim it and all following whitespace.
                let nb = self.text.as_bytes()[self.pos];
                if nb == b'\n'
                    || (nb == b'\r' && self.text.as_bytes().get(self.pos + 1) == Some(&b'\n'))
                {
                    if nb == b'\r' {
                        self.pos += 1;
                    }
                    self.pos += 1; // '\n'
                    while self.pos < self.text.len()
                        && matches!(self.text.as_bytes()[self.pos], b' ' | b'\t' | b'\n' | b'\r')
                    {
                        self.pos += 1;
                    }
                    continue;
                }
                match nb {
                    b'n' => out.push('\n'),
                    b't' => out.push('\t'),
                    b'r' => out.push('\r'),
                    b'"' => out.push('"'),
                    b'\\' => out.push('\\'),
                    b'b' => out.push('\u{8}'),
                    b'f' => out.push('\u{c}'),
                    b'u' => {
                        let cp = self.read_hex(4)?;
                        out.push(
                            char::from_u32(cp)
                                .ok_or_else(|| Error::custom("toml: invalid unicode escape"))?,
                        );
                    }
                    b'U' => {
                        let cp = self.read_hex(8)?;
                        out.push(
                            char::from_u32(cp)
                                .ok_or_else(|| Error::custom("toml: invalid unicode escape"))?,
                        );
                    }
                    other => {
                        return Err(Error::custom(alloc::format!(
                            "toml: invalid escape '\\{}'",
                            other as char
                        )))
                    }
                }
                self.pos += 1;
            } else {
                let len = utf8_len(b).ok_or_else(|| Error::custom("toml: invalid utf-8"))?;
                let chunk = &self.text[self.pos..self.pos + len];
                out.push_str(chunk);
                self.pos += len;
            }
        }
        // Trim trailing whitespace (spaces / tabs / newlines) before the
        // closing delimiter, per the TOML multi-line string rules.
        Ok(trim_whitespace_end(&out).to_string())
    }

    /// Multi-line literal string (`'''...'''`), TOML 1.0.
    ///
    /// No escapes; the newline immediately following the opening delimiter is
    /// trimmed; trailing whitespace before the closing delimiter is trimmed.
    fn parse_multi_literal_string(&mut self) -> Result<String> {
        self.pos += 3; // opening `'''`
        self.skip_crlf();
        let start = self.pos;
        loop {
            if self.pos + 3 <= self.text.len()
                && &self.text.as_bytes()[self.pos..self.pos + 3] == b"'''"
            {
                break;
            }
            if self.pos >= self.text.len() {
                return Err(Error::custom(
                    "toml: unterminated multi-line literal string",
                ));
            }
            self.pos += 1;
        }
        let s = self.text[start..self.pos].to_string();
        self.pos += 3;
        Ok(trim_whitespace_end(&s).to_string())
    }

    /// Skip a single CRLF / LF after an opening multi-line delimiter.
    fn skip_crlf(&mut self) {
        if self.pos < self.text.len() && self.text.as_bytes()[self.pos] == b'\r' {
            self.pos += 1;
        }
        if self.pos < self.text.len() && self.text.as_bytes()[self.pos] == b'\n' {
            self.pos += 1;
        }
    }

    fn read_hex(&mut self, n: usize) -> Result<u32> {
        let mut v: u32 = 0;
        for _ in 0..n {
            self.pos += 1;
            let b = self.text.as_bytes().get(self.pos).copied().unwrap_or(0);
            let d = crate::lex::hex_digit(b)
                .ok_or_else(|| Error::custom("toml: invalid hex escape"))?;
            v = v * 16 + d as u32;
        }
        Ok(v)
    }

    fn expect_lit(&mut self, lit: &[u8]) -> Result<()> {
        if self.text.len() - self.pos < lit.len()
            || &self.text.as_bytes()[self.pos..self.pos + lit.len()] != lit
        {
            return Err(Error::custom("toml: invalid literal"));
        }
        self.pos += lit.len();
        Ok(())
    }
}

/// Trim trailing ASCII whitespace (spaces, tabs, CR, LF) from a multi-line
/// string before its closing delimiter, per the TOML multi-line rules.
fn trim_whitespace_end(s: &str) -> &str {
    s.trim_end_matches([' ', '\t', '\n', '\r'])
}

/// Strict TOML 1.0 date-time grammar check.
///
/// Returns true when `raw` is one of the four supported forms (offset
/// date-time, local date-time, local date, local time). The JSON data model
/// has no native temporal type, so matching values are preserved verbatim as
/// strings; anything that merely *looks* numeric-with-dashes is rejected by
/// the number path instead of being silently misread.
fn is_toml_datetime(raw: &str) -> bool {
    let raw = raw.trim();
    if raw.is_empty() {
        return false;
    }
    let b = raw.as_bytes();
    // Local time: HH:MM:SS[.fraction].
    if b.len() >= 8 && b[2] == b':' && b[5] == b':' && is_time_range(&raw[..8]) {
        return raw.len() == 8 || fraction_only(&raw[8..]);
    }
    // Everything else must start with a date YYYY-MM-DD.
    if b.len() < 10 || b[4] != b'-' || b[7] != b'-' || !is_date(&raw[..10]) {
        return false;
    }
    if raw.len() == 10 {
        return true; // local date
    }
    // Date-time: the separator is 'T', 't' or a single space.
    let sep = b[10];
    if !(sep == b'T' || sep == b't' || sep == b' ') {
        return false;
    }
    let rest = &raw[11..];
    let rb = rest.as_bytes();
    if rb.len() < 8 || rb[2] != b':' || rb[5] != b':' || !is_time_range(&rest[..8]) {
        return false;
    }
    let tail = &rest[8..];
    if tail.is_empty() {
        return true; // local date-time
    }
    // Optional fractional seconds (digits after '.').
    let tail = if let Some(frac) = tail.strip_prefix('.') {
        let digits_end = frac
            .find(|c: char| !c.is_ascii_digit())
            .unwrap_or(frac.len());
        if digits_end == 0 {
            return false; // '.' with no digits
        }
        &frac[digits_end..]
    } else {
        tail
    };
    if tail.is_empty() {
        return true; // local date-time with fraction
    }
    // Offset: 'Z'/'z' or ±HH:MM (RFC 3339 hour/minute ranges enforced).
    match tail.as_bytes()[0] {
        b'Z' | b'z' => tail.len() == 1,
        b'+' | b'-' => {
            let b = tail.as_bytes();
            if b.len() != 6 || b[3] != b':' {
                return false;
            }
            let digits =
                b[1..3].iter().all(u8::is_ascii_digit) && b[4..6].iter().all(u8::is_ascii_digit);
            if !digits {
                return false;
            }
            let h = (b[1] - b'0') as u32 * 10 + (b[2] - b'0') as u32;
            let m = (b[4] - b'0') as u32 * 10 + (b[5] - b'0') as u32;
            h <= 23 && m <= 59
        }
        _ => false,
    }
}

/// `YYYY-MM-DD` with digits in the right slots and a plausible calendar range
/// (leap years not enforced).
fn is_date(s: &str) -> bool {
    let b = s.as_bytes();
    if b.len() != 10 || b[4] != b'-' || b[7] != b'-' {
        return false;
    }
    let digits_ok = b.iter().enumerate().all(|(i, &c)| {
        if i == 4 || i == 7 {
            c == b'-'
        } else {
            c.is_ascii_digit()
        }
    });
    if !digits_ok {
        return false;
    }
    let y: u32 = s[0..4].parse().unwrap_or(0);
    let m: u32 = s[5..7].parse().unwrap_or(0);
    let d: u32 = s[8..10].parse().unwrap_or(0);
    y >= 1 && (1..=12).contains(&m) && (1..=31).contains(&d)
}

/// `HH:MM:SS` with plausible ranges.
///
/// The caller guarantees the slice is at least 8 bytes with `:` at offsets
/// 2 and 5, but NOT that the remaining offsets are digits — a crafted value
/// like `+:2:345` reaches here with `+` at offset 0. Digit-check first so
/// the arithmetic below can never underflow (a plain `- b'0'` on a byte
/// below `'0'` panics in debug builds).
fn is_time_range(s: &str) -> bool {
    let b = s.as_bytes();
    if b.len() < 8 {
        return false;
    }
    let digits_ok = b[..8]
        .iter()
        .enumerate()
        .all(|(i, &c)| i == 2 || i == 5 || c.is_ascii_digit());
    if !digits_ok {
        return false;
    }
    let h = (b[0] - b'0') as u32 * 10 + (b[1] - b'0') as u32;
    let m = (b[3] - b'0') as u32 * 10 + (b[4] - b'0') as u32;
    let sec = (b[6] - b'0') as u32 * 10 + (b[7] - b'0') as u32;
    h <= 23 && m <= 59 && sec <= 59
}

/// `.digits` fractional-seconds suffix.
fn fraction_only(s: &str) -> bool {
    s.starts_with('.') && s[1..].bytes().all(|c| c.is_ascii_digit())
}

/// Insert a (possibly dotted) key into a map, creating intermediate tables.
///
/// Duplicate keys are an error per the TOML spec, not a silent overwrite.
fn insert_dotted(map: &mut Map, key: &[String], value: Value) -> Result<()> {
    if key.len() == 1 {
        if map.contains_key(&key[0]) {
            return Err(Error::custom(alloc::format!(
                "toml: duplicate key `{}`",
                key[0]
            )));
        }
        map.insert(key[0].clone(), value);
        return Ok(());
    }
    let mut current = map;
    for (i, seg) in key.iter().enumerate() {
        let is_last = i + 1 == key.len();
        if is_last {
            if current.contains_key(seg) {
                return Err(Error::custom(alloc::format!(
                    "toml: duplicate key `{}`",
                    seg
                )));
            }
            current.insert(seg.clone(), value.clone());
            return Ok(());
        }
        if current.get(seg).is_none() {
            current.insert(seg.clone(), Value::Object(Map::new()));
        }
        current = match current.get_mut(seg) {
            Some(Value::Object(m)) => m,
            _ => return Err(Error::custom("toml: dotted key is not a table")),
        };
    }
    Ok(())
}

fn utf8_len(b: u8) -> Option<usize> {
    match b {
        0x00..=0x7F => Some(1),
        0xC0..=0xDF => Some(2),
        0xE0..=0xEF => Some(3),
        0xF0..=0xF7 => Some(4),
        _ => None,
    }
}