fn file_digest(digest_alg: &'static digest::Algorithm, file_path: &std::path::Path) -> Result<Digest, std::string::String> {
std::fs::File::open(file_path).map_err(|why| {
format!("couldn't open {}: {}", file_path.display(), why.description())
}).and_then(|mut file| {
let mut ctx = digest::Context::new(digest_alg);
let mut chunk = vec![0u8; 128 * 1024];
loop {
match file.read(&mut chunk[..]) {
Ok(0) => break,
Ok(bytes_read) => ctx.update(&chunk[0..bytes_read]),
Err(why) => {
return Err(format!("couldn't read {}: {}", file_path.display(), why.description()));
},
}
}
Ok(x.finish())
})
}
return
inside the closure
fn file_digest(digest_alg: &'static digest::Algorithm, file_path: &std::path::Path) -> Result<Digest, std::string::String> {
let mut file = try!(File::open(file_path).map_err(|why| format!("couldn't open {}: {}", file_path.display(), why.description()));
let mut ctx = digest::Context::new(digest_alg);
let mut chunk = vec![0u8; 128 * 1024];
loop {
let bytes_read = try!(file.read(&mut chunk[..]).map_err(|why| format!("couldn't read {}: {}", file_path.display(), why.description())));
if bytes_read > 0 {
ctx.update(&chunk[0..bytes_read]);
} else {
break;
}
}
Ok(ctx.finish())
}
std::path::Path
and std::io::File
with use
's
String
error is very idiomatic
Actually if what you want is a buffered reader:
use std::path::Path;
use std::io;
// do you really need this lifetime to be 'static ??
fn file_digest(digest_alg: &'static digest::Algorithm, file_path: &Path) -> io::Result<Digest> {
let mut file = try!(io::File::open(file_path));
let mut reader = BufReader::with_capacity(capacity, file);
let mut ctx = digest::Context::new(digest_alg);
for byte in reader.bytes() {
ctx.update(try!(byte));
}
Ok(ctx.finish())
}
Also, your digest
stuff could directly take an Iterator
over bytes ?
use std::path::Path;
use std::io;
fn file_digest(digest_alg: &digest::Algorithm, file_path: &Path) -> io::Result<Digest> {
let mut file = try!(io::File::open(file_path));
let mut reader = io::BufReader::with_capacity(capacity, file);
try!(bytes_digest(digest_alg, reader.bytes()))
}