nojson 0.3.12

A flexible Rust JSON library with no dependencies, no macros, no unsafe and optional no_std support
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
use alloc::{
    borrow::Cow, borrow::ToOwned, boxed::Box, format, string::String, string::ToString, vec::Vec,
};
use core::{fmt::Display, hash::Hash, ops::Range};

use crate::{
    DisplayJson, JsonArrayFormatter, JsonFormatter, JsonObjectFormatter, JsonValueKind,
    parse::{JsonParser, Jsonc, Plain},
};

pub use crate::parse_error::JsonParseError;

/// Owned version of [`RawJson`].
#[derive(Debug, Clone)]
pub struct RawJsonOwned {
    text: String,
    values: Vec<JsonValueIndexEntry>,
}

impl RawJsonOwned {
    /// Parses a JSON string into a [`RawJsonOwned`] instance.
    ///
    /// This validates the JSON syntax without converting values to Rust types.
    /// Unlike [`RawJson::parse`], this creates an owned version that doesn't
    /// borrow from the input string.
    ///
    /// # Example
    ///
    /// ```
    /// # fn main() -> Result<(), nojson::JsonParseError> {
    /// let text = r#"{"name": "John", "age": 30}"#;
    /// let json = nojson::RawJsonOwned::parse(text)?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn parse<T>(text: T) -> Result<Self, JsonParseError>
    where
        T: Into<String>,
    {
        let text = text.into();
        let (values, _) = JsonParser::<Plain>::new(&text).parse()?;
        Ok(Self { text, values })
    }

    /// Parses a JSONC (JSON with Comments) string into a [`RawJsonOwned`] instance.
    ///
    /// This validates the JSONC syntax and strips out comments, returning both
    /// the parsed JSON structure and the byte ranges where comments were found
    /// in the original text. Comments can be either line comments (`//`) or
    /// block comments (`/* */`). Additionally, this parser allows trailing commas
    /// in objects and arrays.
    ///
    /// Unlike [`RawJson::parse_jsonc`], this creates an owned version that doesn't
    /// borrow from the input string.
    ///
    /// # Example
    ///
    /// ```
    /// # fn main() -> Result<(), nojson::JsonParseError> {
    /// let text = r#"{
    ///     "name": "John", // This is a comment
    ///     "age": 30,
    ///     /*
    ///      * This is a multi-line
    ///      * block comment
    ///      */
    ///     "city": "New York", // Trailing comma is allowed
    /// }"#;
    ///
    /// let (json, comment_ranges) = nojson::RawJsonOwned::parse_jsonc(text)?;
    ///
    /// // The parsed JSON works normally
    /// let name: String = json.value().to_member("name")?.required()?.try_into()?;
    /// assert_eq!(name, "John");
    ///
    /// // Comment ranges indicate where comments were found in the original text
    /// assert_eq!(comment_ranges.len(), 3); // Three comments found
    ///
    /// // You can extract the comment text if needed
    /// let first_comment = &text[comment_ranges[0].clone()];
    /// assert!(first_comment.contains("This is a comment"));
    /// # Ok(())
    /// # }
    /// ```
    pub fn parse_jsonc<T>(text: T) -> Result<(Self, Vec<Range<usize>>), JsonParseError>
    where
        T: Into<String>,
    {
        let text = text.into();
        let (values, comments) = JsonParser::<Jsonc>::new(&text).parse()?;
        Ok((Self { text, values }, comments))
    }

