Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/interplane-mv/blob/main/rust/crates/interplane-core/src/jcs.rs # interplane-mv INTERPLANE: open interoperability protocol between AI models and agent runtimes. Models express intent. Runtimes retain authority. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `interplane-mv / rust / crates / interplane-core / src / jcs.rs` 178 lines · 5430 bytes Raw Blame History 1 //! RFC 8785 (JCS) canonical JSON and `sha256:` digests. 2 use serde_json::{Number, Value}; 3 use sha2::{Digest, Sha256}; 4 5 /// Canonical JSON text: sorted keys (by UTF-16 code units), no whitespace, ES6 numbers. 6 pub fn canonicalize(v: &Value) -> String { 7 let mut out = String::new(); 8 write_value(v, &mut out); 9 out 10 } 11 12 /// `"sha256:" + lowercase hex` of the canonical JSON bytes. 13 pub fn digest(v: &Value) -> String { 14 digest_bytes(canonicalize(v).as_bytes()) 15 } 16 17 /// `"sha256:" + lowercase hex` of raw bytes. 18 pub fn digest_bytes(b: &[u8]) -> String { 19 let h = Sha256::digest(b); 20 let mut s = String::with_capacity(71); 21 s.push_str("sha256:"); 22 for byte in h { 23 s.push_str(&format!("{byte:02x}")); 24 } 25 s 26 } 27 28 fn write_value(v: &Value, out: &mut String) { 29 match v { 30 Value::Null => out.push_str("null"), 31 Value::Bool(true) => out.push_str("true"), 32 Value::Bool(false) => out.push_str("false"), 33 Value::Number(n) => out.push_str(&number(n)), 34 Value::String(s) => write_string(s, out), 35 Value::Array(a) => { 36 out.push('['); 37 for (i, x) in a.iter().enumerate() { 38 if i > 0 { 39 out.push(','); 40 } 41 write_value(x, out); 42 } 43 out.push(']'); 44 } 45 Value::Object(m) => { 46 let mut keys: Vec<&String> = m.keys().collect(); 47 keys.sort_by(|a, b| a.encode_utf16().cmp(b.encode_utf16())); 48 out.push('{'); 49 for (i, k) in keys.into_iter().enumerate() { 50 if i > 0 { 51 out.push(','); 52 } 53 write_string(k, out); 54 out.push(':'); 55 write_value(&m[k], out); 56 } 57 out.push('}'); 58 } 59 } 60 } 61 62 fn write_string(s: &str, out: &mut String) { 63 out.push('"'); 64 for c in s.chars() { 65 match c { 66 '"' => out.push_str("\\\""), 67 '\\' => out.push_str("\\\\"), 68 '\u{8}' => out.push_str("\\b"), 69 '\t' => out.push_str("\\t"), 70 '\n' => out.push_str("\\n"), 71 '\u{c}' => out.push_str("\\f"), 72 '\r' => out.push_str("\\r"), 73 c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)), 74 c => out.push(c), 75 } 76 } 77 out.push('"'); 78 } 79 80 fn number(n: &Number) -> String { 81 if let Some(i) = n.as_i64() { 82 return i.to_string(); 83 } 84 if let Some(u) = n.as_u64() { 85 return u.to_string(); 86 } 87 es6_f64(n.as_f64().unwrap_or(0.0)) 88 } 89 90 /// ECMAScript `Number::toString` for finite doubles (NaN/Infinity cannot occur in JSON values). 91 pub fn es6_f64(x: f64) -> String { 92 if x == 0.0 { 93 return "0".into(); 94 } 95 let neg = x < 0.0; 96 let ax = x.abs(); 97 // Shortest round-trip digits via LowerExp: d.ddddde 98 let e = format!("{ax:e}"); 99 let (mant, exp) = e.split_once('e').expect("lower exp"); 100 let exp: i32 = exp.parse().expect("exp"); 101 let digits: String = mant.chars().filter(|c| *c != '.').collect(); 102 let k = digits.len() as i32; 103 let n = exp + 1; 104 let mut s = String::new(); 105 if neg { 106 s.push('-'); 107 } 108 if k <= n && n <= 21 { 109 s.push_str(&digits); 110 s.push_str(&"0".repeat((n - k) as usize)); 111 } else if 0 < n && n <= 21 { 112 s.push_str(&digits[..n as usize]); 113 s.push('.'); 114 s.push_str(&digits[n as usize..]); 115 } else if -6 < n && n <= 0 { 116 s.push_str("0."); 117 s.push_str(&"0".repeat((-n) as usize)); 118 s.push_str(&digits); 119 } else { 120 let sign = if n - 1 < 0 { '-' } else { '+' }; 121 s.push_str(&digits[..1]); 122 if k > 1 { 123 s.push('.'); 124 s.push_str(&digits[1..]); 125 } 126 s.push('e'); 127 s.push(sign); 128 s.push_str(&(n - 1).abs().to_string()); 129 } 130 s 131 } 132 133 #[cfg(test)] 134 mod tests { 135 use super::*; 136 use serde_json::json; 137 138 #[test] 139 fn sorts_keys_and_strips_whitespace() { 140 assert_eq!( 141 canonicalize(&json!({"b": 1, "a": [true, null, "x"]})), 142 r#"{"a":[true,null,"x"],"b":1}"# 143 ); 144 } 145 #[test] 146 fn numbers_es6() { 147 assert_eq!(es6_f64(1e21), "1e+21"); 148 assert_eq!(es6_f64(1e20), "`100000000000000000000`"); 149 assert_eq!(es6_f64(1.5), "1.5"); 150 assert_eq!(es6_f64(0.000001), "0.000001"); 151 assert_eq!(es6_f64(0.`0000001`), "1e-7"); 152 assert_eq!(es6_f64(-2.5e-9), "-2.5e-9"); 153 assert_eq!(es6_f64(`123456789012345680000`.0), "`123456789012345680000`"); 154 assert_eq!(canonicalize(&json!(1.0)), "1.0".replace(".0", "")); // 1.0 parses as f64 -> "1" 155 assert_eq!(canonicalize(&json!(-0.0)), "0"); 156 assert_eq!(canonicalize(&json!(10)), "10"); 157 } 158 #[test] 159 fn strings_escape() { 160 assert_eq!( 161 canonicalize(&json!("a\"b\\c\n\u{1}\u{7f}é😀")), 162 "\"a\\\"b\\\\c\\n\\u0001\u{7f}é😀\"" 163 ); 164 } 165 #[test] 166 fn utf16_key_order() { 167 // U+FFFD (BMP) sorts after U+1F600 (surrogate D83D) in UTF-16 order. 168 let v = json!({"\u{fffd}": 1, "\u{1f600}": 2}); 169 assert_eq!(canonicalize(&v), "{\"\u{1f600}\":2,\"\u{fffd}\":1}"); 170 } 171 #[test] 172 fn digest_known() { 173 assert_eq!( 174 digest(&json!({})), 175 "sha256:`44136fa355b3678a1146ad16f7e8649e94fb4fc21fe77e8310c060f61caaff8a`" 176 ); 177 } 178 }