sonic_rs/value/
node.rs

1use core::mem::size_of;
2#[cfg(feature = "sort_keys")]
3use std::collections::BTreeMap;
4use std::{
5    alloc::Layout,
6    fmt::{Debug, Display, Formatter},
7    mem::{transmute, ManuallyDrop},
8    ptr::NonNull,
9    slice::from_raw_parts,
10    str::from_utf8_unchecked,
11    sync::Arc,
12};
13
14#[cfg(not(feature = "sort_keys"))]
15use ahash::AHashMap;
16use faststr::FastStr;
17use ref_cast::RefCast;
18use serde::ser::{Serialize, SerializeMap, SerializeSeq};
19
20use super::{
21    object::Pair,
22    shared::Shared,
23    tls_buffer::TlsBuf,
24    value_trait::{JsonContainerTrait, JsonValueMutTrait},
25    visitor::JsonVisitor,
26};
27use crate::{
28    config::DeserializeCfg,
29    error::Result,
30    index::Index,
31    parser::Parser,
32    reader::{PaddedSliceRead, Reader},
33    serde::tri,
34    util::string::str_from_raw_parts,
35    value::{array::Array, object::Object, value_trait::JsonValueTrait},
36    JsonNumberTrait, JsonType, Number, RawNumber,
37};
38
39/// Represents any valid JSON value.
40///
41/// `Value` can be parsed from a JSON and from any type that implements `serde::Serialize`.
42///
43/// # Example
44/// ```
45/// use sonic_rs::json;
46/// use sonic_rs::value::Value;
47///
48/// let v1 = json!({"a": 123});
49/// let v2: Value = sonic_rs::from_str(r#"{"a": 123}"#).unwrap();
50/// let v3 = {
51///     use std::collections::HashMap;
52///     let mut map: HashMap<&str, i32> = HashMap::new();
53///     map.insert(&"a", 123);
54///     sonic_rs::to_value(&map).unwrap()
55/// };
56///
57/// assert_eq!(v1, v2);
58/// assert_eq!(v2, v3);
59///
60/// assert_eq!(v1["a"], 123);
61/// ```
62///
63/// # Notes
64///
65/// Not use any unsafe invalid_reference_casting for `Value`, it will cause UB.
66///
67/// ```rust,no_run
68/// use sonic_rs::{from_str, Value};
69/// let json = r#"["a", "b", "c"]"#;
70/// let root: Value = from_str(json).unwrap();
71/// let immref = &root["b"];
72///
73/// // This is dangerous, will coredump when using sanitizer
74/// #[allow(invalid_reference_casting)]
75/// let ub_cast = unsafe { &mut *(immref as *const _ as *mut Value) };
76/// let _ub = std::mem::take(ub_cast);
77/// ```
78#[repr(C)]
79pub struct Value {
80    pub(crate) meta: Meta,
81    pub(crate) data: Data,
82}
83
84#[rustfmt::skip]
85// A compact and mutable JSON Value.
86//
87//  Thera are three kind nodes into the Value:
88//  - Static Node: no need drop
89//  - Owned Node : mutable
90//  - Shared Node: in SharedDom, not mutable
91//
92// |  Kind        | 3 bits | 5 bits |       24 bits     |     ---->  32 bits ---->       |    32 bits    |    32 bits    |       limit          |
93// |--------------|-----------------|-------------------|--------------------------------|-------------------------------|----------------------|
94// |   Null       |   0    |   0    |                                                    +                               |                      |
95// |   True       |   0    |   1    |                                                    +                               |                      |
96// |   False      |   0    |   2    |                                                    +                               |                      |
97// |   I64        |   0    |   3    |                                                    +             i64               |                      |
98// |   U64        |   0    |   4    |                                                    +             u64               |                      |
99// |   F64        |   0    |   5    |                                                    +             f64               |                      |
100// |  empty arr   |   0    |   6    |                                                                                    |
101// |  empty obj   |   0    |   7    |                                                                                    |
102// |  static str  |   0    |   8    |                   |           string length        +          *const u8            | excced will fallback |
103// |   faststr    |   1    |   0    |                                                    +         Box<FastStr>          |                      |
104// |rawnum_faststr|   1    |   1    |                                                    +         Box<FastStr>          |                      |
105// |   arr_mut    |   1    |   2    |                                                    +        Arc<Vec<Node>>         |                      |
106// |   obj_mut    |   1    |   3    |                                                    + Arc<AHashMap<FastStr, Value>> |                      |
107// |   str_node   |   2    |        node idx            |           string length        +          *const u8            |    max len 2^32      |
108// | raw_num_node |   3    |        node idx            |           string length        +          *const u8            |    max len 2^32      |
109// |   arr_node   |   4    |        node idx            |           array length         +          *const Node          |    max len 2^32      |
110// |   obj_node   |   5    |        node idx            |           object length        +          *const Pair          |    max len 2^32      |
111// |   _reserved  |   6    |
112// |  root_node   |   7    |      *const ShardDom (from Arc, MUST aligned 8)             +      *const Node (head)       |                      |
113//
114// NB: we will check the JSON length when parsing, if JSON is >= 4GB, will return a error, so we will not check the limits when parsing or using dom.
115#[allow(clippy::box_collection)]
116#[repr(C)]
117pub(crate) union Data {
118    pub(crate) uval: u64,
119    pub(crate) ival: i64,
120    pub(crate) fval: f64,
121    pub(crate) static_str: NonNull<u8>,
122
123    pub(crate) dom_str: NonNull<u8>,
124    pub(crate) arr_elems: NonNull<Value>,
125    pub(crate) obj_pairs: NonNull<Pair>,
126
127    pub(crate) root: NonNull<Value>,
128
129    pub(crate) str_own: ManuallyDrop<Box<FastStr>>,
130    #[cfg(not(feature = "sort_keys"))]
131    pub(crate) obj_own: ManuallyDrop<Arc<AHashMap<FastStr, Value>>>,
132    #[cfg(feature="sort_keys")]
133    pub(crate) obj_own: ManuallyDrop<Arc<BTreeMap<FastStr, Value>>>,
134    pub(crate) arr_own: ManuallyDrop<Arc<Vec<Value>>>,
135
136    pub(crate) parent: u64,
137}
138
139#[derive(Copy, Clone)]
140#[repr(C)]
141pub(crate) union Meta {
142    shared: NonNull<Shared>,
143    typ: u64,
144    val: u64,
145}
146
147impl Meta {
148    const STAIC_NODE: u64 = 0;
149    const NULL: u64 = (0 << Self::KIND_BITS);
150    const TRUE: u64 = (1 << Self::KIND_BITS);
151    const FALSE: u64 = (2 << Self::KIND_BITS);
152    const I64: u64 = (3 << Self::KIND_BITS);
153    const U64: u64 = (4 << Self::KIND_BITS);
154    const F64: u64 = (5 << Self::KIND_BITS);
155    const EMPTY_ARR: u64 = (6 << Self::KIND_BITS);
156    const EMPTY_OBJ: u64 = (7 << Self::KIND_BITS);
157    const STATIC_STR: u64 = (8 << Self::KIND_BITS);
158
159    const OWNED_NODE: u64 = 1;
160    const FASTSTR: u64 = 1 | (0 << Self::KIND_BITS);
161    const RAWNUM_FASTSTR: u64 = 1 | (1 << Self::KIND_BITS);
162    const ARR_MUT: u64 = 1 | (2 << Self::KIND_BITS);
163    const OBJ_MUT: u64 = 1 | (3 << Self::KIND_BITS);
164
165    const STR_NODE: u64 = 2;
166    const RAWNUM_NODE: u64 = 3;
167    const ARR_NODE: u64 = 4;
168    const OBJ_NODE: u64 = 5;
169
170    const ROOT_NODE: u64 = 7;
171
172    const KIND_BITS: u64 = 3;
173    const KIND_MASK: u64 = (1 << Self::KIND_BITS) - 1;
174
175    const TYPE_BITS: u64 = 8;
176    const TYPE_MASK: u64 = (1 << Self::TYPE_BITS) - 1;
177
178    const IDX_MASK: u64 = ((1 << Self::LEN_OFFSET) - 1) & !Self::KIND_MASK;
179    const LEN_OFFSET: u64 = 32;
180}
181
182impl Meta {
183    pub const fn new(typ: u64) -> Self {
184        Self { typ }
185    }
186
187    fn pack_dom_node(kind: u64, idx: u32, len: u32) -> Self {
188        debug_assert!(matches!(
189            kind,
190            Self::ARR_NODE | Self::OBJ_NODE | Self::STR_NODE | Self::RAWNUM_NODE
191        ));
192        let idx = idx as u64;
193        let len = len as u64;
194        let val = kind | (idx << Self::KIND_BITS) | (len << Self::LEN_OFFSET);
195        Self { val }
196    }
197
198    fn pack_static_str(kind: u64, len: usize) -> Self {
199        assert!(len < (u32::MAX as usize));
200        assert!(kind == Self::STATIC_STR);
201        let val = kind | ((len as u64) << Self::LEN_OFFSET);
202        Self { val }
203    }
204
205    fn pack_shared(ptr: *const Shared) -> Self {
206        unsafe { Arc::increment_strong_count(ptr) };
207        let addr = ptr as usize as u64;
208        let val = addr | Self::ROOT_NODE;
209        Self { val }
210    }
211
212    fn get_kind(&self) -> u64 {
213        let val = unsafe { self.val };
214        val & 0x7
215    }
216
217    fn get_type(&self) -> u64 {
218        let val = unsafe { self.val };
219        let typ = val & Self::TYPE_MASK;
220        let kind = self.get_kind();
221        match kind {
222            Self::STAIC_NODE | Self::OWNED_NODE => typ,
223            Self::STR_NODE | Self::RAWNUM_NODE | Self::ARR_NODE | Self::OBJ_NODE => {
224                typ & Self::KIND_MASK
225            }
226            Self::ROOT_NODE => typ & Self::KIND_MASK,
227            _ => unreachable!("unknown kind {kind}"),
228        }
229    }
230
231    fn unpack_dom_node(&self) -> NodeMeta {
232        debug_assert!(self.in_shared());
233        let val = unsafe { self.val };
234        let idx = (val & Self::IDX_MASK) >> Self::KIND_BITS;
235        let len = val >> Self::LEN_OFFSET;
236        NodeMeta {
237            idx: idx as u32,
238            len: len as u32,
239        }
240    }
241
242    fn unpack_root(&self) -> *const Shared {
243        debug_assert!(self.get_kind() == Self::ROOT_NODE);
244        let val = unsafe { self.val };
245        let addr = (val & !Self::ROOT_NODE) as usize;
246        addr as *const Shared
247    }
248
249    fn has_strlen(&self) -> bool {
250        matches!(
251            self.get_type(),
252            Self::STR_NODE | Self::RAWNUM_NODE | Self::STATIC_STR
253        )
254    }
255
256    fn in_shared(&self) -> bool {
257        matches!(
258            self.get_type(),
259            Self::STR_NODE | Self::RAWNUM_NODE | Self::ARR_NODE | Self::OBJ_NODE
260        )
261    }
262
263    fn unpack_strlen(&self) -> usize {
264        debug_assert!(self.has_strlen());
265        let val = unsafe { self.val };
266        (val >> Self::LEN_OFFSET) as usize
267    }
268}
269
270struct NodeMeta {
271    idx: u32,
272    len: u32,
273}
274
275struct NodeInDom<'a> {
276    node: &'a Value,
277    dom: &'a Shared,
278}
279
280impl<'a> NodeInDom<'a> {
281    #[inline(always)]
282    fn get_inner(&self) -> ValueRefInner<'a> {
283        let typ = self.node.meta.get_type();
284        match typ {
285            Meta::STR_NODE => ValueRefInner::Str(self.unpack_str()),
286            Meta::RAWNUM_NODE => ValueRefInner::RawNum(self.unpack_str()),
287            Meta::ARR_NODE => ValueRefInner::Array(self.unpack_value_slice()),
288            Meta::OBJ_NODE => ValueRefInner::Object(self.unpack_pair_slice()),
289            _ => unreachable!("unknown type {typ} in dom"),
290        }
291    }
292
293    #[inline(always)]
294    fn unpack_str(&self) -> &'a str {
295        let len = self.node.meta.unpack_dom_node().len as usize;
296        let ptr = unsafe { self.node.data.dom_str.as_ptr() };
297        unsafe { str_from_raw_parts(ptr, len) }
298    }
299
300    #[inline(always)]
301    fn unpack_value_slice(&self) -> &'a [Value] {
302        let len = self.node.meta.unpack_dom_node().len as usize;
303        let elems = unsafe { self.node.data.arr_elems.as_ptr() };
304        unsafe { from_raw_parts(elems, len) }
305    }
306
307    #[inline(always)]
308    fn unpack_pair_slice(&self) -> &'a [Pair] {
309        let len = self.node.meta.unpack_dom_node().len as usize;
310        let pairs = unsafe { self.node.data.obj_pairs.as_ptr() };
311        unsafe { from_raw_parts(pairs, len) }
312    }
313}
314
315impl<'a> From<NodeInDom<'a>> for Value {
316    fn from(value: NodeInDom<'a>) -> Self {
317        Self {
318            meta: Meta::pack_shared(value.dom as *const _),
319            data: Data {
320                root: NonNull::from(value.node),
321            },
322        }
323    }
324}
325
326/// The value borrowed from the SharedDom
327enum ValueDetail<'a> {
328    Null,
329    Bool(bool),
330    Number(Number),
331    StaticStr(&'static str),
332    FastStr(&'a FastStr),
333    RawNumFasStr(&'a FastStr),
334    Array(&'a Arc<Vec<Value>>),
335    #[cfg(not(feature = "sort_keys"))]
336    Object(&'a Arc<AHashMap<FastStr, Value>>),
337    #[cfg(feature = "sort_keys")]
338    Object(&'a Arc<BTreeMap<FastStr, Value>>),
339    Root(NodeInDom<'a>),
340    NodeInDom(NodeInDom<'a>),
341    EmptyArray,
342    EmptyObject,
343}
344
345/// ValueRef is a immutable reference helper for `Value`.
346///
347/// # Example
348///
349/// ```
350/// use sonic_rs::{ValueRef, json, JsonValueTrait};
351///
352/// let v = json!({
353///    "name": "Xiaoming",
354///    "age": 18,
355/// });
356///
357/// match v.as_ref() {
358///     ValueRef::Object(obj) => {
359///        assert_eq!(obj.get(&"name").unwrap().as_str().unwrap(), "Xiaoming");
360///        assert_eq!(obj.get(&"age").unwrap().as_i64().unwrap(), 18);
361///    },
362///    _ => unreachable!(),
363/// }
364/// ```
365#[derive(Debug)]
366pub enum ValueRef<'a> {
367    Null,
368    Bool(bool),
369    Number(Number),
370    String(&'a str),
371    Array(&'a Array),
372    Object(&'a Object),
373}
374
375#[derive(Debug)]
376pub enum ValueRefInner<'a> {
377    Null,
378    Bool(bool),
379    Number(Number),
380    Str(&'a str),
381    RawNum(&'a str),
382    Array(&'a [Value]),
383    Object(&'a [Pair]),
384    #[cfg(not(feature = "sort_keys"))]
385    ObjectOwned(&'a Arc<AHashMap<FastStr, Value>>),
386    #[cfg(feature = "sort_keys")]
387    ObjectOwned(&'a Arc<BTreeMap<FastStr, Value>>),
388    EmptyArray,
389    EmptyObject,
390}
391
392impl<'a> From<&'a [Pair]> for Value {
393    fn from(value: &'a [Pair]) -> Self {
394        #[cfg(not(feature = "sort_keys"))]
395        let mut newd = AHashMap::with_capacity(value.len());
396        #[cfg(feature = "sort_keys")]
397        let mut newd = BTreeMap::new();
398
399        for (k, v) in value {
400            if let Some(k) = k.as_str() {
401                newd.insert(FastStr::new(k), v.clone());
402            }
403        }
404
405        Self {
406            meta: Meta::new(Meta::OBJ_MUT),
407            data: Data {
408                obj_own: ManuallyDrop::new(Arc::new(newd)),
409            },
410        }
411    }
412}
413
414impl Drop for Value {
415    fn drop(&mut self) {
416        if self.meta.get_kind() == Meta::STAIC_NODE || self.meta.in_shared() {
417            return;
418        }
419        unsafe {
420            match self.meta.get_type() {
421                Meta::FASTSTR | Meta::RAWNUM_FASTSTR => ManuallyDrop::drop(&mut self.data.str_own),
422                Meta::ARR_MUT => ManuallyDrop::drop(&mut self.data.arr_own),
423                Meta::OBJ_MUT => ManuallyDrop::drop(&mut self.data.obj_own),
424                Meta::ROOT_NODE => {
425                    let dom = self.meta.unpack_root();
426                    drop(Arc::from_raw(dom));
427                }
428                _ => unreachable!("should not be dropped"),
429            }
430        }
431    }
432}
433
434pub(crate) enum ValueMut<'a> {
435    Null,
436    Bool,
437    Number,
438    Str,
439    RawNum,
440    Array(&'a mut Vec<Value>),
441    #[cfg(not(feature = "sort_keys"))]
442    Object(&'a mut AHashMap<FastStr, Value>),
443    #[cfg(feature = "sort_keys")]
444    Object(&'a mut BTreeMap<FastStr, Value>),
445}
446
447impl Value {
448    fn is_node_kind(&self) -> bool {
449        matches!(
450            self.meta.get_kind(),
451            Meta::ARR_NODE | Meta::OBJ_NODE | Meta::STR_NODE | Meta::RAWNUM_NODE
452        )
453    }
454
455    pub(crate) fn as_mut(&mut self) -> ValueMut<'_> {
456        let typ = self.meta.get_type();
457        match typ {
458            Meta::NULL => ValueMut::Null,
459            Meta::TRUE | Meta::FALSE => ValueMut::Bool,
460            Meta::F64 | Meta::I64 | Meta::U64 => ValueMut::Number,
461            Meta::STATIC_STR | Meta::STR_NODE | Meta::FASTSTR => ValueMut::Str,
462            Meta::RAWNUM_FASTSTR | Meta::RAWNUM_NODE => ValueMut::RawNum,
463            Meta::ARR_MUT => ValueMut::Array(unsafe { Arc::make_mut(&mut self.data.arr_own) }),
464            Meta::OBJ_MUT => ValueMut::Object(unsafe { Arc::make_mut(&mut self.data.obj_own) }),
465            Meta::ROOT_NODE | Meta::EMPTY_ARR | Meta::EMPTY_OBJ => {
466                /* convert to mutable */
467                self.to_mut();
468                self.as_mut()
469            }
470            _ => unreachable!("should not be access in mutable api"),
471        }
472    }
473    fn to_mut(&mut self) {
474        assert!(
475            !self.meta.in_shared(),
476            "chidlren in shared should not to mut"
477        );
478        match self.unpack_ref() {
479            ValueDetail::Root(indom) => match indom.node.meta.get_type() {
480                Meta::ARR_NODE => {
481                    let slice = indom.unpack_value_slice();
482                    *self = slice.into();
483                }
484                Meta::OBJ_NODE => {
485                    let slice = indom.unpack_pair_slice();
486                    *self = slice.into();
487                }
488                _ => {}
489            },
490            ValueDetail::EmptyArray => *self = Value::new_array_with(8),
491            ValueDetail::EmptyObject => *self = Value::new_object_with(8),
492            _ => {}
493        }
494    }
495
496    fn unpack_static_str(&self) -> &'static str {
497        debug_assert!(self.meta.get_type() == Meta::STATIC_STR);
498        let ptr = unsafe { self.data.static_str.as_ptr() };
499        let len = self.meta.unpack_strlen();
500        unsafe { from_utf8_unchecked(from_raw_parts(ptr, len)) }
501    }
502
503    fn forward_find_shared(current: *const Value, idx: usize) -> *const Shared {
504        assert!(unsafe { (*(current.sub(idx) as *const MetaNode)).canary() });
505        unsafe { (*(current.sub(idx) as *const MetaNode)).shared }
506    }
507
508    fn unpack_shared(&self) -> &Shared {
509        assert!(self.is_node_kind());
510        unsafe {
511            let idx = self.meta.unpack_dom_node().idx;
512            let cur = self as *const _;
513            let shared: *const Shared = Self::forward_find_shared(cur, idx as usize);
514            &*shared
515        }
516    }
517
518    #[inline(always)]
519    fn get_enum(&self) -> ValueRefInner<'_> {
520        match self.unpack_ref() {
521            ValueDetail::Null => ValueRefInner::Null,
522            ValueDetail::Bool(b) => ValueRefInner::Bool(b),
523            ValueDetail::Number(n) => ValueRefInner::Number(n.clone()),
524            ValueDetail::StaticStr(s) => ValueRefInner::Str(s),
525            ValueDetail::FastStr(s) => ValueRefInner::Str(s.as_str()),
526            ValueDetail::RawNumFasStr(s) => ValueRefInner::RawNum(s.as_str()),
527            ValueDetail::Array(a) => ValueRefInner::Array(a),
528            #[cfg(not(feature = "sort_keys"))]
529            ValueDetail::Object(o) => ValueRefInner::ObjectOwned(o),
530            #[cfg(feature = "sort_keys")]
531            ValueDetail::Object(o) => ValueRefInner::ObjectOwned(o),
532            ValueDetail::Root(n) | ValueDetail::NodeInDom(n) => n.get_inner(),
533            ValueDetail::EmptyArray => ValueRefInner::EmptyArray,
534            ValueDetail::EmptyObject => ValueRefInner::EmptyObject,
535        }
536    }
537
538    #[inline(always)]
539    fn unpack_ref(&self) -> ValueDetail<'_> {
540        unsafe {
541            match self.meta.get_type() {
542                Meta::NULL => ValueDetail::Null,
543                Meta::TRUE => ValueDetail::Bool(true),
544                Meta::FALSE => ValueDetail::Bool(false),
545                Meta::STATIC_STR => ValueDetail::StaticStr(self.unpack_static_str()),
546                Meta::I64 => ValueDetail::Number(Number::from(self.data.ival)),
547                Meta::U64 => ValueDetail::Number(Number::from(self.data.uval)),
548                Meta::F64 => ValueDetail::Number(Number::try_from(self.data.fval).unwrap()),
549                Meta::EMPTY_ARR => ValueDetail::EmptyArray,
550                Meta::EMPTY_OBJ => ValueDetail::EmptyObject,
551                Meta::STR_NODE | Meta::RAWNUM_NODE | Meta::ARR_NODE | Meta::OBJ_NODE => {
552                    ValueDetail::NodeInDom(NodeInDom {
553                        node: self,
554                        dom: self.unpack_shared(),
555                    })
556                }
557                Meta::FASTSTR => ValueDetail::FastStr(&self.data.str_own),
558                Meta::RAWNUM_FASTSTR => ValueDetail::RawNumFasStr(&self.data.str_own),
559                Meta::ARR_MUT => ValueDetail::Array(&self.data.arr_own),
560                Meta::OBJ_MUT => ValueDetail::Object(&self.data.obj_own),
561                Meta::ROOT_NODE => ValueDetail::Root(NodeInDom {
562                    node: self.data.root.as_ref(),
563                    dom: &*self.meta.unpack_root(),
564                }),
565                _ => unreachable!("unknown type"),
566            }
567        }
568    }
569}
570
571unsafe impl Sync for Value {}
572unsafe impl Send for Value {}
573
574impl Clone for Value {
575    /// Clone the value, if the value is a root node, we will create a new allocator for it.
576    ///
577    /// # Example
578    ///
579    /// ```
580    /// use sonic_rs::json;
581    ///
582    /// let a = json!({"a": [1, 2, 3]});
583    /// assert_eq!(a, a.clone());
584    /// ```
585    fn clone(&self) -> Self {
586        match self.unpack_ref() {
587            ValueDetail::Root(indom) | ValueDetail::NodeInDom(indom) => Value::from(indom),
588            ValueDetail::Null => Value::new_null(),
589            ValueDetail::Bool(b) => Value::new_bool(b),
590            ValueDetail::Number(n) => n.into(),
591            ValueDetail::StaticStr(s) => Value::from_static_str(s),
592            ValueDetail::FastStr(s) => s.into(),
593            ValueDetail::RawNumFasStr(s) => Value::new_rawnum_faststr(s),
594            ValueDetail::Array(a) => a.clone().into(),
595            ValueDetail::Object(o) => o.clone().into(),
596            ValueDetail::EmptyArray => Value::new_array(),
597            ValueDetail::EmptyObject => Value::new_object(),
598        }
599    }
600}
601
602impl From<Arc<Vec<Value>>> for Value {
603    fn from(value: Arc<Vec<Value>>) -> Self {
604        Self {
605            meta: Meta::new(Meta::ARR_MUT),
606            data: Data {
607                arr_own: ManuallyDrop::new(value),
608            },
609        }
610    }
611}
612
613#[cfg(not(feature = "sort_keys"))]
614impl From<Arc<AHashMap<FastStr, Value>>> for Value {
615    fn from(value: Arc<AHashMap<FastStr, Value>>) -> Self {
616        Self {
617            meta: Meta::new(Meta::OBJ_MUT),
618            data: Data {
619                obj_own: ManuallyDrop::new(value),
620            },
621        }
622    }
623}
624
625#[cfg(feature = "sort_keys")]
626impl From<Arc<BTreeMap<FastStr, Value>>> for Value {
627    fn from(value: Arc<BTreeMap<FastStr, Value>>) -> Self {
628        Self {
629            meta: Meta::new(Meta::OBJ_MUT),
630            data: Data {
631                obj_own: ManuallyDrop::new(value),
632            },
633        }
634    }
635}
636
637impl Debug for Value {
638    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
639        write!(f, "{:?}", self.as_ref2())?;
640        Ok(())
641    }
642}
643
644impl Default for Value {
645    fn default() -> Self {
646        Value::new()
647    }
648}
649
650impl Value {
651    /// Convert into `Object`. If the value is not an object, return `None`.
652    #[inline]
653    pub fn into_object(self) -> Option<Object> {
654        if self.is_object() {
655            Some(Object(self))
656        } else {
657            None
658        }
659    }
660
661    /// Convert into `Array`. If the value is not an array, return `None`.
662    #[inline]
663    pub fn into_array(self) -> Option<Array> {
664        if self.is_array() {
665            Some(Array(self))
666        } else {
667            None
668        }
669    }
670}
671
672impl Display for Value {
673    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
674        write!(f, "{}", crate::to_string(self).expect("invalid value"))
675    }
676}
677
678impl Debug for Data {
679    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
680        unsafe {
681            match self.parent {
682                0 => write!(f, "parent: null"),
683                _ => write!(f, "parent: {}", self.parent),
684            }
685        }
686    }
687}
688
689impl super::value_trait::JsonValueTrait for Value {
690    type ValueType<'v>
691        = &'v Value
692    where
693        Self: 'v;
694
695    #[inline]
696    fn get_type(&self) -> JsonType {
697        let typ = match self.get_enum() {
698            ValueRefInner::Null => JsonType::Null,
699            ValueRefInner::Bool(_) => JsonType::Boolean,
700            ValueRefInner::Number(_) => JsonType::Number,
701            ValueRefInner::Str(_) => JsonType::String,
702            ValueRefInner::Array(_) => JsonType::Array,
703            ValueRefInner::Object(_) | ValueRefInner::ObjectOwned(_) => JsonType::Object,
704            ValueRefInner::RawNum(_) => JsonType::Number,
705            ValueRefInner::EmptyArray => JsonType::Array,
706            ValueRefInner::EmptyObject => JsonType::Object,
707        };
708        typ
709    }
710
711    #[inline]
712    fn as_number(&self) -> Option<Number> {
713        match self.get_enum() {
714            ValueRefInner::Number(s) => Some(s),
715            ValueRefInner::RawNum(s) => crate::from_str(s).ok(),
716            _ => None,
717        }
718    }
719
720    fn as_raw_number(&self) -> Option<RawNumber> {
721        match self.unpack_ref() {
722            ValueDetail::RawNumFasStr(s) => Some(RawNumber::from_faststr(s.clone())),
723            ValueDetail::NodeInDom(indom) | ValueDetail::Root(indom) => match indom.get_inner() {
724                ValueRefInner::RawNum(s) => Some(RawNumber::new(s)),
725                _ => None,
726            },
727            _ => None,
728        }
729    }
730
731    #[inline]
732    fn as_i64(&self) -> Option<i64> {
733        self.as_number().and_then(|num| num.as_i64())
734    }
735
736    #[inline]
737    fn as_u64(&self) -> Option<u64> {
738        self.as_number().and_then(|num| num.as_u64())
739    }
740
741    #[inline]
742    fn as_f64(&self) -> Option<f64> {
743        self.as_number().and_then(|num| num.as_f64())
744    }
745
746    #[inline]
747    fn as_bool(&self) -> Option<bool> {
748        match self.meta.get_type() {
749            Meta::TRUE => Some(true),
750            Meta::FALSE => Some(false),
751            _ => None,
752        }
753    }
754
755    #[inline]
756    fn as_str(&self) -> Option<&str> {
757        match self.as_ref2() {
758            ValueRefInner::Str(s) => Some(s),
759            _ => None,
760        }
761    }
762
763    #[inline]
764    fn pointer<P: IntoIterator>(&self, path: P) -> Option<Self::ValueType<'_>>
765    where
766        P::Item: Index,
767    {
768        let path = path.into_iter();
769        let mut value = self;
770        for index in path {
771            value = value.get(index)?;
772        }
773        Some(value)
774    }
775
776    #[inline]
777    fn get<I: Index>(&self, index: I) -> Option<Self::ValueType<'_>> {
778        index.value_index_into(self)
779    }
780}
781
782impl JsonContainerTrait for Value {
783    type ArrayType = Array;
784    type ObjectType = Object;
785
786    #[inline]
787    fn as_array(&self) -> Option<&Self::ArrayType> {
788        if self.is_array() {
789            Some(Self::ArrayType::ref_cast(self))
790        } else {
791            None
792        }
793    }
794
795    #[inline]
796    fn as_object(&self) -> Option<&Self::ObjectType> {
797        if self.is_object() {
798            Some(Self::ObjectType::ref_cast(self))
799        } else {
800            None
801        }
802    }
803}
804
805impl JsonValueMutTrait for Value {
806    type ValueType = Value;
807    type ArrayType = Array;
808    type ObjectType = Object;
809
810    #[inline]
811    fn as_object_mut(&mut self) -> Option<&mut Self::ObjectType> {
812        if self.is_object() {
813            self.to_mut();
814            Some(Self::ObjectType::ref_cast_mut(self))
815        } else {
816            None
817        }
818    }
819
820    #[inline]
821    fn as_array_mut(&mut self) -> Option<&mut Self::ArrayType> {
822        if self.is_array() {
823            self.to_mut();
824            Some(Self::ArrayType::ref_cast_mut(self))
825        } else {
826            None
827        }
828    }
829
830    #[inline]
831    fn pointer_mut<P: IntoIterator>(&mut self, path: P) -> Option<&mut Self::ValueType>
832    where
833        P::Item: Index,
834    {
835        let mut path = path.into_iter();
836        let mut value = self.get_mut(path.next().unwrap())?;
837        for index in path {
838            value = value.get_mut(index)?;
839        }
840        Some(value)
841    }
842
843    #[inline]
844    fn get_mut<I: Index>(&mut self, index: I) -> Option<&mut Self::ValueType> {
845        index.index_into_mut(self)
846    }
847}
848
849impl Value {
850    const PADDING_SIZE: usize = 64;
851    pub(crate) const HEAD_NODE_COUNT: usize = 1;
852
853    /// Create a new `null` Value. It is also the default value of `Value`.
854    #[inline]
855    pub const fn new() -> Self {
856        Value {
857            // without shared allocator
858            meta: Meta::new(Meta::NULL),
859            data: Data { uval: 0 },
860        }
861    }
862
863    /// Create a reference `ValueRef` from a `&Value`.
864    ///
865    /// # Example
866    ///
867    /// ```
868    /// use sonic_rs::{ValueRef, json, JsonValueTrait};
869    ///
870    /// let v = json!({
871    ///    "name": "Xiaoming",
872    ///    "age": 18,
873    /// });
874    ///
875    /// match v.as_ref() {
876    ///     ValueRef::Object(obj) => {
877    ///        assert_eq!(obj.get(&"name").unwrap().as_str().unwrap(), "Xiaoming");
878    ///        assert_eq!(obj.get(&"age").unwrap().as_i64().unwrap(), 18);
879    ///    },
880    ///    _ => unreachable!(),
881    /// }
882    /// ```
883    #[inline]
884    pub fn as_ref(&self) -> ValueRef<'_> {
885        match self.get_enum() {
886            ValueRefInner::Null => ValueRef::Null,
887            ValueRefInner::Bool(b) => ValueRef::Bool(b),
888            ValueRefInner::Number(n) => ValueRef::Number(n),
889            ValueRefInner::Str(s) => ValueRef::String(s),
890            ValueRefInner::Array(_) | ValueRefInner::EmptyArray => {
891                ValueRef::Array(self.as_array().unwrap())
892            }
893            ValueRefInner::Object(_)
894            | ValueRefInner::EmptyObject
895            | ValueRefInner::ObjectOwned(_) => ValueRef::Object(self.as_object().unwrap()),
896            ValueRefInner::RawNum(raw) => {
897                crate::from_str(raw).map_or(ValueRef::Null, ValueRef::Number)
898            }
899        }
900    }
901
902    #[inline]
903    pub(crate) fn as_ref2(&self) -> ValueRefInner<'_> {
904        self.get_enum()
905    }
906
907    /// Create a new string Value from a `&'static str` with zero-copy.
908    ///
909    /// # Example
910    /// ```
911    /// use sonic_rs::{array, JsonValueTrait, Value};
912    ///
913    /// let s = "hello";
914    /// let v1 = Value::from_static_str("hello");
915    /// assert_eq!(v1.as_str().unwrap().as_ptr(), s.as_ptr());
916    ///
917    /// let v2 = v1.clone();
918    /// assert_eq!(v1.as_str().unwrap().as_ptr(), v2.as_str().unwrap().as_ptr());
919    /// ```
920    #[inline]
921    pub fn from_static_str(val: &'static str) -> Self {
922        if val.len() >= (u32::MAX as usize) {
923            return Value {
924                meta: Meta::new(Meta::FASTSTR),
925                data: Data {
926                    str_own: ManuallyDrop::new(Box::new(FastStr::new(val))),
927                },
928            };
929        }
930
931        Value {
932            meta: Meta::pack_static_str(Meta::STATIC_STR, val.len()),
933            data: Data {
934                static_str: unsafe { NonNull::from(&*val.as_ptr()) },
935            },
936        }
937    }
938
939    #[doc(hidden)]
940    #[inline]
941    pub fn new_u64(val: u64) -> Self {
942        Value {
943            meta: Meta::new(Meta::U64),
944            data: Data { uval: val },
945        }
946    }
947
948    #[doc(hidden)]
949    #[inline]
950    pub fn new_i64(ival: i64) -> Self {
951        Value {
952            meta: Meta::new(Meta::I64),
953            data: Data { ival },
954        }
955    }
956
957    #[doc(hidden)]
958    #[inline]
959    pub(crate) unsafe fn new_f64_unchecked(fval: f64) -> Self {
960        Value {
961            meta: Meta::new(Meta::F64),
962            data: Data { fval },
963        }
964    }
965
966    #[doc(hidden)]
967    #[inline]
968    pub fn new_f64(fval: f64) -> Option<Self> {
969        if fval.is_finite() {
970            Some(Value {
971                meta: Meta::new(Meta::F64),
972                data: Data { fval },
973            })
974        } else {
975            None
976        }
977    }
978
979    #[doc(hidden)]
980    #[inline]
981    pub fn new_null() -> Self {
982        Value {
983            meta: Meta::new(Meta::NULL),
984            data: Data { uval: 0 },
985        }
986    }
987
988    #[doc(hidden)]
989    #[inline]
990    pub const fn new_array() -> Self {
991        Value {
992            meta: Meta::new(Meta::EMPTY_ARR),
993            data: Data { uval: 0 },
994        }
995    }
996
997    #[doc(hidden)]
998    #[inline]
999    pub const fn new_object() -> Self {
1000        Value {
1001            meta: Meta::new(Meta::EMPTY_OBJ),
1002            data: Data { uval: 0 },
1003        }
1004    }
1005
1006    #[doc(hidden)]
1007    #[inline]
1008    pub fn new_array_with(capacity: usize) -> Self {
1009        let arr_own = ManuallyDrop::new(Arc::new(Vec::<Value>::with_capacity(capacity)));
1010        Value {
1011            meta: Meta::new(Meta::ARR_MUT),
1012            data: Data { arr_own },
1013        }
1014    }
1015
1016    #[doc(hidden)]
1017    #[inline]
1018    pub fn new_bool(val: bool) -> Self {
1019        Value {
1020            meta: Meta::new(if val { Meta::TRUE } else { Meta::FALSE }),
1021            data: Data { uval: 0 },
1022        }
1023    }
1024
1025    #[doc(hidden)]
1026    #[inline]
1027    pub fn pack_str(kind: u64, idx: usize, val: &str) -> Self {
1028        let node_idx = idx as u32;
1029        // we check the json length when parsing, so val.len() should always be less than u32::MAX
1030        Value {
1031            meta: Meta::pack_dom_node(kind, node_idx, val.len() as u32),
1032            data: Data {
1033                dom_str: unsafe { NonNull::new_unchecked(val.as_ptr() as *mut _) },
1034            },
1035        }
1036    }
1037
1038    #[inline]
1039    pub(crate) fn new_rawnum_faststr(num: &FastStr) -> Self {
1040        let str_own = ManuallyDrop::new(Box::new(num.clone()));
1041        Value {
1042            meta: Meta::new(Meta::RAWNUM_FASTSTR),
1043            data: Data { str_own },
1044        }
1045    }
1046
1047    #[inline]
1048    pub(crate) fn new_rawnum(num: &str) -> Self {
1049        let str_own = ManuallyDrop::new(Box::new(FastStr::new(num)));
1050        Value {
1051            meta: Meta::new(Meta::RAWNUM_FASTSTR),
1052            data: Data { str_own },
1053        }
1054    }
1055
1056    pub(crate) fn len(&self) -> usize {
1057        match self.as_ref2() {
1058            ValueRefInner::Array(arr) => arr.len(),
1059            ValueRefInner::Object(obj) => obj.len(),
1060            ValueRefInner::Str(s) => s.len(),
1061            _ => 0,
1062        }
1063    }
1064
1065    pub(crate) fn as_value_slice(&self) -> Option<&[Value]> {
1066        match self.as_ref2() {
1067            ValueRefInner::Array(s) => Some(s),
1068            ValueRefInner::EmptyArray => Some(&[]),
1069            _ => None,
1070        }
1071    }
1072
1073    pub(crate) fn as_obj_len(&self) -> usize {
1074        match self.as_ref2() {
1075            ValueRefInner::Object(s) => s.len(),
1076            ValueRefInner::EmptyObject => 0,
1077            ValueRefInner::ObjectOwned(s) => s.len(),
1078            _ => unreachable!("value is not object"),
1079        }
1080    }
1081
1082    #[doc(hidden)]
1083    #[inline]
1084    pub fn copy_str(val: &str) -> Self {
1085        let str_own = ManuallyDrop::new(Box::new(FastStr::new(val)));
1086        Value {
1087            meta: Meta::new(Meta::FASTSTR),
1088            data: Data { str_own },
1089        }
1090    }
1091
1092    #[doc(hidden)]
1093    #[inline]
1094    pub fn copy_str_in(kind: u64, val: &str, idx: usize, shared: &mut Shared) -> Self {
1095        let str = shared.get_alloc().alloc_str(val);
1096        let node_idx = idx as u32;
1097        // we check the json length when parsing, so val.len() should always be less than u32::MAX
1098        Value {
1099            meta: Meta::pack_dom_node(kind, node_idx, str.len() as u32),
1100            data: Data {
1101                dom_str: unsafe { NonNull::new_unchecked(str.as_ptr() as *mut _) },
1102            },
1103        }
1104    }
1105
1106    #[doc(hidden)]
1107    #[inline]
1108    pub fn new_faststr(val: FastStr) -> Self {
1109        let str_own = ManuallyDrop::new(Box::new(val));
1110        Value {
1111            meta: Meta::new(Meta::FASTSTR),
1112            data: Data { str_own },
1113        }
1114    }
1115
1116    #[doc(hidden)]
1117    pub fn new_object_with(
1118        #[cfg(not(feature = "sort_keys"))] capacity: usize,
1119        #[cfg(feature = "sort_keys")] _: usize,
1120    ) -> Self {
1121        let obj_own = ManuallyDrop::new(Arc::new(
1122            #[cfg(not(feature = "sort_keys"))]
1123            AHashMap::with_capacity(capacity),
1124            #[cfg(feature = "sort_keys")]
1125            BTreeMap::new(),
1126        ));
1127        Value {
1128            meta: Meta::new(Meta::OBJ_MUT),
1129            data: Data { obj_own },
1130        }
1131    }
1132
1133    pub(crate) fn get_index(&self, index: usize) -> Option<&Self> {
1134        debug_assert!(self.is_array(), "{self:?}");
1135        if let ValueRefInner::Array(s) = self.as_ref2() {
1136            if index < s.len() {
1137                return Some(&s[index]);
1138            }
1139        }
1140        None
1141    }
1142
1143    pub(crate) fn get_index_mut(&mut self, index: usize) -> Option<&mut Self> {
1144        debug_assert!(self.is_array());
1145        if let ValueMut::Array(s) = self.as_mut() {
1146            if index < s.len() {
1147                return Some(&mut s[index]);
1148            }
1149        }
1150        None
1151    }
1152
1153    #[inline]
1154    pub(crate) fn get_key(&self, key: &str) -> Option<&Self> {
1155        self.get_key_value(key).map(|(_, v)| v)
1156    }
1157
1158    pub(crate) fn get_key_value(&self, key: &str) -> Option<(&str, &Self)> {
1159        debug_assert!(self.is_object());
1160        let ref_inner = self.as_ref2();
1161        if let ValueRefInner::Object(kv) = ref_inner {
1162            for (k, v) in kv {
1163                let k = k.as_str().expect("key is not string");
1164                if k == key {
1165                    return Some((k, v));
1166                }
1167            }
1168        } else if let ValueRefInner::ObjectOwned(kv) = ref_inner {
1169            if let Some((k, v)) = kv.get_key_value(key) {
1170                return Some((k.as_str(), v));
1171            }
1172        }
1173        None
1174    }
1175
1176    #[inline]
1177    pub(crate) fn get_key_mut(&mut self, key: &str) -> Option<&mut Self> {
1178        if let ValueMut::Object(kv) = self.as_mut() {
1179            if let Some(v) = kv.get_mut(key) {
1180                return Some(v);
1181            }
1182        }
1183        None
1184    }
1185
1186    #[inline]
1187    pub(crate) fn capacity(&self) -> usize {
1188        debug_assert!(self.is_object() || self.is_array());
1189        match self.unpack_ref() {
1190            ValueDetail::Array(arr) => arr.capacity(),
1191            #[cfg(not(feature = "sort_keys"))]
1192            ValueDetail::Object(obj) => obj.capacity(),
1193            #[cfg(feature = "sort_keys")]
1194            ValueDetail::Object(obj) => obj.len(),
1195            ValueDetail::NodeInDom(indom) | ValueDetail::Root(indom) => {
1196                if self.is_object() {
1197                    indom.unpack_pair_slice().len()
1198                } else {
1199                    indom.unpack_value_slice().len()
1200                }
1201            }
1202            ValueDetail::EmptyArray | ValueDetail::EmptyObject => 0,
1203            _ => unreachable!("value is not array or object"),
1204        }
1205    }
1206
1207    #[inline]
1208    pub(crate) fn clear(&mut self) {
1209        debug_assert!(self.is_object() || self.is_array());
1210        match self.as_mut() {
1211            ValueMut::Array(arr) => arr.clear(),
1212            ValueMut::Object(obj) => obj.clear(),
1213            _ => unreachable!("value is not array or object"),
1214        }
1215    }
1216
1217    #[inline]
1218    pub(crate) fn remove_index(&mut self, index: usize) -> Value {
1219        debug_assert!(self.is_array());
1220        match self.as_mut() {
1221            ValueMut::Array(arr) => arr.remove(index),
1222            _ => unreachable!("value is not array"),
1223        }
1224    }
1225
1226    #[inline]
1227    pub(crate) fn remove_key(&mut self, k: &str) -> Option<Value> {
1228        debug_assert!(self.is_object());
1229        match self.as_mut() {
1230            ValueMut::Object(obj) => obj.remove(k),
1231            _ => unreachable!("value is not object"),
1232        }
1233    }
1234
1235    /// Take the value from the node, and set the node as a empty node.
1236    /// Take will creat a new root node.
1237    ///
1238    /// # Examples
1239    /// ```
1240    /// use sonic_rs::json;
1241    /// use sonic_rs::JsonValueTrait;
1242    ///
1243    /// let mut value = json!({"a": 123});
1244    /// assert_eq!(value.take()["a"], 123);
1245    /// assert!(value.is_null());
1246    ///
1247    /// let mut value = json!(null);
1248    /// assert!(value.take().is_null());
1249    /// assert!(value.is_null());
1250    /// ```
1251    #[inline]
1252    pub fn take(&mut self) -> Self {
1253        std::mem::take(self)
1254    }
1255
1256    #[inline]
1257    pub(crate) fn reserve<T>(&mut self, additional: usize) {
1258        debug_assert!(self.is_object() || self.is_array());
1259        debug_assert!(size_of::<T>() == size_of::<Value>() || size_of::<T>() == size_of::<Pair>());
1260        match self.as_mut() {
1261            ValueMut::Array(arr) => arr.reserve(additional),
1262            #[cfg(not(feature = "sort_keys"))]
1263            ValueMut::Object(obj) => obj.reserve(additional),
1264            #[cfg(feature = "sort_keys")]
1265            ValueMut::Object(_) => {}
1266            _ => unreachable!("value is not array or object"),
1267        }
1268    }
1269
1270    #[doc(hidden)]
1271    #[inline]
1272    pub fn append_value(&mut self, val: Value) -> &mut Value {
1273        debug_assert!(self.is_array());
1274        match self.as_mut() {
1275            ValueMut::Array(arr) => {
1276                arr.push(val);
1277                let len = arr.len();
1278                &mut arr[len - 1]
1279            }
1280            _ => unreachable!("value is not array"),
1281        }
1282    }
1283
1284    #[doc(hidden)]
1285    #[inline]
1286    pub fn insert(&mut self, key: &str, val: Value) -> &mut Value {
1287        debug_assert!(self.is_object());
1288        match self.as_mut() {
1289            ValueMut::Object(obj) => {
1290                obj.insert(FastStr::new(key), val);
1291                obj.get_mut(key).unwrap()
1292            }
1293            _ => unreachable!("value is not object"),
1294        }
1295    }
1296
1297    #[inline]
1298    pub(crate) fn pop(&mut self) -> Option<Value> {
1299        debug_assert!(self.is_array());
1300        match self.as_mut() {
1301            ValueMut::Array(arr) => arr.pop(),
1302            _ => unreachable!("value is not object"),
1303        }
1304    }
1305
1306    #[inline(never)]
1307    pub(crate) fn parse_with_padding(&mut self, json: &[u8], cfg: DeserializeCfg) -> Result<usize> {
1308        // allocate the padding buffer for the input json
1309        let mut shared = Arc::new(Shared::default());
1310        let mut buffer = Vec::with_capacity(json.len() + Self::PADDING_SIZE);
1311        buffer.extend_from_slice(json);
1312        buffer.extend_from_slice(&b"x\"x"[..]);
1313        buffer.extend_from_slice(&[0; 61]);
1314
1315        let smut = Arc::get_mut(&mut shared).unwrap();
1316        let slice = PaddedSliceRead::new(buffer.as_mut_slice(), json);
1317        let mut parser = Parser::new(slice).with_config(cfg);
1318        let mut vis = DocumentVisitor::new(json.len(), smut);
1319        parser.parse_dom(&mut vis)?;
1320        let idx = parser.read.index();
1321
1322        // NOTE: root node should is the first node
1323        *self = unsafe { vis.root.as_ref().clone() };
1324        smut.set_json(buffer);
1325        Ok(idx)
1326    }
1327
1328    #[inline(never)]
1329    pub(crate) fn parse_without_padding<'de, R: Reader<'de>>(
1330        &mut self,
1331        shared: &mut Shared,
1332        strbuf: &mut Vec<u8>,
1333        parser: &mut Parser<R>,
1334    ) -> Result<()> {
1335        let remain_len = parser.read.remain();
1336        let mut vis = DocumentVisitor::new(remain_len, shared);
1337        parser.parse_dom2(&mut vis, strbuf)?;
1338        *self = unsafe { vis.root.as_ref().clone() };
1339        Ok(())
1340    }
1341}
1342
1343// a simple wrapper for visitor
1344pub(crate) struct DocumentVisitor<'a> {
1345    pub(crate) shared: &'a mut Shared,
1346    pub(crate) buf: TlsBuf,
1347    pub(crate) parent: usize,
1348    pub(crate) nodes_start: usize,
1349    pub(crate) root: NonNull<Value>,
1350}
1351
1352impl<'a> DocumentVisitor<'a> {
1353    fn new(json_len: usize, shared: &'a mut Shared) -> Self {
1354        // optimize: use a pre-allocated vec.
1355        // If json is valid, the max number of value nodes should be
1356        // half of the valid json length + 2. like as [1,2,3,1,2,3...]
1357        // if the capacity is not enough, we will return a error.
1358        let max_len = (json_len / 2) + 2;
1359        let buf = TlsBuf::with_capacity(max_len);
1360        DocumentVisitor {
1361            shared,
1362            buf,
1363            parent: 0,
1364            nodes_start: 0,
1365            root: NonNull::dangling(),
1366        }
1367    }
1368
1369    fn nodes(&mut self) -> &mut Vec<ManuallyDrop<Value>> {
1370        unsafe { NonNull::new_unchecked(self.buf.as_vec_mut() as *mut _).as_mut() }
1371    }
1372
1373    fn index(&mut self) -> usize {
1374        self.nodes().len() - self.parent
1375    }
1376}
1377
1378#[repr(C)]
1379struct MetaNode {
1380    shared: *const Shared,
1381    canary: u64,
1382}
1383
1384impl MetaNode {
1385    fn new(shared: *const Shared) -> Self {
1386        let canary = b"SONICRS\0";
1387        MetaNode {
1388            shared,
1389            canary: u64::from_ne_bytes(*canary),
1390        }
1391    }
1392
1393    fn canary(&self) -> bool {
1394        self.canary == u64::from_ne_bytes(*b"SONICRS\0")
1395    }
1396}
1397
1398impl<'a> DocumentVisitor<'a> {
1399    fn visit_container_start(&mut self, kind: u64) -> bool {
1400        let ret = self.push_node(Value {
1401            meta: Meta::pack_dom_node(kind, 0, 0), // update when array ending
1402            data: Data {
1403                parent: self.parent as u64, // record the old parent offset
1404            },
1405        });
1406        let len = self.nodes().len();
1407        self.parent = len - 1;
1408        ret
1409    }
1410
1411    // the array and object's logic is same.
1412    fn visit_container_end(&mut self, kind: u64, len: usize) -> bool {
1413        let vis = self;
1414        let parent = vis.parent;
1415        let old = unsafe { vis.nodes()[parent].data.parent as usize };
1416
1417        vis.parent = old;
1418        if len == 0 {
1419            let container = &mut vis.nodes()[parent];
1420            container.meta = Meta::new(if kind == Meta::OBJ_NODE {
1421                Meta::EMPTY_OBJ
1422            } else {
1423                Meta::EMPTY_ARR
1424            });
1425            return true;
1426        }
1427        unsafe {
1428            // not use `len` in here
1429            let visited_children = &vis.nodes()[(parent + 1)..];
1430            let real_count = visited_children.len() + Value::HEAD_NODE_COUNT;
1431            let layout = Layout::array::<Value>(real_count).unwrap();
1432            let hdr =
1433                vis.shared.get_alloc().alloc_layout(layout).as_ptr() as *mut ManuallyDrop<Value>;
1434
1435            // copy visited nodes into document
1436            let visited_children = &vis.nodes()[(parent + 1)..];
1437            let src = visited_children.as_ptr();
1438            let elems = hdr.add(Value::HEAD_NODE_COUNT);
1439            std::ptr::copy_nonoverlapping(src, elems, visited_children.len());
1440
1441            // record the `Shared` pointer
1442            let meta = &mut *(hdr as *mut MetaNode);
1443            meta.shared = vis.shared as *const _;
1444            meta.canary = u64::from_ne_bytes(*b"SONICRS\0");
1445
1446            // update the container header
1447            let idx = (parent - vis.parent) as u32;
1448            let container = &mut vis.nodes()[parent];
1449            container.meta = Meta::pack_dom_node(kind, idx, len as u32);
1450            container.data.arr_elems = NonNull::new_unchecked(elems as *mut _);
1451            // must reset the length, because we copy the children into bumps
1452            vis.nodes().set_len(parent + 1);
1453        }
1454        true
1455    }
1456
1457    fn visit_root(&mut self) {
1458        // should alloc root node in the bump allocator
1459        let start = self.nodes_start;
1460        let (rm, ru) = unsafe { (self.nodes()[start].meta, self.nodes()[start].data.uval) };
1461        let ptr = self.shared as *const _;
1462        let (_, root) = self
1463            .shared
1464            .get_alloc()
1465            .alloc((MetaNode::new(ptr), Value::default()));
1466
1467        // copy visited nodes into document
1468        root.meta = rm;
1469        root.data.uval = ru;
1470        self.root = NonNull::from(root);
1471    }
1472
1473    #[inline(always)]
1474    fn push_node(&mut self, node: Value) -> bool {
1475        if self.nodes().len() == self.nodes().capacity() {
1476            false
1477        } else {
1478            self.nodes().push(ManuallyDrop::new(node));
1479            true
1480        }
1481    }
1482
1483    #[inline(always)]
1484    fn push_meta(&mut self, node: MetaNode) -> bool {
1485        if self.nodes().len() == self.nodes().capacity() {
1486            false
1487        } else {
1488            self.nodes().push(ManuallyDrop::new(unsafe {
1489                transmute::<MetaNode, Value>(node)
1490            }));
1491            true
1492        }
1493    }
1494}
1495
1496impl<'de, 'a> JsonVisitor<'de> for DocumentVisitor<'a> {
1497    #[inline(always)]
1498    fn visit_dom_start(&mut self) -> bool {
1499        let shared = self.shared as *mut _ as *const _;
1500        self.push_meta(MetaNode::new(shared));
1501        self.nodes_start = self.nodes().len();
1502        assert_eq!(self.nodes().len(), 1);
1503        true
1504    }
1505
1506    #[inline(always)]
1507    fn visit_bool(&mut self, val: bool) -> bool {
1508        self.push_node(Value::new_bool(val))
1509    }
1510
1511    #[inline(always)]
1512    fn visit_f64(&mut self, val: f64) -> bool {
1513        // # Safety
1514        // we have checked the f64 in parsing number.
1515        let node = unsafe { Value::new_f64_unchecked(val) };
1516        self.push_node(node)
1517    }
1518
1519    #[inline(always)]
1520    fn visit_raw_number(&mut self, val: &str) -> bool {
1521        let idx = self.index();
1522        let node = Value::copy_str_in(Meta::RAWNUM_NODE, val, idx, self.shared);
1523        self.push_node(node)
1524    }
1525
1526    #[inline(always)]
1527    fn visit_borrowed_raw_number(&mut self, val: &str) -> bool {
1528        let idx = self.index();
1529        self.push_node(Value::pack_str(Meta::RAWNUM_NODE, idx, val))
1530    }
1531
1532    #[inline(always)]
1533    fn visit_i64(&mut self, val: i64) -> bool {
1534        self.push_node(Value::new_i64(val))
1535    }
1536
1537    #[inline(always)]
1538    fn visit_u64(&mut self, val: u64) -> bool {
1539        self.push_node(Value::new_u64(val))
1540    }
1541
1542    #[inline(always)]
1543    fn visit_array_start(&mut self, _hint: usize) -> bool {
1544        self.visit_container_start(Meta::ARR_NODE)
1545    }
1546
1547    #[inline(always)]
1548    fn visit_array_end(&mut self, len: usize) -> bool {
1549        self.visit_container_end(Meta::ARR_NODE, len)
1550    }
1551
1552    #[inline(always)]
1553    fn visit_object_start(&mut self, _hint: usize) -> bool {
1554        self.visit_container_start(Meta::OBJ_NODE)
1555    }
1556
1557    #[inline(always)]
1558    fn visit_object_end(&mut self, len: usize) -> bool {
1559        self.visit_container_end(Meta::OBJ_NODE, len)
1560    }
1561
1562    #[inline(always)]
1563    fn visit_null(&mut self) -> bool {
1564        self.push_node(Value::new_null())
1565    }
1566
1567    // this api should never used for parsing with padding buffer
1568    #[inline(always)]
1569    fn visit_str(&mut self, val: &str) -> bool {
1570        let idx = self.index();
1571        let node = Value::copy_str_in(Meta::STR_NODE, val, idx, self.shared);
1572        self.push_node(node)
1573    }
1574
1575    #[inline(always)]
1576    fn visit_borrowed_str(&mut self, val: &'de str) -> bool {
1577        let idx = self.index();
1578        self.push_node(Value::pack_str(Meta::STR_NODE, idx, val))
1579    }
1580
1581    #[inline(always)]
1582    fn visit_key(&mut self, key: &str) -> bool {
1583        self.visit_str(key)
1584    }
1585
1586    #[inline(always)]
1587    fn visit_borrowed_key(&mut self, key: &'de str) -> bool {
1588        self.visit_borrowed_str(key)
1589    }
1590
1591    fn visit_dom_end(&mut self) -> bool {
1592        self.visit_root();
1593        true
1594    }
1595}
1596
1597impl Serialize for Value {
1598    #[inline]
1599    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
1600    where
1601        S: ::serde::Serializer,
1602    {
1603        match self.as_ref2() {
1604            ValueRefInner::Null => serializer.serialize_unit(),
1605            ValueRefInner::Bool(b) => serializer.serialize_bool(b),
1606            ValueRefInner::Number(n) => n.serialize(serializer),
1607            ValueRefInner::Str(s) => s.serialize(serializer),
1608            ValueRefInner::Array(a) => {
1609                let mut seq = tri!(serializer.serialize_seq(Some(a.len())));
1610                for n in a {
1611                    tri!(seq.serialize_element(n));
1612                }
1613                seq.end()
1614            }
1615            ValueRefInner::EmptyArray => serializer.serialize_seq(None)?.end(),
1616            ValueRefInner::EmptyObject => serializer.serialize_map(None)?.end(),
1617            ValueRefInner::Object(o) => {
1618                #[cfg(feature = "sort_keys")]
1619                {
1620                    // TODO: sort the keys use thread-local buffer
1621                    let mut kvs: Vec<&(Value, Value)> = o.iter().collect();
1622                    kvs.sort_by(|(k1, _), (k2, _)| k1.as_str().unwrap().cmp(k2.as_str().unwrap()));
1623                    let mut map = tri!(serializer.serialize_map(Some(kvs.len())));
1624                    for (k, v) in kvs {
1625                        tri!(map.serialize_key(k.as_str().unwrap()));
1626                        tri!(map.serialize_value(v));
1627                    }
1628                    map.end()
1629                }
1630                #[cfg(not(feature = "sort_keys"))]
1631                {
1632                    let entries = o.iter();
1633                    let mut map = tri!(serializer.serialize_map(Some(entries.len())));
1634                    for (k, v) in entries {
1635                        tri!(map.serialize_key(k.as_str().unwrap()));
1636                        tri!(map.serialize_value(v));
1637                    }
1638                    map.end()
1639                }
1640            }
1641            #[cfg(not(feature = "sort_keys"))]
1642            ValueRefInner::ObjectOwned(o) => {
1643                let mut map = tri!(serializer.serialize_map(Some(o.len())));
1644                for (k, v) in o.iter() {
1645                    tri!(map.serialize_key(k.as_str()));
1646                    tri!(map.serialize_value(v));
1647                }
1648                map.end()
1649            }
1650            #[cfg(feature = "sort_keys")]
1651            ValueRefInner::ObjectOwned(o) => {
1652                let mut map = tri!(serializer.serialize_map(Some(o.len())));
1653                for (k, v) in o.iter() {
1654                    tri!(map.serialize_key(k.as_str()));
1655                    tri!(map.serialize_value(v));
1656                }
1657                map.end()
1658            }
1659            ValueRefInner::RawNum(raw) => {
1660                use serde::ser::SerializeStruct;
1661
1662                use crate::serde::rawnumber::TOKEN;
1663                let mut struct_ = tri!(serializer.serialize_struct(TOKEN, 1));
1664                tri!(struct_.serialize_field(TOKEN, raw));
1665                struct_.end()
1666            }
1667        }
1668    }
1669}
1670
1671#[cfg(test)]
1672mod test {
1673    use std::path::Path;
1674
1675    use super::*;
1676    use crate::{error::make_error, from_slice, from_str, object, pointer, util::mock::MockString};
1677
1678    #[derive(serde::Serialize, serde::Deserialize, Debug, PartialEq)]
1679    struct ValueInStruct {
1680        val: Value,
1681    }
1682
1683    fn test_value_instruct(data: &str) -> Result<()> {
1684        if let Ok(val) = from_str::<Value>(data) {
1685            let valin = ValueInStruct { val: val.clone() };
1686            let out = crate::to_string(&valin)?;
1687            let valin2: ValueInStruct = from_str(&out).unwrap();
1688            if valin2.val != val {
1689                diff_json(data);
1690                return Err(make_error(format!(
1691                    "invalid result when test parse valid json to ValueInStruct {data}"
1692                )));
1693            }
1694        }
1695        Ok(())
1696    }
1697
1698    fn test_value(data: &str) -> Result<()> {
1699        let serde_value: serde_json::Result<serde_json::Value> = serde_json::from_str(data);
1700        let dom: Result<Value> = from_slice(data.as_bytes());
1701
1702        if let Ok(serde_value) = serde_value {
1703            let dom = dom.unwrap();
1704            let sonic_out = crate::to_string(&dom)?;
1705            let serde_value2: serde_json::Value = serde_json::from_str(&sonic_out).unwrap();
1706
1707            if serde_value == serde_value2 {
1708                test_value_instruct(data)?;
1709                Ok(())
1710            } else {
1711                diff_json(data);
1712                Err(make_error(format!("invalid result for valid json {data}")))
1713            }
1714        } else {
1715            if dom.is_err() {
1716                return Ok(());
1717            }
1718            let dom = dom.unwrap();
1719            Err(make_error(format!(
1720                "invalid result for invalid json {}, got {}",
1721                data,
1722                crate::to_string(&dom).unwrap(),
1723            )))
1724        }
1725    }
1726
1727    fn diff_json(data: &str) {
1728        let serde_value: serde_json::Value = serde_json::from_str(data).unwrap();
1729        let dom: Value = from_slice(data.as_bytes()).unwrap();
1730        let sonic_out = crate::to_string(&dom).unwrap();
1731        let serde_value2: serde_json::Value = serde_json::from_str(&sonic_out).unwrap();
1732        let expect = serde_json::to_string_pretty(&serde_value).unwrap();
1733        let got = serde_json::to_string_pretty(&serde_value2).unwrap();
1734
1735        fn write_to(file: &str, data: &str) -> std::io::Result<()> {
1736            use std::io::Write;
1737            let mut file = std::fs::File::create(file)?;
1738            file.write_all(data.as_bytes())?;
1739            Ok(())
1740        }
1741
1742        if serde_value != serde_value2 {
1743            write_to("got.json", &got).unwrap();
1744            write_to("expect.json", &expect).unwrap();
1745        }
1746    }
1747
1748    fn test_value_file(path: &Path) {
1749        let data = std::fs::read_to_string(path).unwrap();
1750        assert!(test_value(&data).is_ok(), "failed json is {path:?}");
1751    }
1752
1753    #[test]
1754    fn test_node_basic() {
1755        // // Valid JSON object
1756        // let data = r#"{"name": "John", "age": 30}"#;
1757        // assert!(test_value(data).is_ok(), "failed json is {}", data);
1758
1759        // // Valid JSON array
1760        // let data = r#"[1, 2, 3]"#;
1761        // assert!(test_value(data).is_ok(), "failed json is {}", data);
1762
1763        // Valid JSON data with nested objects and arrays
1764        let data = r#"{
1765            "name": "John",
1766            "age": 30,
1767            "cars": [
1768                { "name": "Ford", "models": ["Fiesta", "Focus", "Mustang"] },
1769                { "name": "BMW", "models": ["320", "X3", "X5"] },
1770                { "name": "Fiat", "models": ["500", "Panda"] }
1771            ],
1772            "address": {
1773                "street": "Main Street",
1774                "city": "New York",
1775                "state": "NY",
1776                "zip": "10001"
1777            }
1778        }"#;
1779        assert!(test_value(data).is_ok(), "failed json is {data}");
1780
1781        // // Valid JSON data with escape characters
1782        // let data = r#"{
1783        //     "name": "John",
1784        //     "age": 30,
1785        //     "description": "He said, \"I'm coming home.\""
1786        // }"#;
1787        // assert!(test_value(data).is_ok(), "failed json is {}", data);
1788    }
1789
1790    #[test]
1791    #[cfg(not(target_arch = "wasm32"))]
1792    fn test_node_from_files3() {
1793        use std::fs::DirEntry;
1794        let path = env!("CARGO_MANIFEST_DIR").to_string() + "/benchmarks/benches/testdata/";
1795        println!("dir is {path}");
1796
1797        let mut files: Vec<DirEntry> = std::fs::read_dir(path)
1798            .unwrap()
1799            .filter_map(|e| e.ok())
1800            .filter(|e| e.file_type().ok().map(|t| t.is_file()).unwrap_or(false))
1801            .collect();
1802
1803        files.sort_by(|a, b| {
1804            a.metadata()
1805                .unwrap()
1806                .len()
1807                .cmp(&b.metadata().unwrap().len())
1808        });
1809
1810        for file in files {
1811            let path = file.path();
1812            if path.extension().unwrap_or_default() == "json" && !path.ends_with("canada.json") {
1813                println!(
1814                    "test json file: {:?},  {} bytes",
1815                    path,
1816                    file.metadata().unwrap().len()
1817                );
1818                test_value_file(&path)
1819            }
1820        }
1821    }
1822
1823    #[test]
1824    fn test_json_tralings() {
1825        let testdata = [
1826            "-0.99999999999999999xxx",
1827            "\"\"\"",
1828            "{} x",
1829            "\"xxxxx",
1830            r#""\uDBDD\u1DD000"#,
1831        ];
1832
1833        for data in testdata {
1834            let ret: Result<Value> = from_slice(data.as_bytes());
1835            assert!(ret.is_err(), "failed json is {data}");
1836        }
1837    }
1838
1839    #[test]
1840    fn test_parse_numbrs() {
1841        let testdata = [
1842            " 33.3333333043333333",
1843            " 33.3333333053333333 ",
1844            " 33.3333333043333333--",
1845            &f64::MAX.to_string(),
1846            &f64::MIN.to_string(),
1847            &u64::MAX.to_string(),
1848            &u64::MIN.to_string(),
1849            &i64::MIN.to_string(),
1850            &i64::MAX.to_string(),
1851        ];
1852        for data in testdata {
1853            test_value(data).unwrap();
1854        }
1855    }
1856
1857    #[cfg(not(feature = "utf8_lossy"))]
1858    #[test]
1859    fn test_parse_escaped() {
1860        let testdata = [
1861            r#""\\9,\ud9CC\u8888|""#,
1862            r#"{"\t:0000000006427[{\t:003E:[[{0.77":96}"#,
1863        ];
1864        for data in testdata {
1865            test_value(data).unwrap();
1866        }
1867    }
1868
1869    const TEST_JSON: &str = r#"{
1870        "bool": true,
1871        "int": -1,
1872        "uint": 0,
1873        "float": 1.1,
1874        "string": "hello",
1875        "array": [1,2,3],
1876        "object": {"a":"aaa"},
1877        "strempty": "",
1878        "objempty": {},
1879        "arrempty": []
1880    }"#;
1881
1882    #[test]
1883    fn test_value_is() {
1884        let value: Value = crate::from_str(TEST_JSON).unwrap();
1885        assert!(value.get("bool").is_boolean());
1886        assert!(value.get("bool").is_true());
1887        assert!(value.get("uint").is_u64());
1888        assert!(value.get("uint").is_number());
1889        assert!(value.get("int").is_i64());
1890        assert!(value.get("float").is_f64());
1891        assert!(value.get("string").is_str());
1892        assert!(value.get("array").is_array());
1893        assert!(value.get("object").is_object());
1894        assert!(value.get("strempty").is_str());
1895        assert!(value.get("objempty").is_object());
1896        assert!(value.get("arrempty").is_array());
1897    }
1898
1899    #[test]
1900    fn test_value_get() {
1901        let value: Value = crate::from_str(TEST_JSON).unwrap();
1902        assert_eq!(value.get("int").as_i64().unwrap(), -1);
1903        assert_eq!(value["array"].get(0).as_i64().unwrap(), 1);
1904
1905        assert_eq!(value.pointer(pointer!["array", 2]).as_u64().unwrap(), 3);
1906        assert_eq!(
1907            value.pointer(pointer!["object", "a"]).as_str().unwrap(),
1908            "aaa"
1909        );
1910        assert_eq!(value.pointer(pointer!["objempty", "a"]).as_str(), None);
1911
1912        assert_eq!(value.pointer(pointer!["arrempty", 1]).as_str(), None);
1913
1914        assert!(!value.pointer(pointer!["unknown"]).is_str());
1915    }
1916
1917    #[cfg(not(feature = "utf8_lossy"))]
1918    #[test]
1919    fn test_invalid_utf8() {
1920        use crate::{from_slice, from_slice_unchecked};
1921
1922        let data = [b'"', 0x80, 0x90, b'"'];
1923        let ret: Result<Value> = from_slice(&data);
1924        assert_eq!(
1925            ret.err().unwrap().to_string(),
1926            "Invalid UTF-8 characters in json at line 1 column 2\n\n\t\"��\"\n\t.^..\n"
1927        );
1928
1929        let dom: Result<Value> = unsafe { from_slice_unchecked(&data) };
1930        assert!(dom.is_ok(), "{}", dom.unwrap_err());
1931
1932        let data = [b'"', b'"', 0x80];
1933        let dom: Result<Value> = from_slice(&data);
1934        assert_eq!(
1935            dom.err().unwrap().to_string(),
1936            "Invalid UTF-8 characters in json at line 1 column 3\n\n\t\"\"�\n\t..^\n"
1937        );
1938
1939        let data = [0x80, b'"', b'"'];
1940        let dom: Result<Value> = unsafe { from_slice_unchecked(&data) };
1941        assert_eq!(
1942            dom.err().unwrap().to_string(),
1943            "Invalid JSON value at line 1 column 1\n\n\t�\"\"\n\t^..\n"
1944        );
1945    }
1946
1947    #[test]
1948    fn test_value_serde() {
1949        use serde::{Deserialize, Serialize};
1950
1951        use crate::{array, object};
1952        #[derive(Deserialize, Debug, Serialize, PartialEq)]
1953        struct Foo {
1954            value: Value,
1955            object: Object,
1956            array: Array,
1957        }
1958
1959        let foo: Foo = crate::from_str(&MockString::from(
1960            r#"
1961        {
1962            "value": "hello",
1963            "object": {"a": "b"},
1964            "array": [1,2,3]
1965        }"#,
1966        ))
1967        .unwrap();
1968
1969        assert_eq!(
1970            foo,
1971            Foo {
1972                value: Value::from("hello"),
1973                object: object! {"a": "b"},
1974                array: array![1, 2, 3],
1975            }
1976        );
1977
1978        let _ = crate::from_str::<Foo>(
1979            r#"{
1980                "value": "hello",
1981                "object": {"a": "b"},
1982                "array": [1,2,3
1983            }"#,
1984        )
1985        .unwrap_err();
1986    }
1987
1988    #[test]
1989    fn test_arbitrary_precision() {
1990        use crate::Deserializer;
1991
1992        let nums = [
1993            "-46333333333333333333333333333333.6",
1994            "43.420273000",
1995            "1e123",
1996            "0.001","0e+12","0.1e+12",
1997            "0", "0.0", "1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345e+1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345",
1998            "12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123",
1999         "1.23456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567e89012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123",
2000        "-0.000000023456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567e+89012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123",
2001        ];
2002
2003        for num in nums {
2004            let mut de = Deserializer::from_str(num).use_rawnumber();
2005            let value: Value = de.deserialize().unwrap();
2006            assert_eq!(value.as_raw_number().unwrap().as_str(), num);
2007            assert_eq!(value.to_string(), num);
2008        }
2009    }
2010
2011    #[cfg(feature = "sort_keys")]
2012    #[test]
2013    fn test_sort_keys() {
2014        struct Case<'a> {
2015            input: &'a str,
2016            output: &'a str,
2017        }
2018
2019        let cases = [
2020            Case {
2021                input: r#"{"b": 2,"bc":{"cb":1,"ca":"hello"},"a": 1}"#,
2022                output: r#"{"a":1,"b":2,"bc":{"ca":"hello","cb":1}}"#,
2023            },
2024            Case {
2025                input: r#"{"a":1}"#,
2026                output: r#"{"a":1}"#,
2027            },
2028            Case {
2029                input: r#"{"b": 2,"a": 1}"#,
2030                output: r#"{"a":1,"b":2}"#,
2031            },
2032            Case {
2033                input: "{}",
2034                output: "{}",
2035            },
2036            Case {
2037                input: r#"[{"b": 2,"c":{"cb":1,"ca":"hello"},"a": 1}, {"ab": 2,"aa": 1}]"#,
2038                output: r#"[{"a":1,"b":2,"c":{"ca":"hello","cb":1}},{"aa":1,"ab":2}]"#,
2039            },
2040        ];
2041
2042        for case in cases {
2043            let value: Value = crate::from_str(case.input).unwrap();
2044            assert_eq!(value.to_string(), case.output);
2045        }
2046    }
2047
2048    #[cfg(feature = "sort_keys")]
2049    #[test]
2050    fn test_sort_keys_owned() {
2051        let obj = object! {
2052            "b": 2,
2053            "bc": object! {
2054                "cb": 1,
2055                "ca": "hello",
2056            },
2057            "a": 1,
2058        };
2059
2060        let obj2 = object! {
2061            "a": 1,
2062            "b": 2,
2063            "bc": object! {
2064                "ca": "hello",
2065                "cb": 1,
2066            },
2067        };
2068
2069        assert_eq!(obj, obj2);
2070    }
2071
2072    #[test]
2073    fn test_issue_179_line_column() {
2074        let json = r#"
2075        {
2076            "key\nwith\nnewlines": "value",
2077            "another_key": [, 1, 2, 3]
2078        }
2079        "#;
2080        let err = crate::from_str::<Value>(json).unwrap_err();
2081        assert_eq!(err.line(), 4);
2082    }
2083}