io_adapters/adapters/hasher.rs
1use std::{hash::Hasher, io};
2
3use crate::WriteExtension;
4
5/// Adapter that enables writing through an [`io::Write`]r to an underlying
6/// [`Hasher`].
7///
8/// # Examples
9///
10/// ```rust
11/// # use std::{hash::{DefaultHasher, Hasher}, io, io::Read};
12/// use io_adapters::WriteExtension;
13///
14/// let mut hasher = DefaultHasher::new();
15///
16/// io::copy(
17/// &mut io::repeat(42).take(10),
18/// &mut (&mut hasher).write_adapter(),
19/// )
20/// .unwrap();
21///
22/// assert_eq!(hasher.finish(), 2882615036743451676);
23/// ```
24#[derive(Copy, Clone, Debug)]
25pub struct IoToHasher<H>(H);
26
27impl<H: Hasher> io::Write for IoToHasher<H> {
28 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
29 self.0.write(buf);
30 Ok(buf.len())
31 }
32
33 fn flush(&mut self) -> io::Result<()> {
34 Ok(())
35 }
36}
37
38impl<H: Hasher> WriteExtension<IoToHasher<H>> for H {
39 type Adapter = IoToHasher<H>;
40
41 fn write_adapter(self) -> IoToHasher<H> {
42 IoToHasher(self)
43 }
44}