evorule-primitives 0.1.0

EvoRule base primitive types: the deterministic JSON value model and the I/O handler contract (single definition site, zero evorule-* dependencies)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
// SPDX-License-Identifier: AGPL-3.0-or-later
// Copyright (C) 2026 EvoRule Project
// This file is part of EvoRule, licensed under GNU Affero General Public License v3 or later.
//! JSON value types — deterministic data model.
//!
//! # Design principles
//! - Clone-avoidance first (`Cow` to skip unnecessary copies)
//! - Deterministic iteration (`BTreeMap`)
//! - Type safety (all conversions return `Option`)
//! - Never panics
//!
//! # Migration note
//! This module is the single definition site of the value model. The
//! canonical repo (evorule-tcb / evorule-reactor) re-exports these types
//! unchanged, so every downstream API path and type identity is preserved.

use alloc::borrow::Cow;
use alloc::string::{String, ToString};
use alloc::vec::Vec;
use core::cmp::Ordering;
use core::fmt;

#[cfg(not(kani))]
use alloc::collections::BTreeMap;

/// Kani-verification object backend: ordered `Vec` emulating `BTreeMap`
/// (enabled under `cfg(kani)`).
///
/// # Root cause (probed 2026-09-13: the 23 tier-B proof timeouts)
///
/// Kani 0.67's CBMC backend models the `BTreeMap` red-black tree: inserting
/// >= 2 keys explodes the state space (90s+ without convergence; larger
/// unwinds do not help). An ordered `Vec` handles 3-key insert + get in 2-3s:
/// no pointer tracking, no recursive tree traversal — CBMC linear expansion
/// covers it.
///
/// # Semantic-equivalence guarantee
///
/// - Entries stay sorted by key (`insert` locates the position linearly and
///   maintains the invariant); `iter()` order matches `BTreeMap`;
/// - API signatures match the `BTreeMap<String, JsonValue>` methods in use
///   (`get`/`get_mut`/`insert`/`remove`/`contains_key`/`values`/`iter`, etc.);
/// - Production builds (`cfg(not(kani))`) are unaffected: `ObjectMap` stays
///   a `BTreeMap`.
#[cfg(kani)]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct KaniMap {
    /// Ordered entries (sorted by key, maintained by `insert`)
    entries: Vec<(String, JsonValue)>,
}

/// Kani-verification no-op `Drop` (same true-no-op pattern as `JsonValue`'s
/// no-op `Drop`, root cause documented there): prevents the compiler from
/// synthesizing a recursive field destructor for `entries`
/// (Vec -> per-element slice -> String RawVec::deallocate), which CBMC would
/// expand iteration by iteration (measured: verify_evaluate_domain_eq 11GB+
/// OOM, unwind log shows the Vec<(String, JsonValue)>/KaniMap drop chain
/// iterating 10-13 levels deep).
#[cfg(kani)]
impl Drop for KaniMap {
    fn drop(&mut self) {
        // Same true-no-op pattern as JsonValue Drop: take leaves an empty Vec,
        // forget skips destructing the taken entries; synthesized field drop then
        // destructs an empty Vec (nothing).
        let leaked = core::mem::take(&mut self.entries);
        core::mem::forget(leaked);
    }
}

#[cfg(kani)]
impl KaniMap {
    /// Key location: `Ok(index)` on hit; `Err(insertion point)` on miss
    /// (the first position holding a key greater than `key`)
    fn locate(&self, key: &str) -> Result<usize, usize> {
        for (i, (k, _)) in self.entries.iter().enumerate() {
            if k.as_str() == key {
                return Ok(i);
            }
            if k.as_str() > key {
                return Err(i);
            }
        }
        Err(self.entries.len())
    }

    /// Construct an empty map
    pub fn new() -> Self {
        KaniMap {
            entries: Vec::new(),
        }
    }

    /// Insert or update, returning the old value (semantics match `BTreeMap::insert`)
    pub fn insert(&mut self, key: String, value: JsonValue) -> Option<JsonValue> {
        match self.locate(&key) {
            Ok(i) => self
                .entries
                .get_mut(i)
                .map(|slot| core::mem::replace(&mut slot.1, value)),
            Err(pos) => {
                self.entries.insert(pos, (key, value));
                None
            }
        }
    }

    /// Lookup (semantics match `BTreeMap::get`)
    pub fn get(&self, key: &str) -> Option<&JsonValue> {
        match self.locate(key) {
            Ok(i) => self.entries.get(i).map(|(_, v)| v),
            Err(_) => None,
        }
    }

    /// Mutable lookup (semantics match `BTreeMap::get_mut`)
    pub fn get_mut(&mut self, key: &str) -> Option<&mut JsonValue> {
        match self.locate(key) {
            Ok(i) => match self.entries.get_mut(i) {
                Some((_, v)) => Some(v),
                None => None,
            },
            Err(_) => None,
        }
    }

    /// Remove and return the old value (semantics match `BTreeMap::remove`)
    pub fn remove(&mut self, key: &str) -> Option<JsonValue> {
        match self.locate(key) {
            Ok(i) => {
                let (_, value) = self.entries.remove(i);
                Some(value)
            }
            Err(_) => None,
        }
    }

    /// Key existence check (semantics match `BTreeMap::contains_key`)
    pub fn contains_key(&self, key: &str) -> bool {
        self.locate(key).is_ok()
    }

    /// Value iterator (semantics match `BTreeMap::values`)
    pub fn values(&self) -> impl Iterator<Item = &JsonValue> {
        self.entries.iter().map(|(_, v)| v)
    }

    /// Ordered entry iterator (iteration order matches `BTreeMap::iter`, keys sorted)
    pub fn iter(&self) -> core::slice::Iter<'_, (String, JsonValue)> {
        self.entries.iter()
    }

    /// Entry count
    pub fn len(&self) -> usize {
        self.entries.len()
    }

    /// Whether the map is empty
    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }

    /// Clear all entries
    pub fn clear(&mut self) {
        self.entries.clear();
    }
}

#[cfg(kani)]
impl Default for KaniMap {
    fn default() -> Self {
        KaniMap::new()
    }
}

