#type #hash #macro-derive #struct #macro

type_hash

Generate a hash for a Rust type. The primary use-case for this crate is for detecting differences in message types between versions of a crate. The TypeHash trait is implemented for most built-in types and a derive macro is provided, for implementing it for your own types

5 unstable releases

0.3.0 Feb 27, 2021
0.2.2 Jan 4, 2021
0.2.1 Jan 3, 2021
0.2.0 Jan 3, 2021
0.1.0 Jan 3, 2021

#2671 in Rust patterns

Download history 303/week @ 2024-08-21 336/week @ 2024-08-28 266/week @ 2024-09-04 359/week @ 2024-09-11 320/week @ 2024-09-18 387/week @ 2024-09-25 4834/week @ 2024-10-02 4938/week @ 2024-10-09 6727/week @ 2024-10-16 8906/week @ 2024-10-23 9103/week @ 2024-10-30 11846/week @ 2024-11-06 10636/week @ 2024-11-13 12246/week @ 2024-11-20 11027/week @ 2024-11-27 13657/week @ 2024-12-04

50,063 downloads per month
Used in edsm-dumps-model

MIT license

13KB
253 lines

type_hash

Generate a hash for a Rust type.

The primary use-case for this crate is for detecting differences in message types between versions of a crate.

The TypeHash trait is implemented for most built-in types and a derive macro is provided, for implementing it for your own types.

Examples

use type_hash::TypeHash;

#[derive(TypeHash)]
pub enum Message {
    LaunchMissiles { destination: String },
    CancelMissiles,
}

fn main() {
    let hash = Message::type_hash();
    // this will only change if the type definition changes
    assert_eq!(hash, 11652809455620829461);
}

Customising derived TypeHash implementations

#[type_hash(foreign_type)]

If a struct field has a foreign type that does not implement TypeHash, you can mark it as a foreign type and the derive TypeHash implementation will use the name of the type in the hash instead. You need to be a little bit careful here because a change in the third party crate could change your type in an undetectable way.

#[derive(TypeHash)]
pub struct MyStruct {
    #[type_hash(foreign_type)]
    data: ArrayVec<[u16; 7]>
}

#[type_hash(skip)]

Skip a field, so it is not part of the hash.

#[derive(TypeHash)]
pub struct MyStruct {
    #[type_hash(skip)]
    not_important: Vec<i64>,
}

#[type_hash(as = "...")]

Hash a field as if it had a different type. This allows you to change the type of a field to a different type that is still compatible for your application, without affecting the hash.

#[derive(TypeHash)]
pub struct MyStruct {
    #[type_hash(as = "HashSet<i64>")]
    numbers: BTreeSet<i64>,
}

Dependencies

~1.5MB
~38K SLoC