1use 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#[cfg(kani)]
37#[derive(Debug, Clone, PartialEq, Eq)]
38pub struct KaniMap {
39 entries: Vec<(String, JsonValue)>,
41}
42
43#[cfg(kani)]
48impl Drop for KaniMap {
49 fn drop(&mut self) {
50 let leaked = core::mem::take(&mut self.entries);
54 core::mem::forget(leaked);
55 }
56}
57
58#[cfg(kani)]
59impl KaniMap {
60 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 pub fn new() -> Self {
75 KaniMap {
76 entries: Vec::new(),
77 }
78 }
79
80 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 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 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 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 pub fn contains_key(&self, key: &str) -> bool {
126 self.locate(key).is_ok()
127 }
128
129 pub fn values(&self) -> impl Iterator<Item = &JsonValue> {
131 self.entries.iter().map(|(_, v)| v)
132 }
133
134 pub fn iter(&self) -> core::slice::Iter<'_, (String, JsonValue)> {
136 self.entries.iter()
137 }
138
139 pub fn len(&self) -> usize {
141 self.entries.len()
142 }
143
144 pub fn is_empty(&self) -> bool {
146 self.entries.is_empty()
147 }
148
149 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 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#[cfg(not(kani))]
200pub type ObjectMap = BTreeMap<String, JsonValue>;
201#[cfg(kani)]
203pub type ObjectMap = KaniMap;
204
205#[derive(Debug, Clone)]
246pub enum JsonValue {
247 Null,
249 Bool(bool),
251 Integer(i64),
253 U64(u64),
256 String(Cow<'static, str>),
258 Array(Vec<JsonValue>),
260 Object(ObjectMap),
262}
263
264#[cfg(kani)]
273impl Drop for JsonValue {
274 fn drop(&mut self) {
275 let leaked = core::mem::replace(self, JsonValue::Null);
281 core::mem::forget(leaked);
282 }
283}
284
285#[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
300impl 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 (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
334impl Ord for JsonValue {
336 fn cmp(&self, other: &Self) -> Ordering {
337 match (self, other) {
338 (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 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 pub fn is_object(&self) -> bool {
397 matches!(self, JsonValue::Object(_))
398 }
399
400 pub fn is_array(&self) -> bool {
402 matches!(self, JsonValue::Array(_))
403 }
404
405 pub fn is_integer(&self) -> bool {
407 matches!(self, JsonValue::Integer(_))
408 }
409
410 pub fn is_u64(&self) -> bool {
412 matches!(self, JsonValue::U64(_))
413 }
414
415 pub fn is_string(&self) -> bool {
417 matches!(self, JsonValue::String(_))
418 }
419
420 pub fn is_bool(&self) -> bool {
422 matches!(self, JsonValue::Bool(_))
423 }
424
425 pub fn is_null(&self) -> bool {
427 matches!(self, JsonValue::Null)
428 }
429
430 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 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 pub fn as_i64(&self) -> Option<i64> {
467 match self {
468 JsonValue::Integer(v) => Some(*v),
469 _ => None,
470 }
471 }
472
473 pub fn as_u64(&self) -> Option<u64> {
475 match self {
476 JsonValue::U64(v) => Some(*v),
477 _ => None,
478 }
479 }
480
481 pub fn as_str(&self) -> Option<&str> {
483 match self {
484 JsonValue::String(s) => Some(s.as_ref()),
485 _ => None,
486 }
487 }
488
489 pub fn as_bool(&self) -> Option<bool> {
491 match self {
492 JsonValue::Bool(b) => Some(*b),
493 _ => None,
494 }
495 }
496
497 pub fn as_array(&self) -> Option<&[JsonValue]> {
499 match self {
500 JsonValue::Array(arr) => Some(arr.as_slice()),
501 _ => None,
502 }
503 }
504
505 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 pub fn as_object(&self) -> Option<&ObjectMap> {
515 match self {
516 JsonValue::Object(map) => Some(map),
517 _ => None,
518 }
519 }
520
521 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 pub fn get(&self, key: &str) -> Option<&JsonValue> {
552 match self {
553 JsonValue::Object(map) => map.get(key),
554 _ => None,
555 }
556 }
557
558 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 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 #[allow(clippy::map_entry)]
613 pub fn try_insert(&mut self, key: String, value: JsonValue) -> Result<(), &JsonValue> {
614 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 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 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
667impl 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
702fn 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
724impl JsonValue {
727 pub const fn null() -> Self {
729 JsonValue::Null
730 }
731
732 pub const fn bool(b: bool) -> Self {
734 JsonValue::Bool(b)
735 }
736
737 pub const fn integer(i: i64) -> Self {
739 JsonValue::Integer(i)
740 }
741
742 pub const fn u64(v: u64) -> Self {
756 JsonValue::U64(v)
757 }
758
759 pub fn string<S: Into<String>>(s: S) -> Self {
770 JsonValue::String(Cow::Owned(s.into()))
771 }
772
773 pub fn array(v: Vec<JsonValue>) -> Self {
785 JsonValue::Array(v)
786 }
787
788 pub fn object(map: ObjectMap) -> Self {
804 JsonValue::Object(map)
805 }
806
807 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 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 pub fn empty_object() -> Self {
866 JsonValue::Object(ObjectMap::new())
867 }
868
869 pub fn empty_array() -> Self {
881 JsonValue::Array(Vec::new())
882 }
883}
884
885impl From<ObjectMap> for JsonValue {
889 fn from(map: ObjectMap) -> Self {
890 JsonValue::Object(map)
891 }
892}
893
894impl From<Vec<JsonValue>> for JsonValue {
896 fn from(v: Vec<JsonValue>) -> Self {
897 JsonValue::Array(v)
898 }
899}
900
901impl From<&str> for JsonValue {
903 fn from(s: &str) -> Self {
904 JsonValue::String(Cow::Owned(s.to_string()))
905 }
906}
907
908impl From<String> for JsonValue {
910 fn from(s: String) -> Self {
911 JsonValue::String(Cow::Owned(s))
912 }
913}
914
915impl From<Cow<'static, str>> for JsonValue {
917 fn from(s: Cow<'static, str>) -> Self {
918 JsonValue::String(s)
919 }
920}
921
922impl From<i64> for JsonValue {
924 fn from(i: i64) -> Self {
925 JsonValue::Integer(i)
926 }
927}
928
929impl From<u64> for JsonValue {
931 fn from(v: u64) -> Self {
932 JsonValue::U64(v)
933 }
934}
935
936impl 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 #[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 #[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 #[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 #[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 #[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(); assert!(null.is_null());
1152 }
1153
1154 #[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 #[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 #[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 #[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 #[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 let v = JsonValue::string("\u{1f}");
1296 assert_eq!(v.to_string(), "\"\\u001f\"");
1297 }
1298
1299 #[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 #[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 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 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 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 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}