rust Serde不会为泛型结构派生

p8h8hvxi  于 2023-01-14  发布在  其他
关注(0)|答案(1)|浏览(113)

所以我尝试使用serdepostcard来序列化和反序列化某个通用结构(HashStore<T: ImgHashOutput>)。如果我能对所有的ImgHashOutput进行序列化和反序列化,那就太好了,但我真的只需要它对u128起作用。以下是所涉及的结构和特征。

pub trait ImgHashOutput:
    Default + AddAssign + ShlAssign<u8> + From<u8> + Copy + IntegerStuff + Serialize + DeserializeOwned {}

impl<T> ImgHashOutput for T where
    T: Default + AddAssign + ShlAssign<u8> + From<u8> + Copy + IntegerStuff + Serialize + DeserializeOwned {}

// store a vec of perceptual image hashes that correspond to a specific character
#[derive(Debug, Serialize, Deserialize)]
pub struct StoreValue<T: ImgHashOutput> {
    pub value: char,
    pub hashes: Vec<T>,
}

// collection of StoreValue for all the characters that can be recognized
#[derive(Debug, Serialize, Deserialize)]
pub struct HashStore<T: ImgHashOutput> {
    pub arr: Vec<StoreValue<T>>
}

pub trait SerdeStoreValue:
    Serialize + DeserializeOwned
{}

impl<T> SerdeStoreValue for T where
    T: Serialize + DeserializeOwned
{}

下面的代码工作得很好(据我所知)。我把它包括在上下文中。

pub trait IntegerStuff {
    const BITS: u32;
    fn hamming_dist<T: ImgHashOutput>(a: Self, b: Self) -> u32;
}

macro_rules! impl_integer_stuff {
    ($type:ty) => {
        impl IntegerStuff for $type {
            const BITS: u32 = (<$type>::BITS) as u32;
        
            #[inline(always)]
            fn hamming_dist<T: ImgHashOutput>(a: Self, b: Self) -> u32 {
                (a ^ b).count_ones() as u32
            }
        }
    };
}

impl_integer_stuff!(i8);
impl_integer_stuff!(u8);
impl_integer_stuff!(i16);
impl_integer_stuff!(u16);
impl_integer_stuff!(i32);
impl_integer_stuff!(u32);
impl_integer_stuff!(i64);
impl_integer_stuff!(u64);
impl_integer_stuff!(i128);
impl_integer_stuff!(u128);
impl_integer_stuff!(isize);
impl_integer_stuff!(usize);
xzv2uavs

xzv2uavs1#

我需要省略StoreValue上的ImgHashOutput绑定。
source:wowie#4254 on discord

相关问题