jsonx-lib 0.5.2

Strict RFC 8259 JSON: a borrowing parser, a pull reader, and a deterministic writer, with budgets checked before allocation and no recursion. No dependencies, no_std.
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
//! The document model.

use alloc::{
    borrow::Cow,
    string::{String, ToString},
    vec::Vec,
};
use core::{
    fmt,
    hash::{Hash, Hasher},
    ops::Index,
};

use crate::{Array, Number, Object, tree};

/// The `null` that indexing returns for a missing member or item.
pub(crate) static NULL: Value<'static> = Value::Null;

/// A JSON value, borrowing from the text it was parsed from.
///
/// Strings without escape sequences borrow their bytes from the input
/// (`Cow::Borrowed`); only a string that had to be unescaped owns a copy.
/// Numbers keep their exact text (see [`Number`]). Object members keep their
/// document order. The lifetime `'a` is the input's; [`into_owned`](Self::into_owned)
/// detaches a value from it, and a value built in code from `'static` data is
/// a `Value<'static>`.
///
/// Every operation on a `Value` (drop, clone, comparison, writing) uses a
/// bounded amount of stack whatever the depth, so a value of any depth is safe
/// to use.
///
/// Equality is structural and exact: numbers compare by text (`1` and `1.0`
/// differ), and object members compare in order. A `Value` also compares
/// directly with Rust strings, booleans, and numbers, which is what
/// `assert_eq!(doc["id"], 7)` uses.
///
/// # Examples
///
/// ```
/// use jsonx_lib::{parse, Value};
///
/// let doc = parse(r#"{"user": {"name": "ada", "langs": ["en", "fr"]}, "admin": false}"#)?;
///
/// // Index freely: a missing member or item reads as `null`.
/// assert_eq!(doc["user"]["name"], "ada");
/// assert_eq!(doc["user"]["langs"][1], "fr");
/// assert!(doc["nope"][3].is_null());
///
/// // Or ask with typed accessors that say whether the shape matched.
/// assert_eq!(doc["admin"].as_bool(), Some(false));
/// assert_eq!(doc.pointer("/user/langs/0").and_then(Value::as_str), Some("en"));
/// # Ok::<(), jsonx_lib::Error>(())
/// ```
#[derive(Default)]
pub enum Value<'a> {
    /// `null`.
    #[default]
    Null,
    /// `true` or `false`.
    Bool(bool),
    /// A number, kept as its exact text.
    Number(Number<'a>),
    /// A string: borrowed from the input when it had no escapes, owned otherwise.
    String(Cow<'a, str>),
    /// An array.
    Array(Array<'a>),
    /// An object.
    Object(Object<'a>),
}

/// Which of JSON's six kinds of value a [`Value`] is.
///
/// Useful for error messages ("expected a string, found an array").
///
/// # Examples
///
/// ```
/// use jsonx_lib::{parse, Kind};
///
/// let doc = parse("[1]")?;
/// assert_eq!(doc.kind(), Kind::Array);
/// assert_eq!(doc[0].kind().to_string(), "number");
/// # Ok::<(), jsonx_lib::Error>(())
/// ```
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum Kind {
    /// `null`.
    Null,
    /// `true` or `false`.
    Bool,
    /// A number.
    Number,
    /// A string.
    String,
    /// An array.
    Array,
    /// An object.
    Object,
}

impl Kind {
    /// The kind's name in lowercase: `null`, `boolean`, `number`, `string`,
    /// `array`, or `object`.
    ///
    /// # Examples
    ///
    /// ```
    /// assert_eq!(jsonx_lib::Kind::Bool.name(), "boolean");
    /// ```
    #[must_use]
    pub const fn name(self) -> &'static str {
        match self {
            Self::Null => "null",
            Self::Bool => "boolean",
            Self::Number => "number",
            Self::String => "string",
            Self::Array => "array",
            Self::Object => "object",
        }
    }
}

impl fmt::Display for Kind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.name())
    }
}

impl<'a> Value<'a> {
    /// Which kind of value this is.
    ///
    /// # Examples
    ///
    /// ```
    /// use jsonx_lib::{json, Kind};
    ///
    /// assert_eq!(json!({}).kind(), Kind::Object);
    /// ```
    #[must_use]
    pub const fn kind(&self) -> Kind {
        match self {
            Self::Null => Kind::Null,
            Self::Bool(_) => Kind::Bool,
            Self::Number(_) => Kind::Number,
            Self::String(_) => Kind::String,
            Self::Array(_) => Kind::Array,
            Self::Object(_) => Kind::Object,
        }
    }

