dtolnay / typetag

Serde serializable and deserializable trait objects
Apache License 2.0
1.19k stars 38 forks source link

Iterating over the typetag inventory #39

Closed leftadjoint closed 2 years ago

leftadjoint commented 3 years ago

I'd like to be able to iterate over the typetag inventory in order to generate a JSON schema inclusive of all of my trait's impls as of link time.

Unfortunately this doesn't seem to be supported in typetag; inventory seems to explicitly support it.

A simple example that fails:

#[cfg(test)]
mod test {
    use serde::{Deserialize, Serialize};
    use typetag;

    #[typetag::serde]
    trait A {}

    #[derive(Serialize, Deserialize)]
    struct Y {}

    #[typetag::serde]
    impl A for Y {}

    #[derive(Serialize, Deserialize)]
    struct Z {}

    #[typetag::serde]
    impl A for Z {}

    #[test]
    fn test() {
        let x = typetag::inventory::iter::<Box<dyn A>>;
        for y in x {}
    }
}

This complains:

the trait bound `inventory::private::iter<Box<dyn reference::test::A>>: IntoIterator` is not satisfied
the following implementations were found:
  <inventory::private::iter<T> as IntoIterator>
required by `into_iter`rustcE0277

It seems that since the iterator is private, this might not be possible at the moment.

Is it possible to make the iterator part of the public API?

dtolnay commented 2 years ago

I would prefer not to add this into this crate's public API.

You should be able to directly use inventory yourself, with your own type for the registry entries.