#macro-derive #hashing #u8 #metadata #field #u16 #tysh

tysh-derive

本软件包提供了Tysh的派生宏

1个不稳定版本

0.1.0 2023年3月25日

#30 in #u16


tysh中使用

Apache-2.0

8KB
90

tysh

Tysh是一个帮助对类型元数据进行哈希的crate。

目的

Tysh是一个与bincode crate一起使用的工具,该crate帮助进行数据序列化。虽然bincode crate与某些数据结构(如Color { r: u8, g: u8, b: u8 }Color { b: u8, g: u8, r: u8 }结构具有相同的类型结构且与JSON序列化兼容,但bincode在序列化和反序列化数据时可能会改变数据的含义。为了避免这个问题,tysh还提供了字段名称以及类型信息,这有助于确保不同版本的数据结构之间的兼容性。

如何使用

use tysh::TypeHash;

#[derive(TypeHash)]
struct A {
    a: u8,
    b: u16,
}

这将生成以下代码

struct A {
    a: u8,
    b: u16,
}
impl ::tysh::TypeHash for A {
    fn type_hash<H: ::core::hash::Hasher>(hasher: &mut H) {
        use ::core::hash::Hash;
        "@struct@".hash(hasher);
        "A".hash(hasher);
        "@field@".hash(hasher);
        "a".hash(hasher);
        <u8 as ::tysh::TypeHash>::type_hash(hasher);
        "@field@".hash(hasher);
        "b".hash(hasher);
        <u16 as ::tysh::TypeHash>::type_hash(hasher);
    }
}

您还可以使用#[type_hash(name = "name")]属性来指定内部名称。

use tysh::TypeHash;

#[derive(TypeHash)]
#[type_hash(name = "AnotherName")]
struct A {
    a: u8,
    #[type_hash(name = "another special name")]
    b: u16,
}
pub struct A {
    a: u8,
    b: u16,
}
impl ::tysh::TypeHash for A {
    fn type_hash<H: ::core::hash::Hasher>(hasher: &mut H) {
        use ::core::hash::Hash;
        "@struct@".hash(hasher);
        "AnotherName".hash(hasher);
        "@field@".hash(hasher);
        "a".hash(hasher);
        <u8 as ::tysh::TypeHash>::type_hash(hasher);
        "@field@".hash(hasher);
        "another special name".hash(hasher);
        <u16 as ::tysh::TypeHash>::type_hash(hasher);
    }
}

依赖项

~300–760KB
~18K SLoC