本文提供了一种计算文件md5和sha1的方法。
添加依赖
cargo add file-hashing
cargo add md-5
cargo add sha1
添加功能函数
use file_hashing::get_hash_file;
use md5::Md5;
use sha1::{Digest, Sha1};
use std::io::Error;
use std::path::Path;
pub fn md5<P: AsRef<Path>>(path: P) -> Result<String, Error> {
let mut hasher = Md5::new();
get_hash_file(path, &mut hasher)
}
pub fn sha1<P: AsRef<Path>>(path: P) -> Result<String, Error> {
let mut hasher = Sha1::new();
get_hash_file(path, &mut hasher)
}
测试功能
文件 tests/data.txt,内容如下
111
222
333
444
555
单元测试如下
use core_utils::file;
use std::env;
#[test]
fn test_md5() {
let path = env::current_dir().unwrap().join("tests/data.txt");
let actual = file::md5(path).unwrap();
let expect = "0401d7b371d25d5999e456d4cc8366ac".to_string();
assert_eq!(actual, expect);
}
#[test]
fn test_sha1() {
let path = env::current_dir().unwrap().join("tests/data.txt");
let actual = file::sha1(path).unwrap();
let expect = "09b97787f67e6470945da3db502bf12c0012ff5c".to_string();
assert_eq!(actual, expect);
}