EmbarkStudios / mirror-mirror

🪞 Powerful reflection library for Rust
Apache License 2.0
79 stars 2 forks source link

A way to pass "context" to `FromReflect` #38

Closed davidpdrsn closed 1 year ago

davidpdrsn commented 1 year ago

We have a use case where it would be useful to pass data into FromReflect which is needed to perform the conversion: We have entity ids encoded as opaque u32s. Before converting a u32 back into an entity id we'd need to check that it actually points to a valid entity, or perhaps do additional checks. Doing that check would require a handle to the system that manages entities. It is currently not possible to pass that into from_reflect and we only get the raw u32.

We can't simply add a new argument for from_reflect...

pub trait FromReflect<C: ?Sized>: Reflect + Sized {
    fn from_reflect(reflect: &dyn Reflect, context: &C) -> Option<Self>;
}

...since from_reflect called from:

So we'd have to also pass the new arg to those functions. We also cannot add generic parameters to those functions since Reflect needs to be object safe. Could make Reflect itself generic over the context but thats a large change that'd cause other changes pretty much everywhere.

Perhaps there is a more elegant solution that wouldn't require changing everything 🤔

davidpdrsn commented 1 year ago

I'm not sure we really need this after all. The use case we had internally turned out to be solvable in a different way (EntityId::invalid()). So since we don't need it and its unlikely there is a good way to solve it I think I'll close this for now.