#hash #enums #discriminant #traits #fields #variant #derive

discriminant_hash_derive

仅基于枚举的判别符实现Hash trait的派生宏,忽略变体的字段

1个不稳定版本

0.1.0 2021年6月11日

#1687 in 过程宏

MIT/Apache

6KB

discriminant_hash_derive

派生DiscriminantHash为底层枚举实现Hash trait。这里的hash仅依赖于判别符,不受变体字段的影响。

示例

use discriminant_hash_derive::DiscriminantHash;
use std::{
    collections::hash_map::DefaultHasher,
    hash::{Hash, Hasher},
};

#[derive(DiscriminantHash)]
enum Abc<T> {
    Simple,
    HashNotImplemented(Xyz),
    Generic(T),
}

#[allow(unused)]
#[derive(Hash)]
enum Pqr<'a> {
    Simple,
    Lifetime(&'a str),
}

// Xyz doesn't impl Hash
struct Xyz;

fn main() {
    assert_eq!(my_hash(Abc::Simple::<i32>), my_hash(Abc::Simple::<Xyz>));
    assert_eq!(
        my_hash(Abc::HashNotImplemented::<i32>(Xyz)),
        my_hash(Abc::HashNotImplemented::<String>(Xyz))
    );
    assert_eq!(
        my_hash(Abc::Generic::<i32>(4)),
        my_hash(Abc::Generic::<Xyz>(Xyz))
    );

    assert_ne!(
        my_hash(Abc::Simple::<i32>),
        my_hash(Abc::Generic::<Xyz>(Xyz))
    );

     
    // This may be same depending on how Pqr is defined
    // assert_eq!(
    //     my_hash(Abc::Simple::<i32>),
    //     my_hash(Pqr::Simple)
    // );
     
}

fn my_hash<T>(obj: T) -> u64
where
    T: Hash,
{
    let mut hasher = DefaultHasher::new();
    obj.hash(&mut hasher);
    hasher.finish()
}

依赖项

~1.5MB
~35K SLoC