Skip to main content

lighty_core/
hash.rs

1// Copyright (c) 2025 Hamadi
2// Licensed under the MIT License
3
4//! SHA1 file hashing utilities (sync and async).
5
6use std::path::Path;
7use sha1::{Sha1, Digest};
8use std::io::{self, Read};
9use tokio::fs;
10use tokio::task;
11use thiserror::Error;
12
13/// Errors raised by the hashing helpers.
14#[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
25/// Verifies the SHA1 hash of a file (async, reads whole file into memory).
26pub 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
36/// Verifies the SHA1 hash of a file (async, streaming for large files).
37pub async fn verify_file_sha1_streaming(path: &Path, expected_sha1: &str) -> HashResult<bool> {
38    // Hashed on the blocking pool: a read buffer held across `.await` would sit in every
39    // caller's future, and the installer joins nine of them (stack overflow on Windows).
40    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
47/// Calculates the SHA1 hash of a file (sync, blocking I/O — for non-async contexts).
48pub 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
64/// Verifies the SHA1 hash of a file (sync).
65pub 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
70/// Calculates the SHA1 hash of arbitrary bytes as a lowercase hex string.
71pub fn calculate_sha1_bytes(data: &[u8]) -> String {
72    let mut hasher = Sha1::new();
73    hasher.update(data);
74    hex::encode(hasher.finalize())
75}
76
77/// Calculates the SHA1 hash of arbitrary bytes as raw 20-byte output.
78pub fn calculate_sha1_bytes_raw(data: &[u8]) -> [u8; 20] {
79    let mut hasher = Sha1::new();
80    hasher.update(data);
81    hasher.finalize().into()
82}