    /// Creates an owned JSON object using the in-place object formatter.
    ///
    /// This is a convenience for building a [`RawJsonOwned`] object directly
    /// without going through intermediate parsing calls in user code.
    /// It is a shorthand for
    /// `RawJsonOwned::parse(nojson::object(|f| ...).to_string())`,
    /// provided for this common pattern.
    ///
    /// # Example
    ///
    /// ```
    /// let json = nojson::RawJsonOwned::object(|f| {
    ///     f.member("name", "Alice")?;
    ///     f.member("age", 30)
    /// });
    ///
    /// assert_eq!(json.text(), r#"{"name":"Alice","age":30}"#);
    /// ```
    pub fn object<F>(fmt: F) -> Self
    where
        F: Fn(&mut JsonObjectFormatter<'_, '_, '_>) -> core::fmt::Result,
    {
        Self::parse(crate::object(fmt).to_string())
            .expect("bug: object formatter must produce valid JSON")
    }

    /// Creates owned JSON using the in-place formatter.
    ///
    /// This is a convenience for building a [`RawJsonOwned`] value directly
    /// without going through intermediate parsing calls in user code.
    /// It is a shorthand for
    /// `RawJsonOwned::parse(nojson::json(|f| ...).to_string())`,
    /// provided for this common pattern.
    ///
    /// # Example
    ///
    /// ```
    /// let json = nojson::RawJsonOwned::json(|f| f.value([1, 2, 3]));
    /// assert_eq!(json.text(), "[1,2,3]");
    /// ```
    pub fn json<F>(fmt: F) -> Self
    where
        F: Fn(&mut JsonFormatter<'_, '_>) -> core::fmt::Result,
    {
        Self::parse(crate::json(fmt).to_string())
            .expect("bug: json formatter must produce valid JSON")
    }

    /// Creates an owned JSON array using the in-place array formatter.
    ///
    /// This is a convenience for building a [`RawJsonOwned`] array directly
    /// without going through intermediate parsing calls in user code.
    /// It is a shorthand for
    /// `RawJsonOwned::parse(nojson::array(|f| ...).to_string())`,
    /// provided for this common pattern.
    ///
    /// # Example
    ///
    /// ```
    /// let json = nojson::RawJsonOwned::array(|f| {
    ///     f.element(1)?;
    ///     f.element(2)?;
    ///     f.element(3)
    /// });
    ///
    /// assert_eq!(json.text(), "[1,2,3]");
    /// ```
    pub fn array<F>(fmt: F) -> Self
    where
        F: Fn(&mut JsonArrayFormatter<'_, '_, '_>) -> core::fmt::Result,
    {
        Self::parse(crate::array(fmt).to_string())
            .expect("bug: array formatter must produce valid JSON")
    }

    /// Returns the original JSON text.
    pub fn text(&self) -> &str {
        &self.text
    }

    /// Returns the top-level value of the JSON.
    ///
    /// This value can be used as an entry point to traverse the entire JSON structure
    /// and convert it to Rust types.
    ///
    /// # Example
    ///
    /// ```
    /// # fn main() -> Result<(), nojson::JsonParseError> {
    /// let text = r#"{"name": "John", "age": 30}"#;
    /// let json = nojson::RawJsonOwned::parse(text).unwrap();
    /// let value = json.value();
    /// # Ok(())
    /// # }
    /// ```
    pub fn value(&self) -> RawJsonValue<'_, '_> {
        RawJsonValue {
            json: self.as_raw_json_ref(),
            index: 0,
        }
    }

    /// Finds the JSON value at the specified byte position in the original text.
    ///
    /// This method traverses the JSON structure to find the most specific value
    /// that contains the given position.
    /// It returns `None` if the position is outside the bounds of the JSON text.
    ///
    /// This method is useful for retrieving the context
    /// where a [`JsonParseError::InvalidValue`] error occurred.
    ///
    /// # Example
    ///
    /// ```
    /// # fn main() -> Result<(), nojson::JsonParseError> {
    /// let json = nojson::RawJsonOwned::parse(r#"{"name": "John", "age": 30}"#)?;
    ///
    /// // Position at "name" key
    /// let name_value = json.get_value_by_position(2).expect("infallible");
    /// assert_eq!(name_value.as_raw_str(), r#""name""#);
    ///
    /// // Position at number value
    /// let age_value = json.get_value_by_position(25).expect("infallible");
    /// assert_eq!(age_value.as_raw_str(), "30");
    /// # Ok(())
    /// # }
    /// ```
    pub fn get_value_by_position(&self, position: usize) -> Option<RawJsonValue<'_, '_>> {
        self.as_raw_json_ref().get_value_by_position(position)
    }

    /// Returns the JSON value at the specified index in the internal value array.
    ///
    /// This method provides direct access to any value in the JSON structure by its
    /// internal index. It's useful when you need to access a value after validation
    /// or when you've stored an index for later retrieval, allowing constant-time
    /// access without traversing the JSON structure.
    ///
    /// Returns `None` if the index is out of bounds.
    ///
    /// # Example
    ///
    /// ```
    /// # fn main() -> Result<(), nojson::JsonParseError> {
    /// let json = nojson::RawJsonOwned::parse(r#"{"name": "John", "age": 30}"#)?;
    ///
    /// // Get the root object (always at index 0)
    /// let root = json.get_value_by_index(0).expect("root exists");
    ///
    /// // Access nested values by storing their indices
    /// let name_value = root.to_member("name")?.required()?;
    /// let name_index = name_value.index();
    ///
    /// // Later, retrieve the value directly by index
    /// let same_value = json.get_value_by_index(name_index).expect("index is valid");
    /// assert_eq!(same_value.as_raw_str(), r#""John""#);
    /// # Ok(())
    /// # }
    /// ```
    pub fn get_value_by_index(&self, index: usize) -> Option<RawJsonValue<'_, '_>> {
        (index < self.values.len()).then(|| RawJsonValue {
            json: self.as_raw_json_ref(),
            index,
        })
    }

    fn as_raw_json_ref(&self) -> RawJsonRef<'_, '_> {
        RawJsonRef {
            text: &self.text,
            values: &self.values,
        }
    }
}

impl PartialEq for RawJsonOwned {
    fn eq(&self, other: &Self) -> bool {
        self.text == other.text
    }
}

impl Eq for RawJsonOwned {}

impl PartialOrd for RawJsonOwned {
    fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for RawJsonOwned {
    fn cmp(&self, other: &Self) -> core::cmp::Ordering {
        self.text.cmp(&other.text)
    }
}

impl Hash for RawJsonOwned {
    fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
        self.text.hash(state);
    }
}

impl Display for RawJsonOwned {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "{}", crate::Json(self))
    }
}

impl DisplayJson for RawJsonOwned {
    fn fmt(&self, f: &mut JsonFormatter<'_, '_>) -> core::fmt::Result {
        DisplayJson::fmt(&self.value(), f)
    }
}

impl core::str::FromStr for RawJsonOwned {
    type Err = JsonParseError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Self::parse(s)
    }
}

impl<'text, 'raw> TryFrom<RawJsonValue<'text, 'raw>> for RawJsonOwned {
    type Error = JsonParseError;

    fn try_from(value: RawJsonValue<'text, 'raw>) -> Result<Self, Self::Error> {
        Ok(value.extract().into_owned())
    }
}

/// Parsed JSON text (syntactically correct, but not yet converted to Rust types).
///
/// This struct holds a JSON text in its original form
/// (i.e., JSON integers are not converted to Rust's integers),
/// while ensuring the text is valid JSON syntax.
///
/// [`RawJson`] maintains index information about each JSON value in the text,
/// including its type ([`JsonValueKind`]) and the start and end byte positions.
/// You can traverse the JSON structure by accessing the top-level value
/// via [`RawJson::value()`], which returns a [`RawJsonValue`]
/// that provides methods to explore nested elements and convert them into Rust types.
///
/// Note that, for simple use cases,
/// using [`Json`](crate::Json), which internally uses [`RawJson`], is a more convenient way to parse JSON text into Rust types.
#[derive(Debug, Clone)]
pub struct RawJson<'text> {
    text: &'text str,
    values: Vec<JsonValueIndexEntry>,
}

