#serde #seed #serialize #serializeseed

no-std serde-serialize-seed

The SerializeSeed trait for convinience

9 releases

0.0.9 Dec 21, 2022
0.0.8 Dec 21, 2022

#1390 in Encoding

Download history 35/week @ 2023-11-04 38/week @ 2023-11-11 36/week @ 2023-11-18 64/week @ 2023-11-25 51/week @ 2023-12-02 33/week @ 2023-12-09 43/week @ 2023-12-16 31/week @ 2023-12-23 15/week @ 2023-12-30 11/week @ 2024-01-06 15/week @ 2024-01-13 10/week @ 2024-01-20 27/week @ 2024-01-27 11/week @ 2024-02-03 37/week @ 2024-02-10 171/week @ 2024-02-17

250 downloads per month
Used in 2 crates

MIT/Apache

12KB
182 lines

maintenance: actively developed

serde-serialize-seed

The SerializeSeed trait for convinience.

Example

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);
}

Dependencies

~1.6–2.1MB
~49K SLoC