toml-spanner 1.0.2

High Performance Toml parser and deserializer that preserves span information with fast compile times.
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
use super::FromToml;
use crate::Item;
use crate::arena::Arena;
use crate::error::Error;
use crate::span::Spanned;

fn parse_val<'a, T: FromToml<'a>>(input: &'a str, arena: &'a Arena) -> Result<T, Error> {
    let mut doc = crate::parser::parse(input, arena).unwrap();
    let result = {
        let mut helper = doc.table_helper();
        helper.required::<T>("v")
    };
    match result {
        Ok(val) => Ok(val),
        Err(_) => Err(doc.ctx.errors.remove(0)),
    }
}

#[test]
fn deser_strings() {
    let arena = Arena::new();
    // String (owned)
    let val: String = parse_val(r#"v = "hello""#, &arena).unwrap();
    assert_eq!(val, "hello");

    // Str (borrowed)
    let val: &str = parse_val(r#"v = "borrowed""#, &arena).unwrap();
    assert_eq!(val, "borrowed");

    // Cow<str>
    let val: std::borrow::Cow<'_, str> = parse_val(r#"v = "cow""#, &arena).unwrap();
    assert_eq!(&*val, "cow");
}

#[test]
fn deser_booleans() {
    let arena = Arena::new();

    // true
    let val: bool = parse_val("v = true", &arena).unwrap();
    assert!(val);

    // false
    let val: bool = parse_val("v = false", &arena).unwrap();
    assert!(!val);

    // wrong type
    let err = parse_val::<bool>(r#"v = "not a bool""#, &arena).unwrap_err();
    assert!(matches!(err.kind(), crate::ErrorKind::Wanted { .. }));
}

#[test]
fn deser_integers() {
    let arena = Arena::new();

    // Signed types
    let val: i8 = parse_val("v = 42", &arena).unwrap();
    assert_eq!(val, 42);

    let val: i16 = parse_val("v = 1000", &arena).unwrap();
    assert_eq!(val, 1000);

    let val: i32 = parse_val("v = 100000", &arena).unwrap();
    assert_eq!(val, 100000);

    let val: i64 = parse_val("v = 9999999999", &arena).unwrap();
    assert_eq!(val, 9999999999);

    let val: isize = parse_val("v = -42", &arena).unwrap();
    assert_eq!(val, -42);

    // Unsigned types
    let val: u8 = parse_val("v = 255", &arena).unwrap();
    assert_eq!(val, 255);

    let val: u16 = parse_val("v = 65535", &arena).unwrap();
    assert_eq!(val, 65535);

    let val: u32 = parse_val("v = 100000", &arena).unwrap();
    assert_eq!(val, 100000);

    let val: u64 = parse_val("v = 9999999999", &arena).unwrap();
    assert_eq!(val, 9999999999);

    let val: usize = parse_val("v = 42", &arena).unwrap();
    assert_eq!(val, 42);

    // Out-of-range errors
    let err = parse_val::<i8>("v = 200", &arena).unwrap_err();
    assert!(matches!(
        err.kind(),
        crate::ErrorKind::OutOfRange { ty: &"i8", .. }
    ));

    let err = parse_val::<u8>("v = 256", &arena).unwrap_err();
    assert!(matches!(
        err.kind(),
        crate::ErrorKind::OutOfRange { ty: &"u8", .. }
    ));

    let err = parse_val::<u64>("v = -1", &arena).unwrap_err();
    assert!(matches!(
        err.kind(),
        crate::ErrorKind::OutOfRange { ty: &"u64", .. }
    ));

    let err = parse_val::<usize>("v = -1", &arena).unwrap_err();
    assert!(matches!(
        err.kind(),
        crate::ErrorKind::OutOfRange { ty: &"usize", .. }
    ));

    // Wrong type
    let err = parse_val::<i32>(r#"v = "not an int""#, &arena).unwrap_err();
    assert!(matches!(err.kind(), crate::ErrorKind::Wanted { .. }));
}

#[test]
fn deser_floats() {
    let arena = Arena::new();

    // f32
    let val: f32 = parse_val("v = 3.15", &arena).unwrap();
    assert!((val - 3.15_f32).abs() < 0.001);

    // f64
    let val: f64 = parse_val("v = 3.15", &arena).unwrap();
    assert!((val - 3.15).abs() < f64::EPSILON);

    // Wrong type
    let err = parse_val::<f64>(r#"v = "not a float""#, &arena).unwrap_err();
    assert!(matches!(err.kind(), crate::ErrorKind::Wanted { .. }));

    let err = parse_val::<f32>(r#"v = "not a float""#, &arena).unwrap_err();
    assert!(matches!(err.kind(), crate::ErrorKind::Wanted { .. }));
}

#[test]
fn deser_vecs() {
    let arena = Arena::new();

    // Integers
    let val: Vec<i64> = parse_val("v = [1, 2, 3]", &arena).unwrap();
    assert_eq!(val, vec![1, 2, 3]);

    // Strings
    let val: Vec<String> = parse_val(r#"v = ["a", "b"]"#, &arena).unwrap();
    assert_eq!(val, vec!["a", "b"]);

    // Empty
    let val: Vec<i64> = parse_val("v = []", &arena).unwrap();
    assert!(val.is_empty());

    // Wrong type
    let err = parse_val::<Vec<i64>>(r#"v = "not an array""#, &arena).unwrap_err();
    assert!(matches!(err.kind(), crate::ErrorKind::Wanted { .. }));
}

#[test]
fn deser_spanned() {
    let arena = Arena::new();
    let input = "v = 42";
    let mut doc = crate::parser::parse(input, &arena).unwrap();
    let val: Spanned<i64> = {
        let mut helper = doc.table_helper();
        helper.required("v").unwrap()
    };
    assert_eq!(val.value, 42);
    assert_eq!(&input[val.span.start as usize..val.span.end as usize], "42");
}

#[test]
fn into_remaining() {
    fn check(key_count: usize, use_every_nth: usize) {
        let mut toml = String::new();
        for i in 0..key_count {
            if !toml.is_empty() {
                toml.push('\n');
            }
            toml.push_str(&format!("k{i} = {i}"));
        }
        let arena = Arena::new();
        let mut doc = crate::parser::parse(&toml, &arena).unwrap();
        let mut helper = doc.table_helper();

        let mut expected_remaining = Vec::new();
        for i in 0..key_count {
            let name = format!("k{i}");
            if use_every_nth > 0 && i % use_every_nth == 0 {
                let _: Option<i64> = helper.optional(&name);
            } else {
                expected_remaining.push(name);
            }
        }

        let keys: Vec<_> = helper.into_remaining().map(|(k, _)| k.name).collect();
        assert_eq!(
            keys, expected_remaining,
            "key_count={key_count} use_every_nth={use_every_nth}"
        );
    }

    // Empty table.
    check(0, 0);
    // Single bucket, none/some/all used.
    check(3, 0);
    check(3, 2);
    check(3, 1);
    // Exact bucket boundary.
    check(64, 0);
    check(64, 2);
    check(64, 1);
    // Multi-bucket, non-aligned.
    check(65, 0);
    check(65, 3);

    // too slow under mirir.
    if !cfg!(miri) {
        check(65, 1);
        // Two full buckets + partial third.
        check(150, 0);
        check(150, 5);
        check(150, 1);
    }
}

#[test]
fn table_helper_workflows() {
    let arena = Arena::new();

    // require_empty succeeds when all fields are consumed
    let mut doc = crate::parser::parse("a = 1\nb = 2", &arena).unwrap();
    {
        let mut helper = doc.table_helper();
        let _: i64 = helper.required("a").unwrap();
        let _: i64 = helper.required("b").unwrap();
        assert_eq!(helper.remaining_count(), 0);
        helper.require_empty().unwrap();
    }
    assert!(doc.ctx.errors.is_empty());

    // require_empty fails with unexpected keys when fields are not consumed
    let mut doc = crate::parser::parse("a = 1\nb = 2\nc = 3", &arena).unwrap();
    {
        let mut helper = doc.table_helper();
        let _: i64 = helper.required("a").unwrap();
        assert_eq!(helper.remaining_count(), 2);
        assert!(helper.require_empty().is_err());
    }
    assert!(matches!(
        doc.ctx.errors[0].kind(),
        crate::ErrorKind::UnexpectedKey { .. }
    ));

    // required() returns MissingField error for nonexistent key
    let mut doc = crate::parser::parse("a = 1", &arena).unwrap();
    {
        let mut helper = doc.table_helper();
        assert!(helper.required::<i64>("nonexistent").is_err());
    }
    assert!(matches!(
        doc.ctx.errors[0].kind(),
        crate::ErrorKind::MissingField("nonexistent")
    ));

    // optional() returns None for missing key (no error) and None with
    // error on type mismatch
    let mut doc = crate::parser::parse(r#"a = "string""#, &arena).unwrap();
    {
        let mut helper = doc.table_helper();
        assert!(helper.optional::<i64>("nonexistent").is_none());
        assert!(helper.optional::<i64>("a").is_none());
    }
    assert_eq!(doc.ctx.errors.len(), 1);

    // Indexed table (7+ entries) exercises get_entry hash path
    let mut lines = Vec::new();
    for i in 0..8 {
        lines.push(format!("k{i} = {i}"));
    }
    let input = lines.join("\n");
    let mut doc = crate::parser::parse(&input, &arena).unwrap();
    {
        let mut helper = doc.table_helper();
        let v: i64 = helper.required("k0").unwrap();
        assert_eq!(v, 0);
        let v: i64 = helper.required("k7").unwrap();
        assert_eq!(v, 7);
        assert!(helper.required::<i64>("nonexistent").is_err());
        assert_eq!(helper.remaining_count(), 6);
    }
}

#[test]
fn deser_boxed_and_array_types() {
    let arena = Arena::new();

    // Box<str>
    let val: Box<str> = parse_val(r#"v = "boxed""#, &arena).unwrap();
    assert_eq!(&*val, "boxed");
    let err = parse_val::<Box<str>>("v = 42", &arena).unwrap_err();
    assert!(matches!(err.kind(), crate::ErrorKind::Wanted { .. }));

    // Box<T>
    let val: Box<i64> = parse_val("v = 42", &arena).unwrap();
    assert_eq!(*val, 42);
    let err = parse_val::<Box<i64>>(r#"v = "nope""#, &arena).unwrap_err();
    assert!(matches!(err.kind(), crate::ErrorKind::Wanted { .. }));

    // Box<[T]>
    let val: Box<[i64]> = parse_val("v = [1, 2, 3]", &arena).unwrap();
    assert_eq!(&*val, &[1, 2, 3]);
    let err = parse_val::<Box<[i64]>>(r#"v = "nope""#, &arena).unwrap_err();
    assert!(matches!(err.kind(), crate::ErrorKind::Wanted { .. }));

    // String wrong type
    let err = parse_val::<String>("v = 42", &arena).unwrap_err();
    assert!(matches!(err.kind(), crate::ErrorKind::Wanted { .. }));

    // [T; N] correct size
    let val: [i64; 3] = parse_val("v = [1, 2, 3]", &arena).unwrap();
    assert_eq!(val, [1, 2, 3]);

    // [T; N] wrong size
    let err = parse_val::<[i64; 2]>("v = [1, 2, 3]", &arena).unwrap_err();
    assert!(matches!(err.kind(), crate::ErrorKind::Custom(_)));

    // &str and Cow<str> wrong type errors
    let err = parse_val::<&str>("v = 42", &arena).unwrap_err();
    assert!(matches!(err.kind(), crate::ErrorKind::Wanted { .. }));
    let err = parse_val::<std::borrow::Cow<'_, str>>("v = 42", &arena).unwrap_err();
    assert!(matches!(err.kind(), crate::ErrorKind::Wanted { .. }));

    // Vec<T> with element type errors
    let mut doc = crate::parser::parse(r#"v = [1, "bad", 3, "worse"]"#, &arena).unwrap();
    let result = {
        let mut helper = doc.table_helper();
        helper.required::<Vec<i64>>("v")
    };
    assert!(result.is_err());
    assert_eq!(doc.ctx.errors.len(), 2);
}

#[test]
fn require_custom_string_and_context_errors() {
    let arena = Arena::new();

    // require_custom_string via parse and helper
    let mut doc = crate::parser::parse("ip = \"127.0.0.1\"\nport = 8080", &arena).unwrap();
    {
        let helper = doc.table_helper();
        let (_, ip_item) = helper.get_entry("ip").unwrap();
        assert_eq!(
            ip_item
                .require_custom_string(helper.ctx, &"an IPv4 address")
                .unwrap(),
            "127.0.0.1"
        );
        let (_, port_item) = helper.get_entry("port").unwrap();
        assert!(
            port_item
                .require_custom_string(helper.ctx, &"an IPv4 address")
                .is_err()
        );
    }
    assert!(matches!(
        doc.ctx.errors[0].kind(),
        crate::ErrorKind::Wanted { .. }
    ));

    // table_helper() on table vs non-table items
    let mut doc = crate::parser::parse("[sub]\na = 1\nval = 42", &arena).unwrap();
    {
        let helper = doc.table_helper();
        let (_, sub_item) = helper.get_entry("sub").unwrap();
        let mut th = sub_item.table_helper(helper.ctx).unwrap();
        let v: i64 = th.required("a").unwrap();
        assert_eq!(v, 1);
    }
    let mut doc = crate::parser::parse("val = 42", &arena).unwrap();
    {
        let helper = doc.table_helper();
        let (_, val_item) = helper.get_entry("val").unwrap();
        assert!(val_item.table_helper(helper.ctx).is_err());
    }

    // Context::report_error_at and push_error
    let span = crate::Span::new(0, 5);
    let mut ctx = super::Context {
        arena: &arena,
        index: Default::default(),
        errors: Vec::new(),
        source: "",
    };
    let _ = ctx.report_error_at("something went wrong", span);
    let _ = ctx.push_error(Error::new(crate::ErrorKind::InvalidInteger(""), span));
    assert_eq!(ctx.errors.len(), 2);
    assert!(matches!(ctx.errors[0].kind(), crate::ErrorKind::Custom(_)));
    assert!(matches!(
        ctx.errors[1].kind(),
        crate::ErrorKind::InvalidInteger(_)
    ));
}

#[test]
fn root_methods() {
    let arena = Arena::new();

    // table(), errors(), has_errors(), Debug, Index
    let doc = crate::parser::parse("a = 1\nb = 2", &arena).unwrap();
    assert_eq!(doc.table().len(), 2);
    assert_eq!(doc["a"].as_i64(), Some(1));
    assert!(doc.errors().is_empty());
    assert!(!doc.has_errors());
    let debug = format!("{:?}", doc);
    assert!(debug.contains("a"));

    // into_item() converts root table to item
    let doc = crate::parser::parse("x = 42", &arena).unwrap();
    let item = doc.into_item();
    assert_eq!(item.as_table().unwrap().len(), 1);

    // deserialize() on root (type mismatch: root is table, asking for i64)
    let mut doc = crate::parser::parse("a = 1", &arena).unwrap();
    let err = doc.to::<i64>().unwrap_err();
    assert!(!err.errors.is_empty());
}

#[test]
fn required_item_and_optional_item() {
    let arena = Arena::new();

    // required_item succeeds for each value kind
    let mut doc = crate::parser::parse(
        r#"
s = "hello"
i = 42
f = 3.15
b = true
a = [1, 2]

[t]
x = 1
"#,
        &arena,
    )
    .unwrap();
    {
        let mut h = doc.table_helper();

        let item = h.required_item("s").unwrap();
        assert_eq!(item.as_str(), Some("hello"));

        let item = h.required_item("i").unwrap();
        assert_eq!(item.as_i64(), Some(42));

        let item = h.required_item("f").unwrap();
        assert!((item.as_f64().unwrap() - 3.15).abs() < f64::EPSILON);

        let item = h.required_item("b").unwrap();
        assert_eq!(item.as_bool(), Some(true));

        let item = h.required_item("a").unwrap();
        assert_eq!(item.as_array().unwrap().len(), 2);

        let item = h.required_item("t").unwrap();
        assert!(item.as_table().is_some());

        assert_eq!(h.remaining_count(), 0);
        h.require_empty().unwrap();
    }
    assert!(doc.ctx.errors.is_empty());

    // required_item fails for missing key
    let mut doc = crate::parser::parse("a = 1", &arena).unwrap();
    {
        let mut h = doc.table_helper();
        assert!(h.required_item("missing").is_err());
    }
    assert!(matches!(
        doc.ctx.errors[0].kind(),
        crate::ErrorKind::MissingField("missing")
    ));

    // optional_item returns Some for present key, None for absent
    let mut doc = crate::parser::parse("x = 99\ny = true", &arena).unwrap();
    {
        let mut h = doc.table_helper();

        let item = h.optional_item("x");
        assert!(item.is_some());
        assert_eq!(item.unwrap().as_i64(), Some(99));

        let item = h.optional_item("y");
        assert_eq!(item.unwrap().as_bool(), Some(true));

        assert!(h.optional_item("absent").is_none());

        assert_eq!(h.remaining_count(), 0);
        h.require_empty().unwrap();
    }
    assert!(doc.ctx.errors.is_empty());

    // optional_item does not record an error for missing keys
    let mut doc = crate::parser::parse("a = 1", &arena).unwrap();
    {
        let mut h = doc.table_helper();
        assert!(h.optional_item("nope").is_none());
        let _ = h.optional_item("a");
        h.require_empty().unwrap();
    }
    assert!(doc.ctx.errors.is_empty());

    // Consuming with required_item/optional_item makes require_empty pass
    let mut doc = crate::parser::parse("a = 1\nb = 2\nc = 3", &arena).unwrap();
    {
        let mut h = doc.table_helper();
        h.required_item("a").unwrap();
        h.optional_item("b");
        h.required_item("c").unwrap();
        h.require_empty().unwrap();
    }
    assert!(doc.ctx.errors.is_empty());

    // Unconsumed fields after required_item cause require_empty to fail
    let mut doc = crate::parser::parse("a = 1\nb = 2\nc = 3", &arena).unwrap();
    {
        let mut h = doc.table_helper();
        h.required_item("a").unwrap();
        assert_eq!(h.remaining_count(), 2);
        assert!(h.require_empty().is_err());
    }
    assert!(matches!(
        doc.ctx.errors[0].kind(),
        crate::ErrorKind::UnexpectedKey { .. }
    ));

    // Works with indexed tables (7+ entries)
    let mut lines = Vec::new();
    for i in 0..10 {
        lines.push(format!("k{i} = {i}"));
    }
    let input = lines.join("\n");
    let mut doc = crate::parser::parse(&input, &arena).unwrap();
    {
        let mut h = doc.table_helper();
        let item = h.required_item("k0").unwrap();
        assert_eq!(item.as_i64(), Some(0));
        let item = h.required_item("k9").unwrap();
        assert_eq!(item.as_i64(), Some(9));
        let item = h.optional_item("k5").unwrap();
        assert_eq!(item.as_i64(), Some(5));
        assert!(h.optional_item("nonexistent").is_none());
        assert!(h.required_item("also_missing").is_err());
    }

    // Duplicate calls to optional_item on the same key return the item but
    // don't double-count consumption.
    let mut doc = crate::parser::parse("only = 1", &arena).unwrap();
    {
        let mut h = doc.table_helper();
        h.optional_item("only");
        h.optional_item("only");
        assert_eq!(h.remaining_count(), 0);
        h.require_empty().unwrap();
    }
    assert!(doc.ctx.errors.is_empty());
}

#[test]
fn required_entry_and_optional_entry() {
    let arena = Arena::new();

    // required_entry returns both key and item
    let input = "name = \"alice\"\nage = 30";
    let mut doc = crate::parser::parse(input, &arena).unwrap();
    {
        let mut h = doc.table_helper();

        let (key, item) = h.required_entry("name").unwrap();
        assert_eq!(key.name, "name");
        assert_eq!(item.as_str(), Some("alice"));
        // Key span should cover "name" in the source
        let key_text = &input[key.span.start as usize..key.span.end as usize];
        assert_eq!(key_text, "name");

        let (key, item) = h.required_entry("age").unwrap();
        assert_eq!(key.name, "age");
        assert_eq!(item.as_i64(), Some(30));

        h.require_empty().unwrap();
    }
    assert!(doc.ctx.errors.is_empty());

    // required_entry fails for missing key
    let mut doc = crate::parser::parse("x = 1", &arena).unwrap();
    {
        let mut h = doc.table_helper();
        assert!(h.required_entry("missing").is_err());
    }
    assert!(matches!(
        doc.ctx.errors[0].kind(),
        crate::ErrorKind::MissingField("missing")
    ));

    // optional_entry returns Some with key+item for present key
    let input = "color = \"red\"";
    let mut doc = crate::parser::parse(input, &arena).unwrap();
    {
        let mut h = doc.table_helper();

        let entry = h.optional_entry("color");
        assert!(entry.is_some());
        let (key, item) = entry.unwrap();
        assert_eq!(key.name, "color");
        assert_eq!(item.as_str(), Some("red"));

        h.require_empty().unwrap();
    }
    assert!(doc.ctx.errors.is_empty());

    // optional_entry returns None for absent key without error
    let mut doc = crate::parser::parse("a = 1", &arena).unwrap();
    {
        let mut h = doc.table_helper();
        assert!(h.optional_entry("nope").is_none());
        h.optional_entry("a");
        h.require_empty().unwrap();
    }
    assert!(doc.ctx.errors.is_empty());

    // Entries are marked consumed correctly
    let mut doc = crate::parser::parse("a = 1\nb = 2\nc = 3", &arena).unwrap();
    {
        let mut h = doc.table_helper();
        h.optional_entry("a");
        h.required_entry("c").unwrap();
        assert_eq!(h.remaining_count(), 1);
        assert!(h.require_empty().is_err());
    }
    assert!(matches!(
        doc.ctx.errors[0].kind(),
        crate::ErrorKind::UnexpectedKey { .. }
    ));

    // Works with indexed tables (7+ entries)
    let mut lines = Vec::new();
    for i in 0..8 {
        lines.push(format!("field{i} = \"{i}\""));
    }
    let input = lines.join("\n");
    let mut doc = crate::parser::parse(&input, &arena).unwrap();
    {
        let mut h = doc.table_helper();
        let (key, item) = h.required_entry("field0").unwrap();
        assert_eq!(key.name, "field0");
        assert_eq!(item.as_str(), Some("0"));
        let (key, item) = h.required_entry("field7").unwrap();
        assert_eq!(key.name, "field7");
        assert_eq!(item.as_str(), Some("7"));
        assert!(h.optional_entry("nonexistent").is_none());
    }

    // Key span is valid for quoted keys
    let input = r#""quoted-key" = 42"#;
    let mut doc = crate::parser::parse(input, &arena).unwrap();
    {
        let mut h = doc.table_helper();
        let (key, item) = h.required_entry("quoted-key").unwrap();
        assert_eq!(key.name, "quoted-key");
        assert_eq!(item.as_i64(), Some(42));
    }
}

#[test]
fn required_mapped_and_optional_mapped() {
    use std::net::Ipv4Addr;

    fn parse_positive_int(item: &crate::item::Item<'_>) -> Result<u32, Error> {
        let val = item
            .as_i64()
            .ok_or_else(|| item.expected(&"a positive integer"))?;
        if val > 0 && val <= u32::MAX as i64 {
            Ok(val as u32)
        } else {
            Err(item.expected(&"a positive integer"))
        }
    }

    fn parse_uppercase(item: &crate::item::Item<'_>) -> Result<String, Error> {
        let s = item.as_str().ok_or_else(|| item.expected(&"a string"))?;
        Ok(s.to_uppercase())
    }

    let arena = Arena::new();

    // required_mapped succeeds with a valid mapping function
    let mut doc =
        crate::parser::parse("ip = \"192.168.1.1\"\ncount = 5\nname = \"hello\"", &arena).unwrap();
    {
        let mut h = doc.table_helper();

        let ip: Ipv4Addr = h.required_mapped("ip", Item::parse::<Ipv4Addr>).unwrap();
        assert_eq!(ip, Ipv4Addr::new(192, 168, 1, 1));

        let count: u32 = h.required_mapped("count", parse_positive_int).unwrap();
        assert_eq!(count, 5);

        let name: String = h.required_mapped("name", parse_uppercase).unwrap();
        assert_eq!(name, "HELLO");

        h.require_empty().unwrap();
    }
    assert!(doc.ctx.errors.is_empty());

    // required_mapped fails for missing key
    let mut doc = crate::parser::parse("a = 1", &arena).unwrap();
    {
        let mut h = doc.table_helper();
        assert!(h.required_mapped("missing", parse_positive_int).is_err());
    }
    assert!(matches!(
        doc.ctx.errors[0].kind(),
        crate::ErrorKind::MissingField("missing")
    ));

    // required_mapped fails when the mapping function returns an error
    let mut doc = crate::parser::parse("ip = \"not-an-ip\"", &arena).unwrap();
    {
        let mut h = doc.table_helper();
        assert!(h.required_mapped("ip", Item::parse::<Ipv4Addr>).is_err());
    }
    assert_eq!(doc.ctx.errors.len(), 1);
    assert!(matches!(
        doc.ctx.errors[0].kind(),
        crate::ErrorKind::Custom(_)
    ));

    // required_mapped fails when item is wrong type for mapping
    let mut doc = crate::parser::parse("count = -5", &arena).unwrap();
    {
        let mut h = doc.table_helper();
        assert!(h.required_mapped("count", parse_positive_int).is_err());
    }
    assert_eq!(doc.ctx.errors.len(), 1);

    // optional_mapped returns Some for valid mapping
    let mut doc = crate::parser::parse("ip = \"10.0.0.1\"\nport = 8080", &arena).unwrap();
    {
        let mut h = doc.table_helper();

        let ip = h.optional_mapped("ip", Item::parse::<Ipv4Addr>);
        assert_eq!(ip, Some(Ipv4Addr::new(10, 0, 0, 1)));

        let port = h.optional_mapped("port", parse_positive_int);
        assert_eq!(port, Some(8080));

        h.require_empty().unwrap();
    }
    assert!(doc.ctx.errors.is_empty());

    // optional_mapped returns None for missing key without recording an error
    let mut doc = crate::parser::parse("a = 1", &arena).unwrap();
    {
        let mut h = doc.table_helper();
        assert!(
            h.optional_mapped("absent", Item::parse::<Ipv4Addr>)
                .is_none()
        );
        h.optional_mapped("a", parse_positive_int);
        h.require_empty().unwrap();
    }
    assert!(doc.ctx.errors.is_empty());

    // optional_mapped returns None when mapping fails, records error
    let mut doc = crate::parser::parse("ip = \"bad\"", &arena).unwrap();
    {
        let mut h = doc.table_helper();
        assert!(h.optional_mapped("ip", Item::parse::<Ipv4Addr>).is_none());
        h.require_empty().unwrap();
    }
    assert_eq!(doc.ctx.errors.len(), 1);
    assert!(matches!(
        doc.ctx.errors[0].kind(),
        crate::ErrorKind::Custom(_)
    ));

    // optional_mapped returns None when item is wrong type, records error
    let mut doc = crate::parser::parse("name = 42", &arena).unwrap();
    {
        let mut h = doc.table_helper();
        assert!(h.optional_mapped("name", parse_uppercase).is_none());
        h.require_empty().unwrap();
    }
    assert_eq!(doc.ctx.errors.len(), 1);

    // Both mark fields as consumed: mixing mapped with other helpers
    let mut doc = crate::parser::parse(
        "ip = \"1.2.3.4\"\nname = \"test\"\ncount = 7\nextra = true",
        &arena,
    )
    .unwrap();
    {
        let mut h = doc.table_helper();
        let _: Ipv4Addr = h.required_mapped("ip", Item::parse::<Ipv4Addr>).unwrap();
        let _: String = h.required("name").unwrap();
        let _ = h.optional_mapped("count", parse_positive_int);
        let _: bool = h.optional("extra").unwrap();
        assert_eq!(h.remaining_count(), 0);
        h.require_empty().unwrap();
    }
    assert!(doc.ctx.errors.is_empty());

    // Works with indexed tables (7+ entries)
    let mut lines = Vec::new();
    for i in 0..8 {
        lines.push(format!("n{i} = \"{i}\""));
    }
    let input = lines.join("\n");
    let mut doc = crate::parser::parse(&input, &arena).unwrap();
    {
        let mut h = doc.table_helper();
        let v: String = h.required_mapped("n0", parse_uppercase).unwrap();
        assert_eq!(v, "0");
        let v = h.optional_mapped("n7", parse_uppercase);
        assert_eq!(v.as_deref(), Some("7"));
        assert!(h.required_mapped("nonexistent", parse_uppercase).is_err());
        assert!(h.optional_mapped("also_missing", parse_uppercase).is_none());
    }
}

#[test]
fn deser_hashmap_and_btreemap() {
    let arena = Arena::new();

    // BTreeMap<String, i64>
    let input = r#"
[v]
alpha = 1
beta = 2
gamma = 3
"#;
    let val: std::collections::BTreeMap<String, i64> = parse_val(input, &arena).unwrap();
    assert_eq!(val.len(), 3);
    assert_eq!(val["alpha"], 1);
    assert_eq!(val["beta"], 2);
    assert_eq!(val["gamma"], 3);

    // HashMap<String, String>
    let input = r#"
[v]
key1 = "val1"
key2 = "val2"
"#;
    let val: std::collections::HashMap<String, String> = parse_val(input, &arena).unwrap();
    assert_eq!(val.len(), 2);
    assert_eq!(val["key1"], "val1");
    assert_eq!(val["key2"], "val2");

    // BTreeMap wrong type (not a table)
    let err = parse_val::<std::collections::BTreeMap<String, i64>>("v = 42", &arena).unwrap_err();
    assert!(matches!(err.kind(), crate::ErrorKind::Wanted { .. }));

    // HashMap wrong type
    let err =
        parse_val::<std::collections::HashMap<String, i64>>("v = \"nope\"", &arena).unwrap_err();
    assert!(matches!(err.kind(), crate::ErrorKind::Wanted { .. }));

    // PathBuf
    let val: std::path::PathBuf = parse_val(r#"v = "/usr/bin/test""#, &arena).unwrap();
    assert_eq!(val, std::path::PathBuf::from("/usr/bin/test"));

    // PathBuf wrong type
    let err = parse_val::<std::path::PathBuf>("v = 42", &arena).unwrap_err();
    assert!(matches!(err.kind(), crate::ErrorKind::Wanted { .. }));

    // HashMap with value type mismatch triggers error accumulation
    let input = r#"
[v]
good = 1
bad = "not a number"
"#;
    let err = parse_val::<std::collections::HashMap<String, i64>>(input, &arena).unwrap_err();
    assert!(matches!(err.kind(), crate::ErrorKind::Wanted { .. }));

    // BTreeMap with value type mismatch
    let input = r#"
[v]
ok = 10
nope = "string"
"#;
    let err = parse_val::<std::collections::BTreeMap<String, i64>>(input, &arena).unwrap_err();
    assert!(matches!(err.kind(), crate::ErrorKind::Wanted { .. }));
}

#[test]
fn from_str_and_to_string_roundtrip() {
    use std::collections::BTreeMap;

    // from_str convenience function with flat key-value pairs
    let val: BTreeMap<String, String> = crate::from_str("x = \"hello\"\ny = \"world\"").unwrap();
    assert_eq!(val["x"], "hello");
    assert_eq!(val["y"], "world");

    // to_string convenience function
    let mut map = BTreeMap::new();
    map.insert("name".to_string(), "test".to_string());
    map.insert("value".to_string(), "42".to_string());
    let toml_str = crate::to_string(&map).unwrap();
    assert!(toml_str.contains("name = \"test\""), "got: {toml_str}");
    assert!(toml_str.contains("value = \"42\""), "got: {toml_str}");

    // Roundtrip: to_string then from_str
    let restored: BTreeMap<String, String> = crate::from_str(&toml_str).unwrap();
    assert_eq!(restored["name"], "test");
    assert_eq!(restored["value"], "42");

    // Formatting::preserved_from preserving formatting
    let source = "name = \"test\"\nvalue = \"42\"\n";
    let arena = crate::Arena::new();
    let doc = crate::parse(source, &arena).unwrap();
    let output = crate::Formatting::preserved_from(&doc)
        .format(&map)
        .unwrap();
    assert!(output.contains("name = \"test\""), "got: {output}");

    // to_string with non-table value should error
    let err = crate::to_string(&42i64).unwrap_err();
    assert!(
        err.message.contains("Top-level item must be a table"),
        "got: {}",
        err.message
    );

    // Formatting::format with non-table value should error
    let err = crate::Formatting::preserved_from(&doc)
        .format(&42i64)
        .unwrap_err();
    assert!(
        err.message.contains("Top-level item must be a table"),
        "got: {}",
        err.message
    );
}

#[test]
fn to_toml_wrapper_types() {
    use crate::Arena;
    use crate::ser::ToToml;
    use std::collections::{BTreeMap, BTreeSet};
    use std::path::PathBuf;
    use std::rc::Rc;
    use std::sync::Arc;

    let arena = Arena::new();

    // str (not String)
    let s: &str = "hello";
    let item = s.to_toml(&arena).unwrap();
    assert_eq!(item.as_str(), Some("hello"));

    // &T delegates to T
    let num: i64 = 42;
    let item = (&num).to_toml(&arena).unwrap();
    assert_eq!(item.as_i64(), Some(42));

    // Box<T>
    let boxed = Box::new(99i64);
    let item = boxed.to_toml(&arena).unwrap();
    assert_eq!(item.as_i64(), Some(99));

    // Rc<T>
    let rc = Rc::new("rc-str".to_string());
    let item = rc.to_toml(&arena).unwrap();
    assert_eq!(item.as_str(), Some("rc-str"));

    // Arc<T>
    let arc = Arc::new(7i64);
    let item = arc.to_toml(&arena).unwrap();
    assert_eq!(item.as_i64(), Some(7));

    // Cow<T>
    let cow: std::borrow::Cow<'_, str> = std::borrow::Cow::Borrowed("cow-val");
    let item = cow.to_toml(&arena).unwrap();
    assert_eq!(item.as_str(), Some("cow-val"));

    // char
    let ch = 'A';
    let item = ch.to_toml(&arena).unwrap();
    assert_eq!(item.as_str(), Some("A"));

    // f32
    let f: f32 = 1.5;
    let item = f.to_toml(&arena).unwrap();
    assert!((item.as_f64().unwrap() - 1.5).abs() < f64::EPSILON);

    // f64
    let f: f64 = 2.5;
    let item = f.to_toml(&arena).unwrap();
    assert!((item.as_f64().unwrap() - 2.5).abs() < f64::EPSILON);

    // bool
    let b = true;
    let item = b.to_toml(&arena).unwrap();
    assert_eq!(item.as_bool(), Some(true));

    // PathBuf
    let path = PathBuf::from("/usr/bin");
    let item = path.to_toml(&arena).unwrap();
    assert_eq!(item.as_str(), Some("/usr/bin"));

    // std::path::Path (via &Path)
    let path = std::path::Path::new("/etc/config");
    let item = path.to_toml(&arena).unwrap();
    assert_eq!(item.as_str(), Some("/etc/config"));

    // Vec<T> → [T]
    let vec = vec![1i64, 2, 3];
    let item = vec.to_toml(&arena).unwrap();
    assert_eq!(item.as_array().unwrap().len(), 3);

    // [T; N]
    let arr = [10i64, 20, 30];
    let item = arr.to_toml(&arena).unwrap();
    assert_eq!(item.as_array().unwrap().len(), 3);

    // BTreeSet
    let mut set = BTreeSet::new();
    set.insert("a".to_string());
    set.insert("b".to_string());
    let item = set.to_toml(&arena).unwrap();
    assert_eq!(item.as_array().unwrap().len(), 2);

    // HashSet
    let mut hset = std::collections::HashSet::new();
    hset.insert("x".to_string());
    let item = hset.to_toml(&arena).unwrap();
    assert_eq!(item.as_array().unwrap().len(), 1);

    // Option<T>: Some and None
    let some_val: Option<i64> = Some(5);
    let item = some_val.to_optional_toml(&arena).unwrap();
    assert!(item.is_some());
    assert_eq!(item.unwrap().as_i64(), Some(5));

    let none_val: Option<i64> = None;
    let item = none_val.to_optional_toml(&arena).unwrap();
    assert!(item.is_none());

    // BTreeMap (as table)
    let mut btm = BTreeMap::new();
    btm.insert("k".to_string(), "v".to_string());
    let item = btm.to_toml(&arena).unwrap();
    assert!(item.as_table().is_some());
    assert_eq!(
        item.as_table().unwrap().get("k").unwrap().as_str(),
        Some("v")
    );

    // HashMap (as table)
    let mut hm = std::collections::HashMap::new();
    hm.insert("key".to_string(), 42i64);
    let item = hm.to_toml(&arena).unwrap();
    assert!(item.as_table().is_some());

    // Integer types
    let item = (42u8).to_toml(&arena).unwrap();
    assert_eq!(item.as_i64(), Some(42));
    let item = (-5i8).to_toml(&arena).unwrap();
    assert_eq!(item.as_i64(), Some(-5));
    let item = (1000u16).to_toml(&arena).unwrap();
    assert_eq!(item.as_i64(), Some(1000));
    let item = (-200i16).to_toml(&arena).unwrap();
    assert_eq!(item.as_i64(), Some(-200));
    let item = (100000u32).to_toml(&arena).unwrap();
    assert_eq!(item.as_i64(), Some(100000));
    let item = (-50000i32).to_toml(&arena).unwrap();
    assert_eq!(item.as_i64(), Some(-50000));

    // Table::to_toml (clone)
    let tbl = btm.to_toml(&arena).unwrap();
    let tbl_ref = tbl.as_table().unwrap();
    let item = tbl_ref.to_toml(&arena).unwrap();
    assert!(item.as_table().is_some());

    // Array::to_toml (clone)
    let arr_item = vec.to_toml(&arena).unwrap();
    let arr_ref = arr_item.as_array().unwrap();
    let item = arr_ref.to_toml(&arena).unwrap();
    assert_eq!(item.as_array().unwrap().len(), 3);

    // Item::to_toml (clone)
    let original = Item::from(42i64);
    let item = original.to_toml(&arena).unwrap();
    assert_eq!(item.as_i64(), Some(42));

    // &mut T delegates to T
    let mut num2: i64 = 77;
    let num2_ref = &mut num2;
    let item = num2_ref.to_toml(&arena).unwrap();
    assert_eq!(item.as_i64(), Some(77));

    // Cow (owned variant)
    let cow_owned: std::borrow::Cow<'_, str> = std::borrow::Cow::Owned("owned-val".to_string());
    let item = cow_owned.to_toml(&arena).unwrap();
    assert_eq!(item.as_str(), Some("owned-val"));

    // Multi-byte char
    let ch_multi = '\u{1F600}';
    let item = ch_multi.to_toml(&arena).unwrap();
    assert_eq!(item.as_str(), Some("\u{1F600}"));
}

#[test]
fn toml_path_on_unexpected_key() {
    use crate::error::ErrorKind;

    let arena = Arena::new();

    // Nested table: unexpected key in a sub-table gets a path
    let input = r#"
[server]
host = "localhost"
port = 8080
unknown_field = true
"#;
    let mut doc = crate::parser::parse(input, &arena).unwrap();
    let result = {
        let (ctx, table) = doc.split();
        let server_entry = table.get("server").unwrap();
        let server_table = server_entry.as_table().unwrap();
        let mut th = super::TableHelper::new(ctx, server_table);
        let _: String = th.required("host").unwrap();
        let _: i64 = th.required("port").unwrap();
        let r = th.require_empty();
        super::compute_paths(table, &mut ctx.errors);
        r
    };
    assert!(result.is_err());
    assert_eq!(doc.ctx.errors.len(), 1);
    assert!(matches!(
        doc.ctx.errors[0].kind(),
        ErrorKind::UnexpectedKey { .. }
    ));
    assert!(doc.ctx.errors[0].path().is_some());
    assert_eq!(
        format!("{}", doc.ctx.errors[0]),
        "unexpected key at `server.unknown_field`"
    );

    // Deeply nested: array of tables with unexpected key
    let input = r#"
[[items]]
name = "a"
bogus = 1
"#;
    let mut doc = crate::parser::parse(input, &arena).unwrap();
    let result = {
        let (ctx, table) = doc.split();
        let items_entry = table.get("items").unwrap();
        let items_array = items_entry.as_array().unwrap();
        let elem = &items_array.as_slice()[0];
        let elem_table = elem.as_table().unwrap();
        let mut th = super::TableHelper::new(ctx, elem_table);
        let _: String = th.required("name").unwrap();
        let r = th.require_empty();
        super::compute_paths(table, &mut ctx.errors);
        r
    };
    assert!(result.is_err());
    assert_eq!(doc.ctx.errors.len(), 1);
    assert!(doc.ctx.errors[0].path().is_some());

    // Display includes path in error message
    let display = format!("{}", doc.ctx.errors[0]);
    assert_eq!(display, "unexpected key at `items[0].bogus`");

    // No item means empty path (backward compat)
    let mut doc = crate::parser::parse("a = 1\nb = 2", &arena).unwrap();
    {
        let mut helper = doc.table_helper();
        let _: i64 = helper.required("a").unwrap();
        assert!(helper.require_empty().is_err());
    }
    assert!(doc.ctx.errors[0].path().is_none());
}

#[test]
fn deser_tuple_1() {
    let arena = Arena::new();
    let val: (i64,) = parse_val("v = [42]", &arena).unwrap();
    assert_eq!(val, (42,));
}

#[test]
fn deser_tuple_2() {
    let arena = Arena::new();
    let val: (String, i64) = parse_val(r#"v = ["hello", 7]"#, &arena).unwrap();
    assert_eq!(val, ("hello".to_string(), 7));
}

#[test]
fn deser_tuple_3() {
    let arena = Arena::new();
    let val: (bool, i64, String) = parse_val(r#"v = [true, 99, "ok"]"#, &arena).unwrap();
    assert_eq!(val, (true, 99, "ok".to_string()));
}

#[test]
fn deser_tuple_wrong_size() {
    let arena = Arena::new();
    let err = parse_val::<(i64, i64)>("v = [1, 2, 3]", &arena).unwrap_err();
    let msg = format!("{err}");
    assert!(msg.contains("size of 2"), "got: {msg}");
}

#[test]
fn deser_tuple_wrong_type() {
    let arena = Arena::new();
    assert!(parse_val::<(i64,)>(r#"v = "not an array""#, &arena).is_err());
}