    /// Whether the value is `null`.
    ///
    /// # Examples
    ///
    /// ```
    /// assert!(jsonx_lib::parse("null")?.is_null());
    /// # Ok::<(), jsonx_lib::Error>(())
    /// ```
    #[inline]
    #[must_use]
    pub const fn is_null(&self) -> bool {
        matches!(self, Self::Null)
    }

    /// Whether the value is `true` or `false`.
    ///
    /// # Examples
    ///
    /// ```
    /// assert!(jsonx_lib::json!(false).is_bool());
    /// ```
    #[inline]
    #[must_use]
    pub const fn is_bool(&self) -> bool {
        matches!(self, Self::Bool(_))
    }

    /// Whether the value is a number.
    ///
    /// # Examples
    ///
    /// ```
    /// assert!(jsonx_lib::json!(1.5).is_number());
    /// ```
    #[inline]
    #[must_use]
    pub const fn is_number(&self) -> bool {
        matches!(self, Self::Number(_))
    }

    /// Whether the value is a string.
    ///
    /// # Examples
    ///
    /// ```
    /// assert!(jsonx_lib::json!("s").is_string());
    /// ```
    #[inline]
    #[must_use]
    pub const fn is_string(&self) -> bool {
        matches!(self, Self::String(_))
    }

    /// Whether the value is an array.
    ///
    /// # Examples
    ///
    /// ```
    /// assert!(jsonx_lib::json!([]).is_array());
    /// ```
    #[inline]
    #[must_use]
    pub const fn is_array(&self) -> bool {
        matches!(self, Self::Array(_))
    }

    /// Whether the value is an object.
    ///
    /// # Examples
    ///
    /// ```
    /// assert!(jsonx_lib::json!({}).is_object());
    /// ```
    #[inline]
    #[must_use]
    pub const fn is_object(&self) -> bool {
        matches!(self, Self::Object(_))
    }

    /// The boolean, if the value is one.
    ///
    /// # Examples
    ///
    /// ```
    /// assert_eq!(jsonx_lib::parse("true")?.as_bool(), Some(true));
    /// assert_eq!(jsonx_lib::parse("1")?.as_bool(), None);
    /// # Ok::<(), jsonx_lib::Error>(())
    /// ```
    #[inline]
    #[must_use]
    pub const fn as_bool(&self) -> Option<bool> {
        match self {
            Self::Bool(b) => Some(*b),
            _ => None,
        }
    }

