jsonbb 0.2.3

A binary representation of json value, optimized for parsing and querying.
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
// Copyright 2023 RisingWave Labs
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use std::fmt;
use std::hash::{Hash, Hasher};

use super::*;
use bytes::Buf;
use serde_json::Number;

/// A reference to a JSON value.
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum ValueRef<'a> {
    // NOTE: Order matters!
    // we follow postgresql's order:
    //  Object > Array > Boolean > Number > String > Null
    /// Represents a JSON null value.
    Null,
    /// Represents a JSON string.
    String(StringRef<'a>),
    /// Represents a JSON number.
    Number(NumberRef<'a>),
    /// Represents a JSON boolean.
    Bool(bool),
    /// Represents a JSON array.
    Array(ArrayRef<'a>),
    /// Represents a JSON object.
    Object(ObjectRef<'a>),
}

impl<'a> ValueRef<'a> {
    /// Creates a `ValueRef` from a byte slice.
    pub fn from_bytes(bytes: &[u8]) -> ValueRef<'_> {
        let entry = Entry::from(&bytes[bytes.len() - 4..]);
        ValueRef::from_slice(bytes, entry)
    }

    /// Returns true if the value is a null. Returns false otherwise.
    pub fn is_null(self) -> bool {
        matches!(self, Self::Null)
    }

    /// Returns true if the value is a boolean. Returns false otherwise.
    pub fn is_boolean(self) -> bool {
        matches!(self, Self::Bool(_))
    }

    /// Returns true if the value is a number. Returns false otherwise.
    pub fn is_number(self) -> bool {
        matches!(self, Self::Number(_))
    }

    /// Returns true if the value is an integer between zero and `u64::MAX`.
    pub fn is_u64(self) -> bool {
        matches!(self, Self::Number(n) if n.is_u64())
    }

    /// Returns true if the value is an integer between `i64::MIN` and `i64::MAX`.
    pub fn is_i64(self) -> bool {
        matches!(self, Self::Number(n) if n.is_i64())
    }

    /// Returns true if the value is a number that can be represented by f64.
    pub fn is_f64(self) -> bool {
        matches!(self, Self::Number(n) if n.is_f64())
    }

    /// Returns true if the value is a string. Returns false otherwise.
    pub fn is_string(self) -> bool {
        matches!(self, Self::String(_))
    }

    /// Returns true if the value is an array. Returns false otherwise.
    pub fn is_array(self) -> bool {
        matches!(self, Self::Array(_))
    }

    /// Returns true if the value is an object. Returns false otherwise.
    pub fn is_object(self) -> bool {
        matches!(self, Self::Object(_))
    }

    /// If the value is `null`, returns `()`. Returns `None` otherwise.
    pub fn as_null(self) -> Option<()> {
        match self {
            Self::Null => Some(()),
            _ => None,
        }
    }

    /// If the value is a boolean, returns the associated bool. Returns `None` otherwise.
    pub fn as_bool(self) -> Option<bool> {
        match self {
            Self::Bool(b) => Some(b),
            _ => None,
        }
    }

    /// If the value is a number, returns the associated number. Returns `None` otherwise.
    pub fn as_number(self) -> Option<NumberRef<'a>> {
        match self {
            Self::Number(n) => Some(n),
            _ => None,
        }
    }

    /// If the value is an integer, returns the associated u64. Returns `None` otherwise.
    pub fn as_u64(self) -> Option<u64> {
        match self {
            Self::Number(n) => n.as_u64(),
            _ => None,
        }
    }

    /// If the value is an integer, returns the associated i64. Returns `None` otherwise.
    pub fn as_i64(self) -> Option<i64> {
        match self {
            Self::Number(n) => n.as_i64(),
            _ => None,
        }
    }

    /// If the value is a float, returns the associated f64. Returns `None` otherwise.
    pub fn as_f64(self) -> Option<f64> {
        match self {
            Self::Number(n) => n.as_f64(),
            _ => None,
        }
    }

    /// If the value is a string, returns the associated str. Returns `None` otherwise.
    pub fn as_str(self) -> Option<&'a str> {
        match self {
            Self::String(s) => Some(s.as_str()),
            _ => None,
        }
    }

    /// If the value is an array, returns the associated array. Returns `None` otherwise.
    pub fn as_array(self) -> Option<ArrayRef<'a>> {
        match self {
            Self::Array(a) => Some(a),
            _ => None,
        }
    }

    /// If the value is an object, returns the associated map. Returns `None` otherwise.
    pub fn as_object(self) -> Option<ObjectRef<'a>> {
        match self {
            Self::Object(o) => Some(o),
            _ => None,
        }
    }

    /// Creates owned `Value` from `ValueRef`.
    pub fn to_owned(self) -> Value {
        self.into()
    }

    pub(crate) fn from_slice(data: &'a [u8], entry: Entry) -> Self {
        match entry.tag() {
            Entry::NULL_TAG => Self::Null,
            Entry::FALSE_TAG => Self::Bool(false),
            Entry::TRUE_TAG => Self::Bool(true),
            Entry::NUMBER_TAG => {
                let ptr = entry.offset();
                let data = &data[ptr..ptr + 1 + number_size(data[ptr])];
                Self::Number(NumberRef { data })
            }
            Entry::STRING_TAG => {
                let ptr = entry.offset();
                let len = (&data[ptr..]).get_u32_ne() as usize;
                Self::String(StringRef::from_bytes(&data[ptr..ptr + 4 + len]))
            }
            Entry::ARRAY_TAG => {
                let ptr = entry.offset();
                Self::Array(ArrayRef::from_slice(data, ptr))
            }
            Entry::OBJECT_TAG => {
                let ptr = entry.offset();
                Self::Object(ObjectRef::from_slice(data, ptr))
            }
            _ => panic!("invalid entry"),
        }
    }

    /// Returns the entire value as a slice.
    pub(crate) fn as_slice(self) -> &'a [u8] {
        match self {
            Self::Null => &[],
            Self::Bool(_) => &[],
            Self::Number(n) => n.data,
            Self::String(s) => s.as_slice(),
            Self::Array(a) => a.as_slice(),
            Self::Object(o) => o.as_slice(),
        }
    }

    /// Makes an entry from the value.
    pub(crate) fn make_entry(self, offset: usize) -> Entry {
        match self {
            Self::Null => Entry::null(),
            Self::Bool(b) => Entry::bool(b),
            Self::Number(_) => Entry::number(offset),
            Self::String(_) => Entry::string(offset),
            Self::Array(a) => Entry::array(offset + a.as_slice().len()),
            Self::Object(o) => Entry::object(offset + o.as_slice().len()),
        }
    }

    /// Returns the entry and data of the value.
    pub fn to_raw_parts(self) -> (Entry, &'a [u8]) {
        (self.make_entry(0), self.as_slice())
    }

    /// Creates a `ValueRef` from an entry and data.
    pub fn from_raw_parts(entry: Entry, data: &'a [u8]) -> Self {
        Self::from_slice(data, entry)
    }

    /// Returns the capacity to store this value, in bytes.
    pub fn capacity(self) -> usize {
        self.as_slice().len()
    }

    /// Index into a JSON array or object.
    /// A string index can be used to access a value in an object,
    /// and a usize index can be used to access an element of an array.
    pub fn get(self, index: impl Index) -> Option<ValueRef<'a>> {
        index.index_into(self)
    }

    /// Looks up a value by a JSON Pointer.
    pub fn pointer(self, pointer: &str) -> Option<Self> {
        if pointer.is_empty() {
            return Some(self);
        }
        if !pointer.starts_with('/') {
            return None;
        }

        fn parse_index(s: &str) -> Option<usize> {
            if s.starts_with('+') || (s.starts_with('0') && s.len() != 1) {
                return None;
            }
            s.parse().ok()
        }

        pointer
            .split('/')
            .skip(1)
            .map(|x| x.replace("~1", "/").replace("~0", "~"))
            .try_fold(self, |target, token| match target {
                Self::Object(map) => map.get(&token),
                Self::Array(list) => parse_index(&token).and_then(|x| list.get(x)),
                _ => None,
            })
    }
}