impl<'text> RawJson<'text> {
    /// Parses a JSON string into a [`RawJson`] instance.
    ///
    /// This validates the JSON syntax without converting values to Rust types.
    ///
    /// # Example
    ///
    /// ```
    /// # fn main() -> Result<(), nojson::JsonParseError> {
    /// let text = r#"{"name": "John", "age": 30}"#;
    /// let json = nojson::RawJson::parse(text)?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn parse(text: &'text str) -> Result<Self, JsonParseError> {
        let (values, _) = JsonParser::<Plain>::new(text).parse()?;
        Ok(Self { text, values })
    }

    /// Parses a JSONC (JSON with Comments) string into a [`RawJson`] instance.
    ///
    /// This validates the JSONC syntax and strips out comments, returning both
    /// the parsed JSON structure and the byte ranges where comments were found
    /// in the original text. Comments can be either line comments (`//`) or
    /// block comments (`/* */`). Additionally, this parser allows trailing commas
    /// in objects and arrays.
    ///
    /// # Example
    ///
    /// ```
    /// # fn main() -> Result<(), nojson::JsonParseError> {
    /// let text = r#"{
    ///     "name": "John", // This is a comment
    ///     "age": 30,
    ///     /* This is a block comment */
    ///     "city": "New York", // Trailing comma is allowed
    /// }"#;
    ///
    /// let (json, comment_ranges) = nojson::RawJson::parse_jsonc(text)?;
    ///
    /// // The parsed JSON works normally
    /// let name: String = json.value().to_member("name")?.required()?.try_into()?;
    /// assert_eq!(name, "John");
    ///
    /// // Comment ranges indicate where comments were found in the original text
    /// assert_eq!(comment_ranges.len(), 3); // Three comments found
    ///
    /// // You can extract the comment text if needed
    /// let first_comment = &text[comment_ranges[0].clone()];
    /// assert!(first_comment.contains("This is a comment"));
    /// # Ok(())
    /// # }
    /// ```
    pub fn parse_jsonc(text: &'text str) -> Result<(Self, Vec<Range<usize>>), JsonParseError> {
        let (values, comments) = JsonParser::<Jsonc>::new(text).parse()?;
        Ok((Self { text, values }, comments))
    }

    /// Returns the original JSON text.
    pub fn text(&self) -> &'text str {
        self.text
    }

    /// Returns the top-level value of the JSON.
    ///
    /// This value can be used as an entry point to traverse the entire JSON structure
    /// and convert it to Rust types.
    ///
    /// # Example
    ///
    /// ```
    /// # fn main() -> Result<(), nojson::JsonParseError> {
    /// let text = r#"{"name": "John", "age": 30}"#;
    /// let json = nojson::RawJson::parse(text).unwrap();
    /// let value = json.value();
    /// # Ok(())
    /// # }
    /// ```
    pub fn value(&self) -> RawJsonValue<'text, '_> {
        RawJsonValue {
            json: self.as_raw_json_ref(),
            index: 0,
        }
    }

    /// Finds the JSON value at the specified byte position in the original text.
    ///
    /// This method traverses the JSON structure to find the most specific value
    /// that contains the given position.
    /// It returns `None` if the position is outside the bounds of the JSON text.
    ///
    /// This method is useful for retrieving the context
    /// where a [`JsonParseError::InvalidValue`] error occurred.
    ///
    /// # Example
    ///
    /// ```
    /// # fn main() -> Result<(), nojson::JsonParseError> {
    /// let json = nojson::RawJson::parse(r#"{"name": "John", "age": 30}"#)?;
    ///
    /// // Position at "name" key
    /// let name_value = json.get_value_by_position(2).expect("infallible");
    /// assert_eq!(name_value.as_raw_str(), r#""name""#);
    ///
    /// // Position at number value
    /// let age_value = json.get_value_by_position(25).expect("infallible");
    /// assert_eq!(age_value.as_raw_str(), "30");
    /// # Ok(())
    /// # }
    /// ```
    pub fn get_value_by_position(&self, position: usize) -> Option<RawJsonValue<'text, '_>> {
        self.as_raw_json_ref().get_value_by_position(position)
    }

    /// Returns the JSON value at the specified index in the internal value array.
    ///
    /// This method provides direct access to any value in the JSON structure by its
    /// internal index. It's useful when you need to access a value after validation
    /// or when you've stored an index for later retrieval, allowing constant-time
    /// access without traversing the JSON structure.
    ///
    /// Returns `None` if the index is out of bounds.
    ///
    /// # Example
    ///
    /// ```
    /// # fn main() -> Result<(), nojson::JsonParseError> {
    /// let json = nojson::RawJson::parse(r#"{"name": "John", "age": 30}"#)?;
    ///
    /// // Get the root object (always at index 0)
    /// let root = json.get_value_by_index(0).expect("root exists");
    ///
    /// // Access nested values by storing their indices
    /// let name_value = root.to_member("name")?.required()?;
    /// let name_index = name_value.index();
    ///
    /// // Later, retrieve the value directly by index
    /// let same_value = json.get_value_by_index(name_index).expect("index is valid");
    /// assert_eq!(same_value.as_raw_str(), r#""John""#);
    /// # Ok(())
    /// # }
    /// ```
    pub fn get_value_by_index(&self, index: usize) -> Option<RawJsonValue<'text, '_>> {
        (index < self.values.len()).then(|| RawJsonValue {
            json: self.as_raw_json_ref(),
            index,
        })
    }

    /// Converts this borrowed [`RawJson`] into an owned [`RawJsonOwned`].
    ///
    /// This method creates an owned copy of the JSON data, allowing it to be used
    /// beyond the lifetime of the original text. The resulting [`RawJsonOwned`]
    /// contains its own copy of the JSON text and can be moved freely.
    ///
    /// # Example
    ///
    /// ```
    /// # fn main() -> Result<(), nojson::JsonParseError> {
    /// let text = r#"{"name": "John", "age": 30}"#;
    /// let json = nojson::RawJson::parse(text)?;
    /// let owned_json = json.into_owned();
    ///
    /// // The owned version can outlive the original text
    /// drop(text);
    /// assert_eq!(owned_json.text(), r#"{"name": "John", "age": 30}"#);
    /// # Ok(())
    /// # }
    /// ```
    pub fn into_owned(self) -> RawJsonOwned {
        RawJsonOwned {
            text: self.text.to_owned(),
            values: self.values,
        }
    }

    fn as_raw_json_ref(&self) -> RawJsonRef<'text, '_> {
        RawJsonRef {
            text: self.text,
            values: &self.values,
        }
    }
}

impl PartialEq for RawJson<'_> {
    fn eq(&self, other: &Self) -> bool {
        self.text == other.text
    }
}

impl Eq for RawJson<'_> {}

impl PartialOrd for RawJson<'_> {
    fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for RawJson<'_> {
    fn cmp(&self, other: &Self) -> core::cmp::Ordering {
        self.text.cmp(other.text)
    }
}

impl Hash for RawJson<'_> {
    fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
        self.text.hash(state);
    }
}

impl Display for RawJson<'_> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "{}", crate::Json(self))
    }
}

impl DisplayJson for RawJson<'_> {
    fn fmt(&self, f: &mut JsonFormatter<'_, '_>) -> core::fmt::Result {
        DisplayJson::fmt(&self.value(), f)
    }
}

