我试图使用twox-hash为文件生成哈希,因为它似乎是最快的哈希实现,并且安全性不是此实现的问题。
为了让它与读者一起工作,我实现了一个包装器结构,该结构实现了该特征并直接从该特征Write调用。有没有更优雅或更标准的方法来做到这一点?XxHash::writeHash
#[derive(Deref)]
struct HashWriter<T: Hasher>(T);
impl<T: Hasher> std::io::Write for HashWriter<T> {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
self.0.write(buf);
Ok(buf.len())
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
Run Code Online (Sandbox Code Playgroud)
这就是我要做的,尽管我也会实现,write_all因为它同样简单:
use std::{hash::Hasher, io};
struct HashWriter<T: Hasher>(T);
impl<T: Hasher> io::Write for HashWriter<T> {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.0.write(buf);
Ok(buf.len())
}
fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
self.write(buf).map(|_| ())
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}
Run Code Online (Sandbox Code Playgroud)
然后您可以像这样使用它:
use std::fs::File;
use twox_hash::XxHash64;
fn main() {
let mut f = File::open("/etc/hosts").expect("Unable to open file");
let hasher = XxHash64::with_seed(0);
let mut hw = HashWriter(hasher);
io::copy(&mut f, &mut hw).expect("Unable to copy data");
let hasher = hw.0;
println!("{}", hasher.finish());
}
Run Code Online (Sandbox Code Playgroud)
免责声明:我是twox-hash的作者/搬运工。