How can deserialization of polymorphic trait objects be added in Rust if at all?

后端 未结 3 584
余生分开走
余生分开走 2020-12-01 21:05

I\'m trying to solve the problem of serializing and deserializing Box. I know that in the case of a closed type hierarchy, the recommended way

相关标签:
3条回答
  • 2020-12-01 21:43

    This has been implemented by dtolnay.

    The concept is quite clever ans is explained in the README:

    How does it work?

    We use the inventory crate to produce a registry of impls of your trait, which is built on the ctor crate to hook up initialization functions that insert into the registry. The first Box<dyn Trait> deserialization will perform the work of iterating the registry and building a map of tags to deserialization functions. Subsequent deserializations find the right deserialization function in that map. The erased-serde crate is also involved, to do this all in a way that does not break object safety.

    To summarize, every implementation of the trait declared as [de]serializable is registered at compile-time, and this is resolved at runtime in case of [de]serialization of a trait object.

    0 讨论(0)
  • 2020-12-01 21:46

    A library to do this should be possible. To create such a library, we would create a bidirectional mapping from TypeId to type name before using the library, and then use that for serialization/deserialization with a type marker. It would be possible to have a function for registering types that are not owned by your package, and to provide a macro annotation that automatically does this for types declared in your package.

    If there's a way to access a type ID in a macro, that would be a good way to instrument the mapping between TypeId and type name at compile time rather than runtime.

    0 讨论(0)
  • 2020-12-01 21:57

    All your libraries could provide a registration routine, guarded by std::sync::Once, that register some identifier into a common static mut, but obviously your program must call them all.

    I've no idea if TypeId yields consistent values across recompiles with different dependencies.

    0 讨论(0)
提交回复
热议问题