#[cfg(kani)]
impl<'a> IntoIterator for &'a KaniMap {
    type Item = &'a (String, JsonValue);
    type IntoIter = core::slice::Iter<'a, (String, JsonValue)>;

    fn into_iter(self) -> Self::IntoIter {
        self.entries.iter()
    }
}

#[cfg(kani)]
impl IntoIterator for KaniMap {
    type Item = (String, JsonValue);
    type IntoIter = alloc::vec::IntoIter<(String, JsonValue)>;

    fn into_iter(mut self) -> Self::IntoIter {
        // mem::take: whole-value move (partial move-out rejected for Drop types)
        core::mem::take(&mut self.entries).into_iter()
    }
}

#[cfg(kani)]
impl<const N: usize> From<[(String, JsonValue); N]> for KaniMap {
    fn from(arr: [(String, JsonValue); N]) -> Self {
        let mut map = KaniMap::new();
        for (k, v) in arr {
            map.insert(k, v);
        }
        map
    }
}

/// Object backend type (`BTreeMap` guarantees deterministic iteration).
///
/// Under Kani builds (`cfg(kani)`) this switches to [`KaniMap`]: CBMC's
/// red-black-tree model of `BTreeMap` explodes the state space on >= 2-key
/// insertion (root cause of the 23 tier-B proof timeouts — see the
/// [`KaniMap`] documentation). The ordered-`Vec` backend keeps the API
/// compatible, the iteration order identical, and production behavior
/// unaffected.
#[cfg(not(kani))]
pub type ObjectMap = BTreeMap<String, JsonValue>;
/// `ObjectMap` under Kani builds (see documentation above).
#[cfg(kani)]
pub type ObjectMap = KaniMap;

/// JSON value type (deterministic implementation).
///
/// # Design decisions
/// - No `Float` variant (formal-verification obstacle)
/// - `BTreeMap` for deterministic iteration order
/// - `Vec` instead of `im::Vector`
/// - `Integer` is `i64` (Kani-friendly)
/// - `U64` is the full-range `u64` channel (v0.9.0): `Integer` cannot carry
///   high u64 values losslessly (e.g. the audit-chain rule-set anchor
///   `FactId(u64::MAX-1)` sentinel); any source whose value range may exceed
///   `i64` must go through `U64` — `as i64` cast wrap-around is forbidden
/// - `Cow` to reduce clone overhead
///
/// # Why `PartialEq` is not derived
/// Implemented manually to guarantee cross-language consistency.
///
/// # Examples
///
/// ```
/// extern crate alloc;
/// use evorule_primitives::JsonValue;
/// use alloc::collections::BTreeMap;
///
/// // Construct via constructors
/// let name = JsonValue::string("Alice");
/// let age = JsonValue::Integer(30);
/// assert!(name.is_string());
/// assert_eq!(age.as_i64(), Some(30));
///
/// // Construct via From impls
/// let from_str: JsonValue = "hello".into();
/// let from_int: JsonValue = 42i64.into();
/// assert_eq!(from_str.as_str(), Some("hello"));
/// assert_eq!(from_int.as_i64(), Some(42));
///
/// // Construct a nested object
/// let mut map = BTreeMap::new();
/// map.insert("items".to_string(), JsonValue::array(vec![JsonValue::Integer(1), JsonValue::Integer(2)]));
/// let v = JsonValue::object(map);
/// assert!(v.is_object());
/// ```
#[derive(Debug, Clone)]
pub enum JsonValue {
    /// JSON null
    Null,
    /// Boolean value
    Bool(bool),
    /// Integer (i64)
    Integer(i64),
    /// Unsigned integer (full-range u64 channel; strictly distinguished from
    /// [`JsonValue::Integer`] — no cross-shape numeric equality, see the
    /// [`PartialEq`] / [`Ord`] implementations)
    U64(u64),
    /// String (uses `Cow` to reduce cloning)
    String(Cow<'static, str>),
    /// Array (ordered list)
    Array(Vec<JsonValue>),
    /// Object (key-value pairs; `BTreeMap` guarantees deterministic order)
    Object(ObjectMap),
}

/// Kani-verification no-op `Drop`: skips modeling of JsonValue recursive
/// destruction.
///
/// Root cause (probed 2026-09-13): JsonValue's default Drop recursively
/// releases Vec/ObjectMap, and CBMC expands every destruction level along all
/// paths. Even with fully concrete constant inputs, temporaries
/// (to_string products, object_from_pairs inter-layer values, evaluate_domain
/// internal temporaries) still explode the state space during destruction
/// (verify_evaluate_domain_eq 11GB+ without convergence).
/// Kani builds have no real release requirement (the verification process
/// exits and the memory is reclaimed), so a no-op Drop makes CBMC skip
/// destruction expansion; production builds (`cfg(not(kani))`) keep the
/// default Drop, zero impact.
#[cfg(kani)]
impl Drop for JsonValue {
    fn drop(&mut self) {
        // Rust Drop semantics: drop_in_place = user Drop::drop THEN compiler-
        // synthesized field drops. An empty body does NOT suppress recursive field
        // destruction (measured: 11GB+ CBMC OOM, drop-chain iterations 10-13). True
        // no-op: swap self to fieldless Null and forget the old value, so the
        // subsequent synthesized field drops act on Null (no recursion).
        let leaked = core::mem::replace(self, JsonValue::Null);
        core::mem::forget(leaked);
    }
}

/// Kani build: static Null reference (explicit `impl Drop` blocks rvalue
/// promotion of `&JsonValue::Null`, see E0515); non-kani keeps promotion path.
#[cfg(kani)]
static NULL_VALUE: JsonValue = JsonValue::Null;

#[cfg(not(kani))]
fn null_ref() -> &'static JsonValue {
    &JsonValue::Null
}

#[cfg(kani)]
fn null_ref() -> &'static JsonValue {
    &NULL_VALUE
}

