struson 0.7.2

A low-level streaming JSON reader and writer
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
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
//! Module for reading JSON data
//!
//! [`JsonReader`] is the general trait for JSON readers, [`JsonStreamReader`] is an implementation
//! of it which reads a JSON document from a [`Read`] in a streaming way.

/// Module for 'JSON path'
///
/// A 'JSON path' points to a single value in a JSON document. It consists of zero or more [`JsonPathPiece`]
/// elements which either represent the index of a JSON array item or the name of a JSON object member.
/// These pieces combined form the _path_ to a value in a JSON document.
///
/// This is not an implementation of the [JSONPath RFC 9535](https://www.rfc-editor.org/rfc/rfc9535) standard;
/// the implementation here uses a different syntax and only covers a subset of these features needed for
/// JSON reader functionality, most notably for reporting the location of errors and for [`JsonReader::seek_to`].
/// If you need more functionality, prefer a library which fully implements the JSONPath standard.
///
/// The macro [`json_path!`](json_path::json_path) can be used to create a JSON path in a concise way.
///
/// Consider for example the following code:
/// ```
/// # use struson::reader::json_path::*;
/// vec![
///     JsonPathPiece::ObjectMember("a".to_owned()),
///     JsonPathPiece::ArrayItem(2),
/// ]
/// # ;
/// ```
/// It means: Within a JSON object the member with name "a", and assuming the value of that member is
/// a JSON array, of that array the item at index 2 (starting at 0). The string representation of the
/// path in dot-notation would be `a[2]`.\
/// For example in the JSON string `{"a": [0.5, 1.5, 2.5]}` it would point to the value `2.5`.
pub mod json_path {
    /// A piece of a JSON path
    ///
    /// A piece can either represent the index of a JSON array item or the name of a JSON object member.
    #[derive(PartialEq, Eq, Clone, Debug)]
    pub enum JsonPathPiece {
        /// JSON array item at the specified index (starting at 0)
        ArrayItem(u32),
        /// JSON object member with the specified name
        ObjectMember(String),
    }

    /// Creates a [`JsonPathPiece::ArrayItem`] with the number as index
    impl From<u32> for JsonPathPiece {
        fn from(v: u32) -> Self {
            JsonPathPiece::ArrayItem(v)
        }
    }

    /// Creates a [`JsonPathPiece::ObjectMember`] with the string as member name
    impl From<String> for JsonPathPiece {
        fn from(v: String) -> Self {
            JsonPathPiece::ObjectMember(v)
        }
    }

    /// Creates a [`JsonPathPiece::ObjectMember`] with the string as member name
    impl From<&str> for JsonPathPiece {
        fn from(v: &str) -> Self {
            JsonPathPiece::ObjectMember(v.to_string())
        }
    }

    /// A JSON path
    ///
    /// A JSON path as represented by this module are zero or more [`JsonPathPiece`] elements.
    /// The macro [`json_path!`] can be used to create a JSON path in a concise way.
    /* TODO: Check if it is somehow possible to implement Display for this (and reuse code from format_abs_json_path then) */
    pub type JsonPath = [JsonPathPiece];

    pub(crate) fn format_abs_json_path(json_path: &JsonPath) -> String {
        "$".to_string()
            + json_path
                .iter()
                .map(|p| match p {
                    JsonPathPiece::ArrayItem(index) => format!("[{index}]"),
                    JsonPathPiece::ObjectMember(name) => format!(".{name}"),
                })
                .collect::<String>()
                .as_str()
    }

    /// Creates a JSON path from path pieces, separated by commas
    ///
    /// The arguments to this macro represent the path pieces:
    /// - numbers of type `u32` are converted to [`JsonPathPiece::ArrayItem`]
    /// - strings are converted to [`JsonPathPiece::ObjectMember`]
    ///
    /// Providing no arguments creates an empty path without any path pieces.
    ///
    /// # Examples
    /// ```
    /// # use struson::reader::json_path::*;
    /// # use struson::reader::json_path::JsonPathPiece::*;
    /// let json_path = json_path!["outer", 3, "inner"];
    /// assert_eq!(
    ///     json_path,
    ///     [
    ///         ObjectMember("outer".to_owned()),
    ///         ArrayItem(3),
    ///         ObjectMember("inner".to_owned()),
    ///     ]
    /// );
    /// ```
    /*
     * TODO: Ideally in the future not expose this at the crate root but only from the `json_path` module
     *       however, that is apparently not easily possible yet, see https://users.rust-lang.org/t/how-to-namespace-a-macro-rules-macro-within-a-module-or-macro-export-it-without-polluting-the-top-level-namespace/63779/5
     * TODO: Prefix this with `__` and use `#[doc(hidden)]` to not expose it at the crate root,
     *       see https://internals.rust-lang.org/t/pub-on-macro-rules/19358/16
     */
    #[macro_export]
    macro_rules! json_path {
        () => {
            // Specify the type to avoid it being used by accident as an empty array of any type
            [] as [$crate::reader::json_path::JsonPathPiece; 0]
        };
        ( $($piece:expr),+ $(,)? ) => {
            [
                $(
                    $crate::reader::json_path::JsonPathPiece::from($piece),
                )*
            ]
        };
    }

    // Re-export the macro to be available under the `struson::reader::json_path` module path
    #[doc(inline)]
    pub use json_path;

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

        #[test]
        fn test_format_abs_json_path() {
            assert_eq!("$", format_abs_json_path(&Vec::new()));

            assert_eq!("$[2]", format_abs_json_path(&[JsonPathPiece::ArrayItem(2)]));
            assert_eq!(
                "$[2][3]",
                format_abs_json_path(&[JsonPathPiece::ArrayItem(2), JsonPathPiece::ArrayItem(3)])
            );
            assert_eq!(
                "$[2].a",
                format_abs_json_path(&[
                    JsonPathPiece::ArrayItem(2),
                    JsonPathPiece::ObjectMember("a".to_owned())
                ])
            );

            assert_eq!(
                "$.a",
                format_abs_json_path(&[JsonPathPiece::ObjectMember("a".to_owned())])
            );
            assert_eq!(
                "$.a.b",
                format_abs_json_path(&[
                    JsonPathPiece::ObjectMember("a".to_owned()),
                    JsonPathPiece::ObjectMember("b".to_owned())
                ])
            );
            assert_eq!(
                "$.a[2]",
                format_abs_json_path(&[
                    JsonPathPiece::ObjectMember("a".to_owned()),
                    JsonPathPiece::ArrayItem(2)
                ])
            );
        }

        #[test]
        fn macro_json_path() {
            assert_eq!(json_path![], []);
            // Make sure the type is correct and it can be compared with a &JsonPath
            assert_ne!(json_path![], &[JsonPathPiece::ArrayItem(1)] as &JsonPath);
            assert_eq!(json_path![3], [JsonPathPiece::ArrayItem(3)]);
            // Make sure the type is correct and it can be compared with a &JsonPath
            assert_eq!(json_path![3], &[JsonPathPiece::ArrayItem(3)] as &JsonPath);
            assert_eq!(
                json_path!["a"],
                [JsonPathPiece::ObjectMember("a".to_owned())]
            );
            assert_eq!(
                // Trailing comma
                json_path!["a",],
                [JsonPathPiece::ObjectMember("a".to_owned())]
            );
            assert_eq!(
                json_path!["a".to_owned()],
                [JsonPathPiece::ObjectMember("a".to_owned())]
            );
            assert_eq!(
                json_path!["outer", 1, "inner".to_owned(), 2],
                [
                    JsonPathPiece::ObjectMember("outer".to_owned()),
                    JsonPathPiece::ArrayItem(1),
                    JsonPathPiece::ObjectMember("inner".to_owned()),
                    JsonPathPiece::ArrayItem(2),
                ]
            );
        }
    }
}

use std::{
    fmt::{Debug, Display, Formatter},
    io::Read,
    str::FromStr,
};

use thiserror::Error;

use self::json_path::{JsonPath, JsonPathPiece, format_abs_json_path};
use crate::writer::JsonWriter;

mod stream_reader;
// Re-export streaming implementation under `reader` module
pub use stream_reader::*;
#[cfg(feature = "simple-api")]
pub mod simple;

type IoError = std::io::Error;

/// Type of a JSON value
#[derive(PartialEq, Eq, Clone, Copy, strum::Display, Debug)]
pub enum ValueType {
    /// JSON array: `[ ... ]`
    Array,
    /// JSON object: `{ ... }`
    Object,
    /// JSON string value, for example `"text in \"quotes\""`
    String,
    /// JSON number value, for example `123.4e+10`
    Number,
    /// JSON boolean value, `true` or `false`
    Boolean,
    /// JSON `null`
    Null,
    // No EndOfDocument because peeking after top-level element is a logic error

    // No ArrayEnd and ObjectEnd, should use has_next()
}

/// Line and column position
///
/// # Examples
/// Consider the following JSON document:
/// ```json
/// {
///   "a": null
/// }
/// ```
/// The position of `null` is:
/// - line: 1\
///   Line numbering starts at 0 and it is in the second line
/// - column: 7\
///   Column numbering starts at 0 and the `n` of `null` is the 8th character in that line,
///   respectively there are 7 characters in front of it
#[derive(PartialEq, Eq, Copy, Clone, Debug)]
pub struct LinePosition {
    /// Line number, starting at 0
    ///
    /// The characters _CR_ (U+000D), _LF_ (U+000A) and _CR LF_ are considered line breaks. Other characters and
    /// escaped line breaks in member names and string values are not considered line breaks.
    pub line: u64,
    /// Character column within the current line, starting at 0
    ///
    /// For all Unicode characters this value is incremented only by one, regardless of whether some encodings
    /// such as UTF-8 might use more than one byte for the character, or whether encodings such as UTF-16
    /// might use two characters (a *surrogate pair*) to encode the character. Similarly the tab character
    /// (U+0009) is also considered a single character even though code editors might display it as if it
    /// consisted of more than one space character.
    pub column: u64,
}

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

