-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhash.rs
76 lines (66 loc) · 1.35 KB
/
hash.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
75
76
use {
sha1::{Digest, Sha1},
std::{
fmt,
fmt::{Display, Formatter},
io,
io::Write,
},
};
#[derive(Clone, Copy, Debug)]
pub enum Hash {
Sha1([u8; 20]),
}
impl Hash {
pub fn as_bytes(&self) -> &[u8] {
match self {
Hash::Sha1(bytes) => bytes,
}
}
}
impl Display for Hash {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
match self {
Self::Sha1(bytes) => {
for byte in bytes.iter() {
write!(f, "{:02x}", byte)?;
}
Ok(())
}
}
}
}
#[derive(Debug)]
pub enum Hasher {
Sha1(Sha1),
}
impl Hasher {
pub fn new(kind: Kind) -> Self {
match kind {
Kind::Sha1 => Hasher::Sha1(Sha1::new()),
}
}
pub fn update(&mut self, data: &[u8]) {
match self {
Hasher::Sha1(hasher) => hasher.update(data),
}
}
pub fn finalize(self) -> Hash {
match self {
Hasher::Sha1(hasher) => Hash::Sha1(hasher.finalize().into()),
}
}
}
impl Write for Hasher {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.update(buf);
Ok(buf.len())
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}
#[derive(Clone, Copy, Debug)]
pub enum Kind {
Sha1,
}