Erased Serde
This crate provides type-erased versions of Serde's Serialize
, Serializer
and Deserializer
traits that can be used as trait objects.
The usual Serde Serialize
, Serializer
and Deserializer
traits cannot be
used as trait objects like &dyn Serialize
or boxed trait objects like
Box<dyn Serialize>
because of Rust's "object safety" rules. In particular,
all three traits contain generic methods which cannot be made into a trait
object.
This library should be considered a low-level building block for interacting
with Serde APIs in an object-safe way. Most use cases will require higher level
functionality such as provided by typetag
which uses this crate internally.
The traits in this crate work seamlessly with any existing Serde Serialize
and Deserialize
type and any existing Serde Serializer
and Deserializer
format.
[]
= "1.0"
= "0.4"
Serialization
use ;
use BTreeMap as Map;
use io;
Deserialization
use Deserializer;
use BTreeMap as Map;
How it works
This crate is based on a general technique for building trait objects of traits that have generic methods (like all of Serde's traits). This example code demonstrates the technique applied to a simplified case of a single generic method. Try it in the playground.
In erased-serde things are a bit more complicated than in the example for three reasons but the idea is the same.
- We need to deal with trait methods that take
self
by value -- effectively by implementing the object-safe trait forOption<T>
whereT
implements the real trait. - We need to deal with traits that have associated types like
Serializer::Ok
andVisitor::Value
-- by carefully short-term stashing things behind a pointer. - We need to support trait methods that have a generic type in the return type
but none of the argument types, like
SeqAccess::next_element
-- this can be flipped around into a callback style where the return value is instead passed on to a generic argument.
In the future maybe the Rust compiler will be able to apply this technique automatically to any trait that is not already object safe by the current rules.