// Manual PartialEq implementation for cross-language consistency
impl PartialEq for JsonValue {
    fn eq(&self, other: &Self) -> bool {
        match (self, other) {
            (JsonValue::Null, JsonValue::Null) => true,
            (JsonValue::Bool(a), JsonValue::Bool(b)) => a == b,
            (JsonValue::Integer(a), JsonValue::Integer(b)) => a == b,
            (JsonValue::U64(a), JsonValue::U64(b)) => a == b,
            // Cross-shape (Integer vs U64) is intentionally unequal: shape
            // strictness keeps equality and Ord type grouping aligned, avoiding
            // an equality/ordering semantic split (callers convert shapes
            // explicitly when numeric comparison is needed).
            (JsonValue::String(a), JsonValue::String(b)) => a == b,
            (JsonValue::Array(a), JsonValue::Array(b)) => a == b,
            (JsonValue::Object(a), JsonValue::Object(b)) => {
                if a.len() != b.len() {
                    return false;
                }
                for (k, v) in a.iter() {
                    if let Some(bv) = b.get(k) {
                        if v != bv {
                            return false;
                        }
                    } else {
                        return false;
                    }
                }
                true
            }
            _ => false,
        }
    }
}

impl Eq for JsonValue {}

// Manual Ord implementation to support ordering inside BTreeMap
impl Ord for JsonValue {
    fn cmp(&self, other: &Self) -> Ordering {
        match (self, other) {
            // Type-group order: Null < Bool < Integer < U64 < String < Array < Object
            (JsonValue::Null, JsonValue::Null) => Ordering::Equal,
            (JsonValue::Null, _) => Ordering::Less,
            (_, JsonValue::Null) => Ordering::Greater,

            (JsonValue::Bool(a), JsonValue::Bool(b)) => a.cmp(b),
            (JsonValue::Bool(_), _) => Ordering::Less,
            (_, JsonValue::Bool(_)) => Ordering::Greater,

            (JsonValue::Integer(a), JsonValue::Integer(b)) => a.cmp(b),
            (JsonValue::Integer(_), _) => Ordering::Less,
            (_, JsonValue::Integer(_)) => Ordering::Greater,

            (JsonValue::U64(a), JsonValue::U64(b)) => a.cmp(b),
            (JsonValue::U64(_), _) => Ordering::Less,
            (_, JsonValue::U64(_)) => Ordering::Greater,

            (JsonValue::String(a), JsonValue::String(b)) => a.cmp(b),
            (JsonValue::String(_), _) => Ordering::Less,
            (_, JsonValue::String(_)) => Ordering::Greater,

            (JsonValue::Array(a), JsonValue::Array(b)) => a.cmp(b),
            (JsonValue::Array(_), _) => Ordering::Less,
            (_, JsonValue::Array(_)) => Ordering::Greater,

            (JsonValue::Object(a), JsonValue::Object(b)) => {
                // Lexicographic comparison of key-value pairs
                let mut a_iter = a.iter();
                let mut b_iter = b.iter();
                loop {
                    match (a_iter.next(), b_iter.next()) {
                        (None, None) => return Ordering::Equal,
                        (None, Some(_)) => return Ordering::Less,
                        (Some(_), None) => return Ordering::Greater,
                        (Some((ak, av)), Some((bk, bv))) => match ak.cmp(bk) {
                            Ordering::Equal => match av.cmp(bv) {
                                Ordering::Equal => {}
                                other => return other,
                            },
                            other => return other,
                        },
                    }
                }
            }
        }
    }
}

impl PartialOrd for JsonValue {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl JsonValue {
    // ===== Type checks =====

    /// Check whether the value is an object
    pub fn is_object(&self) -> bool {
        matches!(self, JsonValue::Object(_))
    }

    /// Check whether the value is an array
    pub fn is_array(&self) -> bool {
        matches!(self, JsonValue::Array(_))
    }

    /// Check whether the value is an integer
    pub fn is_integer(&self) -> bool {
        matches!(self, JsonValue::Integer(_))
    }

    /// Check whether the value is an unsigned integer (full-range u64 channel)
    pub fn is_u64(&self) -> bool {
        matches!(self, JsonValue::U64(_))
    }

    /// Check whether the value is a string
    pub fn is_string(&self) -> bool {
        matches!(self, JsonValue::String(_))
    }

    /// Check whether the value is a boolean
    pub fn is_bool(&self) -> bool {
        matches!(self, JsonValue::Bool(_))
    }

    /// Check whether the value is null
    pub fn is_null(&self) -> bool {
        matches!(self, JsonValue::Null)
    }

    /// Get the value's length (array element count or object entry count)
    ///
    /// # Examples
    ///
    /// ```
    /// use evorule_primitives::JsonValue;
    ///
    /// let arr = JsonValue::array(vec![JsonValue::Integer(1), JsonValue::Integer(2)]);
    /// assert_eq!(arr.len(), Some(2));
    ///
    /// let obj = JsonValue::empty_object();
    /// assert_eq!(obj.len(), Some(0));
    ///
    /// let null = JsonValue::Null;
    /// assert_eq!(null.len(), None);
    /// ```
    pub fn len(&self) -> Option<usize> {
        match self {
            JsonValue::Array(arr) => Some(arr.len()),
            JsonValue::Object(map) => Some(map.len()),
            _ => None,
        }
    }

    /// Check whether the value is empty (array or object)
    pub fn is_empty(&self) -> bool {
        match self {
            JsonValue::Array(arr) => arr.is_empty(),
            JsonValue::Object(map) => map.is_empty(),
            _ => false,
        }
    }

    // ===== Type conversions =====

    /// Try to convert to i64
    pub fn as_i64(&self) -> Option<i64> {
        match self {
            JsonValue::Integer(v) => Some(*v),
            _ => None,
        }
    }

    /// Try to convert to u64 (matches [`JsonValue::U64`] only; strictly
    /// symmetric with `as_i64` shape-wise)
    pub fn as_u64(&self) -> Option<u64> {
        match self {
            JsonValue::U64(v) => Some(*v),
            _ => None,
        }
    }

    /// Try to convert to &str
    pub fn as_str(&self) -> Option<&str> {
        match self {
            JsonValue::String(s) => Some(s.as_ref()),
            _ => None,
        }
    }

    /// Try to convert to bool
    pub fn as_bool(&self) -> Option<bool> {
        match self {
            JsonValue::Bool(b) => Some(*b),
            _ => None,
        }
    }

