use std::fmt::Write as _;
use serde_json::Value;
use sha2::{Digest, Sha256};
use crate::wire::Row;
pub fn write_canonical(value: &Value, out: &mut String) {
match value {
Value::Null => out.push_str("null"),
Value::Bool(true) => out.push_str("true"),
Value::Bool(false) => out.push_str("false"),
Value::Number(number) => {
let _ = write!(out, "{number}");
}
Value::String(text) => write_json_string(text, out),
Value::Array(items) => {
out.push('[');
for (index, item) in items.iter().enumerate() {
if index > 0 {
out.push(',');
}
write_canonical(item, out);
}
out.push(']');
}
Value::Object(object) => {
let sorted = object.keys().zip(object.keys().skip(1)).all(|(a, b)| a < b);
out.push('{');
if sorted {
write_entries(object.iter(), out);
} else {
let mut entries: Vec<(&String, &Value)> = object.iter().collect();
entries.sort_by(|a, b| a.0.cmp(b.0));
write_entries(entries.into_iter(), out);
}
out.push('}');
}
}
}
fn write_entries<'v>(entries: impl Iterator<Item = (&'v String, &'v Value)>, out: &mut String) {
for (index, (key, item)) in entries.enumerate() {
if index > 0 {
out.push(',');
}
write_json_string(key, out);
out.push(':');
write_canonical(item, out);
}
}
pub fn canonical_json(value: &Value) -> String {
let mut out = String::new();
write_canonical(value, &mut out);
out
}
pub fn canonical_len(value: &Value) -> usize {
match value {
Value::Null => 4,
Value::Bool(true) => 4,
Value::Bool(false) => 5,
Value::Number(number) => number.to_string().len(),
Value::String(text) => json_len_of_str(text),
Value::Array(items) => {
2 + items.iter().map(canonical_len).sum::<usize>() + items.len().saturating_sub(1)
}
Value::Object(object) => {
2 + object
.iter()
.map(|(key, item)| json_len_of_str(key) + 1 + canonical_len(item))
.sum::<usize>()
+ object.len().saturating_sub(1)
}
}
}
fn write_json_string(text: &str, out: &mut String) {
out.push('"');
if !text.bytes().any(|b| b == b'"' || b == b'\\' || b < 0x20) {
out.push_str(text);
out.push('"');
return;
}
for ch in text.chars() {
match ch {
'"' => out.push_str("\\\""),
'\\' => out.push_str("\\\\"),
'\u{08}' => out.push_str("\\b"),
'\u{0c}' => out.push_str("\\f"),
'\n' => out.push_str("\\n"),
'\r' => out.push_str("\\r"),
'\t' => out.push_str("\\t"),
ch if (ch as u32) < 0x20 => {
out.push_str("\\u00");
out.push(hex_digit((ch as u32 >> 4) as u8));
out.push(hex_digit((ch as u32 & 0xf) as u8));
}
ch => out.push(ch),
}
}
out.push('"');
}
pub(crate) fn json_len_of_str(text: &str) -> usize {
2 + text
.chars()
.map(|ch| match ch {
'"' | '\\' | '\u{08}' | '\u{0c}' | '\n' | '\r' | '\t' => 2,
ch if (ch as u32) < 0x20 => 6,
ch => ch.len_utf8(),
})
.sum::<usize>()
}
fn hex_digit(nibble: u8) -> char {
char::from(b"0123456789abcdef"[usize::from(nibble & 0xf)])
}
pub fn row_digest(row: &Row) -> String {
digest_and_value_len(row).0
}
pub(crate) fn digest_and_value_len(row: &Row) -> (String, usize) {
let mut canonical = String::with_capacity(256);
canonical.push('[');
write_canonical(&row.value, &mut canonical);
let value_len = canonical.len() - 1;
let _ = write!(canonical, ",{},", row.ord);
write_json_string(&row.part, &mut canonical);
canonical.push(']');
let hash = Sha256::digest(canonical.as_bytes());
let mut out = String::with_capacity(32);
for byte in hash.iter().take(16) {
out.push(hex_digit(byte >> 4));
out.push(hex_digit(*byte));
}
(out, value_len)
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn canonical_json_sorts_keys_and_matches_compact_serde_for_strings() {
let value = json!({"b": [1, 2.5, "x\"\\\n\u{1}\u{7f}é"], "a": {"d": null, "c": true}});
assert_eq!(
canonical_json(&value),
"{\"a\":{\"c\":true,\"d\":null},\"b\":[1,2.5,\"x\\\"\\\\\\n\\u0001\u{7f}é\"]}"
);
let text = Value::String("x\"\\\n\u{1}\u{8}\u{c}\t\r\u{1f}\u{7f}é".into());
assert_eq!(canonical_json(&text), serde_json::to_string(&text).unwrap());
assert_eq!(canonical_len(&value), canonical_json(&value).len());
assert_eq!(canonical_len(&text), canonical_json(&text).len());
}
#[test]
fn digest_ignores_key_order_and_sees_value_ord_and_part() {
let a = Row::new("k", json!({"x": 1, "y": 2}));
let b = Row::new("k", serde_json::from_str("{\"y\":2,\"x\":1}").unwrap());
assert_eq!(row_digest(&a), row_digest(&b));
assert_eq!(row_digest(&a).len(), 32);
assert_ne!(row_digest(&a), row_digest(&a.clone().with_ord(1)));
assert_ne!(row_digest(&a), row_digest(&a.clone().with_part("p")));
assert_ne!(
row_digest(&a),
row_digest(&Row::new("k", json!({"x": 1, "y": 3})))
);
assert_eq!(
row_digest(&a),
row_digest(&Row::new("other", a.value.clone()))
);
}
}