    /// The number, if the value is one.
    ///
    /// # Examples
    ///
    /// ```
    /// let doc = jsonx_lib::parse("6.02e23")?;
    /// assert_eq!(doc.as_number().map(|n| n.as_str()), Some("6.02e23"));
    /// # Ok::<(), jsonx_lib::Error>(())
    /// ```
    #[inline]
    #[must_use]
    pub const fn as_number(&self) -> Option<&Number<'a>> {
        match self {
            Self::Number(n) => Some(n),
            _ => None,
        }
    }

    /// The value as an `i64`: see [`Number::as_i64`]. `None` for anything but
    /// an integer number in range.
    ///
    /// # Examples
    ///
    /// ```
    /// let doc = jsonx_lib::parse("[-5, 5.5, \"5\"]")?;
    /// assert_eq!(doc[0].as_i64(), Some(-5));
    /// assert_eq!(doc[1].as_i64(), None);
    /// assert_eq!(doc[2].as_i64(), None);
    /// # Ok::<(), jsonx_lib::Error>(())
    /// ```
    #[must_use]
    pub fn as_i64(&self) -> Option<i64> {
        self.as_number().and_then(Number::as_i64)
    }

    /// The value as a `u64`: see [`Number::as_u64`].
    ///
    /// # Examples
    ///
    /// ```
    /// assert_eq!(jsonx_lib::parse("42")?.as_u64(), Some(42));
    /// assert_eq!(jsonx_lib::parse("-42")?.as_u64(), None);
    /// # Ok::<(), jsonx_lib::Error>(())
    /// ```
    #[must_use]
    pub fn as_u64(&self) -> Option<u64> {
        self.as_number().and_then(Number::as_u64)
    }

    /// The value as an `i128`: see [`Number::as_i128`].
    ///
    /// # Examples
    ///
    /// ```
    /// let doc = jsonx_lib::parse("-170141183460469231731687303715884105728")?;
    /// assert_eq!(doc.as_i128(), Some(i128::MIN));
    /// # Ok::<(), jsonx_lib::Error>(())
    /// ```
    #[must_use]
    pub fn as_i128(&self) -> Option<i128> {
        self.as_number().and_then(Number::as_i128)
    }

    /// The value as a `u128`: see [`Number::as_u128`].
    ///
    /// # Examples
    ///
    /// ```
    /// let doc = jsonx_lib::parse("340282366920938463463374607431768211455")?;
    /// assert_eq!(doc.as_u128(), Some(u128::MAX));
    /// # Ok::<(), jsonx_lib::Error>(())
    /// ```
    #[must_use]
    pub fn as_u128(&self) -> Option<u128> {
        self.as_number().and_then(Number::as_u128)
    }

    /// The value as an `f64`: see [`Number::as_f64`]. Integers convert too.
    ///
    /// # Examples
    ///
    /// ```
    /// assert_eq!(jsonx_lib::parse("2")?.as_f64(), Some(2.0));
    /// assert_eq!(jsonx_lib::parse("\"2\"")?.as_f64(), None);
    /// # Ok::<(), jsonx_lib::Error>(())
    /// ```
    #[must_use]
    pub fn as_f64(&self) -> Option<f64> {
        self.as_number().and_then(Number::as_f64)
    }

    /// The string, if the value is one.
    ///
    /// # Examples
    ///
    /// ```
    /// assert_eq!(jsonx_lib::parse(r#""a\tb""#)?.as_str(), Some("a\tb"));
    /// # Ok::<(), jsonx_lib::Error>(())
    /// ```
    #[inline]
    #[must_use]
    pub fn as_str(&self) -> Option<&str> {
        match self {
            Self::String(s) => Some(s),
            _ => None,
        }
    }

    /// The array, if the value is one.
    ///
    /// # Examples
    ///
    /// ```
    /// let doc = jsonx_lib::parse("[1, 2, 3]")?;
    /// assert_eq!(doc.as_array().map(|a| a.len()), Some(3));
    /// # Ok::<(), jsonx_lib::Error>(())
    /// ```
    #[inline]
    #[must_use]
    pub const fn as_array(&self) -> Option<&Array<'a>> {
        match self {
            Self::Array(a) => Some(a),
            _ => None,
        }
    }

    /// The array, mutably, if the value is one.
    ///
    /// # Examples
    ///
    /// ```
    /// let mut v = jsonx_lib::json!([1]);
    /// v.as_array_mut().unwrap().push(2.into());
    /// assert_eq!(v.to_string(), "[1,2]");
    /// ```
    #[inline]
    #[must_use]
    pub fn as_array_mut(&mut self) -> Option<&mut Array<'a>> {
        match self {
            Self::Array(a) => Some(a),
            _ => None,
        }
    }

    /// The object, if the value is one.
    ///
    /// # Examples
    ///
    /// ```
    /// let doc = jsonx_lib::parse(r#"{"k": 1}"#)?;
    /// assert!(doc.as_object().is_some_and(|o| o.contains_key("k")));
    /// # Ok::<(), jsonx_lib::Error>(())
    /// ```
    #[inline]
    #[must_use]
    pub const fn as_object(&self) -> Option<&Object<'a>> {
        match self {
            Self::Object(o) => Some(o),
            _ => None,
        }
    }

    /// The object, mutably, if the value is one.
    ///
    /// # Examples
    ///
    /// ```
    /// let mut v = jsonx_lib::json!({});
    /// v.as_object_mut().unwrap().insert("k", "v");
    /// assert_eq!(v.to_string(), r#"{"k":"v"}"#);
    /// ```
    #[inline]
    #[must_use]
    pub fn as_object_mut(&mut self) -> Option<&mut Object<'a>> {
        match self {
            Self::Object(o) => Some(o),
            _ => None,
        }
    }

    /// The value of the member named `key`, if this is an object that has one.
    ///
    /// # Examples
    ///
    /// ```
    /// let doc = jsonx_lib::parse(r#"{"jsonrpc": "2.0", "id": 1}"#)?;
    /// assert_eq!(doc.get("jsonrpc").and_then(|v| v.as_str()), Some("2.0"));
    /// assert!(doc.get("method").is_none());
    /// # Ok::<(), jsonx_lib::Error>(())
    /// ```
    #[must_use]
    pub fn get(&self, key: &str) -> Option<&Value<'a>> {
        self.as_object().and_then(|o| o.get(key))
    }

    /// A mutable reference to the member named `key`, if this is an object
    /// that has one.
    ///
    /// # Examples
    ///
    /// ```
    /// let mut v = jsonx_lib::json!({ "n": 1 });
    /// if let Some(n) = v.get_mut("n") {
    ///     *n = 2.into();
    /// }
    /// assert_eq!(v["n"], 2);
    /// ```
    #[must_use]
    pub fn get_mut(&mut self, key: &str) -> Option<&mut Value<'a>> {
        self.as_object_mut().and_then(|o| o.get_mut(key))
    }

    /// The item at `index`, if this is an array that long.
    ///
    /// # Examples
    ///
    /// ```
    /// let doc = jsonx_lib::parse("[10, 20]")?;
    /// assert_eq!(doc.get_index(1).and_then(|v| v.as_i64()), Some(20));
    /// assert!(doc.get_index(2).is_none());
    /// # Ok::<(), jsonx_lib::Error>(())
    /// ```
    #[must_use]
    pub fn get_index(&self, index: usize) -> Option<&Value<'a>> {
        self.as_array().and_then(|a| a.get(index))
    }

    /// Looks a value up by [RFC 6901](https://www.rfc-editor.org/rfc/rfc6901)
    /// JSON Pointer: `""` is the whole value, `/a/0` is item 0 of member `a`,
    /// and `~1` and `~0` stand for `/` and `~` inside a key.
    ///
    /// Returns `None` when the pointer is malformed (it does not start with
    /// `/`, or has a `~` not followed by `0` or `1`) or names something that
    /// is not there. An array index must be a plain decimal number without
    /// leading zeros; `-` (past the end) never resolves.
    ///
    /// # Examples
    ///
    /// ```
    /// let doc = jsonx_lib::parse(r#"{"a/b": {"c~d": [true]}}"#)?;
    /// assert_eq!(doc.pointer("/a~1b/c~0d/0"), Some(&true.into()));
    /// assert_eq!(doc.pointer(""), Some(&doc));
    /// assert!(doc.pointer("/a~1b/c~0d/01").is_none());
    /// assert!(doc.pointer("a").is_none());
    /// # Ok::<(), jsonx_lib::Error>(())
    /// ```
    #[must_use]
    pub fn pointer(&self, pointer: &str) -> Option<&Value<'a>> {
        if pointer.is_empty() {
            return Some(self);
        }
        let rest = pointer.strip_prefix('/')?;
        let mut target = self;
        for token in rest.split('/') {
            let token = unescape_pointer_token(token)?;
            target = match target {
                Self::Object(o) => o.get(&token)?,
                Self::Array(a) => a.get(array_index(&token)?)?,
                _ => return None,
            };
        }
        Some(target)
    }

    /// A mutable reference to the value at a JSON Pointer, as
    /// [`pointer`](Self::pointer) finds it.
    ///
    /// # Examples
    ///
    /// ```
    /// let mut v = jsonx_lib::json!({ "a": [1, 2] });
    /// if let Some(item) = v.pointer_mut("/a/1") {
    ///     *item = "two".into();
    /// }
    /// assert_eq!(v.to_string(), r#"{"a":[1,"two"]}"#);
    /// assert!(v.pointer_mut("/a/9").is_none());
    /// ```
    #[must_use]
    pub fn pointer_mut(&mut self, pointer: &str) -> Option<&mut Value<'a>> {
        if pointer.is_empty() {
            return Some(self);
        }
        let rest = pointer.strip_prefix('/')?;
        let mut target = self;
        for token in rest.split('/') {
            let token = unescape_pointer_token(token)?;
            target = match target {
                Self::Object(o) => o.get_mut(&token)?,
                Self::Array(a) => a.get_mut(array_index(&token)?)?,
                _ => return None,
            };
        }
        Some(target)
    }

    /// Takes the value out, leaving `null` in its place.
    ///
    /// # Examples
    ///
    /// ```
    /// let mut v = jsonx_lib::json!({ "big": [1, 2, 3] });
    /// let big = v.get_mut("big").map(|b| b.take()).unwrap_or_default();
    /// assert_eq!(big.to_string(), "[1,2,3]");
    /// assert!(v["big"].is_null());
    /// ```
    #[inline]
    pub fn take(&mut self) -> Value<'a> {
        core::mem::take(self)
    }

    /// Copies every borrowed key, string, and number so the value no longer
    /// borrows from the input. Iterative at any depth.
    ///
    /// # Examples
    ///
    /// ```
    /// use jsonx_lib::{parse, Value};
    ///
    /// fn load() -> Result<Value<'static>, jsonx_lib::Error> {
    ///     let text = String::from(r#"{"kept": "after the text is gone"}"#);
    ///     Ok(parse(&text)?.into_owned())
    /// }
    /// assert_eq!(load()?["kept"], "after the text is gone");
    /// # Ok::<(), jsonx_lib::Error>(())
    /// ```
    #[must_use]
    pub fn into_owned(self) -> Value<'static> {
        tree::into_owned(self)
    }
}