impl<'text, 'raw> TryFrom<RawJsonValue<'text, 'raw>> for RawJson<'text> {
    type Error = JsonParseError;

    fn try_from(value: RawJsonValue<'text, 'raw>) -> Result<Self, Self::Error> {
        Ok(value.extract())
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct JsonValueIndexEntry {
    pub kind: JsonValueKind,
    pub escaped: bool,
    pub text: Range<usize>,
    pub end_index: usize,
}

#[derive(Debug, Clone, Copy)]
struct RawJsonRef<'text, 'raw> {
    text: &'text str,
    values: &'raw [JsonValueIndexEntry],
}

impl<'text, 'raw> RawJsonRef<'text, 'raw> {
    fn get_value_by_position(self, position: usize) -> Option<RawJsonValue<'text, 'raw>> {
        let mut value = self.value();
        if !value.entry().text.contains(&position) {
            return None;
        }
        while let Some(child) = Children::new(value).find(|c| c.entry().text.contains(&position)) {
            value = child;
        }
        Some(value)
    }

    fn value(self) -> RawJsonValue<'text, 'raw> {
        RawJsonValue {
            json: self,
            index: 0,
        }
    }
}

impl PartialEq for RawJsonRef<'_, '_> {
    fn eq(&self, other: &Self) -> bool {
        self.text == other.text
    }
}

impl Eq for RawJsonRef<'_, '_> {}

impl PartialOrd for RawJsonRef<'_, '_> {
    fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for RawJsonRef<'_, '_> {
    fn cmp(&self, other: &Self) -> core::cmp::Ordering {
        self.text.cmp(other.text)
    }
}

impl Hash for RawJsonRef<'_, '_> {
    fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
        self.text.hash(state);
    }
}

impl Display for RawJsonRef<'_, '_> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "{}", crate::Json(self))
    }
}

impl DisplayJson for RawJsonRef<'_, '_> {
    fn fmt(&self, f: &mut JsonFormatter<'_, '_>) -> core::fmt::Result {
        DisplayJson::fmt(&self.value(), f)
    }
}

/// A JSON value in a [`RawJson`].
///
/// This struct provides the text and structural information (e.g., kind, parent, children) of a JSON value.
/// Interpreting that text is the responsibility of the user.
///
/// To convert this JSON value to a Rust type, you can use the standard [`TryFrom`] and [`TryInto`] traits.
/// For other parsing approaches, you can use the [`FromStr`](std::str::FromStr) trait or other parsing methods
/// to parse the underlying JSON text of this value as shown below:
///
/// ```
/// # fn main() -> Result<(), nojson::JsonParseError> {
/// let text = "1.23";
/// let json = nojson::RawJson::parse(text)?;
/// let raw = json.value();
/// let parsed: f32 =
///     raw.as_number_str()?.parse().map_err(|e| raw.invalid(e))?;
/// assert_eq!(parsed, 1.23);
/// # Ok(())
/// # }
/// ```
///
/// For types that implement `TryFrom<RawJsonValue<'_, '_>>`, you can use the [`TryInto`] trait:
///
/// ```
/// # fn main() -> Result<(), nojson::JsonParseError> {
/// let json = nojson::RawJson::parse("[1, 2, 3]")?;
/// let numbers: [u32; 3] = json.value().try_into()?;
/// assert_eq!(numbers, [1, 2, 3]);
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct RawJsonValue<'text, 'raw> {
    index: usize,
    json: RawJsonRef<'text, 'raw>,
}

impl<'text, 'raw> RawJsonValue<'text, 'raw> {
    /// Returns the kind of this JSON value.
    pub fn kind(self) -> JsonValueKind {
        self.json.values[self.index].kind
    }

    /// Returns the byte position where this value begins in the JSON text (`self.json().text()`).
    pub fn position(self) -> usize {
        self.json.values[self.index].text.start
    }

    /// Returns the internal index of this value in the JSON structure.
    ///
    /// Each value in a parsed JSON document is assigned a unique index in the
    /// internal value array. This method returns that index, which can be used
    /// later with [`RawJson::get_value_by_index`] or [`RawJsonOwned::get_value_by_index`]
    /// to retrieve the same value in constant time without traversing the JSON structure.
    ///
    /// # Example
    ///
    /// ```
    /// # fn main() -> Result<(), nojson::JsonParseError> {
    /// let json = nojson::RawJson::parse(r#"{"users": [{"name": "Alice"}, {"name": "Bob"}]}"#)?;
    ///
    /// // Find and store the index of a specific user
    /// let users = json.value().to_member("users")?.required()?.to_array()?;
    /// let bob = users.skip(1).next().expect("Bob exists");
    /// let bob_index = bob.index();
    ///
    /// // Later, retrieve Bob directly by index
    /// let bob_again = json.get_value_by_index(bob_index).expect("index is valid");
    /// let name: String = bob_again.to_member("name")?.required()?.try_into()?;
    /// assert_eq!(name, "Bob");
    /// # Ok(())
    /// # }
    /// ```
    pub fn index(self) -> usize {
        self.index
    }

    /// Returns the parent value (array or object) that contains this value.
    pub fn parent(self) -> Option<Self> {
        if self.index == 0 {
            return None;
        }
        self.json.get_value_by_position(self.position() - 1)
    }

    /// Returns the root (top-level) value of the JSON data.
    ///
    /// This method navigates back to the root value of the entire JSON structure,
    /// regardless of where this value is located in the JSON hierarchy. This is
    /// useful when you want to access other parts of the JSON from a nested value.
    ///
    /// This operation is O(1) and more efficient than repeatedly calling [`parent()`](Self::parent)
    /// to reach the root.
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> Result<(), nojson::JsonParseError> {
    /// let json = nojson::RawJson::parse(r#"{"user": {"name": "John", "age": 30}, "count": 42}"#)?;
    /// let age_value = json
    ///     .value()
    ///     .to_member("user")?.required()?
    ///     .to_member("age")?.required()?;
    ///
    /// // From the nested age value, navigate back to the root
    /// let root = age_value.root();
    ///
    /// // Access any part of the original JSON structure
    /// let count: i32 = root.to_member("count")?.required()?.try_into()?;
    /// assert_eq!(count, 42);
    ///
    /// let user_name: String = root
    ///     .to_member("user")?.required()?
    ///     .to_member("name")?.required()?
    ///     .try_into()?;
    /// assert_eq!(user_name, "John");
    /// # Ok(())
    /// # }
    /// ```
    pub fn root(self) -> Self {
        Self {
            json: self.json,
            index: 0,
        }
    }

    /// Returns the raw JSON text of this value as-is.
    pub fn as_raw_str(self) -> &'text str {
        let text = &self.json.values[self.index].text;
        &self.json.text[text.start..text.end]
    }

