use sha2::{Digest, Sha256}; use std::io::{self, Read, Write}; pub fn hex(bytes: &[u8]) -> String { let mut h = Sha256::new(); h.update(bytes); hex::encode(h.finalize()) } pub fn hex_str(s: &str) -> String { hex(s.as_bytes()) } pub fn short(bytes: &[u8], n: usize) -> String { let h = hex(bytes); h[..n.min(h.len())].to_string() } pub fn digest_reader(mut r: R, mut sink: Option<&mut dyn Write>) -> io::Result<(String, u64)> { let mut h = Sha256::new(); let mut buf = vec![0u8; 64 * 1024]; let mut total = 0u64; loop { let n = r.read(&mut buf)?; if n == 0 { break; } h.update(&buf[..n]); if let Some(s) = sink.as_mut() { s.write_all(&buf[..n])?; } total += n as u64; } Ok((hex::encode(h.finalize()), total)) } pub fn digest_file(path: &std::path::Path) -> io::Result<(String, u64)> { let f = std::fs::File::open(path)?; let mut br = io::BufReader::new(f); digest_reader(&mut br, None) } pub fn recipe_hash(entries: &[(String, String)]) -> String { let mut sorted: Vec<&(String, String)> = entries.iter().collect(); sorted.sort_unstable_by(|a, b| a.0.cmp(&b.0)); let mut h = Sha256::new(); for (path, blob) in &sorted { h.update(path.as_bytes()); h.update([0u8]); h.update(blob.as_bytes()); h.update([0u8]); } hex::encode(h.finalize()) } pub fn canonical_json(v: &T) -> Result { serde_json::to_string(&serde_json::to_value(v)?) }