/// Decodes `~1` and `~0` in one JSON Pointer reference token.
pub(crate) fn unescape_pointer_token(token: &str) -> Option<Cow<'_, str>> {
    if !token.contains('~') {
        return Some(Cow::Borrowed(token));
    }
    let mut out = String::with_capacity(token.len());
    let mut chars = token.chars();
    while let Some(c) = chars.next() {
        if c == '~' {
            match chars.next() {
                Some('0') => out.push('~'),
                Some('1') => out.push('/'),
                _ => return None,
            }
        } else {
            out.push(c);
        }
    }
    Some(Cow::Owned(out))
}

/// An RFC 6901 array index: `0`, or a decimal without a leading zero.
pub(crate) fn array_index(token: &str) -> Option<usize> {
    let digits = token.as_bytes();
    let canonical = !digits.is_empty()
        && digits.iter().all(u8::is_ascii_digit)
        && (digits.len() == 1 || digits.first() != Some(&b'0'));
    if canonical { token.parse().ok() } else { None }
}

impl Clone for Value<'_> {
    fn clone(&self) -> Self {
        match self {
            Self::Null => Self::Null,
            Self::Bool(b) => Self::Bool(*b),
            Self::Number(n) => Self::Number(n.clone()),
            Self::String(s) => Self::String(s.clone()),
            Self::Array(a) => Self::Array(a.clone()),
            Self::Object(o) => Self::Object(o.clone()),
        }
    }
}