impl fmt::Debug for ValueRef<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Null => f.write_str("null"),
            Self::Bool(b) => b.fmt(f),
            Self::Number(n) => n.fmt(f),
            Self::String(s) => s.as_str().fmt(f),
            Self::Array(a) => a.fmt(f),
            Self::Object(o) => o.fmt(f),
        }
    }
}

/// Display a JSON value as a string.
impl fmt::Display for ValueRef<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        serialize_in_json(self, f)
    }
}

/// Build a `serde_json::Value` from a jsonbb node.
impl From<ValueRef<'_>> for serde_json::Value {
    fn from(value: ValueRef<'_>) -> Self {
        match value {
            ValueRef::Null => Self::Null,
            ValueRef::Bool(b) => Self::Bool(b),
            ValueRef::Number(n) => Self::Number(n.to_number()),
            ValueRef::String(s) => Self::String(s.as_str().to_owned()),
            ValueRef::Array(a) => Self::Array(a.iter().map(Self::from).collect()),
            ValueRef::Object(o) => Self::Object(
                o.iter()
                    .map(|(k, v)| (k.to_owned(), Self::from(v)))
                    .collect(),
            ),
        }
    }
}

/// A reference to a JSON string.
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct StringRef<'a> {
    // # layout
    // | len (u32) | bytes    |
    // |    4      | 0..len  |
    data: &'a [u8],
}

