bevy
bevy copied to clipboard
OwningPtr should impl From<Box<T>>
What problem does this solve or what need does it fill?
I am trying to copy the value for a type erased entity component of type &dyn Reflect
.
insert_by_id
requires an OwningPtr
to be passed in. I want to copy the component &dyn Reflect
points to and insert the same component for an entity. I can copy the value of &dyn Reflect
via clone_value()
giving me Box<dyn Reflect>
.
There isn't an easy way to get an OwningPtr from a Box<dyn Reflect>. A Box is a unique pointer to some value on the heap - I don't see any reason why it can't be an OwningPtr.
What solution would you like?
implement From<Box<T>>
for OwningPtr
.
What alternative(s) have you considered?
This can be done with raw pointers.
Additional context
Note that for dyn Reflect
we probably want to only do this via the ReflectFromPtr
type data.
The reason for this is because a Box<dyn Reflect>
might not actually be a Box<T>
.
Specifically, when cloning via Reflect::clone_value
, you almost always get back a dynamic type (e.g. Box<DynamicStruct>
). It would be unsafe to treat the OwningPtr
as one that points to T
when it really points to DynamicStruct
.
So ideally we expose this API through the ReflectFromPtr
type data to help ensure these kinds of operations are done safely.
Another reason why this should be avoided is that OwningPtr
only owns the data, not the allocation, so the proposed conversion would have to leak the allocation.
I would instead suggest using ReflectComponent
to insert a reflected value as component.