Skip to main content

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