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
use crate::{backend, Block, Key};
use universal_hash::{consts::U16, NewUniversalHash, Output, UniversalHash};
cpuid_bool::new!(clmul_cpuid, "pclmulqdq", "sse4.1");
pub struct Polyval {
inner: Inner,
token: clmul_cpuid::InitToken,
}
union Inner {
clmul: backend::clmul::Polyval,
soft: backend::soft::Polyval,
}
impl NewUniversalHash for Polyval {
type KeySize = U16;
fn new(h: &Key) -> Self {
let (token, clmul_present) = clmul_cpuid::init_get();
let inner = if clmul_present {
Inner {
clmul: backend::clmul::Polyval::new(h),
}
} else {
Inner {
soft: backend::soft::Polyval::new(h),
}
};
Self { inner, token }
}
}
impl UniversalHash for Polyval {
type BlockSize = U16;
#[inline]
fn update(&mut self, x: &Block) {
if self.token.get() {
unsafe { self.inner.clmul.update(x) }
} else {
unsafe { self.inner.soft.update(x) }
}
}
fn reset(&mut self) {
if self.token.get() {
unsafe { self.inner.clmul.reset() }
} else {
unsafe { self.inner.soft.reset() }
}
}
fn finalize(self) -> Output<Self> {
let output_bytes = if self.token.get() {
unsafe { self.inner.clmul.finalize().into_bytes() }
} else {
unsafe { self.inner.soft.finalize().into_bytes() }
};
Output::new(output_bytes)
}
}
impl Clone for Polyval {
fn clone(&self) -> Self {
let inner = if self.token.get() {
Inner {
clmul: unsafe { self.inner.clmul.clone() },
}
} else {
Inner {
soft: unsafe { self.inner.soft.clone() },
}
};
Self {
inner,
token: self.token,
}
}
}
#[cfg(feature = "zeroize")]
impl Drop for Polyval {
fn drop(&mut self) {
use zeroize::Zeroize;
const SIZE: usize = core::mem::size_of::<Polyval>();
let state = unsafe { &mut *(self as *mut Polyval as *mut [u8; SIZE]) };
state.zeroize();
}
}