Skip to main content

pacenotes_server/store/
file_hash.rs

1/// Lowercase hex sha256 of a file's contents, streamed rather than read whole.
2pub fn sha256_file(path: &std::path::Path) -> anyhow::Result<String> {
3    let mut file =
4        std::fs::File::open(path).map_err(|e| anyhow::anyhow!("open {}: {e}", path.display()))?;
5    let mut hasher = <sha2::Sha256 as sha2::Digest>::new();
6    std::io::copy(&mut file, &mut hasher)
7        .map_err(|e| anyhow::anyhow!("hash {}: {e}", path.display()))?;
8    Ok(hex(&sha2::Digest::finalize(hasher)))
9}
10
11/// Lowercase hex sha256 of bytes already in memory.
12pub fn sha256_bytes(bytes: &[u8]) -> String {
13    hex(&<sha2::Sha256 as sha2::Digest>::digest(bytes))
14}
15
16fn hex(digest: &[u8]) -> String {
17    digest.iter().map(|byte| format!("{byte:02x}")).collect()
18}