Skip to main content

codewhale_runtime/
hashing.rs

1use sha2::{Digest, Sha256};
2
3pub fn sha256_hex(bytes: impl AsRef<[u8]>) -> String {
4    hex_bytes(Sha256::digest(bytes.as_ref()))
5}
6
7pub fn hex_bytes(bytes: impl AsRef<[u8]>) -> String {
8    let bytes = bytes.as_ref();
9    let mut out = String::with_capacity(bytes.len() * 2);
10    for byte in bytes {
11        use std::fmt::Write as _;
12        let _ = write!(&mut out, "{byte:02x}");
13    }
14    out
15}
16
17/// Canonical JSON: object keys sorted, no insignificant whitespace.
18///
19/// Deterministic for a given `Value` regardless of how it was built.
20pub fn canonical_json(value: &serde_json::Value) -> String {
21    let mut out = String::new();
22    write_canonical(value, &mut out);
23    out
24}
25
26fn write_canonical(value: &serde_json::Value, out: &mut String) {
27    match value {
28        serde_json::Value::Object(map) => {
29            let mut keys: Vec<&String> = map.keys().collect();
30            keys.sort_unstable();
31            out.push('{');
32            for (index, key) in keys.iter().enumerate() {
33                if index > 0 {
34                    out.push(',');
35                }
36                push_json_string(key, out);
37                out.push(':');
38                write_canonical(&map[*key], out);
39            }
40            out.push('}');
41        }
42        serde_json::Value::Array(items) => {
43            out.push('[');
44            for (index, item) in items.iter().enumerate() {
45                if index > 0 {
46                    out.push(',');
47                }
48                write_canonical(item, out);
49            }
50            out.push(']');
51        }
52        other => out.push_str(&other.to_string()),
53    }
54}
55
56fn push_json_string(value: &str, out: &mut String) {
57    out.push_str(&serde_json::Value::String(value.to_string()).to_string());
58}