#serde #serialization #seed #serializeseed

no-std serde-serialize-seed

方便使用的SerializeSeed特质

10个版本

0.0.10 2024年5月25日
0.0.9 2022年12月21日

#5 in #seed

Download history 3/week @ 2024-04-10 1/week @ 2024-05-08 3/week @ 2024-05-15 225/week @ 2024-05-22 42/week @ 2024-05-29 35/week @ 2024-06-05 21/week @ 2024-06-12 8/week @ 2024-06-19 10/week @ 2024-06-26 43/week @ 2024-07-03 9/week @ 2024-07-10 6/week @ 2024-07-17 1/week @ 2024-07-24

每月下载 62次
用于 2 crates

MIT/Apache

12KB
183

maintenance: actively developed

serde-serialize-seed

SerializeSeed特质,方便使用。

示例

mod complex_type {
    use serde::{Deserializer, Serializer};
    use serde::de::{self, DeserializeSeed};
    use serde_serialize_seed::SerializeSeed;
    use std::fmt::{self, Formatter};

    pub struct ComplexType(pub u8);

    pub struct ComplexTypeSerde {
        pub xor: u8,
    }

    struct ComplexTypeDeVisitor(ComplexTypeSerde);

    impl<'de> de::Visitor<'de> for ComplexTypeDeVisitor {
        type Value = ComplexType;

        fn expecting(&self, f: &mut Formatter) -> fmt::Result {
            write!(f, "u8")
        }

        fn visit_u64<E: de::Error>(self, v: u64) -> Result<Self::Value, E> {
            let v = u8::try_from(v).map_err(|_| E::invalid_value(de::Unexpected::Unsigned(v), &self))?;
            Ok(ComplexType(v ^ self.0.xor))
        }
    }

    impl<'de> DeserializeSeed<'de> for ComplexTypeSerde {
        type Value = ComplexType;

        fn deserialize<D: Deserializer<'de>>(self, deserializer: D) -> Result<Self::Value, D::Error> {
            deserializer.deserialize_u8(ComplexTypeDeVisitor(self))
        }
    }

    impl SerializeSeed for ComplexTypeSerde {
        type Value = ComplexType;

        fn serialize<S: Serializer>(&self, value: &Self::Value, serializer: S) -> Result<S::Ok, S::Error> {
            serializer.serialize_u8(value.0 ^ self.xor)
        }
    }
}

use complex_type::*;
use serde::de::DeserializeSeed;
use serde_serialize_seed::ValueWithSeed;

fn main() {
    let x = ComplexType(10);
    let json = serde_json::to_value(ValueWithSeed(&x, ComplexTypeSerde { xor: 0x34 })).unwrap();
    let y = ComplexTypeSerde { xor: 0x34 }.deserialize(json).unwrap();
    assert_eq!(x.0, y.0);
}

依赖项

~0.4–1MB
~22K SLoC