Crate detrojt [] [src]

A hack to support deserialization of arbitrary trait objects.

This an implementation of a workaround for rust-lang/rfcs#668 "Encodable trait objects".

See README.md for the caveats and security implications.

The core of the library rests upon the trio TyConst, get_ty_const, and get_ty_const_key. They provide a mechanism for looking up data associated with a type using a persistent identifier ("key").

D: TyConst<T> is a trait used to define such data. Each implementation associates an arbitrary value of type D (i.e. Self) with the type parameter T. Conceptually, it's as if every D has its own table of data, indexed by T. Within a given table, every T is associated with a unique usize key.

get_ty_const_key returns the unique key for the data associated with T in the table of D. The key is persistent (serializable): it can be used in a later execution of the same program. The key is only guaranteed to be unique for a given D (i.e. the key is meaningless without knowing what D is).

get_ty_const uses the key to retrieve the data D associated with T without knowing what T was. If the key is invalid, then None is returned.

Example

For a more interesting example, see the serde submodule, which uses TyConst under the hood.

use detrojt::{TyConst, get_ty_const, get_ty_const_key};

#[derive(Debug, PartialEq, Eq)]
struct Size(usize);

impl<T: 'static> TyConst<T> for Size {
    fn get_data() -> Self { Size(std::mem::size_of::<T>()) }
}

assert_eq!(get_ty_const(get_ty_const_key::<Size, ()>()), Some(Size(0)));
assert_eq!(get_ty_const(get_ty_const_key::<Size, i64>()), Some(Size(8)));
assert_eq!(get_ty_const::<Size>(1), None);

Modules

serde

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

Traits

TyConst

This represents a mapping from a type T to some data of type Self (also referred to as D in other places).

Functions

get_ty_const

Get the data in the impl for the type that matches the given key. If the key is invalid, returns None.

get_ty_const_key

Get the key associated with TyConst<T> for D. Instantiations of this function determine what goes into the type constant table for D.