/// Position of the JSON reader in the JSON document
///
/// The position information can be used for troubleshooting malformed JSON or JSON data with an unexpected structure.
/// Which position information is available depends on the implementation of the JSON reader and its configuration.
#[derive(PartialEq, Eq, Clone, Debug)]
pub struct JsonReaderPosition {
    /// JSON path of the position
    ///
    /// The path describes which JSON array items and JSON object members to traverse to reach this position.\
    /// The last piece of the path cannot accurately point to the position in all cases because the position can be
    /// anywhere in the JSON document and in some cases this cannot be accurately or unambiguously described using
    /// a JSON path. The last path piece has the following meaning:
    ///
    /// - [`JsonPathPiece::ArrayItem`]: Index of the currently processed item, or index of the potential next item
    ///
    ///   For example the path `[..., ArrayItem(2)]` means that either the position is in front of a potential item
    ///   at index 2 (including the case where there are no subsequent items), or at the start or within the item at
    ///   index 2.
    ///
    ///   In general the index is incremented once a value in an array was fully consumed, which results in the
    ///   behavior described above.
    ///
    /// - [`JsonPathPiece::ObjectMember`]: Name of the previously read member, or name of the current member
    ///
    ///   For example the path `[..., ObjectMember("a")]` means that either the position is at the start or within
    ///   the value of the member with name "a" or before the end of the potential next member name (including the
    ///   case where there are no subsequent members).\
    ///   The special name `<?>` is used to indicate that a JSON object was started, but the name of the first member
    ///   has not been consumed yet.
    ///
    ///   In general the name in the JSON path is updated once the name of a member has been successfully read,
    ///   which results in the behavior described above.
    ///
    /// The path is `None` if the JSON reader implementation does not track the JSON path or if tracking the
    /// JSON path is [disabled in the `ReaderSettings`](ReaderSettings::track_path).
    ///
    /// For the exact position the [`line_pos`](Self::line_pos) and [`data_pos`](Self::data_pos) should be used.
    ///
    /// # Examples
    /// Consider the following JSON document:
    /// ```json
    /// {
    ///   "a": [1, null]
    /// }
    /// ```
    /// The position of `null` is `[ObjectMember("a"), ArrayItem(1)]`:
    /// - `ObjectMember("a")`: It is part of the value for the JSON object member named "a"
    /// - `ArrayItem(1)`: Within that value, which is a JSON array, it is at index 1 (numbering starts at 0)
    /* TODO: Maybe this should be `Cow<'a, JsonPath>`, but then need to propagate lifetime everywhere? */
    pub path: Option<Vec<JsonPathPiece>>,

    /// Line and column number
    ///
    /// This information is generally only provided by JSON reader implementations which read the JSON
    /// document as text in some way and where the concept of a line and column number makes sense.
    /// For other JSON reader implementations this might be `None`.
    pub line_pos: Option<LinePosition>,

    /// Position in the underlying data source
    ///
    /// The exact meaning depends on the JSON reader implementation and what type the underlying data
    /// has. The value starts at 0, representing the first data unit. It may either refer to the data
    /// unit which is currently processed (for example if it has an unexpected value) or the potential
    /// next data unit. For example for a JSON reader implementation based on [`std::io::Read`] the
    /// value might be the byte position.
    ///
    /// `None` if the JSON reader implementation does provide information about the data position.
    ///
    /// This value might not be equal to the amount of data consumed from the underlying data source
    /// in case the JSON reader buffers data internally which it has not processed yet.
    pub data_pos: Option<u64>,
}
impl JsonReaderPosition {
    /// Creates an 'unknown' position, with all position information being [`None`]
    #[allow(
        dead_code,
        reason = "called by Simple API (but guarded by feature flag)"
    )]
    pub(crate) fn unknown_position() -> Self {
        JsonReaderPosition {
            path: None,
            line_pos: None,
            data_pos: None,
        }
    }
}

impl Display for JsonReaderPosition {
    // Create display string depending on which of the Option values are present
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        if let Some(path) = &self.path {
            write!(f, "path '{}'", format_abs_json_path(path))?;

            if let Some(line_pos) = &self.line_pos {
                write!(f, ", {line_pos}")?;

                if let Some(data_pos) = &self.data_pos {
                    write!(f, " (data pos {data_pos})")?;
                }
            } else if let Some(data_pos) = &self.data_pos {
                write!(f, ", data pos {data_pos}")?;
            }
        } else if let Some(line_pos) = &self.line_pos {
            write!(f, "{line_pos}")?;

            if let Some(data_pos) = &self.data_pos {
                write!(f, " (data pos {data_pos})")?;
            }
        } else if let Some(data_pos) = &self.data_pos {
            write!(f, "data pos {data_pos}")?;
        } else {
            write!(f, "<location unavailable>")?;
        }

        Ok(())
    }
}

/// JSON syntax error
/*
 * This is a separate public struct because StringValueReader uses it when wrapping syntax error
 * inside std::io::Error. Otherwise, this should be private, and `ReaderError::SyntaxError` should
 * be a struct with these fields for consistency with the other error variants and for easier usage.
 */
#[derive(Error, PartialEq, Eq, Clone, Debug)]
#[error("JSON syntax error {kind} at {location}")]
pub struct JsonSyntaxError {
    /// Kind of the error
    pub kind: SyntaxErrorKind,
    /// Location where the error occurred in the JSON document
    pub location: JsonReaderPosition,
}

/// Describes why a syntax error occurred
#[non_exhaustive]
#[derive(PartialEq, Eq, Clone, Copy, strum::Display, Debug)]
pub enum SyntaxErrorKind {
    /// A comment was encountered, but comments are not [enabled in the `ReaderSettings`](ReaderSettings::allow_comments)
    CommentsNotEnabled,
    /// A comment is incomplete
    IncompleteComment,
    /// A block comment is missing the closing `*/`
    BlockCommentNotClosed,

    /// A literal value is incomplete or invalid, for example `tru` instead of `true`
    InvalidLiteral,
    /// There is unexpected trailing data after a literal, for example `truey` instead of `true`
    TrailingDataAfterLiteral,
    /// A closing bracket (`]` or `}`) was encountered where it was not expected
    UnexpectedClosingBracket,
    /// A comma (`,`) was encountered where it was not expected
    UnexpectedComma,
    /// A comma (`,`) is missing between array elements or object members
    MissingComma,
    /// A trailing comma (for example in `[1,]`) was encountered, but trailing commas are not
    /// [enabled in the `ReaderSettings`](ReaderSettings::allow_trailing_comma)
    TrailingCommaNotEnabled,
    /// A colon (`:`) was encountered where it was not expected
    UnexpectedColon,
    /// A colon (`:`) is missing between member name and member value
    MissingColon,
    /// A JSON number is malformed, for example `01` (leading 0 is not allowed)
    MalformedNumber,
    /// There is unexpected trailing data after a number, for example `123a`
    TrailingDataAfterNumber,
    /// A member name or the end of an object (`}`) was expected but something else was encountered
    ExpectingMemberNameOrObjectEnd,
    /// The JSON data is malformed for a reason other than any of the other kinds
    ///
    /// This is usually the case when Unicode characters other than the ones used as start or end of JSON values
    /// (such as `"`, `[`, `}` ...) are encountered.
    MalformedJson,

    /// A control character was encountered in the raw JSON data of a member name or string value
    ///
    /// The JSON specification requires that Unicode characters in the range from `0x00` to `0x1F` (inclusive) must be
    /// escaped when part of a member name or string value. This can be done either with a `\uXXXX` escape or with a
    /// short escape sequence such as `\n`, if one exists.
    NotEscapedControlCharacter,
    /// An unknown escape sequence (`\...`) was encountered
    UnknownEscapeSequence,
    /// A malformed escape sequence was encountered, for example `\u00` instead of `\u0000`
    MalformedEscapeSequence,
    /// An unpaired UTF-16 surrogate pair was encountered in a member name or a string value
    ///
    /// Since Rust strings must consist of valid UTF-8 data, UTF-16 surrogate characters in the form
    /// of escape sequences in JSON (`\uXXXX`) must always form a valid surrogate pair. For example
    /// the character U+10FFFF would either have to be in raw form in the UTF-8 data of the JSON document
    /// or be encoded as the escape sequence pair `\uDBFF\uDFFF`.
    UnpairedSurrogatePairEscapeSequence,

    /// The JSON document is incomplete, for example a closing `]` is missing
    IncompleteDocument,
    /// Unexpected trailing data was detected at the end of the JSON document
    ///
    /// This error kind is used by [`JsonReader::consume_trailing_whitespace`].
    TrailingData,
}

/// Describes why the JSON document is considered to have an unexpected structure
#[derive(PartialEq, Eq, Clone, strum::Display, Debug)]
pub enum UnexpectedStructureKind {
    /// A JSON array has fewer items than expected
    /* include field value; not included by default */
    #[strum(to_string = "TooShortArray(expected_index = {expected_index})")]
    TooShortArray {
        /// Index (starting at 0) of the expected item
        expected_index: u32,
    },

    /// A JSON object does not have a member with a certain name
    /* include field value; not included by default */
    #[strum(to_string = "MissingObjectMember(\"{member_name}\")")]
    MissingObjectMember {
        /// Name of the expected member
        member_name: String,
    },

    /// A JSON array or object has fewer elements than expected
    ///
    /// This is a more general version than [`TooShortArray`](UnexpectedStructureKind::TooShortArray)
    /// and [`MissingObjectMember`](UnexpectedStructureKind::MissingObjectMember) where it is only known
    /// that more elements are expected without knowing the expected index or member name.
    FewerElementsThanExpected,

    /// A JSON array or object has more elements than expected
    MoreElementsThanExpected,
}

