Skip to main content

xso_trait

Macro xso_trait 

Source
macro_rules! xso_trait {
    ($trait:ident use $registry:ty = $reginit:expr) => { ... };
    ($trait:ident) => { ... };
}
Expand description

Make a trait usable as dynamic XSO trait.

This macro generates DynXso and MayContain trait implementations for dyn Trait for a given Trait. For more background information on when that is a useful thing to have, see the dynxso module.

§Syntax

This macro can be called in two forms:

  • xso_trait!(Trait) uses the default BuilderRegistry as DynXso::Registry type and is only available if xso is built with the "std" feature.
  • xso_trait!(Trait use Type = expr) where Type is used as DynXso::Registry, initialized with expr. This form is available for any set of crate features.

§Example

 trait MyPayload: Any {}

 xso_trait!(MyPayload);

 #[derive(FromXml, Debug, PartialEq)]
 #[xml(namespace = "urn:example", name = "foo")]
 struct Foo;
 impl MyPayload for Foo {}
 Xso::<dyn MyPayload>::register_type::<Foo>();

 #[derive(FromXml, Debug, PartialEq)]
 #[xml(namespace = "urn:example", name = "bar")]
 struct Bar;
 impl MyPayload for Bar {}
 Xso::<dyn MyPayload>::register_type::<Bar>();

 let x: Xso<dyn MyPayload> = from_bytes("<foo xmlns='urn:example'/>".as_bytes()).unwrap();
 assert_eq!(Foo, *x.downcast::<Foo>().unwrap());

 let x: Xso<dyn MyPayload> = from_bytes("<bar xmlns='urn:example'/>".as_bytes()).unwrap();
 assert_eq!(Bar, *x.downcast::<Bar>().unwrap());

 Note that the trait this macro is called on must have a bound on Any, otherwise the generated code will not compile:

 use xso::dynxso::xso_trait;
 trait Foo {}
 xso_trait!(Foo);
 // ↑ will generate a bunch of errors about incompatible types

If the std feature is not enabled or if you want to use another Registry for whichever reason, the explicit form can be used:

use xso::dynxso::xso_trait;
trait Foo: Any {}
struct Registry { /* .. */ }
xso_trait!(Foo use Registry = Registry { /* .. */ });

In that case, you should review the trait requirements of the DynXso::Registry associated type.