crates/edge/proto/src/mirror.rs 6.6 KiB 185 lines Raw
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.16 17 use crate::cbor::Value;18 19 /// The key that marks a byte string in the mirror.20 const BYTES: &str = "$bytes";21 22 /// The JSON form of a CBOR value.23 pub fn to_json(value: &Value) -> inf3r_json::Value {24     use inf3r_json::Value as J;25     match value {26         Value::Uint(n) => match i64::try_from(*n) {27             Ok(n) => J::Int(n),28             Err(_) => J::Float(*n as f64),29         },30         Value::Nint(n) => J::Int(*n),31         Value::Bytes(bytes) => inf3r_json::Object::new()32             .put(BYTES, J::str(inf3r_json::b64::encode(bytes)))33             .build(),34         Value::Text(text) => J::str(text.clone()),35         Value::Array(items) => J::Array(items.iter().map(to_json).collect()),36         Value::Map(entries) => {37             let mut object = inf3r_json::Object::new();38             for (key, value) in entries {39                 let Value::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));43                     continue;44                 };45                 object = object.put(key.clone(), to_json(value));46             }47             object.build()48         }49         Value::Bool(b) => J::Bool(*b),50         Value::Null => J::Null,51         Value::Float(x) => J::Float(*x),52     }53 }54 55 /// 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.60 pub fn from_json(value: &inf3r_json::Value) -> Option<Value> {61     use inf3r_json::Value as J;62     Some(match value {63         J::Null => Value::Null,64         J::Bool(b) => Value::Bool(*b),65         J::Int(n) => {66             if *n >= 0 {67                 Value::Uint(*n as u64)68             } else {69                 Value::Nint(*n)70             }71         }72         J::Float(x) => Value::Float(*x),73         J::Str(text) => Value::Text(text.clone()),74         J::Array(items) => Value::Array(75             items76                 .iter()77                 .map(from_json)78                 .collect::<Option<Vec<Value>>>()?,79         ),80         J::Object(map) => {81             if map.len() == 182                 && let Some(J::Str(bytes)) = map.get(BYTES)83             {84                 return inf3r_json::b64::decode(bytes).map(Value::Bytes);85             }86             let mut entries = Vec::with_capacity(map.len());87             for (key, value) in map {88                 entries.push((Value::Text(key.clone()), from_json(value)?));89             }90             Value::Map(entries)91         }92     })93 }94 95 #[cfg(test)]96 mod tests {97     use super::*;98 99     fn json(value: &Value) -> String {100         inf3r_json::to_string(&to_json(value))101     }102 103     #[test]104     fn a_body_survives_the_mirror() {105         let 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!(113             json(&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.118         let 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     }127 128     #[test]129     fn bytes_have_their_own_key_so_they_cannot_be_confused_with_text() {130         let value = Value::Bytes(vec![0, 1, 2]);131         assert_eq!(json(&value), r#"{"$bytes":"AAEC"}"#);132         assert_eq!(133             from_json(&to_json(&value)),134             Some(Value::Bytes(vec![0, 1, 2]))135         );136 137         // Text that happens to be the base64 of the bytes stays text.138         let text = Value::Text("AAEC".into());139         assert_eq!(json(&text), r#""AAEC""#);140         assert_ne!(141             from_json(&to_json(&text)),142             Some(Value::Bytes(vec![0, 1, 2]))143         );144     }145 146     #[test]147     fn a_large_unsigned_value_widens_instead_of_wrapping() {148         let value = Value::Uint(u64::MAX);149         let mirrored = to_json(&value);150         assert!(mirrored.as_f64().is_some(), "a huge u64 becomes a float");151     }152 153     #[test]154     fn only_a_lone_bytes_key_is_a_byte_string() {155         let parsed = inf3r_json::parse(r#"{"$bytes":"AAEC"}"#);156         assert!(parsed.is_ok(), "the marker object parses");157         let Ok(marked) = parsed else {158             return;159         };160         assert_eq!(from_json(&marked), Some(Value::Bytes(vec![0, 1, 2])));161 162         let parsed = inf3r_json::parse(r#"{"$bytes":"AAEC","other":1}"#);163         assert!(parsed.is_ok(), "the ordinary object parses");164         let Ok(ordinary) = parsed else {165             return;166         };167         let mirrored = from_json(&ordinary);168         assert!(matches!(mirrored, Some(Value::Map(_))));169         let Some(Value::Map(entries)) = mirrored else {170             return;171         };172         assert_eq!(entries.len(), 2);173         assert!(entries.contains(&(Value::Text("$bytes".into()), Value::Text("AAEC".into()))));174     }175 176     #[test]177     fn one_invalid_array_item_fails_the_whole_mirror() {178         let parsed = inf3r_json::parse(r#"[1,{"$bytes":"not base64!"},3]"#);179         assert!(parsed.is_ok(), "the array parses");180         let Ok(value) = parsed else {181             return;182         };183         assert_eq!(from_json(&value), None);184     }185 }