    /// Converts this value to a borrowed [`RawJson`] containing just this value and its children.
    ///
    /// This method creates a borrowed view of this specific JSON value and its text,
    /// including all nested children if the value is an object or array. The resulting
    /// [`RawJson`] contains only this value and its descendants as its root,
    /// not the entire original JSON text.
    ///
    /// If you need an owned version, you can call `.into_owned()` on the result.
    ///
    /// # Example
    ///
    /// ```
    /// # fn main() -> Result<(), nojson::JsonParseError> {
    /// let text = r#"{"user": {"name": "John", "age": 30}, "count": 42}"#;
    /// let json = nojson::RawJson::parse(text)?;
    /// let user_value = json.value().to_member("user")?.required()?;
    ///
    /// // Extract the user object and its children to borrowed
    /// let borrowed_user = user_value.extract();
    ///
    /// // The borrowed version references the original text
    /// assert_eq!(borrowed_user.text(), r#"{"name": "John", "age": 30}"#);
    /// let name: String = borrowed_user.value().to_member("name")?.required()?.try_into()?;
    /// assert_eq!(name, "John");
    ///
    /// // Convert to owned if needed
    /// let owned_user = borrowed_user.into_owned();
    /// # Ok(())
    /// # }
    /// ```
    pub fn extract(self) -> RawJson<'text> {
        let start_index = self.index;
        let end_index = self.entry().end_index;

        // Extract the text range that covers this value and all its children
        let start_pos = self.entry().text.start;
        let end_pos = self.entry().text.end;
        let value_text = &self.json.text[start_pos..end_pos];

        // Extract all relevant value entries (this value and its children)
        let relevant_entries = &self.json.values[start_index..end_index];

        // Create new values vector with adjusted positions
        let new_values = relevant_entries
            .iter()
            .map(|entry| JsonValueIndexEntry {
                kind: entry.kind,
                escaped: entry.escaped,
                text: (entry.text.start - start_pos)..(entry.text.end - start_pos),
                end_index: entry.end_index - start_index,
            })
            .collect();

