pub use synctick_derive::StableHash;
pub trait StableHash {
fn hash_into(&self, hasher: &mut StateHasher);
}
pub struct StateHasher(u64);
impl Default for StateHasher {
fn default() -> Self {
Self::new()
}
}
impl StateHasher {
#[must_use]
pub const fn new() -> Self {
Self(0xcbf2_9ce4_8422_2325)
}
pub fn field<T: StableHash + ?Sized>(&mut self, value: &T) {
value.hash_into(self);
}
pub fn write_bytes(&mut self, bytes: &[u8]) {
for &byte in bytes {
self.0 = (self.0 ^ u64::from(byte)).wrapping_mul(0x100_0000_01b3);
}
}
#[must_use]
pub const fn finish(self) -> u64 {
self.0
}
}
#[must_use]
pub fn stable_hash<T: StableHash + ?Sized>(value: &T) -> u64 {
let mut hasher = StateHasher::new();
hasher.field(value);
hasher.finish()
}
macro_rules! integers {
($($ty:ty),* $(,)?) => {$ (
impl StableHash for $ty {
fn hash_into(&self, hasher: &mut StateHasher) {
hasher.write_bytes(&self.to_le_bytes());
}
}
)*};
}
integers!(u8, u16, u32, u64, u128, i8, i16, i32, i64, i128);
impl StableHash for bool {
fn hash_into(&self, hasher: &mut StateHasher) {
hasher.field(&u8::from(*self));
}
}
impl StableHash for f32 {
fn hash_into(&self, hasher: &mut StateHasher) {
hasher.field(&self.to_bits());
}
}
impl StableHash for f64 {
fn hash_into(&self, hasher: &mut StateHasher) {
hasher.field(&self.to_bits());
}
}
impl StableHash for () {
fn hash_into(&self, _: &mut StateHasher) {}
}
impl<T: StableHash + ?Sized> StableHash for &T {
fn hash_into(&self, hasher: &mut StateHasher) {
T::hash_into(self, hasher);
}
}
impl<T: StableHash + ?Sized> StableHash for &mut T {
fn hash_into(&self, hasher: &mut StateHasher) {
T::hash_into(self, hasher);
}
}
impl StableHash for str {
fn hash_into(&self, hasher: &mut StateHasher) {
hasher.field(&(self.len() as u64));
hasher.write_bytes(self.as_bytes());
}
}
impl StableHash for String {
fn hash_into(&self, hasher: &mut StateHasher) {
self.as_str().hash_into(hasher);
}
}
impl<T: StableHash> StableHash for [T] {
fn hash_into(&self, hasher: &mut StateHasher) {
hasher.field(&(self.len() as u64));
for value in self {
hasher.field(value);
}
}
}
impl<T: StableHash> StableHash for Vec<T> {
fn hash_into(&self, hasher: &mut StateHasher) {
self.as_slice().hash_into(hasher);
}
}
impl<T: StableHash, const N: usize> StableHash for [T; N] {
fn hash_into(&self, hasher: &mut StateHasher) {
self.as_slice().hash_into(hasher);
}
}
impl<T: StableHash> StableHash for Option<T> {
fn hash_into(&self, hasher: &mut StateHasher) {
match self {
None => hasher.field(&0u8),
Some(value) => {
hasher.field(&1u8);
hasher.field(value);
}
}
}
}
macro_rules! tuples {
($(($($ty:ident : $index:tt),+)),+ $(,)?) => {$ (
impl<$($ty: StableHash),+> StableHash for ($($ty,)+) {
fn hash_into(&self, hasher: &mut StateHasher) {
$(hasher.field(&self.$index);)+
}
}
)+};
}
tuples!(
(A:0), (A:0, B:1), (A:0, B:1, C:2), (A:0, B:1, C:2, D:3),
(A:0, B:1, C:2, D:3, E:4), (A:0, B:1, C:2, D:3, E:4, F:5),
(A:0, B:1, C:2, D:3, E:4, F:5, G:6),
(A:0, B:1, C:2, D:3, E:4, F:5, G:6, H:7),
);