impl<'a> StringRef<'a> {
    /// Creates a `StringRef` from a byte slice that contains the string data with length prefix.
    pub(crate) fn from_bytes(data: &'a [u8]) -> Self {
        Self { data }
    }

    /// Returns the string as a `&str`.
    pub fn as_str(&self) -> &'a str {
        let len = (&self.data[..4]).get_u32_ne() as usize;
        // SAFETY: we don't check for utf8 validity because it's expensive
        unsafe { std::str::from_utf8_unchecked(&self.data[4..4 + len]) }
    }

    /// Returns the entire string as a slice including the length prefix.
    pub(crate) fn as_slice(&self) -> &'a [u8] {
        self.data
    }
}

/// A reference to a JSON number.
#[derive(Clone, Copy)]
pub struct NumberRef<'a> {
    // # layout
    // | tag | number    |
    // |  1  | 0/1/2/4/8 |
    data: &'a [u8],
}

impl NumberRef<'_> {
    /// Dereferences the number.
    pub fn to_number(self) -> Number {
        let mut data = self.data;
        match data.get_u8() {
            NUMBER_ZERO => Number::from(0),
            NUMBER_I8 => Number::from(data.get_i8()),
            NUMBER_I16 => Number::from(data.get_i16_ne()),
            NUMBER_I32 => Number::from(data.get_i32_ne()),
            NUMBER_I64 => Number::from(data.get_i64_ne()),
            NUMBER_U64 => Number::from(data.get_u64_ne()),
            NUMBER_F64 => Number::from_f64(data.get_f64_ne()).unwrap(),
            t => panic!("invalid number tag: {t}"),
        }
    }

    /// If the number is an integer, returns the associated u64. Returns `None` otherwise.
    pub fn as_u64(self) -> Option<u64> {
        self.to_number().as_u64()
    }

    /// If the number is an integer, returns the associated i64. Returns `None` otherwise.
    pub fn as_i64(self) -> Option<i64> {
        self.to_number().as_i64()
    }

    /// Represents the number as f64 if possible. Returns None otherwise.
    pub fn as_f64(self) -> Option<f64> {
        self.to_number().as_f64()
    }

    /// Represents the number as f32 if possible. Returns None otherwise.
    pub(crate) fn as_f32(&self) -> Option<f32> {
        let mut data = self.data;
        Some(match data.get_u8() {
            NUMBER_ZERO => 0 as f32,
            NUMBER_I8 => data.get_i8() as f32,
            NUMBER_I16 => data.get_i16_ne() as f32,
            NUMBER_I32 => data.get_i32_ne() as f32,
            NUMBER_I64 => data.get_i64_ne() as f32,
            NUMBER_U64 => data.get_u64_ne() as f32,
            NUMBER_F64 => data.get_f64_ne() as f32,
            t => panic!("invalid number tag: {t}"),
        })
    }

    /// Returns true if the number can be represented by u64.
    pub fn is_u64(self) -> bool {
        self.to_number().is_u64()
    }

    /// Returns true if the number can be represented by i64.
    pub fn is_i64(self) -> bool {
        self.to_number().is_i64()
    }

    /// Returns true if the number can be represented by f64.
    pub fn is_f64(self) -> bool {
        self.to_number().is_f64()
    }
}

impl fmt::Debug for NumberRef<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.to_number().fmt(f)
    }
}

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

