Module detrojt::serde [] [src]

A collection of helper traits that can be used to add serialization support to user-defined traits.

See Trait for more information.

Example

extern crate detrojt;
extern crate serde;
extern crate serde_json;

use std::rc::Rc;
use detrojt::serde::{HasInterDeserialize, Trait, deserialize, serialize};

// a minimal example trait that requires Debug
trait MyTrait: Trait<serde_json::Value, MyTraitObj> + std::fmt::Debug {}

// add a few implementations
impl MyTrait for String {}
impl MyTrait for f64 {}
impl MyTrait for (u8, MyTraitObj) {}

// Create a wrapper type for the trait object.
// The wrapper type must support From<T: MyTrait> and HasInterDeserialize.
#[derive(Clone, Debug)]
struct MyTraitObj(Rc<MyTrait>);

impl<T: MyTrait + 'static> From<T> for MyTraitObj {
    fn from(t: T) -> Self { MyTraitObj(Rc::new(t)) }
}

impl HasInterDeserialize for MyTraitObj {
    type InterDeserialize = serde_json::Value;
}

impl serde::Serialize for MyTraitObj {
    fn serialize<S>(&self, s: S) -> Result<S::Ok, S::Error>
        where S: serde::Serializer { serialize(&*self.0, s) }
}

impl<'de> serde::Deserialize<'de> for MyTraitObj {
    fn deserialize<D>(d: D) -> Result<Self, D::Error>
        where D: serde::Deserializer<'de> { deserialize(d) }
}

let a = MyTraitObj::from(String::from("hello world"));
let b = MyTraitObj::from(std::f64::consts::PI);
let c = MyTraitObj::from((42u8, b.clone()));
let sa = serde_json::to_value(&a)?;
let sb = serde_json::to_value(&b)?;
let sc = serde_json::to_value(&c)?;
let a2: MyTraitObj = serde_json::from_value(sa)?;
let b2: MyTraitObj = serde_json::from_value(sb)?;
let c2: MyTraitObj = serde_json::from_value(sc)?;
assert_eq!(format!("{:?}", a), format!("{:?}", a2));
assert_eq!(format!("{:?}", b), format!("{:?}", b2));
assert_eq!(format!("{:?}", c), format!("{:?}", c2));
assert_ne!(format!("{:?}", a), format!("{:?}", b2));
assert_ne!(format!("{:?}", b), format!("{:?}", c2));
assert_ne!(format!("{:?}", c), format!("{:?}", a2));

Traits

HasInterDeserialize

Used to associate the trait object with an intermediate deserializer.

InterDeserialize

Intermediate format used to deserialize the trait object.

InterSerialize

Intermediate format used to serialize the trait object.

Trait

Supertrait for adding serialization support to user-defined traits.

Functions

deserialize

Deserialize the given trait object. You can plug this method directly into your trait object's Deserialize implementation.

serialize

Serialize the given trait object. You can plug this method directly into your trait object's Serialize implementation.