impl PartialEq for Value<'_> {
    fn eq(&self, other: &Self) -> bool {
        tree::eq(self, other)
    }
}

impl Eq for Value<'_> {}

impl Hash for Value<'_> {
    /// Hashes consistently with `==`: numbers by their text, object members
    /// in order. Iterative at any depth.
    fn hash<H: Hasher>(&self, state: &mut H) {
        tree::hash(self, state);
    }
}

impl<'a> Index<&str> for Value<'a> {
    type Output = Value<'a>;

    /// The member named `key`, or `null` if this is not an object or has no
    /// such member. Never panics.
    fn index(&self, key: &str) -> &Value<'a> {
        self.get(key).unwrap_or(&NULL)
    }
}

impl<'a> Index<usize> for Value<'a> {
    type Output = Value<'a>;

    /// The item at `index`, or `null` if this is not an array or is shorter.
    /// Never panics.
    fn index(&self, index: usize) -> &Value<'a> {
        self.get_index(index).unwrap_or(&NULL)
    }
}

// ---- Conversions into `Value` ------------------------------------------------

impl From<bool> for Value<'_> {
    #[inline]
    fn from(b: bool) -> Self {
        Self::Bool(b)
    }
}

macro_rules! from_integer {
    ($($t:ty),*) => {$(
        impl From<$t> for Value<'_> {
            #[inline]
            fn from(n: $t) -> Self {
                Self::Number(Number::from(n))
            }
        }
    )*};
}

from_integer!(
    i8, i16, i32, i64, i128, isize, u8, u16, u32, u64, u128, usize
);

impl From<f64> for Value<'_> {
    /// A number in shortest round-trip form (see [`Number::from_f64`]), or
    /// `null` for NaN and the infinities, which JSON cannot represent.
    fn from(x: f64) -> Self {
        Number::from_f64(x).map_or(Self::Null, Self::Number)
    }
}