impl PartialEq for NumberRef<'_> {
    fn eq(&self, other: &Self) -> bool {
        let a = self.to_number();
        let b = other.to_number();
        match (a.as_u64(), b.as_u64()) {
            (Some(a), Some(b)) => return a == b,           // a, b > 0
            (Some(_), None) if b.is_i64() => return false, // a >= 0 > b
            (None, Some(_)) if a.is_i64() => return false, // a < 0 <= b
            (None, None) => {
                if let (Some(a), Some(b)) = (a.as_i64(), b.as_i64()) {
                    return a == b; // a, b < 0
                }
            }
            _ => {}
        }
        // either a or b is a float
        let a = a.as_f64().unwrap();
        let b = b.as_f64().unwrap();
        a == b
    }
}

impl Eq for NumberRef<'_> {}

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

impl Ord for NumberRef<'_> {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        let a = self.to_number();
        let b = other.to_number();
        match (a.as_u64(), b.as_u64()) {
            (Some(a), Some(b)) => return a.cmp(&b), // a, b > 0
            (Some(_), None) if b.is_i64() => return std::cmp::Ordering::Greater, // a >= 0 > b
            (None, Some(_)) if a.is_i64() => return std::cmp::Ordering::Less, // a < 0 <= b
            (None, None) => {
                if let (Some(a), Some(b)) = (a.as_i64(), b.as_i64()) {
                    return a.cmp(&b); // a, b < 0
                }
            }
            _ => {}
        }
        // either a or b is a float
        let a = a.as_f64().unwrap();
        let b = b.as_f64().unwrap();
        a.partial_cmp(&b).expect("NaN or Inf in JSON number")
    }
}

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

/// A reference to a JSON array.
#[derive(Clone, Copy)]
pub struct ArrayRef<'a> {
    // # layout
    //      v---------\
    // | elements | [eptr] x len | len | size |
    // |          |   4 x len    |  4  |  4   |
    // |<----------- data (size) ------------>|^ptr
    data: &'a [u8],
}

impl<'a> ArrayRef<'a> {
    /// Returns the element at the given index, or `None` if the index is out of bounds.
    pub fn get(self, index: usize) -> Option<ValueRef<'a>> {
        let len = self.len();
        if index >= len {
            return None;
        }
        let offset = self.data.len() - 8 - 4 * (len - index);
        let entry = Entry::from(&self.data[offset..offset + 4]);
        Some(ValueRef::from_slice(self.data, entry))
    }

    /// Returns the number of elements in the array.
    pub fn len(self) -> usize {
        (&self.data[self.data.len() - 8..]).get_u32_ne() as usize
    }

    /// Returns `true` if the array contains no elements.
    pub fn is_empty(self) -> bool {
        self.len() == 0
    }

    /// Returns an iterator over the array's elements.
    pub fn iter(self) -> impl ExactSizeIterator<Item = ValueRef<'a>> {
        let len = self.len();
        let offset = self.data.len() - 8 - 4 * len;
        self.data[offset..offset + 4 * len]
            .chunks_exact(4)
            .map(|slice| ValueRef::from_slice(self.data, Entry::from(slice)))
    }

    /// Returns the entire array as a slice.
    pub(crate) fn as_slice(self) -> &'a [u8] {
        self.data
    }

    /// Creates an `ArrayRef` from a slice.
    fn from_slice(data: &'a [u8], end: usize) -> Self {
        let size = (&data[end - 4..end]).get_u32_ne() as usize;
        Self {
            data: &data[end - size..end],
        }
    }
}

impl fmt::Debug for ArrayRef<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_list().entries(self.iter()).finish()
    }
}

/// Display a JSON array as a string.
impl fmt::Display for ArrayRef<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        serialize_in_json(self, f)
    }
}

impl PartialEq for ArrayRef<'_> {
    fn eq(&self, other: &Self) -> bool {
        if self.len() != other.len() {
            return false;
        }
        self.iter().eq(other.iter())
    }
}

impl Eq for ArrayRef<'_> {}

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

impl Ord for ArrayRef<'_> {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        // Array with n elements > array with n - 1 elements
        match self.len().cmp(&other.len()) {
            std::cmp::Ordering::Equal => self.iter().cmp(other.iter()),
            ord => ord,
        }
    }
}

impl Hash for ArrayRef<'_> {
    fn hash<H: Hasher>(&self, state: &mut H) {
        for v in self.iter() {
            v.hash(state);
        }
    }
}

/// A reference to a JSON object.
#[derive(Clone, Copy)]
pub struct ObjectRef<'a> {
    // # layout
    //      v-v------ \-----\
    // | elements | [kptr, vptr] x len | len | size |
    // |          |     4 x 2 x len    |  4  |  4   |
    // |<-------------- data (size) --------------->|^ptr
    //
    // entries are ordered by key and each key is unique.
    data: &'a [u8],
}