/// Error which occurred while reading from a JSON reader
#[non_exhaustive]
#[derive(Error, Debug)]
// TODO: Rename to `JsonReaderError? current name might sound like this is only for errors from underlying `Read`
pub enum ReaderError {
    /// A syntax error was encountered
    #[error("syntax error: {0}")]
    SyntaxError(#[from] JsonSyntaxError),

    /// The next JSON value had an unexpected type
    ///
    /// This error can occur for example when trying to read a JSON number when the next value is actually
    /// a JSON boolean.
    #[error("expected JSON value type {expected} but got {actual} at {location}")]
    UnexpectedValueType {
        /// The expected JSON value type
        expected: ValueType,
        /// The actual JSON value type
        actual: ValueType,
        /// Location where the error occurred in the JSON document
        location: JsonReaderPosition,
    },

    /// The JSON document had an unexpected structure
    ///
    /// This error occurs when trying to consume more elements than a JSON array or object has, or
    /// when trying to end a JSON array or object when there are still unprocessed elements in it.
    /// If these remaining elements should be ignored they can be skipped like this:
    /// ```
    /// # use struson::reader::*;
    /// # let mut json_reader = JsonStreamReader::new("[]".as_bytes());
    /// # json_reader.begin_array()?;
    /// while json_reader.has_next()? {
    ///     json_reader.skip_value()?;
    /// }
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    /// Note: For a JSON object [`skip_name`](JsonReader::skip_name) and [`skip_value`](JsonReader::skip_value)
    /// have to be called for every member to skip its name and value.
    #[error("unexpected JSON structure {kind} at {location}")]
    UnexpectedStructure {
        /// Describes why the JSON document is considered to have an invalid structure
        kind: UnexpectedStructureKind,
        /// Location where the error occurred in the JSON document
        location: JsonReaderPosition,
    },

    /// The maximum nesting depth was exceeded while reading
    ///
    /// See [`ReaderSettings::max_nesting_depth`] for more information.
    #[error("maximum nesting depth {max_nesting_depth} exceeded at {location}")]
    MaxNestingDepthExceeded {
        /// The maximum nesting depth
        max_nesting_depth: u32,
        /// Location within the JSON document
        location: JsonReaderPosition,
    },

    /// An unsupported JSON number value was encountered
    ///
    /// See [`ReaderSettings::restrict_number_values`] for more information.
    #[error("unsupported number value '{number}' at {location}")]
    UnsupportedNumberValue {
        /// The unsupported number value
        number: String,
        /// Location of the number value within the JSON document
        location: JsonReaderPosition,
    },

    /// An IO error occurred while trying to read from the underlying reader, or
    /// malformed UTF-8 data was encountered
    #[error("IO error '{error}' at (roughly) {location}")]
    IoError {
        /// The IO error which occurred
        error: IoError,
        /// Rough location where the error occurred within the JSON document
        ///
        /// The location might not be completely accurate. Since the IO error might have
        /// been returned by the underlying reader, it might not be related to the content
        /// of the JSON document. For example the location might still point to the beginning
        /// of the current JSON value while the IO error actually occurred multiple bytes
        /// ahead while fetching more data from the underlying reader.
        location: JsonReaderPosition,
    },
}

impl ReaderError {
    /// Creates a clone of this Error
    ///
    /// For most of the variants of this error this acts like a regular [`Clone`]. The only
    /// exception is [`ReaderError::IoError`] where it might not be possible to fully preserve
    /// all data of the original error.
    #[allow(
        dead_code,
        reason = "called by Simple API (but guarded by feature flag)"
    )]
    pub(crate) fn rough_clone(&self) -> Self {
        match self {
            Self::SyntaxError(e) => Self::SyntaxError(e.clone()),
            Self::UnexpectedValueType {
                expected,
                actual,
                location,
            } => Self::UnexpectedValueType {
                expected: *expected,
                actual: *actual,
                location: location.clone(),
            },
            Self::UnexpectedStructure { kind, location } => Self::UnexpectedStructure {
                kind: kind.clone(),
                location: location.clone(),
            },
            Self::MaxNestingDepthExceeded {
                max_nesting_depth,
                location,
            } => Self::MaxNestingDepthExceeded {
                max_nesting_depth: *max_nesting_depth,
                location: location.clone(),
            },
            Self::UnsupportedNumberValue { number, location } => Self::UnsupportedNumberValue {
                number: number.clone(),
                location: location.clone(),
            },
            Self::IoError { error, location } => Self::IoError {
                error: IoError::new(error.kind(), error.to_string()),
                location: location.clone(),
            },
        }
    }
}