impl From<f32> for Value<'_> {
    /// The `f32` widened to `f64` (exactly), then as `From<f64>`.
    fn from(x: f32) -> Self {
        Self::from(f64::from(x))
    }
}

impl<'a> From<Number<'a>> for Value<'a> {
    #[inline]
    fn from(n: Number<'a>) -> Self {
        Self::Number(n)
    }
}

impl<'a> From<&'a str> for Value<'a> {
    #[inline]
    fn from(s: &'a str) -> Self {
        Self::String(Cow::Borrowed(s))
    }
}

impl<'a> From<&'a String> for Value<'a> {
    #[inline]
    fn from(s: &'a String) -> Self {
        Self::String(Cow::Borrowed(s))
    }
}

impl From<String> for Value<'_> {
    #[inline]
    fn from(s: String) -> Self {
        Self::String(Cow::Owned(s))
    }
}

impl<'a> From<Cow<'a, str>> for Value<'a> {
    #[inline]
    fn from(s: Cow<'a, str>) -> Self {
        Self::String(s)
    }
}

impl From<char> for Value<'_> {
    #[inline]
    fn from(c: char) -> Self {
        Self::String(Cow::Owned(c.to_string()))
    }
}

impl<'a> From<Array<'a>> for Value<'a> {
    #[inline]
    fn from(a: Array<'a>) -> Self {
        Self::Array(a)
    }
}

impl<'a> From<Object<'a>> for Value<'a> {
    #[inline]
    fn from(o: Object<'a>) -> Self {
        Self::Object(o)
    }
}

impl<'a, T: Into<Value<'a>>> From<Vec<T>> for Value<'a> {
    fn from(items: Vec<T>) -> Self {
        Self::Array(items.into_iter().collect())
    }
}

impl<'a, T: Into<Value<'a>>> From<Option<T>> for Value<'a> {
    /// `None` is `null`.
    fn from(value: Option<T>) -> Self {
        value.map_or(Self::Null, Into::into)
    }
}

impl From<()> for Value<'_> {
    /// `()` is `null`.
    #[inline]
    fn from((): ()) -> Self {
        Self::Null
    }
}

impl<'a, T: Into<Value<'a>>> FromIterator<T> for Value<'a> {
    /// Collects into an array.
    fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
        Self::Array(iter.into_iter().collect())
    }
}

// ---- Comparisons with Rust values --------------------------------------------

impl PartialEq<str> for Value<'_> {
    fn eq(&self, other: &str) -> bool {
        self.as_str() == Some(other)
    }
}

impl PartialEq<&str> for Value<'_> {
    fn eq(&self, other: &&str) -> bool {
        self.as_str() == Some(*other)
    }
}

impl PartialEq<String> for Value<'_> {
    fn eq(&self, other: &String) -> bool {
        self.as_str() == Some(other.as_str())
    }
}

impl PartialEq<bool> for Value<'_> {
    fn eq(&self, other: &bool) -> bool {
        self.as_bool() == Some(*other)
    }
}

impl PartialEq<f32> for Value<'_> {
    /// Compares the number's value, read as an `f32` (see
    /// [`Number::as_f32`]).
    fn eq(&self, other: &f32) -> bool {
        self.as_number().and_then(Number::as_f32) == Some(*other)
    }
}

impl PartialEq<i128> for Value<'_> {
    /// True when the value is an integer number equal to `other`.
    fn eq(&self, other: &i128) -> bool {
        self.as_i128() == Some(*other)
    }
}

impl PartialEq<u128> for Value<'_> {
    /// True when the value is an integer number equal to `other`.
    fn eq(&self, other: &u128) -> bool {
        self.as_u128() == Some(*other)
    }
}

impl PartialEq<f64> for Value<'_> {
    /// Compares the number's value, so `1.0`, `1`, and `1e0` all equal `1.0`.
    fn eq(&self, other: &f64) -> bool {
        self.as_f64() == Some(*other)
    }
}

macro_rules! eq_signed {
    ($($t:ty),*) => {$(
        impl PartialEq<$t> for Value<'_> {
            /// True when the value is an integer number equal to `other`.
            fn eq(&self, other: &$t) -> bool {
                self.as_i64() == Some(i64::from(*other))
            }
        }
    )*};
}

