From 253cc6a77b6abd10a5ad1c26b845d5cf0484b839 Mon Sep 17 00:00:00 2001 From: Alexandra Date: Sat, 15 Feb 2025 14:07:01 -0500 Subject: [PATCH] Add `TypeRegistry::register_by_val` (#17817) # Objective It is impossible to register a type with `TypeRegistry::register` if the type is unnameable (in the current scope). ## Solution Add `TypeRegistry::register_by_val` which mirrors std's `size_of_val` and friends. ## Testing There's a doc test (unrelated but there seem to be some pre-existing broken doc links in `bevy_reflect`). --- crates/bevy_reflect/src/type_registry.rs | 37 ++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/crates/bevy_reflect/src/type_registry.rs b/crates/bevy_reflect/src/type_registry.rs index d9d0e509bf..cf80749ede 100644 --- a/crates/bevy_reflect/src/type_registry.rs +++ b/crates/bevy_reflect/src/type_registry.rs @@ -165,6 +165,43 @@ impl TypeRegistry { } } + /// Attempts to register the referenced type `T` if it has not yet been registered. + /// + /// See [`register`] for more details. + /// + /// # Example + /// + /// ``` + /// # use bevy_reflect::{Reflect, TypeRegistry}; + /// # use core::any::TypeId; + /// # + /// # let mut type_registry = TypeRegistry::default(); + /// # + /// #[derive(Reflect)] + /// struct Foo { + /// bar: Bar, + /// } + /// + /// #[derive(Reflect)] + /// struct Bar; + /// + /// let foo = Foo { bar: Bar }; + /// + /// // Equivalent to `type_registry.register::()` + /// type_registry.register_by_val(&foo); + /// + /// assert!(type_registry.contains(TypeId::of::())); + /// assert!(type_registry.contains(TypeId::of::())); + /// ``` + /// + /// [`register`]: Self::register + pub fn register_by_val(&mut self, _: &T) + where + T: GetTypeRegistration, + { + self.register::(); + } + /// Attempts to register the type described by `registration`. /// /// If the registration for the type already exists, it will not be registered again.