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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
use crate::error::Error;
use core::fmt::Debug;
use generic_array::typenum::marker_traits::Unsigned;
use generic_array::{ArrayLength, GenericArray};
pub trait Size:
ArrayLength<u8> + Debug + Default + Eq + core::hash::Hash + Send + Sync + 'static
{
}
impl<T: ArrayLength<u8> + Debug + Default + Eq + core::hash::Hash + Send + Sync + 'static> Size
for T
{
}
pub trait Digest<S: Size>:
AsRef<[u8]>
+ AsMut<[u8]>
+ From<GenericArray<u8, S>>
+ Into<GenericArray<u8, S>>
+ Clone
+ core::hash::Hash
+ Debug
+ Default
+ Eq
+ Send
+ Sync
+ 'static
{
fn size(&self) -> u8 {
S::to_u8()
}
fn wrap(digest: &[u8]) -> Result<Self, Error> {
if digest.len() != S::to_usize() {
return Err(Error::InvalidSize(digest.len() as _));
}
let mut array = GenericArray::default();
let len = digest.len().min(array.len());
array[..len].copy_from_slice(&digest[..len]);
Ok(array.into())
}
#[cfg(feature = "std")]
fn from_reader<R>(mut r: R) -> Result<Self, Error>
where
R: std::io::Read,
{
use unsigned_varint::io::read_u64;
let size = read_u64(&mut r)?;
if size > S::to_u64() || size > u8::max_value() as u64 {
return Err(Error::InvalidSize(size));
}
let mut digest = GenericArray::default();
r.read_exact(&mut digest[..size as usize])?;
Ok(Self::from(digest))
}
}
pub trait StatefulHasher: Default + Send + Sync {
type Size: Size;
type Digest: Digest<Self::Size>;
fn update(&mut self, input: &[u8]);
fn finalize(&self) -> Self::Digest;
fn reset(&mut self);
}
pub trait Hasher: Default + Send + Sync {
type Size: Size;
type Digest: Digest<Self::Size>;
fn size() -> u8 {
Self::Size::to_u8()
}
fn digest(input: &[u8]) -> Self::Digest
where
Self: Sized;
}
impl<T: StatefulHasher> Hasher for T {
type Size = T::Size;
type Digest = T::Digest;
fn digest(input: &[u8]) -> Self::Digest {
let mut hasher = Self::default();
hasher.update(input);
hasher.finalize()
}
}
#[cfg(feature = "std")]
pub struct WriteHasher<H: Hasher>(H);
#[cfg(feature = "std")]
impl<H: StatefulHasher> std::io::Write for WriteHasher<H> {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
self.0.update(buf);
Ok(buf.len())
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}