impl<'a> ObjectRef<'a> {
    /// Returns the value associated with the given key, or `None` if the key is not present.
    ///
    /// # Examples
    /// ```
    /// let json: jsonbb::Value = r#"{"a": 1, "b": 2}"#.parse().unwrap();
    /// let object = json.as_object().unwrap();
    /// assert!(object.get("a").is_some());
    /// assert!(object.get("c").is_none());
    /// ```
    pub fn get(self, key: &str) -> Option<ValueRef<'a>> {
        // do binary search since entries are ordered by key
        let entries = self.entries();
        let idx = entries
            .binary_search_by_key(&key, |&(kentry, _)| {
                ValueRef::from_slice(self.data, kentry)
                    .as_str()
                    .expect("key must be string")
            })
            .ok()?;
        let (_, ventry) = entries[idx];
        Some(ValueRef::from_slice(self.data, ventry))
    }

    /// Returns `true` if the object contains a value for the specified key.
    ///
    /// # Examples
    /// ```
    /// let json: jsonbb::Value = r#"{"a": 1, "b": 2}"#.parse().unwrap();
    /// let object = json.as_object().unwrap();
    /// assert_eq!(object.contains_key("a"), true);
    /// assert_eq!(object.contains_key("c"), false);
    /// ```
    pub fn contains_key(self, key: &str) -> bool {
        // do binary search since entries are ordered by key
        let entries = self.entries();
        entries
            .binary_search_by_key(&key, |&(kentry, _)| {
                ValueRef::from_slice(self.data, kentry)
                    .as_str()
                    .expect("key must be string")
            })
            .is_ok()
    }

    /// Returns the number of elements in the object.
    ///
    /// # Examples
    /// ```
    /// let json: jsonbb::Value = r#"{"a": 1, "b": 2}"#.parse().unwrap();
    /// let object = json.as_object().unwrap();
    /// assert_eq!(object.len(), 2);
    /// ```
    pub fn len(self) -> usize {
        (&self.data[self.data.len() - 8..]).get_u32_ne() as usize
    }

    /// Returns `true` if the object contains no elements.
    ///
    /// # Examples
    /// ```
    /// let json: jsonbb::Value = r#"{"a": 1, "b": 2}"#.parse().unwrap();
    /// let object = json.as_object().unwrap();
    /// assert_eq!(object.is_empty(), false);
    /// ```
    pub fn is_empty(self) -> bool {
        self.len() == 0
    }

    /// Returns an iterator over the object's key-value pairs.
    ///
    /// # Examples
    /// ```
    /// let json: jsonbb::Value = r#"{"b": 2, "a": 1}"#.parse().unwrap();
    /// let kvs: Vec<_> = json.as_object().unwrap().iter().map(|(k, v)| (k, v.as_u64().unwrap())).collect();
    /// assert_eq!(kvs, [("a", 1), ("b", 2)]);
    /// ```
    pub fn iter(self) -> impl ExactSizeIterator<Item = (&'a str, ValueRef<'a>)> {
        self.entries().iter().map(move |&(kentry, ventry)| {
            let k = ValueRef::from_slice(self.data, kentry);
            let v = ValueRef::from_slice(self.data, ventry);
            (k.as_str().expect("key must be string"), v)
        })
    }

    /// Returns an iterator over the object's keys.
    ///
    /// # Examples
    /// ```
    /// let json: jsonbb::Value = r#"{"b": 2, "a": 1}"#.parse().unwrap();
    /// let keys: Vec<_> = json.as_object().unwrap().keys().collect();
    /// assert_eq!(keys, ["a", "b"]);
    /// ```
    pub fn keys(self) -> impl ExactSizeIterator<Item = &'a str> {
        self.iter().map(|(k, _)| k)
    }

    /// Returns an iterator over the object's values.
    ///
    /// # Examples
    /// ```
    /// let json: jsonbb::Value = r#"{"b": 2, "a": 1}"#.parse().unwrap();
    /// let values: Vec<_> = json.as_object().unwrap().values().map(|v| v.as_u64().unwrap()).collect();
    /// assert_eq!(values, [1, 2]);
    /// ```
    pub fn values(self) -> impl ExactSizeIterator<Item = ValueRef<'a>> {
        self.iter().map(|(_, v)| v)
    }

    /// Returns the entire object as a slice.
    pub(crate) fn as_slice(self) -> &'a [u8] {
        self.data
    }

    /// Creates an `ObjectRef` from a slice.
    fn from_slice(data: &'a [u8], end: usize) -> Self {
        let size = (&data[end - 4..end]).get_u32_ne() as usize;
        Self {
            data: &data[end - size..end],
        }
    }

    /// Returns the key-value entries.
    fn entries(self) -> &'a [(Entry, Entry)] {
        let len = self.len();
        let base = self.data.len() - 8 - 8 * len;
        let slice = &self.data[base..base + 8 * len];
        unsafe { std::slice::from_raw_parts(slice.as_ptr() as _, len) }
    }
}

