Skip to content

Commit 82b0669

Browse files
committed
Improving the hasher.rs implementation, and dependencies
1 parent 46c224a commit 82b0669

File tree

2 files changed

+19
-27
lines changed

2 files changed

+19
-27
lines changed

Cargo.lock

Lines changed: 8 additions & 8 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

src/hasher.rs

Lines changed: 11 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -17,31 +17,25 @@ fn hash_file<D: Digest>(filename: impl AsRef<str>) -> anyhow::Result<Output<D>>
1717
let filesize = usize::try_from(file_size(filename.as_ref())?).ok();
1818

1919
if filesize.is_some_and(|size| size <= BUFFER_SIZE) {
20-
// this file is smaller than the buffer size, so we can hash it all at once
20+
// Small file optimization - hash it all at once
2121
return hash_file_whole::<D>(filename);
2222
}
2323

24-
// read the file in chunks
24+
// For larger files, read in chunks
2525
let file = File::open(filename.as_ref())?;
2626
let mut reader = BufReader::new(file);
2727
let mut buffer = build_heap_buffer(BUFFER_SIZE);
28-
2928
let mut hasher = D::new();
30-
loop {
31-
let bytes_read = reader.read(&mut buffer)?;
29+
30+
// More efficient reading pattern
31+
while let Ok(bytes_read) = reader.read(&mut buffer) {
3232
if bytes_read == 0 {
33-
break; // nothing more to read
33+
break;
3434
}
3535
hasher.update(&buffer[..bytes_read]);
36-
if bytes_read < BUFFER_SIZE {
37-
break; // we've reached the end of the file
38-
}
3936
}
4037

41-
// Output<T> = GenericArray<u8, <T as OutputSizeUser>::OutputSize>
42-
// just return this directly to avoid an extra allocation
43-
let hash_array = hasher.finalize();
44-
Ok(hash_array)
38+
Ok(hasher.finalize())
4539
}
4640

4741
/// Hash the entire file at once
@@ -50,8 +44,7 @@ fn hash_file_whole<D: Digest>(filename: impl AsRef<str>) -> anyhow::Result<Outpu
5044
let mut hasher = D::new();
5145
hasher.update(&data);
5246

53-
let hash_array = hasher.finalize();
54-
Ok(hash_array)
47+
Ok(hasher.finalize())
5548
}
5649

5750
/// Hash a file using the given hasher as a Digest implementation, and encode the output
@@ -62,7 +55,8 @@ pub fn hash_file_encoded<D: Digest>(
6255
) -> anyhow::Result<BasicHash> {
6356
let h = hash_file::<D>(filename)?;
6457

65-
let encoded = match encoding {
58+
// Convert hash directly to BasicHash without separate variable
59+
Ok(BasicHash(match encoding {
6660
OutputEncoding::Hex | OutputEncoding::Unspecified => hex::encode(h),
6761
OutputEncoding::Base64 => BASE64.encode(&h),
6862
OutputEncoding::Base32 => BASE32.encode(&h),
@@ -73,9 +67,7 @@ pub fn hash_file_encoded<D: Digest>(
7367
let number = BigEndian::read_u32(&h);
7468
format!("{number:010}")
7569
}
76-
};
77-
78-
Ok(BasicHash(encoded))
70+
}))
7971
}
8072

8173
/// check if file exists

0 commit comments

Comments
 (0)