1use serde::Serialize;
11use serde_json::{Map, Value};
12use std::collections::BTreeMap;
13
14#[derive(Debug, thiserror::Error)]
16pub enum CanonicalError {
17 #[error("Serialization error")]
18 Serialize(#[from] serde_json::Error),
19}
20
21pub fn canonical_json<T: Serialize>(value: &T) -> Result<Vec<u8>, CanonicalError> {
41 let value = serde_json::to_value(value)?;
42 let canonical = canonicalize_value(value);
43 let json = serde_json::to_string(&canonical)?;
44 Ok(json.into_bytes())
45}
46
47fn canonicalize_value(value: Value) -> Value {
52 match value {
53 Value::Object(map) => {
54 let mut sorted = BTreeMap::new();
55 for (k, v) in map {
56 sorted.insert(k, canonicalize_value(v));
57 }
58 Value::Object(Map::from_iter(sorted))
59 }
60 Value::Array(arr) => {
61 let normalized = arr.into_iter().map(canonicalize_value).collect();
62 Value::Array(normalized)
63 }
64 _ => value,
65 }
66}
67
68#[cfg(test)]
69mod tests {
70 use super::*;
71 use serde_json::json;
72
73 #[test]
74 fn canonical_sorts_object_keys() {
75 let obj = json!({ "b": 2, "a": 1 });
76 let bytes = canonical_json(&obj).unwrap();
77 assert_eq!(bytes, br#"{"a":1,"b":2}"#.as_slice());
78 }
79
80 #[test]
81 fn canonical_preserves_array_order() {
82 let obj = json!({ "items": [3, 1, 2] });
83 let bytes = canonical_json(&obj).unwrap();
84 assert_eq!(bytes, br#"{"items":[3,1,2]}"#.as_slice());
85 }
86
87 #[test]
88 fn canonical_nested_objects() {
89 let obj = json!({
90 "b": 2,
91 "a": 1,
92 "c": { "z": 26, "y": 25 }
93 });
94 let bytes = canonical_json(&obj).unwrap();
95 assert_eq!(bytes, br#"{"a":1,"b":2,"c":{"y":25,"z":26}}"#.as_slice());
96 }
97
98 #[test]
99 fn canonical_idempotent() {
100 let obj = json!({
101 "b": 2,
102 "a": 1,
103 "c": [3, 1, 2]
104 });
105 let bytes1 = canonical_json(&obj).unwrap();
106 let json_str = String::from_utf8(bytes1.clone()).unwrap();
107 let parsed: Value = serde_json::from_str(&json_str).unwrap();
108 let bytes2 = canonical_json(&parsed).unwrap();
109 assert_eq!(bytes1, bytes2);
110 }
111
112 #[test]
113 fn canonical_preserves_float_values() {
114 let obj = json!({ "value": 0.123456789 });
115 let bytes = canonical_json(&obj).unwrap();
116 let parsed: Value = serde_json::from_slice(&bytes).unwrap();
117 let value = parsed.get("value").and_then(|v| v.as_f64()).unwrap();
118 assert!((value - 0.123456789).abs() < 1e-12);
119 }
120
121 #[test]
122 fn canonical_preserves_scientific_notation() {
123 let obj = json!({ "value": 1e20 });
124 let bytes = canonical_json(&obj).unwrap();
125 let parsed: Value = serde_json::from_slice(&bytes).unwrap();
126 let value = parsed.get("value").and_then(|v| v.as_f64()).unwrap();
127 assert_eq!(value, 1e20);
128 }
129
130 #[test]
131 fn canonical_does_not_normalize_unicode() {
132 let composed = json!({ "café": 1 });
133 let decomposed = json!({ "cafe\u{0301}": 1 });
134
135 let bytes_composed = canonical_json(&composed).unwrap();
136 let bytes_decomposed = canonical_json(&decomposed).unwrap();
137
138 assert_ne!(bytes_composed, bytes_decomposed);
139 assert_eq!(canonical_json(&composed).unwrap(), bytes_composed);
140 assert_eq!(canonical_json(&decomposed).unwrap(), bytes_decomposed);
141 }
142}