    /// Try to convert to &[JsonValue]
    pub fn as_array(&self) -> Option<&[JsonValue]> {
        match self {
            JsonValue::Array(arr) => Some(arr.as_slice()),
            _ => None,
        }
    }

    /// Try to convert to &mut [JsonValue]
    pub fn as_array_mut(&mut self) -> Option<&mut [JsonValue]> {
        match self {
            JsonValue::Array(arr) => Some(arr.as_mut_slice()),
            _ => None,
        }
    }

    /// Try to convert to &ObjectMap
    pub fn as_object(&self) -> Option<&ObjectMap> {
        match self {
            JsonValue::Object(map) => Some(map),
            _ => None,
        }
    }

    /// Try to convert to &mut ObjectMap
    pub fn as_object_mut(&mut self) -> Option<&mut ObjectMap> {
        match self {
            JsonValue::Object(map) => Some(map),
            _ => None,
        }
    }

    // ===== Object operations =====

    /// Get an object field (if present)
    ///
    /// # Examples
    ///
    /// ```
    /// extern crate alloc;
    /// use evorule_primitives::JsonValue;
    /// use alloc::collections::BTreeMap;
    ///
    /// let mut map = BTreeMap::new();
    /// map.insert("a".to_string(), JsonValue::Integer(1));
    /// let obj = JsonValue::object(map);
    ///
    /// assert_eq!(obj.get("a").and_then(|v| v.as_i64()), Some(1));
    /// assert_eq!(obj.get("missing"), None);
    ///
    /// // Calling on a non-object always returns None (never panics)
    /// let n = JsonValue::Null;
    /// assert_eq!(n.get("anything"), None);
    /// ```
    pub fn get(&self, key: &str) -> Option<&JsonValue> {
        match self {
            JsonValue::Object(map) => map.get(key),
            _ => None,
        }
    }

    /// Get an object field (mutable)
    pub fn get_mut(&mut self, key: &str) -> Option<&mut JsonValue> {
        match self {
            JsonValue::Object(map) => map.get_mut(key),
            _ => None,
        }
    }

    /// Insert or update an object field
    ///
    /// # Examples
    ///
    /// ```
    /// use evorule_primitives::JsonValue;
    ///
    /// let mut obj = JsonValue::empty_object();
    /// let old = obj.insert("k".to_string(), JsonValue::Integer(1));
    /// assert_eq!(old, None);
    ///
    /// let old = obj.insert("k".to_string(), JsonValue::Integer(2));
    /// assert_eq!(old.and_then(|v| v.as_i64()), Some(1));
    /// assert_eq!(obj.get("k").and_then(|v| v.as_i64()), Some(2));
    /// ```
    pub fn insert(&mut self, key: String, value: JsonValue) -> Option<JsonValue> {
        match self {
            JsonValue::Object(map) => map.insert(key, value),
            _ => None,
        }
    }

    /// Try to insert (returns an error if the key already exists)
    ///
    /// # Examples
    ///
    /// ```
    /// use evorule_primitives::JsonValue;
    ///
    /// let mut obj = JsonValue::empty_object();
    /// assert!(obj.try_insert("k".to_string(), JsonValue::Integer(1)).is_ok());
    /// assert!(obj.try_insert("k".to_string(), JsonValue::Integer(2)).is_err());
    /// ```
    /// # Why an explicit `allow(clippy::map_entry)` instead of the Entry API
    ///
    /// Clippy's `map_entry` lint suggests rewriting to `BTreeMap::entry`, but
    /// **the type of this function is cfg-determined** (see [`ObjectMap`]):
    ///
    /// - `cfg(not(kani))` -> `BTreeMap`, which **has** an `Entry` API;
    /// - `cfg(kani)` -> [`KaniMap`] (ordered `Vec`), which has **no** `Entry`
    ///   API — its whole point is to avoid CBMC's state explosion on red-black
    ///   tree insertion.
    ///
    /// Both branches must compile from the same source, so **no** backend-
    /// specific API can be used. Keeping `contains_key` + `get`/`insert` is
    /// the **only backend-independent** formulation, at zero performance cost
    /// (`contains_key` and `get` follow the same `BTreeMap` lookup path; only
    /// the return type differs). **Do not "fix" this.**
    #[allow(clippy::map_entry)]
    pub fn try_insert(&mut self, key: String, value: JsonValue) -> Result<(), &JsonValue> {
        // Backend-independent implementation (BTreeMap / KaniMap compatible):
        // on hit return a reference to the existing value; on miss insert.
        // No BTreeMap-specific Entry API, so the same source compiles once
        // cfg(kani) switches ObjectMap to KaniMap.
        // contains_key is checked first (returns bool, holds no borrow); the
        // get borrow and the insert mutable borrow are separated to satisfy NLL.
        match self {
            JsonValue::Object(map) => {
                if map.contains_key(&key) {
                    match map.get(&key) {
                        Some(existing) => Err(existing),
                        None => Err(null_ref()),
                    }
                } else {
                    map.insert(key, value);
                    Ok(())
                }
            }
            _ => Err(null_ref()),
        }
    }

    /// Remove a field from the object
    pub fn remove(&mut self, key: &str) -> Option<JsonValue> {
        match self {
            JsonValue::Object(map) => map.remove(key),
            _ => None,
        }
    }

    /// Clear all contents of the object or array
    ///
    /// # Examples
    ///
    /// ```
    /// use evorule_primitives::JsonValue;
    ///
    /// let mut arr = JsonValue::array(vec![JsonValue::Integer(1), JsonValue::Integer(2)]);
    /// arr.clear();
    /// assert_eq!(arr.len(), Some(0));
    ///
    /// // Calling on a non-container type is a no-op
    /// let mut null = JsonValue::Null;
    /// null.clear();
    /// ```
    pub fn clear(&mut self) {
        match self {
            JsonValue::Array(arr) => arr.clear(),
            JsonValue::Object(map) => map.clear(),
            _ => {}
        }
    }
}

// ===== Display implementation =====

impl fmt::Display for JsonValue {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            JsonValue::Null => write!(f, "null"),
            JsonValue::Bool(b) => write!(f, "{b}"),
            JsonValue::Integer(i) => write!(f, "{i}"),
            JsonValue::U64(v) => write!(f, "{v}"),
            JsonValue::String(s) => escape_json_string(s.as_ref(), f),
            JsonValue::Array(arr) => {
                write!(f, "[")?;
                for (i, v) in arr.iter().enumerate() {
                    if i > 0 {
                        write!(f, ", ")?;
                    }
                    write!(f, "{v}")?;
                }
                write!(f, "]")
            }
            JsonValue::Object(map) => {
                write!(f, "{{")?;
                for (i, (k, v)) in map.iter().enumerate() {
                    if i > 0 {
                        write!(f, ", ")?;
                    }
                    escape_json_string(k, f)?;
                    write!(f, ": {v}")?;
                }
                write!(f, "}}")
            }
        }
    }
}

