diff --git a/ciphers/src/subtle/hash_functions/infer_keyed_hash.rs b/ciphers/src/subtle/hash_functions/infer_keyed_hash.rs new file mode 100644 index 0000000..4422881 --- /dev/null +++ b/ciphers/src/subtle/hash_functions/infer_keyed_hash.rs @@ -0,0 +1,82 @@ +use std::marker::PhantomData; +use anyhow::Result; +use rosenpass_cipher_traits::{KeyedHash, KeyedHashInstance}; + +/// This is a helper to allow for type parameter inference when calling functions +/// that need a [KeyedHash]. +/// +/// Really just binds the [KeyedHash] trait to a dummy variable, so the type of this dummy variable +/// can be used for type inference. Less typing work. +#[derive(Debug, PartialEq, Eq)] +pub struct InferKeyedHash +where + Static: KeyedHash, +{ + pub _phantom_keyed_hasher: PhantomData<*const Static>, +} + +impl InferKeyedHash +where + Static: KeyedHash, +{ + pub const KEY_LEN : usize = KEY_LEN; + pub const HASH_LEN: usize = HASH_LEN; + + pub const fn new() -> Self { + Self { _phantom_keyed_hasher: PhantomData } + } + + /// This just forwards to [KeyedHash::keyed_hash] of the type parameter `Static` + fn keyed_hash_internal<'a>( + &self, + key: &'a [u8; KEY_LEN], + data: &'a [u8], + out: &mut [u8; HASH_LEN], + ) -> Result<()> { + Static::keyed_hash(key, data, out) + } + + pub const fn key_len(self) -> usize { + Self::KEY_LEN + } + + pub const fn hash_len(self) -> usize { + Self::HASH_LEN + } +} + +impl> KeyedHashInstance for InferKeyedHash { + type KeyType = [u8; KEY_LEN]; + type OutputType = [u8; HASH_LEN]; + type Error = anyhow::Error; + + fn keyed_hash(&self, key: &[u8; KEY_LEN], data: &[u8], out: &mut [u8; HASH_LEN]) -> Result<()> { + self.keyed_hash_internal(key, data, out) + } +} + +/// Helper traits ///////////////////////////////////////////// + +impl Default for InferKeyedHash +where + Static: KeyedHash, +{ + fn default() -> Self { + Self::new() + } +} + +impl Clone for InferKeyedHash +where + Static: KeyedHash, +{ + fn clone(&self) -> Self { + Self::new() + } +} + +impl Copy for InferKeyedHash +where + Static: KeyedHash, +{ +} diff --git a/ciphers/src/subtle/hash_functions/mod.rs b/ciphers/src/subtle/hash_functions/mod.rs index 328de65..ac1404e 100644 --- a/ciphers/src/subtle/hash_functions/mod.rs +++ b/ciphers/src/subtle/hash_functions/mod.rs @@ -1 +1,2 @@ -pub mod keyed_shake256; \ No newline at end of file +pub mod keyed_shake256; +mod infer_keyed_hash; \ No newline at end of file