1use std::path::Path;
7use sha1::{Sha1, Digest};
8use std::io::{self, Read};
9use tokio::fs;
10use tokio::task;
11use thiserror::Error;
12
13#[derive(Debug, Error)]
15pub enum HashError {
16 #[error("IO error: {0}")]
17 Io(#[from] std::io::Error),
18
19 #[error("SHA1 mismatch: expected {expected}, got {actual}")]
20 Mismatch { expected: String, actual: String },
21}
22
23pub type HashResult<T> = Result<T, HashError>;
24
25pub async fn verify_file_sha1(path: &Path, expected_sha1: &str) -> HashResult<bool> {
27 let content = fs::read(path).await?;
28
29 let mut hasher = Sha1::new();
30 hasher.update(&content);
31 let calculated_sha1 = hex::encode(hasher.finalize());
32
33 Ok(calculated_sha1.eq_ignore_ascii_case(expected_sha1))
34}
35
36pub async fn verify_file_sha1_streaming(path: &Path, expected_sha1: &str) -> HashResult<bool> {
38 let path = path.to_path_buf();
41 let expected_sha1 = expected_sha1.to_owned();
42 task::spawn_blocking(move || verify_file_sha1_sync(&path, &expected_sha1))
43 .await
44 .map_err(|error| HashError::Io(io::Error::other(error)))?
45}
46
47pub fn calculate_file_sha1_sync(path: &Path) -> HashResult<String> {
49 let mut file = std::fs::File::open(path)?;
50 let mut hasher = Sha1::new();
51 let mut buffer = [0u8; 8192];
52
53 loop {
54 let n = file.read(&mut buffer)?;
55 if n == 0 {
56 break;
57 }
58 hasher.update(&buffer[..n]);
59 }
60
61 Ok(hex::encode(hasher.finalize()))
62}
63
64pub fn verify_file_sha1_sync(path: &Path, expected_sha1: &str) -> HashResult<bool> {
66 let calculated_sha1 = calculate_file_sha1_sync(path)?;
67 Ok(calculated_sha1.eq_ignore_ascii_case(expected_sha1))
68}
69
70pub fn calculate_sha1_bytes(data: &[u8]) -> String {
72 let mut hasher = Sha1::new();
73 hasher.update(data);
74 hex::encode(hasher.finalize())
75}
76
77pub fn calculate_sha1_bytes_raw(data: &[u8]) -> [u8; 20] {
79 let mut hasher = Sha1::new();
80 hasher.update(data);
81 hasher.finalize().into()
82}