Skip to main content

evorule_primitives/
value.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later
2// Copyright (C) 2026 EvoRule Project
3// This file is part of EvoRule, licensed under GNU Affero General Public License v3 or later.
4//! JSON value types — deterministic data model.
5//!
6//! # Design principles
7//! - Clone-avoidance first (`Cow` to skip unnecessary copies)
8//! - Deterministic iteration (`BTreeMap`)
9//! - Type safety (all conversions return `Option`)
10//! - Never panics
11//!
12//! # Migration note
13//! This module is the single definition site of the value model. The
14//! canonical repo (evorule-tcb / evorule-reactor) re-exports these types
15//! unchanged, so every downstream API path and type identity is preserved.
16
17use alloc::borrow::Cow;
18use alloc::string::{String, ToString};
19use alloc::vec::Vec;
20use core::cmp::Ordering;
21use core::fmt;
22
23#[cfg(not(kani))]
24use alloc::collections::BTreeMap;
25
26/// Kani-verification object backend: ordered `Vec` emulating `BTreeMap`
27/// (enabled under `cfg(kani)`).
28///
29/// # Root cause (probed 2026-09-13: the 23 tier-B proof timeouts)
30///
31/// Kani 0.67's CBMC backend models the `BTreeMap` red-black tree: inserting
32/// >= 2 keys explodes the state space (90s+ without convergence; larger
33/// unwinds do not help). An ordered `Vec` handles 3-key insert + get in 2-3s:
34/// no pointer tracking, no recursive tree traversal — CBMC linear expansion
35/// covers it.
36///
37/// # Semantic-equivalence guarantee
38///
39/// - Entries stay sorted by key (`insert` locates the position linearly and
40///   maintains the invariant); `iter()` order matches `BTreeMap`;
41/// - API signatures match the `BTreeMap<String, JsonValue>` methods in use
42///   (`get`/`get_mut`/`insert`/`remove`/`contains_key`/`values`/`iter`, etc.);
43/// - Production builds (`cfg(not(kani))`) are unaffected: `ObjectMap` stays
44///   a `BTreeMap`.
45#[cfg(kani)]
46#[derive(Debug, Clone, PartialEq, Eq)]
47pub struct KaniMap {
48    /// Ordered entries (sorted by key, maintained by `insert`)
49    entries: Vec<(String, JsonValue)>,
50}
51
52/// Kani-verification no-op `Drop` (same true-no-op pattern as `JsonValue`'s
53/// no-op `Drop`, root cause documented there): prevents the compiler from
54/// synthesizing a recursive field destructor for `entries`
55/// (Vec -> per-element slice -> String RawVec::deallocate), which CBMC would
56/// expand iteration by iteration (measured: verify_evaluate_domain_eq 11GB+
57/// OOM, unwind log shows the Vec<(String, JsonValue)>/KaniMap drop chain
58/// iterating 10-13 levels deep).
59#[cfg(kani)]
60impl Drop for KaniMap {
61    fn drop(&mut self) {
62        // Same true-no-op pattern as JsonValue Drop: take leaves an empty Vec,
63        // forget skips destructing the taken entries; synthesized field drop then
64        // destructs an empty Vec (nothing).
65        let leaked = core::mem::take(&mut self.entries);
66        core::mem::forget(leaked);
67    }
68}
69
70#[cfg(kani)]
71impl KaniMap {
72    /// Key location: `Ok(index)` on hit; `Err(insertion point)` on miss
73    /// (the first position holding a key greater than `key`)
74    fn locate(&self, key: &str) -> Result<usize, usize> {
75        for (i, (k, _)) in self.entries.iter().enumerate() {
76            if k.as_str() == key {
77                return Ok(i);
78            }
79            if k.as_str() > key {
80                return Err(i);
81            }
82        }
83        Err(self.entries.len())
84    }
85
86    /// Construct an empty map
87    pub fn new() -> Self {
88        KaniMap {
89            entries: Vec::new(),
90        }
91    }
92
93    /// Insert or update, returning the old value (semantics match `BTreeMap::insert`)
94    pub fn insert(&mut self, key: String, value: JsonValue) -> Option<JsonValue> {
95        match self.locate(&key) {
96            Ok(i) => self
97                .entries
98                .get_mut(i)
99                .map(|slot| core::mem::replace(&mut slot.1, value)),
100            Err(pos) => {
101                self.entries.insert(pos, (key, value));
102                None
103            }
104        }
105    }
106
107    /// Lookup (semantics match `BTreeMap::get`)
108    pub fn get(&self, key: &str) -> Option<&JsonValue> {
109        match self.locate(key) {
110            Ok(i) => self.entries.get(i).map(|(_, v)| v),
111            Err(_) => None,
112        }
113    }
114
115    /// Mutable lookup (semantics match `BTreeMap::get_mut`)
116    pub fn get_mut(&mut self, key: &str) -> Option<&mut JsonValue> {
117        match self.locate(key) {
118            Ok(i) => match self.entries.get_mut(i) {
119                Some((_, v)) => Some(v),
120                None => None,
121            },
122            Err(_) => None,
123        }
124    }
125
126    /// Remove and return the old value (semantics match `BTreeMap::remove`)
127    pub fn remove(&mut self, key: &str) -> Option<JsonValue> {
128        match self.locate(key) {
129            Ok(i) => {
130                let (_, value) = self.entries.remove(i);
131                Some(value)
132            }
133            Err(_) => None,
134        }
135    }
136
137    /// Key existence check (semantics match `BTreeMap::contains_key`)
138    pub fn contains_key(&self, key: &str) -> bool {
139        self.locate(key).is_ok()
140    }
141
142    /// Value iterator (semantics match `BTreeMap::values`)
143    pub fn values(&self) -> impl Iterator<Item = &JsonValue> {
144        self.entries.iter().map(|(_, v)| v)
145    }
146
147    /// Ordered entry iterator (iteration order matches `BTreeMap::iter`, keys sorted)
148    pub fn iter(&self) -> core::slice::Iter<'_, (String, JsonValue)> {
149        self.entries.iter()
150    }
151
152    /// Entry count
153    pub fn len(&self) -> usize {
154        self.entries.len()
155    }
156
157    /// Whether the map is empty
158    pub fn is_empty(&self) -> bool {
159        self.entries.is_empty()
160    }
161
162    /// Clear all entries
163    pub fn clear(&mut self) {
164        self.entries.clear();
165    }
166}
167
168#[cfg(kani)]
169impl Default for KaniMap {
170    fn default() -> Self {
171        KaniMap::new()
172    }
173}
174
175#[cfg(kani)]
176impl<'a> IntoIterator for &'a KaniMap {
177    type Item = &'a (String, JsonValue);
178    type IntoIter = core::slice::Iter<'a, (String, JsonValue)>;
179
180    fn into_iter(self) -> Self::IntoIter {
181        self.entries.iter()
182    }
183}
184
185#[cfg(kani)]
186impl IntoIterator for KaniMap {
187    type Item = (String, JsonValue);
188    type IntoIter = alloc::vec::IntoIter<(String, JsonValue)>;
189
190    fn into_iter(mut self) -> Self::IntoIter {
191        // mem::take: whole-value move (partial move-out rejected for Drop types)
192        core::mem::take(&mut self.entries).into_iter()
193    }
194}
195
196#[cfg(kani)]
197impl<const N: usize> From<[(String, JsonValue); N]> for KaniMap {
198    fn from(arr: [(String, JsonValue); N]) -> Self {
199        let mut map = KaniMap::new();
200        for (k, v) in arr {
201            map.insert(k, v);
202        }
203        map
204    }
205}
206
207/// Object backend type (`BTreeMap` guarantees deterministic iteration).
208///
209/// Under Kani builds (`cfg(kani)`) this switches to [`KaniMap`]: CBMC's
210/// red-black-tree model of `BTreeMap` explodes the state space on >= 2-key
211/// insertion (root cause of the 23 tier-B proof timeouts — see the
212/// [`KaniMap`] documentation). The ordered-`Vec` backend keeps the API
213/// compatible, the iteration order identical, and production behavior
214/// unaffected.
215#[cfg(not(kani))]
216pub type ObjectMap = BTreeMap<String, JsonValue>;
217/// `ObjectMap` under Kani builds (see documentation above).
218#[cfg(kani)]
219pub type ObjectMap = KaniMap;
220
221/// JSON value type (deterministic implementation).
222///
223/// # Design decisions
224/// - No `Float` variant (formal-verification obstacle)
225/// - `BTreeMap` for deterministic iteration order
226/// - `Vec` instead of `im::Vector`
227/// - `Integer` is `i64` (Kani-friendly)
228/// - `U64` is the full-range `u64` channel (v0.9.0): `Integer` cannot carry
229///   high u64 values losslessly (e.g. the audit-chain rule-set anchor
230///   `FactId(u64::MAX-1)` sentinel); any source whose value range may exceed
231///   `i64` must go through `U64` — `as i64` cast wrap-around is forbidden
232/// - `Cow` to reduce clone overhead
233///
234/// # Why `PartialEq` is not derived
235/// Implemented manually to guarantee cross-language consistency.
236///
237/// # Examples
238///
239/// ```
240/// extern crate alloc;
241/// use evorule_primitives::JsonValue;
242/// use alloc::collections::BTreeMap;
243///
244/// // Construct via constructors
245/// let name = JsonValue::string("Alice");
246/// let age = JsonValue::Integer(30);
247/// assert!(name.is_string());
248/// assert_eq!(age.as_i64(), Some(30));
249///
250/// // Construct via From impls
251/// let from_str: JsonValue = "hello".into();
252/// let from_int: JsonValue = 42i64.into();
253/// assert_eq!(from_str.as_str(), Some("hello"));
254/// assert_eq!(from_int.as_i64(), Some(42));
255///
256/// // Construct a nested object
257/// let mut map = BTreeMap::new();
258/// map.insert("items".to_string(), JsonValue::array(vec![JsonValue::Integer(1), JsonValue::Integer(2)]));
259/// let v = JsonValue::object(map);
260/// assert!(v.is_object());
261/// ```
262#[derive(Debug, Clone)]
263pub enum JsonValue {
264    /// JSON null
265    Null,
266    /// Boolean value
267    Bool(bool),
268    /// Integer (i64)
269    Integer(i64),
270    /// Unsigned integer (full-range u64 channel; strictly distinguished from
271    /// [`JsonValue::Integer`] — no cross-shape numeric equality, see the
272    /// [`PartialEq`] / [`Ord`] implementations)
273    U64(u64),
274    /// String (uses `Cow` to reduce cloning)
275    String(Cow<'static, str>),
276    /// Array (ordered list)
277    Array(Vec<JsonValue>),
278    /// Object (key-value pairs; `BTreeMap` guarantees deterministic order)
279    Object(ObjectMap),
280}
281
282/// Kani-verification no-op `Drop`: skips modeling of JsonValue recursive
283/// destruction.
284///
285/// Root cause (probed 2026-09-13): JsonValue's default Drop recursively
286/// releases Vec/ObjectMap, and CBMC expands every destruction level along all
287/// paths. Even with fully concrete constant inputs, temporaries
288/// (to_string products, object_from_pairs inter-layer values, evaluate_domain
289/// internal temporaries) still explode the state space during destruction
290/// (verify_evaluate_domain_eq 11GB+ without convergence).
291/// Kani builds have no real release requirement (the verification process
292/// exits and the memory is reclaimed), so a no-op Drop makes CBMC skip
293/// destruction expansion; production builds (`cfg(not(kani))`) keep the
294/// default Drop, zero impact.
295#[cfg(kani)]
296impl Drop for JsonValue {
297    fn drop(&mut self) {
298        // Rust Drop semantics: drop_in_place = user Drop::drop THEN compiler-
299        // synthesized field drops. An empty body does NOT suppress recursive field
300        // destruction (measured: 11GB+ CBMC OOM, drop-chain iterations 10-13). True
301        // no-op: swap self to fieldless Null and forget the old value, so the
302        // subsequent synthesized field drops act on Null (no recursion).
303        let leaked = core::mem::replace(self, JsonValue::Null);
304        core::mem::forget(leaked);
305    }
306}
307
308/// Kani build: static Null reference (explicit `impl Drop` blocks rvalue
309/// promotion of `&JsonValue::Null`, see E0515); non-kani keeps promotion path.
310#[cfg(kani)]
311static NULL_VALUE: JsonValue = JsonValue::Null;
312
313#[cfg(not(kani))]
314fn null_ref() -> &'static JsonValue {
315    &JsonValue::Null
316}
317
318#[cfg(kani)]
319fn null_ref() -> &'static JsonValue {
320    &NULL_VALUE
321}
322
323// Manual PartialEq implementation for cross-language consistency
324impl PartialEq for JsonValue {
325    fn eq(&self, other: &Self) -> bool {
326        match (self, other) {
327            (JsonValue::Null, JsonValue::Null) => true,
328            (JsonValue::Bool(a), JsonValue::Bool(b)) => a == b,
329            (JsonValue::Integer(a), JsonValue::Integer(b)) => a == b,
330            (JsonValue::U64(a), JsonValue::U64(b)) => a == b,
331            // Cross-shape (Integer vs U64) is intentionally unequal: shape
332            // strictness keeps equality and Ord type grouping aligned, avoiding
333            // an equality/ordering semantic split (callers convert shapes
334            // explicitly when numeric comparison is needed).
335            (JsonValue::String(a), JsonValue::String(b)) => a == b,
336            (JsonValue::Array(a), JsonValue::Array(b)) => a == b,
337            (JsonValue::Object(a), JsonValue::Object(b)) => {
338                if a.len() != b.len() {
339                    return false;
340                }
341                for (k, v) in a.iter() {
342                    if let Some(bv) = b.get(k) {
343                        if v != bv {
344                            return false;
345                        }
346                    } else {
347                        return false;
348                    }
349                }
350                true
351            }
352            _ => false,
353        }
354    }
355}
356
357impl Eq for JsonValue {}
358
359// Manual Ord implementation to support ordering inside BTreeMap
360impl Ord for JsonValue {
361    fn cmp(&self, other: &Self) -> Ordering {
362        match (self, other) {
363            // Type-group order: Null < Bool < Integer < U64 < String < Array < Object
364            (JsonValue::Null, JsonValue::Null) => Ordering::Equal,
365            (JsonValue::Null, _) => Ordering::Less,
366            (_, JsonValue::Null) => Ordering::Greater,
367
368            (JsonValue::Bool(a), JsonValue::Bool(b)) => a.cmp(b),
369            (JsonValue::Bool(_), _) => Ordering::Less,
370            (_, JsonValue::Bool(_)) => Ordering::Greater,
371
372            (JsonValue::Integer(a), JsonValue::Integer(b)) => a.cmp(b),
373            (JsonValue::Integer(_), _) => Ordering::Less,
374            (_, JsonValue::Integer(_)) => Ordering::Greater,
375
376            (JsonValue::U64(a), JsonValue::U64(b)) => a.cmp(b),
377            (JsonValue::U64(_), _) => Ordering::Less,
378            (_, JsonValue::U64(_)) => Ordering::Greater,
379
380            (JsonValue::String(a), JsonValue::String(b)) => a.cmp(b),
381            (JsonValue::String(_), _) => Ordering::Less,
382            (_, JsonValue::String(_)) => Ordering::Greater,
383
384            (JsonValue::Array(a), JsonValue::Array(b)) => a.cmp(b),
385            (JsonValue::Array(_), _) => Ordering::Less,
386            (_, JsonValue::Array(_)) => Ordering::Greater,
387
388            (JsonValue::Object(a), JsonValue::Object(b)) => {
389                // Lexicographic comparison of key-value pairs
390                let mut a_iter = a.iter();
391                let mut b_iter = b.iter();
392                loop {
393                    match (a_iter.next(), b_iter.next()) {
394                        (None, None) => return Ordering::Equal,
395                        (None, Some(_)) => return Ordering::Less,
396                        (Some(_), None) => return Ordering::Greater,
397                        (Some((ak, av)), Some((bk, bv))) => match ak.cmp(bk) {
398                            Ordering::Equal => match av.cmp(bv) {
399                                Ordering::Equal => {}
400                                other => return other,
401                            },
402                            other => return other,
403                        },
404                    }
405                }
406            }
407        }
408    }
409}
410
411impl PartialOrd for JsonValue {
412    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
413        Some(self.cmp(other))
414    }
415}
416
417impl JsonValue {
418    // ===== Type checks =====
419
420    /// Check whether the value is an object
421    pub fn is_object(&self) -> bool {
422        matches!(self, JsonValue::Object(_))
423    }
424
425    /// Check whether the value is an array
426    pub fn is_array(&self) -> bool {
427        matches!(self, JsonValue::Array(_))
428    }
429
430    /// Check whether the value is an integer
431    pub fn is_integer(&self) -> bool {
432        matches!(self, JsonValue::Integer(_))
433    }
434
435    /// Check whether the value is an unsigned integer (full-range u64 channel)
436    pub fn is_u64(&self) -> bool {
437        matches!(self, JsonValue::U64(_))
438    }
439
440    /// Check whether the value is a string
441    pub fn is_string(&self) -> bool {
442        matches!(self, JsonValue::String(_))
443    }
444
445    /// Check whether the value is a boolean
446    pub fn is_bool(&self) -> bool {
447        matches!(self, JsonValue::Bool(_))
448    }
449
450    /// Check whether the value is null
451    pub fn is_null(&self) -> bool {
452        matches!(self, JsonValue::Null)
453    }
454
455    /// Get the value's length (array element count or object entry count)
456    ///
457    /// # Examples
458    ///
459    /// ```
460    /// use evorule_primitives::JsonValue;
461    ///
462    /// let arr = JsonValue::array(vec![JsonValue::Integer(1), JsonValue::Integer(2)]);
463    /// assert_eq!(arr.len(), Some(2));
464    ///
465    /// let obj = JsonValue::empty_object();
466    /// assert_eq!(obj.len(), Some(0));
467    ///
468    /// let null = JsonValue::Null;
469    /// assert_eq!(null.len(), None);
470    /// ```
471    pub fn len(&self) -> Option<usize> {
472        match self {
473            JsonValue::Array(arr) => Some(arr.len()),
474            JsonValue::Object(map) => Some(map.len()),
475            _ => None,
476        }
477    }
478
479    /// Check whether the value is empty (array or object)
480    pub fn is_empty(&self) -> bool {
481        match self {
482            JsonValue::Array(arr) => arr.is_empty(),
483            JsonValue::Object(map) => map.is_empty(),
484            _ => false,
485        }
486    }
487
488    // ===== Type conversions =====
489
490    /// Try to convert to i64
491    pub fn as_i64(&self) -> Option<i64> {
492        match self {
493            JsonValue::Integer(v) => Some(*v),
494            _ => None,
495        }
496    }
497
498    /// Try to convert to u64 (matches [`JsonValue::U64`] only; strictly
499    /// symmetric with `as_i64` shape-wise)
500    pub fn as_u64(&self) -> Option<u64> {
501        match self {
502            JsonValue::U64(v) => Some(*v),
503            _ => None,
504        }
505    }
506
507    /// Try to convert to &str
508    pub fn as_str(&self) -> Option<&str> {
509        match self {
510            JsonValue::String(s) => Some(s.as_ref()),
511            _ => None,
512        }
513    }
514
515    /// Try to convert to bool
516    pub fn as_bool(&self) -> Option<bool> {
517        match self {
518            JsonValue::Bool(b) => Some(*b),
519            _ => None,
520        }
521    }
522
523    /// Try to convert to &[JsonValue]
524    pub fn as_array(&self) -> Option<&[JsonValue]> {
525        match self {
526            JsonValue::Array(arr) => Some(arr.as_slice()),
527            _ => None,
528        }
529    }
530
531    /// Try to convert to &mut [JsonValue]
532    pub fn as_array_mut(&mut self) -> Option<&mut [JsonValue]> {
533        match self {
534            JsonValue::Array(arr) => Some(arr.as_mut_slice()),
535            _ => None,
536        }
537    }
538
539    /// Try to convert to &ObjectMap
540    pub fn as_object(&self) -> Option<&ObjectMap> {
541        match self {
542            JsonValue::Object(map) => Some(map),
543            _ => None,
544        }
545    }
546
547    /// Try to convert to &mut ObjectMap
548    pub fn as_object_mut(&mut self) -> Option<&mut ObjectMap> {
549        match self {
550            JsonValue::Object(map) => Some(map),
551            _ => None,
552        }
553    }
554
555    // ===== Object operations =====
556
557    /// Get an object field (if present)
558    ///
559    /// # Examples
560    ///
561    /// ```
562    /// extern crate alloc;
563    /// use evorule_primitives::JsonValue;
564    /// use alloc::collections::BTreeMap;
565    ///
566    /// let mut map = BTreeMap::new();
567    /// map.insert("a".to_string(), JsonValue::Integer(1));
568    /// let obj = JsonValue::object(map);
569    ///
570    /// assert_eq!(obj.get("a").and_then(|v| v.as_i64()), Some(1));
571    /// assert_eq!(obj.get("missing"), None);
572    ///
573    /// // Calling on a non-object always returns None (never panics)
574    /// let n = JsonValue::Null;
575    /// assert_eq!(n.get("anything"), None);
576    /// ```
577    pub fn get(&self, key: &str) -> Option<&JsonValue> {
578        match self {
579            JsonValue::Object(map) => map.get(key),
580            _ => None,
581        }
582    }
583
584    /// Get an object field (mutable)
585    pub fn get_mut(&mut self, key: &str) -> Option<&mut JsonValue> {
586        match self {
587            JsonValue::Object(map) => map.get_mut(key),
588            _ => None,
589        }
590    }
591
592    /// Insert or update an object field
593    ///
594    /// # Examples
595    ///
596    /// ```
597    /// use evorule_primitives::JsonValue;
598    ///
599    /// let mut obj = JsonValue::empty_object();
600    /// let old = obj.insert("k".to_string(), JsonValue::Integer(1));
601    /// assert_eq!(old, None);
602    ///
603    /// let old = obj.insert("k".to_string(), JsonValue::Integer(2));
604    /// assert_eq!(old.and_then(|v| v.as_i64()), Some(1));
605    /// assert_eq!(obj.get("k").and_then(|v| v.as_i64()), Some(2));
606    /// ```
607    pub fn insert(&mut self, key: String, value: JsonValue) -> Option<JsonValue> {
608        match self {
609            JsonValue::Object(map) => map.insert(key, value),
610            _ => None,
611        }
612    }
613
614    /// Try to insert (returns an error if the key already exists)
615    ///
616    /// # Examples
617    ///
618    /// ```
619    /// use evorule_primitives::JsonValue;
620    ///
621    /// let mut obj = JsonValue::empty_object();
622    /// assert!(obj.try_insert("k".to_string(), JsonValue::Integer(1)).is_ok());
623    /// assert!(obj.try_insert("k".to_string(), JsonValue::Integer(2)).is_err());
624    /// ```
625    /// # Why an explicit `allow(clippy::map_entry)` instead of the Entry API
626    ///
627    /// Clippy's `map_entry` lint suggests rewriting to `BTreeMap::entry`, but
628    /// **the type of this function is cfg-determined** (see [`ObjectMap`]):
629    ///
630    /// - `cfg(not(kani))` -> `BTreeMap`, which **has** an `Entry` API;
631    /// - `cfg(kani)` -> [`KaniMap`] (ordered `Vec`), which has **no** `Entry`
632    ///   API — its whole point is to avoid CBMC's state explosion on red-black
633    ///   tree insertion.
634    ///
635    /// Both branches must compile from the same source, so **no** backend-
636    /// specific API can be used. Keeping `contains_key` + `get`/`insert` is
637    /// the **only backend-independent** formulation, at zero performance cost
638    /// (`contains_key` and `get` follow the same `BTreeMap` lookup path; only
639    /// the return type differs). **Do not "fix" this.**
640    #[allow(clippy::map_entry)]
641    pub fn try_insert(&mut self, key: String, value: JsonValue) -> Result<(), &JsonValue> {
642        // Backend-independent implementation (BTreeMap / KaniMap compatible):
643        // on hit return a reference to the existing value; on miss insert.
644        // No BTreeMap-specific Entry API, so the same source compiles once
645        // cfg(kani) switches ObjectMap to KaniMap.
646        // contains_key is checked first (returns bool, holds no borrow); the
647        // get borrow and the insert mutable borrow are separated to satisfy NLL.
648        match self {
649            JsonValue::Object(map) => {
650                if map.contains_key(&key) {
651                    match map.get(&key) {
652                        Some(existing) => Err(existing),
653                        None => Err(null_ref()),
654                    }
655                } else {
656                    map.insert(key, value);
657                    Ok(())
658                }
659            }
660            _ => Err(null_ref()),
661        }
662    }
663
664    /// Remove a field from the object
665    pub fn remove(&mut self, key: &str) -> Option<JsonValue> {
666        match self {
667            JsonValue::Object(map) => map.remove(key),
668            _ => None,
669        }
670    }
671
672    /// Clear all contents of the object or array
673    ///
674    /// # Examples
675    ///
676    /// ```
677    /// use evorule_primitives::JsonValue;
678    ///
679    /// let mut arr = JsonValue::array(vec![JsonValue::Integer(1), JsonValue::Integer(2)]);
680    /// arr.clear();
681    /// assert_eq!(arr.len(), Some(0));
682    ///
683    /// // Calling on a non-container type is a no-op
684    /// let mut null = JsonValue::Null;
685    /// null.clear();
686    /// ```
687    pub fn clear(&mut self) {
688        match self {
689            JsonValue::Array(arr) => arr.clear(),
690            JsonValue::Object(map) => map.clear(),
691            _ => {}
692        }
693    }
694}
695
696// ===== Display implementation =====
697
698impl fmt::Display for JsonValue {
699    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
700        match self {
701            JsonValue::Null => write!(f, "null"),
702            JsonValue::Bool(b) => write!(f, "{b}"),
703            JsonValue::Integer(i) => write!(f, "{i}"),
704            JsonValue::U64(v) => write!(f, "{v}"),
705            JsonValue::String(s) => escape_json_string(s.as_ref(), f),
706            JsonValue::Array(arr) => {
707                write!(f, "[")?;
708                for (i, v) in arr.iter().enumerate() {
709                    if i > 0 {
710                        write!(f, ", ")?;
711                    }
712                    write!(f, "{v}")?;
713                }
714                write!(f, "]")
715            }
716            JsonValue::Object(map) => {
717                write!(f, "{{")?;
718                for (i, (k, v)) in map.iter().enumerate() {
719                    if i > 0 {
720                        write!(f, ", ")?;
721                    }
722                    escape_json_string(k, f)?;
723                    write!(f, ": {v}")?;
724                }
725                write!(f, "}}")
726            }
727        }
728    }
729}
730
731/// JSON string escaping helper.
732///
733/// Writes the string escaped per the JSON standard into the formatter.
734/// Used for both string values and object keys.
735fn escape_json_string(s: &str, f: &mut fmt::Formatter<'_>) -> fmt::Result {
736    write!(f, "\"")?;
737    for c in s.chars() {
738        match c {
739            '"' => write!(f, "\\\"")?,
740            '\\' => write!(f, "\\\\")?,
741            '\n' => write!(f, "\\n")?,
742            '\r' => write!(f, "\\r")?,
743            '\t' => write!(f, "\\t")?,
744            '\x08' => write!(f, "\\b")?,
745            '\x0c' => write!(f, "\\f")?,
746            c if (c as u32) < 0x20 => write!(f, "\\u{:04x}", c as u32)?,
747            c => write!(f, "{c}")?,
748        }
749    }
750    write!(f, "\"")
751}
752
753// ===== Constructors =====
754
755impl JsonValue {
756    /// Construct null
757    pub const fn null() -> Self {
758        JsonValue::Null
759    }
760
761    /// Construct a boolean
762    pub const fn bool(b: bool) -> Self {
763        JsonValue::Bool(b)
764    }
765
766    /// Construct an integer
767    pub const fn integer(i: i64) -> Self {
768        JsonValue::Integer(i)
769    }
770
771    /// Construct an unsigned integer (full-range u64 channel)
772    ///
773    /// # Examples
774    ///
775    /// ```
776    /// use evorule_primitives::JsonValue;
777    ///
778    /// let v = JsonValue::u64(u64::MAX - 1);
779    /// assert!(v.is_u64());
780    /// assert_eq!(v.as_u64(), Some(u64::MAX - 1));
781    /// // Shape-strict: U64 and Integer are never cross-shape equal
782    /// assert_ne!(JsonValue::u64(5), JsonValue::Integer(5));
783    /// ```
784    pub const fn u64(v: u64) -> Self {
785        JsonValue::U64(v)
786    }
787
788    /// Construct a string
789    ///
790    /// # Examples
791    ///
792    /// ```
793    /// use evorule_primitives::JsonValue;
794    ///
795    /// let v = JsonValue::string("hello");
796    /// assert_eq!(v.as_str(), Some("hello"));
797    /// ```
798    pub fn string<S: Into<String>>(s: S) -> Self {
799        JsonValue::String(Cow::Owned(s.into()))
800    }
801
802    /// Construct an array
803    ///
804    /// # Examples
805    ///
806    /// ```
807    /// use evorule_primitives::JsonValue;
808    ///
809    /// let arr = JsonValue::array(vec![JsonValue::Integer(1), JsonValue::Integer(2)]);
810    /// assert!(arr.is_array());
811    /// assert_eq!(arr.as_array().map(|a| a.len()), Some(2));
812    /// ```
813    pub fn array(v: Vec<JsonValue>) -> Self {
814        JsonValue::Array(v)
815    }
816
817    /// Construct an object
818    ///
819    /// # Examples
820    ///
821    /// ```
822    /// extern crate alloc;
823    /// use evorule_primitives::JsonValue;
824    /// use alloc::collections::BTreeMap;
825    ///
826    /// let mut map = BTreeMap::new();
827    /// map.insert("key".to_string(), JsonValue::Integer(42));
828    /// let obj = JsonValue::object(map);
829    /// assert!(obj.is_object());
830    /// assert_eq!(obj.get("key").and_then(|v| v.as_i64()), Some(42));
831    /// ```
832    pub fn object(map: ObjectMap) -> Self {
833        JsonValue::Object(map)
834    }
835
836    /// Construct an object from key-value pairs (owning version).
837    ///
838    /// More efficient than `object_from_pairs` because values are not cloned.
839    ///
840    /// # Examples
841    ///
842    /// ```
843    /// use evorule_primitives::JsonValue;
844    ///
845    /// let pairs = vec![
846    ///     ("a".to_string(), JsonValue::Integer(1)),
847    ///     ("b".to_string(), JsonValue::Integer(2)),
848    /// ];
849    /// let obj = JsonValue::object_from_pairs_owned(pairs);
850    /// assert_eq!(obj.get("a").and_then(|v| v.as_i64()), Some(1));
851    /// ```
852    pub fn object_from_pairs_owned(pairs: Vec<(String, JsonValue)>) -> Self {
853        let mut map = ObjectMap::new();
854        for (k, v) in pairs {
855            map.insert(k, v);
856        }
857        JsonValue::Object(map)
858    }
859
860    /// Construct an object from key-value pairs (borrowed version; clones values).
861    ///
862    /// Note: this method clones all values. Use `object_from_pairs_owned` to
863    /// avoid cloning.
864    ///
865    /// # Examples
866    ///
867    /// ```
868    /// use evorule_primitives::JsonValue;
869    ///
870    /// let obj = JsonValue::object_from_pairs(&[
871    ///     ("a", JsonValue::Integer(1)),
872    ///     ("b", JsonValue::Integer(2)),
873    /// ]);
874    /// assert_eq!(obj.get("a").and_then(|v| v.as_i64()), Some(1));
875    /// ```
876    pub fn object_from_pairs(pairs: &[(&str, JsonValue)]) -> Self {
877        let mut map = ObjectMap::new();
878        for (k, v) in pairs {
879            map.insert((*k).to_string(), v.clone());
880        }
881        JsonValue::Object(map)
882    }
883
884    /// Construct an empty object
885    ///
886    /// # Examples
887    ///
888    /// ```
889    /// use evorule_primitives::JsonValue;
890    ///
891    /// let obj = JsonValue::empty_object();
892    /// assert!(obj.is_object());
893    /// assert_eq!(obj.as_object().map(|m| m.len()), Some(0));
894    /// ```
895    pub fn empty_object() -> Self {
896        JsonValue::Object(ObjectMap::new())
897    }
898
899    /// Construct an empty array
900    ///
901    /// # Examples
902    ///
903    /// ```
904    /// use evorule_primitives::JsonValue;
905    ///
906    /// let arr = JsonValue::empty_array();
907    /// assert!(arr.is_array());
908    /// assert_eq!(arr.as_array().map(|a| a.len()), Some(0));
909    /// ```
910    pub fn empty_array() -> Self {
911        JsonValue::Array(Vec::new())
912    }
913}
914
915// ===== From trait implementations =====
916
917/// Construct an object from a map
918impl From<ObjectMap> for JsonValue {
919    fn from(map: ObjectMap) -> Self {
920        JsonValue::Object(map)
921    }
922}
923
924/// Construct an array from a Vec
925impl From<Vec<JsonValue>> for JsonValue {
926    fn from(v: Vec<JsonValue>) -> Self {
927        JsonValue::Array(v)
928    }
929}
930
931/// Construct a string from a &str
932impl From<&str> for JsonValue {
933    fn from(s: &str) -> Self {
934        JsonValue::String(Cow::Owned(s.to_string()))
935    }
936}
937
938/// Construct a string from a String
939impl From<String> for JsonValue {
940    fn from(s: String) -> Self {
941        JsonValue::String(Cow::Owned(s))
942    }
943}
944
945/// Construct a string from a Cow<'static, str>
946impl From<Cow<'static, str>> for JsonValue {
947    fn from(s: Cow<'static, str>) -> Self {
948        JsonValue::String(s)
949    }
950}
951
952/// Construct an integer from i64
953impl From<i64> for JsonValue {
954    fn from(i: i64) -> Self {
955        JsonValue::Integer(i)
956    }
957}
958
959/// Construct an unsigned integer from u64 (full-range channel, no i64 cast wrap-around)
960impl From<u64> for JsonValue {
961    fn from(v: u64) -> Self {
962        JsonValue::U64(v)
963    }
964}
965
966/// Construct a boolean from bool
967impl From<bool> for JsonValue {
968    fn from(b: bool) -> Self {
969        JsonValue::Bool(b)
970    }
971}
972
973#[cfg(test)]
974mod tests {
975    #![allow(clippy::unwrap_used)]
976    #![allow(clippy::expect_used)]
977    #![allow(clippy::panic)]
978    #![allow(clippy::indexing_slicing)]
979
980    use super::*;
981    use alloc::format;
982    use alloc::vec;
983    use core::cmp::Ordering;
984
985    // ===== Constructor tests =====
986
987    #[test]
988    fn test_const_constructors() {
989        const N: JsonValue = JsonValue::null();
990        const B: JsonValue = JsonValue::bool(true);
991        const I: JsonValue = JsonValue::integer(-7);
992        assert_eq!(N, JsonValue::Null);
993        assert_eq!(B, JsonValue::Bool(true));
994        assert_eq!(I, JsonValue::Integer(-7));
995    }
996
997    #[test]
998    fn test_string_constructor() {
999        let s = JsonValue::string("hello");
1000        assert_eq!(s.as_str(), Some("hello"));
1001        let owned = JsonValue::string(String::from("world"));
1002        assert_eq!(owned.as_str(), Some("world"));
1003    }
1004
1005    #[test]
1006    fn test_empty_array() {
1007        assert_eq!(JsonValue::empty_array(), JsonValue::Array(Vec::new()));
1008    }
1009
1010    #[test]
1011    fn test_empty_object() {
1012        assert!(JsonValue::empty_object().is_object());
1013        assert_eq!(JsonValue::empty_object().len(), Some(0));
1014    }
1015
1016    #[test]
1017    fn test_object_from_pairs_owned() {
1018        let pairs = vec![
1019            ("a".to_string(), JsonValue::Integer(1)),
1020            ("b".to_string(), JsonValue::Integer(2)),
1021        ];
1022        let obj = JsonValue::object_from_pairs_owned(pairs);
1023        assert_eq!(obj.get("a").and_then(|v| v.as_i64()), Some(1));
1024        assert_eq!(obj.get("b").and_then(|v| v.as_i64()), Some(2));
1025    }
1026
1027    // ===== Type-check tests =====
1028
1029    #[test]
1030    fn test_is_methods_match_correct_type() {
1031        assert!(JsonValue::Null.is_null());
1032        assert!(JsonValue::Bool(true).is_bool());
1033        assert!(JsonValue::Integer(0).is_integer());
1034        assert!(JsonValue::string("x").is_string());
1035        assert!(JsonValue::empty_array().is_array());
1036        assert!(JsonValue::empty_object().is_object());
1037    }
1038
1039    #[test]
1040    fn test_is_methods_reject_wrong_type() {
1041        assert!(!JsonValue::Null.is_bool());
1042        assert!(!JsonValue::Null.is_integer());
1043        assert!(!JsonValue::Integer(1).is_string());
1044        assert!(!JsonValue::string("x").is_array());
1045        assert!(!JsonValue::empty_array().is_object());
1046        assert!(!JsonValue::Bool(false).is_null());
1047    }
1048
1049    // ===== len() and is_empty() tests =====
1050
1051    #[test]
1052    fn test_len_and_is_empty() {
1053        assert_eq!(JsonValue::Null.len(), None);
1054        assert_eq!(JsonValue::Integer(42).len(), None);
1055        assert_eq!(JsonValue::string("test").len(), None);
1056
1057        let arr = JsonValue::array(vec![JsonValue::Integer(1), JsonValue::Integer(2)]);
1058        assert_eq!(arr.len(), Some(2));
1059        assert!(!arr.is_empty());
1060
1061        let empty_arr = JsonValue::empty_array();
1062        assert_eq!(empty_arr.len(), Some(0));
1063        assert!(empty_arr.is_empty());
1064
1065        let obj = JsonValue::object_from_pairs(&[("a", JsonValue::Integer(1))]);
1066        assert_eq!(obj.len(), Some(1));
1067        assert!(!obj.is_empty());
1068
1069        assert!(JsonValue::empty_object().is_empty());
1070    }
1071
1072    // ===== Conversion tests =====
1073
1074    #[test]
1075    fn test_as_methods_success_paths() {
1076        assert_eq!(JsonValue::Integer(42).as_i64(), Some(42));
1077        assert_eq!(JsonValue::string("hi").as_str(), Some("hi"));
1078        assert_eq!(JsonValue::Bool(true).as_bool(), Some(true));
1079        assert!(JsonValue::empty_array().as_array().is_some());
1080        assert!(JsonValue::empty_object().as_object().is_some());
1081    }
1082
1083    #[test]
1084    fn test_as_methods_type_mismatch_returns_none() {
1085        assert_eq!(JsonValue::Null.as_i64(), None);
1086        assert_eq!(JsonValue::Bool(true).as_i64(), None);
1087        assert_eq!(JsonValue::string("x").as_i64(), None);
1088        assert_eq!(JsonValue::Null.as_str(), None);
1089        assert_eq!(JsonValue::Integer(1).as_str(), None);
1090        assert_eq!(JsonValue::Integer(1).as_bool(), None);
1091        assert_eq!(JsonValue::Null.as_array(), None);
1092        assert_eq!(JsonValue::Integer(0).as_array(), None);
1093        assert_eq!(JsonValue::Null.as_object(), None);
1094        assert_eq!(JsonValue::Integer(0).as_object(), None);
1095    }
1096
1097    #[test]
1098    fn test_as_mut_methods_type_mismatch() {
1099        let mut v = JsonValue::Integer(0);
1100        assert!(v.as_array_mut().is_none());
1101        assert!(v.as_object_mut().is_none());
1102        let mut arr = JsonValue::empty_array();
1103        assert!(arr.as_array_mut().is_some());
1104        let mut obj = JsonValue::empty_object();
1105        assert!(obj.as_object_mut().is_some());
1106    }
1107
1108    // ===== Object operation tests =====
1109
1110    #[test]
1111    fn test_object_accessors_on_non_object() {
1112        let mut v = JsonValue::Integer(0);
1113        assert_eq!(v.get("any"), None);
1114        assert_eq!(v.get_mut("any"), None);
1115        assert_eq!(v.insert("k".to_string(), JsonValue::Null), None);
1116        assert_eq!(v.remove("k"), None);
1117        assert_eq!(v, JsonValue::Integer(0));
1118    }
1119
1120    #[test]
1121    fn test_get_on_object() {
1122        let obj = JsonValue::object_from_pairs(&[("x", JsonValue::Integer(7))]);
1123        assert_eq!(obj.get("x"), Some(&JsonValue::Integer(7)));
1124        assert_eq!(obj.get("missing"), None);
1125    }
1126
1127    #[test]
1128    fn test_get_mut_on_object() {
1129        let mut obj = JsonValue::object_from_pairs(&[("a", JsonValue::Integer(1))]);
1130        if let Some(v) = obj.get_mut("a") {
1131            *v = JsonValue::Integer(42);
1132        }
1133        assert_eq!(obj.get("a"), Some(&JsonValue::Integer(42)));
1134        assert_eq!(obj.get_mut("missing"), None);
1135    }
1136
1137    #[test]
1138    fn test_insert_and_remove() {
1139        let mut obj = JsonValue::empty_object();
1140        assert_eq!(obj.insert("k".to_string(), JsonValue::Integer(1)), None);
1141        assert_eq!(obj.get("k"), Some(&JsonValue::Integer(1)));
1142
1143        let old = obj.insert("k".to_string(), JsonValue::Integer(2));
1144        assert_eq!(old, Some(JsonValue::Integer(1)));
1145        assert_eq!(obj.get("k"), Some(&JsonValue::Integer(2)));
1146
1147        assert_eq!(obj.remove("k"), Some(JsonValue::Integer(2)));
1148        assert_eq!(obj.get("k"), None);
1149        assert_eq!(obj.remove("missing"), None);
1150    }
1151
1152    #[test]
1153    fn test_try_insert() {
1154        let mut obj = JsonValue::empty_object();
1155        assert!(obj
1156            .try_insert("k".to_string(), JsonValue::Integer(1))
1157            .is_ok());
1158        assert!(obj
1159            .try_insert("k".to_string(), JsonValue::Integer(2))
1160            .is_err());
1161        assert_eq!(obj.get("k"), Some(&JsonValue::Integer(1)));
1162
1163        let mut non_obj = JsonValue::Integer(0);
1164        assert!(non_obj
1165            .try_insert("k".to_string(), JsonValue::Integer(1))
1166            .is_err());
1167    }
1168
1169    #[test]
1170    fn test_clear() {
1171        let mut arr = JsonValue::array(vec![JsonValue::Integer(1), JsonValue::Integer(2)]);
1172        arr.clear();
1173        assert_eq!(arr.len(), Some(0));
1174
1175        let mut obj = JsonValue::object_from_pairs(&[("a", JsonValue::Integer(1))]);
1176        obj.clear();
1177        assert_eq!(obj.len(), Some(0));
1178
1179        let mut null = JsonValue::Null;
1180        null.clear(); // no-op
1181        assert!(null.is_null());
1182    }
1183
1184    // ===== PartialEq tests =====
1185
1186    #[test]
1187    fn test_partial_eq_same_type() {
1188        assert_eq!(JsonValue::Null, JsonValue::Null);
1189        assert_eq!(JsonValue::Bool(true), JsonValue::Bool(true));
1190        assert_eq!(JsonValue::Integer(5), JsonValue::Integer(5));
1191        assert_eq!(JsonValue::string("hi"), JsonValue::string("hi"));
1192        assert_eq!(
1193            JsonValue::array(vec![JsonValue::Integer(1)]),
1194            JsonValue::array(vec![JsonValue::Integer(1)])
1195        );
1196    }
1197
1198    #[test]
1199    fn test_partial_eq_cross_type() {
1200        assert_ne!(JsonValue::Null, JsonValue::Bool(false));
1201        assert_ne!(JsonValue::Bool(true), JsonValue::Integer(1));
1202        assert_ne!(JsonValue::Integer(0), JsonValue::string("0"));
1203        assert_ne!(JsonValue::string(""), JsonValue::empty_array());
1204        assert_ne!(JsonValue::empty_array(), JsonValue::empty_object());
1205    }
1206
1207    #[test]
1208    fn test_partial_eq_object() {
1209        let mut a = ObjectMap::new();
1210        a.insert("x".to_string(), JsonValue::Integer(1));
1211        a.insert("y".to_string(), JsonValue::Integer(2));
1212        let mut b = ObjectMap::new();
1213        b.insert("x".to_string(), JsonValue::Integer(1));
1214        b.insert("y".to_string(), JsonValue::Integer(2));
1215        assert_eq!(JsonValue::object(a.clone()), JsonValue::object(b));
1216
1217        let mut c = ObjectMap::new();
1218        c.insert("x".to_string(), JsonValue::Integer(1));
1219        c.insert("y".to_string(), JsonValue::Integer(99));
1220        assert_ne!(JsonValue::object(a.clone()), JsonValue::object(c));
1221
1222        let mut d = ObjectMap::new();
1223        d.insert("x".to_string(), JsonValue::Integer(1));
1224        d.insert("z".to_string(), JsonValue::Integer(2));
1225        assert_ne!(JsonValue::object(a.clone()), JsonValue::object(d));
1226
1227        let mut e = ObjectMap::new();
1228        e.insert("x".to_string(), JsonValue::Integer(1));
1229        assert_ne!(JsonValue::object(a), JsonValue::object(e));
1230    }
1231
1232    // ===== Ord tests =====
1233
1234    #[test]
1235    fn test_ord_type_order() {
1236        assert_eq!(JsonValue::Null.cmp(&JsonValue::Null), Ordering::Equal);
1237        assert!(JsonValue::Null < JsonValue::Bool(false));
1238        assert!(JsonValue::Bool(false) < JsonValue::Integer(0));
1239        assert!(JsonValue::Integer(0) < JsonValue::string(""));
1240        assert!(JsonValue::string("") < JsonValue::empty_array());
1241        assert!(JsonValue::empty_array() < JsonValue::empty_object());
1242    }
1243
1244    #[test]
1245    fn test_ord_lexicographic() {
1246        assert!(JsonValue::Integer(0) < JsonValue::Integer(1));
1247        assert!(JsonValue::string("a") < JsonValue::string("b"));
1248
1249        let mut short = ObjectMap::new();
1250        short.insert("a".to_string(), JsonValue::Integer(1));
1251        let mut long = ObjectMap::new();
1252        long.insert("a".to_string(), JsonValue::Integer(1));
1253        long.insert("b".to_string(), JsonValue::Integer(2));
1254        assert!(JsonValue::object(short) < JsonValue::object(long));
1255    }
1256
1257    // ===== Display tests =====
1258
1259    #[test]
1260    fn test_display_simple_types() {
1261        assert_eq!(format!("{}", JsonValue::Null), "null");
1262        assert_eq!(format!("{}", JsonValue::Bool(true)), "true");
1263        assert_eq!(format!("{}", JsonValue::Bool(false)), "false");
1264        assert_eq!(format!("{}", JsonValue::Integer(0)), "0");
1265        assert_eq!(format!("{}", JsonValue::Integer(-42)), "-42");
1266    }
1267
1268    #[test]
1269    fn test_display_string_escapes() {
1270        assert_eq!(format!("{}", JsonValue::string("")), "\"\"");
1271        assert_eq!(format!("{}", JsonValue::string("hello")), "\"hello\"");
1272        assert_eq!(format!("{}", JsonValue::string("a\"b")), "\"a\\\"b\"");
1273        assert_eq!(format!("{}", JsonValue::string("a\\b")), "\"a\\\\b\"");
1274        assert_eq!(format!("{}", JsonValue::string("a\nb")), "\"a\\nb\"");
1275    }
1276
1277    #[test]
1278    fn test_display_array() {
1279        assert_eq!(format!("{}", JsonValue::empty_array()), "[]");
1280        let arr = JsonValue::array(vec![
1281            JsonValue::Integer(1),
1282            JsonValue::Integer(2),
1283            JsonValue::Integer(3),
1284        ]);
1285        assert_eq!(format!("{arr}"), "[1, 2, 3]");
1286    }
1287
1288    #[test]
1289    fn test_display_object() {
1290        assert_eq!(format!("{}", JsonValue::empty_object()), "{}");
1291        let obj = JsonValue::object_from_pairs(&[
1292            ("z", JsonValue::Integer(1)),
1293            ("a", JsonValue::Integer(2)),
1294        ]);
1295        assert_eq!(format!("{obj}"), "{\"a\": 2, \"z\": 1}");
1296    }
1297
1298    // ===== From trait tests =====
1299
1300    #[test]
1301    fn test_from_traits() {
1302        let v: JsonValue = 42i64.into();
1303        assert_eq!(v, JsonValue::Integer(42));
1304
1305        let v: JsonValue = "hello".into();
1306        assert_eq!(v, JsonValue::string("hello"));
1307
1308        let v: JsonValue = true.into();
1309        assert_eq!(v, JsonValue::Bool(true));
1310
1311        let v: JsonValue = vec![JsonValue::Integer(1), JsonValue::Integer(2)].into();
1312        assert_eq!(v.len(), Some(2));
1313    }
1314
1315    // ===== JSON string escaping boundaries (Display output validity) =====
1316
1317    /// Control characters (< 0x20 without a dedicated escape) must go through
1318    /// the \u00XX channel — emitting them verbatim produces invalid JSON
1319    /// (consumers crash on parse)
1320    #[test]
1321    fn test_display_escapes_control_chars() {
1322        let v = JsonValue::string("a\u{1}b");
1323        assert_eq!(v.to_string(), "\"a\\u0001b\"");
1324
1325        // \x1f is the last non-dedicated control character below the 0x20 boundary
1326        let v = JsonValue::string("\u{1f}");
1327        assert_eq!(v.to_string(), "\"\\u001f\"");
1328    }
1329
1330    /// Space (0x20) is printable and outside the escape range —
1331    /// writing the escape bound as <= would wrongly escape spaces to \u0020
1332    #[test]
1333    fn test_display_space_verbatim() {
1334        let v = JsonValue::string("a b");
1335        assert_eq!(v.to_string(), "\"a b\"");
1336    }
1337
1338    // ===== U64 (full-range u64 channel) =====
1339
1340    #[test]
1341    fn test_u64_construct_and_access() {
1342        let v = JsonValue::u64(u64::MAX - 1);
1343        assert!(v.is_u64());
1344        assert!(!v.is_integer());
1345        assert_eq!(v.as_u64(), Some(u64::MAX - 1));
1346        // Shape-strict symmetry: as_i64 only matches Integer, as_u64 only U64;
1347        // is_u64 likewise only matches U64 — non-U64 variants are always false
1348        // (negative-kill assertion guarding against an is_u64 always-true mutation)
1349        assert_eq!(v.as_i64(), None);
1350        assert_eq!(JsonValue::Integer(5).as_u64(), None);
1351        assert!(!JsonValue::Integer(5).is_u64());
1352        assert!(!JsonValue::Bool(true).is_u64());
1353        assert!(!JsonValue::Null.is_u64());
1354
1355        let from_trait: JsonValue = 42u64.into();
1356        assert_eq!(from_trait, JsonValue::u64(42));
1357    }
1358
1359    #[test]
1360    fn test_u64_partial_eq_strict_shape() {
1361        // Cross-shape intentionally unequal (consistent with Ord type grouping)
1362        assert_ne!(JsonValue::u64(5), JsonValue::Integer(5));
1363        assert_ne!(JsonValue::Integer(5), JsonValue::u64(5));
1364        assert_eq!(JsonValue::u64(5), JsonValue::u64(5));
1365        assert_ne!(JsonValue::u64(u64::MAX), JsonValue::u64(u64::MAX - 1));
1366    }
1367
1368    #[test]
1369    fn test_u64_ord_group_order() {
1370        // Group order: Integer < U64 < String (type grouping dominates value)
1371        assert!(JsonValue::Integer(0) < JsonValue::u64(0));
1372        assert!(JsonValue::u64(0) < JsonValue::string(""));
1373        assert!(JsonValue::u64(0) < JsonValue::u64(1));
1374        assert!(JsonValue::u64(u64::MAX - 1) < JsonValue::u64(u64::MAX));
1375        // The Integer group still compares less than any U64 value (group
1376        // decision precedes in-group comparison)
1377        assert!(JsonValue::Integer(i64::MAX) < JsonValue::u64(0));
1378    }
1379
1380    #[test]
1381    fn test_u64_display() {
1382        assert_eq!(format!("{}", JsonValue::u64(0)), "0");
1383        assert_eq!(
1384            format!("{}", JsonValue::u64(u64::MAX - 1)),
1385            "18446744073709551614"
1386        );
1387    }
1388}