use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
use byteorder::{LittleEndian};
use rand::Rng;
use serde::{Serialize, Deserialize, de::DeserializeOwned};
use crate::serialization::cdr_serializer::to_bytes;
pub trait Keyed {
type K;
fn get_key(&self) -> Self::K;
fn get_hash(&self) -> u64
where
Self::K: Key,
{
let mut hasher = DefaultHasher::new();
self.get_key().hash(&mut hasher);
hasher.finish()
}
}
pub trait Key:
Eq + PartialEq + PartialOrd + Ord + Hash + Clone + Serialize + DeserializeOwned
{
fn into_hash_key(&self) -> u128 {
let cdr_bytes = match to_bytes::<Self, LittleEndian>(&self) {
Ok(b) => b,
_ => Vec::new(),
};
let digest = if cdr_bytes.len() > 16 {
md5::compute(&cdr_bytes).to_vec()
} else {
cdr_bytes
};
let mut digarr: [u8; 16] = [0; 16];
for i in 0..digest.len() {
digarr[i] = digest[i];
}
u128::from_le_bytes(digarr)
}
}
impl Key for () {
fn into_hash_key(&self) -> u128 {
0
}
}
impl<D: Keyed> Keyed for &D {
type K = D::K;
fn get_key(&self) -> Self::K {
(*self).get_key()
}
}
impl Key for bool {}
impl Key for char {}
impl Key for i8 {}
impl Key for i16 {}
impl Key for i32 {}
impl Key for i64 {}
impl Key for i128 {}
impl Key for isize {}
impl Key for u8 {}
impl Key for u16 {}
impl Key for u32 {}
impl Key for u64 {}
impl Key for u128 {}
impl Key for usize {}
impl Key for String {}
#[derive(Debug, Eq, PartialEq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub struct BuiltInTopicKey {
value: [i32; 3],
}
impl BuiltInTopicKey {
pub fn get_random_key() -> BuiltInTopicKey {
let mut rng = rand::thread_rng();
BuiltInTopicKey {
value: [rng.gen(), rng.gen(), rng.gen()],
}
}
pub fn default() -> BuiltInTopicKey {
BuiltInTopicKey { value: [0, 0, 0] }
}
}