        RawJson {
            text: value_text,
            values: new_values,
        }
    }

    /// Similar to [`RawJsonValue::as_raw_str()`],
    /// but this method verifies whether the value is a JSON boolean.
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> Result<(), nojson::JsonParseError> {
    /// let json = nojson::RawJson::parse("false")?;
    /// assert_eq!(json.value().as_boolean_str()?.parse(), Ok(false));
    ///
    /// let json = nojson::RawJson::parse("10")?;
    /// assert!(json.value().as_boolean_str().is_err());
    /// # Ok(())
    /// # }
    /// ```
    pub fn as_boolean_str(self) -> Result<&'text str, JsonParseError> {
        self.expect([JsonValueKind::Boolean])
            .map(|v| v.as_raw_str())
    }

    /// Similar to [`RawJsonValue::as_raw_str()`],
    /// but this method verifies whether the value is a JSON integer number.
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> Result<(), nojson::JsonParseError> {
    /// let json = nojson::RawJson::parse("123")?;
    /// assert_eq!(json.value().as_integer_str()?.parse(), Ok(123));
    ///
    /// let json = nojson::RawJson::parse("12.3")?;
    /// assert!(json.value().as_integer_str().is_err());
    /// # Ok(())
    /// # }
    /// ```
    pub fn as_integer_str(self) -> Result<&'text str, JsonParseError> {
        self.expect([JsonValueKind::Integer])
            .map(|v| v.as_raw_str())
    }

    /// Similar to [`RawJsonValue::as_raw_str()`],
    /// but this method verifies whether the value is a JSON floating-point number.
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> Result<(), nojson::JsonParseError> {
    /// let json = nojson::RawJson::parse("12.3")?;
    /// assert_eq!(json.value().as_float_str()?.parse(), Ok(12.3));
    ///
    /// let json = nojson::RawJson::parse("123")?;
    /// assert!(json.value().as_float_str().is_err());
    /// # Ok(())
    /// # }
    /// ```
    pub fn as_float_str(self) -> Result<&'text str, JsonParseError> {
        self.expect([JsonValueKind::Float]).map(|v| v.as_raw_str())
    }

    /// Similar to [`RawJsonValue::as_raw_str()`],
    /// but this method verifies whether the value is a JSON number.
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> Result<(), nojson::JsonParseError> {
    /// let json = nojson::RawJson::parse("123")?;
    /// assert_eq!(json.value().as_number_str()?.parse(), Ok(123));
    ///
    /// let json = nojson::RawJson::parse("12.3")?;
    /// assert_eq!(json.value().as_number_str()?.parse(), Ok(12.3));
    ///
    /// let json = nojson::RawJson::parse("null")?;
    /// assert!(json.value().as_number_str().is_err());
    /// # Ok(())
    /// # }
    /// ```
    pub fn as_number_str(self) -> Result<&'text str, JsonParseError> {
        self.expect([JsonValueKind::Integer, JsonValueKind::Float])
            .map(|v| v.as_raw_str())
    }

    /// Similar to [`RawJsonValue::as_raw_str()`],
    /// but this method verifies whether the value is a JSON string and returns
    /// the unquoted content only if the string doesn't require unescaping.
    ///
    /// Returns the unquoted string content as a borrowed `&'text str` if the value
    /// is a JSON string without escape sequences. If the string contains any escape
    /// sequences (like `\n`, `\t`, `\"`, etc.), this method returns an error instead
    /// of performing the unescaping.
    ///
    /// For strings that may require unescaping, use [`RawJsonValue::to_unquoted_string_str()`] instead.
    ///
    /// This is useful when you want to work directly with the original string content
    /// without the overhead of unescaping or allocation.
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> Result<(), nojson::JsonParseError> {
    /// // Simple string without escapes - succeeds
    /// let json = nojson::RawJson::parse(r#""hello""#)?;
    /// assert_eq!(json.value().as_string_str()?, "hello");
    ///
    /// // String with escape sequences - fails
    /// let json = nojson::RawJson::parse(r#""hello\nworld""#)?;
    /// assert!(json.value().as_string_str().is_err());
    ///
    /// // String with unicode escapes - fails
    /// let json = nojson::RawJson::parse(r#""hello\u0041""#)?;
    /// assert!(json.value().as_string_str().is_err());
    ///
    /// // Non-string value - fails
    /// let json = nojson::RawJson::parse("123")?;
    /// assert!(json.value().as_string_str().is_err());
    /// # Ok(())
    /// # }
    /// ```
    pub fn as_string_str(self) -> Result<&'text str, JsonParseError> {
        self.expect([JsonValueKind::String]).and_then(|v| {
            if v.entry().escaped {
                Err(v.invalid("string requires unescaping"))
            } else {
                // Safe to unwrap: we know it's a valid JSON string with quotes
                let raw = v.as_raw_str();
                Ok(&raw[1..raw.len() - 1])
            }
        })
    }

    /// Similar to [`RawJsonValue::as_raw_str()`],
    /// but this method verifies whether the value is a JSON string and returns the unquoted content of the string.
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> Result<(), nojson::JsonParseError> {
    /// let json = nojson::RawJson::parse("\"123\"")?;
    /// assert_eq!(json.value().to_unquoted_string_str()?, "123");
    /// assert_eq!(json.value().to_unquoted_string_str()?.parse(), Ok(123));
    ///
    /// let json = nojson::RawJson::parse("123")?;
    /// assert!(json.value().to_unquoted_string_str().is_err());
    /// # Ok(())
    /// # }
    /// ```
    pub fn to_unquoted_string_str(self) -> Result<Cow<'text, str>, JsonParseError> {
        self.expect([JsonValueKind::String]).map(|v| v.unquote())
    }

    /// If the value is a JSON array,
    /// this method returns an iterator that iterates over the array's elements.
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> Result<(), nojson::JsonParseError> {
    /// let json = nojson::RawJson::parse("[0, 1, 2]")?;
    /// for (i, v) in json.value().to_array()?.enumerate() {
    ///     assert_eq!(v.as_integer_str()?.parse(), Ok(i));
    /// }
    ///
    /// let json = nojson::RawJson::parse("null")?;
    /// assert!(json.value().to_array().is_err());
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Note
    ///
    /// For converting to a fixed-size array, you can use the `TryInto` trait instead:
    /// ```
    /// # fn main() -> Result<(), nojson::JsonParseError> {
    /// let json = nojson::RawJson::parse("[0, 1, 2]")?;
    /// let fixed_array: [usize; 3] = json.value().try_into()?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn to_array(self) -> Result<impl Iterator<Item = Self>, JsonParseError> {
        self.expect([JsonValueKind::Array]).map(Children::new)
    }

    /// If the value is a JSON object,
    /// this method returns an iterator that iterates over
    /// the name and value pairs of the object's members.
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> Result<(), nojson::JsonParseError> {
    /// let json = nojson::RawJson::parse(r#"{"a": 1, "b": 2, "c": 3}"#)?;
    /// let mut members = json.value().to_object()?;
    /// let (k, v) = members.next().expect("some");
    /// assert_eq!(k.to_unquoted_string_str()?, "a");
    /// assert_eq!(v.as_integer_str()?.parse(), Ok(1));
    ///
    /// let json = nojson::RawJson::parse("null")?;
    /// assert!(json.value().to_object().is_err());
    /// # Ok(())
    /// # }
    /// ```
    pub fn to_object(self) -> Result<impl Iterator<Item = (Self, Self)>, JsonParseError> {
        self.expect([JsonValueKind::Object])
            .map(JsonKeyValuePairs::new)
    }

    /// Attempts to access a member of a JSON object by name.
    ///
    /// The returned [`RawJsonMember`] lets you handle both required and optional
    /// access with [`RawJsonMember::required()`] and [`RawJsonMember::optional()`].
    ///
    /// # Performance
    ///
    /// This method has O(n) complexity where n is the number of members in the object,
    /// as it performs a linear search through all object members to find the requested name.
    /// If you need to access multiple members from the same object, consider using
    /// [`RawJsonValue::to_object()`] and scanning members once.
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> Result<(), nojson::JsonParseError> {
    /// let json = nojson::RawJson::parse(r#"{"name": "Alice", "age": 30}"#)?;
    /// let obj = json.value();
    ///
    /// let name_value: String = obj.to_member("name")?.required()?.try_into()?;
    /// assert_eq!(name_value, "Alice");
    ///
    /// let city = obj.to_member("city")?.optional();
    /// assert_eq!(city, None);
    /// # Ok(())
    /// # }
    /// ```
    pub fn to_member<'a>(
        self,
        name: &'a str,
    ) -> Result<RawJsonMember<'text, 'raw, 'a>, JsonParseError> {
        let member = self.find_member_by_name(name)?;

        Ok(RawJsonMember {
            object: self,
            name,
            member,
        })
    }

    /// Attempts to access a nested member in a JSON object by a path of member names.
    ///
    /// All intermediate members in `path` are treated as required object members.
    /// The final member is returned as [`RawJsonMember`], so you can choose required
    /// or optional handling with [`RawJsonMember::required()`] or
    /// [`RawJsonMember::optional()`].
    ///
    /// # Performance
    ///
    /// This method is a convenience API. When you access multiple nested members
    /// under the same parent, each call starts from `self` and repeats intermediate
    /// lookups. For performance-critical paths, prefer resolving the parent once
    /// and then using [`RawJsonValue::to_member()`] for sibling fields.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - `path` is empty,
    /// - an intermediate member is missing,
    /// - an intermediate value is not an object.
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> Result<(), nojson::JsonParseError> {
    /// let json = nojson::RawJson::parse(r#"{"user": {"profile": {"name": "Alice"}}}"#)?;
    ///
    /// let name: String = json
    ///     .value()
    ///     .to_path_member(&["user", "profile", "name"])?
    ///     .required()?
    ///     .try_into()?;
    /// assert_eq!(name, "Alice");
    ///
    /// let city = json
    ///     .value()
    ///     .to_path_member(&["user", "profile", "city"])?
    ///     .optional();
    /// assert_eq!(city, None);
    /// # Ok(())
    /// # }
    /// ```
    pub fn to_path_member<'a>(
        self,
        path: &'a [&str],
    ) -> Result<RawJsonMember<'text, 'raw, 'a>, JsonParseError> {
        let (last, parents) = path
            .split_last()
            .ok_or_else(|| self.invalid("path must not be empty"))?;

        let mut current = self;
        for name in parents {
            current = current.to_member(name)?.required()?;
        }

        current.to_member(last)
    }

    /// Applies a transformation function to this JSON value.
    ///
    /// This method allows you to transform a `RawJsonValue` into any other type `T`
    /// using a closure that can potentially fail with a `JsonParseError`. It's particularly
    /// useful for chaining operations or applying custom parsing logic.
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> Result<(), nojson::JsonParseError> {
    /// let json = nojson::RawJson::parse("\"42\"")?;
    ///
    /// // Transform a string value to an integer
    /// let number: i32 = json.value().map(|v| {
    ///     v.to_unquoted_string_str()?.parse().map_err(|e| v.invalid(e))
    /// })?;
    /// assert_eq!(number, 42);
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// This method is equivalent to directly calling the function with the value,
    /// but provides a more functional programming style for chaining operations.
    pub fn map<F, T>(self, f: F) -> Result<T, JsonParseError>
    where
        F: FnOnce(RawJsonValue<'text, 'raw>) -> Result<T, JsonParseError>,
    {
        f(self)
    }

    /// Creates a [`JsonParseError::InvalidValue`] error for this value.
    ///
    /// This is a convenience method that's equivalent to calling
    /// [`JsonParseError::invalid_value()`] with this value.
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> Result<(), nojson::JsonParseError> {
    /// let json = nojson::RawJson::parse("\"not_a_number\"")?;
    /// let value = json.value();
    ///
    /// // These are equivalent:
    /// let error1 = value.invalid("expected a number");
    /// let error2 = nojson::JsonParseError::invalid_value(value, "expected a number");
    /// # Ok(())
    /// # }
    /// ```
    pub fn invalid<E>(self, error: E) -> JsonParseError
    where
        E: Into<Box<dyn Send + Sync + core::error::Error>>,
    {
        JsonParseError::invalid_value(self, error)
    }

    fn unquote(self) -> Cow<'text, str> {
        debug_assert!(self.kind().is_string());

        let content = &self.as_raw_str()[1..self.as_raw_str().len() - 1];
        if !self.entry().escaped {
            return Cow::Borrowed(content);
        }

        let mut unescaped = String::with_capacity(content.len());
        let mut chars = content.chars();
        while let Some(c) = chars.next() {
            match c {
                '\\' => {
                    let c = chars.next().expect("infallible");
                    match c {
                        '\\' | '/' | '"' => unescaped.push(c),
                        'n' => unescaped.push('\n'),
                        't' => unescaped.push('\t'),
                        'r' => unescaped.push('\r'),
                        'b' => unescaped.push('\u{8}'),
                        'f' => unescaped.push('\u{c}'),
                        'u' => {
                            let c = core::str::from_utf8(&[
                                chars.next().expect("infallible") as u8,
                                chars.next().expect("infallible") as u8,
                                chars.next().expect("infallible") as u8,
                                chars.next().expect("infallible") as u8,
                            ])
                            .ok()
                            .and_then(|code| u32::from_str_radix(code, 16).ok())
                            .and_then(char::from_u32)
                            .expect("infallible");
                            unescaped.push(c);
                        }
                        _ => unreachable!(),
                    }
                }
                _ => unescaped.push(c),
            }
        }
        Cow::Owned(unescaped)
    }

    fn expect<const N: usize>(self, kinds: [JsonValueKind; N]) -> Result<Self, JsonParseError> {
        if kinds.contains(&self.kind()) {
            Ok(self)
        } else {
            Err(self.invalid(format!(
                "expected {}, but found {:?}",
                if kinds.len() == 1 {
                    format!("{:?}", kinds[0])
                } else {
                    format!("one of {kinds:?}")
                },
                self.kind()
            )))
        }
    }

    fn find_member_by_name(self, name: &str) -> Result<Option<Self>, JsonParseError> {
        Ok(self
            .to_object()?
            .find_map(|(k, v)| (k.unquote() == name).then_some(v)))
    }

    fn entry(&self) -> &JsonValueIndexEntry {
        &self.json.values[self.index]
    }
}

