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