impl fmt::Debug for ObjectRef<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_map().entries(self.iter()).finish()
    }
}

/// Display a JSON object as a string.
impl fmt::Display for ObjectRef<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        serialize_in_json(self, f)
    }
}

impl PartialEq for ObjectRef<'_> {
    fn eq(&self, other: &Self) -> bool {
        if self.len() != other.len() {
            return false;
        }
        self.iter().eq(other.iter())
    }
}

impl Eq for ObjectRef<'_> {}

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

impl Ord for ObjectRef<'_> {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        // Object with n pairs > object with n - 1 pairs
        match self.len().cmp(&other.len()) {
            std::cmp::Ordering::Equal => self.iter().cmp(other.iter()),
            ord => ord,
        }
    }
}

impl Hash for ObjectRef<'_> {
    fn hash<H: Hasher>(&self, state: &mut H) {
        for (k, v) in self.iter() {
            k.hash(state);
            v.hash(state);
        }
    }
}

/// Serialize a value in JSON format.
fn serialize_in_json(value: &impl ::serde::Serialize, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    use std::io;

    struct WriterFormatter<'a, 'b: 'a> {
        inner: &'a mut fmt::Formatter<'b>,
    }

    impl<'a, 'b> io::Write for WriterFormatter<'a, 'b> {
        fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
            // Safety: the serializer below only emits valid utf8 when using
            // the default formatter.
            let s = unsafe { std::str::from_utf8_unchecked(buf) };
            self.inner.write_str(s).map_err(io_error)?;
            Ok(buf.len())
        }

        fn flush(&mut self) -> io::Result<()> {
            Ok(())
        }
    }

    fn io_error(_: fmt::Error) -> io::Error {
        // Error value does not matter because Display impl just maps it
        // back to fmt::Error.
        io::Error::other("fmt error")
    }

    let alternate = f.alternate();
    let mut wr = WriterFormatter { inner: f };
    if alternate {
        // {:#}
        value
            .serialize(&mut serde_json::Serializer::pretty(&mut wr))
            .map_err(|_| fmt::Error)
    } else {
        // {}
        value
            .serialize(&mut serde_json::Serializer::new(&mut wr))
            .map_err(|_| fmt::Error)
    }
}

/// A type that can be used to index into a `ValueRef`.
pub trait Index: private::Sealed {
    /// Return None if the key is not already in the array or object.
    #[doc(hidden)]
    fn index_into<'v>(&self, v: ValueRef<'v>) -> Option<ValueRef<'v>>;
}

impl Index for usize {
    fn index_into<'v>(&self, v: ValueRef<'v>) -> Option<ValueRef<'v>> {
        match v {
            ValueRef::Array(a) => a.get(*self),
            _ => None,
        }
    }
}

impl Index for str {
    fn index_into<'v>(&self, v: ValueRef<'v>) -> Option<ValueRef<'v>> {
        match v {
            ValueRef::Object(o) => o.get(self),
            _ => None,
        }
    }
}

impl Index for String {
    fn index_into<'v>(&self, v: ValueRef<'v>) -> Option<ValueRef<'v>> {
        match v {
            ValueRef::Object(o) => o.get(self),
            _ => None,
        }
    }
}

impl<T> Index for &T
where
    T: ?Sized + Index,
{
    fn index_into<'v>(&self, v: ValueRef<'v>) -> Option<ValueRef<'v>> {
        (**self).index_into(v)
    }
}

// Prevent users from implementing the Index trait.
mod private {
    pub trait Sealed {}
    impl Sealed for usize {}
    impl Sealed for str {}
    impl Sealed for String {}
    impl<T> Sealed for &T where T: ?Sized + Sealed {}
}