/// JSON string escaping helper.
///
/// Writes the string escaped per the JSON standard into the formatter.
/// Used for both string values and object keys.
fn escape_json_string(s: &str, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    write!(f, "\"")?;
    for c in s.chars() {
        match c {
            '"' => write!(f, "\\\"")?,
            '\\' => write!(f, "\\\\")?,
            '\n' => write!(f, "\\n")?,
            '\r' => write!(f, "\\r")?,
            '\t' => write!(f, "\\t")?,
            '\x08' => write!(f, "\\b")?,
            '\x0c' => write!(f, "\\f")?,
            c if (c as u32) < 0x20 => write!(f, "\\u{:04x}", c as u32)?,
            c => write!(f, "{c}")?,
        }
    }
    write!(f, "\"")
}

// ===== Constructors =====

impl JsonValue {
    /// Construct null
    pub const fn null() -> Self {
        JsonValue::Null
    }

    /// Construct a boolean
    pub const fn bool(b: bool) -> Self {
        JsonValue::Bool(b)
    }

    /// Construct an integer
    pub const fn integer(i: i64) -> Self {
        JsonValue::Integer(i)
    }

    /// Construct an unsigned integer (full-range u64 channel)
    ///
    /// # Examples
    ///
    /// ```
    /// use evorule_primitives::JsonValue;
    ///
    /// let v = JsonValue::u64(u64::MAX - 1);
    /// assert!(v.is_u64());
    /// assert_eq!(v.as_u64(), Some(u64::MAX - 1));
    /// // Shape-strict: U64 and Integer are never cross-shape equal
    /// assert_ne!(JsonValue::u64(5), JsonValue::Integer(5));
    /// ```
    pub const fn u64(v: u64) -> Self {
        JsonValue::U64(v)
    }

    /// Construct a string
    ///
    /// # Examples
    ///
    /// ```
    /// use evorule_primitives::JsonValue;
    ///
    /// let v = JsonValue::string("hello");
    /// assert_eq!(v.as_str(), Some("hello"));
    /// ```
    pub fn string<S: Into<String>>(s: S) -> Self {
        JsonValue::String(Cow::Owned(s.into()))
    }

    /// Construct an array
    ///
    /// # Examples
    ///
    /// ```
    /// use evorule_primitives::JsonValue;
    ///
    /// let arr = JsonValue::array(vec![JsonValue::Integer(1), JsonValue::Integer(2)]);
    /// assert!(arr.is_array());
    /// assert_eq!(arr.as_array().map(|a| a.len()), Some(2));
    /// ```
    pub fn array(v: Vec<JsonValue>) -> Self {
        JsonValue::Array(v)
    }

    /// Construct an object
    ///
    /// # Examples
    ///
    /// ```
    /// extern crate alloc;
    /// use evorule_primitives::JsonValue;
    /// use alloc::collections::BTreeMap;
    ///
    /// let mut map = BTreeMap::new();
    /// map.insert("key".to_string(), JsonValue::Integer(42));
    /// let obj = JsonValue::object(map);
    /// assert!(obj.is_object());
    /// assert_eq!(obj.get("key").and_then(|v| v.as_i64()), Some(42));
    /// ```
    pub fn object(map: ObjectMap) -> Self {
        JsonValue::Object(map)
    }

    /// Construct an object from key-value pairs (owning version).
    ///
    /// More efficient than `object_from_pairs` because values are not cloned.
    ///
    /// # Examples
    ///
    /// ```
    /// use evorule_primitives::JsonValue;
    ///
    /// let pairs = vec![
    ///     ("a".to_string(), JsonValue::Integer(1)),
    ///     ("b".to_string(), JsonValue::Integer(2)),
    /// ];
    /// let obj = JsonValue::object_from_pairs_owned(pairs);
    /// assert_eq!(obj.get("a").and_then(|v| v.as_i64()), Some(1));
    /// ```
    pub fn object_from_pairs_owned(pairs: Vec<(String, JsonValue)>) -> Self {
        let mut map = ObjectMap::new();
        for (k, v) in pairs {
            map.insert(k, v);
        }
        JsonValue::Object(map)
    }

    /// Construct an object from key-value pairs (borrowed version; clones values).
    ///
    /// Note: this method clones all values. Use `object_from_pairs_owned` to
    /// avoid cloning.
    ///
    /// # Examples
    ///
    /// ```
    /// use evorule_primitives::JsonValue;
    ///
    /// let obj = JsonValue::object_from_pairs(&[
    ///     ("a", JsonValue::Integer(1)),
    ///     ("b", JsonValue::Integer(2)),
    /// ]);
    /// assert_eq!(obj.get("a").and_then(|v| v.as_i64()), Some(1));
    /// ```
    pub fn object_from_pairs(pairs: &[(&str, JsonValue)]) -> Self {
        let mut map = ObjectMap::new();
        for (k, v) in pairs {
            map.insert((*k).to_string(), v.clone());
        }
        JsonValue::Object(map)
    }

    /// Construct an empty object
    ///
    /// # Examples
    ///
    /// ```
    /// use evorule_primitives::JsonValue;
    ///
    /// let obj = JsonValue::empty_object();
    /// assert!(obj.is_object());
    /// assert_eq!(obj.as_object().map(|m| m.len()), Some(0));
    /// ```
    pub fn empty_object() -> Self {
        JsonValue::Object(ObjectMap::new())
    }

