Skip to main content

evorule_tcb/
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 值类型 - 确定性数据模型
5//!
6//! # 设计原则
7//! - 零克隆优先(使用 `Cow` 减少不必要的复制)
8//! - 确定性迭代(`BTreeMap`)
9//! - 类型安全(所有转换返回 `Option`)
10//! - 永不 panic
11
12use alloc::borrow::Cow;
13use alloc::string::{String, ToString};
14use alloc::vec::Vec;
15use core::cmp::Ordering;
16use core::fmt;
17
18#[cfg(not(kani))]
19use alloc::collections::BTreeMap;
20
21/// Kani 验证专用 Object 后端:有序 `Vec` 模拟 `BTreeMap`(`cfg(kani)` 下启用)
22///
23/// # 根因(2026-09-13 探针实测,B 档 23 个 proof 超时定位)
24///
25/// Kani 0.67 的 CBMC 后端对 `BTreeMap` 红黑树建模:插入 ≥2 键即状态爆炸
26/// (90s+ 不收敛,加大 unwind 无改善);有序 `Vec` 3 键 insert + get 仅 2-3s。
27/// `Vec` 无指针追踪、无递归树遍历,CBMC 线性展开即可覆盖。
28///
29/// # 语义等价保证
30///
31/// - 条目始终按键字典序排列(`insert` 线性定位 + 位置插入维护不变式),
32///   `iter()` 迭代顺序与 `BTreeMap` 一致;
33/// - API 与 `BTreeMap<String, JsonValue>` 的 TCB/reactor 在用方法签名兼容
34///   (`get`/`get_mut`/`insert`/`remove`/`contains_key`/`values`/`iter` 等);
35/// - 生产构建(`cfg(not(kani))`)零影响,`ObjectMap` 仍为 `BTreeMap`。
36#[cfg(kani)]
37#[derive(Debug, Clone, PartialEq, Eq)]
38pub struct KaniMap {
39    /// 有序条目(键字典序,`insert` 维护)
40    entries: Vec<(String, JsonValue)>,
41}
42
43/// Kani 验证专用 no-op Drop(同 JsonValue 的 no-op Drop,根因见其文档注释):
44/// 阻止编译器合成 entries 字段的递归析构(Vec → slice 逐元素 → String 的
45/// RawVec::deallocate),后者在 CBMC 中逐迭代展开(实测 verify_evaluate_domain_eq
46/// 11GB+ OOM,unwind 日志见 Vec<(String, JsonValue)>/KaniMap drop 链迭代 10-13 层)。
47#[cfg(kani)]
48impl Drop for KaniMap {
49    fn drop(&mut self) {
50        // Same true-no-op pattern as JsonValue Drop: take leaves an empty Vec,
51        // forget skips destructing the taken entries; synthesized field drop then
52        // destructs an empty Vec (nothing).
53        let leaked = core::mem::take(&mut self.entries);
54        core::mem::forget(leaked);
55    }
56}
57
58#[cfg(kani)]
59impl KaniMap {
60    /// 键定位:命中返回 `Ok(下标)`;未命中返回 `Err(插入点)`(首个大于 key 的位置)
61    fn locate(&self, key: &str) -> Result<usize, usize> {
62        for (i, (k, _)) in self.entries.iter().enumerate() {
63            if k.as_str() == key {
64                return Ok(i);
65            }
66            if k.as_str() > key {
67                return Err(i);
68            }
69        }
70        Err(self.entries.len())
71    }
72
73    /// 构造空映射
74    pub fn new() -> Self {
75        KaniMap {
76            entries: Vec::new(),
77        }
78    }
79
80    /// 插入或更新,返回旧值(语义与 `BTreeMap::insert` 一致)
81    pub fn insert(&mut self, key: String, value: JsonValue) -> Option<JsonValue> {
82        match self.locate(&key) {
83            Ok(i) => self
84                .entries
85                .get_mut(i)
86                .map(|slot| core::mem::replace(&mut slot.1, value)),
87            Err(pos) => {
88                self.entries.insert(pos, (key, value));
89                None
90            }
91        }
92    }
93
94    /// 查找(语义与 `BTreeMap::get` 一致)
95    pub fn get(&self, key: &str) -> Option<&JsonValue> {
96        match self.locate(key) {
97            Ok(i) => self.entries.get(i).map(|(_, v)| v),
98            Err(_) => None,
99        }
100    }
101
102    /// 可变查找(语义与 `BTreeMap::get_mut` 一致)
103    pub fn get_mut(&mut self, key: &str) -> Option<&mut JsonValue> {
104        match self.locate(key) {
105            Ok(i) => match self.entries.get_mut(i) {
106                Some((_, v)) => Some(v),
107                None => None,
108            },
109            Err(_) => None,
110        }
111    }
112
113    /// 移除并返回旧值(语义与 `BTreeMap::remove` 一致)
114    pub fn remove(&mut self, key: &str) -> Option<JsonValue> {
115        match self.locate(key) {
116            Ok(i) => {
117                let (_, value) = self.entries.remove(i);
118                Some(value)
119            }
120            Err(_) => None,
121        }
122    }
123
124    /// 键存在性检查(语义与 `BTreeMap::contains_key` 一致)
125    pub fn contains_key(&self, key: &str) -> bool {
126        self.locate(key).is_ok()
127    }
128
129    /// 值迭代器(语义与 `BTreeMap::values` 一致)
130    pub fn values(&self) -> impl Iterator<Item = &JsonValue> {
131        self.entries.iter().map(|(_, v)| v)
132    }
133
134    /// 有序条目迭代器(迭代顺序与 `BTreeMap::iter` 一致,键字典序)
135    pub fn iter(&self) -> core::slice::Iter<'_, (String, JsonValue)> {
136        self.entries.iter()
137    }
138
139    /// 条目数
140    pub fn len(&self) -> usize {
141        self.entries.len()
142    }
143
144    /// 是否为空
145    pub fn is_empty(&self) -> bool {
146        self.entries.is_empty()
147    }
148
149    /// 清空全部条目
150    pub fn clear(&mut self) {
151        self.entries.clear();
152    }
153}
154
155#[cfg(kani)]
156impl Default for KaniMap {
157    fn default() -> Self {
158        KaniMap::new()
159    }
160}
161
162#[cfg(kani)]
163impl<'a> IntoIterator for &'a KaniMap {
164    type Item = &'a (String, JsonValue);
165    type IntoIter = core::slice::Iter<'a, (String, JsonValue)>;
166
167    fn into_iter(self) -> Self::IntoIter {
168        self.entries.iter()
169    }
170}
171
172#[cfg(kani)]
173impl IntoIterator for KaniMap {
174    type Item = (String, JsonValue);
175    type IntoIter = alloc::vec::IntoIter<(String, JsonValue)>;
176
177    fn into_iter(mut self) -> Self::IntoIter {
178        // mem::take: whole-value move (partial move-out rejected for Drop types)
179        core::mem::take(&mut self.entries).into_iter()
180    }
181}
182
183#[cfg(kani)]
184impl<const N: usize> From<[(String, JsonValue); N]> for KaniMap {
185    fn from(arr: [(String, JsonValue); N]) -> Self {
186        let mut map = KaniMap::new();
187        for (k, v) in arr {
188            map.insert(k, v);
189        }
190        map
191    }
192}
193
194/// Object 后端类型(BTreeMap 保证确定性迭代)
195///
196/// Kani 构建(`cfg(kani)`)下切换为 [`KaniMap`]:CBMC 对 `BTreeMap` 红黑树
197/// 插入 ≥2 键即状态爆炸(B 档 23 个 proof 超时根因,见 `KaniMap` 文档),
198/// 有序 `Vec` 后端 API 兼容、迭代序一致、生产行为零影响。
199#[cfg(not(kani))]
200pub type ObjectMap = BTreeMap<String, JsonValue>;
201/// Kani 构建下的 `ObjectMap`(见上方文档)。
202#[cfg(kani)]
203pub type ObjectMap = KaniMap;
204
205/// JSON 值类型(确定性实现)
206///
207/// # 设计决策
208/// - 无 `Float` 类型(形式化验证障碍)
209/// - 使用 `BTreeMap` 保证确定性迭代顺序
210/// - 使用 `Vec` 而非 `im::Vector`
211/// - `Integer` 为 `i64`(Kani 友好)
212/// - `U64` 为 `u64` 全域通道(v0.9.0):`Integer` 无法无损承载 u64 高位值
213///   (如审计链规则集锚定事实的 `FactId(u64::MAX-1)` 哨兵),凡值域可能
214///   超出 `i64` 的来源一律走 `U64`,禁止 `as i64` cast 回绕
215/// - 使用 `Cow` 减少克隆开销
216///
217/// # 不实现 `PartialEq` 的自动派生
218/// 手动实现以保证跨语言一致性
219///
220/// # 示例
221///
222/// ```
223/// extern crate alloc;
224/// use evorule_tcb::JsonValue;
225/// use alloc::collections::BTreeMap;
226///
227/// // 通过构造函数构造
228/// let name = JsonValue::string("Alice");
229/// let age = JsonValue::Integer(30);
230/// assert!(name.is_string());
231/// assert_eq!(age.as_i64(), Some(30));
232///
233/// // 通过 From trait 构造
234/// let from_str: JsonValue = "hello".into();
235/// let from_int: JsonValue = 42i64.into();
236/// assert_eq!(from_str.as_str(), Some("hello"));
237/// assert_eq!(from_int.as_i64(), Some(42));
238///
239/// // 构造嵌套对象
240/// let mut map = BTreeMap::new();
241/// map.insert("items".to_string(), JsonValue::array(vec![JsonValue::Integer(1), JsonValue::Integer(2)]));
242/// let v = JsonValue::object(map);
243/// assert!(v.is_object());
244/// ```
245#[derive(Debug, Clone)]
246pub enum JsonValue {
247    /// JSON null
248    Null,
249    /// 布尔值
250    Bool(bool),
251    /// 整数(i64)
252    Integer(i64),
253    /// 无符号整数(u64 全域;与 [`JsonValue::Integer`] 形态严格区分,
254    /// 不做跨形态数值相等——见 [`PartialEq`] / [`Ord`] 实现)
255    U64(u64),
256    /// 字符串(使用 `Cow` 减少克隆)
257    String(Cow<'static, str>),
258    /// 数组(有序列表)
259    Array(Vec<JsonValue>),
260    /// 对象(键值对,使用 `BTreeMap` 保证确定性顺序)
261    Object(ObjectMap),
262}
263
264/// Kani 验证专用 no-op Drop:跳过 JsonValue 递归析构建模
265///
266/// 根因(2026-09-13 探针实测):JsonValue 默认 Drop 递归释放 Vec/ObjectMap,
267/// CBMC 对每层析构做全路径展开,即使输入全为具体常量,中间临时对象
268/// (to_string 产物、object_from_pairs 层间值、evaluate_domain 内部临时值)
269/// 的析构仍会状态爆炸(verify_evaluate_domain_eq 11GB+ 不收敛)。
270/// Kani 构建无真实释放需求(验证进程退出即回收),
271/// no-op Drop 使 CBMC 跳过析构展开;生产构建(cfg(not(kani)))保持默认 Drop,零影响。
272#[cfg(kani)]
273impl Drop for JsonValue {
274    fn drop(&mut self) {
275        // Rust Drop semantics: drop_in_place = user Drop::drop THEN compiler-
276        // synthesized field drops. An empty body does NOT suppress recursive field
277        // destruction (measured: 11GB+ CBMC OOM, drop-chain iterations 10-13). True
278        // no-op: swap self to fieldless Null and forget the old value, so the
279        // subsequent synthesized field drops act on Null (no recursion).
280        let leaked = core::mem::replace(self, JsonValue::Null);
281        core::mem::forget(leaked);
282    }
283}
284
285/// Kani build: static Null reference (explicit `impl Drop` blocks rvalue
286/// promotion of `&JsonValue::Null`, see E0515); non-kani keeps promotion path.
287#[cfg(kani)]
288static NULL_VALUE: JsonValue = JsonValue::Null;
289
290#[cfg(not(kani))]
291fn null_ref() -> &'static JsonValue {
292    &JsonValue::Null
293}
294
295#[cfg(kani)]
296fn null_ref() -> &'static JsonValue {
297    &NULL_VALUE
298}
299
300// 手动实现 PartialEq 以保证跨语言一致性
301impl PartialEq for JsonValue {
302    fn eq(&self, other: &Self) -> bool {
303        match (self, other) {
304            (JsonValue::Null, JsonValue::Null) => true,
305            (JsonValue::Bool(a), JsonValue::Bool(b)) => a == b,
306            (JsonValue::Integer(a), JsonValue::Integer(b)) => a == b,
307            (JsonValue::U64(a), JsonValue::U64(b)) => a == b,
308            // 跨形态(Integer vs U64)有意不相等:形态严格与 Ord 类型分组一致,
309            // 避免相等/排序语义分叉(需要数值比较时调用方显式转换形态)。
310            (JsonValue::String(a), JsonValue::String(b)) => a == b,
311            (JsonValue::Array(a), JsonValue::Array(b)) => a == b,
312            (JsonValue::Object(a), JsonValue::Object(b)) => {
313                if a.len() != b.len() {
314                    return false;
315                }
316                for (k, v) in a.iter() {
317                    if let Some(bv) = b.get(k) {
318                        if v != bv {
319                            return false;
320                        }
321                    } else {
322                        return false;
323                    }
324                }
325                true
326            }
327            _ => false,
328        }
329    }
330}
331
332impl Eq for JsonValue {}
333
334// 手动实现 Ord 以支持 BTreeMap 中的排序
335impl Ord for JsonValue {
336    fn cmp(&self, other: &Self) -> Ordering {
337        match (self, other) {
338            // 按类型分组顺序:Null < Bool < Integer < U64 < String < Array < Object
339            (JsonValue::Null, JsonValue::Null) => Ordering::Equal,
340            (JsonValue::Null, _) => Ordering::Less,
341            (_, JsonValue::Null) => Ordering::Greater,
342
343            (JsonValue::Bool(a), JsonValue::Bool(b)) => a.cmp(b),
344            (JsonValue::Bool(_), _) => Ordering::Less,
345            (_, JsonValue::Bool(_)) => Ordering::Greater,
346
347            (JsonValue::Integer(a), JsonValue::Integer(b)) => a.cmp(b),
348            (JsonValue::Integer(_), _) => Ordering::Less,
349            (_, JsonValue::Integer(_)) => Ordering::Greater,
350
351            (JsonValue::U64(a), JsonValue::U64(b)) => a.cmp(b),
352            (JsonValue::U64(_), _) => Ordering::Less,
353            (_, JsonValue::U64(_)) => Ordering::Greater,
354
355            (JsonValue::String(a), JsonValue::String(b)) => a.cmp(b),
356            (JsonValue::String(_), _) => Ordering::Less,
357            (_, JsonValue::String(_)) => Ordering::Greater,
358
359            (JsonValue::Array(a), JsonValue::Array(b)) => a.cmp(b),
360            (JsonValue::Array(_), _) => Ordering::Less,
361            (_, JsonValue::Array(_)) => Ordering::Greater,
362
363            (JsonValue::Object(a), JsonValue::Object(b)) => {
364                // 按字典序比较键值对
365                let mut a_iter = a.iter();
366                let mut b_iter = b.iter();
367                loop {
368                    match (a_iter.next(), b_iter.next()) {
369                        (None, None) => return Ordering::Equal,
370                        (None, Some(_)) => return Ordering::Less,
371                        (Some(_), None) => return Ordering::Greater,
372                        (Some((ak, av)), Some((bk, bv))) => match ak.cmp(bk) {
373                            Ordering::Equal => match av.cmp(bv) {
374                                Ordering::Equal => {}
375                                other => return other,
376                            },
377                            other => return other,
378                        },
379                    }
380                }
381            }
382        }
383    }
384}
385
386impl PartialOrd for JsonValue {
387    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
388        Some(self.cmp(other))
389    }
390}
391
392impl JsonValue {
393    // ===== 类型检查 =====
394
395    /// 检查是否为对象类型
396    pub fn is_object(&self) -> bool {
397        matches!(self, JsonValue::Object(_))
398    }
399
400    /// 检查是否为数组类型
401    pub fn is_array(&self) -> bool {
402        matches!(self, JsonValue::Array(_))
403    }
404
405    /// 检查是否为整数类型
406    pub fn is_integer(&self) -> bool {
407        matches!(self, JsonValue::Integer(_))
408    }
409
410    /// 检查是否为无符号整数类型(u64 全域通道)
411    pub fn is_u64(&self) -> bool {
412        matches!(self, JsonValue::U64(_))
413    }
414
415    /// 检查是否为字符串类型
416    pub fn is_string(&self) -> bool {
417        matches!(self, JsonValue::String(_))
418    }
419
420    /// 检查是否为布尔类型
421    pub fn is_bool(&self) -> bool {
422        matches!(self, JsonValue::Bool(_))
423    }
424
425    /// 检查是否为 null
426    pub fn is_null(&self) -> bool {
427        matches!(self, JsonValue::Null)
428    }
429
430    /// 获取值的长度(数组元素个数或对象键值对数)
431    ///
432    /// # 示例
433    ///
434    /// ```
435    /// use evorule_tcb::JsonValue;
436    ///
437    /// let arr = JsonValue::array(vec![JsonValue::Integer(1), JsonValue::Integer(2)]);
438    /// assert_eq!(arr.len(), Some(2));
439    ///
440    /// let obj = JsonValue::empty_object();
441    /// assert_eq!(obj.len(), Some(0));
442    ///
443    /// let null = JsonValue::Null;
444    /// assert_eq!(null.len(), None);
445    /// ```
446    pub fn len(&self) -> Option<usize> {
447        match self {
448            JsonValue::Array(arr) => Some(arr.len()),
449            JsonValue::Object(map) => Some(map.len()),
450            _ => None,
451        }
452    }
453
454    /// 检查是否为空(数组或对象)
455    pub fn is_empty(&self) -> bool {
456        match self {
457            JsonValue::Array(arr) => arr.is_empty(),
458            JsonValue::Object(map) => map.is_empty(),
459            _ => false,
460        }
461    }
462
463    // ===== 类型转换 =====
464
465    /// 尝试转换为 i64
466    pub fn as_i64(&self) -> Option<i64> {
467        match self {
468            JsonValue::Integer(v) => Some(*v),
469            _ => None,
470        }
471    }
472
473    /// 尝试转换为 u64(仅 [`JsonValue::U64`] 命中;与 `as_i64` 形态严格对称)
474    pub fn as_u64(&self) -> Option<u64> {
475        match self {
476            JsonValue::U64(v) => Some(*v),
477            _ => None,
478        }
479    }
480
481    /// 尝试转换为 &str
482    pub fn as_str(&self) -> Option<&str> {
483        match self {
484            JsonValue::String(s) => Some(s.as_ref()),
485            _ => None,
486        }
487    }
488
489    /// 尝试转换为 bool
490    pub fn as_bool(&self) -> Option<bool> {
491        match self {
492            JsonValue::Bool(b) => Some(*b),
493            _ => None,
494        }
495    }
496
497    /// 尝试转换为 &[JsonValue]
498    pub fn as_array(&self) -> Option<&[JsonValue]> {
499        match self {
500            JsonValue::Array(arr) => Some(arr.as_slice()),
501            _ => None,
502        }
503    }
504
505    /// 尝试转换为 &mut [JsonValue]
506    pub fn as_array_mut(&mut self) -> Option<&mut [JsonValue]> {
507        match self {
508            JsonValue::Array(arr) => Some(arr.as_mut_slice()),
509            _ => None,
510        }
511    }
512
513    /// 尝试转换为 &ObjectMap
514    pub fn as_object(&self) -> Option<&ObjectMap> {
515        match self {
516            JsonValue::Object(map) => Some(map),
517            _ => None,
518        }
519    }
520
521    /// 尝试转换为 &mut ObjectMap
522    pub fn as_object_mut(&mut self) -> Option<&mut ObjectMap> {
523        match self {
524            JsonValue::Object(map) => Some(map),
525            _ => None,
526        }
527    }
528
529    // ===== 对象操作 =====
530
531    /// 获取对象字段(若存在)
532    ///
533    /// # 示例
534    ///
535    /// ```
536    /// extern crate alloc;
537    /// use evorule_tcb::JsonValue;
538    /// use alloc::collections::BTreeMap;
539    ///
540    /// let mut map = BTreeMap::new();
541    /// map.insert("a".to_string(), JsonValue::Integer(1));
542    /// let obj = JsonValue::object(map);
543    ///
544    /// assert_eq!(obj.get("a").and_then(|v| v.as_i64()), Some(1));
545    /// assert_eq!(obj.get("missing"), None);
546    ///
547    /// // 在非对象上调用总是返回 None(不会 panic)
548    /// let n = JsonValue::Null;
549    /// assert_eq!(n.get("anything"), None);
550    /// ```
551    pub fn get(&self, key: &str) -> Option<&JsonValue> {
552        match self {
553            JsonValue::Object(map) => map.get(key),
554            _ => None,
555        }
556    }
557
558    /// 获取对象字段(可变)
559    pub fn get_mut(&mut self, key: &str) -> Option<&mut JsonValue> {
560        match self {
561            JsonValue::Object(map) => map.get_mut(key),
562            _ => None,
563        }
564    }
565
566    /// 插入或更新对象字段
567    ///
568    /// # 示例
569    ///
570    /// ```
571    /// use evorule_tcb::JsonValue;
572    ///
573    /// let mut obj = JsonValue::empty_object();
574    /// let old = obj.insert("k".to_string(), JsonValue::Integer(1));
575    /// assert_eq!(old, None);
576    ///
577    /// let old = obj.insert("k".to_string(), JsonValue::Integer(2));
578    /// assert_eq!(old.and_then(|v| v.as_i64()), Some(1));
579    /// assert_eq!(obj.get("k").and_then(|v| v.as_i64()), Some(2));
580    /// ```
581    pub fn insert(&mut self, key: String, value: JsonValue) -> Option<JsonValue> {
582        match self {
583            JsonValue::Object(map) => map.insert(key, value),
584            _ => None,
585        }
586    }
587
588    /// 尝试插入(如果 key 已存在则返回错误)
589    ///
590    /// # 示例
591    ///
592    /// ```
593    /// use evorule_tcb::JsonValue;
594    ///
595    /// let mut obj = JsonValue::empty_object();
596    /// assert!(obj.try_insert("k".to_string(), JsonValue::Integer(1)).is_ok());
597    /// assert!(obj.try_insert("k".to_string(), JsonValue::Integer(2)).is_err());
598    /// ```
599    /// # 为什么显式 `allow(clippy::map_entry)` 而不是改用 Entry API
600    ///
601    /// Clippy 的 `map_entry` 建议改写为 `BTreeMap::entry`,但**本函数的类型
602    /// 由 cfg 决定**(见 [`ObjectMap`]):
603    ///
604    /// - `cfg(not(kani))` → `BTreeMap`,**有** `Entry` API;
605    /// - `cfg(kani)` → [`KaniMap`](有序 `Vec`),**没有** `Entry` API——
606    ///   它的存在正是为了绕开 CBMC 对红黑树插入的状态爆炸。
607    ///
608    /// 两条分支都必须编译同一份源码,所以**不能**使用任一后端专有的 API。
609    /// 这里保留 `contains_key` + `get`/`insert` 是**唯一后端无关**的写法,
610    /// 且零性能代价(`contains_key` 与 `get` 走的是同一个 `BTreeMap` 查找路径,
611    /// 差别仅在返回类型)。**不要"修好"它。**
612    #[allow(clippy::map_entry)]
613    pub fn try_insert(&mut self, key: String, value: JsonValue) -> Result<(), &JsonValue> {
614        // 后端无关实现(BTreeMap / KaniMap 通用):命中返回既有值的引用,
615        // 未命中插入。不使用 BTreeMap 专有的 Entry API,保证 cfg(kani) 下
616        // ObjectMap 切换为 KaniMap 后同一份源码可直接编译。
617        // contains_key 先行判定(返回 bool 不持有借用),get 借用与
618        // insert 可变借用分离,满足 NLL。
619        match self {
620            JsonValue::Object(map) => {
621                if map.contains_key(&key) {
622                    match map.get(&key) {
623                        Some(existing) => Err(existing),
624                        None => Err(null_ref()),
625                    }
626                } else {
627                    map.insert(key, value);
628                    Ok(())
629                }
630            }
631            _ => Err(null_ref()),
632        }
633    }
634
635    /// 从对象中移除字段
636    pub fn remove(&mut self, key: &str) -> Option<JsonValue> {
637        match self {
638            JsonValue::Object(map) => map.remove(key),
639            _ => None,
640        }
641    }
642
643    /// 清空对象或数组的所有内容
644    ///
645    /// # 示例
646    ///
647    /// ```
648    /// use evorule_tcb::JsonValue;
649    ///
650    /// let mut arr = JsonValue::array(vec![JsonValue::Integer(1), JsonValue::Integer(2)]);
651    /// arr.clear();
652    /// assert_eq!(arr.len(), Some(0));
653    ///
654    /// // 对非容器类型调用是 no-op
655    /// let mut null = JsonValue::Null;
656    /// null.clear();
657    /// ```
658    pub fn clear(&mut self) {
659        match self {
660            JsonValue::Array(arr) => arr.clear(),
661            JsonValue::Object(map) => map.clear(),
662            _ => {}
663        }
664    }
665}
666
667// ===== Display 实现 =====
668
669impl fmt::Display for JsonValue {
670    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
671        match self {
672            JsonValue::Null => write!(f, "null"),
673            JsonValue::Bool(b) => write!(f, "{b}"),
674            JsonValue::Integer(i) => write!(f, "{i}"),
675            JsonValue::U64(v) => write!(f, "{v}"),
676            JsonValue::String(s) => escape_json_string(s.as_ref(), f),
677            JsonValue::Array(arr) => {
678                write!(f, "[")?;
679                for (i, v) in arr.iter().enumerate() {
680                    if i > 0 {
681                        write!(f, ", ")?;
682                    }
683                    write!(f, "{v}")?;
684                }
685                write!(f, "]")
686            }
687            JsonValue::Object(map) => {
688                write!(f, "{{")?;
689                for (i, (k, v)) in map.iter().enumerate() {
690                    if i > 0 {
691                        write!(f, ", ")?;
692                    }
693                    escape_json_string(k, f)?;
694                    write!(f, ": {v}")?;
695                }
696                write!(f, "}}")
697            }
698        }
699    }
700}
701
702/// JSON 字符串转义辅助函数
703///
704/// 将字符串按 JSON 标准转义后写入 Formatter。
705/// 同时用于字符串值和对象键。
706fn escape_json_string(s: &str, f: &mut fmt::Formatter<'_>) -> fmt::Result {
707    write!(f, "\"")?;
708    for c in s.chars() {
709        match c {
710            '"' => write!(f, "\\\"")?,
711            '\\' => write!(f, "\\\\")?,
712            '\n' => write!(f, "\\n")?,
713            '\r' => write!(f, "\\r")?,
714            '\t' => write!(f, "\\t")?,
715            '\x08' => write!(f, "\\b")?,
716            '\x0c' => write!(f, "\\f")?,
717            c if (c as u32) < 0x20 => write!(f, "\\u{:04x}", c as u32)?,
718            c => write!(f, "{c}")?,
719        }
720    }
721    write!(f, "\"")
722}
723
724// ===== 构造函数 =====
725
726impl JsonValue {
727    /// 构造 null
728    pub const fn null() -> Self {
729        JsonValue::Null
730    }
731
732    /// 构造布尔值
733    pub const fn bool(b: bool) -> Self {
734        JsonValue::Bool(b)
735    }
736
737    /// 构造整数
738    pub const fn integer(i: i64) -> Self {
739        JsonValue::Integer(i)
740    }
741
742    /// 构造无符号整数(u64 全域通道)
743    ///
744    /// # 示例
745    ///
746    /// ```
747    /// use evorule_tcb::JsonValue;
748    ///
749    /// let v = JsonValue::u64(u64::MAX - 1);
750    /// assert!(v.is_u64());
751    /// assert_eq!(v.as_u64(), Some(u64::MAX - 1));
752    /// // 形态严格:U64 与 Integer 不做跨形态相等
753    /// assert_ne!(JsonValue::u64(5), JsonValue::Integer(5));
754    /// ```
755    pub const fn u64(v: u64) -> Self {
756        JsonValue::U64(v)
757    }
758
759    /// 构造字符串
760    ///
761    /// # 示例
762    ///
763    /// ```
764    /// use evorule_tcb::JsonValue;
765    ///
766    /// let v = JsonValue::string("hello");
767    /// assert_eq!(v.as_str(), Some("hello"));
768    /// ```
769    pub fn string<S: Into<String>>(s: S) -> Self {
770        JsonValue::String(Cow::Owned(s.into()))
771    }
772
773    /// 构造数组
774    ///
775    /// # 示例
776    ///
777    /// ```
778    /// use evorule_tcb::JsonValue;
779    ///
780    /// let arr = JsonValue::array(vec![JsonValue::Integer(1), JsonValue::Integer(2)]);
781    /// assert!(arr.is_array());
782    /// assert_eq!(arr.as_array().map(|a| a.len()), Some(2));
783    /// ```
784    pub fn array(v: Vec<JsonValue>) -> Self {
785        JsonValue::Array(v)
786    }
787
788    /// 构造对象
789    ///
790    /// # 示例
791    ///
792    /// ```
793    /// extern crate alloc;
794    /// use evorule_tcb::JsonValue;
795    /// use alloc::collections::BTreeMap;
796    ///
797    /// let mut map = BTreeMap::new();
798    /// map.insert("key".to_string(), JsonValue::Integer(42));
799    /// let obj = JsonValue::object(map);
800    /// assert!(obj.is_object());
801    /// assert_eq!(obj.get("key").and_then(|v| v.as_i64()), Some(42));
802    /// ```
803    pub fn object(map: ObjectMap) -> Self {
804        JsonValue::Object(map)
805    }
806
807    /// 从键值对构造对象(转移所有权版本)
808    ///
809    /// 比 `object_from_pairs` 更高效,因为不需要克隆值。
810    ///
811    /// # 示例
812    ///
813    /// ```
814    /// use evorule_tcb::JsonValue;
815    ///
816    /// let pairs = vec![
817    ///     ("a".to_string(), JsonValue::Integer(1)),
818    ///     ("b".to_string(), JsonValue::Integer(2)),
819    /// ];
820    /// let obj = JsonValue::object_from_pairs_owned(pairs);
821    /// assert_eq!(obj.get("a").and_then(|v| v.as_i64()), Some(1));
822    /// ```
823    pub fn object_from_pairs_owned(pairs: Vec<(String, JsonValue)>) -> Self {
824        let mut map = ObjectMap::new();
825        for (k, v) in pairs {
826            map.insert(k, v);
827        }
828        JsonValue::Object(map)
829    }
830
831    /// 从键值对构造对象(借用版本,会克隆值)
832    ///
833    /// 注意:此方法会克隆所有值。如需避免克隆,请使用 `object_from_pairs_owned`。
834    ///
835    /// # 示例
836    ///
837    /// ```
838    /// use evorule_tcb::JsonValue;
839    ///
840    /// let obj = JsonValue::object_from_pairs(&[
841    ///     ("a", JsonValue::Integer(1)),
842    ///     ("b", JsonValue::Integer(2)),
843    /// ]);
844    /// assert_eq!(obj.get("a").and_then(|v| v.as_i64()), Some(1));
845    /// ```
846    pub fn object_from_pairs(pairs: &[(&str, JsonValue)]) -> Self {
847        let mut map = ObjectMap::new();
848        for (k, v) in pairs {
849            map.insert((*k).to_string(), v.clone());
850        }
851        JsonValue::Object(map)
852    }
853
854    /// 构造空对象
855    ///
856    /// # 示例
857    ///
858    /// ```
859    /// use evorule_tcb::JsonValue;
860    ///
861    /// let obj = JsonValue::empty_object();
862    /// assert!(obj.is_object());
863    /// assert_eq!(obj.as_object().map(|m| m.len()), Some(0));
864    /// ```
865    pub fn empty_object() -> Self {
866        JsonValue::Object(ObjectMap::new())
867    }
868
869    /// 构造空数组
870    ///
871    /// # 示例
872    ///
873    /// ```
874    /// use evorule_tcb::JsonValue;
875    ///
876    /// let arr = JsonValue::empty_array();
877    /// assert!(arr.is_array());
878    /// assert_eq!(arr.as_array().map(|a| a.len()), Some(0));
879    /// ```
880    pub fn empty_array() -> Self {
881        JsonValue::Array(Vec::new())
882    }
883}
884
885// ===== From trait 实现 =====
886
887/// 从 BTreeMap 快捷构造对象
888impl From<ObjectMap> for JsonValue {
889    fn from(map: ObjectMap) -> Self {
890        JsonValue::Object(map)
891    }
892}
893
894/// 从 Vec 快捷构造数组
895impl From<Vec<JsonValue>> for JsonValue {
896    fn from(v: Vec<JsonValue>) -> Self {
897        JsonValue::Array(v)
898    }
899}
900
901/// 从 &str 快捷构造字符串
902impl From<&str> for JsonValue {
903    fn from(s: &str) -> Self {
904        JsonValue::String(Cow::Owned(s.to_string()))
905    }
906}
907
908/// 从 String 快捷构造字符串
909impl From<String> for JsonValue {
910    fn from(s: String) -> Self {
911        JsonValue::String(Cow::Owned(s))
912    }
913}
914
915/// 从 Cow<'static, str> 快捷构造字符串
916impl From<Cow<'static, str>> for JsonValue {
917    fn from(s: Cow<'static, str>) -> Self {
918        JsonValue::String(s)
919    }
920}
921
922/// 从 i64 快捷构造整数
923impl From<i64> for JsonValue {
924    fn from(i: i64) -> Self {
925        JsonValue::Integer(i)
926    }
927}
928
929/// 从 u64 快捷构造无符号整数(u64 全域通道,无 i64 cast 回绕)
930impl From<u64> for JsonValue {
931    fn from(v: u64) -> Self {
932        JsonValue::U64(v)
933    }
934}
935
936/// 从 bool 快捷构造布尔
937impl From<bool> for JsonValue {
938    fn from(b: bool) -> Self {
939        JsonValue::Bool(b)
940    }
941}
942
943#[cfg(test)]
944mod tests {
945    #![allow(clippy::unwrap_used)]
946    #![allow(clippy::expect_used)]
947    #![allow(clippy::panic)]
948    #![allow(clippy::indexing_slicing)]
949
950    use super::*;
951    use alloc::format;
952    use alloc::vec;
953    use core::cmp::Ordering;
954
955    // ===== 构造函数测试 =====
956
957    #[test]
958    fn test_const_constructors() {
959        const N: JsonValue = JsonValue::null();
960        const B: JsonValue = JsonValue::bool(true);
961        const I: JsonValue = JsonValue::integer(-7);
962        assert_eq!(N, JsonValue::Null);
963        assert_eq!(B, JsonValue::Bool(true));
964        assert_eq!(I, JsonValue::Integer(-7));
965    }
966
967    #[test]
968    fn test_string_constructor() {
969        let s = JsonValue::string("hello");
970        assert_eq!(s.as_str(), Some("hello"));
971        let owned = JsonValue::string(String::from("world"));
972        assert_eq!(owned.as_str(), Some("world"));
973    }
974
975    #[test]
976    fn test_empty_array() {
977        assert_eq!(JsonValue::empty_array(), JsonValue::Array(Vec::new()));
978    }
979
980    #[test]
981    fn test_empty_object() {
982        assert!(JsonValue::empty_object().is_object());
983        assert_eq!(JsonValue::empty_object().len(), Some(0));
984    }
985
986    #[test]
987    fn test_object_from_pairs_owned() {
988        let pairs = vec![
989            ("a".to_string(), JsonValue::Integer(1)),
990            ("b".to_string(), JsonValue::Integer(2)),
991        ];
992        let obj = JsonValue::object_from_pairs_owned(pairs);
993        assert_eq!(obj.get("a").and_then(|v| v.as_i64()), Some(1));
994        assert_eq!(obj.get("b").and_then(|v| v.as_i64()), Some(2));
995    }
996
997    // ===== 类型检查测试 =====
998
999    #[test]
1000    fn test_is_methods_match_correct_type() {
1001        assert!(JsonValue::Null.is_null());
1002        assert!(JsonValue::Bool(true).is_bool());
1003        assert!(JsonValue::Integer(0).is_integer());
1004        assert!(JsonValue::string("x").is_string());
1005        assert!(JsonValue::empty_array().is_array());
1006        assert!(JsonValue::empty_object().is_object());
1007    }
1008
1009    #[test]
1010    fn test_is_methods_reject_wrong_type() {
1011        assert!(!JsonValue::Null.is_bool());
1012        assert!(!JsonValue::Null.is_integer());
1013        assert!(!JsonValue::Integer(1).is_string());
1014        assert!(!JsonValue::string("x").is_array());
1015        assert!(!JsonValue::empty_array().is_object());
1016        assert!(!JsonValue::Bool(false).is_null());
1017    }
1018
1019    // ===== len() 和 is_empty() 测试 =====
1020
1021    #[test]
1022    fn test_len_and_is_empty() {
1023        assert_eq!(JsonValue::Null.len(), None);
1024        assert_eq!(JsonValue::Integer(42).len(), None);
1025        assert_eq!(JsonValue::string("test").len(), None);
1026
1027        let arr = JsonValue::array(vec![JsonValue::Integer(1), JsonValue::Integer(2)]);
1028        assert_eq!(arr.len(), Some(2));
1029        assert!(!arr.is_empty());
1030
1031        let empty_arr = JsonValue::empty_array();
1032        assert_eq!(empty_arr.len(), Some(0));
1033        assert!(empty_arr.is_empty());
1034
1035        let obj = JsonValue::object_from_pairs(&[("a", JsonValue::Integer(1))]);
1036        assert_eq!(obj.len(), Some(1));
1037        assert!(!obj.is_empty());
1038
1039        assert!(JsonValue::empty_object().is_empty());
1040    }
1041
1042    // ===== 类型转换测试 =====
1043
1044    #[test]
1045    fn test_as_methods_success_paths() {
1046        assert_eq!(JsonValue::Integer(42).as_i64(), Some(42));
1047        assert_eq!(JsonValue::string("hi").as_str(), Some("hi"));
1048        assert_eq!(JsonValue::Bool(true).as_bool(), Some(true));
1049        assert!(JsonValue::empty_array().as_array().is_some());
1050        assert!(JsonValue::empty_object().as_object().is_some());
1051    }
1052
1053    #[test]
1054    fn test_as_methods_type_mismatch_returns_none() {
1055        assert_eq!(JsonValue::Null.as_i64(), None);
1056        assert_eq!(JsonValue::Bool(true).as_i64(), None);
1057        assert_eq!(JsonValue::string("x").as_i64(), None);
1058        assert_eq!(JsonValue::Null.as_str(), None);
1059        assert_eq!(JsonValue::Integer(1).as_str(), None);
1060        assert_eq!(JsonValue::Integer(1).as_bool(), None);
1061        assert_eq!(JsonValue::Null.as_array(), None);
1062        assert_eq!(JsonValue::Integer(0).as_array(), None);
1063        assert_eq!(JsonValue::Null.as_object(), None);
1064        assert_eq!(JsonValue::Integer(0).as_object(), None);
1065    }
1066
1067    #[test]
1068    fn test_as_mut_methods_type_mismatch() {
1069        let mut v = JsonValue::Integer(0);
1070        assert!(v.as_array_mut().is_none());
1071        assert!(v.as_object_mut().is_none());
1072        let mut arr = JsonValue::empty_array();
1073        assert!(arr.as_array_mut().is_some());
1074        let mut obj = JsonValue::empty_object();
1075        assert!(obj.as_object_mut().is_some());
1076    }
1077
1078    // ===== 对象操作测试 =====
1079
1080    #[test]
1081    fn test_object_accessors_on_non_object() {
1082        let mut v = JsonValue::Integer(0);
1083        assert_eq!(v.get("any"), None);
1084        assert_eq!(v.get_mut("any"), None);
1085        assert_eq!(v.insert("k".to_string(), JsonValue::Null), None);
1086        assert_eq!(v.remove("k"), None);
1087        assert_eq!(v, JsonValue::Integer(0));
1088    }
1089
1090    #[test]
1091    fn test_get_on_object() {
1092        let obj = JsonValue::object_from_pairs(&[("x", JsonValue::Integer(7))]);
1093        assert_eq!(obj.get("x"), Some(&JsonValue::Integer(7)));
1094        assert_eq!(obj.get("missing"), None);
1095    }
1096
1097    #[test]
1098    fn test_get_mut_on_object() {
1099        let mut obj = JsonValue::object_from_pairs(&[("a", JsonValue::Integer(1))]);
1100        if let Some(v) = obj.get_mut("a") {
1101            *v = JsonValue::Integer(42);
1102        }
1103        assert_eq!(obj.get("a"), Some(&JsonValue::Integer(42)));
1104        assert_eq!(obj.get_mut("missing"), None);
1105    }
1106
1107    #[test]
1108    fn test_insert_and_remove() {
1109        let mut obj = JsonValue::empty_object();
1110        assert_eq!(obj.insert("k".to_string(), JsonValue::Integer(1)), None);
1111        assert_eq!(obj.get("k"), Some(&JsonValue::Integer(1)));
1112
1113        let old = obj.insert("k".to_string(), JsonValue::Integer(2));
1114        assert_eq!(old, Some(JsonValue::Integer(1)));
1115        assert_eq!(obj.get("k"), Some(&JsonValue::Integer(2)));
1116
1117        assert_eq!(obj.remove("k"), Some(JsonValue::Integer(2)));
1118        assert_eq!(obj.get("k"), None);
1119        assert_eq!(obj.remove("missing"), None);
1120    }
1121
1122    #[test]
1123    fn test_try_insert() {
1124        let mut obj = JsonValue::empty_object();
1125        assert!(obj
1126            .try_insert("k".to_string(), JsonValue::Integer(1))
1127            .is_ok());
1128        assert!(obj
1129            .try_insert("k".to_string(), JsonValue::Integer(2))
1130            .is_err());
1131        assert_eq!(obj.get("k"), Some(&JsonValue::Integer(1)));
1132
1133        let mut non_obj = JsonValue::Integer(0);
1134        assert!(non_obj
1135            .try_insert("k".to_string(), JsonValue::Integer(1))
1136            .is_err());
1137    }
1138
1139    #[test]
1140    fn test_clear() {
1141        let mut arr = JsonValue::array(vec![JsonValue::Integer(1), JsonValue::Integer(2)]);
1142        arr.clear();
1143        assert_eq!(arr.len(), Some(0));
1144
1145        let mut obj = JsonValue::object_from_pairs(&[("a", JsonValue::Integer(1))]);
1146        obj.clear();
1147        assert_eq!(obj.len(), Some(0));
1148
1149        let mut null = JsonValue::Null;
1150        null.clear(); // no-op
1151        assert!(null.is_null());
1152    }
1153
1154    // ===== PartialEq 测试 =====
1155
1156    #[test]
1157    fn test_partial_eq_same_type() {
1158        assert_eq!(JsonValue::Null, JsonValue::Null);
1159        assert_eq!(JsonValue::Bool(true), JsonValue::Bool(true));
1160        assert_eq!(JsonValue::Integer(5), JsonValue::Integer(5));
1161        assert_eq!(JsonValue::string("hi"), JsonValue::string("hi"));
1162        assert_eq!(
1163            JsonValue::array(vec![JsonValue::Integer(1)]),
1164            JsonValue::array(vec![JsonValue::Integer(1)])
1165        );
1166    }
1167
1168    #[test]
1169    fn test_partial_eq_cross_type() {
1170        assert_ne!(JsonValue::Null, JsonValue::Bool(false));
1171        assert_ne!(JsonValue::Bool(true), JsonValue::Integer(1));
1172        assert_ne!(JsonValue::Integer(0), JsonValue::string("0"));
1173        assert_ne!(JsonValue::string(""), JsonValue::empty_array());
1174        assert_ne!(JsonValue::empty_array(), JsonValue::empty_object());
1175    }
1176
1177    #[test]
1178    fn test_partial_eq_object() {
1179        let mut a = ObjectMap::new();
1180        a.insert("x".to_string(), JsonValue::Integer(1));
1181        a.insert("y".to_string(), JsonValue::Integer(2));
1182        let mut b = ObjectMap::new();
1183        b.insert("x".to_string(), JsonValue::Integer(1));
1184        b.insert("y".to_string(), JsonValue::Integer(2));
1185        assert_eq!(JsonValue::object(a.clone()), JsonValue::object(b));
1186
1187        let mut c = ObjectMap::new();
1188        c.insert("x".to_string(), JsonValue::Integer(1));
1189        c.insert("y".to_string(), JsonValue::Integer(99));
1190        assert_ne!(JsonValue::object(a.clone()), JsonValue::object(c));
1191
1192        let mut d = ObjectMap::new();
1193        d.insert("x".to_string(), JsonValue::Integer(1));
1194        d.insert("z".to_string(), JsonValue::Integer(2));
1195        assert_ne!(JsonValue::object(a.clone()), JsonValue::object(d));
1196
1197        let mut e = ObjectMap::new();
1198        e.insert("x".to_string(), JsonValue::Integer(1));
1199        assert_ne!(JsonValue::object(a), JsonValue::object(e));
1200    }
1201
1202    // ===== Ord 测试 =====
1203
1204    #[test]
1205    fn test_ord_type_order() {
1206        assert_eq!(JsonValue::Null.cmp(&JsonValue::Null), Ordering::Equal);
1207        assert!(JsonValue::Null < JsonValue::Bool(false));
1208        assert!(JsonValue::Bool(false) < JsonValue::Integer(0));
1209        assert!(JsonValue::Integer(0) < JsonValue::string(""));
1210        assert!(JsonValue::string("") < JsonValue::empty_array());
1211        assert!(JsonValue::empty_array() < JsonValue::empty_object());
1212    }
1213
1214    #[test]
1215    fn test_ord_lexicographic() {
1216        assert!(JsonValue::Integer(0) < JsonValue::Integer(1));
1217        assert!(JsonValue::string("a") < JsonValue::string("b"));
1218
1219        let mut short = ObjectMap::new();
1220        short.insert("a".to_string(), JsonValue::Integer(1));
1221        let mut long = ObjectMap::new();
1222        long.insert("a".to_string(), JsonValue::Integer(1));
1223        long.insert("b".to_string(), JsonValue::Integer(2));
1224        assert!(JsonValue::object(short) < JsonValue::object(long));
1225    }
1226
1227    // ===== Display 测试 =====
1228
1229    #[test]
1230    fn test_display_simple_types() {
1231        assert_eq!(format!("{}", JsonValue::Null), "null");
1232        assert_eq!(format!("{}", JsonValue::Bool(true)), "true");
1233        assert_eq!(format!("{}", JsonValue::Bool(false)), "false");
1234        assert_eq!(format!("{}", JsonValue::Integer(0)), "0");
1235        assert_eq!(format!("{}", JsonValue::Integer(-42)), "-42");
1236    }
1237
1238    #[test]
1239    fn test_display_string_escapes() {
1240        assert_eq!(format!("{}", JsonValue::string("")), "\"\"");
1241        assert_eq!(format!("{}", JsonValue::string("hello")), "\"hello\"");
1242        assert_eq!(format!("{}", JsonValue::string("a\"b")), "\"a\\\"b\"");
1243        assert_eq!(format!("{}", JsonValue::string("a\\b")), "\"a\\\\b\"");
1244        assert_eq!(format!("{}", JsonValue::string("a\nb")), "\"a\\nb\"");
1245    }
1246
1247    #[test]
1248    fn test_display_array() {
1249        assert_eq!(format!("{}", JsonValue::empty_array()), "[]");
1250        let arr = JsonValue::array(vec![
1251            JsonValue::Integer(1),
1252            JsonValue::Integer(2),
1253            JsonValue::Integer(3),
1254        ]);
1255        assert_eq!(format!("{arr}"), "[1, 2, 3]");
1256    }
1257
1258    #[test]
1259    fn test_display_object() {
1260        assert_eq!(format!("{}", JsonValue::empty_object()), "{}");
1261        let obj = JsonValue::object_from_pairs(&[
1262            ("z", JsonValue::Integer(1)),
1263            ("a", JsonValue::Integer(2)),
1264        ]);
1265        assert_eq!(format!("{obj}"), "{\"a\": 2, \"z\": 1}");
1266    }
1267
1268    // ===== From trait 测试 =====
1269
1270    #[test]
1271    fn test_from_traits() {
1272        let v: JsonValue = 42i64.into();
1273        assert_eq!(v, JsonValue::Integer(42));
1274
1275        let v: JsonValue = "hello".into();
1276        assert_eq!(v, JsonValue::string("hello"));
1277
1278        let v: JsonValue = true.into();
1279        assert_eq!(v, JsonValue::Bool(true));
1280
1281        let v: JsonValue = vec![JsonValue::Integer(1), JsonValue::Integer(2)].into();
1282        assert_eq!(v.len(), Some(2));
1283    }
1284
1285    // ===== JSON 字符串转义边界(Display 面输出合法性)=====
1286
1287    /// 控制字符(< 0x20 且非专用转义字符)必须走 \u00XX 通道,
1288    /// 原样输出会产生非法 JSON(消费方解析即崩)
1289    #[test]
1290    fn test_display_escapes_control_chars() {
1291        let v = JsonValue::string("a\u{1}b");
1292        assert_eq!(v.to_string(), "\"a\\u0001b\"");
1293
1294        // \x1f 是 < 0x20 边界的最后一个非专用控制字符
1295        let v = JsonValue::string("\u{1f}");
1296        assert_eq!(v.to_string(), "\"\\u001f\"");
1297    }
1298
1299    /// 空格(0x20)是可打印字符,不属于转义区间——
1300    /// 转义上界写成 <= 会把空格错误转义为 \u0020
1301    #[test]
1302    fn test_display_space_verbatim() {
1303        let v = JsonValue::string("a b");
1304        assert_eq!(v.to_string(), "\"a b\"");
1305    }
1306
1307    // ===== U64(u64 全域通道)=====
1308
1309    #[test]
1310    fn test_u64_construct_and_access() {
1311        let v = JsonValue::u64(u64::MAX - 1);
1312        assert!(v.is_u64());
1313        assert!(!v.is_integer());
1314        assert_eq!(v.as_u64(), Some(u64::MAX - 1));
1315        // 形态严格对称:as_i64 只认 Integer,as_u64 只认 U64;
1316        // is_u64 同样只认 U64——Integer/Bool 等 non-U64 一律 false
1317        // (is_u64 恒 true 突变的负向杀灭断言,o01 批补)
1318        assert_eq!(v.as_i64(), None);
1319        assert_eq!(JsonValue::Integer(5).as_u64(), None);
1320        assert!(!JsonValue::Integer(5).is_u64());
1321        assert!(!JsonValue::Bool(true).is_u64());
1322        assert!(!JsonValue::Null.is_u64());
1323
1324        let from_trait: JsonValue = 42u64.into();
1325        assert_eq!(from_trait, JsonValue::u64(42));
1326    }
1327
1328    #[test]
1329    fn test_u64_partial_eq_strict_shape() {
1330        // 跨形态有意不相等(与 Ord 类型分组一致)
1331        assert_ne!(JsonValue::u64(5), JsonValue::Integer(5));
1332        assert_ne!(JsonValue::Integer(5), JsonValue::u64(5));
1333        assert_eq!(JsonValue::u64(5), JsonValue::u64(5));
1334        assert_ne!(JsonValue::u64(u64::MAX), JsonValue::u64(u64::MAX - 1));
1335    }
1336
1337    #[test]
1338    fn test_u64_ord_group_order() {
1339        // 组序:Integer < U64 < String(类型分组优先于数值)
1340        assert!(JsonValue::Integer(0) < JsonValue::u64(0));
1341        assert!(JsonValue::u64(0) < JsonValue::string(""));
1342        assert!(JsonValue::u64(0) < JsonValue::u64(1));
1343        assert!(JsonValue::u64(u64::MAX - 1) < JsonValue::u64(u64::MAX));
1344        // 整数组仍小于 U64 组内任意值(组间判定优先)
1345        assert!(JsonValue::Integer(i64::MAX) < JsonValue::u64(0));
1346    }
1347
1348    #[test]
1349    fn test_u64_display() {
1350        assert_eq!(format!("{}", JsonValue::u64(0)), "0");
1351        assert_eq!(
1352            format!("{}", JsonValue::u64(u64::MAX - 1)),
1353            "18446744073709551614"
1354        );
1355    }
1356}