Skip to main content

xtask_kit/
hash.rs

1use std::fmt::Write as _;
2use std::fs;
3use std::io::Read;
4use std::path::Path;
5
6use anyhow::{Context, Result};
7use sha2::{Digest, Sha256};
8
9/// Return the lowercase hexadecimal SHA-256 digest for `path`.
10pub fn sha256_file(path: impl AsRef<Path>) -> Result<String> {
11    let path = path.as_ref();
12    let mut file = fs::File::open(path).with_context(|| format!("open {}", path.display()))?;
13    let mut hasher = Sha256::new();
14    let mut buffer = [0; 64 * 1024];
15    loop {
16        let read = file
17            .read(&mut buffer)
18            .with_context(|| format!("read {}", path.display()))?;
19        if read == 0 {
20            break;
21        }
22        hasher.update(&buffer[..read]);
23    }
24
25    let mut digest = String::with_capacity(64);
26    for byte in hasher.finalize() {
27        write!(&mut digest, "{byte:02x}")?;
28    }
29    Ok(digest)
30}
31
32/// Format a byte count for compact release logs.
33pub fn human_size(bytes: u64) -> String {
34    const UNITS: &[&str] = &["B", "K", "M", "G", "T"];
35    let mut size = bytes as f64;
36    let mut unit = 0;
37    while size >= 1024.0 && unit + 1 < UNITS.len() {
38        size /= 1024.0;
39        unit += 1;
40    }
41    if unit == 0 {
42        format!("{bytes}B")
43    } else {
44        format!("{size:.1}{}", UNITS[unit])
45    }
46}
47
48/// Write a `*.sha256` sidecar next to `path` and return the sidecar path.
49pub fn write_sha256_sidecar(path: impl AsRef<Path>) -> Result<std::path::PathBuf> {
50    let path = path.as_ref();
51    let digest = sha256_file(path)?;
52    let file_name = path
53        .file_name()
54        .and_then(|name| name.to_str())
55        .with_context(|| format!("path has no UTF-8 filename: {}", path.display()))?;
56    let sidecar = std::path::PathBuf::from(format!("{}.sha256", path.display()));
57    crate::fs::write_string(&sidecar, format!("{digest}  {file_name}\n"))?;
58    Ok(sidecar)
59}