/// Error which occurred while calling [`JsonReader::transfer_to`]
#[derive(Error, Debug)]
pub enum TransferError {
    /// Error which occurred while reading from the JSON reader
    #[error("reader error: {0}")]
    ReaderError(#[from] ReaderError),
    /// Error which occurred while writing to the JSON writer
    #[error("writer error: {0}")]
    WriterError(#[from] IoError),
}

// TODO: Doc: Deduplicate documentation for errors and panics for value reading methods and only describe it
//       once in the documentation of JsonReader?

/// A trait for JSON readers
///
/// The methods of this reader can be divided into the following categories:
///
/// - Peeking values, without consuming them
///     - [`peek`](Self::peek): Peeks at the type of the next value
///     - [`has_next`](Self::has_next): Checks if there is a next value
/// - Reading values
///     - [`begin_array`](Self::begin_array), [`end_array`](Self::end_array): Starting and ending a JSON array
///     - [`begin_object`](Self::begin_object), [`end_object`](Self::end_object): Starting and ending a JSON object
///     - [`next_name`](Self::next_name), [`next_name_owned`](Self::next_name_owned): Reading the name of a JSON object member
///     - [`next_str`](Self::next_str), [`next_string`](Self::next_string), [`next_string_reader`](Self::next_string_reader): Reading a JSON string value
///     - [`next_number`](Self::next_number), [`next_number_as_str`](Self::next_number_as_str), [`next_number_as_string`](Self::next_number_as_string): Reading a JSON number value
///     - [`next_bool`](Self::next_bool): Reading a JSON boolean value
///     - [`next_null`](Self::next_null): Reading a JSON null value
///     - [`deserialize_next`](Self::deserialize_next): Deserializes a Serde [`Deserialize`](serde_core::de::Deserialize) from the next value (optional feature)
///  - Skipping values
///     - [`skip_name`](Self::skip_name): Skipping the name of a JSON object member
///     - [`skip_value`](Self::skip_value): Skipping a value
///     - [`seek_to`](Self::seek_to): Skipping values until a specified location is reached
///     - [`seek_back`](Self::seek_back): Skipping to the original nesting level where `seek_to` started
///     - [`skip_to_top_level`](Self::skip_to_top_level): Skipping the remaining elements of all enclosing JSON arrays and objects
///  - Other:
///     - [`transfer_to`](Self::transfer_to): Reading a JSON value and writing it to a given JSON writer
///     - [`consume_trailing_whitespace`](Self::consume_trailing_whitespace): Consuming trailing whitespace at the end of the JSON document
///
/// JSON documents have at least one top-level value which can be either a JSON array, object,
/// string, number, boolean or null value. For JSON arrays and objects the opening brackets
/// must be consumed with the corresponding `begin_` method (for example [`begin_array`](Self::begin_array)) and the
/// closing bracket with the corresponding `end_` method (for example [`end_array`](Self::end_array)). JSON objects
/// consist of *members* which are name-value pairs. The name of a member can be read with
/// [`next_name`](Self::next_name) and the value with any of the value reading methods such as [`next_bool`](Self::next_bool).
///
/// It is not necessary to consume the complete JSON document, for example a user of this reader
/// can simply drop the reader once the relevant information was extracted, ignoring the remainder
/// of the JSON data. However, in that case no validation will be performed that the remainder
/// has actually valid JSON syntax. To ensure that, [`skip_to_top_level`](Self::skip_to_top_level)
/// can be used to skip (and validate) the remainder of the current top-level JSON array or object.
///
/// **Important:** Even after the top-level has been fully consumed this reader does *not*
/// automatically consume the remainder of the JSON document (which is expected to consist
/// of optional whitespace only). To verify that there is no trailing data it is necessary
/// to explicitly call [`consume_trailing_whitespace`](Self::consume_trailing_whitespace).
///
/// # Examples
/// ```
/// # use struson::reader::*;
/// // In this example JSON data comes from a string;
/// // normally it would come from a file or a network connection
/// let json = r#"{"a": [1, 2, true]}"#;
/// let mut json_reader = JsonStreamReader::new(json.as_bytes());
///
/// json_reader.begin_object()?;
/// assert_eq!(json_reader.next_name()?, "a");
///
/// json_reader.begin_array()?;
/// assert_eq!(json_reader.next_number::<u32>()??, 1);
/// json_reader.skip_value()?;
/// assert_eq!(json_reader.next_bool()?, true);
/// json_reader.end_array()?;
///
/// json_reader.end_object()?;
/// // Ensures that there is no trailing data
/// json_reader.consume_trailing_whitespace()?;
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
///
/// # Error handling
/// The methods of this reader return a [`Result::Err`] when an error occurs while reading
/// the JSON document. The error can for example be caused by an IO error from the underlying
/// reader, a JSON syntax error or an unexpected structure of the JSON document.
/// See [`ReaderError`] for more details.
///
/// When encountering [`ReaderError::SyntaxError`] and [`ReaderError::IoError`] processing the
/// JSON document **must** be aborted. Trying to call any reader methods afterwards can lead
/// to unspecified behavior, such as errors, panics or incorrect data. However, no _undefined_
/// behavior occurs.
///
/// When encountering [`ReaderError::UnexpectedValueType`] or [`ReaderError::UnexpectedStructure`]
/// depending on the use case it might be possible to continue processing the JSON document
/// (except for [`seek_to`](Self::seek_to) where it might not be obvious how many elements have already been
/// skipped). However, these errors can usually be avoided by using either [`peek`](Self::peek) or [`has_next`](Self::has_next)
/// before trying to consume a value whose type is not known in advance, or for which it
/// is not known whether it is present in the JSON document.
///
/// In general it is recommended to handle errors with the `?` operator of Rust, for example
/// `json_reader.next_bool()?` and to abort processing the JSON document when an error occurs.
///
/// # Panics
/// Methods of this reader panic when used in an incorrect way. The documentation of the methods
/// describes in detail the situations when that will happen. In general all these cases are
/// related to incorrect usage by the user (such as trying to call [`end_object`](Self::end_object) when currently
/// reading a JSON array) and are unrelated to the JSON data which is processed.
pub trait JsonReader {
    /// Peeks at the type of the next value, without consuming it
    ///
    /// Peeking at the type of a value can be useful when the exact structure of a JSON document is
    /// not known in advance, or when a value could be of more than one type. The value can then be
    /// consumed with one of the other methods.
    ///
    /// This method does not guarantee that the peeked value is complete or valid; consuming it
    /// (with a separate method call) can return an error when malformed JSON data is detected.
    ///
    /// # Examples
    /// ```
    /// # use struson::reader::*;
    /// # let mut json_reader = JsonStreamReader::new("true".as_bytes());
    /// # assert_eq!(json_reader.peek()?, ValueType::Boolean);
    /// match json_reader.peek()? {
    ///     ValueType::Boolean => println!("A boolean: {}", json_reader.next_bool()?),
    ///     ValueType::String => println!("A string: {}", json_reader.next_str()?),
    ///     _ => panic!("Unexpected type"),
    /// }
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    ///
    /// # Errors
    /// (besides [`ReaderError::SyntaxError`] and [`ReaderError::IoError`])
    ///
    /// If there is no next value a [`ReaderError::UnexpectedStructure`] is returned. The method
    /// [`has_next`](Self::has_next) can be used to check if there is a next value.
    ///
    /// # Panics
    /// Panics when called on a JSON reader which currently expects a member name, or
    /// when called after the top-level value has already been consumed and multiple top-level
    /// values are not [enabled in the `ReaderSettings`](ReaderSettings::allow_multiple_top_level).
    /// Both cases indicate incorrect usage by the user and are unrelated to the JSON data.
    /* TODO: Rename to peek_value (or peek_value_type)? */
    fn peek(&mut self) -> Result<ValueType, ReaderError>;

    /// Begins consuming a JSON object
    ///
    /// The method [`has_next`](Self::has_next) can be used to check if there is a next object member.
    /// To consume a member first call [`next_name`](Self::next_name) or [`next_name_owned`](Self::next_name_owned)
    /// and afterwards one of the value reading methods such as [`next_number`](Self::next_number).
    /// At the end call [`end_object`](Self::end_object) to consume the closing bracket of the JSON object.
    ///
    /// # Examples
    /// ```
    /// # use struson::reader::*;
    /// let mut json_reader = JsonStreamReader::new(r#"{"a": 1, "b": 2}"#.as_bytes());
    /// json_reader.begin_object()?;
    ///
    /// // Prints "a: 1", "b: 2"
    /// while json_reader.has_next()? {
    ///     let name = json_reader.next_name_owned()?;
    ///     let value: u32 = json_reader.next_number()??;
    ///     println!("{name}: {value}");
    /// }
    ///
    /// json_reader.end_object()?;
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    ///
    /// # Errors
    /// (besides [`ReaderError::SyntaxError`] and [`ReaderError::IoError`])
    ///
    /// If there is no next value a [`ReaderError::UnexpectedStructure`] is returned. The [`has_next`](Self::has_next)
    /// method can be used to check if there is a next value.
    ///
    /// If the next value is not a JSON object but is a value of a different type
    /// a [`ReaderError::UnexpectedValueType`] is returned. The [`peek`](Self::peek) method can be used to
    /// check the type if it is not known in advance.
    ///
    /// # Panics
    /// Panics when called on a JSON reader which currently expects a member name, or
    /// when called after the top-level value has already been consumed and multiple top-level
    /// values are not [enabled in the `ReaderSettings`](ReaderSettings::allow_multiple_top_level).
    /// Both cases indicate incorrect usage by the user and are unrelated to the JSON data.
    fn begin_object(&mut self) -> Result<(), ReaderError>;

    /// Consumes the closing bracket `}` of the current JSON object
    ///
    /// This method is used to end a JSON object started by [`begin_object`](Self::begin_object).
    ///
    /// # Errors
    /// (besides [`ReaderError::SyntaxError`] and [`ReaderError::IoError`])
    ///
    /// If there are remaining members in the object a [`ReaderError::UnexpectedStructure`] is returned.
    /// [`skip_name`](Self::skip_name) and [`skip_value`](Self::skip_value) can be used to skip these
    /// remaining members in case they should be ignored:
    /// ```
    /// # use struson::reader::*;
    /// # let mut json_reader = JsonStreamReader::new("{}".as_bytes());
    /// # json_reader.begin_object()?;
    /// while json_reader.has_next()? {
    ///     // Skip member name
    ///     json_reader.skip_name()?;
    ///     // Skip member value
    ///     json_reader.skip_value()?;
    /// }
    ///
    /// json_reader.end_object()?;
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    ///
    /// # Panics
    /// Panics when called on a JSON reader which is currently not inside a JSON object,
    /// or when the value of a member is currently expected. Both cases indicate incorrect
    /// usage by the user and are unrelated to the JSON data.
    fn end_object(&mut self) -> Result<(), ReaderError>;

    /// Begins consuming a JSON array
    ///
    /// The method [`has_next`](Self::has_next) can be used to check if there is a next array item. To consume an item one of
    /// the regular value reading methods such as [`next_number`](Self::next_number) can be used. At the end call
    /// [`end_array`](Self::end_array) to consume the closing bracket of the JSON array.
    ///
    /// Note that JSON arrays can contain values of different types, so for example the
    /// following is valid JSON: `[1, true, "a"]`
    ///
    /// # Examples
    /// ```
    /// # use struson::reader::*;
    /// let mut json_reader = JsonStreamReader::new("[1, 2, 3]".as_bytes());
    /// json_reader.begin_array()?;
    ///
    /// // Prints: "Number: 1", "Number: 2", "Number: 3"
    /// while json_reader.has_next()? {
    ///     let number: u32 = json_reader.next_number()??;
    ///     println!("Number: {number}");
    /// }
    ///
    /// json_reader.end_array()?;
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    ///
    /// # Errors
    /// (besides [`ReaderError::SyntaxError`] and [`ReaderError::IoError`])
    ///
    /// If there is no next value a [`ReaderError::UnexpectedStructure`] is returned. The [`has_next`](Self::has_next)
    /// method can be used to check if there is a next value.
    ///
    /// If the next value is not a JSON array but is a value of a different type
    /// a [`ReaderError::UnexpectedValueType`] is returned. The [`peek`](Self::peek) method can be used to
    /// check the type if it is not known in advance.
    ///
    /// # Panics
    /// Panics when called on a JSON reader which currently expects a member name, or
    /// when called after the top-level value has already been consumed and multiple top-level
    /// values are not [enabled in the `ReaderSettings`](ReaderSettings::allow_multiple_top_level).
    /// Both cases indicate incorrect usage by the user and are unrelated to the JSON data.
    fn begin_array(&mut self) -> Result<(), ReaderError>;

    /// Consumes the closing bracket `]` of the current JSON array
    ///
    /// This method is used to end a JSON array started by [`begin_array`](Self::begin_array).
    ///
    /// # Errors
    /// (besides [`ReaderError::SyntaxError`] and [`ReaderError::IoError`])
    ///
    /// If there are remaining items in the array a [`ReaderError::UnexpectedStructure`] is returned.
    /// [`skip_value`](Self::skip_value) can be used to skip these remaining items in case they should be ignored:
    /// ```
    /// # use struson::reader::*;
    /// # let mut json_reader = JsonStreamReader::new("[]".as_bytes());
    /// # json_reader.begin_array()?;
    /// while json_reader.has_next()? {
    ///     json_reader.skip_value()?;
    /// }
    ///
    /// json_reader.end_array()?;
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    ///
    /// # Panics
    /// Panics when called on a JSON reader which is currently not inside a JSON array. This
    /// indicates incorrect usage by the user and is unrelated to the JSON data.
    fn end_array(&mut self) -> Result<(), ReaderError>;

    /// Checks if there is a next element in the current JSON array or object, without consuming it
    ///
    /// Returns `true` if there is a next element, `false` otherwise. When multiple top-level
    /// values are [enabled in the `ReaderSettings`](ReaderSettings::allow_multiple_top_level)
    /// this method can also be used to check if there are more top-level values.
    ///
    /// This method can be useful as condition of a `while` loop when processing a JSON array or object
    /// of unknown size.
    ///
    /// # Examples
    /// ```
    /// # use struson::reader::*;
    /// let mut json_reader = JsonStreamReader::new("[1]".as_bytes());
    /// json_reader.begin_array()?;
    ///
    /// // Array has a next item
    /// assert!(json_reader.has_next()?);
    ///
    /// json_reader.skip_value()?;
    /// // Array does not have a next item anymore
    /// assert_eq!(json_reader.has_next()?, false);
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    ///
    /// # Panics
    /// Panics when called on a JSON reader which currently expects a member name, or
    /// when called after the top-level value has already been consumed and multiple top-level
    /// values are not [enabled in the `ReaderSettings`](ReaderSettings::allow_multiple_top_level).
    /// Both cases indicate incorrect usage by the user and are unrelated to the JSON data.
    ///
    /// Additionally this method also panics when called on a JSON reader which has not
    /// consumed any top-level value yet. An empty JSON document is not valid so there
    /// should be no need to check for a next element since there must always be one.
    fn has_next(&mut self) -> Result<bool, ReaderError>;

    /// Consumes and returns the name of the next JSON object member as `str`
    ///
    /// The name is returned as borrowed `str`. While that value is in scope, the Rust
    /// compiler might not permit using the JSON reader in any other way.
    /// If an owned `String` is needed, prefer [`next_name_owned`](Self::next_name_owned),
    /// that will most likely be more efficient than using this method to obtain a `str`
    /// and then converting that to an owned `String`.
    ///
    /// Afterwards one of the value reading methods such as [`next_number`](Self::next_number) can be
    /// used to read the corresponding member value.
    ///
    /// **Important:** This method does not detect duplicate  member names, such as
    /// in `{"a": 1, "a": 2}`. Programs processing JSON data from an untrusted source
    /// must implement this detection themselves to protect against exploits relying
    /// on different handling of duplicate names by different JSON parsing libraries.
    ///
    /// # Examples
    /// ```
    /// # use struson::reader::*;
    /// let mut json_reader = JsonStreamReader::new(r#"{"a": 1}"#.as_bytes());
    /// json_reader.begin_object()?;
    /// assert_eq!(json_reader.next_name()?, "a");
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    ///
    /// # Errors
    /// (besides [`ReaderError::SyntaxError`] and [`ReaderError::IoError`])
    ///
    /// If there is no next object member a [`ReaderError::UnexpectedStructure`] is returned.
    /// [`has_next`](Self::has_next) can be used to check if there are further members in the current JSON object.
    ///
    /// # Panics
    /// Panics when called on a JSON reader which currently does not expect a member name. This
    /// indicates incorrect usage by the user and is unrelated to the JSON data.
    fn next_name(&mut self) -> Result<&str, ReaderError>;

    /// Consumes and returns the name of the next JSON object member as `String`
    ///
    /// The name is returned as owned `String`. If a borrowed `str` suffices for
    /// your use case, prefer [`next_name`](Self::next_name), that will most likely
    /// be more efficient.
    ///
    /// See the documentation of [`next_name`](Self::next_name) for a detailed
    /// description of the behavior of reading a member name.
    fn next_name_owned(&mut self) -> Result<String, ReaderError>;

    /// Consumes and returns a JSON string value as `str`
    ///
    /// This method is only intended to consume string values, it cannot be used to consume
    /// JSON object member names. The method [`next_name`](Self::next_name) has to be used for that.
    ///
    /// The string value is returned as borrowed `str`. While that value is in scope, the Rust
    /// compiler might not permit using the JSON reader in any other way.
    /// If an owned `String` is needed, prefer [`next_string`](Self::next_string),
    /// that will most likely be more efficient than using this method to obtain a `str`
    /// and then converting that to an owned `String`.
    ///
    /// To avoid reading the complete string value into memory, the method [`next_string_reader`](Self::next_string_reader)
    /// can be used to obtain a reader which allows lazily reading the value. Especially for
    /// large string values this can be useful.
    ///
    /// # Examples
    /// ```
    /// # use struson::reader::*;
    /// let mut json_reader = JsonStreamReader::new(r#""text with \"quotes\"""#.as_bytes());
    /// assert_eq!(json_reader.next_str()?, "text with \"quotes\"");
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    ///
    /// # Errors
    /// (besides [`ReaderError::SyntaxError`] and [`ReaderError::IoError`])
    ///
    /// If there is no next value a [`ReaderError::UnexpectedStructure`] is returned. The [`has_next`](Self::has_next)
    /// method can be used to check if there is a next value.
    ///
    /// If the next value is not a JSON string value but is a value of a different type
    /// a [`ReaderError::UnexpectedValueType`] is returned. The [`peek`](Self::peek) method can be used to
    /// check the type if it is not known in advance.
    ///
    /// # Panics
    /// Panics when called on a JSON reader which currently expects a member name, or
    /// when called after the top-level value has already been consumed and multiple top-level
    /// values are not [enabled in the `ReaderSettings`](ReaderSettings::allow_multiple_top_level).
    /// Both cases indicate incorrect usage by the user and are unrelated to the JSON data.
    fn next_str(&mut self) -> Result<&str, ReaderError>;

    /// Consumes and returns a JSON string value as `String`
    ///
    /// The string value is returned as owned `String`. If a borrowed `str` suffices
    /// for your use case, prefer [`next_str`](Self::next_str), that will most likely
    /// be more efficient.
    ///
    /// See the documentation of [`next_str`](Self::next_str) for a detailed
    /// description of the behavior of reading a string value.
    fn next_string(&mut self) -> Result<String, ReaderError>;

    /// Provides a reader for lazily reading a JSON string value
    ///
    /// This method is mainly designed to process large string values in a memory efficient
    /// way. If that is not a concern the method [`next_str`](Self::next_str) should be used instead.
    ///
    /// This method is only intended to consume string values, it cannot be used to consume
    /// JSON object member names. The method [`next_name`](Self::next_name) has to be used for that.
    ///
    /// Escape sequences will be automatically converted to the corresponding characters.
    ///
    /// **Important:** The data of the string value reader must be fully consumed, that means
    /// `read` has to be called with a non-empty buffer until it returns `Ok(0)`. Otherwise the
    /// string value reader will still be considered 'active' and all methods of this JSON reader
    /// will panic. Note that after finishing reading from the string value reader, it might be
    /// necessary to explicitly `drop(...)` it for the Rust compiler to allow using the original
    /// JSON reader again.
    ///
    /// # Examples
    /// ```
    /// # use struson::reader::*;
    /// # use std::io::Read;
    /// let mut json_reader = JsonStreamReader::new(r#"["hello"]"#.as_bytes());
    /// json_reader.begin_array()?;
    ///
    /// let mut string_reader = json_reader.next_string_reader()?;
    /// let mut buf = [0_u8; 1];
    ///
    /// // Important: This calls read until it returns Ok(0) to properly end the string value
    /// while string_reader.read(&mut buf)? > 0 {
    ///     println!("Read byte: {}", buf[0]);
    /// }
    ///
    /// // Drop the string reader to allow using the JSON reader again
    /// drop(string_reader);
    ///
    /// json_reader.end_array()?;
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    ///
    /// # Errors
    /// (besides [`ReaderError::SyntaxError`] and [`ReaderError::IoError`])
    ///
    /// If there is no next value a [`ReaderError::UnexpectedStructure`] is returned. The [`has_next`](Self::has_next)
    /// method can be used to check if there is a next value.
    ///
    /// If the next value is not a JSON string value but is a value of a different type
    /// a [`ReaderError::UnexpectedValueType`] is returned. The [`peek`](Self::peek) method can be used to
    /// check the type if it is not known in advance.
    ///
    /// # Reader errors
    /// JSON syntax errors and invalid UTF-8 data which occurs while consuming the JSON string
    /// value with the reader are reported as [`std::io::Error`] for that reader.
    ///
    /// The error behavior of the string reader differs from the guarantees made by [`Read`]:
    /// - if an error is returned there are no guarantees about if or how many data has been
    ///   consumed from the underlying data source and been stored in the provided `buf`
    /// - if an error occurs, processing should be aborted, regardless of the kind of the error;
    ///   trying to use the string reader or the underlying JSON reader afterwards will lead
    ///   to unspecified behavior
    ///
    /// # Panics
    /// Panics when called on a JSON reader which currently expects a member name, or
    /// when called after the top-level value has already been consumed and multiple top-level
    /// values are not [enabled in the `ReaderSettings`](ReaderSettings::allow_multiple_top_level).
    /// Both cases indicate incorrect usage by the user and are unrelated to the JSON data.
    fn next_string_reader(&mut self) -> Result<impl Read + '_, ReaderError>;

    /// Consumes and returns a JSON number value
    ///
    /// The result is either the parsed number or the parse error. It might be necessary to
    /// help the Rust compiler a bit by explicitly specifying the number type in case it cannot
    /// be inferred automatically.
    ///
    /// If parsing the number should be deferred to a later point or the exact format of the
    /// JSON number should be preserved, the method [`next_number_as_str`](Self::next_number_as_str)
    /// can be used.
    ///
    /// # Examples
    /// ```
    /// # use struson::reader::*;
    /// let mut json_reader = JsonStreamReader::new("12".as_bytes());
    /// assert_eq!(json_reader.next_number::<u32>()??, 12);
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    ///
    /// # Errors
    /// (besides [`ReaderError::SyntaxError`] and [`ReaderError::IoError`])
    ///
    /// If there is no next value a [`ReaderError::UnexpectedStructure`] is returned. The [`has_next`](Self::has_next)
    /// method can be used to check if there is a next value.
    ///
    /// If the next value is not a JSON number value but is a value of a different type
    /// a [`ReaderError::UnexpectedValueType`] is returned. The [`peek`](Self::peek) method can be used to
    /// check the type if it is not known in advance.
    ///
    /// If the number is too large or has too many decimal places a [`ReaderError::UnsupportedNumberValue`]
    /// is returned, depending on the [reader settings](ReaderSettings::restrict_number_values).
    ///
    /// # Panics
    /// Panics when called on a JSON reader which currently expects a member name, or
    /// when called after the top-level value has already been consumed and multiple top-level
    /// values are not [enabled in the `ReaderSettings`](ReaderSettings::allow_multiple_top_level).
    /// Both cases indicate incorrect usage by the user and are unrelated to the JSON data.
    /*
     * TODO: Maybe restrict FromStr somehow to numbers?
     * TODO: Solve this in a cleaner way than Result<Result<...>, ...>?
     * TODO: If FromStr returns an error, should include JsonReaderPosition for easier troubleshooting?
     *       Callers (such as Serde Deserializer number parsing implementation) would then not have to
     *       do this themselves
     */
    fn next_number<T: FromStr>(&mut self) -> Result<Result<T, T::Err>, ReaderError> {
        // Default implementation which should be suitable for most JsonReader implementations
        Ok(T::from_str(self.next_number_as_str()?))
    }

    /// Consumes and returns the string representation of a JSON number value as `str`
    ///
    /// This method is mainly intended for situations where parsing the number should be
    /// deferred to a later point, or the exact format of the JSON number should be preserved.
    /// However, this method nonetheless validates that the JSON number matches the format
    /// described by the JSON specification.
    ///
    /// The method [`next_number`](Self::next_number) can be used instead to parse the number directly in place.
    ///
    /// The number value is returned as borrowed `str`. While that value is in scope, the Rust
    /// compiler might not permit using the JSON reader in any other way.
    /// If an owned `String` is needed, prefer [`next_number_as_string`](Self::next_number_as_string),
    /// that will most likely be more efficient than using this method to obtain a `str`
    /// and then converting that to an owned `String`.
    ///
    /// # Examples
    /// ```
    /// # use struson::reader::*;
    /// let mut json_reader = JsonStreamReader::new("12.0e5".as_bytes());
    /// assert_eq!(json_reader.next_number_as_str()?, "12.0e5");
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    ///
    /// # Errors
    /// (besides [`ReaderError::SyntaxError`] and [`ReaderError::IoError`])
    ///
    /// If there is no next value a [`ReaderError::UnexpectedStructure`] is returned. The [`has_next`](Self::has_next)
    /// method can be used to check if there is a next value.
    ///
    /// If the next value is not a JSON number value but is a value of a different type
    /// a [`ReaderError::UnexpectedValueType`] is returned. The [`peek`](Self::peek) method can be used to
    /// check the type if it is not known in advance.
    ///
    /// If the number is too large or has too many decimal places a [`ReaderError::UnsupportedNumberValue`]
    /// is returned, depending on the [reader settings](ReaderSettings::restrict_number_values).
    ///
    /// # Panics
    /// Panics when called on a JSON reader which currently expects a member name, or
    /// when called after the top-level value has already been consumed and multiple top-level
    /// values are not [enabled in the `ReaderSettings`](ReaderSettings::allow_multiple_top_level).
    /// Both cases indicate incorrect usage by the user and are unrelated to the JSON data.
    fn next_number_as_str(&mut self) -> Result<&str, ReaderError>;

    /// Consumes and returns the string representation of a JSON number value as `String`
    ///
    /// The string value is returned as owned `String`. If a borrowed `str` suffices
    /// for your use case, prefer [`next_number_as_str`](Self::next_number_as_str), that
    /// will most likely be more efficient.
    ///
    /// See the documentation of [`next_number_as_str`](Self::next_number_as_str) for
    /// a detailed description of the behavior of reading a number value as string.
    fn next_number_as_string(&mut self) -> Result<String, ReaderError>;

    /// Consumes and returns a JSON boolean value
    ///
    /// # Examples
    /// ```
    /// # use struson::reader::*;
    /// let mut json_reader = JsonStreamReader::new("true".as_bytes());
    /// assert_eq!(json_reader.next_bool()?, true);
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    ///
    /// # Errors
    /// (besides [`ReaderError::SyntaxError`] and [`ReaderError::IoError`])
    ///
    /// If there is no next value a [`ReaderError::UnexpectedStructure`] is returned. The [`has_next`](Self::has_next)
    /// method can be used to check if there is a next value.
    ///
    /// If the next value is not a JSON boolean value but is a value of a different type
    /// a [`ReaderError::UnexpectedValueType`] is returned. The [`peek`](Self::peek) method can be used to
    /// check the type if it is not known in advance.
    ///
    /// # Panics
    /// Panics when called on a JSON reader which currently expects a member name, or
    /// when called after the top-level value has already been consumed and multiple top-level
    /// values are not [enabled in the `ReaderSettings`](ReaderSettings::allow_multiple_top_level).
    /// Both cases indicate incorrect usage by the user and are unrelated to the JSON data.
    fn next_bool(&mut self) -> Result<bool, ReaderError>;

    /// Consumes a JSON null value
    ///
    /// This method does not return a value since there is nothing meaningful to return.
    /// Either the JSON value is a JSON null, or otherwise an error is returned because the
    /// value had a different type (see "Errors" section below).
    ///
    /// # Examples
    /// ```
    /// # use struson::reader::*;
    /// let mut json_reader = JsonStreamReader::new("null".as_bytes());
    /// json_reader.next_null()?;
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    ///
    /// # Errors
    /// (besides [`ReaderError::SyntaxError`] and [`ReaderError::IoError`])
    ///
    /// If there is no next value a [`ReaderError::UnexpectedStructure`] is returned. The [`has_next`](Self::has_next)
    /// method can be used to check if there is a next value.
    ///
    /// If the next value is not a JSON null value but is a value of a different type
    /// a [`ReaderError::UnexpectedValueType`] is returned. The [`peek`](Self::peek) method can be used to
    /// check the type if it is not known in advance.
    ///
    /// # Panics
    /// Panics when called on a JSON reader which currently expects a member name, or
    /// when called after the top-level value has already been consumed and multiple top-level
    /// values are not [enabled in the `ReaderSettings`](ReaderSettings::allow_multiple_top_level).
    /// Both cases indicate incorrect usage by the user and are unrelated to the JSON data.
    fn next_null(&mut self) -> Result<(), ReaderError>;

    /// Deserializes a Serde [`Deserialize`](serde_core::de::Deserialize) from the next value
    ///
    /// This method is part of the optional Serde integration feature, see the
    /// [`serde` module](crate::serde) of this crate for more information.
    ///
    /// If it is not possible to directly deserialize a value in place, instead of using
    /// this method a [`JsonReaderDeserializer`](crate::serde::JsonReaderDeserializer)
    /// can be constructed and deserialization can be performed using it later on. However,
    /// this should only be rarely necessary.
    ///
    /// # Examples
    /// ```
    /// # use struson::reader::*;
    /// # use struson::reader::json_path::*;
    /// # use serde::*;
    /// // In this example JSON data comes from a string;
    /// // normally it would come from a file or a network connection
    /// let json = r#"{"outer": {"text": "some text", "number": 5}}"#;
    /// let mut json_reader = JsonStreamReader::new(json.as_bytes());
    ///
    /// // Skip outer data using the regular JsonReader methods
    /// json_reader.seek_to(&json_path!["outer"])?;
    ///
    /// #[derive(Deserialize, PartialEq, Debug)]
    /// struct MyStruct {
    ///     text: String,
    ///     number: u64,
    /// }
    ///
    /// let value: MyStruct = json_reader.deserialize_next()?;
    ///
    /// // Skip the remainder of the JSON document
    /// json_reader.skip_to_top_level()?;
    ///
    /// // Ensures that there is no trailing data
    /// json_reader.consume_trailing_whitespace()?;
    ///
    /// assert_eq!(
    ///     value,
    ///     MyStruct { text: "some text".to_owned(), number: 5 }
    /// );
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    ///
    /// # Security
    /// Since JSON data can have an arbitrary structure and can contain arbitrary
    /// data, care must be taken when processing untrusted data. See the documentation
    /// of [`JsonReaderDeserializer`](crate::serde::JsonReaderDeserializer) for
    /// security considerations.
    ///
    /// # Errors
    /// Errors can occur when either this JSON reader or the `Deserialize` encounters an
    /// error. In which situations this can happen depends on the `Deserialize` implementation.
    ///
    /// # Panics
    /// Panics when called on a JSON reader which currently expects a member name, or
    /// when called after the top-level value has already been consumed and multiple top-level
    /// values are not [enabled in the `ReaderSettings`](ReaderSettings::allow_multiple_top_level).
    /// Both cases indicate incorrect usage by the user and are unrelated to the JSON data.
    #[cfg(feature = "serde")]
    fn deserialize_next<'de, D: serde_core::de::Deserialize<'de>>(
        &mut self,
    ) -> Result<D, crate::serde::DeserializerError>;

    /// Skips the name of the next JSON object member
    ///
    /// Afterwards one of the value reading methods such as [`next_number`](Self::next_number) can be
    /// used to read the corresponding member value.
    ///
    /// Skipping member names can be useful when the only the values of the JSON object members are
    /// relevant for the application processing the JSON document but the member names don't matter.
    ///
    /// Skipping member names with this method is usually more efficient than calling [`next_name`](Self::next_name)
    /// but discarding its result. However, `skip_name` nonetheless also verifies that the skipped
    /// name has valid syntax.
    ///
    /// # Examples
    /// ```
    /// # use struson::reader::*;
    /// let mut json_reader = JsonStreamReader::new(r#"{"a": 1}"#.as_bytes());
    /// json_reader.begin_object()?;
    ///
    /// // Skip member name "a"
    /// json_reader.skip_name()?;
    ///
    /// assert_eq!(json_reader.next_number_as_str()?, "1");
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    ///
    /// To skip to a specific location in the JSON document the method [`seek_to`](Self::seek_to) can be used.
    ///
    /// # Errors
    /// (besides [`ReaderError::SyntaxError`] and [`ReaderError::IoError`])
    ///
    /// If there is no next object member a [`ReaderError::UnexpectedStructure`] is returned.
    /// [`has_next`](Self::has_next) can be used to check if there are further members in the current JSON object.
    ///
    /// # Panics
    /// Panics when called on a JSON reader which currently does not expect a member name. This
    /// indicates incorrect usage by the user and is unrelated to the JSON data.
    fn skip_name(&mut self) -> Result<(), ReaderError>;

    /// Skips the next value
    ///
    /// This method can be used to skip top-level values, JSON array items and JSON object member
    /// values. To skip an object member name, the method [`skip_name`](Self::skip_name) has to be used.\
    /// Skipping a JSON array or object skips the complete value including all nested ones, if any.
    ///
    /// Skipping values can be useful when parts of the processed JSON document are not relevant
    /// for the application processing it.
    ///
    /// Skipping values with this method is usually more efficient than calling regular value reading
    /// methods (such as `next_str()`) but discarding their result.
    /// However, `skip_value` nonetheless also verifies that the skipped JSON data has valid syntax.
    ///
    /// # Examples
    /// ```
    /// # use struson::reader::*;
    /// let mut json_reader = JsonStreamReader::new(r#"{"a": [{}], "b": 1}"#.as_bytes());
    /// json_reader.begin_object()?;
    ///
    /// assert_eq!(json_reader.next_name()?, "a");
    ///
    /// // Skip member value [{}]
    /// json_reader.skip_value()?;
    ///
    /// assert_eq!(json_reader.next_name()?, "b");
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    ///
    /// To skip to a specific location in the JSON document the method [`seek_to`](Self::seek_to) can be used.
    ///
    /// # Errors
    /// (besides [`ReaderError::SyntaxError`] and [`ReaderError::IoError`])
    ///
    /// If there is no next value a [`ReaderError::UnexpectedStructure`] is returned. The [`has_next`](Self::has_next)
    /// method can be used to check if there is a next value.
    ///
    /// # Panics
    /// Panics when called on a JSON reader which currently expects a member name ([`skip_name`](Self::skip_name)
    /// has to be used for that), or when called after the top-level value has already been consumed
    /// and multiple top-level values are not [enabled in the `ReaderSettings`](ReaderSettings::allow_multiple_top_level).
    /// Both cases indicate incorrect usage by the user and are unrelated to the JSON data.
    fn skip_value(&mut self) -> Result<(), ReaderError>;

    /// Seeks to the specified location in the JSON document
    ///
    /// Seeks to the specified relative JSON path in the JSON document by skipping all previous
    /// values. The JSON reader is expected to be positioned before the first value specified
    /// in the path. Once this method returns successfully the reader will be positioned
    /// before the last element specified by the path.
    ///
    /// For example for the JSON path `json_path!["foo", 2]` it will start consuming a JSON object,
    /// skipping members until it finds one with name "foo". Then it starts consuming the member
    /// value, expecting that it is a JSON array, until right before the array item with (starting
    /// at 0) index 2. If multiple members in a JSON object have the same name (for example
    /// `{"a": 1, "a": 2}`) this method will seek to the first occurrence.
    ///
    /// When given an empty JSON path, that is, an array containing no path pieces, the reader
    /// stays in front of the current JSON value and does not begin any JSON arrays or objects
    /// and does not skip any values.
    ///
    /// Seeking to a specific location can be useful when parts of the processed JSON document
    /// are not relevant for the application processing it.
    ///
    /// To continue reading at the original nesting level before `seek_to` had been called,
    /// use [`seek_back`](Self::seek_back) afterwards.
    ///
    /// # Examples
    /// ```
    /// # use struson::reader::*;
    /// # use struson::reader::json_path::*;
    /// let mut json_reader = JsonStreamReader::new(
    ///     r#"{"bar": true, "foo": ["a", "b", "c"]}"#.as_bytes()
    /// );
    /// json_reader.seek_to(&json_path!["foo", 2])?;
    ///
    /// // Can now consume the value to which the call seeked to
    /// assert_eq!(json_reader.next_str()?, "c");
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    ///
    /// # Errors
    /// (besides [`ReaderError::SyntaxError`] and [`ReaderError::IoError`])
    ///
    /// If the structure or the value types of the JSON document do not match the structure expected
    /// by the JSON path, either a [`ReaderError::UnexpectedStructure`] or a [`ReaderError::UnexpectedValueType`]
    /// is returned.
    ///
    /// # Panics
    /// Panics when called on a JSON reader which currently expects a member name, or
    /// when called after the top-level value has already been consumed and multiple top-level
    /// values are not [enabled in the `ReaderSettings`](ReaderSettings::allow_multiple_top_level).
    /// Both cases indicate incorrect usage by the user and are unrelated to the JSON data.
    /*
     * TODO: Should this rather take a `IntoIterator<Item = JsonPathPiece>` as path?
     *   Though use cases where the path is created dynamically and is not present as slice might be rare
     *   When changing this method, might render the `JsonPath` type alias a bit pointless then
     * TODO: Rename this method? Name is based on file IO function `seek`, but not sure if "seek to"
     *   is a proper phrase in this context
     */
    fn seek_to(&mut self, rel_json_path: &JsonPath) -> Result<(), ReaderError> {
        // peek here to fail if reader is currently not expecting a value, even if `rel_json_path` is empty
        // and it would otherwise not be detected
        self.peek()?;

        for path_piece in rel_json_path {
            match path_piece {
                JsonPathPiece::ArrayItem(index) => {
                    self.begin_array()?;
                    for i in 0..=*index {
                        if !self.has_next()? {
                            return Err(ReaderError::UnexpectedStructure {
                                kind: UnexpectedStructureKind::TooShortArray {
                                    expected_index: *index,
                                },
                                location: self.current_position(true),
                            });
                        }

                        // Last iteration only makes sure has_next() succeeds; don't have to skip value
                        if i < *index {
                            self.skip_value()?;
                        }
                    }
                }
                JsonPathPiece::ObjectMember(name) => {
                    self.begin_object()?;

                    let mut found_member = false;
                    while self.has_next()? {
                        if self.next_name()? == name {
                            found_member = true;
                            break;
                        } else {
                            self.skip_value()?;
                        }
                    }

                    if !found_member {
                        return Err(ReaderError::UnexpectedStructure {
                            kind: UnexpectedStructureKind::MissingObjectMember {
                                member_name: name.clone(),
                            },
                            location: self.current_position(true),
                        });
                    }
                }
            }
        }

        Ok(())
    }

    /// Seeks to the original nesting level where [`seek_to`](Self::seek_to) started
    ///
    /// This method is intended to be used together with `seek_to`. When it is given the
    /// same path which had been passed to `seek_to` before, it goes through the path in
    /// reverse order skipping remaining JSON array items and object members and closing
    /// arrays and objects. Therefore once this method returns the reader is at the same
    /// nesting level it was before `seek_to` had been called and allows continuing reading
    /// values there.\
    /// Note that this method only seeks 'back' to the original nesting level, it still
    /// advances _forward_ in the JSON data. So after `seek_to` followed by `seek_back`
    /// had been called, the reader effectively advanced one JSON value (and its nested
    /// values, if any) at the original nesting level.
    ///
    /// For directly getting to the top-level regardless of the current position of the
    /// JSON reader, prefer [`skip_to_top_level`](Self::skip_to_top_level) instead.
    ///
    /// The correct usage looks like this:
    /// 1. Call `seek_to` with _path_
    /// 2. Read one or more values
    /// 3. Call `seek_back` with the same _path_
    ///
    /// Using this method in a different way can lead to errors and panics. In particular
    /// it is important that for step 2:
    /// - the value and all nested values (if any) are fully consumed; any additional JSON
    ///   arrays and objects which are started must be closed again
    /// - no enclosing JSON arrays or objects must be closed
    /// - if the path points to the member of a JSON object, then for every additionally read
    ///   member name of that object the corresponding member value must be consumed as well
    ///
    /// When given an empty JSON path, that is, an array containing no path pieces, the reader
    /// stays at its current position and does not consume any JSON tokens.
    ///
    /// # Examples
    /// The following example shows how `seek_to` and `seek_back` can be combined to read the
    /// nested object member `a.b` from a JSON array containing multiple such objects.
    /// ```
    /// # use struson::reader::*;
    /// # use struson::reader::json_path::*;
    /// let mut json_reader = JsonStreamReader::new(
    ///     r#"[{"a": {"b": "first"}}, {"a": {"b": "second"}}]"#.as_bytes()
    /// );
    /// let mut values = Vec::<String>::new();
    ///
    /// json_reader.begin_array()?;
    /// while json_reader.has_next()? {
    ///     // Seek to the nested JSON object member
    ///     let path = json_path!["a", "b"];
    ///     json_reader.seek_to(&path)?;
    ///
    ///     // Read the value to which the call seeked to
    ///     let value = json_reader.next_string()?;
    ///     values.push(value);
    ///
    ///     // Go back to original nesting level to continue reading there
    ///     // In this example that is the top-level JSON array
    ///     json_reader.seek_back(&path)?;
    /// }
    /// json_reader.end_array()?;
    ///
    /// assert_eq!(values, vec!["first", "second"]);
    ///
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    ///
    /// # Panics
    /// Panics may occur if not used according to the correct usage described above.
    fn seek_back(&mut self, rel_json_path: &JsonPath) -> Result<(), ReaderError> {
        // Undo seek piece by piece in reverse order
        for piece in rel_json_path.iter().rev() {
            match piece {
                JsonPathPiece::ArrayItem(_) => {
                    // Skip remaining items
                    while self.has_next()? {
                        self.skip_value()?;
                    }
                    self.end_array()?;
                }
                JsonPathPiece::ObjectMember(_) => {
                    // Skip remaining members
                    while self.has_next()? {
                        self.skip_name()?;
                        self.skip_value()?;
                    }
                    self.end_object()?;
                }
            }
        }
        Ok(())
    }

    /// Skips the remaining elements of all currently enclosing JSON arrays and objects
    ///
    /// Based on the current JSON reader position skips the remaining elements of all enclosing
    /// JSON arrays and objects (if any) until the top-level is reached. That is, for every array
    /// started with [`begin_array`](Self::begin_array) and for every object started with [`begin_object`](Self::begin_object)
    /// the remaining elements are skipped and the end of the array respectively object is consumed.
    /// During skipping, the syntax of the skipped values is validated. Calling this method has no
    /// effect when there is currently no enclosing JSON array or object.
    ///
    /// This method is useful when a subsection of a JSON document has been consumed, for example
    /// with the help of [`seek_to`](Self::seek_to), and afterwards either
    /// - the syntax of the remainder of the document should be validated and trailing data should
    ///   be rejected, by calling [`consume_trailing_whitespace`](Self::consume_trailing_whitespace)
    /// - or, multiple top-level values are [enabled in the `ReaderSettings`](ReaderSettings::allow_multiple_top_level).
    ///   and the next top-level value should be consumed
    ///
    /// # Examples
    /// ```
    /// # use struson::reader::*;
    /// # use struson::reader::json_path::*;
    /// let mut json_reader = JsonStreamReader::new(
    ///     r#"{"bar": true, "foo": ["a", "b", "c"]}"#.as_bytes()
    /// );
    /// json_reader.seek_to(&json_path!["foo", 2])?;
    ///
    /// // Consume the value to which the call seeked to
    /// assert_eq!(json_reader.next_str()?, "c");
    ///
    /// // Skip the remainder of the document
    /// json_reader.skip_to_top_level()?;
    /// // And verify that there is only optional whitespace, but no trailing data
    /// json_reader.consume_trailing_whitespace()?;
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    ///
    /// # Errors
    /// None, besides [`ReaderError::SyntaxError`] and [`ReaderError::IoError`].
    fn skip_to_top_level(&mut self) -> Result<(), ReaderError>;

    /// Consumes the next value and writes it to the given JSON writer
    ///
    /// This method consumes the next value and calls the corresponding methods on the
    /// JSON writer to emit the value again. Due to this, whitespace and comments, if
    /// [enabled in the `ReaderSettings`](ReaderSettings::allow_comments), are not preserved.
    /// Instead the formatting of the output is dependent on the configuration of the JSON writer.
    /// Similarly the Unicode characters of member names and string values might be escaped
    /// differently. However, all these differences don't have an effect on the JSON value.
    /// JSON readers will consider it to be equivalent. For JSON numbers the exact format
    /// is preserved.
    ///
    /// This method is useful for extracting a subsection from a JSON document and / or for
    /// embedding it into another JSON document. Extraction can be done by using for example
    /// [`seek_to`](Self::seek_to) to position the reader before calling this method. Embedding
    /// can be done by already writing JSON data to the JSON writer before calling this method.
    ///
    /// # Examples
    /// ```
    /// # use struson::reader::*;
    /// # use struson::reader::json_path::*;
    /// # use struson::writer::*;
    /// let mut json_reader = JsonStreamReader::new(
    ///     r#"{"bar": true, "foo": [1, 2]}"#.as_bytes()
    /// );
    /// json_reader.seek_to(&json_path!["foo"])?;
    ///
    /// let mut writer = Vec::<u8>::new();
    /// let mut json_writer = JsonStreamWriter::new(&mut writer);
    /// json_writer.begin_object()?;
    /// json_writer.name("embedded")?;
    ///
    /// // Extract subsection from reader and embed it in the document created by the writer
    /// json_reader.transfer_to(&mut json_writer)?;
    ///
    /// json_writer.end_object()?;
    /// json_writer.finish_document()?;
    ///
    /// let json = String::from_utf8(writer)?;
    /// assert_eq!(json, r#"{"embedded":[1,2]}"#);
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    ///
    /// # Errors
    /// Errors are reported as [`TransferError`] which wraps either an error which occurred for this
    /// JSON reader or an error which occurred for the given JSON writer.
    ///
    /// ## Reader errors
    /// (besides [`ReaderError::SyntaxError`] and [`ReaderError::IoError`])
    ///
    /// If there is no next value a [`ReaderError::UnexpectedStructure`] is returned. The [`has_next`](Self::has_next)
    /// method can be used to check if there is a next value.
    ///
    /// ## Writer errors
    /// If writing the JSON value fails an IO error is returned.
    ///
    /// # Panics
    /// Panics when called on a JSON reader which currently expects a member name, or
    /// when called after the top-level value has already been consumed and multiple top-level
    /// values are not [enabled in the `ReaderSettings`](ReaderSettings::allow_multiple_top_level).
    ///
    /// Panics when the given JSON writer currently expects a member name, or when it has already
    /// written a top-level value and multiple top-level values are not
    /// [enabled in the `WriterSettings`](crate::writer::WriterSettings::multi_top_level_value_separator).
    ///
    /// These cases indicate incorrect usage by the user and are unrelated to the JSON data.
    /*
     * TODO: Choose a different name which makes it clearer that only the next value is transferred, e.g. `transfer_next_to`?
     * TODO: Are the use cases common enough to justify the existence of this method?
     */
    fn transfer_to<W: JsonWriter>(&mut self, json_writer: &mut W) -> Result<(), TransferError>;

    /// Consumes trailing whitespace at the end of the top-level value
    ///
    /// Additionally, if comments are [enabled in the `ReaderSettings`](ReaderSettings::allow_comments)
    /// also consumes trailing comments. If there is any trailing data a [`ReaderError::SyntaxError`]
    /// is returned.
    ///
    /// This method can be useful to verify that a JSON document is wellformed and does not
    /// have any unexpected data at the end. This is not checked automatically by this JSON reader.
    ///
    /// When multiple top-level values are [enabled in the `ReaderSettings`](ReaderSettings::allow_multiple_top_level)
    /// but not all top-level values are relevant they can be skipped with a loop calling
    /// [`has_next`](Self::has_next) and [`skip_value`](Self::skip_value) to allow calling
    /// `consume_trailing_whitespace` eventually:
    /// ```
    /// # use struson::reader::*;
    /// # let mut json_reader = JsonStreamReader::new_custom("1".as_bytes(), ReaderSettings { allow_multiple_top_level: true, ..ReaderSettings::default() });
    /// # json_reader.skip_value()?;
    /// // Skip all remaining top-level values
    /// while json_reader.has_next()? {
    ///     json_reader.skip_value()?;
    /// }
    ///
    /// // Verify that there is only optional whitespace, but no trailing data
    /// json_reader.consume_trailing_whitespace()?;
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    ///
    /// **Important:** It is expected that there is always at least one top-level value
    /// in a JSON document, so calling this method without having consumed a value yet
    /// will panic, see "Panics" section below.
    ///
    /// # Errors
    /// (besides [`ReaderError::IoError`])
    ///
    /// If there is trailing data at the end of the top-level value a [`ReaderError::SyntaxError`]
    /// of kind [`SyntaxErrorKind::TrailingData`] is returned.
    ///
    /// # Panics
    /// Panics when called on a JSON reader which has not read any top-level yet, or when
    /// called while the top-level value has not been fully consumed yet. Both cases
    /// indicate incorrect usage by the user and are unrelated to the JSON data.
    /* Consumes 'self' */
    fn consume_trailing_whitespace(self) -> Result<(), ReaderError>;

    /// Gets the current position of this JSON reader within the JSON data
    ///
    /// The position can be used to enhance custom errors when building a parser on top
    /// of this JSON reader. `include_path` determines whether the [JSON path](JsonReaderPosition::path)
    /// should be included, assuming the JSON reader implementation supports providing
    /// this information (if it doesn't the path will be `None` regardless of `include_path`
    /// value). Including the JSON path can make the position information more useful
    /// for troubleshooting. However, if a caller frequently requests the position,
    /// for example to have it providently in case subsequent parsing fails, then it
    /// might improve performance to not include the path information.
    ///
    /// [Line](JsonReaderPosition::line_pos) and [data position](JsonReaderPosition::data_pos)
    /// are only specified if [`has_next`](Self::has_next) or [`peek`](Self::peek) have just
    /// been called, in which case their values point at the start of the next token. Otherwise
    /// their values can be anywhere between the previous token and the next token (if any).
    ///
    /// The position information makes no guarantee about the amount of data (e.g. number of
    /// bytes) consumed from the underlying data source. JSON reader implementations might
    /// buffer data which has not been processed yet.
    ///
    /// # Examples
    /// Let's assume an array of points encoded as JSON string in the format `x|y` should
    /// be parsed:
    ///
    /// ```
    /// # use struson::reader::*;
    /// let mut json_reader = JsonStreamReader::new(
    ///     r#"["1|2", "3|2", "8"]"#.as_bytes()
    /// );
    /// json_reader.begin_array()?;
    ///
    /// while json_reader.has_next()? {
    ///     let pos = json_reader.current_position(true);
    ///     let encoded_point = json_reader.next_str()?;
    ///
    /// #   #[expect(unused_variables)]
    ///     if let Some((x, y)) = encoded_point.split_once('|') {
    ///         // ...
    ///     } else {
    ///         // Includes the JSON reader position for easier troubleshooting
    ///         println!("Malformed point '{encoded_point}', at {pos}");
    /// #       assert_eq!(pos.to_string(), "path '$[2]', line 0, column 15 (data pos 15)");
    ///     }
    /// }
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    fn current_position(&self, include_path: bool) -> JsonReaderPosition;
}

#[cfg(test)]
mod tests {
    use std::io::ErrorKind;

    use super::{
        IoError, JsonReaderPosition, JsonSyntaxError, LinePosition, ReaderError, SyntaxErrorKind,
        UnexpectedStructureKind, ValueType,
        json_path::{JsonPathPiece, json_path},
    };

    #[test]
    fn reader_error_clone() {
        let original_location = JsonReaderPosition {
            path: Some(json_path!["a", 1].to_vec()),
            line_pos: Some(LinePosition { line: 0, column: 7 }),
            data_pos: Some(7),
        };

        let syntax_error = JsonSyntaxError {
            kind: SyntaxErrorKind::MalformedJson,
            location: original_location.clone(),
        };
        let original = ReaderError::SyntaxError(syntax_error.clone());
        match original.rough_clone() {
            ReaderError::SyntaxError(e) => assert_eq!(syntax_error, e),
            e => panic!("unexpected error: {e:?}"),
        }

        let original = ReaderError::UnexpectedValueType {
            expected: ValueType::Array,
            actual: ValueType::Boolean,
            location: original_location.clone(),
        };
        match original.rough_clone() {
            ReaderError::UnexpectedValueType {
                expected: ValueType::Array,
                actual: ValueType::Boolean,
                location,
            } => assert_eq!(original_location, location),
            e => panic!("unexpected error: {e:?}"),
        }

        let unexpected_structure = UnexpectedStructureKind::TooShortArray { expected_index: 2 };
        let original = ReaderError::UnexpectedStructure {
            kind: unexpected_structure.clone(),
            location: original_location.clone(),
        };
        match original.rough_clone() {
            ReaderError::UnexpectedStructure { kind, location } => {
                assert_eq!(unexpected_structure, kind);
                assert_eq!(original_location, location);
            }
            e => panic!("unexpected error: {e:?}"),
        }

        let original = ReaderError::MaxNestingDepthExceeded {
            max_nesting_depth: 5,
            location: original_location.clone(),
        };
        match original.rough_clone() {
            ReaderError::MaxNestingDepthExceeded {
                max_nesting_depth: 5,
                location,
            } => assert_eq!(original_location, location),
            e => panic!("unexpected error: {e:?}"),
        }

        let original = ReaderError::UnsupportedNumberValue {
            number: "1e123456".to_owned(),
            location: original_location.clone(),
        };
        match original.rough_clone() {
            ReaderError::UnsupportedNumberValue { number, location } => {
                assert_eq!("1e123456", number);
                assert_eq!(original_location, location);
            }
            e => panic!("unexpected error: {e:?}"),
        }

        let original = ReaderError::IoError {
            error: IoError::new(ErrorKind::InvalidData, "custom-message"),
            location: original_location.clone(),
        };
        match original.rough_clone() {
            ReaderError::IoError { error, location } => {
                assert_eq!(ErrorKind::InvalidData, error.kind());
                // Note: Original error cannot be fully preserved, only its `to_string` value is preserved
                assert_eq!("custom-message", error.get_ref().unwrap().to_string());

                assert_eq!(original_location, location);
            }
            e => panic!("unexpected error: {e:?}"),
        }
    }

    #[test]
    fn json_reader_location_display() {
        let path = Some(vec![
            JsonPathPiece::ArrayItem(1),
            JsonPathPiece::ObjectMember("name".to_owned()),
        ]);
        let line_pos = Some(LinePosition { line: 1, column: 2 });
        let data_pos = Some(3);

        let combinations = vec![
            ((None, None, None), "<location unavailable>"),
            ((None, None, data_pos), "data pos 3"),
            ((None, line_pos, None), "line 1, column 2"),
            ((None, line_pos, data_pos), "line 1, column 2 (data pos 3)"),
            ((path.clone(), None, None), "path '$[1].name'"),
            (
                (path.clone(), None, data_pos),
                "path '$[1].name', data pos 3",
            ),
            (
                (path.clone(), line_pos, None),
                "path '$[1].name', line 1, column 2",
            ),
            (
                (path.clone(), line_pos, data_pos),
                "path '$[1].name', line 1, column 2 (data pos 3)",
            ),
        ];

        for combination in combinations {
            let location_data = combination.0;
            let reader_location = JsonReaderPosition {
                path: location_data.0.clone(),
                line_pos: location_data.1,
                data_pos: location_data.2,
            };
            let display_string = reader_location.to_string();
            let expected_display_string = combination.1;
            assert_eq!(
                expected_display_string, display_string,
                "expected display string for {location_data:?}: {expected_display_string}"
            );
        }
    }

    /// Tests custom `Display` implementation for [`UnexpectedStructureKind`]
    #[test]
    fn unexpected_structure_kind_display() {
        assert_eq!(
            "TooShortArray(expected_index = 2)",
            UnexpectedStructureKind::TooShortArray { expected_index: 2 }.to_string()
        );
        assert_eq!(
            "MissingObjectMember(\"custom-name\")",
            UnexpectedStructureKind::MissingObjectMember {
                member_name: "custom-name".to_owned()
            }
            .to_string()
        );

        assert_eq!(
            "FewerElementsThanExpected",
            UnexpectedStructureKind::FewerElementsThanExpected.to_string()
        );
        assert_eq!(
            "MoreElementsThanExpected",
            UnexpectedStructureKind::MoreElementsThanExpected.to_string()
        );
    }
}