impl Display for RawJsonValue<'_, '_> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "{}", crate::Json(self))
    }
}

impl DisplayJson for RawJsonValue<'_, '_> {
    fn fmt(&self, f: &mut JsonFormatter<'_, '_>) -> core::fmt::Result {
        match self.kind() {
            JsonValueKind::Null
            | JsonValueKind::Boolean
            | JsonValueKind::Integer
            | JsonValueKind::Float => write!(f.inner_mut(), "{}", self.as_raw_str()),
            JsonValueKind::String => f.string(self.unquote()),
            JsonValueKind::Array => f.array(|f| f.elements(self.to_array().expect("infallible"))),
            JsonValueKind::Object => f.object(|f| {
                f.members(
                    self.to_object()
                        .expect("infallible")
                        .map(|(k, v)| (k.unquote(), v)),
                )
            }),
        }
    }
}

#[derive(Debug)]
struct Children<'text, 'raw> {
    value: RawJsonValue<'text, 'raw>,
    end_index: usize,
}

impl<'text, 'raw> Children<'text, 'raw> {
    fn new(mut value: RawJsonValue<'text, 'raw>) -> Self {
        let end_index = value.entry().end_index;
        value.index += 1;
        Self { value, end_index }
    }
}

impl<'text, 'raw> Iterator for Children<'text, 'raw> {
    type Item = RawJsonValue<'text, 'raw>;

    fn next(&mut self) -> Option<Self::Item> {
        if self.value.index == self.end_index {
            return None;
        }
        let value = self.value;
        self.value.index = value.entry().end_index;
        Some(value)
    }
}

#[derive(Debug)]
struct JsonKeyValuePairs<'text, 'raw> {
    inner: Children<'text, 'raw>,
}

impl<'text, 'raw> JsonKeyValuePairs<'text, 'raw> {
    fn new(object: RawJsonValue<'text, 'raw>) -> Self {
        Self {
            inner: Children::new(object),
        }
    }
}

