use super::Context;
use sha2::Digest;
#[derive(Default)]
pub struct Sha512 {
sha512: sha2::Sha512,
}
impl Sha512 {
pub fn new() -> Self {
Self::default()
}
pub fn new_with_context(context: &dyn Context) -> Self {
let mut hash = Self::new();
hash.write(context.as_bytes());
hash
}
pub fn hash(data: &[u8]) -> [u8; 64] {
let mut hash = Self::new();
hash.write(data);
hash.finish()
}
pub fn write(&mut self, data: &[u8]) {
self.sha512.update(data);
}
pub fn finish(self) -> [u8; 64] {
let hash = self.sha512.finalize();
hash.as_slice()
.try_into()
.expect("infallible as length is 64")
}
}
impl std::io::Write for Sha512 {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
self.write(buf);
Ok(buf.len())
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
impl std::hash::Hasher for Sha512 {
fn finish(&self) -> u64 {
panic!(
"not supported because the hash values produced by this hasher \
contain more than just the 64 bits returned by this method"
)
}
fn write(&mut self, bytes: &[u8]) {
self.write(bytes)
}
}