MCPcopy Create free account
hub / github.com/ScriptedAlchemy/tracedecay / canonicalize

Function canonicalize

src/context/read_cache.rs:50–69  ·  view source on GitHub ↗

Sorts JSON object keys recursively so two semantically-equal arg objects hash identically regardless of key insertion order.

(v: &serde_json::Value)

Source from the content-addressed store, hash-verified

48/// Sorts JSON object keys recursively so two semantically-equal arg objects
49/// hash identically regardless of key insertion order.
50fn canonicalize(v: &serde_json::Value) -> String {
51 use serde_json::Value;
52 match v {
53 Value::Object(map) => {
54 let mut entries: Vec<(&String, &Value)> = map.iter().collect();
55 entries.sort_by_key(|(k, _)| k.as_str());
56 let inner = entries
57 .into_iter()
58 .map(|(k, v)| format!("\"{k}\":{}", canonicalize(v)))
59 .collect::<Vec<_>>()
60 .join(",");
61 format!("{{{inner}}}")
62 }
63 Value::Array(items) => {
64 let inner = items.iter().map(canonicalize).collect::<Vec<_>>().join(",");
65 format!("[{inner}]")
66 }
67 other => other.to_string(),
68 }
69}
70
71/// SHA-256 of arbitrary bytes, hex-encoded. Used as the body digest so callers
72/// can detect content changes even when only the cache layer changed.

Calls 2

collectMethod · 0.80
as_strMethod · 0.45