    /// Construct an empty array
    ///
    /// # Examples
    ///
    /// ```
    /// use evorule_primitives::JsonValue;
    ///
    /// let arr = JsonValue::empty_array();
    /// assert!(arr.is_array());
    /// assert_eq!(arr.as_array().map(|a| a.len()), Some(0));
    /// ```
    pub fn empty_array() -> Self {
        JsonValue::Array(Vec::new())
    }
}

// ===== From trait implementations =====

/// Construct an object from a map
impl From<ObjectMap> for JsonValue {
    fn from(map: ObjectMap) -> Self {
        JsonValue::Object(map)
    }
}

/// Construct an array from a Vec
impl From<Vec<JsonValue>> for JsonValue {
    fn from(v: Vec<JsonValue>) -> Self {
        JsonValue::Array(v)
    }
}

/// Construct a string from a &str
impl From<&str> for JsonValue {
    fn from(s: &str) -> Self {
        JsonValue::String(Cow::Owned(s.to_string()))
    }
}

/// Construct a string from a String
impl From<String> for JsonValue {
    fn from(s: String) -> Self {
        JsonValue::String(Cow::Owned(s))
    }
}

/// Construct a string from a Cow<'static, str>
impl From<Cow<'static, str>> for JsonValue {
    fn from(s: Cow<'static, str>) -> Self {
        JsonValue::String(s)
    }
}

/// Construct an integer from i64
impl From<i64> for JsonValue {
    fn from(i: i64) -> Self {
        JsonValue::Integer(i)
    }
}

/// Construct an unsigned integer from u64 (full-range channel, no i64 cast wrap-around)
impl From<u64> for JsonValue {
    fn from(v: u64) -> Self {
        JsonValue::U64(v)
    }
}

/// Construct a boolean from bool
impl From<bool> for JsonValue {
    fn from(b: bool) -> Self {
        JsonValue::Bool(b)
    }
}

#[cfg(test)]
mod tests {
    #![allow(clippy::unwrap_used)]
    #![allow(clippy::expect_used)]
    #![allow(clippy::panic)]
    #![allow(clippy::indexing_slicing)]

    use super::*;
    use alloc::format;
    use alloc::vec;
    use core::cmp::Ordering;

    // ===== Constructor tests =====

    #[test]
    fn test_const_constructors() {
        const N: JsonValue = JsonValue::null();
        const B: JsonValue = JsonValue::bool(true);
        const I: JsonValue = JsonValue::integer(-7);
        assert_eq!(N, JsonValue::Null);
        assert_eq!(B, JsonValue::Bool(true));
        assert_eq!(I, JsonValue::Integer(-7));
    }

    #[test]
    fn test_string_constructor() {
        let s = JsonValue::string("hello");
        assert_eq!(s.as_str(), Some("hello"));
        let owned = JsonValue::string(String::from("world"));
        assert_eq!(owned.as_str(), Some("world"));
    }

    #[test]
    fn test_empty_array() {
        assert_eq!(JsonValue::empty_array(), JsonValue::Array(Vec::new()));
    }

    #[test]
    fn test_empty_object() {
        assert!(JsonValue::empty_object().is_object());
        assert_eq!(JsonValue::empty_object().len(), Some(0));
    }

    #[test]
    fn test_object_from_pairs_owned() {
        let pairs = vec![
            ("a".to_string(), JsonValue::Integer(1)),
            ("b".to_string(), JsonValue::Integer(2)),
        ];
        let obj = JsonValue::object_from_pairs_owned(pairs);
        assert_eq!(obj.get("a").and_then(|v| v.as_i64()), Some(1));
        assert_eq!(obj.get("b").and_then(|v| v.as_i64()), Some(2));
    }

    // ===== Type-check tests =====

    #[test]
    fn test_is_methods_match_correct_type() {
        assert!(JsonValue::Null.is_null());
        assert!(JsonValue::Bool(true).is_bool());
        assert!(JsonValue::Integer(0).is_integer());
        assert!(JsonValue::string("x").is_string());
        assert!(JsonValue::empty_array().is_array());
        assert!(JsonValue::empty_object().is_object());
    }

    #[test]
    fn test_is_methods_reject_wrong_type() {
        assert!(!JsonValue::Null.is_bool());
        assert!(!JsonValue::Null.is_integer());
        assert!(!JsonValue::Integer(1).is_string());
        assert!(!JsonValue::string("x").is_array());
        assert!(!JsonValue::empty_array().is_object());
        assert!(!JsonValue::Bool(false).is_null());
    }

    // ===== len() and is_empty() tests =====

    #[test]
    fn test_len_and_is_empty() {
        assert_eq!(JsonValue::Null.len(), None);
        assert_eq!(JsonValue::Integer(42).len(), None);
        assert_eq!(JsonValue::string("test").len(), None);

        let arr = JsonValue::array(vec![JsonValue::Integer(1), JsonValue::Integer(2)]);
        assert_eq!(arr.len(), Some(2));
        assert!(!arr.is_empty());

        let empty_arr = JsonValue::empty_array();
        assert_eq!(empty_arr.len(), Some(0));
        assert!(empty_arr.is_empty());

        let obj = JsonValue::object_from_pairs(&[("a", JsonValue::Integer(1))]);
        assert_eq!(obj.len(), Some(1));
        assert!(!obj.is_empty());

        assert!(JsonValue::empty_object().is_empty());
    }

    // ===== Conversion tests =====

    #[test]
    fn test_as_methods_success_paths() {
        assert_eq!(JsonValue::Integer(42).as_i64(), Some(42));
        assert_eq!(JsonValue::string("hi").as_str(), Some("hi"));
        assert_eq!(JsonValue::Bool(true).as_bool(), Some(true));
        assert!(JsonValue::empty_array().as_array().is_some());
        assert!(JsonValue::empty_object().as_object().is_some());
    }

    #[test]
    fn test_as_methods_type_mismatch_returns_none() {
        assert_eq!(JsonValue::Null.as_i64(), None);
        assert_eq!(JsonValue::Bool(true).as_i64(), None);
        assert_eq!(JsonValue::string("x").as_i64(), None);
        assert_eq!(JsonValue::Null.as_str(), None);
        assert_eq!(JsonValue::Integer(1).as_str(), None);
        assert_eq!(JsonValue::Integer(1).as_bool(), None);
        assert_eq!(JsonValue::Null.as_array(), None);
        assert_eq!(JsonValue::Integer(0).as_array(), None);
        assert_eq!(JsonValue::Null.as_object(), None);
        assert_eq!(JsonValue::Integer(0).as_object(), None);
    }

