Skip to main content

osom_lib_hashes/
traits.rs

1//! Defines hash function traits.
2
3use core::mem::MaybeUninit;
4
5use osom_lib_reprc::traits::ReprC;
6
7/// Represents a general hash function. Unlike [`core::hash::Hasher`]
8/// trait it doesn't mandate output type, except that it needs to
9/// be [`AsRef<[u8]>`]. This makes it suitable for implementing larger
10/// hash function like SHA.
11pub trait HashFunction: ReprC {
12    type Output: AsRef<[u8]> + ReprC;
13
14    /// Updates the internal state of the [`HashFunction`] with given data.
15    fn update(&mut self, data: impl AsRef<[u8]>);
16
17    /// Writes the final result to the output passed as ref parameter.
18    fn write_result(&self, output: &mut Self::Output);
19
20    /// A wrapper around [`HashFunction::write_result`] that returns the hash
21    /// instead of writing it to output parameter.
22    fn result(&self) -> Self::Output {
23        let mut array = MaybeUninit::<Self::Output>::uninit();
24        let raw_ref = unsafe { &mut *array.as_mut_ptr() };
25        self.write_result(raw_ref);
26        unsafe { array.assume_init() }
27    }
28}
29
30/// A marker trait that ensures that the marked function is
31/// cryptographicall secure.
32///
33/// # Safety
34///
35/// It is up to the implementor to ensure this invariant.
36pub unsafe trait CryptographicallySecureHash: HashFunction {}