use std::collections::BTreeMap;
use std::fmt::Write as _;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use sha2::{Digest as _, Sha256};
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct FileEntry {
pub name: String,
pub sha256: String,
pub rows: usize,
#[serde(default)]
pub dropped: Vec<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Manifest {
pub files: Vec<FileEntry>,
pub created_at: String,
pub tool_version: String,
pub meta: BTreeMap<String, String>,
#[serde(default)]
pub dropped: BTreeMap<String, Vec<String>>,
}
impl PartialEq for Manifest {
fn eq(&self, other: &Self) -> bool {
self.files == other.files
&& self.tool_version == other.tool_version
&& self.meta == other.meta
&& self.dropped == other.dropped
}
}
impl Eq for Manifest {}
impl Manifest {
pub fn to_json(&self) -> Result<String, serde_json::Error> {
Ok(canonical_json(&serde_json::to_value(self)?))
}
pub fn from_json(text: &str) -> Result<Self, serde_json::Error> {
serde_json::from_str(text)
}
}
pub(crate) fn sha256_hex(bytes: &[u8]) -> String {
Sha256::digest(bytes)
.iter()
.fold(String::new(), |mut hex, byte| {
let _ = write!(hex, "{byte:02x}");
hex
})
}
pub(crate) fn canonical_json(value: &Value) -> String {
let mut out = String::new();
write_value(&mut out, value);
out
}
fn write_value(out: &mut String, value: &Value) {
match value {
Value::Null => out.push_str("null"),
Value::Bool(yes) => out.push_str(if *yes { "true" } else { "false" }),
Value::Number(number) => out.push_str(&number.to_string()),
Value::String(text) => write_string(out, text),
Value::Array(items) => {
out.push('[');
for (position, item) in items.iter().enumerate() {
if position > 0 {
out.push(',');
}
write_value(out, item);
}
out.push(']');
}
Value::Object(members) => {
let sorted: BTreeMap<&str, &Value> = members
.iter()
.map(|(key, value)| (key.as_str(), value))
.collect();
out.push('{');
for (position, (key, value)) in sorted.into_iter().enumerate() {
if position > 0 {
out.push(',');
}
write_string(out, key);
out.push(':');
write_value(out, value);
}
out.push('}');
}
}
}
fn write_string(out: &mut String, text: &str) {
out.push_str(&Value::String(text.to_owned()).to_string());
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn sha256_of_abc_is_the_published_vector() {
assert_eq!(
sha256_hex(b"abc"),
"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
);
}
#[test]
fn sha256_of_nothing_is_the_published_empty_vector() {
assert_eq!(
sha256_hex(b""),
"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
);
}
#[test]
fn keys_are_sorted_at_every_depth_and_nothing_is_spaced() {
let document: Value =
serde_json::from_str(r#"{"b": {"z": 1, "a": 2}, "a": [3, 4]}"#).unwrap();
assert_eq!(
canonical_json(&document),
r#"{"a":[3,4],"b":{"a":2,"z":1}}"#
);
}
#[test]
fn strings_keep_the_escaping_json_requires() {
let document: Value = serde_json::from_str(r#"{"note": "a \"quoted\" line\n"}"#).unwrap();
assert_eq!(
canonical_json(&document),
r#"{"note":"a \"quoted\" line\n"}"#
);
}
#[test]
fn array_order_is_content_and_is_not_sorted() {
let one: Value = serde_json::from_str("[1, 2]").unwrap();
let other: Value = serde_json::from_str("[2, 1]").unwrap();
assert_ne!(canonical_json(&one), canonical_json(&other));
}
#[test]
fn a_manifest_is_written_canonical_with_keys_sorted() {
let manifest = Manifest {
files: vec![FileEntry {
name: "id.csv".to_owned(),
sha256: sha256_hex(b"abc"),
rows: 1,
dropped: vec!["email".to_owned()],
}],
created_at: "2026-01-01T00:00:00Z".to_owned(),
tool_version: "0.1.0".to_owned(),
meta: BTreeMap::from([("window".to_owned(), "24h".to_owned())]),
dropped: BTreeMap::from([("id.csv".to_owned(), vec!["email".to_owned()])]),
};
let text = manifest.to_json().unwrap();
assert_eq!(
text,
concat!(
r#"{"created_at":"2026-01-01T00:00:00Z","#,
r#""dropped":{"id.csv":["email"]},"#,
r#""files":[{"dropped":["email"],"name":"id.csv","rows":1,"sha256":"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"}],"#,
r#""meta":{"window":"24h"},"#,
r#""tool_version":"0.1.0"}"#,
)
);
}
}