Trait erased_serde::Serialize[][src]

pub trait Serialize {
    fn erased_serialize(&self, v: &mut dyn Serializer) -> Result<Ok, Error>;
}

An object-safe equivalent of Serde’s Serialize trait.

Any implementation of Serde’s Serialize converts seamlessly to an &erased_serde::Serialize or Box<erased_serde::Serialize> trait object.

use erased_serde::{Serialize, Serializer};
use std::collections::BTreeMap as Map;
use std::io;

fn main() {
    // Construct some serializers.
    let json = &mut serde_json::Serializer::new(io::stdout());
    let cbor = &mut serde_cbor::Serializer::new(serde_cbor::ser::IoWrite::new(io::stdout()));

    // The values in this map are boxed trait objects. Ordinarily this would not
    // be possible with serde::Serializer because of object safety, but type
    // erasure makes it possible with erased_serde::Serializer.
    let mut formats: Map<&str, Box<dyn Serializer>> = Map::new();
    formats.insert("json", Box::new(Serializer::erase(json)));
    formats.insert("cbor", Box::new(Serializer::erase(cbor)));

    // These are boxed trait objects as well. Same thing here - type erasure
    // makes this possible.
    let mut values: Map<&str, Box<dyn Serialize>> = Map::new();
    values.insert("vec", Box::new(vec!["a", "b"]));
    values.insert("int", Box::new(65536));

    // Pick a Serializer out of the formats map.
    let format = formats.get_mut("json").unwrap();

    // Pick a Serialize out of the values map.
    let value = values.get("vec").unwrap();

    // This line prints `["a","b"]` to stdout.
    value.erased_serialize(format).unwrap();
}

Required methods

fn erased_serialize(&self, v: &mut dyn Serializer) -> Result<Ok, Error>[src]

Loading content...

Trait Implementations

impl<'erased> Serialize for dyn Serialize + 'erased[src]

impl<'erased> Serialize for dyn Serialize + Send + 'erased[src]

impl<'erased> Serialize for dyn Serialize + Sync + 'erased[src]

impl<'erased> Serialize for dyn Serialize + Send + Sync + 'erased[src]

Implementors

impl<T: ?Sized> Serialize for T where
    T: Serialize
[src]

Loading content...