Skip to content

Commit 253cc6a

Browse files
authored
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`).
1 parent 3c9e696 commit 253cc6a

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

crates/bevy_reflect/src/type_registry.rs

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -165,6 +165,43 @@ impl TypeRegistry {
165165
}
166166
}
167167

168+
/// Attempts to register the referenced type `T` if it has not yet been registered.
169+
///
170+
/// See [`register`] for more details.
171+
///
172+
/// # Example
173+
///
174+
/// ```
175+
/// # use bevy_reflect::{Reflect, TypeRegistry};
176+
/// # use core::any::TypeId;
177+
/// #
178+
/// # let mut type_registry = TypeRegistry::default();
179+
/// #
180+
/// #[derive(Reflect)]
181+
/// struct Foo {
182+
/// bar: Bar,
183+
/// }
184+
///
185+
/// #[derive(Reflect)]
186+
/// struct Bar;
187+
///
188+
/// let foo = Foo { bar: Bar };
189+
///
190+
/// // Equivalent to `type_registry.register::<Foo>()`
191+
/// type_registry.register_by_val(&foo);
192+
///
193+
/// assert!(type_registry.contains(TypeId::of::<Foo>()));
194+
/// assert!(type_registry.contains(TypeId::of::<Bar>()));
195+
/// ```
196+
///
197+
/// [`register`]: Self::register
198+
pub fn register_by_val<T>(&mut self, _: &T)
199+
where
200+
T: GetTypeRegistration,
201+
{
202+
self.register::<T>();
203+
}
204+
168205
/// Attempts to register the type described by `registration`.
169206
///
170207
/// If the registration for the type already exists, it will not be registered again.

0 commit comments

Comments
 (0)