macro_rules! eq_unsigned {
    ($($t:ty),*) => {$(
        impl PartialEq<$t> for Value<'_> {
            /// True when the value is an integer number equal to `other`.
            fn eq(&self, other: &$t) -> bool {
                self.as_u64() == Some(u64::from(*other))
            }
        }
    )*};
}

eq_signed!(i8, i16, i32, i64);
eq_unsigned!(u8, u16, u32, u64);

impl PartialEq<isize> for Value<'_> {
    /// True when the value is an integer number equal to `other`.
    fn eq(&self, other: &isize) -> bool {
        i64::try_from(*other).is_ok_and(|n| self.as_i64() == Some(n))
    }
}

impl PartialEq<usize> for Value<'_> {
    /// True when the value is an integer number equal to `other`.
    fn eq(&self, other: &usize) -> bool {
        u64::try_from(*other).is_ok_and(|n| self.as_u64() == Some(n))
    }
}

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

    #[test]
    fn test_value_is_four_words() {
        assert!(core::mem::size_of::<Value<'_>>() <= 4 * core::mem::size_of::<usize>());
    }

    #[test]
    fn test_pointer_tokens() {
        assert_eq!(array_index("0"), Some(0));
        assert_eq!(array_index("10"), Some(10));
        assert_eq!(array_index("01"), None);
        assert_eq!(array_index("-"), None);
        assert_eq!(array_index(""), None);
        assert_eq!(array_index("+1"), None);
        assert_eq!(unescape_pointer_token("a~1b~0c").as_deref(), Some("a/b~c"));
        assert_eq!(unescape_pointer_token("~2"), None);
        assert_eq!(unescape_pointer_token("~"), None);
    }

    #[test]
    fn test_predicates_wide_integers_and_comparisons() {
        let v = crate::json!([null, true, 1, "s", [], {}]);
        let kinds: alloc::vec::Vec<[bool; 5]> = v
            .as_array()
            .map(|a| {
                a.iter()
                    .map(|x| {
                        [
                            x.is_bool(),
                            x.is_number(),
                            x.is_string(),
                            x.is_array(),
                            x.is_object(),
                        ]
                    })
                    .collect()
            })
            .unwrap_or_default();
        assert_eq!(kinds.iter().filter(|k| k.iter().any(|&b| b)).count(), 5);
        assert!(v[0].is_null() && !v[1].is_null());
        assert_eq!(Value::from(u128::MAX), u128::MAX);
        assert_eq!(Value::from(i128::MIN), i128::MIN);
        assert_ne!(Value::from(1), 2i128);
        assert_eq!(Value::from(0.5), 0.5f32);
        assert_ne!(Value::from("0.5"), 0.5f32);
        assert_eq!(Value::from(-1).as_u128(), None);
    }

    /// FNV-1a, so the test needs nothing from `std`.
    struct Fnv(u64);

    impl Hasher for Fnv {
        fn finish(&self) -> u64 {
            self.0
        }
        fn write(&mut self, bytes: &[u8]) {
            for &b in bytes {
                self.0 = (self.0 ^ u64::from(b)).wrapping_mul(0x0100_0000_01b3);
            }
        }
    }

    #[test]
    fn test_hash_agrees_with_eq() {
        let h = |v: &Value<'_>| {
            let mut state = Fnv(0xcbf2_9ce4_8422_2325);
            v.hash(&mut state);
            state.finish()
        };
        let a = crate::json!({ "k": [1, { "x": "y" }], "m": null });
        let b = crate::parse(r#"{"k":[1,{"x":"y"}],"m":null}"#).unwrap_or_default();
        assert_eq!(a, b);
        assert_eq!(h(&a), h(&b));
        let reordered = crate::parse(r#"{"m":null,"k":[1,{"x":"y"}]}"#).unwrap_or_default();
        assert_ne!(h(&a), h(&reordered));
        assert_ne!(
            h(&Value::from(1)),
            h(&crate::parse("1.0").unwrap_or_default())
        );
        assert_ne!(h(&crate::json!([[]])), h(&crate::json!([[], []])));
        assert_ne!(h(&crate::json!(["a"])), h(&crate::json!({ "a": null })));
    }

    #[test]
    fn test_index_out_of_shape_is_null() {
        let v = Value::from(3);
        assert!(v["k"].is_null());
        assert!(v[0].is_null());
    }
}