impl<'text, 'raw> Iterator for JsonKeyValuePairs<'text, 'raw> {
    type Item = (RawJsonValue<'text, 'raw>, RawJsonValue<'text, 'raw>);

    fn next(&mut self) -> Option<Self::Item> {
        let key = self.inner.next()?;
        let value = self.inner.next().expect("infallible");
        Some((key, value))
    }
}

/// Represents a member access result for a JSON object.
///
/// This struct is returned by [`RawJsonValue::to_member()`] and allows you to handle
/// both present and missing object members. It wraps an optional value that is
/// `Some` if the member exists and `None` if it doesn't.
///
/// # Examples
///
/// ```
/// # fn main() -> Result<(), nojson::JsonParseError> {
/// let json = nojson::RawJson::parse(r#"{"name": "Alice", "age": 30}"#)?;
/// let obj = json.value();
///
/// // Access an existing member
/// let name_member = obj.to_member("name")?;
/// let name: String = name_member.required()?.try_into()?;
/// assert_eq!(name, "Alice");
///
/// // Access a missing member
/// let city_member = obj.to_member("city")?;
/// let city: Option<String> = city_member.try_into()?;
/// assert_eq!(city, None);
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct RawJsonMember<'text, 'raw, 'a> {
    object: RawJsonValue<'text, 'raw>,
    name: &'a str,
    member: Option<RawJsonValue<'text, 'raw>>,
}

impl<'text, 'raw, 'a> RawJsonMember<'text, 'raw, 'a> {
    /// Returns the member value if it exists, or an error if it's missing.
    ///
    /// This method is useful when you need to ensure that a required member
    /// is present in the JSON object.
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> Result<(), nojson::JsonParseError> {
    /// let json = nojson::RawJson::parse(r#"{"name": "Alice"}"#)?;
    /// let obj = json.value();
    ///
    /// // Required member exists
    /// let name = obj.to_member("name")?.required()?;
    /// assert_eq!(name.to_unquoted_string_str()?, "Alice");
    ///
    /// // Required member missing - returns error
    /// let age_result = obj.to_member("age")?.required();
    /// assert!(age_result.is_err());
    /// # Ok(())
    /// # }
    /// ```
    pub fn required(self) -> Result<RawJsonValue<'text, 'raw>, JsonParseError> {
        self.member.ok_or_else(|| {
            self.object
                .invalid(format!("required member '{}' is missing", self.name))
        })
    }

    /// Returns the inner raw JSON value as an `Option`.
    ///
    /// This method provides direct access to the underlying `Option<RawJsonValue>`,
    /// allowing you to handle the presence or absence of the member yourself.
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> Result<(), nojson::JsonParseError> {
    /// let json = nojson::RawJson::parse(r#"{"name": "Alice", "age": 30}"#)?;
    /// let obj = json.value();
    ///
    /// // Existing member
    /// let name_member = obj.to_member("name")?;
    /// if let Some(name_value) = name_member.optional() {
    ///     assert_eq!(name_value.to_unquoted_string_str()?, "Alice");
    /// }
    ///
    /// // Missing member
    /// let city_member = obj.to_member("city")?;
    /// assert!(city_member.optional().is_none());
    ///
    /// // Using with pattern matching
    /// match obj.to_member("age")?.optional() {
    ///     Some(age_value) => {
    ///         let age: i32 = age_value.as_integer_str()?.parse()
    ///             .map_err(|e| age_value.invalid(e))?;
    ///         assert_eq!(age, 30);
    ///     }
    ///     None => println!("Age not provided"),
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub fn optional(self) -> Option<RawJsonValue<'text, 'raw>> {
        self.member
    }

    /// Returns the inner raw JSON value as an `Option`.
    ///
    /// Deprecated: use [`RawJsonMember::optional()`] instead.
    #[deprecated(note = "use RawJsonMember::optional() instead")]
    pub fn get(self) -> Option<RawJsonValue<'text, 'raw>> {
        self.optional()
    }

    /// Applies a transformation function to the member value if it exists.
    ///
    /// This method is similar to [`Option::map`], but designed for transformations
    /// that can fail with a [`JsonParseError`]. If the member exists, the function
    /// is applied to its value. If the member doesn't exist, `Ok(None)` is returned.
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> Result<(), nojson::JsonParseError> {
    /// let json = nojson::RawJson::parse(r#"{"name": "Alice", "age": "30"}"#)?;
    /// let obj = json.value();
    ///
    /// // Transform existing member
    /// let age_member = obj.to_member("age")?;
    /// let age: Option<i32> = age_member.map(|v| {
    ///     v.to_unquoted_string_str()?.parse().map_err(|e| v.invalid(e))
    /// })?;
    /// assert_eq!(age, Some(30));
    ///
    /// // Transform missing member
    /// let city_member = obj.to_member("city")?;
    /// let city: Option<String> = city_member.map(|v| v.try_into())?;
    /// assert_eq!(city, None);
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// This is particularly useful when you need to perform parsing or validation
    /// on optional members without having to handle the `Option` separately:
    ///
    /// ```
    /// # fn main() -> Result<(), nojson::JsonParseError> {
    /// let json = nojson::RawJson::parse(r#"{"score": "95.5"}"#)?;
    /// let obj = json.value();
    ///
    /// // Parse optional numeric string
    /// let score: Option<f64> = obj.to_member("score")?.map(|v| {
    ///     v.to_unquoted_string_str()?.parse().map_err(|e| v.invalid(e))
    /// })?;
    /// assert_eq!(score, Some(95.5));
    /// # Ok(())
    /// # }
    /// ```
    pub fn map<F, T>(self, f: F) -> Result<Option<T>, JsonParseError>
    where
        F: FnOnce(RawJsonValue<'text, 'raw>) -> Result<T, JsonParseError>,
    {
        self.member.map(f).transpose()
    }
}

impl<'text, 'raw, 'a, T> TryFrom<RawJsonMember<'text, 'raw, 'a>> for Option<T>
where
    T: TryFrom<RawJsonValue<'text, 'raw>, Error = JsonParseError>,
{
    type Error = JsonParseError;

    fn try_from(value: RawJsonMember<'text, 'raw, 'a>) -> Result<Self, Self::Error> {
        value.member.map(T::try_from).transpose()
    }
}