blob: 93627f1bcd9f6ee8abb4584e1062b5ac2f1d7caf (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
|
use sha2::{Digest, Sha256};
use std::fs::File;
use std::io::{BufReader, Read};
use std::path::{Path, PathBuf};
const BUF_SIZE: usize = 4096;
#[derive(Debug)]
pub struct FileChecksum {
pub filename: PathBuf,
pub checksum: String,
}
impl FileChecksum {
pub fn new(filename: &Path, checksum: String) -> Self {
Self {
filename: filename.to_path_buf(),
checksum,
}
}
pub fn print(&self) {
println!("{} {}", self.checksum, self.filename.display());
}
}
pub fn checksum(filename: &Path) -> Result<FileChecksum, std::io::Error> {
let mut checksum = Sha256::new();
let file = File::open(filename)?;
let mut reader = BufReader::new(file);
loop {
let mut buf = vec![0; BUF_SIZE];
let n = reader.read(&mut buf)?;
if n == 0 {
break;
}
checksum.update(&buf[..n]);
}
let checksum = checksum.finalize();
let checksum = format!("{checksum:x}");
Ok(FileChecksum::new(filename, checksum))
}
|