summaryrefslogtreecommitdiff
path: root/crates/utils/sha1_hash/src/lib.rs
diff options
context:
space:
mode:
author魏曹先生 <1992414357@qq.com>2025-11-22 19:38:55 +0800
committer魏曹先生 <1992414357@qq.com>2025-11-22 19:38:55 +0800
commit2d4c1ccc042fff22313799e6b68908c0eda1f73d (patch)
tree40f47792ec6f77730769104b35e0c00f9abf3b48 /crates/utils/sha1_hash/src/lib.rs
parent7654b0e7d264b17c33e58611ab4a1a86cece6b16 (diff)
Add SHA1 string hashing function
Diffstat (limited to 'crates/utils/sha1_hash/src/lib.rs')
-rw-r--r--crates/utils/sha1_hash/src/lib.rs37
1 files changed, 37 insertions, 0 deletions
diff --git a/crates/utils/sha1_hash/src/lib.rs b/crates/utils/sha1_hash/src/lib.rs
index 4373d50..9963cbe 100644
--- a/crates/utils/sha1_hash/src/lib.rs
+++ b/crates/utils/sha1_hash/src/lib.rs
@@ -11,6 +11,18 @@ pub struct Sha1Result {
pub hash: String,
}
+/// Calc SHA1 hash of a string
+pub fn calc_sha1_string<S: AsRef<str>>(input: S) -> String {
+ let mut hasher = Sha1::new();
+ hasher.update(input.as_ref().as_bytes());
+ let hash_result = hasher.finalize();
+
+ hash_result
+ .iter()
+ .map(|b| format!("{:02x}", b))
+ .collect::<String>()
+}
+
/// Calc SHA1 hash of a single file
pub async fn calc_sha1<P: AsRef<Path>>(
path: P,
@@ -103,6 +115,31 @@ mod tests {
use super::*;
use std::fs;
+ #[test]
+ fn test_sha1_string() {
+ let test_string = "Hello, SHA1!";
+ let hash = calc_sha1_string(test_string);
+
+ let expected_hash = "de1c3daadc6f0f1626f4cf56c03e05a1e5d7b187";
+
+ assert_eq!(
+ hash, expected_hash,
+ "SHA1 hash should be consistent for same input"
+ );
+ }
+
+ #[test]
+ fn test_sha1_string_empty() {
+ let hash = calc_sha1_string("");
+
+ // SHA1 of empty string is "da39a3ee5e6b4b0d3255bfef95601890afd80709"
+ let expected_empty_hash = "da39a3ee5e6b4b0d3255bfef95601890afd80709";
+ assert_eq!(
+ hash, expected_empty_hash,
+ "SHA1 hash mismatch for empty string"
+ );
+ }
+
#[tokio::test]
async fn test_sha1_accuracy() {
// Test file path relative to the crate root