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
use byteorder::{LittleEndian, WriteBytesExt};
use std::hash::Hasher;
use std::io::{self, Write};

use ByteHash;

/// Wrapping any `Hasher` in ByteHash
#[derive(Default)]
pub struct Wrapped<H> {
    buf: [u8; 8],
    state: H,
}

impl<H: Hasher> Write for Wrapped<H> {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        self.state.write(buf);
        Ok(buf.len())
    }

    fn flush(&mut self) -> io::Result<()> {
        Ok(())
    }
}

impl<H> ByteHash for Wrapped<H>
where
    H: Hasher,
{
    type Digest = [u8; 8];

    fn fin(self) -> Self::Digest {
        let Wrapped { state, mut buf } = self;
        buf.as_mut()
            .write_u64::<LittleEndian>(state.finish())
            .expect("in-memory write");
        buf
    }
}