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
45
46
47
#![warn(missing_docs)]
extern crate digest;
use std::io::{Result as IoResult, Write};
use digest::{FixedOutput, Input};
use digest::generic_array::GenericArray;
pub struct HashWriter<H: Input + FixedOutput, W: Write> {
hash: H,
writer: W,
}
impl<H: Input + FixedOutput, W: Write> HashWriter<H, W> {
pub fn new(hash: H, writer: W) -> HashWriter<H, W> {
HashWriter { hash, writer }
}
pub fn from_writer(writer: W) -> HashWriter<H, W>
where
H: Default,
{
let hash = H::default();
HashWriter::new(hash, writer)
}
pub fn digest(self) -> GenericArray<u8, H::OutputSize> {
self.hash.fixed_result()
}
}
impl<H: Input + FixedOutput, W: Write> Write for HashWriter<H, W> {
fn write(&mut self, buf: &[u8]) -> IoResult<usize> {
self.hash.process(buf);
self.writer.write(buf)
}
fn flush(&mut self) -> IoResult<()> {
self.writer.flush()
}
}