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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
use std::io::{Read, Write};
use md5::Context;
use super::MD5Sum;
pub struct IOSum<I> {
inner: I,
context: Context,
bytes: usize,
}
impl<I> IOSum<I> {
pub fn get_mut(&mut self) -> &mut I {
&mut self.inner
}
pub fn into_inner(self) -> (I, MD5Sum) {
(self.inner, MD5Sum(self.context.compute().0))
}
pub fn new(inner: I) -> Self {
Self {
inner,
context: Context::new(),
bytes: 0,
}
}
pub fn digest(&self) -> MD5Sum {
MD5Sum(self.context.clone().compute().0)
}
pub fn byte_count(&self) -> usize {
self.bytes
}
}
impl<R: Read> Read for IOSum<R> {
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
let len = self.inner.read(buf)?;
self.context.consume(&buf[..len]);
self.bytes += len;
Ok(len)
}
}
impl<I: Write> Write for IOSum<I> {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
let len = self.inner.write(buf)?;
self.context.consume(&buf[..len]);
self.bytes += len;
Ok(len)
}
fn flush(&mut self) -> std::io::Result<()> {
self.inner.flush()
}
}