    #[test]
    fn test_as_mut_methods_type_mismatch() {
        let mut v = JsonValue::Integer(0);
        assert!(v.as_array_mut().is_none());
        assert!(v.as_object_mut().is_none());
        let mut arr = JsonValue::empty_array();
        assert!(arr.as_array_mut().is_some());
        let mut obj = JsonValue::empty_object();
        assert!(obj.as_object_mut().is_some());
    }

    // ===== Object operation tests =====

    #[test]
    fn test_object_accessors_on_non_object() {
        let mut v = JsonValue::Integer(0);
        assert_eq!(v.get("any"), None);
        assert_eq!(v.get_mut("any"), None);
        assert_eq!(v.insert("k".to_string(), JsonValue::Null), None);
        assert_eq!(v.remove("k"), None);
        assert_eq!(v, JsonValue::Integer(0));
    }

    #[test]
    fn test_get_on_object() {
        let obj = JsonValue::object_from_pairs(&[("x", JsonValue::Integer(7))]);
        assert_eq!(obj.get("x"), Some(&JsonValue::Integer(7)));
        assert_eq!(obj.get("missing"), None);
    }

    #[test]
    fn test_get_mut_on_object() {
        let mut obj = JsonValue::object_from_pairs(&[("a", JsonValue::Integer(1))]);
        if let Some(v) = obj.get_mut("a") {
            *v = JsonValue::Integer(42);
        }
        assert_eq!(obj.get("a"), Some(&JsonValue::Integer(42)));
        assert_eq!(obj.get_mut("missing"), None);
    }

    #[test]
    fn test_insert_and_remove() {
        let mut obj = JsonValue::empty_object();
        assert_eq!(obj.insert("k".to_string(), JsonValue::Integer(1)), None);
        assert_eq!(obj.get("k"), Some(&JsonValue::Integer(1)));

        let old = obj.insert("k".to_string(), JsonValue::Integer(2));
        assert_eq!(old, Some(JsonValue::Integer(1)));
        assert_eq!(obj.get("k"), Some(&JsonValue::Integer(2)));

        assert_eq!(obj.remove("k"), Some(JsonValue::Integer(2)));
        assert_eq!(obj.get("k"), None);
        assert_eq!(obj.remove("missing"), None);
    }

    #[test]
    fn test_try_insert() {
        let mut obj = JsonValue::empty_object();
        assert!(obj
            .try_insert("k".to_string(), JsonValue::Integer(1))
            .is_ok());
        assert!(obj
            .try_insert("k".to_string(), JsonValue::Integer(2))
            .is_err());
        assert_eq!(obj.get("k"), Some(&JsonValue::Integer(1)));

        let mut non_obj = JsonValue::Integer(0);
        assert!(non_obj
            .try_insert("k".to_string(), JsonValue::Integer(1))
            .is_err());
    }

    #[test]
    fn test_clear() {
        let mut arr = JsonValue::array(vec![JsonValue::Integer(1), JsonValue::Integer(2)]);
        arr.clear();
        assert_eq!(arr.len(), Some(0));

        let mut obj = JsonValue::object_from_pairs(&[("a", JsonValue::Integer(1))]);
        obj.clear();
        assert_eq!(obj.len(), Some(0));

        let mut null = JsonValue::Null;
        null.clear(); // no-op
        assert!(null.is_null());
    }

    // ===== PartialEq tests =====

    #[test]
    fn test_partial_eq_same_type() {
        assert_eq!(JsonValue::Null, JsonValue::Null);
        assert_eq!(JsonValue::Bool(true), JsonValue::Bool(true));
        assert_eq!(JsonValue::Integer(5), JsonValue::Integer(5));
        assert_eq!(JsonValue::string("hi"), JsonValue::string("hi"));
        assert_eq!(
            JsonValue::array(vec![JsonValue::Integer(1)]),
            JsonValue::array(vec![JsonValue::Integer(1)])
        );
    }

    #[test]
    fn test_partial_eq_cross_type() {
        assert_ne!(JsonValue::Null, JsonValue::Bool(false));
        assert_ne!(JsonValue::Bool(true), JsonValue::Integer(1));
        assert_ne!(JsonValue::Integer(0), JsonValue::string("0"));
        assert_ne!(JsonValue::string(""), JsonValue::empty_array());
        assert_ne!(JsonValue::empty_array(), JsonValue::empty_object());
    }

    #[test]
    fn test_partial_eq_object() {
        let mut a = ObjectMap::new();
        a.insert("x".to_string(), JsonValue::Integer(1));
        a.insert("y".to_string(), JsonValue::Integer(2));
        let mut b = ObjectMap::new();
        b.insert("x".to_string(), JsonValue::Integer(1));
        b.insert("y".to_string(), JsonValue::Integer(2));
        assert_eq!(JsonValue::object(a.clone()), JsonValue::object(b));

        let mut c = ObjectMap::new();
        c.insert("x".to_string(), JsonValue::Integer(1));
        c.insert("y".to_string(), JsonValue::Integer(99));
        assert_ne!(JsonValue::object(a.clone()), JsonValue::object(c));

        let mut d = ObjectMap::new();
        d.insert("x".to_string(), JsonValue::Integer(1));
        d.insert("z".to_string(), JsonValue::Integer(2));
        assert_ne!(JsonValue::object(a.clone()), JsonValue::object(d));

        let mut e = ObjectMap::new();
        e.insert("x".to_string(), JsonValue::Integer(1));
        assert_ne!(JsonValue::object(a), JsonValue::object(e));
    }

    // ===== Ord tests =====

    #[test]
    fn test_ord_type_order() {
        assert_eq!(JsonValue::Null.cmp(&JsonValue::Null), Ordering::Equal);
        assert!(JsonValue::Null < JsonValue::Bool(false));
        assert!(JsonValue::Bool(false) < JsonValue::Integer(0));
        assert!(JsonValue::Integer(0) < JsonValue::string(""));
        assert!(JsonValue::string("") < JsonValue::empty_array());
        assert!(JsonValue::empty_array() < JsonValue::empty_object());
    }

