bevy icon indicating copy to clipboard operation
bevy copied to clipboard

OwningPtr should impl From<Box<T>>

Open dmyyy opened this issue 9 months ago • 2 comments

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

dmyyy avatar May 09 '24 03:05 dmyyy

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.

MrGVSV avatar May 09 '24 03:05 MrGVSV

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.

SkiFire13 avatar May 09 '24 08:05 SkiFire13