1//! The JSON mirror of a CBOR value.2//!3//! A trace file, a catalogue on stdout, and a golden are JSON. The wire is4//! CBOR. The two value trees are nearly the same, and this module is the only5//! place where one becomes the other, so a body that gains a field cannot6//! arrive in a mirror as a different shape.7//!8//! The two differences are honest ones:9//!10//! - CBOR has bytes and JSON does not, so bytes become base64 text with a11//! marker key. A byte string that a JSON reader turned into plain text would12//! compare equal to the base64 of something else.13//! - CBOR has more than 64 bits of integer, JSON has `i64` or `f64`. A large14//! unsigned value becomes `f64` and loses precision above 2^53, which is why15//! no field that matters is that large.1617usecrate::cbor::Value;1819/// The key that marks a byte string in the mirror.20constBYTES: &str = "$bytes";2122/// The JSON form of a CBOR value.23pubfnto_json(value: &Value) -> inf3r_json::Value {24use inf3r_json::ValueasJ;25match value {26Value::Uint(n) => match i64::try_from(*n) {27Ok(n) => J::Int(n),28Err(_) => J::Float(*n as f64),29 },30Value::Nint(n) => J::Int(*n),31Value::Bytes(bytes) => inf3r_json::Object::new()32 .put(BYTES, J::str(inf3r_json::b64::encode(bytes)))33 .build(),34Value::Text(text) => J::str(text.clone()),35Value::Array(items) => J::Array(items.iter().map(to_json).collect()),36Value::Map(entries) => {37letmut object = inf3r_json::Object::new();38for (key, value) in entries {39letValue::Text(key) = key else {40// A non-text key has no JSON spelling. The protocol never41// writes one, so the mirror names it instead of guessing.42 object = object.put("$key", to_json(key));43continue;44 };45 object = object.put(key.clone(), to_json(value));46 }47 object.build()48 }49Value::Bool(b) => J::Bool(*b),50Value::Null => J::Null,51Value::Float(x) => J::Float(*x),52 }53 }5455/// The CBOR value of a JSON mirror.56///57/// It is the inverse of [`to_json`] for every value that `to_json` writes. A58/// number that JSON holds as an integer comes back as an unsigned value when it59/// is not negative, because the protocol has no signed integer type.60pubfnfrom_json(value: &inf3r_json::Value) -> Option<Value> {61use inf3r_json::ValueasJ;62Some(match value {63J::Null => Value::Null,64J::Bool(b) => Value::Bool(*b),65J::Int(n) => {66if *n >= 0 {67Value::Uint(*n as u64)68 } else {69Value::Nint(*n)70 }71 }72J::Float(x) => Value::Float(*x),73J::Str(text) => Value::Text(text.clone()),74J::Array(items) => Value::Array(75 items76 .iter()77 .map(from_json)78 .collect::<Option<Vec<Value>>>()?,79 ),80J::Object(map) => {81if map.len() == 182 && letSome(J::Str(bytes)) = map.get(BYTES)83 {84return inf3r_json::b64::decode(bytes).map(Value::Bytes);85 }86letmut entries = Vec::with_capacity(map.len());87for (key, value) in map {88 entries.push((Value::Text(key.clone()), from_json(value)?));89 }90Value::Map(entries)91 }92 })93 }9495 #[cfg(test)]96mod tests {97usesuper::*;9899fnjson(value: &Value) -> String {100 inf3r_json::to_string(&to_json(value))101 }102103 #[test]104fna_body_survives_the_mirror() {105let value = Value::Map(vec![106 (Value::Text("ch".into()), Value::Text("text".into())),107 (Value::Text("n".into()), Value::Uint(7)),108 (Value::Text("neg".into()), Value::Nint(-2)),109 (Value::Text("ok".into()), Value::Bool(true)),110 (Value::Text("none".into()), Value::Null),111 ]);112 assert_eq!(113json(&value),114 r#"{"ch":"text","n":7,"neg":-2,"none":null,"ok":true}"#115 );116// A CBOR map is unordered and a JSON object is sorted, so a round trip117// returns the pairs in key order. That is the only difference.118let sorted = Value::Map(vec![119 (Value::Text("ch".into()), Value::Text("text".into())),120 (Value::Text("n".into()), Value::Uint(7)),121 (Value::Text("neg".into()), Value::Nint(-2)),122 (Value::Text("none".into()), Value::Null),123 (Value::Text("ok".into()), Value::Bool(true)),124 ]);125 assert_eq!(from_json(&to_json(&value)), Some(sorted));126 }127128 #[test]129fnbytes_have_their_own_key_so_they_cannot_be_confused_with_text() {130let value = Value::Bytes(vec![0, 1, 2]);131 assert_eq!(json(&value), r#"{"$bytes":"AAEC"}"#);132 assert_eq!(133from_json(&to_json(&value)),134Some(Value::Bytes(vec![0, 1, 2]))135 );136137// Text that happens to be the base64 of the bytes stays text.138let text = Value::Text("AAEC".into());139 assert_eq!(json(&text), r#""AAEC""#);140 assert_ne!(141from_json(&to_json(&text)),142Some(Value::Bytes(vec![0, 1, 2]))143 );144 }145146 #[test]147fna_large_unsigned_value_widens_instead_of_wrapping() {148let value = Value::Uint(u64::MAX);149let mirrored = to_json(&value);150 assert!(mirrored.as_f64().is_some(), "a huge u64 becomes a float");151 }152153 #[test]154fnonly_a_lone_bytes_key_is_a_byte_string() {155let parsed = inf3r_json::parse(r#"{"$bytes":"AAEC"}"#);156 assert!(parsed.is_ok(), "the marker object parses");157letOk(marked) = parsed else {158return;159 };160 assert_eq!(from_json(&marked), Some(Value::Bytes(vec![0, 1, 2])));161162let parsed = inf3r_json::parse(r#"{"$bytes":"AAEC","other":1}"#);163 assert!(parsed.is_ok(), "the ordinary object parses");164letOk(ordinary) = parsed else {165return;166 };167let mirrored = from_json(&ordinary);168 assert!(matches!(mirrored, Some(Value::Map(_))));169letSome(Value::Map(entries)) = mirrored else {170return;171 };172 assert_eq!(entries.len(), 2);173 assert!(entries.contains(&(Value::Text("$bytes".into()), Value::Text("AAEC".into()))));174 }175176 #[test]177fnone_invalid_array_item_fails_the_whole_mirror() {178let parsed = inf3r_json::parse(r#"[1,{"$bytes":"not base64!"},3]"#);179 assert!(parsed.is_ok(), "the array parses");180letOk(value) = parsed else {181return;182 };183 assert_eq!(from_json(&value), None);184 }185 }