Skip to main content

conduit_cli/core/io/
hash.rs

1use crate::core::error::CoreResult;
2use sha2::Digest;
3use std::fmt::Write;
4use std::fs::File;
5use std::io::{BufReader, Read};
6use std::path::Path;
7
8fn hash_file<D: Digest, P: AsRef<Path>>(path: P) -> CoreResult<String> {
9    let file = File::open(path)?;
10    let mut reader = BufReader::new(file);
11    let mut hasher = D::new();
12    let mut buf = [0u8; 8192];
13    
14    loop {
15        let n = reader.read(&mut buf)?;
16        if n == 0 {
17            break;
18        }
19        hasher.update(&buf[..n]);
20    }
21
22    let result = hasher.finalize();
23
24    let mut hash_string = String::with_capacity(result.len() * 2);
25    
26    for b in result {
27        let _ = write!(hash_string, "{b:02x}");
28    }
29
30    Ok(hash_string)
31}
32
33pub fn sha256_file<P: AsRef<Path>>(path: P) -> CoreResult<String> {
34    hash_file::<sha2::Sha256, _>(path)
35}
36
37pub fn sha1_file<P: AsRef<Path>>(path: P) -> CoreResult<String> {
38    hash_file::<sha1::Sha1, _>(path)
39}