1use alloc::borrow::Cow;
18use alloc::string::{String, ToString};
19use alloc::vec::Vec;
20use core::cmp::Ordering;
21use core::fmt;
22
23#[cfg(not(kani))]
24use alloc::collections::BTreeMap;
25
26#[cfg(kani)]
46#[derive(Debug, Clone, PartialEq, Eq)]
47pub struct KaniMap {
48 entries: Vec<(String, JsonValue)>,
50}
51
52#[cfg(kani)]
60impl Drop for KaniMap {
61 fn drop(&mut self) {
62 let leaked = core::mem::take(&mut self.entries);
66 core::mem::forget(leaked);
67 }
68}
69
70#[cfg(kani)]
71impl KaniMap {
72 fn locate(&self, key: &str) -> Result<usize, usize> {
75 for (i, (k, _)) in self.entries.iter().enumerate() {
76 if k.as_str() == key {
77 return Ok(i);
78 }
79 if k.as_str() > key {
80 return Err(i);
81 }
82 }
83 Err(self.entries.len())
84 }
85
86 pub fn new() -> Self {
88 KaniMap {
89 entries: Vec::new(),
90 }
91 }
92
93 pub fn insert(&mut self, key: String, value: JsonValue) -> Option<JsonValue> {
95 match self.locate(&key) {
96 Ok(i) => self
97 .entries
98 .get_mut(i)
99 .map(|slot| core::mem::replace(&mut slot.1, value)),
100 Err(pos) => {
101 self.entries.insert(pos, (key, value));
102 None
103 }
104 }
105 }
106
107 pub fn get(&self, key: &str) -> Option<&JsonValue> {
109 match self.locate(key) {
110 Ok(i) => self.entries.get(i).map(|(_, v)| v),
111 Err(_) => None,
112 }
113 }
114
115 pub fn get_mut(&mut self, key: &str) -> Option<&mut JsonValue> {
117 match self.locate(key) {
118 Ok(i) => match self.entries.get_mut(i) {
119 Some((_, v)) => Some(v),
120 None => None,
121 },
122 Err(_) => None,
123 }
124 }
125
126 pub fn remove(&mut self, key: &str) -> Option<JsonValue> {
128 match self.locate(key) {
129 Ok(i) => {
130 let (_, value) = self.entries.remove(i);
131 Some(value)
132 }
133 Err(_) => None,
134 }
135 }
136
137 pub fn contains_key(&self, key: &str) -> bool {
139 self.locate(key).is_ok()
140 }
141
142 pub fn values(&self) -> impl Iterator<Item = &JsonValue> {
144 self.entries.iter().map(|(_, v)| v)
145 }
146
147 pub fn iter(&self) -> core::slice::Iter<'_, (String, JsonValue)> {
149 self.entries.iter()
150 }
151
152 pub fn len(&self) -> usize {
154 self.entries.len()
155 }
156
157 pub fn is_empty(&self) -> bool {
159 self.entries.is_empty()
160 }
161
162 pub fn clear(&mut self) {
164 self.entries.clear();
165 }
166}
167
168#[cfg(kani)]
169impl Default for KaniMap {
170 fn default() -> Self {
171 KaniMap::new()
172 }
173}
174
175#[cfg(kani)]
176impl<'a> IntoIterator for &'a KaniMap {
177 type Item = &'a (String, JsonValue);
178 type IntoIter = core::slice::Iter<'a, (String, JsonValue)>;
179
180 fn into_iter(self) -> Self::IntoIter {
181 self.entries.iter()
182 }
183}
184
185#[cfg(kani)]
186impl IntoIterator for KaniMap {
187 type Item = (String, JsonValue);
188 type IntoIter = alloc::vec::IntoIter<(String, JsonValue)>;
189
190 fn into_iter(mut self) -> Self::IntoIter {
191 core::mem::take(&mut self.entries).into_iter()
193 }
194}
195
196#[cfg(kani)]
197impl<const N: usize> From<[(String, JsonValue); N]> for KaniMap {
198 fn from(arr: [(String, JsonValue); N]) -> Self {
199 let mut map = KaniMap::new();
200 for (k, v) in arr {
201 map.insert(k, v);
202 }
203 map
204 }
205}
206
207#[cfg(not(kani))]
216pub type ObjectMap = BTreeMap<String, JsonValue>;
217#[cfg(kani)]
219pub type ObjectMap = KaniMap;
220
221#[derive(Debug, Clone)]
263pub enum JsonValue {
264 Null,
266 Bool(bool),
268 Integer(i64),
270 U64(u64),
274 String(Cow<'static, str>),
276 Array(Vec<JsonValue>),
278 Object(ObjectMap),
280}
281
282#[cfg(kani)]
296impl Drop for JsonValue {
297 fn drop(&mut self) {
298 let leaked = core::mem::replace(self, JsonValue::Null);
304 core::mem::forget(leaked);
305 }
306}
307
308#[cfg(kani)]
311static NULL_VALUE: JsonValue = JsonValue::Null;
312
313#[cfg(not(kani))]
314fn null_ref() -> &'static JsonValue {
315 &JsonValue::Null
316}
317
318#[cfg(kani)]
319fn null_ref() -> &'static JsonValue {
320 &NULL_VALUE
321}
322
323impl PartialEq for JsonValue {
325 fn eq(&self, other: &Self) -> bool {
326 match (self, other) {
327 (JsonValue::Null, JsonValue::Null) => true,
328 (JsonValue::Bool(a), JsonValue::Bool(b)) => a == b,
329 (JsonValue::Integer(a), JsonValue::Integer(b)) => a == b,
330 (JsonValue::U64(a), JsonValue::U64(b)) => a == b,
331 (JsonValue::String(a), JsonValue::String(b)) => a == b,
336 (JsonValue::Array(a), JsonValue::Array(b)) => a == b,
337 (JsonValue::Object(a), JsonValue::Object(b)) => {
338 if a.len() != b.len() {
339 return false;
340 }
341 for (k, v) in a.iter() {
342 if let Some(bv) = b.get(k) {
343 if v != bv {
344 return false;
345 }
346 } else {
347 return false;
348 }
349 }
350 true
351 }
352 _ => false,
353 }
354 }
355}
356
357impl Eq for JsonValue {}
358
359impl Ord for JsonValue {
361 fn cmp(&self, other: &Self) -> Ordering {
362 match (self, other) {
363 (JsonValue::Null, JsonValue::Null) => Ordering::Equal,
365 (JsonValue::Null, _) => Ordering::Less,
366 (_, JsonValue::Null) => Ordering::Greater,
367
368 (JsonValue::Bool(a), JsonValue::Bool(b)) => a.cmp(b),
369 (JsonValue::Bool(_), _) => Ordering::Less,
370 (_, JsonValue::Bool(_)) => Ordering::Greater,
371
372 (JsonValue::Integer(a), JsonValue::Integer(b)) => a.cmp(b),
373 (JsonValue::Integer(_), _) => Ordering::Less,
374 (_, JsonValue::Integer(_)) => Ordering::Greater,
375
376 (JsonValue::U64(a), JsonValue::U64(b)) => a.cmp(b),
377 (JsonValue::U64(_), _) => Ordering::Less,
378 (_, JsonValue::U64(_)) => Ordering::Greater,
379
380 (JsonValue::String(a), JsonValue::String(b)) => a.cmp(b),
381 (JsonValue::String(_), _) => Ordering::Less,
382 (_, JsonValue::String(_)) => Ordering::Greater,
383
384 (JsonValue::Array(a), JsonValue::Array(b)) => a.cmp(b),
385 (JsonValue::Array(_), _) => Ordering::Less,
386 (_, JsonValue::Array(_)) => Ordering::Greater,
387
388 (JsonValue::Object(a), JsonValue::Object(b)) => {
389 let mut a_iter = a.iter();
391 let mut b_iter = b.iter();
392 loop {
393 match (a_iter.next(), b_iter.next()) {
394 (None, None) => return Ordering::Equal,
395 (None, Some(_)) => return Ordering::Less,
396 (Some(_), None) => return Ordering::Greater,
397 (Some((ak, av)), Some((bk, bv))) => match ak.cmp(bk) {
398 Ordering::Equal => match av.cmp(bv) {
399 Ordering::Equal => {}
400 other => return other,
401 },
402 other => return other,
403 },
404 }
405 }
406 }
407 }
408 }
409}
410
411impl PartialOrd for JsonValue {
412 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
413 Some(self.cmp(other))
414 }
415}
416
417impl JsonValue {
418 pub fn is_object(&self) -> bool {
422 matches!(self, JsonValue::Object(_))
423 }
424
425 pub fn is_array(&self) -> bool {
427 matches!(self, JsonValue::Array(_))
428 }
429
430 pub fn is_integer(&self) -> bool {
432 matches!(self, JsonValue::Integer(_))
433 }
434
435 pub fn is_u64(&self) -> bool {
437 matches!(self, JsonValue::U64(_))
438 }
439
440 pub fn is_string(&self) -> bool {
442 matches!(self, JsonValue::String(_))
443 }
444
445 pub fn is_bool(&self) -> bool {
447 matches!(self, JsonValue::Bool(_))
448 }
449
450 pub fn is_null(&self) -> bool {
452 matches!(self, JsonValue::Null)
453 }
454
455 pub fn len(&self) -> Option<usize> {
472 match self {
473 JsonValue::Array(arr) => Some(arr.len()),
474 JsonValue::Object(map) => Some(map.len()),
475 _ => None,
476 }
477 }
478
479 pub fn is_empty(&self) -> bool {
481 match self {
482 JsonValue::Array(arr) => arr.is_empty(),
483 JsonValue::Object(map) => map.is_empty(),
484 _ => false,
485 }
486 }
487
488 pub fn as_i64(&self) -> Option<i64> {
492 match self {
493 JsonValue::Integer(v) => Some(*v),
494 _ => None,
495 }
496 }
497
498 pub fn as_u64(&self) -> Option<u64> {
501 match self {
502 JsonValue::U64(v) => Some(*v),
503 _ => None,
504 }
505 }
506
507 pub fn as_str(&self) -> Option<&str> {
509 match self {
510 JsonValue::String(s) => Some(s.as_ref()),
511 _ => None,
512 }
513 }
514
515 pub fn as_bool(&self) -> Option<bool> {
517 match self {
518 JsonValue::Bool(b) => Some(*b),
519 _ => None,
520 }
521 }
522
523 pub fn as_array(&self) -> Option<&[JsonValue]> {
525 match self {
526 JsonValue::Array(arr) => Some(arr.as_slice()),
527 _ => None,
528 }
529 }
530
531 pub fn as_array_mut(&mut self) -> Option<&mut [JsonValue]> {
533 match self {
534 JsonValue::Array(arr) => Some(arr.as_mut_slice()),
535 _ => None,
536 }
537 }
538
539 pub fn as_object(&self) -> Option<&ObjectMap> {
541 match self {
542 JsonValue::Object(map) => Some(map),
543 _ => None,
544 }
545 }
546
547 pub fn as_object_mut(&mut self) -> Option<&mut ObjectMap> {
549 match self {
550 JsonValue::Object(map) => Some(map),
551 _ => None,
552 }
553 }
554
555 pub fn get(&self, key: &str) -> Option<&JsonValue> {
578 match self {
579 JsonValue::Object(map) => map.get(key),
580 _ => None,
581 }
582 }
583
584 pub fn get_mut(&mut self, key: &str) -> Option<&mut JsonValue> {
586 match self {
587 JsonValue::Object(map) => map.get_mut(key),
588 _ => None,
589 }
590 }
591
592 pub fn insert(&mut self, key: String, value: JsonValue) -> Option<JsonValue> {
608 match self {
609 JsonValue::Object(map) => map.insert(key, value),
610 _ => None,
611 }
612 }
613
614 #[allow(clippy::map_entry)]
641 pub fn try_insert(&mut self, key: String, value: JsonValue) -> Result<(), &JsonValue> {
642 match self {
649 JsonValue::Object(map) => {
650 if map.contains_key(&key) {
651 match map.get(&key) {
652 Some(existing) => Err(existing),
653 None => Err(null_ref()),
654 }
655 } else {
656 map.insert(key, value);
657 Ok(())
658 }
659 }
660 _ => Err(null_ref()),
661 }
662 }
663
664 pub fn remove(&mut self, key: &str) -> Option<JsonValue> {
666 match self {
667 JsonValue::Object(map) => map.remove(key),
668 _ => None,
669 }
670 }
671
672 pub fn clear(&mut self) {
688 match self {
689 JsonValue::Array(arr) => arr.clear(),
690 JsonValue::Object(map) => map.clear(),
691 _ => {}
692 }
693 }
694}
695
696impl fmt::Display for JsonValue {
699 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
700 match self {
701 JsonValue::Null => write!(f, "null"),
702 JsonValue::Bool(b) => write!(f, "{b}"),
703 JsonValue::Integer(i) => write!(f, "{i}"),
704 JsonValue::U64(v) => write!(f, "{v}"),
705 JsonValue::String(s) => escape_json_string(s.as_ref(), f),
706 JsonValue::Array(arr) => {
707 write!(f, "[")?;
708 for (i, v) in arr.iter().enumerate() {
709 if i > 0 {
710 write!(f, ", ")?;
711 }
712 write!(f, "{v}")?;
713 }
714 write!(f, "]")
715 }
716 JsonValue::Object(map) => {
717 write!(f, "{{")?;
718 for (i, (k, v)) in map.iter().enumerate() {
719 if i > 0 {
720 write!(f, ", ")?;
721 }
722 escape_json_string(k, f)?;
723 write!(f, ": {v}")?;
724 }
725 write!(f, "}}")
726 }
727 }
728 }
729}
730
731fn escape_json_string(s: &str, f: &mut fmt::Formatter<'_>) -> fmt::Result {
736 write!(f, "\"")?;
737 for c in s.chars() {
738 match c {
739 '"' => write!(f, "\\\"")?,
740 '\\' => write!(f, "\\\\")?,
741 '\n' => write!(f, "\\n")?,
742 '\r' => write!(f, "\\r")?,
743 '\t' => write!(f, "\\t")?,
744 '\x08' => write!(f, "\\b")?,
745 '\x0c' => write!(f, "\\f")?,
746 c if (c as u32) < 0x20 => write!(f, "\\u{:04x}", c as u32)?,
747 c => write!(f, "{c}")?,
748 }
749 }
750 write!(f, "\"")
751}
752
753impl JsonValue {
756 pub const fn null() -> Self {
758 JsonValue::Null
759 }
760
761 pub const fn bool(b: bool) -> Self {
763 JsonValue::Bool(b)
764 }
765
766 pub const fn integer(i: i64) -> Self {
768 JsonValue::Integer(i)
769 }
770
771 pub const fn u64(v: u64) -> Self {
785 JsonValue::U64(v)
786 }
787
788 pub fn string<S: Into<String>>(s: S) -> Self {
799 JsonValue::String(Cow::Owned(s.into()))
800 }
801
802 pub fn array(v: Vec<JsonValue>) -> Self {
814 JsonValue::Array(v)
815 }
816
817 pub fn object(map: ObjectMap) -> Self {
833 JsonValue::Object(map)
834 }
835
836 pub fn object_from_pairs_owned(pairs: Vec<(String, JsonValue)>) -> Self {
853 let mut map = ObjectMap::new();
854 for (k, v) in pairs {
855 map.insert(k, v);
856 }
857 JsonValue::Object(map)
858 }
859
860 pub fn object_from_pairs(pairs: &[(&str, JsonValue)]) -> Self {
877 let mut map = ObjectMap::new();
878 for (k, v) in pairs {
879 map.insert((*k).to_string(), v.clone());
880 }
881 JsonValue::Object(map)
882 }
883
884 pub fn empty_object() -> Self {
896 JsonValue::Object(ObjectMap::new())
897 }
898
899 pub fn empty_array() -> Self {
911 JsonValue::Array(Vec::new())
912 }
913}
914
915impl From<ObjectMap> for JsonValue {
919 fn from(map: ObjectMap) -> Self {
920 JsonValue::Object(map)
921 }
922}
923
924impl From<Vec<JsonValue>> for JsonValue {
926 fn from(v: Vec<JsonValue>) -> Self {
927 JsonValue::Array(v)
928 }
929}
930
931impl From<&str> for JsonValue {
933 fn from(s: &str) -> Self {
934 JsonValue::String(Cow::Owned(s.to_string()))
935 }
936}
937
938impl From<String> for JsonValue {
940 fn from(s: String) -> Self {
941 JsonValue::String(Cow::Owned(s))
942 }
943}
944
945impl From<Cow<'static, str>> for JsonValue {
947 fn from(s: Cow<'static, str>) -> Self {
948 JsonValue::String(s)
949 }
950}
951
952impl From<i64> for JsonValue {
954 fn from(i: i64) -> Self {
955 JsonValue::Integer(i)
956 }
957}
958
959impl From<u64> for JsonValue {
961 fn from(v: u64) -> Self {
962 JsonValue::U64(v)
963 }
964}
965
966impl From<bool> for JsonValue {
968 fn from(b: bool) -> Self {
969 JsonValue::Bool(b)
970 }
971}
972
973#[cfg(test)]
974mod tests {
975 #![allow(clippy::unwrap_used)]
976 #![allow(clippy::expect_used)]
977 #![allow(clippy::panic)]
978 #![allow(clippy::indexing_slicing)]
979
980 use super::*;
981 use alloc::format;
982 use alloc::vec;
983 use core::cmp::Ordering;
984
985 #[test]
988 fn test_const_constructors() {
989 const N: JsonValue = JsonValue::null();
990 const B: JsonValue = JsonValue::bool(true);
991 const I: JsonValue = JsonValue::integer(-7);
992 assert_eq!(N, JsonValue::Null);
993 assert_eq!(B, JsonValue::Bool(true));
994 assert_eq!(I, JsonValue::Integer(-7));
995 }
996
997 #[test]
998 fn test_string_constructor() {
999 let s = JsonValue::string("hello");
1000 assert_eq!(s.as_str(), Some("hello"));
1001 let owned = JsonValue::string(String::from("world"));
1002 assert_eq!(owned.as_str(), Some("world"));
1003 }
1004
1005 #[test]
1006 fn test_empty_array() {
1007 assert_eq!(JsonValue::empty_array(), JsonValue::Array(Vec::new()));
1008 }
1009
1010 #[test]
1011 fn test_empty_object() {
1012 assert!(JsonValue::empty_object().is_object());
1013 assert_eq!(JsonValue::empty_object().len(), Some(0));
1014 }
1015
1016 #[test]
1017 fn test_object_from_pairs_owned() {
1018 let pairs = vec![
1019 ("a".to_string(), JsonValue::Integer(1)),
1020 ("b".to_string(), JsonValue::Integer(2)),
1021 ];
1022 let obj = JsonValue::object_from_pairs_owned(pairs);
1023 assert_eq!(obj.get("a").and_then(|v| v.as_i64()), Some(1));
1024 assert_eq!(obj.get("b").and_then(|v| v.as_i64()), Some(2));
1025 }
1026
1027 #[test]
1030 fn test_is_methods_match_correct_type() {
1031 assert!(JsonValue::Null.is_null());
1032 assert!(JsonValue::Bool(true).is_bool());
1033 assert!(JsonValue::Integer(0).is_integer());
1034 assert!(JsonValue::string("x").is_string());
1035 assert!(JsonValue::empty_array().is_array());
1036 assert!(JsonValue::empty_object().is_object());
1037 }
1038
1039 #[test]
1040 fn test_is_methods_reject_wrong_type() {
1041 assert!(!JsonValue::Null.is_bool());
1042 assert!(!JsonValue::Null.is_integer());
1043 assert!(!JsonValue::Integer(1).is_string());
1044 assert!(!JsonValue::string("x").is_array());
1045 assert!(!JsonValue::empty_array().is_object());
1046 assert!(!JsonValue::Bool(false).is_null());
1047 }
1048
1049 #[test]
1052 fn test_len_and_is_empty() {
1053 assert_eq!(JsonValue::Null.len(), None);
1054 assert_eq!(JsonValue::Integer(42).len(), None);
1055 assert_eq!(JsonValue::string("test").len(), None);
1056
1057 let arr = JsonValue::array(vec![JsonValue::Integer(1), JsonValue::Integer(2)]);
1058 assert_eq!(arr.len(), Some(2));
1059 assert!(!arr.is_empty());
1060
1061 let empty_arr = JsonValue::empty_array();
1062 assert_eq!(empty_arr.len(), Some(0));
1063 assert!(empty_arr.is_empty());
1064
1065 let obj = JsonValue::object_from_pairs(&[("a", JsonValue::Integer(1))]);
1066 assert_eq!(obj.len(), Some(1));
1067 assert!(!obj.is_empty());
1068
1069 assert!(JsonValue::empty_object().is_empty());
1070 }
1071
1072 #[test]
1075 fn test_as_methods_success_paths() {
1076 assert_eq!(JsonValue::Integer(42).as_i64(), Some(42));
1077 assert_eq!(JsonValue::string("hi").as_str(), Some("hi"));
1078 assert_eq!(JsonValue::Bool(true).as_bool(), Some(true));
1079 assert!(JsonValue::empty_array().as_array().is_some());
1080 assert!(JsonValue::empty_object().as_object().is_some());
1081 }
1082
1083 #[test]
1084 fn test_as_methods_type_mismatch_returns_none() {
1085 assert_eq!(JsonValue::Null.as_i64(), None);
1086 assert_eq!(JsonValue::Bool(true).as_i64(), None);
1087 assert_eq!(JsonValue::string("x").as_i64(), None);
1088 assert_eq!(JsonValue::Null.as_str(), None);
1089 assert_eq!(JsonValue::Integer(1).as_str(), None);
1090 assert_eq!(JsonValue::Integer(1).as_bool(), None);
1091 assert_eq!(JsonValue::Null.as_array(), None);
1092 assert_eq!(JsonValue::Integer(0).as_array(), None);
1093 assert_eq!(JsonValue::Null.as_object(), None);
1094 assert_eq!(JsonValue::Integer(0).as_object(), None);
1095 }
1096
1097 #[test]
1098 fn test_as_mut_methods_type_mismatch() {
1099 let mut v = JsonValue::Integer(0);
1100 assert!(v.as_array_mut().is_none());
1101 assert!(v.as_object_mut().is_none());
1102 let mut arr = JsonValue::empty_array();
1103 assert!(arr.as_array_mut().is_some());
1104 let mut obj = JsonValue::empty_object();
1105 assert!(obj.as_object_mut().is_some());
1106 }
1107
1108 #[test]
1111 fn test_object_accessors_on_non_object() {
1112 let mut v = JsonValue::Integer(0);
1113 assert_eq!(v.get("any"), None);
1114 assert_eq!(v.get_mut("any"), None);
1115 assert_eq!(v.insert("k".to_string(), JsonValue::Null), None);
1116 assert_eq!(v.remove("k"), None);
1117 assert_eq!(v, JsonValue::Integer(0));
1118 }
1119
1120 #[test]
1121 fn test_get_on_object() {
1122 let obj = JsonValue::object_from_pairs(&[("x", JsonValue::Integer(7))]);
1123 assert_eq!(obj.get("x"), Some(&JsonValue::Integer(7)));
1124 assert_eq!(obj.get("missing"), None);
1125 }
1126
1127 #[test]
1128 fn test_get_mut_on_object() {
1129 let mut obj = JsonValue::object_from_pairs(&[("a", JsonValue::Integer(1))]);
1130 if let Some(v) = obj.get_mut("a") {
1131 *v = JsonValue::Integer(42);
1132 }
1133 assert_eq!(obj.get("a"), Some(&JsonValue::Integer(42)));
1134 assert_eq!(obj.get_mut("missing"), None);
1135 }
1136
1137 #[test]
1138 fn test_insert_and_remove() {
1139 let mut obj = JsonValue::empty_object();
1140 assert_eq!(obj.insert("k".to_string(), JsonValue::Integer(1)), None);
1141 assert_eq!(obj.get("k"), Some(&JsonValue::Integer(1)));
1142
1143 let old = obj.insert("k".to_string(), JsonValue::Integer(2));
1144 assert_eq!(old, Some(JsonValue::Integer(1)));
1145 assert_eq!(obj.get("k"), Some(&JsonValue::Integer(2)));
1146
1147 assert_eq!(obj.remove("k"), Some(JsonValue::Integer(2)));
1148 assert_eq!(obj.get("k"), None);
1149 assert_eq!(obj.remove("missing"), None);
1150 }
1151
1152 #[test]
1153 fn test_try_insert() {
1154 let mut obj = JsonValue::empty_object();
1155 assert!(obj
1156 .try_insert("k".to_string(), JsonValue::Integer(1))
1157 .is_ok());
1158 assert!(obj
1159 .try_insert("k".to_string(), JsonValue::Integer(2))
1160 .is_err());
1161 assert_eq!(obj.get("k"), Some(&JsonValue::Integer(1)));
1162
1163 let mut non_obj = JsonValue::Integer(0);
1164 assert!(non_obj
1165 .try_insert("k".to_string(), JsonValue::Integer(1))
1166 .is_err());
1167 }
1168
1169 #[test]
1170 fn test_clear() {
1171 let mut arr = JsonValue::array(vec![JsonValue::Integer(1), JsonValue::Integer(2)]);
1172 arr.clear();
1173 assert_eq!(arr.len(), Some(0));
1174
1175 let mut obj = JsonValue::object_from_pairs(&[("a", JsonValue::Integer(1))]);
1176 obj.clear();
1177 assert_eq!(obj.len(), Some(0));
1178
1179 let mut null = JsonValue::Null;
1180 null.clear(); assert!(null.is_null());
1182 }
1183
1184 #[test]
1187 fn test_partial_eq_same_type() {
1188 assert_eq!(JsonValue::Null, JsonValue::Null);
1189 assert_eq!(JsonValue::Bool(true), JsonValue::Bool(true));
1190 assert_eq!(JsonValue::Integer(5), JsonValue::Integer(5));
1191 assert_eq!(JsonValue::string("hi"), JsonValue::string("hi"));
1192 assert_eq!(
1193 JsonValue::array(vec![JsonValue::Integer(1)]),
1194 JsonValue::array(vec![JsonValue::Integer(1)])
1195 );
1196 }
1197
1198 #[test]
1199 fn test_partial_eq_cross_type() {
1200 assert_ne!(JsonValue::Null, JsonValue::Bool(false));
1201 assert_ne!(JsonValue::Bool(true), JsonValue::Integer(1));
1202 assert_ne!(JsonValue::Integer(0), JsonValue::string("0"));
1203 assert_ne!(JsonValue::string(""), JsonValue::empty_array());
1204 assert_ne!(JsonValue::empty_array(), JsonValue::empty_object());
1205 }
1206
1207 #[test]
1208 fn test_partial_eq_object() {
1209 let mut a = ObjectMap::new();
1210 a.insert("x".to_string(), JsonValue::Integer(1));
1211 a.insert("y".to_string(), JsonValue::Integer(2));
1212 let mut b = ObjectMap::new();
1213 b.insert("x".to_string(), JsonValue::Integer(1));
1214 b.insert("y".to_string(), JsonValue::Integer(2));
1215 assert_eq!(JsonValue::object(a.clone()), JsonValue::object(b));
1216
1217 let mut c = ObjectMap::new();
1218 c.insert("x".to_string(), JsonValue::Integer(1));
1219 c.insert("y".to_string(), JsonValue::Integer(99));
1220 assert_ne!(JsonValue::object(a.clone()), JsonValue::object(c));
1221
1222 let mut d = ObjectMap::new();
1223 d.insert("x".to_string(), JsonValue::Integer(1));
1224 d.insert("z".to_string(), JsonValue::Integer(2));
1225 assert_ne!(JsonValue::object(a.clone()), JsonValue::object(d));
1226
1227 let mut e = ObjectMap::new();
1228 e.insert("x".to_string(), JsonValue::Integer(1));
1229 assert_ne!(JsonValue::object(a), JsonValue::object(e));
1230 }
1231
1232 #[test]
1235 fn test_ord_type_order() {
1236 assert_eq!(JsonValue::Null.cmp(&JsonValue::Null), Ordering::Equal);
1237 assert!(JsonValue::Null < JsonValue::Bool(false));
1238 assert!(JsonValue::Bool(false) < JsonValue::Integer(0));
1239 assert!(JsonValue::Integer(0) < JsonValue::string(""));
1240 assert!(JsonValue::string("") < JsonValue::empty_array());
1241 assert!(JsonValue::empty_array() < JsonValue::empty_object());
1242 }
1243
1244 #[test]
1245 fn test_ord_lexicographic() {
1246 assert!(JsonValue::Integer(0) < JsonValue::Integer(1));
1247 assert!(JsonValue::string("a") < JsonValue::string("b"));
1248
1249 let mut short = ObjectMap::new();
1250 short.insert("a".to_string(), JsonValue::Integer(1));
1251 let mut long = ObjectMap::new();
1252 long.insert("a".to_string(), JsonValue::Integer(1));
1253 long.insert("b".to_string(), JsonValue::Integer(2));
1254 assert!(JsonValue::object(short) < JsonValue::object(long));
1255 }
1256
1257 #[test]
1260 fn test_display_simple_types() {
1261 assert_eq!(format!("{}", JsonValue::Null), "null");
1262 assert_eq!(format!("{}", JsonValue::Bool(true)), "true");
1263 assert_eq!(format!("{}", JsonValue::Bool(false)), "false");
1264 assert_eq!(format!("{}", JsonValue::Integer(0)), "0");
1265 assert_eq!(format!("{}", JsonValue::Integer(-42)), "-42");
1266 }
1267
1268 #[test]
1269 fn test_display_string_escapes() {
1270 assert_eq!(format!("{}", JsonValue::string("")), "\"\"");
1271 assert_eq!(format!("{}", JsonValue::string("hello")), "\"hello\"");
1272 assert_eq!(format!("{}", JsonValue::string("a\"b")), "\"a\\\"b\"");
1273 assert_eq!(format!("{}", JsonValue::string("a\\b")), "\"a\\\\b\"");
1274 assert_eq!(format!("{}", JsonValue::string("a\nb")), "\"a\\nb\"");
1275 }
1276
1277 #[test]
1278 fn test_display_array() {
1279 assert_eq!(format!("{}", JsonValue::empty_array()), "[]");
1280 let arr = JsonValue::array(vec![
1281 JsonValue::Integer(1),
1282 JsonValue::Integer(2),
1283 JsonValue::Integer(3),
1284 ]);
1285 assert_eq!(format!("{arr}"), "[1, 2, 3]");
1286 }
1287
1288 #[test]
1289 fn test_display_object() {
1290 assert_eq!(format!("{}", JsonValue::empty_object()), "{}");
1291 let obj = JsonValue::object_from_pairs(&[
1292 ("z", JsonValue::Integer(1)),
1293 ("a", JsonValue::Integer(2)),
1294 ]);
1295 assert_eq!(format!("{obj}"), "{\"a\": 2, \"z\": 1}");
1296 }
1297
1298 #[test]
1301 fn test_from_traits() {
1302 let v: JsonValue = 42i64.into();
1303 assert_eq!(v, JsonValue::Integer(42));
1304
1305 let v: JsonValue = "hello".into();
1306 assert_eq!(v, JsonValue::string("hello"));
1307
1308 let v: JsonValue = true.into();
1309 assert_eq!(v, JsonValue::Bool(true));
1310
1311 let v: JsonValue = vec![JsonValue::Integer(1), JsonValue::Integer(2)].into();
1312 assert_eq!(v.len(), Some(2));
1313 }
1314
1315 #[test]
1321 fn test_display_escapes_control_chars() {
1322 let v = JsonValue::string("a\u{1}b");
1323 assert_eq!(v.to_string(), "\"a\\u0001b\"");
1324
1325 let v = JsonValue::string("\u{1f}");
1327 assert_eq!(v.to_string(), "\"\\u001f\"");
1328 }
1329
1330 #[test]
1333 fn test_display_space_verbatim() {
1334 let v = JsonValue::string("a b");
1335 assert_eq!(v.to_string(), "\"a b\"");
1336 }
1337
1338 #[test]
1341 fn test_u64_construct_and_access() {
1342 let v = JsonValue::u64(u64::MAX - 1);
1343 assert!(v.is_u64());
1344 assert!(!v.is_integer());
1345 assert_eq!(v.as_u64(), Some(u64::MAX - 1));
1346 assert_eq!(v.as_i64(), None);
1350 assert_eq!(JsonValue::Integer(5).as_u64(), None);
1351 assert!(!JsonValue::Integer(5).is_u64());
1352 assert!(!JsonValue::Bool(true).is_u64());
1353 assert!(!JsonValue::Null.is_u64());
1354
1355 let from_trait: JsonValue = 42u64.into();
1356 assert_eq!(from_trait, JsonValue::u64(42));
1357 }
1358
1359 #[test]
1360 fn test_u64_partial_eq_strict_shape() {
1361 assert_ne!(JsonValue::u64(5), JsonValue::Integer(5));
1363 assert_ne!(JsonValue::Integer(5), JsonValue::u64(5));
1364 assert_eq!(JsonValue::u64(5), JsonValue::u64(5));
1365 assert_ne!(JsonValue::u64(u64::MAX), JsonValue::u64(u64::MAX - 1));
1366 }
1367
1368 #[test]
1369 fn test_u64_ord_group_order() {
1370 assert!(JsonValue::Integer(0) < JsonValue::u64(0));
1372 assert!(JsonValue::u64(0) < JsonValue::string(""));
1373 assert!(JsonValue::u64(0) < JsonValue::u64(1));
1374 assert!(JsonValue::u64(u64::MAX - 1) < JsonValue::u64(u64::MAX));
1375 assert!(JsonValue::Integer(i64::MAX) < JsonValue::u64(0));
1378 }
1379
1380 #[test]
1381 fn test_u64_display() {
1382 assert_eq!(format!("{}", JsonValue::u64(0)), "0");
1383 assert_eq!(
1384 format!("{}", JsonValue::u64(u64::MAX - 1)),
1385 "18446744073709551614"
1386 );
1387 }
1388}