rusty_files/utils/
hash.rs

1use sha2::{Digest, Sha256};
2use std::fs::File;
3use std::io::{BufReader, Read};
4use std::path::Path;
5
6pub fn hash_file<P: AsRef<Path>>(path: P) -> std::io::Result<String> {
7    let file = File::open(path)?;
8    let mut reader = BufReader::with_capacity(65536, file);
9    let mut hasher = Sha256::new();
10    let mut buffer = [0u8; 65536];
11
12    loop {
13        let count = reader.read(&mut buffer)?;
14        if count == 0 {
15            break;
16        }
17        hasher.update(&buffer[..count]);
18    }
19
20    Ok(format!("{:x}", hasher.finalize()))
21}
22
23pub fn hash_bytes(data: &[u8]) -> String {
24    let mut hasher = Sha256::new();
25    hasher.update(data);
26    format!("{:x}", hasher.finalize())
27}
28
29pub fn hash_string(text: &str) -> String {
30    hash_bytes(text.as_bytes())
31}
32
33#[cfg(test)]
34mod tests {
35    use super::*;
36
37    #[test]
38    fn test_hash_bytes() {
39        let data = b"Hello, world!";
40        let hash = hash_bytes(data);
41        assert_eq!(hash.len(), 64);
42    }
43
44    #[test]
45    fn test_hash_string() {
46        let text = "Hello, world!";
47        let hash = hash_string(text);
48        assert_eq!(hash.len(), 64);
49    }
50
51    #[test]
52    fn test_hash_consistency() {
53        let data = b"test data";
54        let hash1 = hash_bytes(data);
55        let hash2 = hash_bytes(data);
56        assert_eq!(hash1, hash2);
57    }
58}