-
Notifications
You must be signed in to change notification settings - Fork 26
/
util.rs
74 lines (65 loc) · 1.45 KB
/
util.rs
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
use std::{hash, io};
// A Write computing a digest on the bytes written.
pub struct HasherWrite<'a, W, H>
where
W: 'a + io::Write,
H: 'a + hash::Hasher,
{
write: &'a mut W, // underlying writer
hasher: &'a mut H, // hasher
}
impl<'a, W, H> HasherWrite<'a, W, H>
where
W: io::Write,
H: hash::Hasher,
{
pub fn new(write: &'a mut W, hasher: &'a mut H) -> Self {
Self { write, hasher }
}
}
impl<'a, W, H> io::Write for HasherWrite<'a, W, H>
where
W: io::Write,
H: hash::Hasher,
{
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
let result = self.write.write(buf)?;
self.hasher.write(&buf[..result]);
Ok(result)
}
fn flush(&mut self) -> io::Result<()> {
self.write.flush()
}
}
// A Write counting the bytes written.
pub struct CountWrite<'a, W>
where
W: 'a + io::Write,
{
write: &'a mut W, // underlying writer
count: usize, // number of bytes written
}
impl<'a, W> CountWrite<'a, W>
where
W: io::Write,
{
pub fn new(write: &'a mut W) -> Self {
Self { write, count: 0 }
}
pub fn count(&self) -> usize {
self.count
}
}
impl<'a, W> io::Write for CountWrite<'a, W>
where
W: io::Write,
{
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
let result = self.write.write(buf)?;
self.count += result;
Ok(result)
}
fn flush(&mut self) -> io::Result<()> {
self.write.flush()
}
}