Skip to content

Commit 0aed21d

Browse files
committed
optimize file read in Config::verify
`Config::verify` refactored to improve the efficiency and memory usage of file hashing. Signed-off-by: onur-ozkan <[email protected]>
1 parent 7ed044c commit 0aed21d

File tree

1 file changed

+29
-10
lines changed

1 file changed

+29
-10
lines changed

src/bootstrap/download.rs

Lines changed: 29 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -320,25 +320,44 @@ impl Config {
320320
}
321321

322322
/// Returns whether the SHA256 checksum of `path` matches `expected`.
323-
fn verify(&self, path: &Path, expected: &str) -> bool {
323+
pub(crate) fn verify(&self, path: &Path, expected: &str) -> bool {
324324
use sha2::Digest;
325325

326326
self.verbose(&format!("verifying {}", path.display()));
327+
328+
if self.dry_run() {
329+
return false;
330+
}
331+
327332
let mut hasher = sha2::Sha256::new();
328-
// FIXME: this is ok for rustfmt (4.1 MB large at time of writing), but it seems memory-intensive for rustc and larger components.
329-
// Consider using streaming IO instead?
330-
let contents = if self.dry_run() { vec![] } else { t!(fs::read(path)) };
331-
hasher.update(&contents);
332-
let found = hex::encode(hasher.finalize().as_slice());
333-
let verified = found == expected;
334-
if !verified && !self.dry_run() {
333+
334+
let file = t!(File::open(path));
335+
const BUFFER_SIZE: usize = 4096; // read in chunks of 4KB
336+
let mut reader = BufReader::with_capacity(BUFFER_SIZE, file);
337+
338+
loop {
339+
let buffer = t!(reader.fill_buf());
340+
let l = buffer.len();
341+
// break if EOF
342+
if l == 0 {
343+
break;
344+
}
345+
hasher.update(buffer);
346+
reader.consume(l);
347+
}
348+
349+
let checksum = hex::encode(hasher.finalize().as_slice());
350+
let verified = checksum == expected;
351+
352+
if !verified {
335353
println!(
336354
"invalid checksum: \n\
337-
found: {found}\n\
355+
found: {checksum}\n\
338356
expected: {expected}",
339357
);
340358
}
341-
return verified;
359+
360+
verified
342361
}
343362
}
344363

0 commit comments

Comments
 (0)