    #[test]
    fn test_ord_lexicographic() {
        assert!(JsonValue::Integer(0) < JsonValue::Integer(1));
        assert!(JsonValue::string("a") < JsonValue::string("b"));

        let mut short = ObjectMap::new();
        short.insert("a".to_string(), JsonValue::Integer(1));
        let mut long = ObjectMap::new();
        long.insert("a".to_string(), JsonValue::Integer(1));
        long.insert("b".to_string(), JsonValue::Integer(2));
        assert!(JsonValue::object(short) < JsonValue::object(long));
    }

    // ===== Display tests =====

    #[test]
    fn test_display_simple_types() {
        assert_eq!(format!("{}", JsonValue::Null), "null");
        assert_eq!(format!("{}", JsonValue::Bool(true)), "true");
        assert_eq!(format!("{}", JsonValue::Bool(false)), "false");
        assert_eq!(format!("{}", JsonValue::Integer(0)), "0");
        assert_eq!(format!("{}", JsonValue::Integer(-42)), "-42");
    }

    #[test]
    fn test_display_string_escapes() {
        assert_eq!(format!("{}", JsonValue::string("")), "\"\"");
        assert_eq!(format!("{}", JsonValue::string("hello")), "\"hello\"");
        assert_eq!(format!("{}", JsonValue::string("a\"b")), "\"a\\\"b\"");
        assert_eq!(format!("{}", JsonValue::string("a\\b")), "\"a\\\\b\"");
        assert_eq!(format!("{}", JsonValue::string("a\nb")), "\"a\\nb\"");
    }

    #[test]
    fn test_display_array() {
        assert_eq!(format!("{}", JsonValue::empty_array()), "[]");
        let arr = JsonValue::array(vec![
            JsonValue::Integer(1),
            JsonValue::Integer(2),
            JsonValue::Integer(3),
        ]);
        assert_eq!(format!("{arr}"), "[1, 2, 3]");
    }

    #[test]
    fn test_display_object() {
        assert_eq!(format!("{}", JsonValue::empty_object()), "{}");
        let obj = JsonValue::object_from_pairs(&[
            ("z", JsonValue::Integer(1)),
            ("a", JsonValue::Integer(2)),
        ]);
        assert_eq!(format!("{obj}"), "{\"a\": 2, \"z\": 1}");
    }

    // ===== From trait tests =====

    #[test]
    fn test_from_traits() {
        let v: JsonValue = 42i64.into();
        assert_eq!(v, JsonValue::Integer(42));

        let v: JsonValue = "hello".into();
        assert_eq!(v, JsonValue::string("hello"));

        let v: JsonValue = true.into();
        assert_eq!(v, JsonValue::Bool(true));

        let v: JsonValue = vec![JsonValue::Integer(1), JsonValue::Integer(2)].into();
        assert_eq!(v.len(), Some(2));
    }

    // ===== JSON string escaping boundaries (Display output validity) =====

    /// Control characters (< 0x20 without a dedicated escape) must go through
    /// the \u00XX channel — emitting them verbatim produces invalid JSON
    /// (consumers crash on parse)
    #[test]
    fn test_display_escapes_control_chars() {
        let v = JsonValue::string("a\u{1}b");
        assert_eq!(v.to_string(), "\"a\\u0001b\"");

        // \x1f is the last non-dedicated control character below the 0x20 boundary
        let v = JsonValue::string("\u{1f}");
        assert_eq!(v.to_string(), "\"\\u001f\"");
    }

    /// Space (0x20) is printable and outside the escape range —
    /// writing the escape bound as <= would wrongly escape spaces to \u0020
    #[test]
    fn test_display_space_verbatim() {
        let v = JsonValue::string("a b");
        assert_eq!(v.to_string(), "\"a b\"");
    }

    // ===== U64 (full-range u64 channel) =====

    #[test]
    fn test_u64_construct_and_access() {
        let v = JsonValue::u64(u64::MAX - 1);
        assert!(v.is_u64());
        assert!(!v.is_integer());
        assert_eq!(v.as_u64(), Some(u64::MAX - 1));
        // Shape-strict symmetry: as_i64 only matches Integer, as_u64 only U64;
        // is_u64 likewise only matches U64 — non-U64 variants are always false
        // (negative-kill assertion guarding against an is_u64 always-true mutation)
        assert_eq!(v.as_i64(), None);
        assert_eq!(JsonValue::Integer(5).as_u64(), None);
        assert!(!JsonValue::Integer(5).is_u64());
        assert!(!JsonValue::Bool(true).is_u64());
        assert!(!JsonValue::Null.is_u64());

        let from_trait: JsonValue = 42u64.into();
        assert_eq!(from_trait, JsonValue::u64(42));
    }

    #[test]
    fn test_u64_partial_eq_strict_shape() {
        // Cross-shape intentionally unequal (consistent with Ord type grouping)
        assert_ne!(JsonValue::u64(5), JsonValue::Integer(5));
        assert_ne!(JsonValue::Integer(5), JsonValue::u64(5));
        assert_eq!(JsonValue::u64(5), JsonValue::u64(5));
        assert_ne!(JsonValue::u64(u64::MAX), JsonValue::u64(u64::MAX - 1));
    }

    #[test]
    fn test_u64_ord_group_order() {
        // Group order: Integer < U64 < String (type grouping dominates value)
        assert!(JsonValue::Integer(0) < JsonValue::u64(0));
        assert!(JsonValue::u64(0) < JsonValue::string(""));
        assert!(JsonValue::u64(0) < JsonValue::u64(1));
        assert!(JsonValue::u64(u64::MAX - 1) < JsonValue::u64(u64::MAX));
        // The Integer group still compares less than any U64 value (group
        // decision precedes in-group comparison)
        assert!(JsonValue::Integer(i64::MAX) < JsonValue::u64(0));
    }

    #[test]
    fn test_u64_display() {
        assert_eq!(format!("{}", JsonValue::u64(0)), "0");
        assert_eq!(
            format!("{}", JsonValue::u64(u64::MAX - 1)),
            "18446744073709551614"
        );
    }
}