Skip to content

Commit

Permalink
Provide getters for fields of ReflectFromPtr
Browse files Browse the repository at this point in the history
The reasoning is similar to #8687.

I'm building a dynamic query. Currently, I store the ReflectFromPtr in
my dynamic `Fetch` type.

However, `ReflectFromPtr` is:

- 16 bytes for TypeId
- 8 bytes for the non-mutable function pointer
- 8 bytes for the mutable function pointer

It's a lot, it adds 32 bytes to my base `Fetch` which is only
`ComponendId` (8 bytes) for a total of 40 bytes.

I only need one function per fetch, reducing the total dynamic fetch
size to 16 bytes.

Since I'm querying the components by the ComponendId associated with the
function pointer I'm using, I don't need the TypeId, it's a redundant
check.

In fact, I've difficulties coming up with situations where checking the
TypeId beforehand is relevant. So to me, if ReflectFromPtr makes sense
as a public API, exposing the function pointers also makes sense.
  • Loading branch information
nicopap committed Sep 10, 2023
1 parent 17edf4f commit 81a94a8
Showing 1 changed file with 22 additions and 2 deletions.
24 changes: 22 additions & 2 deletions crates/bevy_reflect/src/type_registry.rs
Original file line number Diff line number Diff line change
Expand Up @@ -528,8 +528,8 @@ impl<T: for<'a> Deserialize<'a> + Reflect> FromType<T> for ReflectDeserialize {
#[derive(Clone)]
pub struct ReflectFromPtr {
type_id: TypeId,
to_reflect: for<'a> unsafe fn(Ptr<'a>) -> &'a dyn Reflect,
to_reflect_mut: for<'a> unsafe fn(PtrMut<'a>) -> &'a mut dyn Reflect,
to_reflect: unsafe fn(Ptr) -> &dyn Reflect,
to_reflect_mut: unsafe fn(PtrMut) -> &mut dyn Reflect,
}

impl ReflectFromPtr {
Expand All @@ -553,6 +553,26 @@ impl ReflectFromPtr {
pub unsafe fn as_reflect_ptr_mut<'a>(&self, val: PtrMut<'a>) -> &'a mut dyn Reflect {
(self.to_reflect_mut)(val)
}
/// Get a function pointer to turn a `Ptr` into `&dyn Reflect` for
/// the type this was constructed for.
///
/// # Safety
/// When calling the unsafe function returned by this method you must ensure that:
/// - The input `Ptr` points to the `Reflect` type this [`ReflectFromPtr`]
/// was constructed for.
pub fn get_to_reflect(&self) -> unsafe fn(Ptr) -> &dyn Reflect {
self.to_reflect
}
/// Get a function pointer to turn a `PtrMut` into `&mut dyn Reflect` for
/// the type this was constructed for.
///
/// # Safety
/// When calling the unsafe function returned by this method you must ensure that:
/// - The input `PtrMut` points to the `Reflect` type this [`ReflectFromPtr`]
/// was constructed for.
pub fn get_to_reflect_mut(&self) -> unsafe fn(PtrMut) -> &mut dyn Reflect {
self.to_reflect_mut
}
}

impl<T: Reflect> FromType<T> for ReflectFromPtr {
Expand Down

0 comments on commit 81a94a8

Please sign in to comment.