repo stringlengths 6 65 | file_url stringlengths 81 311 | file_path stringlengths 6 227 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:31:58 2026-01-04 20:25:31 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/func/reflect_fn_mut.rs | crates/bevy_reflect/src/func/reflect_fn_mut.rs | use variadics_please::all_tuples;
use crate::{
func::{
args::{ArgCount, FromArg},
macros::count_tokens,
ArgList, FunctionError, FunctionResult, IntoReturn,
},
Reflect, TypePath,
};
/// A reflection-based version of the [`FnMut`] trait.
///
/// This allows functions to be called dynamically through [reflection].
///
/// This is a supertrait of [`ReflectFn`], and is used for functions that may mutate their environment,
/// such as closures that capture mutable references.
///
/// # Blanket Implementation
///
/// This trait has a blanket implementation that covers everything that [`ReflectFn`] does:
/// - Functions and methods defined with the `fn` keyword
/// - Anonymous functions
/// - Function pointers
/// - Closures that capture immutable references to their environment
/// - Closures that take ownership of captured variables
///
/// But also allows for:
/// - Closures that capture mutable references to their environment
///
/// For each of the above cases, the function signature may only have up to 15 arguments,
/// not including an optional receiver argument (often `&self` or `&mut self`).
/// This optional receiver argument may be either a mutable or immutable reference to a type.
/// If the return type is also a reference, its lifetime will be bound to the lifetime of this receiver.
///
/// See the [module-level documentation] for more information on valid signatures.
///
/// Arguments are expected to implement [`FromArg`], and the return type is expected to implement [`IntoReturn`].
/// Both of these traits are automatically implemented when using the `Reflect` [derive macro].
///
/// # Example
///
/// ```
/// # use bevy_reflect::func::{ArgList, FunctionInfo, ReflectFnMut};
/// #
/// let mut list: Vec<i32> = vec![1, 3];
///
/// // `insert` is a closure that captures a mutable reference to `list`
/// let mut insert = |index: usize, value: i32| {
/// list.insert(index, value);
/// };
///
/// let args = ArgList::new().with_owned(1_usize).with_owned(2_i32);
///
/// insert.reflect_call_mut(args).unwrap();
/// assert_eq!(list, vec![1, 2, 3]);
/// ```
///
/// # Trait Parameters
///
/// This trait has a `Marker` type parameter that is used to get around issues with
/// [unconstrained type parameters] when defining impls with generic arguments or return types.
/// This `Marker` can be any type, provided it doesn't conflict with other implementations.
///
/// Additionally, it has a lifetime parameter, `'env`, that is used to bound the lifetime of the function.
/// For named functions and some closures, this will end up just being `'static`,
/// however, closures that borrow from their environment will have a lifetime bound to that environment.
///
/// [reflection]: crate
/// [`ReflectFn`]: crate::func::ReflectFn
/// [module-level documentation]: crate::func
/// [derive macro]: derive@crate::Reflect
/// [unconstrained type parameters]: https://doc.rust-lang.org/error_codes/E0207.html
pub trait ReflectFnMut<'env, Marker> {
/// Call the function with the given arguments and return the result.
fn reflect_call_mut<'a>(&mut self, args: ArgList<'a>) -> FunctionResult<'a>;
}
/// Helper macro for implementing [`ReflectFnMut`] on Rust functions.
///
/// This currently implements it for the following signatures (where `argX` may be any of `T`, `&T`, or `&mut T`):
/// - `FnMut(arg0, arg1, ..., argN) -> R`
/// - `FnMut(&Receiver, arg0, arg1, ..., argN) -> &R`
/// - `FnMut(&mut Receiver, arg0, arg1, ..., argN) -> &mut R`
/// - `FnMut(&mut Receiver, arg0, arg1, ..., argN) -> &R`
macro_rules! impl_reflect_fn_mut {
($(($Arg:ident, $arg:ident)),*) => {
// === (...) -> ReturnType === //
impl<'env, $($Arg,)* ReturnType, Function> ReflectFnMut<'env, fn($($Arg),*) -> [ReturnType]> for Function
where
$($Arg: FromArg,)*
// This clause allows us to convert `ReturnType` into `Return`
ReturnType: IntoReturn + Reflect,
Function: FnMut($($Arg),*) -> ReturnType + 'env,
// This clause essentially asserts that `Arg::This` is the same type as `Arg`
Function: for<'a> FnMut($($Arg::This<'a>),*) -> ReturnType + 'env,
{
#[expect(
clippy::allow_attributes,
reason = "This lint is part of a macro, which may not always trigger the `unused_mut` lint."
)]
#[allow(
unused_mut,
reason = "Some invocations of this macro may trigger the `unused_mut` lint, where others won't."
)]
fn reflect_call_mut<'a>(&mut self, mut args: ArgList<'a>) -> FunctionResult<'a> {
const COUNT: usize = count_tokens!($($Arg)*);
if args.len() != COUNT {
return Err(FunctionError::ArgCountMismatch {
expected: ArgCount::new(COUNT).unwrap(),
received: args.len(),
});
}
// Extract all arguments (in order)
$(let $arg = args.take::<$Arg>()?;)*
Ok((self)($($arg,)*).into_return())
}
}
// === (&self, ...) -> &ReturnType === //
impl<'env, Receiver, $($Arg,)* ReturnType, Function> ReflectFnMut<'env, fn(&Receiver, $($Arg),*) -> &ReturnType> for Function
where
Receiver: Reflect + TypePath,
$($Arg: FromArg,)*
ReturnType: Reflect,
// This clause allows us to convert `&ReturnType` into `Return`
for<'a> &'a ReturnType: IntoReturn,
Function: for<'a> FnMut(&'a Receiver, $($Arg),*) -> &'a ReturnType + 'env,
// This clause essentially asserts that `Arg::This` is the same type as `Arg`
Function: for<'a> FnMut(&'a Receiver, $($Arg::This<'a>),*) -> &'a ReturnType + 'env,
{
fn reflect_call_mut<'a>(&mut self, mut args: ArgList<'a>) -> FunctionResult<'a> {
const COUNT: usize = count_tokens!(Receiver $($Arg)*);
if args.len() != COUNT {
return Err(FunctionError::ArgCountMismatch {
expected: ArgCount::new(COUNT).unwrap(),
received: args.len(),
});
}
// Extract all arguments (in order)
let receiver = args.take_ref::<Receiver>()?;
$(let $arg = args.take::<$Arg>()?;)*
Ok((self)(receiver, $($arg,)*).into_return())
}
}
// === (&mut self, ...) -> &mut ReturnType === //
impl<'env, Receiver, $($Arg,)* ReturnType, Function> ReflectFnMut<'env, fn(&mut Receiver, $($Arg),*) -> &mut ReturnType> for Function
where
Receiver: Reflect + TypePath,
$($Arg: FromArg,)*
ReturnType: Reflect,
// This clause allows us to convert `&mut ReturnType` into `Return`
for<'a> &'a mut ReturnType: IntoReturn,
Function: for<'a> FnMut(&'a mut Receiver, $($Arg),*) -> &'a mut ReturnType + 'env,
// This clause essentially asserts that `Arg::This` is the same type as `Arg`
Function: for<'a> FnMut(&'a mut Receiver, $($Arg::This<'a>),*) -> &'a mut ReturnType + 'env,
{
fn reflect_call_mut<'a>(&mut self, mut args: ArgList<'a>) -> FunctionResult<'a> {
const COUNT: usize = count_tokens!(Receiver $($Arg)*);
if args.len() != COUNT {
return Err(FunctionError::ArgCountMismatch {
expected: ArgCount::new(COUNT).unwrap(),
received: args.len(),
});
}
// Extract all arguments (in order)
let receiver = args.take_mut::<Receiver>()?;
$(let $arg = args.take::<$Arg>()?;)*
Ok((self)(receiver, $($arg,)*).into_return())
}
}
// === (&mut self, ...) -> &ReturnType === //
impl<'env, Receiver, $($Arg,)* ReturnType, Function> ReflectFnMut<'env, fn(&mut Receiver, $($Arg),*) -> &ReturnType> for Function
where
Receiver: Reflect + TypePath,
$($Arg: FromArg,)*
ReturnType: Reflect,
// This clause allows us to convert `&ReturnType` into `Return`
for<'a> &'a ReturnType: IntoReturn,
Function: for<'a> FnMut(&'a mut Receiver, $($Arg),*) -> &'a ReturnType + 'env,
// This clause essentially asserts that `Arg::This` is the same type as `Arg`
Function: for<'a> FnMut(&'a mut Receiver, $($Arg::This<'a>),*) -> &'a ReturnType + 'env,
{
fn reflect_call_mut<'a>(&mut self, mut args: ArgList<'a>) -> FunctionResult<'a> {
const COUNT: usize = count_tokens!(Receiver $($Arg)*);
if args.len() != COUNT {
return Err(FunctionError::ArgCountMismatch {
expected: ArgCount::new(COUNT).unwrap(),
received: args.len(),
});
}
// Extract all arguments (in order)
let receiver = args.take_mut::<Receiver>()?;
$(let $arg = args.take::<$Arg>()?;)*
Ok((self)(receiver, $($arg,)*).into_return())
}
}
};
}
all_tuples!(impl_reflect_fn_mut, 0, 15, Arg, arg);
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/func/reflect_fn.rs | crates/bevy_reflect/src/func/reflect_fn.rs | use variadics_please::all_tuples;
use crate::{
func::{
args::{ArgCount, FromArg},
macros::count_tokens,
ArgList, FunctionError, FunctionResult, IntoReturn, ReflectFnMut,
},
Reflect, TypePath,
};
/// A reflection-based version of the [`Fn`] trait.
///
/// This allows functions to be called dynamically through [reflection].
///
/// # Blanket Implementation
///
/// This trait has a blanket implementation that covers:
/// - Functions and methods defined with the `fn` keyword
/// - Anonymous functions
/// - Function pointers
/// - Closures that capture immutable references to their environment
/// - Closures that take ownership of captured variables
///
/// For each of the above cases, the function signature may only have up to 15 arguments,
/// not including an optional receiver argument (often `&self` or `&mut self`).
/// This optional receiver argument may be either a mutable or immutable reference to a type.
/// If the return type is also a reference, its lifetime will be bound to the lifetime of this receiver.
///
/// See the [module-level documentation] for more information on valid signatures.
///
/// To handle functions that capture mutable references to their environment,
/// see the [`ReflectFnMut`] trait instead.
///
/// Arguments are expected to implement [`FromArg`], and the return type is expected to implement [`IntoReturn`].
/// Both of these traits are automatically implemented when using the `Reflect` [derive macro].
///
/// # Example
///
/// ```
/// # use bevy_reflect::func::{ArgList, FunctionInfo, ReflectFn};
/// #
/// fn add(a: i32, b: i32) -> i32 {
/// a + b
/// }
///
/// let args = ArgList::new().with_owned(25_i32).with_owned(75_i32);
///
/// let value = add.reflect_call(args).unwrap().unwrap_owned();
/// assert_eq!(value.try_take::<i32>().unwrap(), 100);
/// ```
///
/// # Trait Parameters
///
/// This trait has a `Marker` type parameter that is used to get around issues with
/// [unconstrained type parameters] when defining impls with generic arguments or return types.
/// This `Marker` can be any type, provided it doesn't conflict with other implementations.
///
/// Additionally, it has a lifetime parameter, `'env`, that is used to bound the lifetime of the function.
/// For named functions and some closures, this will end up just being `'static`,
/// however, closures that borrow from their environment will have a lifetime bound to that environment.
///
/// [reflection]: crate
/// [module-level documentation]: crate::func
/// [derive macro]: derive@crate::Reflect
/// [unconstrained type parameters]: https://doc.rust-lang.org/error_codes/E0207.html
pub trait ReflectFn<'env, Marker>: ReflectFnMut<'env, Marker> {
/// Call the function with the given arguments and return the result.
fn reflect_call<'a>(&self, args: ArgList<'a>) -> FunctionResult<'a>;
}
/// Helper macro for implementing [`ReflectFn`] on Rust functions.
///
/// This currently implements it for the following signatures (where `argX` may be any of `T`, `&T`, or `&mut T`):
/// - `Fn(arg0, arg1, ..., argN) -> R`
/// - `Fn(&Receiver, arg0, arg1, ..., argN) -> &R`
/// - `Fn(&mut Receiver, arg0, arg1, ..., argN) -> &mut R`
/// - `Fn(&mut Receiver, arg0, arg1, ..., argN) -> &R`
macro_rules! impl_reflect_fn {
($(($Arg:ident, $arg:ident)),*) => {
// === (...) -> ReturnType === //
impl<'env, $($Arg,)* ReturnType, Function> ReflectFn<'env, fn($($Arg),*) -> [ReturnType]> for Function
where
$($Arg: FromArg,)*
// This clause allows us to convert `ReturnType` into `Return`
ReturnType: IntoReturn + Reflect,
Function: Fn($($Arg),*) -> ReturnType + 'env,
// This clause essentially asserts that `Arg::This` is the same type as `Arg`
Function: for<'a> Fn($($Arg::This<'a>),*) -> ReturnType + 'env,
{
#[expect(
clippy::allow_attributes,
reason = "This lint is part of a macro, which may not always trigger the `unused_mut` lint."
)]
#[allow(
unused_mut,
reason = "Some invocations of this macro may trigger the `unused_mut` lint, where others won't."
)]
fn reflect_call<'a>(&self, mut args: ArgList<'a>) -> FunctionResult<'a> {
const COUNT: usize = count_tokens!($($Arg)*);
if args.len() != COUNT {
return Err(FunctionError::ArgCountMismatch {
expected: ArgCount::new(COUNT).unwrap(),
received: args.len(),
});
}
// Extract all arguments (in order)
$(let $arg = args.take::<$Arg>()?;)*
Ok((self)($($arg,)*).into_return())
}
}
// === (&self, ...) -> &ReturnType === //
impl<'env, Receiver, $($Arg,)* ReturnType, Function> ReflectFn<'env, fn(&Receiver, $($Arg),*) -> &ReturnType> for Function
where
Receiver: Reflect + TypePath,
$($Arg: FromArg,)*
ReturnType: Reflect,
// This clause allows us to convert `&ReturnType` into `Return`
for<'a> &'a ReturnType: IntoReturn,
Function: for<'a> Fn(&'a Receiver, $($Arg),*) -> &'a ReturnType + 'env,
// This clause essentially asserts that `Arg::This` is the same type as `Arg`
Function: for<'a> Fn(&'a Receiver, $($Arg::This<'a>),*) -> &'a ReturnType + 'env,
{
fn reflect_call<'a>(&self, mut args: ArgList<'a>) -> FunctionResult<'a> {
const COUNT: usize = count_tokens!(Receiver $($Arg)*);
if args.len() != COUNT {
return Err(FunctionError::ArgCountMismatch {
expected: ArgCount::new(COUNT).unwrap(),
received: args.len(),
});
}
// Extract all arguments (in order)
let receiver = args.take_ref::<Receiver>()?;
$(let $arg = args.take::<$Arg>()?;)*
Ok((self)(receiver, $($arg,)*).into_return())
}
}
// === (&mut self, ...) -> &mut ReturnType === //
impl<'env, Receiver, $($Arg,)* ReturnType, Function> ReflectFn<'env, fn(&mut Receiver, $($Arg),*) -> &mut ReturnType> for Function
where
Receiver: Reflect + TypePath,
$($Arg: FromArg,)*
ReturnType: Reflect,
// This clause allows us to convert `&mut ReturnType` into `Return`
for<'a> &'a mut ReturnType: IntoReturn,
Function: for<'a> Fn(&'a mut Receiver, $($Arg),*) -> &'a mut ReturnType + 'env,
// This clause essentially asserts that `Arg::This` is the same type as `Arg`
Function: for<'a> Fn(&'a mut Receiver, $($Arg::This<'a>),*) -> &'a mut ReturnType + 'env,
{
fn reflect_call<'a>(&self, mut args: ArgList<'a>) -> FunctionResult<'a> {
const COUNT: usize = count_tokens!(Receiver $($Arg)*);
if args.len() != COUNT {
return Err(FunctionError::ArgCountMismatch {
expected: ArgCount::new(COUNT).unwrap(),
received: args.len(),
});
}
// Extract all arguments (in order)
let receiver = args.take_mut::<Receiver>()?;
$(let $arg = args.take::<$Arg>()?;)*
Ok((self)(receiver, $($arg,)*).into_return())
}
}
// === (&mut self, ...) -> &ReturnType === //
impl<'env, Receiver, $($Arg,)* ReturnType, Function> ReflectFn<'env, fn(&mut Receiver, $($Arg),*) -> &ReturnType> for Function
where
Receiver: Reflect + TypePath,
$($Arg: FromArg,)*
ReturnType: Reflect,
// This clause allows us to convert `&ReturnType` into `Return`
for<'a> &'a ReturnType: IntoReturn,
Function: for<'a> Fn(&'a mut Receiver, $($Arg),*) -> &'a ReturnType + 'env,
// This clause essentially asserts that `Arg::This` is the same type as `Arg`
Function: for<'a> Fn(&'a mut Receiver, $($Arg::This<'a>),*) -> &'a ReturnType + 'env,
{
fn reflect_call<'a>(&self, mut args: ArgList<'a>) -> FunctionResult<'a> {
const COUNT: usize = count_tokens!(Receiver $($Arg)*);
if args.len() != COUNT {
return Err(FunctionError::ArgCountMismatch {
expected: ArgCount::new(COUNT).unwrap(),
received: args.len(),
});
}
// Extract all arguments (in order)
let receiver = args.take_mut::<Receiver>()?;
$(let $arg = args.take::<$Arg>()?;)*
Ok((self)(receiver, $($arg,)*).into_return())
}
}
};
}
all_tuples!(impl_reflect_fn, 0, 15, Arg, arg);
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/func/dynamic_function_internal.rs | crates/bevy_reflect/src/func/dynamic_function_internal.rs | use crate::func::args::ArgCount;
use crate::func::signature::{ArgListSignature, ArgumentSignature};
use crate::func::{ArgList, FunctionError, FunctionInfo, FunctionOverloadError};
use alloc::{borrow::Cow, vec, vec::Vec};
use bevy_platform::collections::HashMap;
use core::fmt::{Debug, Formatter};
/// An internal structure for storing a function and its corresponding [function information].
///
/// This is used to facilitate the sharing of functionality between [`DynamicFunction`]
/// and [`DynamicFunctionMut`].
///
/// [function information]: FunctionInfo
/// [`DynamicFunction`]: crate::func::DynamicFunction
/// [`DynamicFunctionMut`]: crate::func::DynamicFunctionMut
#[derive(Clone)]
pub(super) struct DynamicFunctionInternal<F> {
functions: Vec<F>,
info: FunctionInfo,
arg_map: HashMap<ArgumentSignature, usize>,
}
impl<F> DynamicFunctionInternal<F> {
/// Create a new instance of [`DynamicFunctionInternal`] with the given function
/// and its corresponding information.
pub fn new(func: F, info: FunctionInfo) -> Self {
let arg_map = info
.signatures()
.iter()
.map(|sig| (ArgumentSignature::from(sig), 0))
.collect();
Self {
functions: vec![func],
info,
arg_map,
}
}
pub fn with_name(mut self, name: impl Into<Cow<'static, str>>) -> Self {
self.info = self.info.with_name(Some(name.into()));
self
}
/// The name of the function.
pub fn name(&self) -> Option<&Cow<'static, str>> {
self.info.name()
}
/// Returns `true` if the function is overloaded.
pub fn is_overloaded(&self) -> bool {
self.info.is_overloaded()
}
/// Get an immutable reference to the function.
///
/// If the function is not overloaded, it will always be returned regardless of the arguments.
/// Otherwise, the function will be selected based on the arguments provided.
///
/// If no overload matches the provided arguments, returns [`FunctionError::NoOverload`].
pub fn get(&self, args: &ArgList) -> Result<&F, FunctionError> {
if !self.info.is_overloaded() {
return Ok(&self.functions[0]);
}
let signature = ArgListSignature::from(args);
self.arg_map
.get(&signature)
.map(|index| &self.functions[*index])
.ok_or_else(|| FunctionError::NoOverload {
expected: self.arg_map.keys().cloned().collect(),
received: ArgumentSignature::from(args),
})
}
/// Get a mutable reference to the function.
///
/// If the function is not overloaded, it will always be returned regardless of the arguments.
/// Otherwise, the function will be selected based on the arguments provided.
///
/// If no overload matches the provided arguments, returns [`FunctionError::NoOverload`].
pub fn get_mut(&mut self, args: &ArgList) -> Result<&mut F, FunctionError> {
if !self.info.is_overloaded() {
return Ok(&mut self.functions[0]);
}
let signature = ArgListSignature::from(args);
self.arg_map
.get(&signature)
.map(|index| &mut self.functions[*index])
.ok_or_else(|| FunctionError::NoOverload {
expected: self.arg_map.keys().cloned().collect(),
received: ArgumentSignature::from(args),
})
}
/// Returns the function information contained in the map.
#[inline]
pub fn info(&self) -> &FunctionInfo {
&self.info
}
/// Returns the number of arguments the function expects.
///
/// For overloaded functions that can have a variable number of arguments,
/// this will contain the full set of counts for all signatures.
pub fn arg_count(&self) -> ArgCount {
self.info.arg_count()
}
/// Helper method for validating that a given set of arguments are _potentially_ valid for this function.
///
/// Currently, this validates:
/// - The number of arguments is within the expected range
pub fn validate_args(&self, args: &ArgList) -> Result<(), FunctionError> {
let expected_arg_count = self.arg_count();
let received_arg_count = args.len();
if !expected_arg_count.contains(received_arg_count) {
Err(FunctionError::ArgCountMismatch {
expected: expected_arg_count,
received: received_arg_count,
})
} else {
Ok(())
}
}
/// Merge another [`DynamicFunctionInternal`] into this one.
///
/// If `other` contains any functions with the same signature as this one,
/// an error will be returned along with the original, unchanged instance.
///
/// Therefore, this method should always return an overloaded function if the merge is successful.
///
/// Additionally, if the merge succeeds, it should be guaranteed that the order
/// of the functions in the map will be preserved.
/// For example, merging `[func_a, func_b]` (self) with `[func_c, func_d]` (other) should result in
/// `[func_a, func_b, func_c, func_d]`.
/// And merging `[func_c, func_d]` (self) with `[func_a, func_b]` (other) should result in
/// `[func_c, func_d, func_a, func_b]`.
pub fn merge(&mut self, mut other: Self) -> Result<(), FunctionOverloadError> {
// Keep a separate map of the new indices to avoid mutating the existing one
// until we can be sure the merge will be successful.
let mut new_signatures = <HashMap<_, _>>::default();
for (sig, index) in other.arg_map {
if self.arg_map.contains_key(&sig) {
return Err(FunctionOverloadError::DuplicateSignature(sig));
}
new_signatures.insert(sig, self.functions.len() + index);
}
self.arg_map.reserve(new_signatures.len());
for (sig, index) in new_signatures {
self.arg_map.insert(sig, index);
}
self.functions.append(&mut other.functions);
self.info.extend_unchecked(other.info);
Ok(())
}
/// Maps the internally stored function(s) from type `F` to type `G`.
pub fn map_functions<G>(self, f: fn(F) -> G) -> DynamicFunctionInternal<G> {
DynamicFunctionInternal {
functions: self.functions.into_iter().map(f).collect(),
info: self.info,
arg_map: self.arg_map,
}
}
}
impl<F> Debug for DynamicFunctionInternal<F> {
fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
self.info
.pretty_printer()
.include_fn_token()
.include_name()
.fmt(f)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::func::{FunctionInfo, SignatureInfo};
use crate::Type;
#[test]
fn should_merge_single_into_single() {
let mut func_a = DynamicFunctionInternal::new(
'a',
FunctionInfo::new(SignatureInfo::anonymous().with_arg::<i8>("arg0")),
);
let func_b = DynamicFunctionInternal::new(
'b',
FunctionInfo::new(SignatureInfo::anonymous().with_arg::<u8>("arg0")),
);
func_a.merge(func_b).unwrap();
assert_eq!(func_a.functions, vec!['a', 'b']);
assert_eq!(func_a.info.signatures().len(), 2);
assert_eq!(
func_a.arg_map,
HashMap::from_iter([
(ArgumentSignature::from_iter([Type::of::<i8>()]), 0),
(ArgumentSignature::from_iter([Type::of::<u8>()]), 1),
])
);
}
#[test]
fn should_merge_single_into_overloaded() {
let mut func_a = DynamicFunctionInternal::new(
'a',
FunctionInfo::new(SignatureInfo::anonymous().with_arg::<i8>("arg0")),
);
let func_b = DynamicFunctionInternal {
functions: vec!['b', 'c'],
info: FunctionInfo::new(SignatureInfo::anonymous().with_arg::<u8>("arg0"))
.with_overload(SignatureInfo::anonymous().with_arg::<u16>("arg0"))
.unwrap(),
arg_map: HashMap::from_iter([
(ArgumentSignature::from_iter([Type::of::<u8>()]), 0),
(ArgumentSignature::from_iter([Type::of::<u16>()]), 1),
]),
};
func_a.merge(func_b).unwrap();
assert_eq!(func_a.functions, vec!['a', 'b', 'c']);
assert_eq!(func_a.info.signatures().len(), 3);
assert_eq!(
func_a.arg_map,
HashMap::from_iter([
(ArgumentSignature::from_iter([Type::of::<i8>()]), 0),
(ArgumentSignature::from_iter([Type::of::<u8>()]), 1),
(ArgumentSignature::from_iter([Type::of::<u16>()]), 2),
])
);
}
#[test]
fn should_merge_overload_into_single() {
let mut func_a = DynamicFunctionInternal {
functions: vec!['a', 'b'],
info: FunctionInfo::new(SignatureInfo::anonymous().with_arg::<i8>("arg0"))
.with_overload(SignatureInfo::anonymous().with_arg::<i16>("arg0"))
.unwrap(),
arg_map: HashMap::from_iter([
(ArgumentSignature::from_iter([Type::of::<i8>()]), 0),
(ArgumentSignature::from_iter([Type::of::<i16>()]), 1),
]),
};
let func_b = DynamicFunctionInternal::new(
'c',
FunctionInfo::new(SignatureInfo::anonymous().with_arg::<u8>("arg0")),
);
func_a.merge(func_b).unwrap();
assert_eq!(func_a.functions, vec!['a', 'b', 'c']);
assert_eq!(func_a.info.signatures().len(), 3);
assert_eq!(
func_a.arg_map,
HashMap::from_iter([
(ArgumentSignature::from_iter([Type::of::<i8>()]), 0),
(ArgumentSignature::from_iter([Type::of::<i16>()]), 1),
(ArgumentSignature::from_iter([Type::of::<u8>()]), 2),
])
);
}
#[test]
fn should_merge_overloaded_into_overloaded() {
let mut func_a = DynamicFunctionInternal {
functions: vec!['a', 'b'],
info: FunctionInfo::new(SignatureInfo::anonymous().with_arg::<i8>("arg0"))
.with_overload(SignatureInfo::anonymous().with_arg::<i16>("arg0"))
.unwrap(),
arg_map: HashMap::from_iter([
(ArgumentSignature::from_iter([Type::of::<i8>()]), 0),
(ArgumentSignature::from_iter([Type::of::<i16>()]), 1),
]),
};
let func_b = DynamicFunctionInternal {
functions: vec!['c', 'd'],
info: FunctionInfo::new(SignatureInfo::anonymous().with_arg::<u8>("arg0"))
.with_overload(SignatureInfo::anonymous().with_arg::<u16>("arg0"))
.unwrap(),
arg_map: HashMap::from_iter([
(ArgumentSignature::from_iter([Type::of::<u8>()]), 0),
(ArgumentSignature::from_iter([Type::of::<u16>()]), 1),
]),
};
func_a.merge(func_b).unwrap();
assert_eq!(func_a.functions, vec!['a', 'b', 'c', 'd']);
assert_eq!(func_a.info.signatures().len(), 4);
assert_eq!(
func_a.arg_map,
HashMap::from_iter([
(ArgumentSignature::from_iter([Type::of::<i8>()]), 0),
(ArgumentSignature::from_iter([Type::of::<i16>()]), 1),
(ArgumentSignature::from_iter([Type::of::<u8>()]), 2),
(ArgumentSignature::from_iter([Type::of::<u16>()]), 3),
])
);
}
#[test]
fn should_return_error_on_duplicate_signature() {
let mut func_a = DynamicFunctionInternal::new(
'a',
FunctionInfo::new(
SignatureInfo::anonymous()
.with_arg::<i8>("arg0")
.with_arg::<i16>("arg1"),
),
);
let func_b = DynamicFunctionInternal {
functions: vec!['b', 'c'],
info: FunctionInfo::new(
SignatureInfo::anonymous()
.with_arg::<u8>("arg0")
.with_arg::<u16>("arg1"),
)
.with_overload(
SignatureInfo::anonymous()
.with_arg::<i8>("arg0")
.with_arg::<i16>("arg1"),
)
.unwrap(),
arg_map: HashMap::from_iter([
(
ArgumentSignature::from_iter([Type::of::<u8>(), Type::of::<u16>()]),
0,
),
(
ArgumentSignature::from_iter([Type::of::<i8>(), Type::of::<i16>()]),
1,
),
]),
};
let FunctionOverloadError::DuplicateSignature(duplicate) =
func_a.merge(func_b).unwrap_err()
else {
panic!("Expected `FunctionOverloadError::DuplicateSignature`");
};
assert_eq!(
duplicate,
ArgumentSignature::from_iter([Type::of::<i8>(), Type::of::<i16>()])
);
// Assert the original remains unchanged:
assert!(!func_a.is_overloaded());
assert_eq!(func_a.functions, vec!['a']);
assert_eq!(func_a.info.signatures().len(), 1);
assert_eq!(
func_a.arg_map,
HashMap::from_iter([(
ArgumentSignature::from_iter([Type::of::<i8>(), Type::of::<i16>()]),
0
),])
);
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/func/return_type.rs | crates/bevy_reflect/src/func/return_type.rs | use crate::PartialReflect;
use alloc::boxed::Box;
/// The return type of a [`DynamicFunction`] or [`DynamicFunctionMut`].
///
/// [`DynamicFunction`]: crate::func::DynamicFunction
/// [`DynamicFunctionMut`]: crate::func::DynamicFunctionMut
#[derive(Debug)]
pub enum Return<'a> {
/// The function returns an owned value.
///
/// This includes functions that return nothing (i.e. they return `()`).
Owned(Box<dyn PartialReflect>),
/// The function returns a reference to a value.
Ref(&'a dyn PartialReflect),
/// The function returns a mutable reference to a value.
Mut(&'a mut dyn PartialReflect),
}
impl<'a> Return<'a> {
/// Creates an [`Owned`](Self::Owned) unit (`()`) type.
pub fn unit() -> Self {
Self::Owned(Box::new(()))
}
/// Returns `true` if the return value is an [`Owned`](Self::Owned) unit (`()`) type.
pub fn is_unit(&self) -> bool {
match self {
Return::Owned(val) => val.represents::<()>(),
_ => false,
}
}
/// Unwraps the return value as an owned value.
///
/// # Panics
///
/// Panics if the return value is not [`Self::Owned`].
pub fn unwrap_owned(self) -> Box<dyn PartialReflect> {
match self {
Return::Owned(value) => value,
_ => panic!("expected owned value"),
}
}
/// Unwraps the return value as a reference to a value.
///
/// # Panics
///
/// Panics if the return value is not [`Self::Ref`].
pub fn unwrap_ref(self) -> &'a dyn PartialReflect {
match self {
Return::Ref(value) => value,
_ => panic!("expected reference value"),
}
}
/// Unwraps the return value as a mutable reference to a value.
///
/// # Panics
///
/// Panics if the return value is not [`Self::Mut`].
pub fn unwrap_mut(self) -> &'a mut dyn PartialReflect {
match self {
Return::Mut(value) => value,
_ => panic!("expected mutable reference value"),
}
}
}
/// A trait for types that can be converted into a [`Return`] value.
///
/// This trait exists so that types can be automatically converted into a [`Return`]
/// by [`ReflectFn`] and [`ReflectFnMut`].
///
/// This trait is used instead of a blanket [`Into`] implementation due to coherence issues:
/// we can't implement `Into<Return>` for both `T` and `&T`/`&mut T`.
///
/// This trait is automatically implemented for non-reference types when using the `Reflect`
/// [derive macro]. Blanket impls cover `&T` and `&mut T`.
///
/// [`ReflectFn`]: crate::func::ReflectFn
/// [`ReflectFnMut`]: crate::func::ReflectFnMut
/// [derive macro]: derive@crate::Reflect
pub trait IntoReturn {
/// Converts [`Self`] into a [`Return`] value.
fn into_return<'a>(self) -> Return<'a>
where
Self: 'a;
}
// Blanket impl.
impl<T: PartialReflect> IntoReturn for &'_ T {
fn into_return<'a>(self) -> Return<'a>
where
Self: 'a,
{
Return::Ref(self)
}
}
// Blanket impl.
impl<T: PartialReflect> IntoReturn for &'_ mut T {
fn into_return<'a>(self) -> Return<'a>
where
Self: 'a,
{
Return::Mut(self)
}
}
impl IntoReturn for () {
fn into_return<'a>(self) -> Return<'a> {
Return::unit()
}
}
/// Implements the [`IntoReturn`] trait for the given type.
///
/// This will implement it for `ty`, `&ty`, and `&mut ty`.
///
/// See [`impl_function_traits`] for details on syntax.
///
/// [`impl_function_traits`]: crate::func::macros::impl_function_traits
macro_rules! impl_into_return {
(
$ty: ty
$(;
< $($T: ident $(: $T1: tt $(+ $T2: tt)*)?),* >
)?
$(
[ $(const $N: ident : $size: ident),* ]
)?
$(
where $($U: ty $(: $U1: tt $(+ $U2: tt)*)?),*
)?
) => {
impl <
$($($T $(: $T1 $(+ $T2)*)?),*)?
$(, $(const $N : $size),*)?
> $crate::func::IntoReturn for $ty
$(
where $($U $(: $U1 $(+ $U2)*)?),*
)?
{
fn into_return<'into_return>(self) -> $crate::func::Return<'into_return>
where Self: 'into_return
{
$crate::func::Return::Owned(bevy_platform::prelude::Box::new(self))
}
}
};
}
pub(crate) use impl_into_return;
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/func/dynamic_function_mut.rs | crates/bevy_reflect/src/func/dynamic_function_mut.rs | use alloc::{borrow::Cow, boxed::Box};
use bevy_platform::sync::Arc;
use core::fmt::{Debug, Formatter};
use crate::func::{
args::{ArgCount, ArgList},
dynamic_function_internal::DynamicFunctionInternal,
DynamicFunction, FunctionInfo, FunctionOverloadError, FunctionResult, IntoFunctionMut,
};
/// A [`Box`] containing a callback to a reflected function.
type BoxFnMut<'env> = Box<dyn for<'a> FnMut(ArgList<'a>) -> FunctionResult<'a> + 'env>;
/// A dynamic representation of a function.
///
/// This type can be used to represent any callable that satisfies [`FnMut`]
/// (or the reflection-based equivalent, [`ReflectFnMut`]).
/// That is, any function or closure.
///
/// For functions that do not need to capture their environment mutably,
/// it's recommended to use [`DynamicFunction`] instead.
///
/// This type can be seen as a superset of [`DynamicFunction`].
///
/// See the [module-level documentation] for more information.
///
/// You will generally not need to construct this manually.
/// Instead, many functions and closures can be automatically converted using the [`IntoFunctionMut`] trait.
///
/// # Example
///
/// Most of the time, a [`DynamicFunctionMut`] can be created using the [`IntoFunctionMut`] trait:
///
/// ```
/// # use bevy_reflect::func::{ArgList, DynamicFunctionMut, FunctionInfo, IntoFunctionMut};
/// #
/// let mut list: Vec<i32> = vec![1, 2, 3];
///
/// // `replace` is a closure that captures a mutable reference to `list`
/// let mut replace = |index: usize, value: i32| -> i32 {
/// let old_value = list[index];
/// list[index] = value;
/// old_value
/// };
///
/// // Since this closure mutably borrows data, we can't convert it into a regular `DynamicFunction`,
/// // as doing so would result in a compile-time error:
/// // let mut func: DynamicFunction = replace.into_function();
///
/// // Instead, we convert it into a `DynamicFunctionMut` using `IntoFunctionMut::into_function_mut`:
/// let mut func: DynamicFunctionMut = replace.into_function_mut();
///
/// // Dynamically call it:
/// let args = ArgList::default().with_owned(1_usize).with_owned(-2_i32);
/// let value = func.call(args).unwrap().unwrap_owned();
///
/// // Check the result:
/// assert_eq!(value.try_take::<i32>().unwrap(), 2);
///
/// // Note that `func` still has a reference to `list`,
/// // so we need to drop it before we can access `list` again.
/// // Alternatively, we could have invoked `func` with
/// // `DynamicFunctionMut::call_once` to immediately consume it.
/// drop(func);
/// assert_eq!(list, vec![1, -2, 3]);
/// ```
///
/// [`ReflectFnMut`]: crate::func::ReflectFnMut
/// [module-level documentation]: crate::func
pub struct DynamicFunctionMut<'env> {
internal: DynamicFunctionInternal<BoxFnMut<'env>>,
}
impl<'env> DynamicFunctionMut<'env> {
/// Create a new [`DynamicFunctionMut`].
///
/// The given function can be used to call out to any other callable,
/// including functions, closures, or methods.
///
/// It's important that the function signature matches the provided [`FunctionInfo`].
/// as this will be used to validate arguments when [calling] the function.
/// This is also required in order for [function overloading] to work correctly.
///
/// # Panics
///
/// This function may panic for any of the following reasons:
/// - No [`SignatureInfo`] is provided.
/// - A provided [`SignatureInfo`] has more arguments than [`ArgCount::MAX_COUNT`].
/// - The conversion to [`FunctionInfo`] fails.
///
/// [calling]: crate::func::dynamic_function_mut::DynamicFunctionMut::call
/// [`SignatureInfo`]: crate::func::SignatureInfo
/// [function overloading]: Self::with_overload
pub fn new<F: for<'a> FnMut(ArgList<'a>) -> FunctionResult<'a> + 'env>(
func: F,
info: impl TryInto<FunctionInfo, Error: Debug>,
) -> Self {
Self {
internal: DynamicFunctionInternal::new(Box::new(func), info.try_into().unwrap()),
}
}
/// Set the name of the function.
///
/// For [`DynamicFunctionMuts`] created using [`IntoFunctionMut`],
/// the default name will always be the full path to the function as returned by [`core::any::type_name`],
/// unless the function is a closure, anonymous function, or function pointer,
/// in which case the name will be `None`.
///
/// [`DynamicFunctionMuts`]: DynamicFunctionMut
pub fn with_name(mut self, name: impl Into<Cow<'static, str>>) -> Self {
self.internal = self.internal.with_name(name);
self
}
/// Add an overload to this function.
///
/// Overloads allow a single [`DynamicFunctionMut`] to represent multiple functions of different signatures.
///
/// This can be used to handle multiple monomorphizations of a generic function
/// or to allow functions with a variable number of arguments.
///
/// Any functions with the same [argument signature] will be overwritten by the one from the new function, `F`.
/// For example, if the existing function had the signature `(i32, i32) -> i32`,
/// and the new function, `F`, also had the signature `(i32, i32) -> i32`,
/// the one from `F` would replace the one from the existing function.
///
/// Overloaded functions retain the [name] of the original function.
///
/// Note that it may be impossible to overload closures that mutably borrow from their environment
/// due to Rust's borrowing rules.
/// However, it's still possible to overload functions that do not capture their environment mutably,
/// or those that maintain mutually exclusive mutable references to their environment.
///
/// # Panics
///
/// Panics if the function, `F`, contains a signature already found in this function.
///
/// For a non-panicking version, see [`try_with_overload`].
///
/// # Example
///
/// ```
/// # use bevy_reflect::func::IntoFunctionMut;
/// let mut total_i32 = 0;
/// let mut add_i32 = |a: i32| total_i32 += a;
///
/// let mut total_f32 = 0.0;
/// let mut add_f32 = |a: f32| total_f32 += a;
///
/// // Currently, the only generic type `func` supports is `i32`.
/// let mut func = add_i32.into_function_mut();
///
/// // However, we can add an overload to handle `f32` as well:
/// func = func.with_overload(add_f32);
///
/// // Test `i32`:
/// let args = bevy_reflect::func::ArgList::new().with_owned(123_i32);
/// func.call(args).unwrap();
///
/// // Test `f32`:
/// let args = bevy_reflect::func::ArgList::new().with_owned(1.23_f32);
/// func.call(args).unwrap();
///
/// drop(func);
/// assert_eq!(total_i32, 123);
/// assert_eq!(total_f32, 1.23);
/// ```
///
/// [argument signature]: crate::func::signature::ArgumentSignature
/// [name]: Self::name
/// [`try_with_overload`]: Self::try_with_overload
pub fn with_overload<'a, F: IntoFunctionMut<'a, Marker>, Marker>(
self,
function: F,
) -> DynamicFunctionMut<'a>
where
'env: 'a,
{
self.try_with_overload(function).unwrap_or_else(|(_, err)| {
panic!("{}", err);
})
}
/// Attempt to add an overload to this function.
///
/// If the function, `F`, contains a signature already found in this function,
/// an error will be returned along with the original function.
///
/// For a panicking version, see [`with_overload`].
///
/// [`with_overload`]: Self::with_overload
pub fn try_with_overload<F: IntoFunctionMut<'env, Marker>, Marker>(
mut self,
function: F,
) -> Result<Self, (Box<Self>, FunctionOverloadError)> {
let function = function.into_function_mut();
match self.internal.merge(function.internal) {
Ok(_) => Ok(self),
Err(err) => Err((Box::new(self), err)),
}
}
/// Call the function with the given arguments.
///
/// Variables that are captured mutably by this function
/// won't be usable until this function is dropped.
/// Consider using [`call_once`] if you want to consume the function
/// immediately after calling it.
///
/// # Example
///
/// ```
/// # use bevy_reflect::func::{IntoFunctionMut, ArgList};
/// let mut total = 0;
/// let add = |a: i32, b: i32| -> i32 {
/// total = a + b;
/// total
/// };
///
/// let mut func = add.into_function_mut().with_name("add");
/// let args = ArgList::new().with_owned(25_i32).with_owned(75_i32);
/// let result = func.call(args).unwrap().unwrap_owned();
/// assert_eq!(result.try_take::<i32>().unwrap(), 100);
/// ```
///
/// # Errors
///
/// This method will return an error if the number of arguments provided does not match
/// the number of arguments expected by the function's [`FunctionInfo`].
///
/// The function itself may also return any errors it needs to.
///
/// [`call_once`]: DynamicFunctionMut::call_once
pub fn call<'a>(&mut self, args: ArgList<'a>) -> FunctionResult<'a> {
self.internal.validate_args(&args)?;
let func = self.internal.get_mut(&args)?;
func(args)
}
/// Call the function with the given arguments and consume it.
///
/// This is useful for functions that capture their environment mutably
/// because otherwise any captured variables would still be borrowed by it.
///
/// # Example
///
/// ```
/// # use bevy_reflect::func::{IntoFunctionMut, ArgList};
/// let mut count = 0;
/// let increment = |amount: i32| count += amount;
///
/// let increment_function = increment.into_function_mut();
/// let args = ArgList::new().with_owned(5_i32);
///
/// // We need to drop `increment_function` here so that we
/// // can regain access to `count`.
/// // `call_once` does this automatically for us.
/// increment_function.call_once(args).unwrap();
/// assert_eq!(count, 5);
/// ```
///
/// # Errors
///
/// This method will return an error if the number of arguments provided does not match
/// the number of arguments expected by the function's [`FunctionInfo`].
///
/// The function itself may also return any errors it needs to.
pub fn call_once(mut self, args: ArgList) -> FunctionResult {
self.call(args)
}
/// Returns the function info.
pub fn info(&self) -> &FunctionInfo {
self.internal.info()
}
/// The name of the function.
///
/// For [`DynamicFunctionMuts`] created using [`IntoFunctionMut`],
/// the default name will always be the full path to the function as returned by [`core::any::type_name`],
/// unless the function is a closure, anonymous function, or function pointer,
/// in which case the name will be `None`.
///
/// This can be overridden using [`with_name`].
///
/// [`DynamicFunctionMuts`]: DynamicFunctionMut
/// [`with_name`]: Self::with_name
pub fn name(&self) -> Option<&Cow<'static, str>> {
self.internal.name()
}
/// Returns `true` if the function is [overloaded].
///
/// # Example
///
/// ```
/// # use bevy_reflect::func::IntoFunctionMut;
/// let mut total_i32 = 0;
/// let increment = (|value: i32| total_i32 += value).into_function_mut();
/// assert!(!increment.is_overloaded());
///
/// let mut total_f32 = 0.0;
/// let increment = increment.with_overload(|value: f32| total_f32 += value);
/// assert!(increment.is_overloaded());
/// ```
///
/// [overloaded]: Self::with_overload
pub fn is_overloaded(&self) -> bool {
self.internal.is_overloaded()
}
/// Returns the number of arguments the function expects.
///
/// For [overloaded] functions that can have a variable number of arguments,
/// this will contain the full set of counts for all signatures.
///
/// # Example
///
/// ```
/// # use bevy_reflect::func::IntoFunctionMut;
/// let add = (|a: i32, b: i32| a + b).into_function_mut();
/// assert!(add.arg_count().contains(2));
///
/// let add = add.with_overload(|a: f32, b: f32, c: f32| a + b + c);
/// assert!(add.arg_count().contains(2));
/// assert!(add.arg_count().contains(3));
/// ```
///
/// [overloaded]: Self::with_overload
pub fn arg_count(&self) -> ArgCount {
self.internal.arg_count()
}
}
/// Outputs the function's signature.
///
/// This takes the format: `DynamicFunctionMut(fn {name}({arg1}: {type1}, {arg2}: {type2}, ...) -> {return_type})`.
///
/// Names for arguments and the function itself are optional and will default to `_` if not provided.
///
/// If the function is [overloaded], the output will include the signatures of all overloads as a set.
/// For example, `DynamicFunctionMut(fn add{(_: i32, _: i32) -> i32, (_: f32, _: f32) -> f32})`.
///
/// [overloaded]: DynamicFunctionMut::with_overload
impl<'env> Debug for DynamicFunctionMut<'env> {
fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
write!(f, "DynamicFunctionMut({:?})", &self.internal)
}
}
impl<'env> From<DynamicFunction<'env>> for DynamicFunctionMut<'env> {
#[inline]
fn from(function: DynamicFunction<'env>) -> Self {
Self {
internal: function.internal.map_functions(arc_to_box),
}
}
}
/// Helper function from converting an [`Arc`] function to a [`Box`] function.
///
/// This is needed to help the compiler infer the correct types.
fn arc_to_box<'env>(
f: Arc<dyn for<'a> Fn(ArgList<'a>) -> FunctionResult<'a> + Send + Sync + 'env>,
) -> BoxFnMut<'env> {
Box::new(move |args| f(args))
}
impl<'env> IntoFunctionMut<'env, ()> for DynamicFunctionMut<'env> {
#[inline]
fn into_function_mut(self) -> DynamicFunctionMut<'env> {
self
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::func::{FunctionError, IntoReturn, SignatureInfo};
use alloc::vec;
use core::ops::Add;
#[test]
fn should_overwrite_function_name() {
let mut total = 0;
let func = (|a: i32, b: i32| total = a + b).into_function_mut();
assert!(func.name().is_none());
let func = func.with_name("my_function");
assert_eq!(func.name().unwrap(), "my_function");
}
#[test]
fn should_convert_dynamic_function_mut_with_into_function() {
fn make_closure<'env, F: IntoFunctionMut<'env, M>, M>(f: F) -> DynamicFunctionMut<'env> {
f.into_function_mut()
}
let mut total = 0;
let closure: DynamicFunctionMut = make_closure(|a: i32, b: i32| total = a + b);
let _: DynamicFunctionMut = make_closure(closure);
}
#[test]
fn should_return_error_on_arg_count_mismatch() {
let mut total = 0;
let mut func = (|a: i32, b: i32| total = a + b).into_function_mut();
let args = ArgList::default().with_owned(25_i32);
let error = func.call(args).unwrap_err();
assert_eq!(
error,
FunctionError::ArgCountMismatch {
expected: ArgCount::new(2).unwrap(),
received: 1
}
);
let args = ArgList::default().with_owned(25_i32);
let error = func.call_once(args).unwrap_err();
assert_eq!(
error,
FunctionError::ArgCountMismatch {
expected: ArgCount::new(2).unwrap(),
received: 1
}
);
}
#[test]
fn should_allow_creating_manual_generic_dynamic_function_mut() {
let mut total = 0_i32;
let func = DynamicFunctionMut::new(
|mut args| {
let value = args.take_arg()?;
if value.is::<i32>() {
let value = value.take::<i32>()?;
total += value;
} else {
let value = value.take::<i16>()?;
total += value as i32;
}
Ok(().into_return())
},
vec![
SignatureInfo::named("add::<i32>").with_arg::<i32>("value"),
SignatureInfo::named("add::<i16>").with_arg::<i16>("value"),
],
);
assert_eq!(func.name().unwrap(), "add::<i32>");
let mut func = func.with_name("add");
assert_eq!(func.name().unwrap(), "add");
let args = ArgList::default().with_owned(25_i32);
func.call(args).unwrap();
let args = ArgList::default().with_owned(75_i16);
func.call(args).unwrap();
drop(func);
assert_eq!(total, 100);
}
// Closures that mutably borrow from their environment cannot realistically
// be overloaded since that would break Rust's borrowing rules.
// However, we still need to verify overloaded functions work since a
// `DynamicFunctionMut` can also be made from a non-mutably borrowing closure/function.
#[test]
fn should_allow_function_overloading() {
fn add<T: Add<Output = T>>(a: T, b: T) -> T {
a + b
}
let mut func = add::<i32>.into_function_mut().with_overload(add::<f32>);
let args = ArgList::default().with_owned(25_i32).with_owned(75_i32);
let result = func.call(args).unwrap().unwrap_owned();
assert_eq!(result.try_take::<i32>().unwrap(), 100);
let args = ArgList::default().with_owned(25.0_f32).with_owned(75.0_f32);
let result = func.call(args).unwrap().unwrap_owned();
assert_eq!(result.try_take::<f32>().unwrap(), 100.0);
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/func/into_function.rs | crates/bevy_reflect/src/func/into_function.rs | use crate::func::{DynamicFunction, ReflectFn, TypedFunction};
/// A trait for types that can be converted into a [`DynamicFunction`].
///
/// This trait is automatically implemented for any type that implements
/// [`ReflectFn`] and [`TypedFunction`].
///
/// See the [module-level documentation] for more information.
///
/// # Trait Parameters
///
/// This trait has a `Marker` type parameter that is used to get around issues with
/// [unconstrained type parameters] when defining impls with generic arguments or return types.
/// This `Marker` can be any type, provided it doesn't conflict with other implementations.
///
/// Additionally, it has a lifetime parameter, `'env`, that is used to bound the lifetime of the function.
/// For named functions and some closures, this will end up just being `'static`,
/// however, closures that borrow from their environment will have a lifetime bound to that environment.
///
/// [module-level documentation]: crate::func
/// [unconstrained type parameters]: https://doc.rust-lang.org/error_codes/E0207.html
pub trait IntoFunction<'env, Marker> {
/// Converts [`Self`] into a [`DynamicFunction`].
fn into_function(self) -> DynamicFunction<'env>;
}
impl<'env, F, Marker1, Marker2> IntoFunction<'env, (Marker1, Marker2)> for F
where
F: ReflectFn<'env, Marker1> + TypedFunction<Marker2> + Send + Sync + 'env,
{
fn into_function(self) -> DynamicFunction<'env> {
DynamicFunction::new(move |args| self.reflect_call(args), Self::function_info())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::func::ArgList;
#[test]
fn should_create_dynamic_function_from_closure() {
let c = 23;
let func = (|a: i32, b: i32| a + b + c).into_function();
let args = ArgList::new().with_owned(25_i32).with_owned(75_i32);
let result = func.call(args).unwrap().unwrap_owned();
assert_eq!(result.try_downcast_ref::<i32>(), Some(&123));
}
#[test]
fn should_create_dynamic_function_from_function() {
fn add(a: i32, b: i32) -> i32 {
a + b
}
let func = add.into_function();
let args = ArgList::new().with_owned(25_i32).with_owned(75_i32);
let result = func.call(args).unwrap().unwrap_owned();
assert_eq!(result.try_downcast_ref::<i32>(), Some(&100));
}
#[test]
fn should_default_closure_name_to_none() {
let c = 23;
let func = (|a: i32, b: i32| a + b + c).into_function();
assert!(func.name().is_none());
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/func/args/count.rs | crates/bevy_reflect/src/func/args/count.rs | use crate::func::args::ArgCountOutOfBoundsError;
use core::fmt::{Debug, Formatter};
/// A container for zero or more argument counts for a function.
///
/// For most functions, this will contain a single count,
/// however, overloaded functions may contain more.
///
/// # Maximum Argument Count
///
/// The maximum number of arguments that can be represented by this struct is 63,
/// as given by [`ArgCount::MAX_COUNT`].
/// The reason for this is that all counts are stored internally as a single `u64`
/// with each bit representing a specific count based on its bit index.
///
/// This allows for a smaller memory footprint and faster lookups compared to a
/// `HashSet` or `Vec` of possible counts.
/// It's also more appropriate for representing the argument counts of a function
/// given that most functions will not have more than a few arguments.
#[derive(Copy, Clone, PartialEq, Eq, Hash)]
pub struct ArgCount {
/// The bits representing the argument counts.
///
/// Each bit represents a specific count based on its bit index.
bits: u64,
/// The total number of argument counts.
len: u8,
}
impl ArgCount {
/// The maximum number of arguments that can be represented by this struct.
pub const MAX_COUNT: usize = u64::BITS as usize - 1;
/// Create a new [`ArgCount`] with the given count.
///
/// # Errors
///
/// Returns an error if the count is greater than [`Self::MAX_COUNT`].
pub fn new(count: usize) -> Result<Self, ArgCountOutOfBoundsError> {
Ok(Self {
bits: 1 << Self::try_to_u8(count)?,
len: 1,
})
}
/// Adds the given count to this [`ArgCount`].
///
/// # Panics
///
/// Panics if the count is greater than [`Self::MAX_COUNT`].
pub fn add(&mut self, count: usize) {
self.try_add(count).unwrap();
}
/// Attempts to add the given count to this [`ArgCount`].
///
/// # Errors
///
/// Returns an error if the count is greater than [`Self::MAX_COUNT`].
pub fn try_add(&mut self, count: usize) -> Result<(), ArgCountOutOfBoundsError> {
let count = Self::try_to_u8(count)?;
if !self.contains_unchecked(count) {
self.len += 1;
self.bits |= 1 << count;
}
Ok(())
}
/// Removes the given count from this [`ArgCount`].
pub fn remove(&mut self, count: usize) {
self.try_remove(count).unwrap();
}
/// Attempts to remove the given count from this [`ArgCount`].
///
/// # Errors
///
/// Returns an error if the count is greater than [`Self::MAX_COUNT`].
pub fn try_remove(&mut self, count: usize) -> Result<(), ArgCountOutOfBoundsError> {
let count = Self::try_to_u8(count)?;
if self.contains_unchecked(count) {
self.len -= 1;
self.bits &= !(1 << count);
}
Ok(())
}
/// Checks if this [`ArgCount`] contains the given count.
pub fn contains(&self, count: usize) -> bool {
count < usize::BITS as usize && (self.bits >> count) & 1 == 1
}
/// Returns the total number of argument counts that this [`ArgCount`] contains.
pub fn len(&self) -> usize {
self.len as usize
}
/// Returns true if this [`ArgCount`] contains no argument counts.
pub fn is_empty(&self) -> bool {
self.len == 0
}
/// Returns an iterator over the argument counts in this [`ArgCount`].
pub fn iter(&self) -> ArgCountIter {
ArgCountIter {
count: *self,
index: 0,
found: 0,
}
}
/// Checks if this [`ArgCount`] contains the given count without any bounds checking.
///
/// # Panics
///
/// Panics if the count is greater than [`Self::MAX_COUNT`].
fn contains_unchecked(&self, count: u8) -> bool {
(self.bits >> count) & 1 == 1
}
/// Attempts to convert the given count to a `u8` within the bounds of the [maximum count].
///
/// [maximum count]: Self::MAX_COUNT
fn try_to_u8(count: usize) -> Result<u8, ArgCountOutOfBoundsError> {
if count > Self::MAX_COUNT {
Err(ArgCountOutOfBoundsError(count))
} else {
Ok(count as u8)
}
}
}
/// Defaults this [`ArgCount`] to empty.
///
/// This means that it contains no argument counts, including zero.
impl Default for ArgCount {
fn default() -> Self {
Self { bits: 0, len: 0 }
}
}
impl Debug for ArgCount {
fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
f.debug_set().entries(self.iter()).finish()
}
}
/// An iterator for the argument counts in an [`ArgCount`].
pub struct ArgCountIter {
count: ArgCount,
index: u8,
found: u8,
}
impl Iterator for ArgCountIter {
type Item = usize;
fn next(&mut self) -> Option<Self::Item> {
loop {
if self.index as usize > ArgCount::MAX_COUNT {
return None;
}
if self.found == self.count.len {
// All counts have been found
return None;
}
if self.count.contains_unchecked(self.index) {
self.index += 1;
self.found += 1;
return Some(self.index as usize - 1);
}
self.index += 1;
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
(self.count.len(), Some(self.count.len()))
}
}
impl ExactSizeIterator for ArgCountIter {}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn should_default_to_empty() {
let count = ArgCount::default();
assert_eq!(count.len(), 0);
assert!(count.is_empty());
assert!(!count.contains(0));
}
#[test]
fn should_construct_with_count() {
let count = ArgCount::new(3).unwrap();
assert_eq!(count.len(), 1);
assert!(!count.is_empty());
assert!(count.contains(3));
}
#[test]
fn should_add_count() {
let mut count = ArgCount::default();
count.add(3);
assert_eq!(count.len(), 1);
assert!(count.contains(3));
}
#[test]
fn should_add_multiple_counts() {
let mut count = ArgCount::default();
count.add(3);
count.add(5);
count.add(7);
assert_eq!(count.len(), 3);
assert!(!count.contains(0));
assert!(!count.contains(1));
assert!(!count.contains(2));
assert!(count.contains(3));
assert!(count.contains(5));
assert!(count.contains(7));
}
#[test]
fn should_add_idempotently() {
let mut count = ArgCount::default();
count.add(3);
count.add(3);
assert_eq!(count.len(), 1);
assert!(count.contains(3));
}
#[test]
fn should_remove_count() {
let mut count = ArgCount::default();
count.add(3);
assert_eq!(count.len(), 1);
assert!(count.contains(3));
count.remove(3);
assert_eq!(count.len(), 0);
assert!(!count.contains(3));
}
#[test]
fn should_allow_removing_nonexistent_count() {
let mut count = ArgCount::default();
assert_eq!(count.len(), 0);
assert!(!count.contains(3));
count.remove(3);
assert_eq!(count.len(), 0);
assert!(!count.contains(3));
}
#[test]
fn should_iterate_over_counts() {
let mut count = ArgCount::default();
count.add(3);
count.add(5);
count.add(7);
let mut iter = count.iter();
assert_eq!(iter.len(), 3);
assert_eq!(iter.next(), Some(3));
assert_eq!(iter.next(), Some(5));
assert_eq!(iter.next(), Some(7));
assert_eq!(iter.next(), None);
}
#[test]
fn should_return_error_for_out_of_bounds_count() {
let count = ArgCount::new(64);
assert_eq!(count, Err(ArgCountOutOfBoundsError(64)));
let mut count = ArgCount::default();
assert_eq!(count.try_add(64), Err(ArgCountOutOfBoundsError(64)));
assert_eq!(count.try_remove(64), Err(ArgCountOutOfBoundsError(64)));
}
#[test]
fn should_return_false_for_out_of_bounds_contains() {
let count = ArgCount::default();
assert!(!count.contains(64));
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/func/args/list.rs | crates/bevy_reflect/src/func/args/list.rs | use crate::{
func::{
args::{Arg, ArgValue, FromArg},
ArgError,
},
PartialReflect, Reflect, TypePath,
};
use alloc::{
boxed::Box,
collections::vec_deque::{Iter, VecDeque},
};
/// A list of arguments that can be passed to a [`DynamicFunction`] or [`DynamicFunctionMut`].
///
/// # Example
///
/// ```
/// # use bevy_reflect::func::{ArgValue, ArgList};
/// let foo = 123;
/// let bar = 456;
/// let mut baz = 789;
/// let args = ArgList::new()
/// // Push an owned argument
/// .with_owned(foo)
/// // Push an owned and boxed argument
/// .with_boxed(Box::new(foo))
/// // Push a reference argument
/// .with_ref(&bar)
/// // Push a mutable reference argument
/// .with_mut(&mut baz)
/// // Push a manually constructed argument
/// .with_arg(ArgValue::Ref(&3.14));
/// ```
///
/// [arguments]: Arg
/// [`DynamicFunction`]: crate::func::DynamicFunction
/// [`DynamicFunctionMut`]: crate::func::DynamicFunctionMut
#[derive(Default, Debug)]
pub struct ArgList<'a> {
list: VecDeque<Arg<'a>>,
/// A flag that indicates if the list needs to be re-indexed.
///
/// This flag should be set when an argument is removed from the beginning of the list,
/// so that any future push operations will re-index the arguments.
needs_reindex: bool,
}
impl<'a> ArgList<'a> {
/// Create a new empty list of arguments.
pub fn new() -> Self {
Self {
list: VecDeque::new(),
needs_reindex: false,
}
}
/// Push an [`ArgValue`] onto the list.
///
/// If an argument was previously removed from the beginning of the list,
/// this method will also re-index the list.
pub fn push_arg(&mut self, arg: ArgValue<'a>) {
if self.needs_reindex {
for (index, arg) in self.list.iter_mut().enumerate() {
arg.set_index(index);
}
self.needs_reindex = false;
}
let index = self.list.len();
self.list.push_back(Arg::new(index, arg));
}
/// Push an [`ArgValue::Ref`] onto the list with the given reference.
///
/// If an argument was previously removed from the beginning of the list,
/// this method will also re-index the list.
pub fn push_ref(&mut self, arg: &'a dyn PartialReflect) {
self.push_arg(ArgValue::Ref(arg));
}
/// Push an [`ArgValue::Mut`] onto the list with the given mutable reference.
///
/// If an argument was previously removed from the beginning of the list,
/// this method will also re-index the list.
pub fn push_mut(&mut self, arg: &'a mut dyn PartialReflect) {
self.push_arg(ArgValue::Mut(arg));
}
/// Push an [`ArgValue::Owned`] onto the list with the given owned value.
///
/// If an argument was previously removed from the beginning of the list,
/// this method will also re-index the list.
pub fn push_owned(&mut self, arg: impl PartialReflect) {
self.push_arg(ArgValue::Owned(Box::new(arg)));
}
/// Push an [`ArgValue::Owned`] onto the list with the given boxed value.
///
/// If an argument was previously removed from the beginning of the list,
/// this method will also re-index the list.
pub fn push_boxed(&mut self, arg: Box<dyn PartialReflect>) {
self.push_arg(ArgValue::Owned(arg));
}
/// Push an [`ArgValue`] onto the list.
///
/// If an argument was previously removed from the beginning of the list,
/// this method will also re-index the list.
pub fn with_arg(mut self, arg: ArgValue<'a>) -> Self {
self.push_arg(arg);
self
}
/// Push an [`ArgValue::Ref`] onto the list with the given reference.
///
/// If an argument was previously removed from the beginning of the list,
/// this method will also re-index the list.
pub fn with_ref(self, arg: &'a dyn PartialReflect) -> Self {
self.with_arg(ArgValue::Ref(arg))
}
/// Push an [`ArgValue::Mut`] onto the list with the given mutable reference.
///
/// If an argument was previously removed from the beginning of the list,
/// this method will also re-index the list.
pub fn with_mut(self, arg: &'a mut dyn PartialReflect) -> Self {
self.with_arg(ArgValue::Mut(arg))
}
/// Push an [`ArgValue::Owned`] onto the list with the given owned value.
///
/// If an argument was previously removed from the beginning of the list,
/// this method will also re-index the list.
pub fn with_owned(self, arg: impl PartialReflect) -> Self {
self.with_arg(ArgValue::Owned(Box::new(arg)))
}
/// Push an [`ArgValue::Owned`] onto the list with the given boxed value.
///
/// If an argument was previously removed from the beginning of the list,
/// this method will also re-index the list.
pub fn with_boxed(self, arg: Box<dyn PartialReflect>) -> Self {
self.with_arg(ArgValue::Owned(arg))
}
/// Remove the first argument in the list and return it.
///
/// It's generally preferred to use [`Self::take`] instead of this method
/// as it provides a more ergonomic way to immediately downcast the argument.
pub fn take_arg(&mut self) -> Result<Arg<'a>, ArgError> {
self.needs_reindex = true;
self.list.pop_front().ok_or(ArgError::EmptyArgList)
}
/// Remove the first argument in the list and return `Ok(T::This)`.
///
/// If the list is empty or the [`FromArg::from_arg`] call fails, returns an error.
///
/// # Example
///
/// ```
/// # use bevy_reflect::func::ArgList;
/// let a = 1u32;
/// let b = 2u32;
/// let mut c = 3u32;
/// let mut args = ArgList::new().with_owned(a).with_ref(&b).with_mut(&mut c);
///
/// let a = args.take::<u32>().unwrap();
/// assert_eq!(a, 1);
///
/// let b = args.take::<&u32>().unwrap();
/// assert_eq!(*b, 2);
///
/// let c = args.take::<&mut u32>().unwrap();
/// assert_eq!(*c, 3);
/// ```
pub fn take<T: FromArg>(&mut self) -> Result<T::This<'a>, ArgError> {
self.take_arg()?.take::<T>()
}
/// Remove the first argument in the list and return `Ok(T)` if the argument is [`ArgValue::Owned`].
///
/// If the list is empty or the argument is not owned, returns an error.
///
/// It's generally preferred to use [`Self::take`] instead of this method.
///
/// # Example
///
/// ```
/// # use bevy_reflect::func::ArgList;
/// let value = 123u32;
/// let mut args = ArgList::new().with_owned(value);
/// let value = args.take_owned::<u32>().unwrap();
/// assert_eq!(value, 123);
/// ```
pub fn take_owned<T: Reflect + TypePath>(&mut self) -> Result<T, ArgError> {
self.take_arg()?.take_owned()
}
/// Remove the first argument in the list and return `Ok(&T)` if the argument is [`ArgValue::Ref`].
///
/// If the list is empty or the argument is not a reference, returns an error.
///
/// It's generally preferred to use [`Self::take`] instead of this method.
///
/// # Example
///
/// ```
/// # use bevy_reflect::func::ArgList;
/// let value = 123u32;
/// let mut args = ArgList::new().with_ref(&value);
/// let value = args.take_ref::<u32>().unwrap();
/// assert_eq!(*value, 123);
/// ```
pub fn take_ref<T: Reflect + TypePath>(&mut self) -> Result<&'a T, ArgError> {
self.take_arg()?.take_ref()
}
/// Remove the first argument in the list and return `Ok(&mut T)` if the argument is [`ArgValue::Mut`].
///
/// If the list is empty or the argument is not a mutable reference, returns an error.
///
/// It's generally preferred to use [`Self::take`] instead of this method.
///
/// # Example
///
/// ```
/// # use bevy_reflect::func::ArgList;
/// let mut value = 123u32;
/// let mut args = ArgList::new().with_mut(&mut value);
/// let value = args.take_mut::<u32>().unwrap();
/// assert_eq!(*value, 123);
/// ```
pub fn take_mut<T: Reflect + TypePath>(&mut self) -> Result<&'a mut T, ArgError> {
self.take_arg()?.take_mut()
}
/// Remove the last argument in the list and return it.
///
/// It's generally preferred to use [`Self::pop`] instead of this method
/// as it provides a more ergonomic way to immediately downcast the argument.
pub fn pop_arg(&mut self) -> Result<Arg<'a>, ArgError> {
self.list.pop_back().ok_or(ArgError::EmptyArgList)
}
/// Remove the last argument in the list and return `Ok(T::This)`.
///
/// If the list is empty or the [`FromArg::from_arg`] call fails, returns an error.
///
/// # Example
///
/// ```
/// # use bevy_reflect::func::ArgList;
/// let a = 1u32;
/// let b = 2u32;
/// let mut c = 3u32;
/// let mut args = ArgList::new().with_owned(a).with_ref(&b).with_mut(&mut c);
///
/// let c = args.pop::<&mut u32>().unwrap();
/// assert_eq!(*c, 3);
///
/// let b = args.pop::<&u32>().unwrap();
/// assert_eq!(*b, 2);
///
/// let a = args.pop::<u32>().unwrap();
/// assert_eq!(a, 1);
/// ```
pub fn pop<T: FromArg>(&mut self) -> Result<T::This<'a>, ArgError> {
self.pop_arg()?.take::<T>()
}
/// Remove the last argument in the list and return `Ok(T)` if the argument is [`ArgValue::Owned`].
///
/// If the list is empty or the argument is not owned, returns an error.
///
/// It's generally preferred to use [`Self::pop`] instead of this method.
///
/// # Example
///
/// ```
/// # use bevy_reflect::func::ArgList;
/// let value = 123u32;
/// let mut args = ArgList::new().with_owned(value);
/// let value = args.pop_owned::<u32>().unwrap();
/// assert_eq!(value, 123);
/// ```
pub fn pop_owned<T: Reflect + TypePath>(&mut self) -> Result<T, ArgError> {
self.pop_arg()?.take_owned()
}
/// Remove the last argument in the list and return `Ok(&T)` if the argument is [`ArgValue::Ref`].
///
/// If the list is empty or the argument is not a reference, returns an error.
///
/// It's generally preferred to use [`Self::pop`] instead of this method.
///
/// # Example
///
/// ```
/// # use bevy_reflect::func::ArgList;
/// let value = 123u32;
/// let mut args = ArgList::new().with_ref(&value);
/// let value = args.pop_ref::<u32>().unwrap();
/// assert_eq!(*value, 123);
/// ```
pub fn pop_ref<T: Reflect + TypePath>(&mut self) -> Result<&'a T, ArgError> {
self.pop_arg()?.take_ref()
}
/// Remove the last argument in the list and return `Ok(&mut T)` if the argument is [`ArgValue::Mut`].
///
/// If the list is empty or the argument is not a mutable reference, returns an error.
///
/// It's generally preferred to use [`Self::pop`] instead of this method.
///
/// # Example
///
/// ```
/// # use bevy_reflect::func::ArgList;
/// let mut value = 123u32;
/// let mut args = ArgList::new().with_mut(&mut value);
/// let value = args.pop_mut::<u32>().unwrap();
/// assert_eq!(*value, 123);
/// ```
pub fn pop_mut<T: Reflect + TypePath>(&mut self) -> Result<&'a mut T, ArgError> {
self.pop_arg()?.take_mut()
}
/// Returns an iterator over the arguments in the list.
pub fn iter(&self) -> Iter<'_, Arg<'a>> {
self.list.iter()
}
/// Returns the number of arguments in the list.
pub fn len(&self) -> usize {
self.list.len()
}
/// Returns `true` if the list of arguments is empty.
pub fn is_empty(&self) -> bool {
self.list.is_empty()
}
}
#[cfg(test)]
mod tests {
use super::*;
use alloc::string::String;
#[test]
fn should_push_arguments_in_order() {
let args = ArgList::new()
.with_owned(123)
.with_owned(456)
.with_owned(789);
assert_eq!(args.len(), 3);
assert_eq!(args.list[0].index(), 0);
assert_eq!(args.list[1].index(), 1);
assert_eq!(args.list[2].index(), 2);
}
#[test]
fn should_push_arg_with_correct_ownership() {
let a = String::from("a");
let b = String::from("b");
let mut c = String::from("c");
let d = String::from("d");
let e = String::from("e");
let f = String::from("f");
let mut g = String::from("g");
let args = ArgList::new()
.with_arg(ArgValue::Owned(Box::new(a)))
.with_arg(ArgValue::Ref(&b))
.with_arg(ArgValue::Mut(&mut c))
.with_owned(d)
.with_boxed(Box::new(e))
.with_ref(&f)
.with_mut(&mut g);
assert!(matches!(args.list[0].value(), &ArgValue::Owned(_)));
assert!(matches!(args.list[1].value(), &ArgValue::Ref(_)));
assert!(matches!(args.list[2].value(), &ArgValue::Mut(_)));
assert!(matches!(args.list[3].value(), &ArgValue::Owned(_)));
assert!(matches!(args.list[4].value(), &ArgValue::Owned(_)));
assert!(matches!(args.list[5].value(), &ArgValue::Ref(_)));
assert!(matches!(args.list[6].value(), &ArgValue::Mut(_)));
}
#[test]
fn should_take_args_in_order() {
let a = String::from("a");
let b = 123_i32;
let c = 456_usize;
let mut d = 5.78_f32;
let mut args = ArgList::new()
.with_owned(a)
.with_ref(&b)
.with_ref(&c)
.with_mut(&mut d);
assert_eq!(args.len(), 4);
assert_eq!(args.take_owned::<String>().unwrap(), String::from("a"));
assert_eq!(args.take::<&i32>().unwrap(), &123);
assert_eq!(args.take_ref::<usize>().unwrap(), &456);
assert_eq!(args.take_mut::<f32>().unwrap(), &mut 5.78);
assert_eq!(args.len(), 0);
}
#[test]
fn should_pop_args_in_reverse_order() {
let a = String::from("a");
let b = 123_i32;
let c = 456_usize;
let mut d = 5.78_f32;
let mut args = ArgList::new()
.with_owned(a)
.with_ref(&b)
.with_ref(&c)
.with_mut(&mut d);
assert_eq!(args.len(), 4);
assert_eq!(args.pop_mut::<f32>().unwrap(), &mut 5.78);
assert_eq!(args.pop_ref::<usize>().unwrap(), &456);
assert_eq!(args.pop::<&i32>().unwrap(), &123);
assert_eq!(args.pop_owned::<String>().unwrap(), String::from("a"));
assert_eq!(args.len(), 0);
}
#[test]
fn should_reindex_on_push_after_take() {
let mut args = ArgList::new()
.with_owned(123)
.with_owned(456)
.with_owned(789);
assert!(!args.needs_reindex);
args.take_arg().unwrap();
assert!(args.needs_reindex);
assert!(args.list[0].value().reflect_partial_eq(&456).unwrap());
assert_eq!(args.list[0].index(), 1);
assert!(args.list[1].value().reflect_partial_eq(&789).unwrap());
assert_eq!(args.list[1].index(), 2);
let args = args.with_owned(123);
assert!(!args.needs_reindex);
assert!(args.list[0].value().reflect_partial_eq(&456).unwrap());
assert_eq!(args.list[0].index(), 0);
assert!(args.list[1].value().reflect_partial_eq(&789).unwrap());
assert_eq!(args.list[1].index(), 1);
assert!(args.list[2].value().reflect_partial_eq(&123).unwrap());
assert_eq!(args.list[2].index(), 2);
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/func/args/from_arg.rs | crates/bevy_reflect/src/func/args/from_arg.rs | use crate::func::args::{Arg, ArgError};
use crate::{Reflect, TypePath};
/// A trait for types that can be created from an [`Arg`].
///
/// This trait exists so that types can be automatically converted into an [`Arg`]
/// so they can be put into an [`ArgList`] and passed to a [`DynamicFunction`] or
/// [`DynamicFunctionMut`].
///
/// This trait is used instead of a blanket [`From`] implementation due to coherence issues:
/// we can't implement `From<T>` for both `T` and `&T`/`&mut T`.
///
/// This trait is automatically implemented for non-reference types when using the `Reflect`
/// [derive macro]. Blanket impls cover `&T` and `&mut T`.
///
/// [`ArgList`]: crate::func::args::ArgList
/// [`DynamicFunction`]: crate::func::DynamicFunction
/// [`DynamicFunctionMut`]: crate::func::DynamicFunctionMut
/// [derive macro]: derive@crate::Reflect
pub trait FromArg {
/// The type to convert into.
///
/// This should almost always be the same as `Self`, but with the lifetime `'a`.
///
/// The reason we use a separate associated type is to allow for the lifetime
/// to be tied to the argument, rather than the type itself.
type This<'a>;
/// Creates an item from an argument.
///
/// The argument must be of the expected type and ownership.
fn from_arg(arg: Arg<'_>) -> Result<Self::This<'_>, ArgError>;
}
// Blanket impl.
impl<T: Reflect + TypePath> FromArg for &'static T {
type This<'a> = &'a T;
fn from_arg(arg: Arg<'_>) -> Result<Self::This<'_>, ArgError> {
arg.take_ref()
}
}
// Blanket impl.
impl<T: Reflect + TypePath> FromArg for &'static mut T {
type This<'a> = &'a mut T;
fn from_arg(arg: Arg<'_>) -> Result<Self::This<'_>, ArgError> {
arg.take_mut()
}
}
/// Implements the [`FromArg`] trait for the given type.
///
/// This will implement it for `$ty`, `&$ty`, and `&mut $ty`.
///
/// See [`impl_function_traits`] for details on syntax.
///
/// [`impl_function_traits`]: crate::func::macros::impl_function_traits
macro_rules! impl_from_arg {
(
$ty: ty
$(;
< $($T: ident $(: $T1: tt $(+ $T2: tt)*)?),* >
)?
$(
[ $(const $N: ident : $size: ident),* ]
)?
$(
where $($U: ty $(: $U1: tt $(+ $U2: tt)*)?),*
)?
) => {
impl <
$($($T $(: $T1 $(+ $T2)*)?),*)?
$(, $(const $N : $size),*)?
> $crate::func::args::FromArg for $ty
$(
where $($U $(: $U1 $(+ $U2)*)?),*
)?
{
type This<'from_arg> = $ty;
fn from_arg(arg: $crate::func::args::Arg<'_>) ->
Result<Self::This<'_>, $crate::func::args::ArgError>
{
arg.take_owned()
}
}
};
}
pub(crate) use impl_from_arg;
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/func/args/info.rs | crates/bevy_reflect/src/func/args/info.rs | use alloc::borrow::Cow;
use crate::{
func::args::{GetOwnership, Ownership},
type_info::impl_type_methods,
Type, TypePath,
};
/// Type information for an [`Arg`] used in a [`DynamicFunction`] or [`DynamicFunctionMut`].
///
/// [`Arg`]: crate::func::args::Arg
/// [`DynamicFunction`]: crate::func::DynamicFunction
/// [`DynamicFunctionMut`]: crate::func::DynamicFunctionMut
#[derive(Debug, Clone)]
pub struct ArgInfo {
/// The index of the argument within its function.
index: usize,
/// The name of the argument (if provided).
name: Option<Cow<'static, str>>,
/// The ownership of the argument.
ownership: Ownership,
/// The [type] of the argument.
///
/// [type]: Type
ty: Type,
}
impl ArgInfo {
/// Create a new [`ArgInfo`] with the given argument index and type `T`.
///
/// To set the name of the argument, use [`Self::with_name`].
pub fn new<T: TypePath + GetOwnership>(index: usize) -> Self {
Self {
index,
name: None,
ownership: T::ownership(),
ty: Type::of::<T>(),
}
}
/// Set the name of the argument.
///
/// Reflected arguments are not required to have a name and by default are not given one,
/// so this method must be called manually to set the name.
pub fn with_name(mut self, name: impl Into<Cow<'static, str>>) -> Self {
self.name = Some(name.into());
self
}
/// The index of the argument within its function.
pub fn index(&self) -> usize {
self.index
}
/// The name of the argument, if it was given one.
///
/// Note that this may return `None` even if the argument has a name.
/// This is because the name needs to be manually set using [`Self::with_name`]
/// since the name can't be inferred from the function type alone.
///
/// For [`DynamicFunctions`] created using [`IntoFunction`]
/// and [`DynamicFunctionMuts`] created using [`IntoFunctionMut`],
/// the name will always be `None`.
///
/// [`DynamicFunctions`]: crate::func::DynamicFunction
/// [`IntoFunction`]: crate::func::IntoFunction
/// [`DynamicFunctionMuts`]: crate::func::DynamicFunctionMut
/// [`IntoFunctionMut`]: crate::func::IntoFunctionMut
pub fn name(&self) -> Option<&str> {
self.name.as_deref()
}
/// The ownership of the argument.
pub fn ownership(&self) -> Ownership {
self.ownership
}
impl_type_methods!(ty);
/// Get an ID representing the argument.
///
/// This will return `ArgId::Name` if the argument has a name,
/// otherwise `ArgId::Index`.
pub fn id(&self) -> ArgId {
self.name
.clone()
.map(ArgId::Name)
.unwrap_or_else(|| ArgId::Index(self.index))
}
}
/// A representation of an argument.
///
/// This is primarily used for error reporting and debugging.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ArgId {
/// The index of the argument within its function.
Index(usize),
/// The name of the argument.
Name(Cow<'static, str>),
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/func/args/error.rs | crates/bevy_reflect/src/func/args/error.rs | use alloc::borrow::Cow;
use thiserror::Error;
use crate::func::args::Ownership;
/// An error that occurs when converting an [argument].
///
/// [argument]: crate::func::args::Arg
#[derive(Debug, Error, PartialEq)]
pub enum ArgError {
/// The argument is not the expected type.
#[error("expected `{expected}` but received `{received}` (@ argument index {index})")]
UnexpectedType {
/// Argument index.
index: usize,
/// Expected argument type path.
expected: Cow<'static, str>,
/// Received argument type path.
received: Cow<'static, str>,
},
/// The argument has the wrong ownership.
#[error("expected {expected} value but received {received} value (@ argument index {index})")]
InvalidOwnership {
/// Argument index.
index: usize,
/// Expected ownership.
expected: Ownership,
/// Received ownership.
received: Ownership,
},
/// Occurs when attempting to access an argument from an empty [`ArgList`].
///
/// [`ArgList`]: crate::func::args::ArgList
#[error("expected an argument but received none")]
EmptyArgList,
}
/// The given argument count is out of bounds.
#[derive(Debug, Error, PartialEq)]
#[error("argument count out of bounds: {0}")]
pub struct ArgCountOutOfBoundsError(pub usize);
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/func/args/arg.rs | crates/bevy_reflect/src/func/args/arg.rs | use crate::{
func::args::{ArgError, FromArg, Ownership},
PartialReflect, Reflect, TypePath,
};
use alloc::{boxed::Box, string::ToString};
use core::ops::Deref;
/// Represents an argument that can be passed to a [`DynamicFunction`] or [`DynamicFunctionMut`].
///
/// [`DynamicFunction`]: crate::func::DynamicFunction
/// [`DynamicFunctionMut`]: crate::func::DynamicFunctionMut
#[derive(Debug)]
pub struct Arg<'a> {
index: usize,
value: ArgValue<'a>,
}
impl<'a> Arg<'a> {
/// Create a new [`Arg`] with the given index and value.
pub fn new(index: usize, value: ArgValue<'a>) -> Self {
Self { index, value }
}
/// The index of the argument.
pub fn index(&self) -> usize {
self.index
}
/// Set the index of the argument.
pub(crate) fn set_index(&mut self, index: usize) {
self.index = index;
}
/// The value of the argument.
pub fn value(&self) -> &ArgValue<'a> {
&self.value
}
/// Take the value of the argument.
pub fn take_value(self) -> ArgValue<'a> {
self.value
}
/// Take the value of the argument and attempt to convert it to a concrete value, `T`.
///
/// This is a convenience method for calling [`FromArg::from_arg`] on the argument.
///
/// # Example
///
/// ```
/// # use bevy_reflect::func::ArgList;
/// let a = 1u32;
/// let b = 2u32;
/// let mut c = 3u32;
/// let mut args = ArgList::new().with_owned(a).with_ref(&b).with_mut(&mut c);
///
/// let a = args.take::<u32>().unwrap();
/// assert_eq!(a, 1);
///
/// let b = args.take::<&u32>().unwrap();
/// assert_eq!(*b, 2);
///
/// let c = args.take::<&mut u32>().unwrap();
/// assert_eq!(*c, 3);
/// ```
pub fn take<T: FromArg>(self) -> Result<T::This<'a>, ArgError> {
T::from_arg(self)
}
/// Returns `Ok(T)` if the argument is [`ArgValue::Owned`].
///
/// If the argument is not owned, returns an error.
///
/// It's generally preferred to use [`Self::take`] instead of this method.
///
/// # Example
///
/// ```
/// # use bevy_reflect::func::ArgList;
/// let value = 123u32;
/// let mut args = ArgList::new().with_owned(value);
/// let value = args.take_owned::<u32>().unwrap();
/// assert_eq!(value, 123);
/// ```
pub fn take_owned<T: Reflect + TypePath>(self) -> Result<T, ArgError> {
match self.value {
ArgValue::Owned(arg) => arg.try_take().map_err(|arg| ArgError::UnexpectedType {
index: self.index,
expected: alloc::borrow::Cow::Borrowed(T::type_path()),
received: alloc::borrow::Cow::Owned(arg.reflect_type_path().to_string()),
}),
ArgValue::Ref(_) => Err(ArgError::InvalidOwnership {
index: self.index,
expected: Ownership::Owned,
received: Ownership::Ref,
}),
ArgValue::Mut(_) => Err(ArgError::InvalidOwnership {
index: self.index,
expected: Ownership::Owned,
received: Ownership::Mut,
}),
}
}
/// Returns `Ok(&T)` if the argument is [`ArgValue::Ref`].
///
/// If the argument is not a reference, returns an error.
///
/// It's generally preferred to use [`Self::take`] instead of this method.
///
/// # Example
///
/// ```
/// # use bevy_reflect::func::ArgList;
/// let value = 123u32;
/// let mut args = ArgList::new().with_ref(&value);
/// let value = args.take_ref::<u32>().unwrap();
/// assert_eq!(*value, 123);
/// ```
pub fn take_ref<T: Reflect + TypePath>(self) -> Result<&'a T, ArgError> {
match self.value {
ArgValue::Owned(_) => Err(ArgError::InvalidOwnership {
index: self.index,
expected: Ownership::Ref,
received: Ownership::Owned,
}),
ArgValue::Ref(arg) => {
Ok(arg
.try_downcast_ref()
.ok_or_else(|| ArgError::UnexpectedType {
index: self.index,
expected: alloc::borrow::Cow::Borrowed(T::type_path()),
received: alloc::borrow::Cow::Owned(arg.reflect_type_path().to_string()),
})?)
}
ArgValue::Mut(_) => Err(ArgError::InvalidOwnership {
index: self.index,
expected: Ownership::Ref,
received: Ownership::Mut,
}),
}
}
/// Returns `Ok(&mut T)` if the argument is [`ArgValue::Mut`].
///
/// If the argument is not a mutable reference, returns an error.
///
/// It's generally preferred to use [`Self::take`] instead of this method.
///
/// # Example
///
/// ```
/// # use bevy_reflect::func::ArgList;
/// let mut value = 123u32;
/// let mut args = ArgList::new().with_mut(&mut value);
/// let value = args.take_mut::<u32>().unwrap();
/// assert_eq!(*value, 123);
/// ```
pub fn take_mut<T: Reflect + TypePath>(self) -> Result<&'a mut T, ArgError> {
match self.value {
ArgValue::Owned(_) => Err(ArgError::InvalidOwnership {
index: self.index,
expected: Ownership::Mut,
received: Ownership::Owned,
}),
ArgValue::Ref(_) => Err(ArgError::InvalidOwnership {
index: self.index,
expected: Ownership::Mut,
received: Ownership::Ref,
}),
ArgValue::Mut(arg) => {
let received = alloc::borrow::Cow::Owned(arg.reflect_type_path().to_string());
Ok(arg
.try_downcast_mut()
.ok_or_else(|| ArgError::UnexpectedType {
index: self.index,
expected: alloc::borrow::Cow::Borrowed(T::type_path()),
received,
})?)
}
}
}
/// Returns `true` if the argument is of type `T`.
pub fn is<T: TypePath>(&self) -> bool {
self.value
.try_as_reflect()
.map(<dyn Reflect>::is::<T>)
.unwrap_or_default()
}
}
/// Represents an argument that can be passed to a [`DynamicFunction`] or [`DynamicFunctionMut`].
///
/// [`DynamicFunction`]: crate::func::DynamicFunction
/// [`DynamicFunctionMut`]: crate::func::DynamicFunctionMut
#[derive(Debug)]
pub enum ArgValue<'a> {
/// An owned argument.
Owned(Box<dyn PartialReflect>),
/// An immutable reference argument.
Ref(&'a dyn PartialReflect),
/// A mutable reference argument.
Mut(&'a mut dyn PartialReflect),
}
impl<'a> Deref for ArgValue<'a> {
type Target = dyn PartialReflect;
fn deref(&self) -> &Self::Target {
match self {
ArgValue::Owned(arg) => arg.as_ref(),
ArgValue::Ref(arg) => *arg,
ArgValue::Mut(arg) => *arg,
}
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/func/args/mod.rs | crates/bevy_reflect/src/func/args/mod.rs | //! Argument types and utilities for working with [`DynamicFunction`] and [`DynamicFunctionMut`].
//!
//! [`DynamicFunction`]: crate::func::DynamicFunction
//! [`DynamicFunctionMut`]: crate::func::DynamicFunctionMut
pub use arg::*;
pub use count::*;
pub use error::*;
pub use from_arg::*;
pub use info::*;
pub use list::*;
pub use ownership::*;
mod arg;
mod count;
mod error;
mod from_arg;
mod info;
mod list;
mod ownership;
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/func/args/ownership.rs | crates/bevy_reflect/src/func/args/ownership.rs | use core::fmt::{Display, Formatter};
/// The ownership of a type.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum Ownership {
/// The type is a reference (i.e. `&T`).
Ref,
/// The type is a mutable reference (i.e. `&mut T`).
Mut,
/// The type is owned (i.e. `T`).
Owned,
}
impl Display for Ownership {
fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
match self {
Self::Ref => write!(f, "reference"),
Self::Mut => write!(f, "mutable reference"),
Self::Owned => write!(f, "owned"),
}
}
}
/// A trait for getting the ownership of a type.
///
/// This trait exists so that [`TypedFunction`] can automatically generate
/// [`FunctionInfo`] containing the proper [`Ownership`] for its [argument] types.
///
/// This trait is automatically implemented for non-reference types when using the `Reflect`
/// [derive macro]. Blanket impls cover `&T` and `&mut T`.
///
/// [`TypedFunction`]: crate::func::TypedFunction
/// [`FunctionInfo`]: crate::func::FunctionInfo
/// [argument]: crate::func::args::Arg
/// [derive macro]: derive@crate::Reflect
pub trait GetOwnership {
/// Returns the ownership of [`Self`].
fn ownership() -> Ownership {
Ownership::Owned
}
}
// Blanket impl.
impl<T> GetOwnership for &'_ T {
fn ownership() -> Ownership {
Ownership::Ref
}
}
// Blanket impl.
impl<T> GetOwnership for &'_ mut T {
fn ownership() -> Ownership {
Ownership::Mut
}
}
/// Implements the [`GetOwnership`] trait for the given type.
///
/// This will implement it for `$ty`, `&$ty`, and `&mut $ty`.
///
/// See [`impl_function_traits`] for details on syntax.
///
/// [`impl_function_traits`]: crate::func::macros::impl_function_traits
macro_rules! impl_get_ownership {
(
$ty: ty
$(;
< $($T: ident $(: $T1: tt $(+ $T2: tt)*)?),* >
)?
$(
[ $(const $N: ident : $size: ident),* ]
)?
$(
where $($U: ty $(: $U1: tt $(+ $U2: tt)*)?),*
)?
) => {
impl <
$($($T $(: $T1 $(+ $T2)*)?),*)?
$(, $(const $N : $size),*)?
> $crate::func::args::GetOwnership for $ty
$(
where $($U $(: $U1 $(+ $U2)*)?),*
)?
{}
};
}
pub(crate) use impl_get_ownership;
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/impls/foldhash.rs | crates/bevy_reflect/src/impls/foldhash.rs | use crate::impl_type_path;
impl_type_path!(::foldhash::fast::FoldHasher<'a>);
impl_type_path!(::foldhash::fast::FixedState);
impl_type_path!(::foldhash::fast::RandomState);
impl_type_path!(::foldhash::quality::FoldHasher<'a>);
impl_type_path!(::foldhash::quality::FixedState);
impl_type_path!(::foldhash::quality::RandomState);
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/impls/glam.rs | crates/bevy_reflect/src/impls/glam.rs | use crate::{std_traits::ReflectDefault, ReflectDeserialize, ReflectSerialize};
use assert_type_match::assert_type_match;
use bevy_reflect_derive::{impl_reflect, impl_reflect_opaque};
use glam::*;
/// Reflects the given foreign type as an enum and asserts that the variants/fields match up.
macro_rules! reflect_enum {
($(#[$meta:meta])* enum $ident:ident { $($ty:tt)* } ) => {
impl_reflect!($(#[$meta])* enum $ident { $($ty)* });
#[assert_type_match($ident, test_only)]
#[expect(
clippy::upper_case_acronyms,
reason = "The variants used are not acronyms."
)]
enum $ident { $($ty)* }
};
}
impl_reflect!(
#[reflect(Clone, Debug, Hash, PartialEq, Default, Deserialize, Serialize)]
#[type_path = "glam"]
struct IVec2 {
x: i32,
y: i32,
}
);
impl_reflect!(
#[reflect(Clone, Debug, Hash, PartialEq, Default, Deserialize, Serialize)]
#[type_path = "glam"]
struct IVec3 {
x: i32,
y: i32,
z: i32,
}
);
impl_reflect!(
#[reflect(Clone, Debug, Hash, PartialEq, Default, Deserialize, Serialize)]
#[type_path = "glam"]
struct IVec4 {
x: i32,
y: i32,
z: i32,
w: i32,
}
);
impl_reflect!(
#[reflect(Clone, Debug, Hash, PartialEq, Default, Deserialize, Serialize)]
#[type_path = "glam"]
struct I8Vec2 {
x: i8,
y: i8,
}
);
impl_reflect!(
#[reflect(Clone, Debug, Hash, PartialEq, Default, Deserialize, Serialize)]
#[type_path = "glam"]
struct I8Vec3 {
x: i8,
y: i8,
z: i8,
}
);
impl_reflect!(
#[reflect(Clone, Debug, Hash, PartialEq, Default, Deserialize, Serialize)]
#[type_path = "glam"]
struct I8Vec4 {
x: i8,
y: i8,
z: i8,
w: i8,
}
);
impl_reflect!(
#[reflect(Clone, Debug, Hash, PartialEq, Default, Deserialize, Serialize)]
#[type_path = "glam"]
struct I16Vec2 {
x: i16,
y: i16,
}
);
impl_reflect!(
#[reflect(Clone, Debug, Hash, PartialEq, Default, Deserialize, Serialize)]
#[type_path = "glam"]
struct I16Vec3 {
x: i16,
y: i16,
z: i16,
}
);
impl_reflect!(
#[reflect(Clone, Debug, Hash, PartialEq, Default, Deserialize, Serialize)]
#[type_path = "glam"]
struct I16Vec4 {
x: i16,
y: i16,
z: i16,
w: i16,
}
);
impl_reflect!(
#[reflect(Clone, Debug, Hash, PartialEq, Default, Deserialize, Serialize)]
#[type_path = "glam"]
struct I64Vec2 {
x: i64,
y: i64,
}
);
impl_reflect!(
#[reflect(Clone, Debug, Hash, PartialEq, Default, Deserialize, Serialize)]
#[type_path = "glam"]
struct I64Vec3 {
x: i64,
y: i64,
z: i64,
}
);
impl_reflect!(
#[reflect(Clone, Debug, Hash, PartialEq, Default, Deserialize, Serialize)]
#[type_path = "glam"]
struct I64Vec4 {
x: i64,
y: i64,
z: i64,
w: i64,
}
);
impl_reflect!(
#[reflect(Clone, Debug, Hash, PartialEq, Default, Deserialize, Serialize)]
#[type_path = "glam"]
struct UVec2 {
x: u32,
y: u32,
}
);
impl_reflect!(
#[reflect(Clone, Debug, Hash, PartialEq, Default, Deserialize, Serialize)]
#[type_path = "glam"]
struct UVec3 {
x: u32,
y: u32,
z: u32,
}
);
impl_reflect!(
#[reflect(Clone, Debug, Hash, PartialEq, Default, Deserialize, Serialize)]
#[type_path = "glam"]
struct UVec4 {
x: u32,
y: u32,
z: u32,
w: u32,
}
);
impl_reflect!(
#[reflect(Clone, Debug, Hash, PartialEq, Default, Deserialize, Serialize)]
#[type_path = "glam"]
struct U8Vec2 {
x: u8,
y: u8,
}
);
impl_reflect!(
#[reflect(Clone, Debug, Hash, PartialEq, Default, Deserialize, Serialize)]
#[type_path = "glam"]
struct U8Vec3 {
x: u8,
y: u8,
z: u8,
}
);
impl_reflect!(
#[reflect(Clone, Debug, Hash, PartialEq, Default, Deserialize, Serialize)]
#[type_path = "glam"]
struct U8Vec4 {
x: u8,
y: u8,
z: u8,
w: u8,
}
);
impl_reflect!(
#[reflect(Clone, Debug, Hash, PartialEq, Default, Deserialize, Serialize)]
#[type_path = "glam"]
struct U16Vec2 {
x: u16,
y: u16,
}
);
impl_reflect!(
#[reflect(Clone, Debug, Hash, PartialEq, Default, Deserialize, Serialize)]
#[type_path = "glam"]
struct U16Vec3 {
x: u16,
y: u16,
z: u16,
}
);
impl_reflect!(
#[reflect(Clone, Debug, Hash, PartialEq, Default, Deserialize, Serialize)]
#[type_path = "glam"]
struct U16Vec4 {
x: u16,
y: u16,
z: u16,
w: u16,
}
);
impl_reflect!(
#[reflect(Clone, Debug, Hash, PartialEq, Default, Deserialize, Serialize)]
#[type_path = "glam"]
struct U64Vec2 {
x: u64,
y: u64,
}
);
impl_reflect!(
#[reflect(Clone, Debug, Hash, PartialEq, Default, Deserialize, Serialize)]
#[type_path = "glam"]
struct U64Vec3 {
x: u64,
y: u64,
z: u64,
}
);
impl_reflect!(
#[reflect(Clone, Debug, Hash, PartialEq, Default, Deserialize, Serialize)]
#[type_path = "glam"]
struct U64Vec4 {
x: u64,
y: u64,
z: u64,
w: u64,
}
);
impl_reflect!(
#[reflect(Clone, Debug, PartialEq, Default, Deserialize, Serialize)]
#[type_path = "glam"]
struct Vec2 {
x: f32,
y: f32,
}
);
impl_reflect!(
#[reflect(Clone, Debug, PartialEq, Default, Deserialize, Serialize)]
#[type_path = "glam"]
struct Vec3 {
x: f32,
y: f32,
z: f32,
}
);
impl_reflect!(
#[reflect(Clone, Debug, PartialEq, Default, Deserialize, Serialize)]
#[type_path = "glam"]
struct Vec3A {
x: f32,
y: f32,
z: f32,
}
);
impl_reflect!(
#[reflect(Clone, Debug, PartialEq, Default, Deserialize, Serialize)]
#[type_path = "glam"]
struct Vec4 {
x: f32,
y: f32,
z: f32,
w: f32,
}
);
impl_reflect!(
#[reflect(Clone, Debug, PartialEq, Default, Deserialize, Serialize)]
#[type_path = "glam"]
struct BVec2 {
x: bool,
y: bool,
}
);
impl_reflect!(
#[reflect(Clone, Debug, PartialEq, Default, Deserialize, Serialize)]
#[type_path = "glam"]
struct BVec3 {
x: bool,
y: bool,
z: bool,
}
);
impl_reflect!(
#[reflect(Clone, Debug, PartialEq, Default, Deserialize, Serialize)]
#[type_path = "glam"]
struct BVec4 {
x: bool,
y: bool,
z: bool,
w: bool,
}
);
impl_reflect!(
#[reflect(Clone, Debug, PartialEq, Default, Deserialize, Serialize)]
#[type_path = "glam"]
struct DVec2 {
x: f64,
y: f64,
}
);
impl_reflect!(
#[reflect(Clone, Debug, PartialEq, Default, Deserialize, Serialize)]
#[type_path = "glam"]
struct DVec3 {
x: f64,
y: f64,
z: f64,
}
);
impl_reflect!(
#[reflect(Clone, Debug, PartialEq, Default, Deserialize, Serialize)]
#[type_path = "glam"]
struct DVec4 {
x: f64,
y: f64,
z: f64,
w: f64,
}
);
impl_reflect!(
#[reflect(Clone, Debug, PartialEq, Default, Deserialize, Serialize)]
#[type_path = "glam"]
struct Mat2 {
x_axis: Vec2,
y_axis: Vec2,
}
);
impl_reflect!(
#[reflect(Clone, Debug, PartialEq, Default, Deserialize, Serialize)]
#[type_path = "glam"]
struct Mat3 {
x_axis: Vec3,
y_axis: Vec3,
z_axis: Vec3,
}
);
impl_reflect!(
#[reflect(Clone, Debug, PartialEq, Default, Deserialize, Serialize)]
#[type_path = "glam"]
struct Mat3A {
x_axis: Vec3A,
y_axis: Vec3A,
z_axis: Vec3A,
}
);
impl_reflect!(
#[reflect(Clone, Debug, PartialEq, Default, Deserialize, Serialize)]
#[type_path = "glam"]
struct Mat4 {
x_axis: Vec4,
y_axis: Vec4,
z_axis: Vec4,
w_axis: Vec4,
}
);
impl_reflect!(
#[reflect(Clone, Debug, PartialEq, Default, Deserialize, Serialize)]
#[type_path = "glam"]
struct DMat2 {
x_axis: DVec2,
y_axis: DVec2,
}
);
impl_reflect!(
#[reflect(Clone, Debug, PartialEq, Default, Deserialize, Serialize)]
#[type_path = "glam"]
struct DMat3 {
x_axis: DVec3,
y_axis: DVec3,
z_axis: DVec3,
}
);
impl_reflect!(
#[reflect(Clone, Debug, PartialEq, Default, Deserialize, Serialize)]
#[type_path = "glam"]
struct DMat4 {
x_axis: DVec4,
y_axis: DVec4,
z_axis: DVec4,
w_axis: DVec4,
}
);
impl_reflect!(
#[reflect(Clone, Debug, PartialEq, Default, Deserialize, Serialize)]
#[type_path = "glam"]
struct Affine2 {
matrix2: Mat2,
translation: Vec2,
}
);
impl_reflect!(
#[reflect(Clone, Debug, PartialEq, Default, Deserialize, Serialize)]
#[type_path = "glam"]
struct Affine3A {
matrix3: Mat3A,
translation: Vec3A,
}
);
impl_reflect!(
#[reflect(Clone, Debug, PartialEq, Default, Deserialize, Serialize)]
#[type_path = "glam"]
struct DAffine2 {
matrix2: DMat2,
translation: DVec2,
}
);
impl_reflect!(
#[reflect(Clone, Debug, PartialEq, Default, Deserialize, Serialize)]
#[type_path = "glam"]
struct DAffine3 {
matrix3: DMat3,
translation: DVec3,
}
);
impl_reflect!(
#[reflect(Clone, Debug, PartialEq, Default, Deserialize, Serialize)]
#[type_path = "glam"]
struct Quat {
x: f32,
y: f32,
z: f32,
w: f32,
}
);
impl_reflect!(
#[reflect(Clone, Debug, PartialEq, Default, Deserialize, Serialize)]
#[type_path = "glam"]
struct DQuat {
x: f64,
y: f64,
z: f64,
w: f64,
}
);
reflect_enum!(
#[reflect(Clone, Debug, PartialEq, Default, Deserialize, Serialize)]
#[type_path = "glam"]
enum EulerRot {
ZYX,
ZXY,
YXZ,
YZX,
XYZ,
XZY,
ZYZ,
ZXZ,
YXY,
YZY,
XYX,
XZX,
ZYXEx,
ZXYEx,
YXZEx,
YZXEx,
XYZEx,
XZYEx,
ZYZEx,
ZXZEx,
YXYEx,
YZYEx,
XYXEx,
XZXEx,
}
);
impl_reflect_opaque!(::glam::BVec3A(
Clone,
Debug,
Default,
Deserialize,
Serialize
));
impl_reflect_opaque!(::glam::BVec4A(
Clone,
Debug,
Default,
Deserialize,
Serialize
));
#[cfg(test)]
mod tests {
use alloc::{format, string::String};
use ron::{
ser::{to_string_pretty, PrettyConfig},
Deserializer,
};
use serde::de::DeserializeSeed;
use static_assertions::assert_impl_all;
use crate::{
prelude::*,
serde::{ReflectDeserializer, ReflectSerializer},
Enum, GetTypeRegistration, TypeRegistry,
};
use super::*;
assert_impl_all!(EulerRot: Enum);
#[test]
fn euler_rot_serialization() {
let v = EulerRot::YXZ;
let mut registry = TypeRegistry::default();
registry.register::<EulerRot>();
let ser = ReflectSerializer::new(&v, ®istry);
let config = PrettyConfig::default()
.new_line(String::from("\n"))
.indentor(String::from(" "));
let output = to_string_pretty(&ser, config).unwrap();
let expected = r#"
{
"glam::EulerRot": YXZ,
}"#;
assert_eq!(expected, format!("\n{output}"));
}
#[test]
fn euler_rot_deserialization() {
let data = r#"
{
"glam::EulerRot": XZY,
}"#;
let mut registry = TypeRegistry::default();
registry.add_registration(EulerRot::get_type_registration());
let de = ReflectDeserializer::new(®istry);
let mut deserializer =
Deserializer::from_str(data).expect("Failed to acquire deserializer");
let dynamic_struct = de
.deserialize(&mut deserializer)
.expect("Failed to deserialize");
let mut result = EulerRot::default();
result.apply(dynamic_struct.as_partial_reflect());
assert_eq!(result, EulerRot::XZY);
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/impls/indexmap.rs | crates/bevy_reflect/src/impls/indexmap.rs | use crate::{
utility::GenericTypeInfoCell, FromReflect, FromType, Generics, GetTypeRegistration,
PartialReflect, Reflect, ReflectCloneError, ReflectFromPtr, ReflectMut, ReflectOwned,
ReflectRef, Set, SetInfo, TypeInfo, TypeParamInfo, TypePath, TypeRegistration,
};
use bevy_platform::prelude::{Box, Vec};
use bevy_reflect::{
DynamicMap, Map, MapInfo, MaybeTyped, ReflectFromReflect, ReflectKind, TypeRegistry, Typed,
};
use bevy_reflect_derive::impl_type_path;
use core::{any::Any, hash::BuildHasher, hash::Hash};
use indexmap::{IndexMap, IndexSet};
impl<K, V, S> Map for IndexMap<K, V, S>
where
K: FromReflect + MaybeTyped + TypePath + GetTypeRegistration + Eq + Hash,
V: FromReflect + MaybeTyped + TypePath + GetTypeRegistration,
S: TypePath + BuildHasher + Default + Send + Sync,
{
fn get(&self, key: &dyn PartialReflect) -> Option<&dyn PartialReflect> {
key.try_downcast_ref::<K>()
.and_then(|key| Self::get(self, key))
.map(|value| value as &dyn PartialReflect)
}
fn get_mut(&mut self, key: &dyn PartialReflect) -> Option<&mut dyn PartialReflect> {
key.try_downcast_ref::<K>()
.and_then(move |key| Self::get_mut(self, key))
.map(|value| value as &mut dyn PartialReflect)
}
fn len(&self) -> usize {
Self::len(self)
}
fn iter(&self) -> Box<dyn Iterator<Item = (&dyn PartialReflect, &dyn PartialReflect)> + '_> {
Box::new(
self.iter()
.map(|(k, v)| (k as &dyn PartialReflect, v as &dyn PartialReflect)),
)
}
fn drain(&mut self) -> Vec<(Box<dyn PartialReflect>, Box<dyn PartialReflect>)> {
self.drain(..)
.map(|(key, value)| {
(
Box::new(key) as Box<dyn PartialReflect>,
Box::new(value) as Box<dyn PartialReflect>,
)
})
.collect()
}
fn retain(&mut self, f: &mut dyn FnMut(&dyn PartialReflect, &mut dyn PartialReflect) -> bool) {
self.retain(move |key, value| f(key, value));
}
fn to_dynamic_map(&self) -> DynamicMap {
let mut dynamic_map = DynamicMap::default();
dynamic_map.set_represented_type(PartialReflect::get_represented_type_info(self));
for (k, v) in self {
let key = K::from_reflect(k).unwrap_or_else(|| {
panic!(
"Attempted to clone invalid key of type {}.",
k.reflect_type_path()
)
});
dynamic_map.insert_boxed(Box::new(key), v.to_dynamic());
}
dynamic_map
}
fn insert_boxed(
&mut self,
key: Box<dyn PartialReflect>,
value: Box<dyn PartialReflect>,
) -> Option<Box<dyn PartialReflect>> {
let key = K::take_from_reflect(key).unwrap_or_else(|key| {
panic!(
"Attempted to insert invalid key of type {}.",
key.reflect_type_path()
)
});
let value = V::take_from_reflect(value).unwrap_or_else(|value| {
panic!(
"Attempted to insert invalid value of type {}.",
value.reflect_type_path()
)
});
self.insert(key, value)
.map(|old_value| Box::new(old_value) as Box<dyn PartialReflect>)
}
fn remove(&mut self, key: &dyn PartialReflect) -> Option<Box<dyn PartialReflect>> {
let mut from_reflect = None;
key.try_downcast_ref::<K>()
.or_else(|| {
from_reflect = K::from_reflect(key);
from_reflect.as_ref()
})
.and_then(|key| self.shift_remove(key))
.map(|value| Box::new(value) as Box<dyn PartialReflect>)
}
}
impl<K, V, S> PartialReflect for IndexMap<K, V, S>
where
K: FromReflect + MaybeTyped + TypePath + GetTypeRegistration + Eq + Hash,
V: FromReflect + MaybeTyped + TypePath + GetTypeRegistration,
S: TypePath + BuildHasher + Default + Send + Sync,
{
fn get_represented_type_info(&self) -> Option<&'static TypeInfo> {
Some(<Self as Typed>::type_info())
}
#[inline]
fn into_partial_reflect(self: Box<Self>) -> Box<dyn PartialReflect> {
self
}
fn as_partial_reflect(&self) -> &dyn PartialReflect {
self
}
fn as_partial_reflect_mut(&mut self) -> &mut dyn PartialReflect {
self
}
#[inline]
fn try_into_reflect(self: Box<Self>) -> Result<Box<dyn Reflect>, Box<dyn PartialReflect>> {
Ok(self)
}
fn try_as_reflect(&self) -> Option<&dyn Reflect> {
Some(self)
}
fn try_as_reflect_mut(&mut self) -> Option<&mut dyn Reflect> {
Some(self)
}
fn apply(&mut self, value: &dyn PartialReflect) {
crate::map_apply(self, value);
}
fn try_apply(&mut self, value: &dyn PartialReflect) -> Result<(), crate::ApplyError> {
crate::map_try_apply(self, value)
}
fn reflect_kind(&self) -> ReflectKind {
ReflectKind::Map
}
fn reflect_ref(&self) -> ReflectRef<'_> {
ReflectRef::Map(self)
}
fn reflect_mut(&mut self) -> ReflectMut<'_> {
ReflectMut::Map(self)
}
fn reflect_owned(self: Box<Self>) -> ReflectOwned {
ReflectOwned::Map(self)
}
fn reflect_clone(&self) -> Result<Box<dyn Reflect>, ReflectCloneError> {
let mut map = Self::with_capacity_and_hasher(self.len(), S::default());
for (key, value) in self.iter() {
let key = key.reflect_clone_and_take()?;
let value = value.reflect_clone_and_take()?;
map.insert(key, value);
}
Ok(Box::new(map))
}
fn reflect_partial_eq(&self, value: &dyn PartialReflect) -> Option<bool> {
crate::map_partial_eq(self, value)
}
}
impl<K, V, S> Reflect for IndexMap<K, V, S>
where
K: FromReflect + MaybeTyped + TypePath + GetTypeRegistration + Eq + Hash,
V: FromReflect + MaybeTyped + TypePath + GetTypeRegistration,
S: TypePath + BuildHasher + Default + Send + Sync,
{
fn into_any(self: Box<Self>) -> Box<dyn Any> {
self
}
fn as_any(&self) -> &dyn Any {
self
}
fn as_any_mut(&mut self) -> &mut dyn Any {
self
}
fn into_reflect(self: Box<Self>) -> Box<dyn Reflect> {
self
}
fn as_reflect(&self) -> &dyn Reflect {
self
}
fn as_reflect_mut(&mut self) -> &mut dyn Reflect {
self
}
fn set(&mut self, value: Box<dyn Reflect>) -> Result<(), Box<dyn Reflect>> {
*self = value.take()?;
Ok(())
}
}
impl<K, V, S> Typed for IndexMap<K, V, S>
where
K: FromReflect + MaybeTyped + TypePath + GetTypeRegistration + Eq + Hash,
V: FromReflect + MaybeTyped + TypePath + GetTypeRegistration,
S: TypePath + BuildHasher + Default + Send + Sync,
{
fn type_info() -> &'static TypeInfo {
static CELL: GenericTypeInfoCell = GenericTypeInfoCell::new();
CELL.get_or_insert::<Self, _>(|| {
TypeInfo::Map(
MapInfo::new::<Self, K, V>().with_generics(Generics::from_iter([
TypeParamInfo::new::<K>("K"),
TypeParamInfo::new::<V>("V"),
])),
)
})
}
}
impl<K, V, S> FromReflect for IndexMap<K, V, S>
where
K: FromReflect + MaybeTyped + TypePath + GetTypeRegistration + Eq + Hash,
V: FromReflect + MaybeTyped + TypePath + GetTypeRegistration,
S: TypePath + BuildHasher + Default + Send + Sync,
{
fn from_reflect(reflect: &dyn PartialReflect) -> Option<Self> {
let ref_map = reflect.reflect_ref().as_map().ok()?;
let mut new_map = Self::with_capacity_and_hasher(ref_map.len(), S::default());
for (key, value) in ref_map.iter() {
let new_key = K::from_reflect(key)?;
let new_value = V::from_reflect(value)?;
new_map.insert(new_key, new_value);
}
Some(new_map)
}
}
impl<K, V, S> GetTypeRegistration for IndexMap<K, V, S>
where
K: Hash + Eq + FromReflect + MaybeTyped + TypePath + GetTypeRegistration,
V: FromReflect + MaybeTyped + TypePath + GetTypeRegistration,
S: TypePath + BuildHasher + Send + Sync + Default,
{
fn get_type_registration() -> TypeRegistration {
let mut registration = TypeRegistration::of::<Self>();
registration.insert::<ReflectFromPtr>(FromType::<Self>::from_type());
registration.insert::<ReflectFromReflect>(FromType::<Self>::from_type());
registration
}
fn register_type_dependencies(registry: &mut TypeRegistry) {
registry.register::<K>();
registry.register::<V>();
}
}
impl_type_path!(::indexmap::IndexMap<K, V, S>);
impl<T, S> Set for IndexSet<T, S>
where
T: FromReflect + TypePath + GetTypeRegistration + Eq + Hash,
S: TypePath + BuildHasher + Default + Send + Sync,
{
fn get(&self, value: &dyn PartialReflect) -> Option<&dyn PartialReflect> {
value
.try_downcast_ref::<T>()
.and_then(|value| Self::get(self, value))
.map(|value| value as &dyn PartialReflect)
}
fn len(&self) -> usize {
self.len()
}
fn iter(&self) -> Box<dyn Iterator<Item = &dyn PartialReflect> + '_> {
let iter = self.iter().map(|v| v as &dyn PartialReflect);
Box::new(iter)
}
fn drain(&mut self) -> Vec<Box<dyn PartialReflect>> {
self.drain(..)
.map(|value| Box::new(value) as Box<dyn PartialReflect>)
.collect()
}
fn retain(&mut self, f: &mut dyn FnMut(&dyn PartialReflect) -> bool) {
self.retain(move |value| f(value));
}
fn insert_boxed(&mut self, value: Box<dyn PartialReflect>) -> bool {
let value = T::take_from_reflect(value).unwrap_or_else(|value| {
panic!(
"Attempted to insert invalid value of type {}.",
value.reflect_type_path()
)
});
self.insert(value)
}
fn remove(&mut self, value: &dyn PartialReflect) -> bool {
let mut from_reflect = None;
value
.try_downcast_ref::<T>()
.or_else(|| {
from_reflect = T::from_reflect(value);
from_reflect.as_ref()
})
.is_some_and(|value| self.shift_remove(value))
}
fn contains(&self, value: &dyn PartialReflect) -> bool {
let mut from_reflect = None;
value
.try_downcast_ref::<T>()
.or_else(|| {
from_reflect = T::from_reflect(value);
from_reflect.as_ref()
})
.is_some_and(|value| self.contains(value))
}
}
impl<T, S> PartialReflect for IndexSet<T, S>
where
T: FromReflect + TypePath + GetTypeRegistration + Eq + Hash,
S: TypePath + BuildHasher + Default + Send + Sync,
{
fn get_represented_type_info(&self) -> Option<&'static TypeInfo> {
Some(<Self as Typed>::type_info())
}
#[inline]
fn into_partial_reflect(self: Box<Self>) -> Box<dyn PartialReflect> {
self
}
fn as_partial_reflect(&self) -> &dyn PartialReflect {
self
}
fn as_partial_reflect_mut(&mut self) -> &mut dyn PartialReflect {
self
}
#[inline]
fn try_into_reflect(self: Box<Self>) -> Result<Box<dyn Reflect>, Box<dyn PartialReflect>> {
Ok(self)
}
fn try_as_reflect(&self) -> Option<&dyn Reflect> {
Some(self)
}
fn try_as_reflect_mut(&mut self) -> Option<&mut dyn Reflect> {
Some(self)
}
fn apply(&mut self, value: &dyn PartialReflect) {
crate::set_apply(self, value);
}
fn try_apply(&mut self, value: &dyn PartialReflect) -> Result<(), crate::ApplyError> {
crate::set_try_apply(self, value)
}
fn reflect_kind(&self) -> ReflectKind {
ReflectKind::Set
}
fn reflect_ref(&self) -> ReflectRef<'_> {
ReflectRef::Set(self)
}
fn reflect_mut(&mut self) -> ReflectMut<'_> {
ReflectMut::Set(self)
}
fn reflect_owned(self: Box<Self>) -> ReflectOwned {
ReflectOwned::Set(self)
}
fn reflect_clone(&self) -> Result<Box<dyn Reflect>, ReflectCloneError> {
Ok(Box::new(
self.iter()
.map(PartialReflect::reflect_clone_and_take)
.collect::<Result<Self, ReflectCloneError>>()?,
))
}
fn reflect_partial_eq(&self, value: &dyn PartialReflect) -> Option<bool> {
crate::set_partial_eq(self, value)
}
}
impl<T, S> Reflect for IndexSet<T, S>
where
T: FromReflect + TypePath + GetTypeRegistration + Eq + Hash,
S: TypePath + BuildHasher + Default + Send + Sync,
{
fn into_any(self: Box<Self>) -> Box<dyn Any> {
self
}
fn as_any(&self) -> &dyn Any {
self
}
fn as_any_mut(&mut self) -> &mut dyn Any {
self
}
fn into_reflect(self: Box<Self>) -> Box<dyn Reflect> {
self
}
fn as_reflect(&self) -> &dyn Reflect {
self
}
fn as_reflect_mut(&mut self) -> &mut dyn Reflect {
self
}
fn set(&mut self, value: Box<dyn Reflect>) -> Result<(), Box<dyn Reflect>> {
*self = value.take()?;
Ok(())
}
}
impl<T, S> Typed for IndexSet<T, S>
where
T: FromReflect + TypePath + GetTypeRegistration + Eq + Hash,
S: TypePath + BuildHasher + Default + Send + Sync,
{
fn type_info() -> &'static TypeInfo {
static CELL: GenericTypeInfoCell = GenericTypeInfoCell::new();
CELL.get_or_insert::<Self, _>(|| {
TypeInfo::Set(
SetInfo::new::<Self, T>()
.with_generics(Generics::from_iter([TypeParamInfo::new::<T>("T")])),
)
})
}
}
impl<T, S> FromReflect for IndexSet<T, S>
where
T: FromReflect + TypePath + GetTypeRegistration + Eq + Hash,
S: TypePath + BuildHasher + Default + Send + Sync,
{
fn from_reflect(reflect: &dyn PartialReflect) -> Option<Self> {
let ref_set = reflect.reflect_ref().as_set().ok()?;
let mut new_set = Self::with_capacity_and_hasher(ref_set.len(), S::default());
for field in ref_set.iter() {
new_set.insert(T::from_reflect(field)?);
}
Some(new_set)
}
}
impl<T, S> GetTypeRegistration for IndexSet<T, S>
where
T: FromReflect + TypePath + GetTypeRegistration + Eq + Hash,
S: TypePath + BuildHasher + Default + Send + Sync,
{
fn get_type_registration() -> TypeRegistration {
let mut registration = TypeRegistration::of::<Self>();
registration.insert::<ReflectFromPtr>(FromType::<Self>::from_type());
registration
}
}
impl_type_path!(::indexmap::IndexSet<T, S>);
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/impls/hashbrown.rs | crates/bevy_reflect/src/impls/hashbrown.rs | use crate::impls::macros::{impl_reflect_for_hashmap, impl_reflect_for_hashset};
#[cfg(feature = "functions")]
use crate::{
from_reflect::FromReflect, type_info::MaybeTyped, type_path::TypePath,
type_registry::GetTypeRegistration,
};
use bevy_reflect_derive::impl_type_path;
#[cfg(feature = "functions")]
use core::hash::{BuildHasher, Hash};
impl_reflect_for_hashmap!(hashbrown::hash_map::HashMap<K, V, S>);
impl_type_path!(::hashbrown::hash_map::HashMap<K, V, S>);
#[cfg(feature = "functions")]
crate::func::macros::impl_function_traits!(::hashbrown::hash_map::HashMap<K, V, S>;
<
K: FromReflect + MaybeTyped + TypePath + GetTypeRegistration + Eq + Hash,
V: FromReflect + MaybeTyped + TypePath + GetTypeRegistration,
S: TypePath + BuildHasher + Default + Send + Sync
>
);
impl_reflect_for_hashset!(::hashbrown::hash_set::HashSet<V,S>);
impl_type_path!(::hashbrown::hash_set::HashSet<V, S>);
#[cfg(feature = "functions")]
crate::func::macros::impl_function_traits!(::hashbrown::hash_set::HashSet<V, S>;
<
V: Hash + Eq + FromReflect + TypePath + GetTypeRegistration,
S: TypePath + BuildHasher + Default + Send + Sync
>
);
#[cfg(test)]
mod tests {
use crate::Reflect;
use static_assertions::assert_impl_all;
#[test]
fn should_reflect_hashmaps() {
// We specify `foldhash::fast::RandomState` directly here since without the `default-hasher`
// feature, hashbrown uses an empty enum to force users to specify their own
assert_impl_all!(hashbrown::HashMap<u32, f32, foldhash::fast::RandomState>: Reflect);
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/impls/petgraph.rs | crates/bevy_reflect/src/impls/petgraph.rs | use crate::{impl_reflect_opaque, prelude::ReflectDefault, ReflectDeserialize, ReflectSerialize};
impl_reflect_opaque!(::petgraph::graph::NodeIndex(
Clone,
Default,
PartialEq,
Hash,
Serialize,
Deserialize
));
impl_reflect_opaque!(::petgraph::graph::DiGraph<
N: ::core::clone::Clone,
E: ::core::clone::Clone,
Ix: ::petgraph::graph::IndexType
>(Clone));
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/impls/smol_str.rs | crates/bevy_reflect/src/impls/smol_str.rs | use crate::{std_traits::ReflectDefault, ReflectDeserialize, ReflectSerialize};
use bevy_reflect_derive::impl_reflect_opaque;
impl_reflect_opaque!(::smol_str::SmolStr(
Clone,
Debug,
Hash,
PartialEq,
Default,
Serialize,
Deserialize,
));
#[cfg(test)]
mod tests {
use crate::{FromReflect, PartialReflect};
use smol_str::SmolStr;
#[test]
fn should_partial_eq_smolstr() {
let a: &dyn PartialReflect = &SmolStr::new("A");
let a2: &dyn PartialReflect = &SmolStr::new("A");
let b: &dyn PartialReflect = &SmolStr::new("B");
assert_eq!(Some(true), a.reflect_partial_eq(a2));
assert_eq!(Some(false), a.reflect_partial_eq(b));
}
#[test]
fn smolstr_should_from_reflect() {
let smolstr = SmolStr::new("hello_world.rs");
let output = <SmolStr as FromReflect>::from_reflect(&smolstr);
assert_eq!(Some(smolstr), output);
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/impls/smallvec.rs | crates/bevy_reflect/src/impls/smallvec.rs | use crate::{
utility::GenericTypeInfoCell, ApplyError, FromReflect, FromType, Generics, GetTypeRegistration,
List, ListInfo, ListIter, MaybeTyped, PartialReflect, Reflect, ReflectFromPtr, ReflectKind,
ReflectMut, ReflectOwned, ReflectRef, TypeInfo, TypeParamInfo, TypePath, TypeRegistration,
Typed,
};
use alloc::{boxed::Box, vec::Vec};
use bevy_reflect::ReflectCloneError;
use bevy_reflect_derive::impl_type_path;
use core::any::Any;
use smallvec::{Array as SmallArray, SmallVec};
impl<T: SmallArray + TypePath + Send + Sync> List for SmallVec<T>
where
T::Item: FromReflect + MaybeTyped + TypePath,
{
fn get(&self, index: usize) -> Option<&dyn PartialReflect> {
if index < SmallVec::len(self) {
Some(&self[index] as &dyn PartialReflect)
} else {
None
}
}
fn get_mut(&mut self, index: usize) -> Option<&mut dyn PartialReflect> {
if index < SmallVec::len(self) {
Some(&mut self[index] as &mut dyn PartialReflect)
} else {
None
}
}
fn insert(&mut self, index: usize, value: Box<dyn PartialReflect>) {
let value = value.try_take::<T::Item>().unwrap_or_else(|value| {
<T as SmallArray>::Item::from_reflect(&*value).unwrap_or_else(|| {
panic!(
"Attempted to insert invalid value of type {}.",
value.reflect_type_path()
)
})
});
SmallVec::insert(self, index, value);
}
fn remove(&mut self, index: usize) -> Box<dyn PartialReflect> {
Box::new(self.remove(index))
}
fn push(&mut self, value: Box<dyn PartialReflect>) {
let value = value.try_take::<T::Item>().unwrap_or_else(|value| {
<T as SmallArray>::Item::from_reflect(&*value).unwrap_or_else(|| {
panic!(
"Attempted to push invalid value of type {}.",
value.reflect_type_path()
)
})
});
SmallVec::push(self, value);
}
fn pop(&mut self) -> Option<Box<dyn PartialReflect>> {
self.pop()
.map(|value| Box::new(value) as Box<dyn PartialReflect>)
}
fn len(&self) -> usize {
<SmallVec<T>>::len(self)
}
fn iter(&self) -> ListIter<'_> {
ListIter::new(self)
}
fn drain(&mut self) -> Vec<Box<dyn PartialReflect>> {
self.drain(..)
.map(|value| Box::new(value) as Box<dyn PartialReflect>)
.collect()
}
}
impl<T: SmallArray + TypePath + Send + Sync> PartialReflect for SmallVec<T>
where
T::Item: FromReflect + MaybeTyped + TypePath,
{
fn get_represented_type_info(&self) -> Option<&'static TypeInfo> {
Some(<Self as Typed>::type_info())
}
#[inline]
fn into_partial_reflect(self: Box<Self>) -> Box<dyn PartialReflect> {
self
}
fn as_partial_reflect(&self) -> &dyn PartialReflect {
self
}
fn as_partial_reflect_mut(&mut self) -> &mut dyn PartialReflect {
self
}
fn try_into_reflect(self: Box<Self>) -> Result<Box<dyn Reflect>, Box<dyn PartialReflect>> {
Ok(self)
}
fn try_as_reflect(&self) -> Option<&dyn Reflect> {
Some(self)
}
fn try_as_reflect_mut(&mut self) -> Option<&mut dyn Reflect> {
Some(self)
}
fn apply(&mut self, value: &dyn PartialReflect) {
crate::list_apply(self, value);
}
fn try_apply(&mut self, value: &dyn PartialReflect) -> Result<(), ApplyError> {
crate::list_try_apply(self, value)
}
fn reflect_kind(&self) -> ReflectKind {
ReflectKind::List
}
fn reflect_ref(&self) -> ReflectRef<'_> {
ReflectRef::List(self)
}
fn reflect_mut(&mut self) -> ReflectMut<'_> {
ReflectMut::List(self)
}
fn reflect_owned(self: Box<Self>) -> ReflectOwned {
ReflectOwned::List(self)
}
fn reflect_clone(&self) -> Result<Box<dyn Reflect>, ReflectCloneError> {
Ok(Box::new(
// `(**self)` avoids getting `SmallVec<T> as List::iter`, which
// would give us the wrong item type.
(**self)
.iter()
.map(PartialReflect::reflect_clone_and_take)
.collect::<Result<Self, ReflectCloneError>>()?,
))
}
fn reflect_partial_eq(&self, value: &dyn PartialReflect) -> Option<bool> {
crate::list_partial_eq(self, value)
}
}
impl<T: SmallArray + TypePath + Send + Sync> Reflect for SmallVec<T>
where
T::Item: FromReflect + MaybeTyped + TypePath,
{
fn into_any(self: Box<Self>) -> Box<dyn Any> {
self
}
fn as_any(&self) -> &dyn Any {
self
}
fn as_any_mut(&mut self) -> &mut dyn Any {
self
}
fn into_reflect(self: Box<Self>) -> Box<dyn Reflect> {
self
}
fn as_reflect(&self) -> &dyn Reflect {
self
}
fn as_reflect_mut(&mut self) -> &mut dyn Reflect {
self
}
fn set(&mut self, value: Box<dyn Reflect>) -> Result<(), Box<dyn Reflect>> {
*self = value.take()?;
Ok(())
}
}
impl<T: SmallArray + TypePath + Send + Sync + 'static> Typed for SmallVec<T>
where
T::Item: FromReflect + MaybeTyped + TypePath,
{
fn type_info() -> &'static TypeInfo {
static CELL: GenericTypeInfoCell = GenericTypeInfoCell::new();
CELL.get_or_insert::<Self, _>(|| {
TypeInfo::List(
ListInfo::new::<Self, T::Item>()
.with_generics(Generics::from_iter([TypeParamInfo::new::<T>("T")])),
)
})
}
}
impl_type_path!(::smallvec::SmallVec<T: SmallArray>);
impl<T: SmallArray + TypePath + Send + Sync> FromReflect for SmallVec<T>
where
T::Item: FromReflect + MaybeTyped + TypePath,
{
fn from_reflect(reflect: &dyn PartialReflect) -> Option<Self> {
let ref_list = reflect.reflect_ref().as_list().ok()?;
let mut new_list = Self::with_capacity(ref_list.len());
for field in ref_list.iter() {
new_list.push(<T as SmallArray>::Item::from_reflect(field)?);
}
Some(new_list)
}
}
impl<T: SmallArray + TypePath + Send + Sync> GetTypeRegistration for SmallVec<T>
where
T::Item: FromReflect + MaybeTyped + TypePath,
{
fn get_type_registration() -> TypeRegistration {
let mut registration = TypeRegistration::of::<SmallVec<T>>();
registration.insert::<ReflectFromPtr>(FromType::<SmallVec<T>>::from_type());
registration
}
}
#[cfg(feature = "functions")]
crate::func::macros::impl_function_traits!(SmallVec<T>; <T: SmallArray + TypePath + Send + Sync> where T::Item: FromReflect + MaybeTyped + TypePath);
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/impls/wgpu_types.rs | crates/bevy_reflect/src/impls/wgpu_types.rs | use crate::{impl_reflect_opaque, ReflectDeserialize, ReflectSerialize};
impl_reflect_opaque!(::wgpu_types::TextureFormat(
Clone,
Debug,
Hash,
PartialEq,
Deserialize,
Serialize,
));
impl_reflect_opaque!(::wgpu_types::BlendState(
Clone,
Debug,
Hash,
PartialEq,
Deserialize,
Serialize,
));
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/impls/uuid.rs | crates/bevy_reflect/src/impls/uuid.rs | use crate::{std_traits::ReflectDefault, ReflectDeserialize, ReflectSerialize};
use bevy_reflect_derive::impl_reflect_opaque;
impl_reflect_opaque!(::uuid::Uuid(
Serialize,
Deserialize,
Default,
Clone,
Debug,
PartialEq,
Hash
));
impl_reflect_opaque!(::uuid::NonNilUuid(
Serialize,
Deserialize,
Clone,
Debug,
PartialEq,
Hash
));
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/impls/macros/list.rs | crates/bevy_reflect/src/impls/macros/list.rs | macro_rules! impl_reflect_for_veclike {
($ty:ty, $insert:expr, $remove:expr, $push:expr, $pop:expr, $sub:ty) => {
const _: () = {
impl<T: $crate::from_reflect::FromReflect + $crate::type_info::MaybeTyped + $crate::type_path::TypePath + $crate::type_registry::GetTypeRegistration> $crate::list::List for $ty {
#[inline]
fn get(&self, index: usize) -> Option<&dyn $crate::reflect::PartialReflect> {
<$sub>::get(self, index).map(|value| value as &dyn $crate::reflect::PartialReflect)
}
#[inline]
fn get_mut(&mut self, index: usize) -> Option<&mut dyn $crate::reflect::PartialReflect> {
<$sub>::get_mut(self, index).map(|value| value as &mut dyn $crate::reflect::PartialReflect)
}
fn insert(&mut self, index: usize, value: bevy_platform::prelude::Box<dyn $crate::reflect::PartialReflect>) {
let value = value.try_take::<T>().unwrap_or_else(|value| {
T::from_reflect(&*value).unwrap_or_else(|| {
panic!(
"Attempted to insert invalid value of type {}.",
value.reflect_type_path()
)
})
});
$insert(self, index, value);
}
fn remove(&mut self, index: usize) -> bevy_platform::prelude::Box<dyn $crate::reflect::PartialReflect> {
bevy_platform::prelude::Box::new($remove(self, index))
}
fn push(&mut self, value: bevy_platform::prelude::Box<dyn $crate::reflect::PartialReflect>) {
let value = T::take_from_reflect(value).unwrap_or_else(|value| {
panic!(
"Attempted to push invalid value of type {}.",
value.reflect_type_path()
)
});
$push(self, value);
}
fn pop(&mut self) -> Option<bevy_platform::prelude::Box<dyn $crate::reflect::PartialReflect>> {
$pop(self).map(|value| bevy_platform::prelude::Box::new(value) as bevy_platform::prelude::Box<dyn $crate::reflect::PartialReflect>)
}
#[inline]
fn len(&self) -> usize {
<$sub>::len(self)
}
#[inline]
fn iter(&self) -> $crate::list::ListIter<'_> {
$crate::list::ListIter::new(self)
}
#[inline]
fn drain(&mut self) -> alloc::vec::Vec<bevy_platform::prelude::Box<dyn $crate::reflect::PartialReflect>> {
self.drain(..)
.map(|value| bevy_platform::prelude::Box::new(value) as bevy_platform::prelude::Box<dyn $crate::reflect::PartialReflect>)
.collect()
}
}
impl<T: $crate::from_reflect::FromReflect + $crate::type_info::MaybeTyped + $crate::type_path::TypePath + $crate::type_registry::GetTypeRegistration> $crate::reflect::PartialReflect for $ty {
#[inline]
fn get_represented_type_info(&self) -> Option<&'static $crate::type_info::TypeInfo> {
Some(<Self as $crate::type_info::Typed>::type_info())
}
fn into_partial_reflect(self: bevy_platform::prelude::Box<Self>) -> bevy_platform::prelude::Box<dyn $crate::reflect::PartialReflect> {
self
}
#[inline]
fn as_partial_reflect(&self) -> &dyn $crate::reflect::PartialReflect {
self
}
#[inline]
fn as_partial_reflect_mut(&mut self) -> &mut dyn $crate::reflect::PartialReflect {
self
}
fn try_into_reflect(
self: bevy_platform::prelude::Box<Self>,
) -> Result<bevy_platform::prelude::Box<dyn $crate::reflect::Reflect>, bevy_platform::prelude::Box<dyn $crate::reflect::PartialReflect>> {
Ok(self)
}
fn try_as_reflect(&self) -> Option<&dyn $crate::reflect::Reflect> {
Some(self)
}
fn try_as_reflect_mut(&mut self) -> Option<&mut dyn $crate::reflect::Reflect> {
Some(self)
}
fn reflect_kind(&self) -> $crate::kind::ReflectKind {
$crate::kind::ReflectKind::List
}
fn reflect_ref(&self) -> $crate::kind::ReflectRef<'_> {
$crate::kind::ReflectRef::List(self)
}
fn reflect_mut(&mut self) -> $crate::kind::ReflectMut<'_> {
$crate::kind::ReflectMut::List(self)
}
fn reflect_owned(self: bevy_platform::prelude::Box<Self>) -> $crate::kind::ReflectOwned {
$crate::kind::ReflectOwned::List(self)
}
fn reflect_clone(&self) -> Result<bevy_platform::prelude::Box<dyn $crate::reflect::Reflect>, $crate::error::ReflectCloneError> {
Ok(bevy_platform::prelude::Box::new(
self.iter()
.map(|value| value.reflect_clone_and_take())
.collect::<Result<Self, $crate::error::ReflectCloneError>>()?,
))
}
fn reflect_hash(&self) -> Option<u64> {
$crate::list::list_hash(self)
}
fn reflect_partial_eq(&self, value: &dyn $crate::reflect::PartialReflect) -> Option<bool> {
$crate::list::list_partial_eq(self, value)
}
fn apply(&mut self, value: &dyn $crate::reflect::PartialReflect) {
$crate::list::list_apply(self, value);
}
fn try_apply(&mut self, value: &dyn $crate::reflect::PartialReflect) -> Result<(), $crate::reflect::ApplyError> {
$crate::list::list_try_apply(self, value)
}
}
$crate::impl_full_reflect!(<T> for $ty where T: $crate::from_reflect::FromReflect + $crate::type_info::MaybeTyped + $crate::type_path::TypePath + $crate::type_registry::GetTypeRegistration);
impl<T: $crate::from_reflect::FromReflect + $crate::type_info::MaybeTyped + $crate::type_path::TypePath + $crate::type_registry::GetTypeRegistration> $crate::type_info::Typed for $ty {
fn type_info() -> &'static $crate::type_info::TypeInfo {
static CELL: $crate::utility::GenericTypeInfoCell = $crate::utility::GenericTypeInfoCell::new();
CELL.get_or_insert::<Self, _>(|| {
$crate::type_info::TypeInfo::List(
$crate::list::ListInfo::new::<Self, T>().with_generics($crate::generics::Generics::from_iter([
$crate::generics::TypeParamInfo::new::<T>("T")
]))
)
})
}
}
impl<T: $crate::from_reflect::FromReflect + $crate::type_info::MaybeTyped + $crate::type_path::TypePath + $crate::type_registry::GetTypeRegistration> $crate::type_registry::GetTypeRegistration
for $ty
{
fn get_type_registration() -> $crate::type_registry::TypeRegistration {
let mut registration = $crate::type_registry::TypeRegistration::of::<$ty>();
registration.insert::<$crate::type_registry::ReflectFromPtr>($crate::type_registry::FromType::<$ty>::from_type());
registration.insert::<$crate::from_reflect::ReflectFromReflect>($crate::type_registry::FromType::<$ty>::from_type());
registration
}
fn register_type_dependencies(registry: &mut $crate::type_registry::TypeRegistry) {
registry.register::<T>();
}
}
impl<T: $crate::from_reflect::FromReflect + $crate::type_info::MaybeTyped + $crate::type_path::TypePath + $crate::type_registry::GetTypeRegistration> $crate::from_reflect::FromReflect for $ty {
fn from_reflect(reflect: &dyn $crate::reflect::PartialReflect) -> Option<Self> {
let ref_list = reflect.reflect_ref().as_list().ok()?;
let mut new_list = Self::with_capacity(ref_list.len());
for field in ref_list.iter() {
$push(&mut new_list, T::from_reflect(field)?);
}
Some(new_list)
}
}
};
};
}
pub(crate) use impl_reflect_for_veclike;
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/impls/macros/map.rs | crates/bevy_reflect/src/impls/macros/map.rs | macro_rules! impl_reflect_for_hashmap {
($ty:path) => {
const _: () = {
impl<K, V, S> $crate::map::Map for $ty
where
K: $crate::from_reflect::FromReflect + $crate::type_info::MaybeTyped + $crate::type_path::TypePath + $crate::type_registry::GetTypeRegistration + Eq + core::hash::Hash,
V: $crate::from_reflect::FromReflect + $crate::type_info::MaybeTyped + $crate::type_path::TypePath + $crate::type_registry::GetTypeRegistration,
S: $crate::type_path::TypePath + core::hash::BuildHasher + Default + Send + Sync,
{
fn get(&self, key: &dyn $crate::reflect::PartialReflect) -> Option<&dyn $crate::reflect::PartialReflect> {
key.try_downcast_ref::<K>()
.and_then(|key| Self::get(self, key))
.map(|value| value as &dyn $crate::reflect::PartialReflect)
}
fn get_mut(&mut self, key: &dyn $crate::reflect::PartialReflect) -> Option<&mut dyn $crate::reflect::PartialReflect> {
key.try_downcast_ref::<K>()
.and_then(move |key| Self::get_mut(self, key))
.map(|value| value as &mut dyn $crate::reflect::PartialReflect)
}
fn len(&self) -> usize {
Self::len(self)
}
fn iter(&self) -> bevy_platform::prelude::Box<dyn Iterator<Item = (&dyn $crate::reflect::PartialReflect, &dyn $crate::reflect::PartialReflect)> + '_> {
bevy_platform::prelude::Box::new(self.iter().map(|(k, v)| (k as &dyn $crate::reflect::PartialReflect, v as &dyn $crate::reflect::PartialReflect)))
}
fn drain(&mut self) -> bevy_platform::prelude::Vec<(bevy_platform::prelude::Box<dyn $crate::reflect::PartialReflect>, bevy_platform::prelude::Box<dyn $crate::reflect::PartialReflect>)> {
self.drain()
.map(|(key, value)| {
(
bevy_platform::prelude::Box::new(key) as bevy_platform::prelude::Box<dyn $crate::reflect::PartialReflect>,
bevy_platform::prelude::Box::new(value) as bevy_platform::prelude::Box<dyn $crate::reflect::PartialReflect>,
)
})
.collect()
}
fn retain(&mut self, f: &mut dyn FnMut(&dyn $crate::reflect::PartialReflect, &mut dyn $crate::reflect::PartialReflect) -> bool) {
self.retain(move |key, value| f(key, value));
}
fn to_dynamic_map(&self) -> $crate::map::DynamicMap {
let mut dynamic_map = $crate::map::DynamicMap::default();
dynamic_map.set_represented_type($crate::reflect::PartialReflect::get_represented_type_info(self));
for (k, v) in self {
let key = K::from_reflect(k).unwrap_or_else(|| {
panic!(
"Attempted to clone invalid key of type {}.",
k.reflect_type_path()
)
});
dynamic_map.insert_boxed(bevy_platform::prelude::Box::new(key), v.to_dynamic());
}
dynamic_map
}
fn insert_boxed(
&mut self,
key: bevy_platform::prelude::Box<dyn $crate::reflect::PartialReflect>,
value: bevy_platform::prelude::Box<dyn $crate::reflect::PartialReflect>,
) -> Option<bevy_platform::prelude::Box<dyn $crate::reflect::PartialReflect>> {
let key = K::take_from_reflect(key).unwrap_or_else(|key| {
panic!(
"Attempted to insert invalid key of type {}.",
key.reflect_type_path()
)
});
let value = V::take_from_reflect(value).unwrap_or_else(|value| {
panic!(
"Attempted to insert invalid value of type {}.",
value.reflect_type_path()
)
});
self.insert(key, value)
.map(|old_value| bevy_platform::prelude::Box::new(old_value) as bevy_platform::prelude::Box<dyn $crate::reflect::PartialReflect>)
}
fn remove(&mut self, key: &dyn $crate::reflect::PartialReflect) -> Option<bevy_platform::prelude::Box<dyn $crate::reflect::PartialReflect>> {
let mut from_reflect = None;
key.try_downcast_ref::<K>()
.or_else(|| {
from_reflect = K::from_reflect(key);
from_reflect.as_ref()
})
.and_then(|key| self.remove(key))
.map(|value| bevy_platform::prelude::Box::new(value) as bevy_platform::prelude::Box<dyn $crate::reflect::PartialReflect>)
}
}
impl<K, V, S> $crate::reflect::PartialReflect for $ty
where
K: $crate::from_reflect::FromReflect + $crate::type_info::MaybeTyped + $crate::type_path::TypePath + $crate::type_registry::GetTypeRegistration + Eq + core::hash::Hash,
V: $crate::from_reflect::FromReflect + $crate::type_info::MaybeTyped + $crate::type_path::TypePath + $crate::type_registry::GetTypeRegistration,
S: $crate::type_path::TypePath + core::hash::BuildHasher + Default + Send + Sync,
{
fn get_represented_type_info(&self) -> Option<&'static $crate::type_info::TypeInfo> {
Some(<Self as $crate::type_info::Typed>::type_info())
}
#[inline]
fn into_partial_reflect(self: bevy_platform::prelude::Box<Self>) -> bevy_platform::prelude::Box<dyn $crate::reflect::PartialReflect> {
self
}
fn as_partial_reflect(&self) -> &dyn $crate::reflect::PartialReflect {
self
}
fn as_partial_reflect_mut(&mut self) -> &mut dyn $crate::reflect::PartialReflect {
self
}
fn try_into_reflect(
self: bevy_platform::prelude::Box<Self>,
) -> Result<bevy_platform::prelude::Box<dyn $crate::reflect::Reflect>, bevy_platform::prelude::Box<dyn $crate::reflect::PartialReflect>> {
Ok(self)
}
fn try_as_reflect(&self) -> Option<&dyn $crate::reflect::Reflect> {
Some(self)
}
fn try_as_reflect_mut(&mut self) -> Option<&mut dyn $crate::reflect::Reflect> {
Some(self)
}
fn reflect_kind(&self) -> $crate::kind::ReflectKind {
$crate::kind::ReflectKind::Map
}
fn reflect_ref(&self) -> $crate::kind::ReflectRef<'_> {
$crate::kind::ReflectRef::Map(self)
}
fn reflect_mut(&mut self) -> $crate::kind::ReflectMut<'_> {
$crate::kind::ReflectMut::Map(self)
}
fn reflect_owned(self: bevy_platform::prelude::Box<Self>) -> $crate::kind::ReflectOwned {
$crate::kind::ReflectOwned::Map(self)
}
fn reflect_clone(&self) -> Result<bevy_platform::prelude::Box<dyn $crate::reflect::Reflect>, $crate::error::ReflectCloneError> {
let mut map = Self::with_capacity_and_hasher(self.len(), S::default());
for (key, value) in self.iter() {
let key = key.reflect_clone_and_take()?;
let value = value.reflect_clone_and_take()?;
map.insert(key, value);
}
Ok(bevy_platform::prelude::Box::new(map))
}
fn reflect_partial_eq(&self, value: &dyn $crate::reflect::PartialReflect) -> Option<bool> {
$crate::map::map_partial_eq(self, value)
}
fn apply(&mut self, value: &dyn $crate::reflect::PartialReflect) {
$crate::map::map_apply(self, value);
}
fn try_apply(&mut self, value: &dyn $crate::reflect::PartialReflect) -> Result<(), $crate::reflect::ApplyError> {
$crate::map::map_try_apply(self, value)
}
}
$crate::impl_full_reflect!(
<K, V, S> for $ty
where
K: $crate::from_reflect::FromReflect + $crate::type_info::MaybeTyped + $crate::type_path::TypePath + $crate::type_registry::GetTypeRegistration + Eq + core::hash::Hash,
V: $crate::from_reflect::FromReflect + $crate::type_info::MaybeTyped + $crate::type_path::TypePath + $crate::type_registry::GetTypeRegistration,
S: $crate::type_path::TypePath + core::hash::BuildHasher + Default + Send + Sync,
);
impl<K, V, S> $crate::type_info::Typed for $ty
where
K: $crate::from_reflect::FromReflect + $crate::type_info::MaybeTyped + $crate::type_path::TypePath + $crate::type_registry::GetTypeRegistration + Eq + core::hash::Hash,
V: $crate::from_reflect::FromReflect + $crate::type_info::MaybeTyped + $crate::type_path::TypePath + $crate::type_registry::GetTypeRegistration,
S: $crate::type_path::TypePath + core::hash::BuildHasher + Default + Send + Sync,
{
fn type_info() -> &'static $crate::type_info::TypeInfo {
static CELL: $crate::utility::GenericTypeInfoCell = $crate::utility::GenericTypeInfoCell::new();
CELL.get_or_insert::<Self, _>(|| {
$crate::type_info::TypeInfo::Map(
$crate::map::MapInfo::new::<Self, K, V>().with_generics($crate::generics::Generics::from_iter([
$crate::generics::TypeParamInfo::new::<K>("K"),
$crate::generics::TypeParamInfo::new::<V>("V"),
])),
)
})
}
}
impl<K, V, S> $crate::type_registry::GetTypeRegistration for $ty
where
K: $crate::from_reflect::FromReflect + $crate::type_info::MaybeTyped + $crate::type_path::TypePath + $crate::type_registry::GetTypeRegistration + Eq + core::hash::Hash,
V: $crate::from_reflect::FromReflect + $crate::type_info::MaybeTyped + $crate::type_path::TypePath + $crate::type_registry::GetTypeRegistration,
S: $crate::type_path::TypePath + core::hash::BuildHasher + Default + Send + Sync + Default,
{
fn get_type_registration() -> $crate::type_registry::TypeRegistration {
let mut registration = $crate::type_registry::TypeRegistration::of::<Self>();
registration.insert::<$crate::type_registry::ReflectFromPtr>($crate::type_registry::FromType::<Self>::from_type());
registration.insert::<$crate::from_reflect::ReflectFromReflect>($crate::type_registry::FromType::<Self>::from_type());
registration
}
fn register_type_dependencies(registry: &mut $crate::type_registry::TypeRegistry) {
registry.register::<K>();
registry.register::<V>();
}
}
impl<K, V, S> $crate::from_reflect::FromReflect for $ty
where
K: $crate::from_reflect::FromReflect + $crate::type_info::MaybeTyped + $crate::type_path::TypePath + $crate::type_registry::GetTypeRegistration + Eq + core::hash::Hash,
V: $crate::from_reflect::FromReflect + $crate::type_info::MaybeTyped + $crate::type_path::TypePath + $crate::type_registry::GetTypeRegistration,
S: $crate::type_path::TypePath + core::hash::BuildHasher + Default + Send + Sync,
{
fn from_reflect(reflect: &dyn $crate::reflect::PartialReflect) -> Option<Self> {
let ref_map = reflect.reflect_ref().as_map().ok()?;
let mut new_map = Self::with_capacity_and_hasher(ref_map.len(), S::default());
for (key, value) in ref_map.iter() {
let new_key = K::from_reflect(key)?;
let new_value = V::from_reflect(value)?;
new_map.insert(new_key, new_value);
}
Some(new_map)
}
}
};
};
}
pub(crate) use impl_reflect_for_hashmap;
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/impls/macros/mod.rs | crates/bevy_reflect/src/impls/macros/mod.rs | pub(crate) use list::*;
pub(crate) use map::*;
pub(crate) use set::*;
mod list;
mod map;
mod set;
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/impls/macros/set.rs | crates/bevy_reflect/src/impls/macros/set.rs | macro_rules! impl_reflect_for_hashset {
($ty:path) => {
const _: () = {
impl<V, S> $crate::set::Set for $ty
where
V: $crate::from_reflect::FromReflect + $crate::type_path::TypePath + $crate::type_registry::GetTypeRegistration + Eq + core::hash::Hash,
S: $crate::type_path::TypePath + core::hash::BuildHasher + Default + Send + Sync,
{
fn get(&self, value: &dyn $crate::reflect::PartialReflect) -> Option<&dyn $crate::reflect::PartialReflect> {
value
.try_downcast_ref::<V>()
.and_then(|value| Self::get(self, value))
.map(|value| value as &dyn $crate::reflect::PartialReflect)
}
fn len(&self) -> usize {
Self::len(self)
}
fn iter(&self) -> bevy_platform::prelude::Box<dyn Iterator<Item = &dyn $crate::reflect::PartialReflect> + '_> {
let iter = self.iter().map(|v| v as &dyn $crate::reflect::PartialReflect);
bevy_platform::prelude::Box::new(iter)
}
fn drain(&mut self) -> bevy_platform::prelude::Vec<bevy_platform::prelude::Box<dyn $crate::reflect::PartialReflect>> {
self.drain()
.map(|value| bevy_platform::prelude::Box::new(value) as bevy_platform::prelude::Box<dyn $crate::reflect::PartialReflect>)
.collect()
}
fn retain(&mut self, f: &mut dyn FnMut(&dyn $crate::reflect::PartialReflect) -> bool) {
self.retain(move |value| f(value));
}
fn insert_boxed(&mut self, value: bevy_platform::prelude::Box<dyn $crate::reflect::PartialReflect>) -> bool {
let value = V::take_from_reflect(value).unwrap_or_else(|value| {
panic!(
"Attempted to insert invalid value of type {}.",
value.reflect_type_path()
)
});
self.insert(value)
}
fn remove(&mut self, value: &dyn $crate::reflect::PartialReflect) -> bool {
let mut from_reflect = None;
value
.try_downcast_ref::<V>()
.or_else(|| {
from_reflect = V::from_reflect(value);
from_reflect.as_ref()
})
.is_some_and(|value| self.remove(value))
}
fn contains(&self, value: &dyn $crate::reflect::PartialReflect) -> bool {
let mut from_reflect = None;
value
.try_downcast_ref::<V>()
.or_else(|| {
from_reflect = V::from_reflect(value);
from_reflect.as_ref()
})
.is_some_and(|value| self.contains(value))
}
}
impl<V, S> $crate::reflect::PartialReflect for $ty
where
V: $crate::from_reflect::FromReflect + $crate::type_path::TypePath + $crate::type_registry::GetTypeRegistration + Eq + core::hash::Hash,
S: $crate::type_path::TypePath + core::hash::BuildHasher + Default + Send + Sync,
{
fn get_represented_type_info(&self) -> Option<&'static $crate::type_info::TypeInfo> {
Some(<Self as $crate::type_info::Typed>::type_info())
}
#[inline]
fn into_partial_reflect(self: bevy_platform::prelude::Box<Self>) -> bevy_platform::prelude::Box<dyn $crate::reflect::PartialReflect> {
self
}
fn as_partial_reflect(&self) -> &dyn $crate::reflect::PartialReflect {
self
}
fn as_partial_reflect_mut(&mut self) -> &mut dyn $crate::reflect::PartialReflect {
self
}
#[inline]
fn try_into_reflect(
self: bevy_platform::prelude::Box<Self>,
) -> Result<bevy_platform::prelude::Box<dyn $crate::reflect::Reflect>, bevy_platform::prelude::Box<dyn $crate::reflect::PartialReflect>> {
Ok(self)
}
fn try_as_reflect(&self) -> Option<&dyn $crate::reflect::Reflect> {
Some(self)
}
fn try_as_reflect_mut(&mut self) -> Option<&mut dyn $crate::reflect::Reflect> {
Some(self)
}
fn apply(&mut self, value: &dyn $crate::reflect::PartialReflect) {
$crate::set::set_apply(self, value);
}
fn try_apply(&mut self, value: &dyn $crate::reflect::PartialReflect) -> Result<(), $crate::reflect::ApplyError> {
$crate::set::set_try_apply(self, value)
}
fn reflect_kind(&self) -> $crate::kind::ReflectKind {
$crate::kind::ReflectKind::Set
}
fn reflect_ref(&self) -> $crate::kind::ReflectRef<'_> {
$crate::kind::ReflectRef::Set(self)
}
fn reflect_mut(&mut self) -> $crate::kind::ReflectMut<'_> {
$crate::kind::ReflectMut::Set(self)
}
fn reflect_owned(self: bevy_platform::prelude::Box<Self>) -> $crate::kind::ReflectOwned {
$crate::kind::ReflectOwned::Set(self)
}
fn reflect_clone(&self) -> Result<bevy_platform::prelude::Box<dyn $crate::reflect::Reflect>, $crate::error::ReflectCloneError> {
let mut set = Self::with_capacity_and_hasher(self.len(), S::default());
for value in self.iter() {
let value = value.reflect_clone_and_take()?;
set.insert(value);
}
Ok(bevy_platform::prelude::Box::new(set))
}
fn reflect_partial_eq(&self, value: &dyn $crate::reflect::PartialReflect) -> Option<bool> {
$crate::set::set_partial_eq(self, value)
}
}
impl<V, S> $crate::type_info::Typed for $ty
where
V: $crate::from_reflect::FromReflect + $crate::type_path::TypePath + $crate::type_registry::GetTypeRegistration + Eq + core::hash::Hash,
S: $crate::type_path::TypePath + core::hash::BuildHasher + Default + Send + Sync,
{
fn type_info() -> &'static $crate::type_info::TypeInfo {
static CELL: $crate::utility::GenericTypeInfoCell = $crate::utility::GenericTypeInfoCell::new();
CELL.get_or_insert::<Self, _>(|| {
$crate::type_info::TypeInfo::Set(
$crate::set::SetInfo::new::<Self, V>().with_generics($crate::generics::Generics::from_iter([
$crate::generics::TypeParamInfo::new::<V>("V")
]))
)
})
}
}
impl<V, S> $crate::type_registry::GetTypeRegistration for $ty
where
V: $crate::from_reflect::FromReflect + $crate::type_path::TypePath + $crate::type_registry::GetTypeRegistration + Eq + core::hash::Hash,
S: $crate::type_path::TypePath + core::hash::BuildHasher + Default + Send + Sync + Default,
{
fn get_type_registration() -> $crate::type_registry::TypeRegistration {
let mut registration = $crate::type_registry::TypeRegistration::of::<Self>();
registration.insert::<$crate::type_registry::ReflectFromPtr>($crate::type_registry::FromType::<Self>::from_type());
registration.insert::<$crate::from_reflect::ReflectFromReflect>($crate::type_registry::FromType::<Self>::from_type());
registration
}
fn register_type_dependencies(registry: &mut $crate::type_registry::TypeRegistry) {
registry.register::<V>();
}
}
$crate::impl_full_reflect!(
<V, S> for $ty
where
V: $crate::from_reflect::FromReflect + $crate::type_path::TypePath + $crate::type_registry::GetTypeRegistration + Eq + core::hash::Hash,
S: $crate::type_path::TypePath + core::hash::BuildHasher + Default + Send + Sync,
);
impl<V, S> $crate::from_reflect::FromReflect for $ty
where
V: $crate::from_reflect::FromReflect + $crate::type_path::TypePath + $crate::type_registry::GetTypeRegistration + Eq + core::hash::Hash,
S: $crate::type_path::TypePath + core::hash::BuildHasher + Default + Send + Sync,
{
fn from_reflect(reflect: &dyn $crate::reflect::PartialReflect) -> Option<Self> {
let ref_set = reflect.reflect_ref().as_set().ok()?;
let mut new_set = Self::with_capacity_and_hasher(ref_set.len(), S::default());
for value in ref_set.iter() {
let new_value = V::from_reflect(value)?;
new_set.insert(new_value);
}
Some(new_set)
}
}
};
};
}
pub(crate) use impl_reflect_for_hashset;
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/impls/bevy_platform/sync.rs | crates/bevy_reflect/src/impls/bevy_platform/sync.rs | use bevy_reflect_derive::impl_reflect_opaque;
impl_reflect_opaque!(::bevy_platform::sync::Arc<T: Send + Sync + ?Sized>(Clone));
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/impls/bevy_platform/time.rs | crates/bevy_reflect/src/impls/bevy_platform/time.rs | use bevy_reflect_derive::impl_reflect_opaque;
impl_reflect_opaque!(::bevy_platform::time::Instant(
Clone, Debug, Hash, PartialEq
));
#[cfg(test)]
mod tests {
use crate::FromReflect;
use bevy_platform::time::Instant;
#[test]
fn instant_should_from_reflect() {
let expected = Instant::now();
let output = Instant::from_reflect(&expected).unwrap();
assert_eq!(expected, output);
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/impls/bevy_platform/mod.rs | crates/bevy_reflect/src/impls/bevy_platform/mod.rs | mod collections;
mod hash;
mod sync;
mod time;
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/impls/bevy_platform/hash.rs | crates/bevy_reflect/src/impls/bevy_platform/hash.rs | use bevy_reflect_derive::impl_type_path;
impl_type_path!(::bevy_platform::hash::NoOpHash);
impl_type_path!(::bevy_platform::hash::FixedHasher);
impl_type_path!(::bevy_platform::hash::PassHash);
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/impls/bevy_platform/collections/hash_map.rs | crates/bevy_reflect/src/impls/bevy_platform/collections/hash_map.rs | use bevy_reflect_derive::impl_type_path;
use crate::impls::macros::impl_reflect_for_hashmap;
#[cfg(feature = "functions")]
use crate::{
from_reflect::FromReflect, type_info::MaybeTyped, type_path::TypePath,
type_registry::GetTypeRegistration,
};
#[cfg(feature = "functions")]
use core::hash::{BuildHasher, Hash};
impl_reflect_for_hashmap!(bevy_platform::collections::HashMap<K, V, S>);
impl_type_path!(::bevy_platform::collections::HashMap<K, V, S>);
#[cfg(feature = "functions")]
crate::func::macros::impl_function_traits!(::bevy_platform::collections::HashMap<K, V, S>;
<
K: FromReflect + MaybeTyped + TypePath + GetTypeRegistration + Eq + Hash,
V: FromReflect + MaybeTyped + TypePath + GetTypeRegistration,
S: TypePath + BuildHasher + Default + Send + Sync
>
);
#[cfg(test)]
mod tests {
use crate::{PartialReflect, Reflect};
use static_assertions::assert_impl_all;
#[test]
fn should_partial_eq_hash_map() {
let mut a = <bevy_platform::collections::HashMap<_, _>>::default();
a.insert(0usize, 1.23_f64);
let b = a.clone();
let mut c = <bevy_platform::collections::HashMap<_, _>>::default();
c.insert(0usize, 3.21_f64);
let a: &dyn PartialReflect = &a;
let b: &dyn PartialReflect = &b;
let c: &dyn PartialReflect = &c;
assert!(a.reflect_partial_eq(b).unwrap_or_default());
assert!(!a.reflect_partial_eq(c).unwrap_or_default());
}
#[test]
fn should_reflect_hashmaps() {
assert_impl_all!(bevy_platform::collections::HashMap<u32, f32>: Reflect);
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/impls/bevy_platform/collections/hash_set.rs | crates/bevy_reflect/src/impls/bevy_platform/collections/hash_set.rs | use bevy_reflect_derive::impl_type_path;
use crate::impls::macros::impl_reflect_for_hashset;
#[cfg(feature = "functions")]
use crate::{from_reflect::FromReflect, type_path::TypePath, type_registry::GetTypeRegistration};
#[cfg(feature = "functions")]
use core::hash::{BuildHasher, Hash};
impl_reflect_for_hashset!(::bevy_platform::collections::HashSet<V,S>);
impl_type_path!(::bevy_platform::collections::HashSet<V, S>);
#[cfg(feature = "functions")]
crate::func::macros::impl_function_traits!(::bevy_platform::collections::HashSet<V, S>;
<
V: Hash + Eq + FromReflect + TypePath + GetTypeRegistration,
S: TypePath + BuildHasher + Default + Send + Sync
>
);
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/impls/bevy_platform/collections/mod.rs | crates/bevy_reflect/src/impls/bevy_platform/collections/mod.rs | mod hash_map;
mod hash_set;
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/impls/alloc/borrow.rs | crates/bevy_reflect/src/impls/alloc/borrow.rs | use crate::{
error::ReflectCloneError,
kind::{ReflectKind, ReflectMut, ReflectOwned, ReflectRef},
list::{List, ListInfo, ListIter},
prelude::*,
reflect::{impl_full_reflect, ApplyError},
type_info::{MaybeTyped, OpaqueInfo, TypeInfo, Typed},
type_registry::{
FromType, GetTypeRegistration, ReflectDeserialize, ReflectFromPtr, ReflectSerialize,
TypeRegistration, TypeRegistry,
},
utility::{reflect_hasher, GenericTypeInfoCell, NonGenericTypeInfoCell},
};
use alloc::borrow::Cow;
use alloc::vec::Vec;
use bevy_platform::prelude::*;
use bevy_reflect_derive::impl_type_path;
use core::any::Any;
use core::fmt;
use core::hash::{Hash, Hasher};
impl_type_path!(::alloc::borrow::Cow<'a: 'static, T: ToOwned + ?Sized>);
impl PartialReflect for Cow<'static, str> {
fn get_represented_type_info(&self) -> Option<&'static TypeInfo> {
Some(<Self as Typed>::type_info())
}
#[inline]
fn into_partial_reflect(self: Box<Self>) -> Box<dyn PartialReflect> {
self
}
fn as_partial_reflect(&self) -> &dyn PartialReflect {
self
}
fn as_partial_reflect_mut(&mut self) -> &mut dyn PartialReflect {
self
}
fn try_into_reflect(self: Box<Self>) -> Result<Box<dyn Reflect>, Box<dyn PartialReflect>> {
Ok(self)
}
fn try_as_reflect(&self) -> Option<&dyn Reflect> {
Some(self)
}
fn try_as_reflect_mut(&mut self) -> Option<&mut dyn Reflect> {
Some(self)
}
fn reflect_kind(&self) -> ReflectKind {
ReflectKind::Opaque
}
fn reflect_ref(&self) -> ReflectRef<'_> {
ReflectRef::Opaque(self)
}
fn reflect_mut(&mut self) -> ReflectMut<'_> {
ReflectMut::Opaque(self)
}
fn reflect_owned(self: Box<Self>) -> ReflectOwned {
ReflectOwned::Opaque(self)
}
fn reflect_clone(&self) -> Result<Box<dyn Reflect>, ReflectCloneError> {
Ok(Box::new(self.clone()))
}
fn reflect_hash(&self) -> Option<u64> {
let mut hasher = reflect_hasher();
Hash::hash(&Any::type_id(self), &mut hasher);
Hash::hash(self, &mut hasher);
Some(hasher.finish())
}
fn reflect_partial_eq(&self, value: &dyn PartialReflect) -> Option<bool> {
if let Some(value) = value.try_downcast_ref::<Self>() {
Some(PartialEq::eq(self, value))
} else {
Some(false)
}
}
fn debug(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(self, f)
}
fn try_apply(&mut self, value: &dyn PartialReflect) -> Result<(), ApplyError> {
if let Some(value) = value.try_downcast_ref::<Self>() {
self.clone_from(value);
} else {
return Err(ApplyError::MismatchedTypes {
from_type: value.reflect_type_path().into(),
// If we invoke the reflect_type_path on self directly the borrow checker complains that the lifetime of self must outlive 'static
to_type: Self::type_path().into(),
});
}
Ok(())
}
}
impl_full_reflect!(for Cow<'static, str>);
impl Typed for Cow<'static, str> {
fn type_info() -> &'static TypeInfo {
static CELL: NonGenericTypeInfoCell = NonGenericTypeInfoCell::new();
CELL.get_or_set(|| TypeInfo::Opaque(OpaqueInfo::new::<Self>()))
}
}
impl GetTypeRegistration for Cow<'static, str> {
fn get_type_registration() -> TypeRegistration {
let mut registration = TypeRegistration::of::<Cow<'static, str>>();
registration.insert::<ReflectDeserialize>(FromType::<Cow<'static, str>>::from_type());
registration.insert::<ReflectFromPtr>(FromType::<Cow<'static, str>>::from_type());
registration.insert::<ReflectFromReflect>(FromType::<Cow<'static, str>>::from_type());
registration.insert::<ReflectSerialize>(FromType::<Cow<'static, str>>::from_type());
registration
}
}
impl FromReflect for Cow<'static, str> {
fn from_reflect(reflect: &dyn PartialReflect) -> Option<Self> {
Some(reflect.try_downcast_ref::<Cow<'static, str>>()?.clone())
}
}
#[cfg(feature = "functions")]
crate::func::macros::impl_function_traits!(Cow<'static, str>);
impl<T: FromReflect + MaybeTyped + Clone + TypePath + GetTypeRegistration> List
for Cow<'static, [T]>
{
fn get(&self, index: usize) -> Option<&dyn PartialReflect> {
self.as_ref().get(index).map(|x| x as &dyn PartialReflect)
}
fn get_mut(&mut self, index: usize) -> Option<&mut dyn PartialReflect> {
self.to_mut()
.get_mut(index)
.map(|x| x as &mut dyn PartialReflect)
}
fn insert(&mut self, index: usize, element: Box<dyn PartialReflect>) {
let value = T::take_from_reflect(element).unwrap_or_else(|value| {
panic!(
"Attempted to insert invalid value of type {}.",
value.reflect_type_path()
);
});
self.to_mut().insert(index, value);
}
fn remove(&mut self, index: usize) -> Box<dyn PartialReflect> {
Box::new(self.to_mut().remove(index))
}
fn push(&mut self, value: Box<dyn PartialReflect>) {
let value = T::take_from_reflect(value).unwrap_or_else(|value| {
panic!(
"Attempted to push invalid value of type {}.",
value.reflect_type_path()
)
});
self.to_mut().push(value);
}
fn pop(&mut self) -> Option<Box<dyn PartialReflect>> {
self.to_mut()
.pop()
.map(|value| Box::new(value) as Box<dyn PartialReflect>)
}
fn len(&self) -> usize {
self.as_ref().len()
}
fn iter(&self) -> ListIter<'_> {
ListIter::new(self)
}
fn drain(&mut self) -> Vec<Box<dyn PartialReflect>> {
self.to_mut()
.drain(..)
.map(|value| Box::new(value) as Box<dyn PartialReflect>)
.collect()
}
}
impl<T: FromReflect + MaybeTyped + Clone + TypePath + GetTypeRegistration> PartialReflect
for Cow<'static, [T]>
{
fn get_represented_type_info(&self) -> Option<&'static TypeInfo> {
Some(<Self as Typed>::type_info())
}
#[inline]
fn into_partial_reflect(self: Box<Self>) -> Box<dyn PartialReflect> {
self
}
fn as_partial_reflect(&self) -> &dyn PartialReflect {
self
}
fn as_partial_reflect_mut(&mut self) -> &mut dyn PartialReflect {
self
}
fn try_into_reflect(self: Box<Self>) -> Result<Box<dyn Reflect>, Box<dyn PartialReflect>> {
Ok(self)
}
fn try_as_reflect(&self) -> Option<&dyn Reflect> {
Some(self)
}
fn try_as_reflect_mut(&mut self) -> Option<&mut dyn Reflect> {
Some(self)
}
fn reflect_kind(&self) -> ReflectKind {
ReflectKind::List
}
fn reflect_ref(&self) -> ReflectRef<'_> {
ReflectRef::List(self)
}
fn reflect_mut(&mut self) -> ReflectMut<'_> {
ReflectMut::List(self)
}
fn reflect_owned(self: Box<Self>) -> ReflectOwned {
ReflectOwned::List(self)
}
fn reflect_clone(&self) -> Result<Box<dyn Reflect>, ReflectCloneError> {
Ok(Box::new(self.clone()))
}
fn reflect_hash(&self) -> Option<u64> {
crate::list_hash(self)
}
fn reflect_partial_eq(&self, value: &dyn PartialReflect) -> Option<bool> {
crate::list_partial_eq(self, value)
}
fn apply(&mut self, value: &dyn PartialReflect) {
crate::list_apply(self, value);
}
fn try_apply(&mut self, value: &dyn PartialReflect) -> Result<(), ApplyError> {
crate::list_try_apply(self, value)
}
}
impl_full_reflect!(
<T> for Cow<'static, [T]>
where
T: FromReflect + Clone + MaybeTyped + TypePath + GetTypeRegistration,
);
impl<T: FromReflect + MaybeTyped + Clone + TypePath + GetTypeRegistration> Typed
for Cow<'static, [T]>
{
fn type_info() -> &'static TypeInfo {
static CELL: GenericTypeInfoCell = GenericTypeInfoCell::new();
CELL.get_or_insert::<Self, _>(|| TypeInfo::List(ListInfo::new::<Self, T>()))
}
}
impl<T: FromReflect + MaybeTyped + Clone + TypePath + GetTypeRegistration> GetTypeRegistration
for Cow<'static, [T]>
{
fn get_type_registration() -> TypeRegistration {
TypeRegistration::of::<Cow<'static, [T]>>()
}
fn register_type_dependencies(registry: &mut TypeRegistry) {
registry.register::<T>();
}
}
impl<T: FromReflect + MaybeTyped + Clone + TypePath + GetTypeRegistration> FromReflect
for Cow<'static, [T]>
{
fn from_reflect(reflect: &dyn PartialReflect) -> Option<Self> {
let ref_list = reflect.reflect_ref().as_list().ok()?;
let mut temp_vec = Vec::with_capacity(ref_list.len());
for field in ref_list.iter() {
temp_vec.push(T::from_reflect(field)?);
}
Some(temp_vec.into())
}
}
#[cfg(feature = "functions")]
crate::func::macros::impl_function_traits!(Cow<'static, [T]>; <T: FromReflect + MaybeTyped + Clone + TypePath + GetTypeRegistration>);
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/impls/alloc/vec.rs | crates/bevy_reflect/src/impls/alloc/vec.rs | use bevy_reflect_derive::impl_type_path;
use crate::impls::macros::impl_reflect_for_veclike;
#[cfg(feature = "functions")]
use crate::{
from_reflect::FromReflect, type_info::MaybeTyped, type_path::TypePath,
type_registry::GetTypeRegistration,
};
impl_reflect_for_veclike!(
::alloc::vec::Vec<T>,
::alloc::vec::Vec::insert,
::alloc::vec::Vec::remove,
::alloc::vec::Vec::push,
::alloc::vec::Vec::pop,
[T]
);
impl_type_path!(::alloc::vec::Vec<T>);
#[cfg(feature = "functions")]
crate::func::macros::impl_function_traits!(::alloc::vec::Vec<T>; <T: FromReflect + MaybeTyped + TypePath + GetTypeRegistration>);
#[cfg(test)]
mod tests {
use alloc::vec;
use bevy_reflect::PartialReflect;
#[test]
fn should_partial_eq_vec() {
let a: &dyn PartialReflect = &vec![1, 2, 3];
let b: &dyn PartialReflect = &vec![1, 2, 3];
let c: &dyn PartialReflect = &vec![3, 2, 1];
assert!(a.reflect_partial_eq(b).unwrap_or_default());
assert!(!a.reflect_partial_eq(c).unwrap_or_default());
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/impls/alloc/string.rs | crates/bevy_reflect/src/impls/alloc/string.rs | use crate::{
std_traits::ReflectDefault,
type_registry::{ReflectDeserialize, ReflectSerialize},
};
use bevy_reflect_derive::impl_reflect_opaque;
impl_reflect_opaque!(::alloc::string::String(
Clone,
Debug,
Hash,
PartialEq,
Serialize,
Deserialize,
Default
));
#[cfg(test)]
mod tests {
use alloc::string::String;
use bevy_reflect::PartialReflect;
#[test]
fn should_partial_eq_string() {
let a: &dyn PartialReflect = &String::from("Hello");
let b: &dyn PartialReflect = &String::from("Hello");
let c: &dyn PartialReflect = &String::from("World");
assert!(a.reflect_partial_eq(b).unwrap_or_default());
assert!(!a.reflect_partial_eq(c).unwrap_or_default());
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/impls/alloc/mod.rs | crates/bevy_reflect/src/impls/alloc/mod.rs | mod borrow;
mod collections;
mod string;
mod vec;
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/impls/alloc/collections/binary_heap.rs | crates/bevy_reflect/src/impls/alloc/collections/binary_heap.rs | use bevy_reflect_derive::impl_reflect_opaque;
impl_reflect_opaque!(::alloc::collections::BinaryHeap<T: Clone>(Clone));
#[cfg(test)]
mod tests {
use alloc::collections::BTreeMap;
use bevy_reflect::Reflect;
#[test]
fn should_partial_eq_btree_map() {
let mut a = BTreeMap::new();
a.insert(0usize, 1.23_f64);
let b = a.clone();
let mut c = BTreeMap::new();
c.insert(0usize, 3.21_f64);
let a: &dyn Reflect = &a;
let b: &dyn Reflect = &b;
let c: &dyn Reflect = &c;
assert!(a
.reflect_partial_eq(b.as_partial_reflect())
.unwrap_or_default());
assert!(!a
.reflect_partial_eq(c.as_partial_reflect())
.unwrap_or_default());
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/impls/alloc/collections/mod.rs | crates/bevy_reflect/src/impls/alloc/collections/mod.rs | mod binary_heap;
mod btree;
mod vec_deque;
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/impls/alloc/collections/vec_deque.rs | crates/bevy_reflect/src/impls/alloc/collections/vec_deque.rs | use bevy_reflect_derive::impl_type_path;
use crate::impls::macros::impl_reflect_for_veclike;
#[cfg(feature = "functions")]
use crate::{
from_reflect::FromReflect, type_info::MaybeTyped, type_path::TypePath,
type_registry::GetTypeRegistration,
};
impl_reflect_for_veclike!(
::alloc::collections::VecDeque<T>,
::alloc::collections::VecDeque::insert,
::alloc::collections::VecDeque::remove,
::alloc::collections::VecDeque::push_back,
::alloc::collections::VecDeque::pop_back,
::alloc::collections::VecDeque::<T>
);
impl_type_path!(::alloc::collections::VecDeque<T>);
#[cfg(feature = "functions")]
crate::func::macros::impl_function_traits!(::alloc::collections::VecDeque<T>; <T: FromReflect + MaybeTyped + TypePath + GetTypeRegistration>);
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/impls/alloc/collections/btree/map.rs | crates/bevy_reflect/src/impls/alloc/collections/btree/map.rs | use crate::{
error::ReflectCloneError,
generics::{Generics, TypeParamInfo},
kind::{ReflectKind, ReflectMut, ReflectOwned, ReflectRef},
map::{map_apply, map_partial_eq, map_try_apply, Map, MapInfo},
prelude::*,
reflect::{impl_full_reflect, ApplyError},
type_info::{MaybeTyped, TypeInfo, Typed},
type_registry::{FromType, GetTypeRegistration, ReflectFromPtr, TypeRegistration},
utility::GenericTypeInfoCell,
};
use alloc::vec::Vec;
use bevy_platform::prelude::*;
use bevy_reflect_derive::impl_type_path;
impl<K, V> Map for ::alloc::collections::BTreeMap<K, V>
where
K: FromReflect + MaybeTyped + TypePath + GetTypeRegistration + Eq + Ord,
V: FromReflect + MaybeTyped + TypePath + GetTypeRegistration,
{
fn get(&self, key: &dyn PartialReflect) -> Option<&dyn PartialReflect> {
key.try_downcast_ref::<K>()
.and_then(|key| Self::get(self, key))
.map(|value| value as &dyn PartialReflect)
}
fn get_mut(&mut self, key: &dyn PartialReflect) -> Option<&mut dyn PartialReflect> {
key.try_downcast_ref::<K>()
.and_then(move |key| Self::get_mut(self, key))
.map(|value| value as &mut dyn PartialReflect)
}
fn len(&self) -> usize {
Self::len(self)
}
fn iter(&self) -> Box<dyn Iterator<Item = (&dyn PartialReflect, &dyn PartialReflect)> + '_> {
Box::new(
self.iter()
.map(|(k, v)| (k as &dyn PartialReflect, v as &dyn PartialReflect)),
)
}
fn drain(&mut self) -> Vec<(Box<dyn PartialReflect>, Box<dyn PartialReflect>)> {
// BTreeMap doesn't have a `drain` function. See
// https://github.com/rust-lang/rust/issues/81074. So we have to fake one by popping
// elements off one at a time.
let mut result = Vec::with_capacity(self.len());
while let Some((k, v)) = self.pop_first() {
result.push((
Box::new(k) as Box<dyn PartialReflect>,
Box::new(v) as Box<dyn PartialReflect>,
));
}
result
}
fn retain(&mut self, f: &mut dyn FnMut(&dyn PartialReflect, &mut dyn PartialReflect) -> bool) {
self.retain(move |k, v| f(k, v));
}
fn insert_boxed(
&mut self,
key: Box<dyn PartialReflect>,
value: Box<dyn PartialReflect>,
) -> Option<Box<dyn PartialReflect>> {
let key = K::take_from_reflect(key).unwrap_or_else(|key| {
panic!(
"Attempted to insert invalid key of type {}.",
key.reflect_type_path()
)
});
let value = V::take_from_reflect(value).unwrap_or_else(|value| {
panic!(
"Attempted to insert invalid value of type {}.",
value.reflect_type_path()
)
});
self.insert(key, value)
.map(|old_value| Box::new(old_value) as Box<dyn PartialReflect>)
}
fn remove(&mut self, key: &dyn PartialReflect) -> Option<Box<dyn PartialReflect>> {
let mut from_reflect = None;
key.try_downcast_ref::<K>()
.or_else(|| {
from_reflect = K::from_reflect(key);
from_reflect.as_ref()
})
.and_then(|key| self.remove(key))
.map(|value| Box::new(value) as Box<dyn PartialReflect>)
}
}
impl<K, V> PartialReflect for ::alloc::collections::BTreeMap<K, V>
where
K: FromReflect + MaybeTyped + TypePath + GetTypeRegistration + Eq + Ord,
V: FromReflect + MaybeTyped + TypePath + GetTypeRegistration,
{
fn get_represented_type_info(&self) -> Option<&'static TypeInfo> {
Some(<Self as Typed>::type_info())
}
#[inline]
fn into_partial_reflect(self: Box<Self>) -> Box<dyn PartialReflect> {
self
}
fn as_partial_reflect(&self) -> &dyn PartialReflect {
self
}
fn as_partial_reflect_mut(&mut self) -> &mut dyn PartialReflect {
self
}
#[inline]
fn try_into_reflect(self: Box<Self>) -> Result<Box<dyn Reflect>, Box<dyn PartialReflect>> {
Ok(self)
}
fn try_as_reflect(&self) -> Option<&dyn Reflect> {
Some(self)
}
fn try_as_reflect_mut(&mut self) -> Option<&mut dyn Reflect> {
Some(self)
}
fn reflect_kind(&self) -> ReflectKind {
ReflectKind::Map
}
fn reflect_ref(&self) -> ReflectRef<'_> {
ReflectRef::Map(self)
}
fn reflect_mut(&mut self) -> ReflectMut<'_> {
ReflectMut::Map(self)
}
fn reflect_owned(self: Box<Self>) -> ReflectOwned {
ReflectOwned::Map(self)
}
fn reflect_clone(&self) -> Result<Box<dyn Reflect>, ReflectCloneError> {
let mut map = Self::new();
for (key, value) in self.iter() {
let key = key.reflect_clone_and_take()?;
let value = value.reflect_clone_and_take()?;
map.insert(key, value);
}
Ok(Box::new(map))
}
fn reflect_partial_eq(&self, value: &dyn PartialReflect) -> Option<bool> {
map_partial_eq(self, value)
}
fn apply(&mut self, value: &dyn PartialReflect) {
map_apply(self, value);
}
fn try_apply(&mut self, value: &dyn PartialReflect) -> Result<(), ApplyError> {
map_try_apply(self, value)
}
}
impl_full_reflect!(
<K, V> for ::alloc::collections::BTreeMap<K, V>
where
K: FromReflect + MaybeTyped + TypePath + GetTypeRegistration + Eq + Ord,
V: FromReflect + MaybeTyped + TypePath + GetTypeRegistration,
);
impl<K, V> Typed for ::alloc::collections::BTreeMap<K, V>
where
K: FromReflect + MaybeTyped + TypePath + GetTypeRegistration + Eq + Ord,
V: FromReflect + MaybeTyped + TypePath + GetTypeRegistration,
{
fn type_info() -> &'static TypeInfo {
static CELL: GenericTypeInfoCell = GenericTypeInfoCell::new();
CELL.get_or_insert::<Self, _>(|| {
TypeInfo::Map(
MapInfo::new::<Self, K, V>().with_generics(Generics::from_iter([
TypeParamInfo::new::<K>("K"),
TypeParamInfo::new::<V>("V"),
])),
)
})
}
}
impl<K, V> GetTypeRegistration for ::alloc::collections::BTreeMap<K, V>
where
K: FromReflect + MaybeTyped + TypePath + GetTypeRegistration + Eq + Ord,
V: FromReflect + MaybeTyped + TypePath + GetTypeRegistration,
{
fn get_type_registration() -> TypeRegistration {
let mut registration = TypeRegistration::of::<Self>();
registration.insert::<ReflectFromPtr>(FromType::<Self>::from_type());
registration.insert::<ReflectFromReflect>(FromType::<Self>::from_type());
registration
}
}
impl<K, V> FromReflect for ::alloc::collections::BTreeMap<K, V>
where
K: FromReflect + MaybeTyped + TypePath + GetTypeRegistration + Eq + Ord,
V: FromReflect + MaybeTyped + TypePath + GetTypeRegistration,
{
fn from_reflect(reflect: &dyn PartialReflect) -> Option<Self> {
let ref_map = reflect.reflect_ref().as_map().ok()?;
let mut new_map = Self::new();
for (key, value) in ref_map.iter() {
let new_key = K::from_reflect(key)?;
let new_value = V::from_reflect(value)?;
new_map.insert(new_key, new_value);
}
Some(new_map)
}
}
impl_type_path!(::alloc::collections::BTreeMap<K, V>);
#[cfg(feature = "functions")]
crate::func::macros::impl_function_traits!(::alloc::collections::BTreeMap<K, V>;
<
K: FromReflect + MaybeTyped + TypePath + GetTypeRegistration + Eq + Ord,
V: FromReflect + MaybeTyped + TypePath + GetTypeRegistration
>
);
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/impls/alloc/collections/btree/mod.rs | crates/bevy_reflect/src/impls/alloc/collections/btree/mod.rs | mod map;
mod set;
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/impls/alloc/collections/btree/set.rs | crates/bevy_reflect/src/impls/alloc/collections/btree/set.rs | use bevy_reflect_derive::impl_reflect_opaque;
impl_reflect_opaque!(::alloc::collections::BTreeSet<T: Ord + Eq + Clone + Send + Sync>(Clone));
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/impls/std/path.rs | crates/bevy_reflect/src/impls/std/path.rs | use crate::{
error::ReflectCloneError,
kind::{ReflectKind, ReflectMut, ReflectOwned, ReflectRef},
prelude::*,
reflect::ApplyError,
type_info::{OpaqueInfo, TypeInfo, Typed},
type_path::DynamicTypePath,
type_registry::{
FromType, GetTypeRegistration, ReflectDeserialize, ReflectFromPtr, ReflectSerialize,
TypeRegistration,
},
utility::{reflect_hasher, NonGenericTypeInfoCell},
};
use alloc::borrow::Cow;
use bevy_platform::prelude::*;
use bevy_reflect_derive::{impl_reflect_opaque, impl_type_path};
use core::any::Any;
use core::fmt;
use core::hash::{Hash, Hasher};
use std::path::Path;
impl_reflect_opaque!(::std::path::PathBuf(
Clone,
Debug,
Hash,
PartialEq,
Serialize,
Deserialize,
Default
));
impl PartialReflect for &'static Path {
fn get_represented_type_info(&self) -> Option<&'static TypeInfo> {
Some(<Self as Typed>::type_info())
}
#[inline]
fn into_partial_reflect(self: Box<Self>) -> Box<dyn PartialReflect> {
self
}
fn as_partial_reflect(&self) -> &dyn PartialReflect {
self
}
fn as_partial_reflect_mut(&mut self) -> &mut dyn PartialReflect {
self
}
fn try_into_reflect(self: Box<Self>) -> Result<Box<dyn Reflect>, Box<dyn PartialReflect>> {
Ok(self)
}
fn try_as_reflect(&self) -> Option<&dyn Reflect> {
Some(self)
}
fn try_as_reflect_mut(&mut self) -> Option<&mut dyn Reflect> {
Some(self)
}
fn reflect_kind(&self) -> ReflectKind {
ReflectKind::Opaque
}
fn reflect_ref(&self) -> ReflectRef<'_> {
ReflectRef::Opaque(self)
}
fn reflect_mut(&mut self) -> ReflectMut<'_> {
ReflectMut::Opaque(self)
}
fn reflect_owned(self: Box<Self>) -> ReflectOwned {
ReflectOwned::Opaque(self)
}
fn reflect_clone(&self) -> Result<Box<dyn Reflect>, ReflectCloneError> {
Ok(Box::new(*self))
}
fn reflect_hash(&self) -> Option<u64> {
let mut hasher = reflect_hasher();
Hash::hash(&Any::type_id(self), &mut hasher);
Hash::hash(self, &mut hasher);
Some(hasher.finish())
}
fn reflect_partial_eq(&self, value: &dyn PartialReflect) -> Option<bool> {
if let Some(value) = value.try_downcast_ref::<Self>() {
Some(PartialEq::eq(self, value))
} else {
Some(false)
}
}
fn try_apply(&mut self, value: &dyn PartialReflect) -> Result<(), ApplyError> {
if let Some(value) = value.try_downcast_ref::<Self>() {
self.clone_from(value);
Ok(())
} else {
Err(ApplyError::MismatchedTypes {
from_type: value.reflect_type_path().into(),
to_type: <Self as DynamicTypePath>::reflect_type_path(self).into(),
})
}
}
}
impl Reflect for &'static Path {
fn into_any(self: Box<Self>) -> Box<dyn Any> {
self
}
fn as_any(&self) -> &dyn Any {
self
}
fn as_any_mut(&mut self) -> &mut dyn Any {
self
}
fn into_reflect(self: Box<Self>) -> Box<dyn Reflect> {
self
}
fn as_reflect(&self) -> &dyn Reflect {
self
}
fn as_reflect_mut(&mut self) -> &mut dyn Reflect {
self
}
fn set(&mut self, value: Box<dyn Reflect>) -> Result<(), Box<dyn Reflect>> {
*self = value.take()?;
Ok(())
}
}
impl Typed for &'static Path {
fn type_info() -> &'static TypeInfo {
static CELL: NonGenericTypeInfoCell = NonGenericTypeInfoCell::new();
CELL.get_or_set(|| TypeInfo::Opaque(OpaqueInfo::new::<Self>()))
}
}
impl GetTypeRegistration for &'static Path {
fn get_type_registration() -> TypeRegistration {
let mut registration = TypeRegistration::of::<Self>();
registration.insert::<ReflectFromPtr>(FromType::<Self>::from_type());
registration.insert::<ReflectFromReflect>(FromType::<Self>::from_type());
registration
}
}
impl FromReflect for &'static Path {
fn from_reflect(reflect: &dyn PartialReflect) -> Option<Self> {
reflect.try_downcast_ref::<Self>().copied()
}
}
impl PartialReflect for Cow<'static, Path> {
fn get_represented_type_info(&self) -> Option<&'static TypeInfo> {
Some(<Self as Typed>::type_info())
}
#[inline]
fn into_partial_reflect(self: Box<Self>) -> Box<dyn PartialReflect> {
self
}
fn as_partial_reflect(&self) -> &dyn PartialReflect {
self
}
fn as_partial_reflect_mut(&mut self) -> &mut dyn PartialReflect {
self
}
fn try_into_reflect(self: Box<Self>) -> Result<Box<dyn Reflect>, Box<dyn PartialReflect>> {
Ok(self)
}
fn try_as_reflect(&self) -> Option<&dyn Reflect> {
Some(self)
}
fn try_as_reflect_mut(&mut self) -> Option<&mut dyn Reflect> {
Some(self)
}
fn reflect_kind(&self) -> ReflectKind {
ReflectKind::Opaque
}
fn reflect_ref(&self) -> ReflectRef<'_> {
ReflectRef::Opaque(self)
}
fn reflect_mut(&mut self) -> ReflectMut<'_> {
ReflectMut::Opaque(self)
}
fn reflect_owned(self: Box<Self>) -> ReflectOwned {
ReflectOwned::Opaque(self)
}
fn reflect_clone(&self) -> Result<Box<dyn Reflect>, ReflectCloneError> {
Ok(Box::new(self.clone()))
}
fn reflect_hash(&self) -> Option<u64> {
let mut hasher = reflect_hasher();
Hash::hash(&Any::type_id(self), &mut hasher);
Hash::hash(self, &mut hasher);
Some(hasher.finish())
}
fn reflect_partial_eq(&self, value: &dyn PartialReflect) -> Option<bool> {
if let Some(value) = value.try_downcast_ref::<Self>() {
Some(PartialEq::eq(self, value))
} else {
Some(false)
}
}
fn debug(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(&self, f)
}
fn try_apply(&mut self, value: &dyn PartialReflect) -> Result<(), ApplyError> {
if let Some(value) = value.try_downcast_ref::<Self>() {
self.clone_from(value);
Ok(())
} else {
Err(ApplyError::MismatchedTypes {
from_type: value.reflect_type_path().into(),
to_type: <Self as DynamicTypePath>::reflect_type_path(self).into(),
})
}
}
}
impl Reflect for Cow<'static, Path> {
fn into_any(self: Box<Self>) -> Box<dyn Any> {
self
}
fn as_any(&self) -> &dyn Any {
self
}
fn as_any_mut(&mut self) -> &mut dyn Any {
self
}
fn into_reflect(self: Box<Self>) -> Box<dyn Reflect> {
self
}
fn as_reflect(&self) -> &dyn Reflect {
self
}
fn as_reflect_mut(&mut self) -> &mut dyn Reflect {
self
}
fn set(&mut self, value: Box<dyn Reflect>) -> Result<(), Box<dyn Reflect>> {
*self = value.take()?;
Ok(())
}
}
impl Typed for Cow<'static, Path> {
fn type_info() -> &'static TypeInfo {
static CELL: NonGenericTypeInfoCell = NonGenericTypeInfoCell::new();
CELL.get_or_set(|| TypeInfo::Opaque(OpaqueInfo::new::<Self>()))
}
}
impl_type_path!(::std::path::Path);
impl FromReflect for Cow<'static, Path> {
fn from_reflect(reflect: &dyn PartialReflect) -> Option<Self> {
Some(reflect.try_downcast_ref::<Self>()?.clone())
}
}
impl GetTypeRegistration for Cow<'static, Path> {
fn get_type_registration() -> TypeRegistration {
let mut registration = TypeRegistration::of::<Self>();
registration.insert::<ReflectDeserialize>(FromType::<Self>::from_type());
registration.insert::<ReflectFromPtr>(FromType::<Self>::from_type());
registration.insert::<ReflectSerialize>(FromType::<Self>::from_type());
registration.insert::<ReflectFromReflect>(FromType::<Self>::from_type());
registration
}
}
#[cfg(feature = "functions")]
crate::func::macros::impl_function_traits!(Cow<'static, Path>);
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/impls/std/ffi.rs | crates/bevy_reflect/src/impls/std/ffi.rs | #[cfg(any(unix, windows))]
use crate::type_registry::{ReflectDeserialize, ReflectSerialize};
use bevy_reflect_derive::impl_reflect_opaque;
// `Serialize` and `Deserialize` only for platforms supported by serde:
// https://github.com/serde-rs/serde/blob/3ffb86fc70efd3d329519e2dddfa306cc04f167c/serde/src/de/impls.rs#L1732
#[cfg(any(unix, windows))]
impl_reflect_opaque!(::std::ffi::OsString(
Clone,
Debug,
Hash,
PartialEq,
Serialize,
Deserialize
));
#[cfg(not(any(unix, windows)))]
impl_reflect_opaque!(::std::ffi::OsString(Clone, Debug, Hash, PartialEq));
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/impls/std/mod.rs | crates/bevy_reflect/src/impls/std/mod.rs | mod collections;
mod ffi;
mod path;
#[cfg(test)]
mod tests {
use crate::{FromReflect, PartialReflect};
use std::collections::HashMap;
use std::path::Path;
#[test]
fn should_partial_eq_hash_map() {
let mut a = <HashMap<_, _>>::default();
a.insert(0usize, 1.23_f64);
let b = a.clone();
let mut c = <HashMap<_, _>>::default();
c.insert(0usize, 3.21_f64);
let a: &dyn PartialReflect = &a;
let b: &dyn PartialReflect = &b;
let c: &dyn PartialReflect = &c;
assert!(a.reflect_partial_eq(b).unwrap_or_default());
assert!(!a.reflect_partial_eq(c).unwrap_or_default());
}
#[test]
fn path_should_from_reflect() {
let path = Path::new("hello_world.rs");
let output = <&'static Path as FromReflect>::from_reflect(&path).unwrap();
assert_eq!(path, output);
}
#[test]
fn type_id_should_from_reflect() {
let type_id = core::any::TypeId::of::<usize>();
let output = <core::any::TypeId as FromReflect>::from_reflect(&type_id).unwrap();
assert_eq!(type_id, output);
}
#[test]
fn static_str_should_from_reflect() {
let expected = "Hello, World!";
let output = <&'static str as FromReflect>::from_reflect(&expected).unwrap();
assert_eq!(expected, output);
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/impls/std/collections/hash_map.rs | crates/bevy_reflect/src/impls/std/collections/hash_map.rs | use bevy_reflect_derive::impl_type_path;
use crate::impls::macros::impl_reflect_for_hashmap;
#[cfg(feature = "functions")]
use crate::{
from_reflect::FromReflect, type_info::MaybeTyped, type_path::TypePath,
type_registry::GetTypeRegistration,
};
#[cfg(feature = "functions")]
use core::hash::{BuildHasher, Hash};
impl_reflect_for_hashmap!(::std::collections::HashMap<K, V, S>);
impl_type_path!(::std::collections::hash_map::RandomState);
impl_type_path!(::std::collections::HashMap<K, V, S>);
#[cfg(feature = "functions")]
crate::func::macros::impl_function_traits!(::std::collections::HashMap<K, V, S>;
<
K: FromReflect + MaybeTyped + TypePath + GetTypeRegistration + Eq + Hash,
V: FromReflect + MaybeTyped + TypePath + GetTypeRegistration,
S: TypePath + BuildHasher + Default + Send + Sync
>
);
#[cfg(test)]
mod tests {
use crate::Reflect;
use static_assertions::assert_impl_all;
#[test]
fn should_reflect_hashmaps() {
assert_impl_all!(std::collections::HashMap<u32, f32>: Reflect);
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/impls/std/collections/hash_set.rs | crates/bevy_reflect/src/impls/std/collections/hash_set.rs | use bevy_reflect_derive::impl_type_path;
use crate::impls::macros::impl_reflect_for_hashset;
#[cfg(feature = "functions")]
use crate::{from_reflect::FromReflect, type_path::TypePath, type_registry::GetTypeRegistration};
#[cfg(feature = "functions")]
use core::hash::{BuildHasher, Hash};
impl_reflect_for_hashset!(::std::collections::HashSet<V,S>);
impl_type_path!(::std::collections::HashSet<V, S>);
#[cfg(feature = "functions")]
crate::func::macros::impl_function_traits!(::std::collections::HashSet<V, S>;
<
V: Hash + Eq + FromReflect + TypePath + GetTypeRegistration,
S: TypePath + BuildHasher + Default + Send + Sync
>
);
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/impls/std/collections/mod.rs | crates/bevy_reflect/src/impls/std/collections/mod.rs | mod hash_map;
mod hash_set;
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/impls/core/sync.rs | crates/bevy_reflect/src/impls/core/sync.rs | use crate::{
error::ReflectCloneError,
kind::{ReflectKind, ReflectMut, ReflectOwned, ReflectRef},
prelude::*,
reflect::{impl_full_reflect, ApplyError},
type_info::{OpaqueInfo, TypeInfo, Typed},
type_path::DynamicTypePath,
type_registry::{FromType, GetTypeRegistration, ReflectFromPtr, TypeRegistration},
utility::NonGenericTypeInfoCell,
};
use bevy_platform::prelude::*;
use bevy_reflect_derive::impl_type_path;
use core::fmt;
macro_rules! impl_reflect_for_atomic {
($ty:ty, $ordering:expr) => {
impl_type_path!($ty);
const _: () = {
#[cfg(feature = "functions")]
crate::func::macros::impl_function_traits!($ty);
impl GetTypeRegistration for $ty {
fn get_type_registration() -> TypeRegistration {
let mut registration = TypeRegistration::of::<Self>();
registration.insert::<ReflectFromPtr>(FromType::<Self>::from_type());
registration.insert::<ReflectFromReflect>(FromType::<Self>::from_type());
registration.insert::<ReflectDefault>(FromType::<Self>::from_type());
// Serde only supports atomic types when the "std" feature is enabled
#[cfg(feature = "std")]
{
registration.insert::<crate::type_registry::ReflectSerialize>(FromType::<Self>::from_type());
registration.insert::<crate::type_registry::ReflectDeserialize>(FromType::<Self>::from_type());
}
registration
}
}
impl Typed for $ty {
fn type_info() -> &'static TypeInfo {
static CELL: NonGenericTypeInfoCell = NonGenericTypeInfoCell::new();
CELL.get_or_set(|| {
let info = OpaqueInfo::new::<Self>();
TypeInfo::Opaque(info)
})
}
}
impl PartialReflect for $ty {
#[inline]
fn get_represented_type_info(&self) -> Option<&'static TypeInfo> {
Some(<Self as Typed>::type_info())
}
#[inline]
fn into_partial_reflect(self: Box<Self>) -> Box<dyn PartialReflect> {
self
}
#[inline]
fn as_partial_reflect(&self) -> &dyn PartialReflect {
self
}
#[inline]
fn as_partial_reflect_mut(&mut self) -> &mut dyn PartialReflect {
self
}
#[inline]
fn try_into_reflect(
self: Box<Self>,
) -> Result<Box<dyn Reflect>, Box<dyn PartialReflect>> {
Ok(self)
}
#[inline]
fn try_as_reflect(&self) -> Option<&dyn Reflect> {
Some(self)
}
#[inline]
fn try_as_reflect_mut(&mut self) -> Option<&mut dyn Reflect> {
Some(self)
}
#[inline]
fn reflect_clone(&self) -> Result<Box<dyn Reflect>, ReflectCloneError> {
Ok(Box::new(<$ty>::new(self.load($ordering))))
}
#[inline]
fn try_apply(&mut self, value: &dyn PartialReflect) -> Result<(), ApplyError> {
if let Some(value) = value.try_downcast_ref::<Self>() {
*self = <$ty>::new(value.load($ordering));
} else {
return Err(ApplyError::MismatchedTypes {
from_type: Into::into(DynamicTypePath::reflect_type_path(value)),
to_type: Into::into(<Self as TypePath>::type_path()),
});
}
Ok(())
}
#[inline]
fn reflect_kind(&self) -> ReflectKind {
ReflectKind::Opaque
}
#[inline]
fn reflect_ref(&self) -> ReflectRef<'_> {
ReflectRef::Opaque(self)
}
#[inline]
fn reflect_mut(&mut self) -> ReflectMut<'_> {
ReflectMut::Opaque(self)
}
#[inline]
fn reflect_owned(self: Box<Self>) -> ReflectOwned {
ReflectOwned::Opaque(self)
}
fn debug(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(self, f)
}
}
impl FromReflect for $ty {
fn from_reflect(reflect: &dyn PartialReflect) -> Option<Self> {
Some(<$ty>::new(
reflect.try_downcast_ref::<$ty>()?.load($ordering),
))
}
}
};
impl_full_reflect!(for $ty);
};
}
impl_reflect_for_atomic!(
::core::sync::atomic::AtomicIsize,
::core::sync::atomic::Ordering::SeqCst
);
impl_reflect_for_atomic!(
::core::sync::atomic::AtomicUsize,
::core::sync::atomic::Ordering::SeqCst
);
#[cfg(target_has_atomic = "64")]
impl_reflect_for_atomic!(
::core::sync::atomic::AtomicI64,
::core::sync::atomic::Ordering::SeqCst
);
#[cfg(target_has_atomic = "64")]
impl_reflect_for_atomic!(
::core::sync::atomic::AtomicU64,
::core::sync::atomic::Ordering::SeqCst
);
impl_reflect_for_atomic!(
::core::sync::atomic::AtomicI32,
::core::sync::atomic::Ordering::SeqCst
);
impl_reflect_for_atomic!(
::core::sync::atomic::AtomicU32,
::core::sync::atomic::Ordering::SeqCst
);
impl_reflect_for_atomic!(
::core::sync::atomic::AtomicI16,
::core::sync::atomic::Ordering::SeqCst
);
impl_reflect_for_atomic!(
::core::sync::atomic::AtomicU16,
::core::sync::atomic::Ordering::SeqCst
);
impl_reflect_for_atomic!(
::core::sync::atomic::AtomicI8,
::core::sync::atomic::Ordering::SeqCst
);
impl_reflect_for_atomic!(
::core::sync::atomic::AtomicU8,
::core::sync::atomic::Ordering::SeqCst
);
impl_reflect_for_atomic!(
::core::sync::atomic::AtomicBool,
::core::sync::atomic::Ordering::SeqCst
);
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/impls/core/panic.rs | crates/bevy_reflect/src/impls/core/panic.rs | use crate::{
error::ReflectCloneError,
kind::{ReflectKind, ReflectMut, ReflectOwned, ReflectRef},
prelude::*,
reflect::ApplyError,
type_info::{OpaqueInfo, TypeInfo, Typed},
type_path::DynamicTypePath,
type_registry::{FromType, GetTypeRegistration, ReflectFromPtr, TypeRegistration},
utility::{reflect_hasher, NonGenericTypeInfoCell},
};
use bevy_platform::prelude::*;
use core::any::Any;
use core::hash::{Hash, Hasher};
use core::panic::Location;
impl TypePath for &'static Location<'static> {
fn type_path() -> &'static str {
"core::panic::Location"
}
fn short_type_path() -> &'static str {
"Location"
}
}
impl PartialReflect for &'static Location<'static> {
fn get_represented_type_info(&self) -> Option<&'static TypeInfo> {
Some(<Self as Typed>::type_info())
}
#[inline]
fn into_partial_reflect(self: Box<Self>) -> Box<dyn PartialReflect> {
self
}
fn as_partial_reflect(&self) -> &dyn PartialReflect {
self
}
fn as_partial_reflect_mut(&mut self) -> &mut dyn PartialReflect {
self
}
fn try_into_reflect(self: Box<Self>) -> Result<Box<dyn Reflect>, Box<dyn PartialReflect>> {
Ok(self)
}
fn try_as_reflect(&self) -> Option<&dyn Reflect> {
Some(self)
}
fn try_as_reflect_mut(&mut self) -> Option<&mut dyn Reflect> {
Some(self)
}
fn reflect_kind(&self) -> ReflectKind {
ReflectKind::Opaque
}
fn reflect_ref(&self) -> ReflectRef<'_> {
ReflectRef::Opaque(self)
}
fn reflect_mut(&mut self) -> ReflectMut<'_> {
ReflectMut::Opaque(self)
}
fn reflect_owned(self: Box<Self>) -> ReflectOwned {
ReflectOwned::Opaque(self)
}
fn reflect_clone(&self) -> Result<Box<dyn Reflect>, ReflectCloneError> {
Ok(Box::new(*self))
}
fn reflect_hash(&self) -> Option<u64> {
let mut hasher = reflect_hasher();
Hash::hash(&Any::type_id(self), &mut hasher);
Hash::hash(self, &mut hasher);
Some(hasher.finish())
}
fn reflect_partial_eq(&self, value: &dyn PartialReflect) -> Option<bool> {
if let Some(value) = value.try_downcast_ref::<Self>() {
Some(PartialEq::eq(self, value))
} else {
Some(false)
}
}
fn try_apply(&mut self, value: &dyn PartialReflect) -> Result<(), ApplyError> {
if let Some(value) = value.try_downcast_ref::<Self>() {
self.clone_from(value);
Ok(())
} else {
Err(ApplyError::MismatchedTypes {
from_type: value.reflect_type_path().into(),
to_type: <Self as DynamicTypePath>::reflect_type_path(self).into(),
})
}
}
}
impl Reflect for &'static Location<'static> {
fn into_any(self: Box<Self>) -> Box<dyn Any> {
self
}
fn as_any(&self) -> &dyn Any {
self
}
fn as_any_mut(&mut self) -> &mut dyn Any {
self
}
fn into_reflect(self: Box<Self>) -> Box<dyn Reflect> {
self
}
fn as_reflect(&self) -> &dyn Reflect {
self
}
fn as_reflect_mut(&mut self) -> &mut dyn Reflect {
self
}
fn set(&mut self, value: Box<dyn Reflect>) -> Result<(), Box<dyn Reflect>> {
*self = value.take()?;
Ok(())
}
}
impl Typed for &'static Location<'static> {
fn type_info() -> &'static TypeInfo {
static CELL: NonGenericTypeInfoCell = NonGenericTypeInfoCell::new();
CELL.get_or_set(|| TypeInfo::Opaque(OpaqueInfo::new::<Self>()))
}
}
impl GetTypeRegistration for &'static Location<'static> {
fn get_type_registration() -> TypeRegistration {
let mut registration = TypeRegistration::of::<Self>();
registration.insert::<ReflectFromPtr>(FromType::<Self>::from_type());
registration.insert::<ReflectFromReflect>(FromType::<Self>::from_type());
registration
}
}
impl FromReflect for &'static Location<'static> {
fn from_reflect(reflect: &dyn PartialReflect) -> Option<Self> {
reflect.try_downcast_ref::<Self>().copied()
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/impls/core/time.rs | crates/bevy_reflect/src/impls/core/time.rs | use crate::{
std_traits::ReflectDefault,
type_registry::{ReflectDeserialize, ReflectSerialize},
};
use bevy_reflect_derive::impl_reflect_opaque;
impl_reflect_opaque!(::core::time::Duration(
Clone,
Debug,
Hash,
PartialEq,
Serialize,
Deserialize,
Default
));
#[cfg(test)]
mod tests {
use bevy_reflect::{ReflectSerialize, TypeRegistry};
use core::time::Duration;
#[test]
fn can_serialize_duration() {
let mut type_registry = TypeRegistry::default();
type_registry.register::<Duration>();
let reflect_serialize = type_registry
.get_type_data::<ReflectSerialize>(core::any::TypeId::of::<Duration>())
.unwrap();
let _serializable = reflect_serialize.get_serializable(&Duration::ZERO);
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/impls/core/primitives.rs | crates/bevy_reflect/src/impls/core/primitives.rs | use crate::{
array::{Array, ArrayInfo, ArrayIter},
error::ReflectCloneError,
kind::{ReflectKind, ReflectMut, ReflectOwned, ReflectRef},
prelude::*,
reflect::ApplyError,
type_info::{MaybeTyped, OpaqueInfo, TypeInfo, Typed},
type_registry::{
FromType, GetTypeRegistration, ReflectDeserialize, ReflectFromPtr, ReflectSerialize,
TypeRegistration, TypeRegistry,
},
utility::{reflect_hasher, GenericTypeInfoCell, GenericTypePathCell, NonGenericTypeInfoCell},
};
use bevy_platform::prelude::*;
use bevy_reflect_derive::{impl_reflect_opaque, impl_type_path};
use core::any::Any;
use core::fmt;
use core::hash::{Hash, Hasher};
impl_reflect_opaque!(bool(
Clone,
Debug,
Hash,
PartialEq,
Serialize,
Deserialize,
Default
));
impl_reflect_opaque!(char(
Clone,
Debug,
Hash,
PartialEq,
Serialize,
Deserialize,
Default
));
impl_reflect_opaque!(u8(
Clone,
Debug,
Hash,
PartialEq,
Serialize,
Deserialize,
Default
));
impl_reflect_opaque!(u16(
Clone,
Debug,
Hash,
PartialEq,
Serialize,
Deserialize,
Default
));
impl_reflect_opaque!(u32(
Clone,
Debug,
Hash,
PartialEq,
Serialize,
Deserialize,
Default
));
impl_reflect_opaque!(u64(
Clone,
Debug,
Hash,
PartialEq,
Serialize,
Deserialize,
Default
));
impl_reflect_opaque!(u128(
Clone,
Debug,
Hash,
PartialEq,
Serialize,
Deserialize,
Default
));
impl_reflect_opaque!(usize(
Clone,
Debug,
Hash,
PartialEq,
Serialize,
Deserialize,
Default
));
impl_reflect_opaque!(i8(
Clone,
Debug,
Hash,
PartialEq,
Serialize,
Deserialize,
Default
));
impl_reflect_opaque!(i16(
Clone,
Debug,
Hash,
PartialEq,
Serialize,
Deserialize,
Default
));
impl_reflect_opaque!(i32(
Clone,
Debug,
Hash,
PartialEq,
Serialize,
Deserialize,
Default
));
impl_reflect_opaque!(i64(
Clone,
Debug,
Hash,
PartialEq,
Serialize,
Deserialize,
Default
));
impl_reflect_opaque!(i128(
Clone,
Debug,
Hash,
PartialEq,
Serialize,
Deserialize,
Default
));
impl_reflect_opaque!(isize(
Clone,
Debug,
Hash,
PartialEq,
Serialize,
Deserialize,
Default
));
impl_reflect_opaque!(f32(
Clone,
Debug,
PartialEq,
Serialize,
Deserialize,
Default
));
impl_reflect_opaque!(f64(
Clone,
Debug,
PartialEq,
Serialize,
Deserialize,
Default
));
impl_type_path!(str);
impl PartialReflect for &'static str {
fn get_represented_type_info(&self) -> Option<&'static TypeInfo> {
Some(<Self as Typed>::type_info())
}
#[inline]
fn into_partial_reflect(self: Box<Self>) -> Box<dyn PartialReflect> {
self
}
fn as_partial_reflect(&self) -> &dyn PartialReflect {
self
}
fn as_partial_reflect_mut(&mut self) -> &mut dyn PartialReflect {
self
}
fn try_into_reflect(self: Box<Self>) -> Result<Box<dyn Reflect>, Box<dyn PartialReflect>> {
Ok(self)
}
fn try_as_reflect(&self) -> Option<&dyn Reflect> {
Some(self)
}
fn try_as_reflect_mut(&mut self) -> Option<&mut dyn Reflect> {
Some(self)
}
fn reflect_ref(&self) -> ReflectRef<'_> {
ReflectRef::Opaque(self)
}
fn reflect_mut(&mut self) -> ReflectMut<'_> {
ReflectMut::Opaque(self)
}
fn reflect_owned(self: Box<Self>) -> ReflectOwned {
ReflectOwned::Opaque(self)
}
fn reflect_clone(&self) -> Result<Box<dyn Reflect>, ReflectCloneError> {
Ok(Box::new(*self))
}
fn reflect_hash(&self) -> Option<u64> {
let mut hasher = reflect_hasher();
Hash::hash(&Any::type_id(self), &mut hasher);
Hash::hash(self, &mut hasher);
Some(hasher.finish())
}
fn reflect_partial_eq(&self, value: &dyn PartialReflect) -> Option<bool> {
if let Some(value) = value.try_downcast_ref::<Self>() {
Some(PartialEq::eq(self, value))
} else {
Some(false)
}
}
fn debug(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(&self, f)
}
fn try_apply(&mut self, value: &dyn PartialReflect) -> Result<(), ApplyError> {
if let Some(value) = value.try_downcast_ref::<Self>() {
self.clone_from(value);
} else {
return Err(ApplyError::MismatchedTypes {
from_type: value.reflect_type_path().into(),
to_type: Self::type_path().into(),
});
}
Ok(())
}
}
impl Reflect for &'static str {
fn into_any(self: Box<Self>) -> Box<dyn Any> {
self
}
fn as_any(&self) -> &dyn Any {
self
}
fn as_any_mut(&mut self) -> &mut dyn Any {
self
}
fn into_reflect(self: Box<Self>) -> Box<dyn Reflect> {
self
}
fn as_reflect(&self) -> &dyn Reflect {
self
}
fn as_reflect_mut(&mut self) -> &mut dyn Reflect {
self
}
fn set(&mut self, value: Box<dyn Reflect>) -> Result<(), Box<dyn Reflect>> {
*self = value.take()?;
Ok(())
}
}
impl Typed for &'static str {
fn type_info() -> &'static TypeInfo {
static CELL: NonGenericTypeInfoCell = NonGenericTypeInfoCell::new();
CELL.get_or_set(|| TypeInfo::Opaque(OpaqueInfo::new::<Self>()))
}
}
impl GetTypeRegistration for &'static str {
fn get_type_registration() -> TypeRegistration {
let mut registration = TypeRegistration::of::<Self>();
registration.insert::<ReflectFromPtr>(FromType::<Self>::from_type());
registration.insert::<ReflectFromReflect>(FromType::<Self>::from_type());
registration.insert::<ReflectSerialize>(FromType::<Self>::from_type());
registration
}
}
impl FromReflect for &'static str {
fn from_reflect(reflect: &dyn PartialReflect) -> Option<Self> {
reflect.try_downcast_ref::<Self>().copied()
}
}
impl<T: Reflect + MaybeTyped + TypePath + GetTypeRegistration, const N: usize> Array for [T; N] {
#[inline]
fn get(&self, index: usize) -> Option<&dyn PartialReflect> {
<[T]>::get(self, index).map(|value| value as &dyn PartialReflect)
}
#[inline]
fn get_mut(&mut self, index: usize) -> Option<&mut dyn PartialReflect> {
<[T]>::get_mut(self, index).map(|value| value as &mut dyn PartialReflect)
}
#[inline]
fn len(&self) -> usize {
N
}
#[inline]
fn iter(&self) -> ArrayIter<'_> {
ArrayIter::new(self)
}
#[inline]
fn drain(self: Box<Self>) -> Vec<Box<dyn PartialReflect>> {
self.into_iter()
.map(|value| Box::new(value) as Box<dyn PartialReflect>)
.collect()
}
}
impl<T: Reflect + MaybeTyped + TypePath + GetTypeRegistration, const N: usize> PartialReflect
for [T; N]
{
fn get_represented_type_info(&self) -> Option<&'static TypeInfo> {
Some(<Self as Typed>::type_info())
}
#[inline]
fn into_partial_reflect(self: Box<Self>) -> Box<dyn PartialReflect> {
self
}
fn as_partial_reflect(&self) -> &dyn PartialReflect {
self
}
fn as_partial_reflect_mut(&mut self) -> &mut dyn PartialReflect {
self
}
fn try_into_reflect(self: Box<Self>) -> Result<Box<dyn Reflect>, Box<dyn PartialReflect>> {
Ok(self)
}
fn try_as_reflect(&self) -> Option<&dyn Reflect> {
Some(self)
}
fn try_as_reflect_mut(&mut self) -> Option<&mut dyn Reflect> {
Some(self)
}
#[inline]
fn reflect_kind(&self) -> ReflectKind {
ReflectKind::Array
}
#[inline]
fn reflect_ref(&self) -> ReflectRef<'_> {
ReflectRef::Array(self)
}
#[inline]
fn reflect_mut(&mut self) -> ReflectMut<'_> {
ReflectMut::Array(self)
}
#[inline]
fn reflect_owned(self: Box<Self>) -> ReflectOwned {
ReflectOwned::Array(self)
}
#[inline]
fn reflect_hash(&self) -> Option<u64> {
crate::array_hash(self)
}
#[inline]
fn reflect_partial_eq(&self, value: &dyn PartialReflect) -> Option<bool> {
crate::array_partial_eq(self, value)
}
fn apply(&mut self, value: &dyn PartialReflect) {
crate::array_apply(self, value);
}
#[inline]
fn try_apply(&mut self, value: &dyn PartialReflect) -> Result<(), ApplyError> {
crate::array_try_apply(self, value)
}
}
impl<T: Reflect + MaybeTyped + TypePath + GetTypeRegistration, const N: usize> Reflect for [T; N] {
#[inline]
fn into_any(self: Box<Self>) -> Box<dyn Any> {
self
}
#[inline]
fn as_any(&self) -> &dyn Any {
self
}
#[inline]
fn as_any_mut(&mut self) -> &mut dyn Any {
self
}
#[inline]
fn into_reflect(self: Box<Self>) -> Box<dyn Reflect> {
self
}
#[inline]
fn as_reflect(&self) -> &dyn Reflect {
self
}
#[inline]
fn as_reflect_mut(&mut self) -> &mut dyn Reflect {
self
}
#[inline]
fn set(&mut self, value: Box<dyn Reflect>) -> Result<(), Box<dyn Reflect>> {
*self = value.take()?;
Ok(())
}
}
impl<T: FromReflect + MaybeTyped + TypePath + GetTypeRegistration, const N: usize> FromReflect
for [T; N]
{
fn from_reflect(reflect: &dyn PartialReflect) -> Option<Self> {
let ref_array = reflect.reflect_ref().as_array().ok()?;
let mut temp_vec = Vec::with_capacity(ref_array.len());
for field in ref_array.iter() {
temp_vec.push(T::from_reflect(field)?);
}
temp_vec.try_into().ok()
}
}
impl<T: Reflect + MaybeTyped + TypePath + GetTypeRegistration, const N: usize> Typed for [T; N] {
fn type_info() -> &'static TypeInfo {
static CELL: GenericTypeInfoCell = GenericTypeInfoCell::new();
CELL.get_or_insert::<Self, _>(|| TypeInfo::Array(ArrayInfo::new::<Self, T>(N)))
}
}
impl<T: TypePath, const N: usize> TypePath for [T; N] {
fn type_path() -> &'static str {
static CELL: GenericTypePathCell = GenericTypePathCell::new();
CELL.get_or_insert::<Self, _>(|| format!("[{t}; {N}]", t = T::type_path()))
}
fn short_type_path() -> &'static str {
static CELL: GenericTypePathCell = GenericTypePathCell::new();
CELL.get_or_insert::<Self, _>(|| format!("[{t}; {N}]", t = T::short_type_path()))
}
}
impl<T: Reflect + MaybeTyped + TypePath + GetTypeRegistration, const N: usize> GetTypeRegistration
for [T; N]
{
fn get_type_registration() -> TypeRegistration {
TypeRegistration::of::<[T; N]>()
}
fn register_type_dependencies(registry: &mut TypeRegistry) {
registry.register::<T>();
}
}
#[cfg(feature = "functions")]
crate::func::macros::impl_function_traits!([T; N]; <T: Reflect + MaybeTyped + TypePath + GetTypeRegistration> [const N: usize]);
impl<T: TypePath> TypePath for [T]
where
[T]: ToOwned,
{
fn type_path() -> &'static str {
static CELL: GenericTypePathCell = GenericTypePathCell::new();
CELL.get_or_insert::<Self, _>(|| format!("[{}]", <T>::type_path()))
}
fn short_type_path() -> &'static str {
static CELL: GenericTypePathCell = GenericTypePathCell::new();
CELL.get_or_insert::<Self, _>(|| format!("[{}]", <T>::short_type_path()))
}
}
impl<T: TypePath + ?Sized> TypePath for &'static T {
fn type_path() -> &'static str {
static CELL: GenericTypePathCell = GenericTypePathCell::new();
CELL.get_or_insert::<Self, _>(|| format!("&{}", T::type_path()))
}
fn short_type_path() -> &'static str {
static CELL: GenericTypePathCell = GenericTypePathCell::new();
CELL.get_or_insert::<Self, _>(|| format!("&{}", T::short_type_path()))
}
}
impl<T: TypePath + ?Sized> TypePath for &'static mut T {
fn type_path() -> &'static str {
static CELL: GenericTypePathCell = GenericTypePathCell::new();
CELL.get_or_insert::<Self, _>(|| format!("&mut {}", T::type_path()))
}
fn short_type_path() -> &'static str {
static CELL: GenericTypePathCell = GenericTypePathCell::new();
CELL.get_or_insert::<Self, _>(|| format!("&mut {}", T::short_type_path()))
}
}
#[cfg(test)]
mod tests {
use bevy_reflect::{FromReflect, PartialReflect};
use core::f32::consts::{PI, TAU};
#[test]
fn should_partial_eq_char() {
let a: &dyn PartialReflect = &'x';
let b: &dyn PartialReflect = &'x';
let c: &dyn PartialReflect = &'o';
assert!(a.reflect_partial_eq(b).unwrap_or_default());
assert!(!a.reflect_partial_eq(c).unwrap_or_default());
}
#[test]
fn should_partial_eq_i32() {
let a: &dyn PartialReflect = &123_i32;
let b: &dyn PartialReflect = &123_i32;
let c: &dyn PartialReflect = &321_i32;
assert!(a.reflect_partial_eq(b).unwrap_or_default());
assert!(!a.reflect_partial_eq(c).unwrap_or_default());
}
#[test]
fn should_partial_eq_f32() {
let a: &dyn PartialReflect = &PI;
let b: &dyn PartialReflect = &PI;
let c: &dyn PartialReflect = &TAU;
assert!(a.reflect_partial_eq(b).unwrap_or_default());
assert!(!a.reflect_partial_eq(c).unwrap_or_default());
}
#[test]
fn static_str_should_from_reflect() {
let expected = "Hello, World!";
let output = <&'static str as FromReflect>::from_reflect(&expected).unwrap();
assert_eq!(expected, output);
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/impls/core/result.rs | crates/bevy_reflect/src/impls/core/result.rs | #![expect(
unused_qualifications,
reason = "the macro uses `MyEnum::Variant` which is generally unnecessary for `Result`"
)]
use bevy_reflect_derive::impl_reflect;
impl_reflect! {
#[type_path = "core::result"]
enum Result<T, E> {
Ok(T),
Err(E),
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/impls/core/num.rs | crates/bevy_reflect/src/impls/core/num.rs | use crate::type_registry::{ReflectDeserialize, ReflectSerialize};
use bevy_reflect_derive::impl_reflect_opaque;
impl_reflect_opaque!(::core::num::NonZeroI128(
Clone,
Debug,
Hash,
PartialEq,
Serialize,
Deserialize
));
impl_reflect_opaque!(::core::num::NonZeroU128(
Clone,
Debug,
Hash,
PartialEq,
Serialize,
Deserialize
));
impl_reflect_opaque!(::core::num::NonZeroIsize(
Clone,
Debug,
Hash,
PartialEq,
Serialize,
Deserialize
));
impl_reflect_opaque!(::core::num::NonZeroUsize(
Clone,
Debug,
Hash,
PartialEq,
Serialize,
Deserialize
));
impl_reflect_opaque!(::core::num::NonZeroI64(
Clone,
Debug,
Hash,
PartialEq,
Serialize,
Deserialize
));
impl_reflect_opaque!(::core::num::NonZeroU64(
Clone,
Debug,
Hash,
PartialEq,
Serialize,
Deserialize
));
impl_reflect_opaque!(::core::num::NonZeroU32(
Clone,
Debug,
Hash,
PartialEq,
Serialize,
Deserialize
));
impl_reflect_opaque!(::core::num::NonZeroI32(
Clone,
Debug,
Hash,
PartialEq,
Serialize,
Deserialize
));
impl_reflect_opaque!(::core::num::NonZeroI16(
Clone,
Debug,
Hash,
PartialEq,
Serialize,
Deserialize
));
impl_reflect_opaque!(::core::num::NonZeroU16(
Clone,
Debug,
Hash,
PartialEq,
Serialize,
Deserialize
));
impl_reflect_opaque!(::core::num::NonZeroU8(
Clone,
Debug,
Hash,
PartialEq,
Serialize,
Deserialize
));
impl_reflect_opaque!(::core::num::NonZeroI8(
Clone,
Debug,
Hash,
PartialEq,
Serialize,
Deserialize
));
impl_reflect_opaque!(::core::num::Wrapping<T: Clone + Send + Sync>(Clone));
impl_reflect_opaque!(::core::num::Saturating<T: Clone + Send + Sync>(Clone));
#[cfg(test)]
mod tests {
use bevy_reflect::{FromReflect, PartialReflect};
#[test]
fn nonzero_usize_impl_reflect_from_reflect() {
let a: &dyn PartialReflect = &core::num::NonZero::<usize>::new(42).unwrap();
let b: &dyn PartialReflect = &core::num::NonZero::<usize>::new(42).unwrap();
assert!(a.reflect_partial_eq(b).unwrap_or_default());
let forty_two: core::num::NonZero<usize> = FromReflect::from_reflect(a).unwrap();
assert_eq!(forty_two, core::num::NonZero::<usize>::new(42).unwrap());
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/impls/core/any.rs | crates/bevy_reflect/src/impls/core/any.rs | use bevy_reflect_derive::impl_reflect_opaque;
impl_reflect_opaque!(::core::any::TypeId(Clone, Debug, Hash, PartialEq,));
#[cfg(test)]
mod tests {
use bevy_reflect::FromReflect;
#[test]
fn type_id_should_from_reflect() {
let type_id = core::any::TypeId::of::<usize>();
let output = <core::any::TypeId as FromReflect>::from_reflect(&type_id).unwrap();
assert_eq!(type_id, output);
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/impls/core/option.rs | crates/bevy_reflect/src/impls/core/option.rs | #![expect(
unused_qualifications,
reason = "the macro uses `MyEnum::Variant` which is generally unnecessary for `Option`"
)]
use bevy_reflect_derive::impl_reflect;
impl_reflect! {
#[type_path = "core::option"]
enum Option<T> {
None,
Some(T),
}
}
#[cfg(test)]
mod tests {
use crate::{Enum, FromReflect, PartialReflect, TypeInfo, Typed, VariantInfo, VariantType};
use bevy_reflect_derive::Reflect;
use static_assertions::assert_impl_all;
#[test]
fn should_partial_eq_option() {
let a: &dyn PartialReflect = &Some(123);
let b: &dyn PartialReflect = &Some(123);
assert_eq!(Some(true), a.reflect_partial_eq(b));
}
#[test]
fn option_should_impl_enum() {
assert_impl_all!(Option<()>: Enum);
let mut value = Some(123usize);
assert!(value
.reflect_partial_eq(&Some(123usize))
.unwrap_or_default());
assert!(!value
.reflect_partial_eq(&Some(321usize))
.unwrap_or_default());
assert_eq!("Some", value.variant_name());
assert_eq!("core::option::Option<usize>::Some", value.variant_path());
if value.is_variant(VariantType::Tuple) {
if let Some(field) = value
.field_at_mut(0)
.and_then(|field| field.try_downcast_mut::<usize>())
{
*field = 321;
}
} else {
panic!("expected `VariantType::Tuple`");
}
assert_eq!(Some(321), value);
}
#[test]
fn option_should_from_reflect() {
#[derive(Reflect, PartialEq, Debug)]
struct Foo(usize);
let expected = Some(Foo(123));
let output = <Option<Foo> as FromReflect>::from_reflect(&expected).unwrap();
assert_eq!(expected, output);
}
#[test]
fn option_should_apply() {
#[derive(Reflect, PartialEq, Debug)]
struct Foo(usize);
// === None on None === //
let patch = None::<Foo>;
let mut value = None::<Foo>;
PartialReflect::apply(&mut value, &patch);
assert_eq!(patch, value, "None apply onto None");
// === Some on None === //
let patch = Some(Foo(123));
let mut value = None::<Foo>;
PartialReflect::apply(&mut value, &patch);
assert_eq!(patch, value, "Some apply onto None");
// === None on Some === //
let patch = None::<Foo>;
let mut value = Some(Foo(321));
PartialReflect::apply(&mut value, &patch);
assert_eq!(patch, value, "None apply onto Some");
// === Some on Some === //
let patch = Some(Foo(123));
let mut value = Some(Foo(321));
PartialReflect::apply(&mut value, &patch);
assert_eq!(patch, value, "Some apply onto Some");
}
#[test]
fn option_should_impl_typed() {
assert_impl_all!(Option<()>: Typed);
type MyOption = Option<i32>;
let info = MyOption::type_info();
if let TypeInfo::Enum(info) = info {
assert_eq!(
"None",
info.variant_at(0).unwrap().name(),
"Expected `None` to be variant at index `0`"
);
assert_eq!(
"Some",
info.variant_at(1).unwrap().name(),
"Expected `Some` to be variant at index `1`"
);
assert_eq!("Some", info.variant("Some").unwrap().name());
if let VariantInfo::Tuple(variant) = info.variant("Some").unwrap() {
assert!(
variant.field_at(0).unwrap().is::<i32>(),
"Expected `Some` variant to contain `i32`"
);
assert!(
variant.field_at(1).is_none(),
"Expected `Some` variant to only contain 1 field"
);
} else {
panic!("Expected `VariantInfo::Tuple`");
}
} else {
panic!("Expected `TypeInfo::Enum`");
}
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/impls/core/mod.rs | crates/bevy_reflect/src/impls/core/mod.rs | mod any;
mod hash;
mod net;
mod num;
mod ops;
mod option;
mod panic;
mod primitives;
mod result;
mod sync;
mod time;
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/impls/core/hash.rs | crates/bevy_reflect/src/impls/core/hash.rs | use bevy_reflect_derive::impl_type_path;
impl_type_path!(::core::hash::BuildHasherDefault<H>);
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/impls/core/ops.rs | crates/bevy_reflect/src/impls/core/ops.rs | use bevy_reflect_derive::impl_reflect_opaque;
impl_reflect_opaque!(::core::ops::Range<T: Clone + Send + Sync>(Clone));
impl_reflect_opaque!(::core::ops::RangeInclusive<T: Clone + Send + Sync>(Clone));
impl_reflect_opaque!(::core::ops::RangeFrom<T: Clone + Send + Sync>(Clone));
impl_reflect_opaque!(::core::ops::RangeTo<T: Clone + Send + Sync>(Clone));
impl_reflect_opaque!(::core::ops::RangeToInclusive<T: Clone + Send + Sync>(Clone));
impl_reflect_opaque!(::core::ops::RangeFull(Clone));
impl_reflect_opaque!(::core::ops::Bound<T: Clone + Send + Sync>(Clone));
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/impls/core/net.rs | crates/bevy_reflect/src/impls/core/net.rs | use crate::type_registry::{ReflectDeserialize, ReflectSerialize};
use bevy_reflect_derive::impl_reflect_opaque;
impl_reflect_opaque!(::core::net::SocketAddr(
Clone,
Debug,
Hash,
PartialEq,
Serialize,
Deserialize
));
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/serde/type_data.rs | crates/bevy_reflect/src/serde/type_data.rs | use crate::Reflect;
use alloc::boxed::Box;
use bevy_platform::collections::{hash_map::Iter, HashMap};
/// Contains data relevant to the automatic reflect powered (de)serialization of a type.
#[derive(Debug, Clone)]
pub struct SerializationData {
skipped_fields: HashMap<usize, SkippedField>,
}
impl SerializationData {
/// Creates a new `SerializationData` instance with the given skipped fields.
///
/// # Arguments
///
/// * `skipped_iter`: The iterator of field indices to be skipped during (de)serialization.
/// Indices are assigned only to reflected fields.
/// Ignored fields (i.e. those marked `#[reflect(ignore)]`) are implicitly skipped
/// and do not need to be included in this iterator.
pub fn new<I: Iterator<Item = (usize, SkippedField)>>(skipped_iter: I) -> Self {
Self {
skipped_fields: skipped_iter.collect(),
}
}
/// Returns true if the given index corresponds to a field meant to be skipped during (de)serialization.
///
/// # Example
///
/// ```
/// # use core::any::TypeId;
/// # use bevy_reflect::{Reflect, Struct, TypeRegistry, serde::SerializationData};
/// #[derive(Reflect)]
/// struct MyStruct {
/// serialize_me: i32,
/// #[reflect(skip_serializing)]
/// skip_me: i32
/// }
///
/// let mut registry = TypeRegistry::new();
/// registry.register::<MyStruct>();
///
/// let my_struct = MyStruct {
/// serialize_me: 123,
/// skip_me: 321,
/// };
///
/// let serialization_data = registry.get_type_data::<SerializationData>(TypeId::of::<MyStruct>()).unwrap();
///
/// for (idx, field) in my_struct.iter_fields().enumerate(){
/// if serialization_data.is_field_skipped(idx) {
/// // Skipped!
/// assert_eq!(1, idx);
/// } else {
/// // Not Skipped!
/// assert_eq!(0, idx);
/// }
/// }
/// ```
pub fn is_field_skipped(&self, index: usize) -> bool {
self.skipped_fields.contains_key(&index)
}
/// Generates a default instance of the skipped field at the given index.
///
/// Returns `None` if the field is not skipped.
///
/// # Example
///
/// ```
/// # use core::any::TypeId;
/// # use bevy_reflect::{Reflect, Struct, TypeRegistry, serde::SerializationData};
/// #[derive(Reflect)]
/// struct MyStruct {
/// serialize_me: i32,
/// #[reflect(skip_serializing)]
/// #[reflect(default = "skip_me_default")]
/// skip_me: i32
/// }
///
/// fn skip_me_default() -> i32 {
/// 789
/// }
///
/// let mut registry = TypeRegistry::new();
/// registry.register::<MyStruct>();
///
/// let serialization_data = registry.get_type_data::<SerializationData>(TypeId::of::<MyStruct>()).unwrap();
/// assert_eq!(789, serialization_data.generate_default(1).unwrap().take::<i32>().unwrap());
/// ```
pub fn generate_default(&self, index: usize) -> Option<Box<dyn Reflect>> {
self.skipped_fields
.get(&index)
.map(SkippedField::generate_default)
}
/// Returns the number of skipped fields.
pub fn len(&self) -> usize {
self.skipped_fields.len()
}
/// Returns true if there are no skipped fields.
pub fn is_empty(&self) -> bool {
self.skipped_fields.is_empty()
}
/// Returns an iterator over the skipped fields.
///
/// Each item in the iterator is a tuple containing:
/// 1. The reflected index of the field
/// 2. The (de)serialization metadata of the field
pub fn iter_skipped(&self) -> Iter<'_, usize, SkippedField> {
self.skipped_fields.iter()
}
}
/// Data needed for (de)serialization of a skipped field.
#[derive(Debug, Clone)]
pub struct SkippedField {
default_fn: fn() -> Box<dyn Reflect>,
}
impl SkippedField {
/// Create a new `SkippedField`.
///
/// # Arguments
///
/// * `default_fn`: A function pointer used to generate a default instance of the field.
pub fn new(default_fn: fn() -> Box<dyn Reflect>) -> Self {
Self { default_fn }
}
/// Generates a default instance of the field.
pub fn generate_default(&self) -> Box<dyn Reflect> {
(self.default_fn)()
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/serde/mod.rs | crates/bevy_reflect/src/serde/mod.rs | //! Serde integration for reflected types.
mod de;
mod ser;
mod type_data;
pub use de::*;
pub use ser::*;
pub use type_data::*;
#[cfg(test)]
mod tests {
use super::*;
use crate::{
type_registry::TypeRegistry, DynamicStruct, DynamicTupleStruct, FromReflect,
PartialReflect, Reflect, Struct,
};
use serde::de::DeserializeSeed;
#[test]
fn test_serialization_struct() {
#[derive(Debug, Reflect, PartialEq)]
#[reflect(PartialEq)]
struct TestStruct {
a: i32,
#[reflect(ignore)]
b: i32,
#[reflect(skip_serializing)]
c: i32,
#[reflect(skip_serializing)]
#[reflect(default = "custom_default")]
d: i32,
e: i32,
}
fn custom_default() -> i32 {
-1
}
let mut registry = TypeRegistry::default();
registry.register::<TestStruct>();
let test_struct = TestStruct {
a: 3,
b: 4,
c: 5,
d: 6,
e: 7,
};
let serializer = ReflectSerializer::new(&test_struct, ®istry);
let serialized =
ron::ser::to_string_pretty(&serializer, ron::ser::PrettyConfig::default()).unwrap();
let mut deserializer = ron::de::Deserializer::from_str(&serialized).unwrap();
let reflect_deserializer = ReflectDeserializer::new(®istry);
let deserialized = reflect_deserializer.deserialize(&mut deserializer).unwrap();
let mut expected = DynamicStruct::default();
expected.insert("a", 3);
// Ignored: expected.insert("b", 0);
expected.insert("c", 0);
expected.insert("d", -1);
expected.insert("e", 7);
assert!(
expected
.reflect_partial_eq(deserialized.as_partial_reflect())
.unwrap(),
"Deserialization failed: expected {expected:?} found {deserialized:?}"
);
let expected = TestStruct {
a: 3,
b: 0,
c: 0,
d: -1,
e: 7,
};
let received =
<TestStruct as FromReflect>::from_reflect(deserialized.as_partial_reflect()).unwrap();
assert_eq!(
expected, received,
"FromReflect failed: expected {expected:?} found {received:?}"
);
}
#[test]
fn test_serialization_tuple_struct() {
#[derive(Debug, Reflect, PartialEq)]
#[reflect(PartialEq)]
struct TestStruct(
i32,
#[reflect(ignore)] i32,
#[reflect(skip_serializing)] i32,
#[reflect(skip_serializing)]
#[reflect(default = "custom_default")]
i32,
i32,
);
fn custom_default() -> i32 {
-1
}
let mut registry = TypeRegistry::default();
registry.register::<TestStruct>();
let test_struct = TestStruct(3, 4, 5, 6, 7);
let serializer = ReflectSerializer::new(&test_struct, ®istry);
let serialized =
ron::ser::to_string_pretty(&serializer, ron::ser::PrettyConfig::default()).unwrap();
let mut deserializer = ron::de::Deserializer::from_str(&serialized).unwrap();
let reflect_deserializer = ReflectDeserializer::new(®istry);
let deserialized = reflect_deserializer.deserialize(&mut deserializer).unwrap();
let mut expected = DynamicTupleStruct::default();
expected.insert(3);
// Ignored: expected.insert(0);
expected.insert(0);
expected.insert(-1);
expected.insert(7);
assert!(
expected
.reflect_partial_eq(deserialized.as_partial_reflect())
.unwrap(),
"Deserialization failed: expected {expected:?} found {deserialized:?}"
);
let expected = TestStruct(3, 0, 0, -1, 7);
let received =
<TestStruct as FromReflect>::from_reflect(deserialized.as_partial_reflect()).unwrap();
assert_eq!(
expected, received,
"FromReflect failed: expected {expected:?} found {received:?}"
);
}
#[test]
#[should_panic(
expected = "cannot serialize dynamic value without represented type: `bevy_reflect::DynamicStruct`"
)]
fn should_not_serialize_unproxied_dynamic() {
let registry = TypeRegistry::default();
let mut value = DynamicStruct::default();
value.insert("foo", 123_u32);
let serializer = ReflectSerializer::new(&value, ®istry);
ron::ser::to_string(&serializer).unwrap();
}
#[test]
fn should_roundtrip_proxied_dynamic() {
#[derive(Reflect)]
struct TestStruct {
a: i32,
b: i32,
}
let mut registry = TypeRegistry::default();
registry.register::<TestStruct>();
let value: DynamicStruct = TestStruct { a: 123, b: 456 }.to_dynamic_struct();
let serializer = ReflectSerializer::new(&value, ®istry);
let expected = r#"{"bevy_reflect::serde::tests::TestStruct":(a:123,b:456)}"#;
let result = ron::ser::to_string(&serializer).unwrap();
assert_eq!(expected, result);
let mut deserializer = ron::de::Deserializer::from_str(&result).unwrap();
let reflect_deserializer = ReflectDeserializer::new(®istry);
let expected = value.to_dynamic();
let result = reflect_deserializer.deserialize(&mut deserializer).unwrap();
assert!(expected
.reflect_partial_eq(result.as_partial_reflect())
.unwrap());
}
mod type_data {
use super::*;
use crate::from_reflect::FromReflect;
use crate::serde::{DeserializeWithRegistry, ReflectDeserializeWithRegistry};
use crate::serde::{ReflectSerializeWithRegistry, SerializeWithRegistry};
use crate::{ReflectFromReflect, TypePath};
use alloc::{format, string::String, vec, vec::Vec};
use bevy_platform::sync::Arc;
use bevy_reflect_derive::reflect_trait;
use core::any::TypeId;
use core::fmt::{Debug, Formatter};
use serde::de::{SeqAccess, Visitor};
use serde::ser::SerializeSeq;
use serde::{Deserializer, Serialize, Serializer};
#[reflect_trait]
trait Enemy: Reflect + Debug {
#[expect(dead_code, reason = "this method is purely for testing purposes")]
fn hp(&self) -> u8;
}
// This is needed to support Arc<dyn Enemy>
impl TypePath for dyn Enemy {
fn type_path() -> &'static str {
"dyn bevy_reflect::serde::tests::type_data::Enemy"
}
fn short_type_path() -> &'static str {
"dyn Enemy"
}
}
#[derive(Reflect, Debug)]
#[reflect(Enemy)]
struct Skeleton(u8);
impl Enemy for Skeleton {
fn hp(&self) -> u8 {
self.0
}
}
#[derive(Reflect, Debug)]
#[reflect(Enemy)]
struct Zombie {
health: u8,
walk_speed: f32,
}
impl Enemy for Zombie {
fn hp(&self) -> u8 {
self.health
}
}
#[derive(Reflect, Debug)]
struct Level {
name: String,
enemies: EnemyList,
}
#[derive(Reflect, Debug)]
#[reflect(SerializeWithRegistry, DeserializeWithRegistry)]
// Note that we have to use `Arc` instead of `Box` here due to the
// former being the only one between the two to implement `Reflect`.
struct EnemyList(Vec<Arc<dyn Enemy>>);
impl SerializeWithRegistry for EnemyList {
fn serialize<S>(
&self,
serializer: S,
registry: &TypeRegistry,
) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut state = serializer.serialize_seq(Some(self.0.len()))?;
for enemy in &self.0 {
state.serialize_element(&ReflectSerializer::new(
(**enemy).as_partial_reflect(),
registry,
))?;
}
state.end()
}
}
impl<'de> DeserializeWithRegistry<'de> for EnemyList {
fn deserialize<D>(deserializer: D, registry: &TypeRegistry) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
struct EnemyListVisitor<'a> {
registry: &'a TypeRegistry,
}
impl<'a, 'de> Visitor<'de> for EnemyListVisitor<'a> {
type Value = Vec<Arc<dyn Enemy>>;
fn expecting(&self, formatter: &mut Formatter) -> core::fmt::Result {
write!(formatter, "a list of enemies")
}
fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
where
A: SeqAccess<'de>,
{
let mut enemies = Vec::new();
while let Some(enemy) =
seq.next_element_seed(ReflectDeserializer::new(self.registry))?
{
let registration = self
.registry
.get_with_type_path(
enemy.get_represented_type_info().unwrap().type_path(),
)
.unwrap();
// 1. Convert any possible dynamic values to concrete ones
let enemy = registration
.data::<ReflectFromReflect>()
.unwrap()
.from_reflect(&*enemy)
.unwrap();
// 2. Convert the concrete value to a boxed trait object
let enemy = registration
.data::<ReflectEnemy>()
.unwrap()
.get_boxed(enemy)
.unwrap();
enemies.push(enemy.into());
}
Ok(enemies)
}
}
deserializer
.deserialize_seq(EnemyListVisitor { registry })
.map(EnemyList)
}
}
fn create_registry() -> TypeRegistry {
let mut registry = TypeRegistry::default();
registry.register::<Level>();
registry.register::<EnemyList>();
registry.register::<Skeleton>();
registry.register::<Zombie>();
registry
}
fn create_arc_dyn_enemy<T: Enemy>(enemy: T) -> Arc<dyn Enemy> {
let arc = Arc::new(enemy);
#[cfg(not(target_has_atomic = "ptr"))]
#[expect(
unsafe_code,
reason = "unsized coercion is an unstable feature for non-std types"
)]
// SAFETY:
// - Coercion from `T` to `dyn Enemy` is valid as `T: Enemy + 'static`
// - `Arc::from_raw` receives a valid pointer from a previous call to `Arc::into_raw`
let arc = unsafe { Arc::from_raw(Arc::into_raw(arc) as *const dyn Enemy) };
arc
}
#[test]
fn should_serialize_with_serialize_with_registry() {
let registry = create_registry();
let level = Level {
name: String::from("Level 1"),
enemies: EnemyList(vec![
create_arc_dyn_enemy(Skeleton(10)),
create_arc_dyn_enemy(Zombie {
health: 20,
walk_speed: 0.5,
}),
]),
};
let serializer = ReflectSerializer::new(&level, ®istry);
let serialized = ron::ser::to_string(&serializer).unwrap();
let expected = r#"{"bevy_reflect::serde::tests::type_data::Level":(name:"Level 1",enemies:[{"bevy_reflect::serde::tests::type_data::Skeleton":(10)},{"bevy_reflect::serde::tests::type_data::Zombie":(health:20,walk_speed:0.5)}])}"#;
assert_eq!(expected, serialized);
}
#[test]
fn should_deserialize_with_deserialize_with_registry() {
let registry = create_registry();
let input = r#"{"bevy_reflect::serde::tests::type_data::Level":(name:"Level 1",enemies:[{"bevy_reflect::serde::tests::type_data::Skeleton":(10)},{"bevy_reflect::serde::tests::type_data::Zombie":(health:20,walk_speed:0.5)}])}"#;
let mut deserializer = ron::de::Deserializer::from_str(input).unwrap();
let reflect_deserializer = ReflectDeserializer::new(®istry);
let value = reflect_deserializer.deserialize(&mut deserializer).unwrap();
let output = Level::from_reflect(&*value).unwrap();
let expected = Level {
name: String::from("Level 1"),
enemies: EnemyList(vec![
create_arc_dyn_enemy(Skeleton(10)),
create_arc_dyn_enemy(Zombie {
health: 20,
walk_speed: 0.5,
}),
]),
};
// Poor man's comparison since we can't derive PartialEq for Arc<dyn Enemy>
assert_eq!(format!("{expected:?}"), format!("{output:?}",));
let unexpected = Level {
name: String::from("Level 1"),
enemies: EnemyList(vec![
create_arc_dyn_enemy(Skeleton(20)),
create_arc_dyn_enemy(Zombie {
health: 20,
walk_speed: 5.0,
}),
]),
};
// Poor man's comparison since we can't derive PartialEq for Arc<dyn Enemy>
assert_ne!(format!("{unexpected:?}"), format!("{output:?}"));
}
#[test]
fn should_serialize_single_tuple_struct_as_newtype() {
#[derive(Reflect, Serialize, PartialEq, Debug)]
struct TupleStruct(u32);
#[derive(Reflect, Serialize, PartialEq, Debug)]
struct TupleStructWithSkip(
u32,
#[reflect(skip_serializing)]
#[serde(skip)]
u32,
);
#[derive(Reflect, Serialize, PartialEq, Debug)]
enum Enum {
TupleStruct(usize),
NestedTupleStruct(TupleStruct),
NestedTupleStructWithSkip(TupleStructWithSkip),
}
let mut registry = TypeRegistry::default();
registry.register::<TupleStruct>();
registry.register::<TupleStructWithSkip>();
registry.register::<Enum>();
let tuple_struct = TupleStruct(1);
let tuple_struct_with_skip = TupleStructWithSkip(2, 3);
let tuple_struct_enum = Enum::TupleStruct(4);
let nested_tuple_struct = Enum::NestedTupleStruct(TupleStruct(5));
let nested_tuple_struct_with_skip =
Enum::NestedTupleStructWithSkip(TupleStructWithSkip(6, 7));
fn assert_serialize<T: Reflect + FromReflect + Serialize + PartialEq + Debug>(
value: &T,
registry: &TypeRegistry,
) {
let serializer = TypedReflectSerializer::new(value, registry);
let reflect_serialize = serde_json::to_string(&serializer).unwrap();
let serde_serialize = serde_json::to_string(value).unwrap();
assert_eq!(reflect_serialize, serde_serialize);
let registration = registry.get(TypeId::of::<T>()).unwrap();
let reflect_deserializer = TypedReflectDeserializer::new(registration, registry);
let mut deserializer = serde_json::Deserializer::from_str(&serde_serialize);
let reflect_value = reflect_deserializer.deserialize(&mut deserializer).unwrap();
let _ = T::from_reflect(&*reflect_value).unwrap();
}
assert_serialize(&tuple_struct, ®istry);
assert_serialize(&tuple_struct_with_skip, ®istry);
assert_serialize(&tuple_struct_enum, ®istry);
assert_serialize(&nested_tuple_struct, ®istry);
assert_serialize(&nested_tuple_struct_with_skip, ®istry);
}
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/serde/de/tuple_utils.rs | crates/bevy_reflect/src/serde/de/tuple_utils.rs | use crate::{
serde::{
de::{error_utils::make_custom_error, registration_utils::try_get_registration},
SerializationData, TypedReflectDeserializer,
},
DynamicTuple, TupleInfo, TupleStructInfo, TupleVariantInfo, TypeRegistration, TypeRegistry,
UnnamedField,
};
use alloc::string::ToString;
use serde::de::{Error, SeqAccess};
use super::ReflectDeserializerProcessor;
pub(super) trait TupleLikeInfo {
fn field_at<E: Error>(&self, index: usize) -> Result<&UnnamedField, E>;
fn field_len(&self) -> usize;
}
impl TupleLikeInfo for TupleInfo {
fn field_len(&self) -> usize {
Self::field_len(self)
}
fn field_at<E: Error>(&self, index: usize) -> Result<&UnnamedField, E> {
Self::field_at(self, index).ok_or_else(|| {
make_custom_error(format_args!(
"no field at index `{}` on tuple `{}`",
index,
self.type_path(),
))
})
}
}
impl TupleLikeInfo for TupleStructInfo {
fn field_len(&self) -> usize {
Self::field_len(self)
}
fn field_at<E: Error>(&self, index: usize) -> Result<&UnnamedField, E> {
Self::field_at(self, index).ok_or_else(|| {
make_custom_error(format_args!(
"no field at index `{}` on tuple struct `{}`",
index,
self.type_path(),
))
})
}
}
impl TupleLikeInfo for TupleVariantInfo {
fn field_len(&self) -> usize {
Self::field_len(self)
}
fn field_at<E: Error>(&self, index: usize) -> Result<&UnnamedField, E> {
Self::field_at(self, index).ok_or_else(|| {
make_custom_error(format_args!(
"no field at index `{}` on tuple variant `{}`",
index,
self.name(),
))
})
}
}
/// Deserializes a [tuple-like] type from a sequence of elements, returning a [`DynamicTuple`].
///
/// [tuple-like]: TupleLikeInfo
pub(super) fn visit_tuple<'de, T, V, P>(
seq: &mut V,
info: &T,
registration: &TypeRegistration,
registry: &TypeRegistry,
mut processor: Option<&mut P>,
) -> Result<DynamicTuple, V::Error>
where
T: TupleLikeInfo,
V: SeqAccess<'de>,
P: ReflectDeserializerProcessor,
{
let mut tuple = DynamicTuple::default();
let len = info.field_len();
if len == 0 {
// Handle empty tuple/tuple struct
return Ok(tuple);
}
let serialization_data = registration.data::<SerializationData>();
for index in 0..len {
if let Some(value) = serialization_data.and_then(|data| data.generate_default(index)) {
tuple.insert_boxed(value.into_partial_reflect());
continue;
}
let value = seq
.next_element_seed(TypedReflectDeserializer::new_internal(
try_get_registration(*info.field_at(index)?.ty(), registry)?,
registry,
processor.as_deref_mut(),
))?
.ok_or_else(|| Error::invalid_length(index, &len.to_string().as_str()))?;
tuple.insert_boxed(value);
}
Ok(tuple)
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/serde/de/arrays.rs | crates/bevy_reflect/src/serde/de/arrays.rs | use crate::{
serde::{de::registration_utils::try_get_registration, TypedReflectDeserializer},
ArrayInfo, DynamicArray, TypeRegistry,
};
use alloc::{string::ToString, vec::Vec};
use core::{fmt, fmt::Formatter};
use serde::de::{Error, SeqAccess, Visitor};
use super::ReflectDeserializerProcessor;
/// A [`Visitor`] for deserializing [`Array`] values.
///
/// [`Array`]: crate::Array
pub(super) struct ArrayVisitor<'a, P> {
pub array_info: &'static ArrayInfo,
pub registry: &'a TypeRegistry,
pub processor: Option<&'a mut P>,
}
impl<'de, P: ReflectDeserializerProcessor> Visitor<'de> for ArrayVisitor<'_, P> {
type Value = DynamicArray;
fn expecting(&self, formatter: &mut Formatter) -> fmt::Result {
formatter.write_str("reflected array value")
}
fn visit_seq<V>(mut self, mut seq: V) -> Result<Self::Value, V::Error>
where
V: SeqAccess<'de>,
{
let mut vec = Vec::with_capacity(seq.size_hint().unwrap_or_default());
let registration = try_get_registration(self.array_info.item_ty(), self.registry)?;
while let Some(value) = seq.next_element_seed(TypedReflectDeserializer::new_internal(
registration,
self.registry,
self.processor.as_deref_mut(),
))? {
vec.push(value);
}
if vec.len() != self.array_info.capacity() {
return Err(Error::invalid_length(
vec.len(),
&self.array_info.capacity().to_string().as_str(),
));
}
Ok(DynamicArray::new(vec.into_boxed_slice()))
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/serde/de/registrations.rs | crates/bevy_reflect/src/serde/de/registrations.rs | use crate::{serde::de::error_utils::make_custom_error, TypeRegistration, TypeRegistry};
use core::{fmt, fmt::Formatter};
use serde::de::{DeserializeSeed, Error, Visitor};
/// A deserializer for type registrations.
///
/// This will return a [`&TypeRegistration`] corresponding to the given type.
/// This deserializer expects a string containing the _full_ [type path] of the
/// type to find the `TypeRegistration` of.
///
/// [`&TypeRegistration`]: TypeRegistration
/// [type path]: crate::TypePath::type_path
pub struct TypeRegistrationDeserializer<'a> {
registry: &'a TypeRegistry,
}
impl<'a> TypeRegistrationDeserializer<'a> {
/// Creates a new [`TypeRegistrationDeserializer`].
pub fn new(registry: &'a TypeRegistry) -> Self {
Self { registry }
}
}
impl<'a, 'de> DeserializeSeed<'de> for TypeRegistrationDeserializer<'a> {
type Value = &'a TypeRegistration;
fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
where
D: serde::Deserializer<'de>,
{
struct TypeRegistrationVisitor<'a>(&'a TypeRegistry);
impl<'de, 'a> Visitor<'de> for TypeRegistrationVisitor<'a> {
type Value = &'a TypeRegistration;
fn expecting(&self, formatter: &mut Formatter) -> fmt::Result {
formatter.write_str("string containing `type` entry for the reflected value")
}
fn visit_str<E>(self, type_path: &str) -> Result<Self::Value, E>
where
E: Error,
{
self.0.get_with_type_path(type_path).ok_or_else(|| {
make_custom_error(format_args!("no registration found for `{type_path}`"))
})
}
}
deserializer.deserialize_str(TypeRegistrationVisitor(self.registry))
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/serde/de/tuple_structs.rs | crates/bevy_reflect/src/serde/de/tuple_structs.rs | use crate::{
serde::{de::tuple_utils::visit_tuple, SerializationData},
DynamicTupleStruct, TupleStructInfo, TypeRegistration, TypeRegistry,
};
use core::{fmt, fmt::Formatter};
use serde::de::{DeserializeSeed, SeqAccess, Visitor};
use super::{registration_utils::try_get_registration, TypedReflectDeserializer};
use super::ReflectDeserializerProcessor;
/// A [`Visitor`] for deserializing [`TupleStruct`] values.
///
/// [`TupleStruct`]: crate::TupleStruct
pub(super) struct TupleStructVisitor<'a, P> {
pub tuple_struct_info: &'static TupleStructInfo,
pub registration: &'a TypeRegistration,
pub registry: &'a TypeRegistry,
pub processor: Option<&'a mut P>,
}
impl<'de, P: ReflectDeserializerProcessor> Visitor<'de> for TupleStructVisitor<'_, P> {
type Value = DynamicTupleStruct;
fn expecting(&self, formatter: &mut Formatter) -> fmt::Result {
formatter.write_str("reflected tuple struct value")
}
fn visit_seq<V>(self, mut seq: V) -> Result<Self::Value, V::Error>
where
V: SeqAccess<'de>,
{
visit_tuple(
&mut seq,
self.tuple_struct_info,
self.registration,
self.registry,
self.processor,
)
.map(DynamicTupleStruct::from)
}
fn visit_newtype_struct<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
where
D: serde::Deserializer<'de>,
{
let mut tuple = DynamicTupleStruct::default();
let serialization_data = self.registration.data::<SerializationData>();
if let Some(value) = serialization_data.and_then(|data| data.generate_default(0)) {
tuple.insert_boxed(value.into_partial_reflect());
return Ok(tuple);
}
let registration = try_get_registration(
*self
.tuple_struct_info
.field_at(0)
.ok_or(serde::de::Error::custom("Field at index 0 not found"))?
.ty(),
self.registry,
)?;
let reflect_deserializer =
TypedReflectDeserializer::new_internal(registration, self.registry, self.processor);
let value = reflect_deserializer.deserialize(deserializer)?;
tuple.insert_boxed(value.into_partial_reflect());
Ok(tuple)
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/serde/de/helpers.rs | crates/bevy_reflect/src/serde/de/helpers.rs | use alloc::{
string::{String, ToString},
vec::Vec,
};
use core::{
fmt,
fmt::{Debug, Display, Formatter},
};
use serde::{
de::{Error, Visitor},
Deserialize,
};
/// A debug struct used for error messages that displays a list of expected values.
///
/// # Example
///
/// ```ignore (Can't import private struct from doctest)
/// let expected = vec!["foo", "bar", "baz"];
/// assert_eq!("`foo`, `bar`, `baz`", format!("{}", ExpectedValues(expected)));
/// ```
pub(super) struct ExpectedValues<T: Display>(pub Vec<T>);
impl<T: Display> FromIterator<T> for ExpectedValues<T> {
fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
Self(iter.into_iter().collect())
}
}
impl<T: Display> Debug for ExpectedValues<T> {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
let len = self.0.len();
for (index, item) in self.0.iter().enumerate() {
write!(f, "`{item}`")?;
if index < len - 1 {
write!(f, ", ")?;
}
}
Ok(())
}
}
/// Represents a simple reflected identifier.
#[derive(Debug, Clone, Eq, PartialEq)]
pub(super) struct Ident(pub String);
impl<'de> Deserialize<'de> for Ident {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
struct IdentVisitor;
impl<'de> Visitor<'de> for IdentVisitor {
type Value = Ident;
fn expecting(&self, formatter: &mut Formatter) -> fmt::Result {
formatter.write_str("identifier")
}
fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
where
E: Error,
{
Ok(Ident(value.to_string()))
}
fn visit_string<E>(self, value: String) -> Result<Self::Value, E>
where
E: Error,
{
Ok(Ident(value))
}
}
deserializer.deserialize_identifier(IdentVisitor)
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/serde/de/lists.rs | crates/bevy_reflect/src/serde/de/lists.rs | use crate::{
serde::{de::registration_utils::try_get_registration, TypedReflectDeserializer},
DynamicList, ListInfo, TypeRegistry,
};
use core::{fmt, fmt::Formatter};
use serde::de::{SeqAccess, Visitor};
use super::ReflectDeserializerProcessor;
/// A [`Visitor`] for deserializing [`List`] values.
///
/// [`List`]: crate::List
pub(super) struct ListVisitor<'a, P> {
pub list_info: &'static ListInfo,
pub registry: &'a TypeRegistry,
pub processor: Option<&'a mut P>,
}
impl<'de, P: ReflectDeserializerProcessor> Visitor<'de> for ListVisitor<'_, P> {
type Value = DynamicList;
fn expecting(&self, formatter: &mut Formatter) -> fmt::Result {
formatter.write_str("reflected list value")
}
fn visit_seq<V>(mut self, mut seq: V) -> Result<Self::Value, V::Error>
where
V: SeqAccess<'de>,
{
let mut list = DynamicList::default();
let registration = try_get_registration(self.list_info.item_ty(), self.registry)?;
while let Some(value) = seq.next_element_seed(TypedReflectDeserializer::new_internal(
registration,
self.registry,
self.processor.as_deref_mut(),
))? {
list.push_box(value);
}
Ok(list)
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/serde/de/structs.rs | crates/bevy_reflect/src/serde/de/structs.rs | use crate::{
serde::de::struct_utils::{visit_struct, visit_struct_seq},
DynamicStruct, StructInfo, TypeRegistration, TypeRegistry,
};
use core::{fmt, fmt::Formatter};
use serde::de::{MapAccess, SeqAccess, Visitor};
use super::ReflectDeserializerProcessor;
/// A [`Visitor`] for deserializing [`Struct`] values.
///
/// [`Struct`]: crate::Struct
pub(super) struct StructVisitor<'a, P> {
pub struct_info: &'static StructInfo,
pub registration: &'a TypeRegistration,
pub registry: &'a TypeRegistry,
pub processor: Option<&'a mut P>,
}
impl<'de, P: ReflectDeserializerProcessor> Visitor<'de> for StructVisitor<'_, P> {
type Value = DynamicStruct;
fn expecting(&self, formatter: &mut Formatter) -> fmt::Result {
formatter.write_str("reflected struct value")
}
fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
where
A: SeqAccess<'de>,
{
visit_struct_seq(
&mut seq,
self.struct_info,
self.registration,
self.registry,
self.processor,
)
}
fn visit_map<V>(self, mut map: V) -> Result<Self::Value, V::Error>
where
V: MapAccess<'de>,
{
visit_struct(
&mut map,
self.struct_info,
self.registration,
self.registry,
self.processor,
)
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/serde/de/processor.rs | crates/bevy_reflect/src/serde/de/processor.rs | use crate::{PartialReflect, TypeRegistration, TypeRegistry};
use alloc::boxed::Box;
/// Allows overriding the default deserialization behavior of
/// [`ReflectDeserializer`] and [`TypedReflectDeserializer`] for specific
/// [`TypeRegistration`]s.
///
/// When deserializing a reflected value, you may want to override the default
/// behavior and use your own logic for deserialization. This logic may also
/// be context-dependent, and only apply for a single use of your
/// [`ReflectDeserializer`]. To achieve this, you can create a processor and
/// pass it in to your deserializer.
///
/// Whenever the deserializer attempts to deserialize a value, it will first
/// call [`try_deserialize`] on your processor, which may take ownership of the
/// deserializer and give back a [`Box<dyn PartialReflect>`], or return
/// ownership of the deserializer back, and continue with the default logic.
///
/// The serialization equivalent of this is [`ReflectSerializerProcessor`].
///
/// # Compared to [`DeserializeWithRegistry`]
///
/// [`DeserializeWithRegistry`] allows you to define how your type will be
/// deserialized by a [`TypedReflectDeserializer`], given the extra context of
/// the [`TypeRegistry`]. If your type can be deserialized entirely from that,
/// then you should prefer implementing that trait instead of using a processor.
///
/// However, you may need more context-dependent data which is only present in
/// the scope where you create the [`TypedReflectDeserializer`]. For example, in
/// an asset loader, the `&mut LoadContext` you get is only valid from within
/// the `load` function. This is where a processor is useful, as the processor
/// can capture local variables.
///
/// A [`ReflectDeserializerProcessor`] always takes priority over a
/// [`DeserializeWithRegistry`] implementation, so this is also useful for
/// overriding deserialization behavior if you need to do something custom.
///
/// # Examples
///
/// Deserializing a reflected value in an asset loader, and replacing asset
/// handles with a loaded equivalent:
///
/// ```
/// # use bevy_reflect::serde::{ReflectDeserializer, ReflectDeserializerProcessor};
/// # use bevy_reflect::{PartialReflect, Reflect, TypeData, TypeRegistration, TypeRegistry};
/// # use serde::de::{DeserializeSeed, Deserializer, Visitor};
/// # use std::marker::PhantomData;
/// #
/// # #[derive(Debug, Clone, Reflect)]
/// # struct LoadedUntypedAsset;
/// # #[derive(Debug, Clone, Reflect)]
/// # struct Handle<T: Reflect>(T);
/// # #[derive(Debug, Clone, Reflect)]
/// # struct Mesh;
/// #
/// # struct LoadContext;
/// # impl LoadContext {
/// # fn load(&mut self) -> &mut Self { unimplemented!() }
/// # fn with_asset_type_id(&mut self, (): ()) -> &mut Self { unimplemented!() }
/// # fn untyped(&mut self) -> &mut Self { unimplemented!() }
/// # fn load_asset(&mut self, (): ()) -> Handle<LoadedUntypedAsset> { unimplemented!() }
/// # }
/// #
/// # struct ReflectHandle;
/// # impl TypeData for ReflectHandle {
/// # fn clone_type_data(&self) -> Box<dyn TypeData> {
/// # unimplemented!()
/// # }
/// # }
/// # impl ReflectHandle {
/// # fn asset_type_id(&self) {
/// # unimplemented!()
/// # }
/// # }
/// #
/// # struct AssetPathVisitor;
/// # impl<'de> Visitor<'de> for AssetPathVisitor {
/// # type Value = ();
/// # fn expecting(&self, formatter: &mut core::fmt::Formatter) -> core::fmt::Result { unimplemented!() }
/// # }
/// # type AssetError = Box<dyn core::error::Error>;
/// #[derive(Debug, Clone, Reflect)]
/// struct MyAsset {
/// name: String,
/// mesh: Handle<Mesh>,
/// }
///
/// fn load(
/// asset_bytes: &[u8],
/// type_registry: &TypeRegistry,
/// load_context: &mut LoadContext,
/// ) -> Result<MyAsset, AssetError> {
/// struct HandleProcessor<'a> {
/// load_context: &'a mut LoadContext,
/// }
///
/// impl ReflectDeserializerProcessor for HandleProcessor<'_> {
/// fn try_deserialize<'de, D>(
/// &mut self,
/// registration: &TypeRegistration,
/// _registry: &TypeRegistry,
/// deserializer: D,
/// ) -> Result<Result<Box<dyn PartialReflect>, D>, D::Error>
/// where
/// D: Deserializer<'de>,
/// {
/// let Some(reflect_handle) = registration.data::<ReflectHandle>() else {
/// // we don't want to deserialize this - give the deserializer back
/// return Ok(Err(deserializer));
/// };
///
/// let asset_type_id = reflect_handle.asset_type_id();
/// let asset_path = deserializer.deserialize_str(AssetPathVisitor)?;
///
/// let handle: Handle<LoadedUntypedAsset> = self.load_context
/// .load()
/// .with_asset_type_id(asset_type_id)
/// .untyped()
/// .load_asset(asset_path);
/// # let _: Result<_, ()> = {
/// Ok(Box::new(handle))
/// # };
/// # unimplemented!()
/// }
/// }
///
/// let mut ron_deserializer = ron::Deserializer::from_bytes(asset_bytes)?;
/// let mut processor = HandleProcessor { load_context };
/// let reflect_deserializer =
/// ReflectDeserializer::with_processor(type_registry, &mut processor);
/// let asset = reflect_deserializer.deserialize(&mut ron_deserializer)?;
/// # unimplemented!()
/// }
/// ```
///
/// [`ReflectDeserializer`]: crate::serde::ReflectDeserializer
/// [`TypedReflectDeserializer`]: crate::serde::TypedReflectDeserializer
/// [`try_deserialize`]: Self::try_deserialize
/// [`DeserializeWithRegistry`]: crate::serde::DeserializeWithRegistry
/// [`ReflectSerializerProcessor`]: crate::serde::ReflectSerializerProcessor
pub trait ReflectDeserializerProcessor {
/// Attempts to deserialize the value which a [`TypedReflectDeserializer`]
/// is currently looking at, and knows the type of.
///
/// If you've read the `registration` and want to override the default
/// deserialization, return `Ok(Ok(value))` with the boxed reflected value
/// that you want to assign this value to. The type inside the box must
/// be the same one as the `registration` is for, otherwise future
/// reflection operations (such as using [`FromReflect`] to convert the
/// resulting [`Box<dyn PartialReflect>`] into a concrete type) will fail.
///
/// If you don't want to override the deserialization, return ownership of
/// the deserializer back via `Ok(Err(deserializer))`.
///
/// Note that, if you do want to return a value, you *must* read from the
/// deserializer passed to this function (you are free to ignore the result
/// though). Otherwise, the deserializer will be in an inconsistent state,
/// and future value parsing will fail.
///
/// # Examples
///
/// Correct way to return a constant value (not using any output from the
/// deserializer):
///
/// ```
/// # use bevy_reflect::{TypeRegistration, PartialReflect, TypeRegistry};
/// # use bevy_reflect::serde::ReflectDeserializerProcessor;
/// # use core::any::TypeId;
/// use serde::de::IgnoredAny;
///
/// struct ConstantI32Processor;
///
/// impl ReflectDeserializerProcessor for ConstantI32Processor {
/// fn try_deserialize<'de, D>(
/// &mut self,
/// registration: &TypeRegistration,
/// _registry: &TypeRegistry,
/// deserializer: D,
/// ) -> Result<Result<Box<dyn PartialReflect>, D>, D::Error>
/// where
/// D: serde::Deserializer<'de>
/// {
/// if registration.type_id() == TypeId::of::<i32>() {
/// _ = deserializer.deserialize_ignored_any(IgnoredAny);
/// Ok(Ok(Box::new(42_i32)))
/// } else {
/// Ok(Err(deserializer))
/// }
/// }
/// }
/// ```
///
/// [`TypedReflectDeserializer`]: crate::serde::TypedReflectDeserializer
/// [`FromReflect`]: crate::FromReflect
fn try_deserialize<'de, D>(
&mut self,
registration: &TypeRegistration,
registry: &TypeRegistry,
deserializer: D,
) -> Result<Result<Box<dyn PartialReflect>, D>, D::Error>
where
D: serde::Deserializer<'de>;
}
impl ReflectDeserializerProcessor for () {
fn try_deserialize<'de, D>(
&mut self,
_registration: &TypeRegistration,
_registry: &TypeRegistry,
deserializer: D,
) -> Result<Result<Box<dyn PartialReflect>, D>, D::Error>
where
D: serde::Deserializer<'de>,
{
Ok(Err(deserializer))
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/serde/de/enums.rs | crates/bevy_reflect/src/serde/de/enums.rs | use crate::{
serde::{
de::{
error_utils::make_custom_error,
helpers::ExpectedValues,
registration_utils::try_get_registration,
struct_utils::{visit_struct, visit_struct_seq},
tuple_utils::{visit_tuple, TupleLikeInfo},
},
TypedReflectDeserializer,
},
DynamicEnum, DynamicStruct, DynamicTuple, DynamicVariant, EnumInfo, StructVariantInfo,
TupleVariantInfo, TypeRegistration, TypeRegistry, VariantInfo,
};
use core::{fmt, fmt::Formatter};
use serde::de::{DeserializeSeed, EnumAccess, Error, MapAccess, SeqAccess, VariantAccess, Visitor};
use super::ReflectDeserializerProcessor;
/// A [`Visitor`] for deserializing [`Enum`] values.
///
/// [`Enum`]: crate::Enum
pub(super) struct EnumVisitor<'a, P> {
pub enum_info: &'static EnumInfo,
pub registration: &'a TypeRegistration,
pub registry: &'a TypeRegistry,
pub processor: Option<&'a mut P>,
}
impl<'de, P: ReflectDeserializerProcessor> Visitor<'de> for EnumVisitor<'_, P> {
type Value = DynamicEnum;
fn expecting(&self, formatter: &mut Formatter) -> fmt::Result {
formatter.write_str("reflected enum value")
}
fn visit_enum<A>(self, data: A) -> Result<Self::Value, A::Error>
where
A: EnumAccess<'de>,
{
let mut dynamic_enum = DynamicEnum::default();
let (variant_info, variant) = data.variant_seed(VariantDeserializer {
enum_info: self.enum_info,
})?;
let value: DynamicVariant = match variant_info {
VariantInfo::Unit(..) => variant.unit_variant()?.into(),
VariantInfo::Struct(struct_info) => variant
.struct_variant(
struct_info.field_names(),
StructVariantVisitor {
struct_info,
registration: self.registration,
registry: self.registry,
processor: self.processor,
},
)?
.into(),
VariantInfo::Tuple(tuple_info) if tuple_info.field_len() == 1 => {
let registration = try_get_registration(
*TupleLikeInfo::field_at(tuple_info, 0)?.ty(),
self.registry,
)?;
let value =
variant.newtype_variant_seed(TypedReflectDeserializer::new_internal(
registration,
self.registry,
self.processor,
))?;
let mut dynamic_tuple = DynamicTuple::default();
dynamic_tuple.insert_boxed(value);
dynamic_tuple.into()
}
VariantInfo::Tuple(tuple_info) => variant
.tuple_variant(
tuple_info.field_len(),
TupleVariantVisitor {
tuple_info,
registration: self.registration,
registry: self.registry,
processor: self.processor,
},
)?
.into(),
};
let variant_name = variant_info.name();
let variant_index = self
.enum_info
.index_of(variant_name)
.expect("variant should exist");
dynamic_enum.set_variant_with_index(variant_index, variant_name, value);
Ok(dynamic_enum)
}
}
struct VariantDeserializer {
enum_info: &'static EnumInfo,
}
impl<'de> DeserializeSeed<'de> for VariantDeserializer {
type Value = &'static VariantInfo;
fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
where
D: serde::Deserializer<'de>,
{
struct VariantVisitor(&'static EnumInfo);
impl<'de> Visitor<'de> for VariantVisitor {
type Value = &'static VariantInfo;
fn expecting(&self, formatter: &mut Formatter) -> fmt::Result {
formatter.write_str("expected either a variant index or variant name")
}
fn visit_u32<E>(self, variant_index: u32) -> Result<Self::Value, E>
where
E: Error,
{
self.0.variant_at(variant_index as usize).ok_or_else(|| {
make_custom_error(format_args!(
"no variant found at index `{}` on enum `{}`",
variant_index,
self.0.type_path()
))
})
}
fn visit_str<E>(self, variant_name: &str) -> Result<Self::Value, E>
where
E: Error,
{
self.0.variant(variant_name).ok_or_else(|| {
let names = self.0.iter().map(VariantInfo::name);
make_custom_error(format_args!(
"unknown variant `{}`, expected one of {:?}",
variant_name,
ExpectedValues::from_iter(names)
))
})
}
}
deserializer.deserialize_identifier(VariantVisitor(self.enum_info))
}
}
struct StructVariantVisitor<'a, P> {
struct_info: &'static StructVariantInfo,
registration: &'a TypeRegistration,
registry: &'a TypeRegistry,
processor: Option<&'a mut P>,
}
impl<'de, P: ReflectDeserializerProcessor> Visitor<'de> for StructVariantVisitor<'_, P> {
type Value = DynamicStruct;
fn expecting(&self, formatter: &mut Formatter) -> fmt::Result {
formatter.write_str("reflected struct variant value")
}
fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
where
A: SeqAccess<'de>,
{
visit_struct_seq(
&mut seq,
self.struct_info,
self.registration,
self.registry,
self.processor,
)
}
fn visit_map<V>(self, mut map: V) -> Result<Self::Value, V::Error>
where
V: MapAccess<'de>,
{
visit_struct(
&mut map,
self.struct_info,
self.registration,
self.registry,
self.processor,
)
}
}
struct TupleVariantVisitor<'a, P> {
tuple_info: &'static TupleVariantInfo,
registration: &'a TypeRegistration,
registry: &'a TypeRegistry,
processor: Option<&'a mut P>,
}
impl<'de, P: ReflectDeserializerProcessor> Visitor<'de> for TupleVariantVisitor<'_, P> {
type Value = DynamicTuple;
fn expecting(&self, formatter: &mut Formatter) -> fmt::Result {
formatter.write_str("reflected tuple variant value")
}
fn visit_seq<V>(self, mut seq: V) -> Result<Self::Value, V::Error>
where
V: SeqAccess<'de>,
{
visit_tuple(
&mut seq,
self.tuple_info,
self.registration,
self.registry,
self.processor,
)
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/serde/de/options.rs | crates/bevy_reflect/src/serde/de/options.rs | use crate::{
serde::{
de::{error_utils::make_custom_error, registration_utils::try_get_registration},
TypedReflectDeserializer,
},
DynamicEnum, DynamicTuple, EnumInfo, TypeRegistry, VariantInfo,
};
use core::{fmt, fmt::Formatter};
use serde::de::{DeserializeSeed, Error, Visitor};
use super::ReflectDeserializerProcessor;
/// A [`Visitor`] for deserializing [`Option`] values.
pub(super) struct OptionVisitor<'a, P> {
pub enum_info: &'static EnumInfo,
pub registry: &'a TypeRegistry,
pub processor: Option<&'a mut P>,
}
impl<'de, P: ReflectDeserializerProcessor> Visitor<'de> for OptionVisitor<'_, P> {
type Value = DynamicEnum;
fn expecting(&self, formatter: &mut Formatter) -> fmt::Result {
formatter.write_str("reflected option value of type ")?;
formatter.write_str(self.enum_info.type_path())
}
fn visit_none<E>(self) -> Result<Self::Value, E>
where
E: Error,
{
let mut option = DynamicEnum::default();
option.set_variant("None", ());
Ok(option)
}
fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
where
D: serde::Deserializer<'de>,
{
let variant_info = self.enum_info.variant("Some").unwrap();
match variant_info {
VariantInfo::Tuple(tuple_info) if tuple_info.field_len() == 1 => {
let field = tuple_info.field_at(0).unwrap();
let registration = try_get_registration(*field.ty(), self.registry)?;
let de = TypedReflectDeserializer::new_internal(
registration,
self.registry,
self.processor,
);
let mut value = DynamicTuple::default();
value.insert_boxed(de.deserialize(deserializer)?);
let mut option = DynamicEnum::default();
option.set_variant("Some", value);
Ok(option)
}
info => Err(make_custom_error(format_args!(
"invalid variant, expected `Some` but got `{}`",
info.name()
))),
}
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/serde/de/mod.rs | crates/bevy_reflect/src/serde/de/mod.rs | pub use deserialize_with_registry::*;
pub use deserializer::*;
pub use processor::*;
pub use registrations::*;
mod arrays;
mod deserialize_with_registry;
mod deserializer;
mod enums;
mod error_utils;
mod helpers;
mod lists;
mod maps;
mod options;
mod processor;
mod registration_utils;
mod registrations;
mod sets;
mod struct_utils;
mod structs;
mod tuple_structs;
mod tuple_utils;
mod tuples;
#[cfg(test)]
mod tests {
use alloc::{
boxed::Box,
string::{String, ToString},
vec,
vec::Vec,
};
use core::{any::TypeId, f32::consts::PI, ops::RangeInclusive};
use serde::{de::DeserializeSeed, Deserialize};
use serde::{de::IgnoredAny, Deserializer};
use bevy_platform::collections::{HashMap, HashSet};
use crate::{
serde::{
ReflectDeserializer, ReflectDeserializerProcessor, ReflectSerializer,
TypedReflectDeserializer,
},
DynamicEnum, FromReflect, PartialReflect, Reflect, ReflectDeserialize, TypeRegistration,
TypeRegistry,
};
#[derive(Reflect, Debug, PartialEq)]
struct MyStruct {
primitive_value: i8,
option_value: Option<String>,
option_value_complex: Option<SomeStruct>,
tuple_value: (f32, usize),
list_value: Vec<i32>,
array_value: [i32; 5],
map_value: HashMap<u8, usize>,
set_value: HashSet<u8>,
struct_value: SomeStruct,
tuple_struct_value: SomeTupleStruct,
unit_struct: SomeUnitStruct,
unit_enum: SomeEnum,
newtype_enum: SomeEnum,
tuple_enum: SomeEnum,
struct_enum: SomeEnum,
ignored_struct: SomeIgnoredStruct,
ignored_tuple_struct: SomeIgnoredTupleStruct,
ignored_struct_variant: SomeIgnoredEnum,
ignored_tuple_variant: SomeIgnoredEnum,
custom_deserialize: CustomDeserialize,
}
#[derive(Reflect, Debug, PartialEq)]
struct SomeStruct {
foo: i64,
}
#[derive(Reflect, Debug, PartialEq)]
struct SomeTupleStruct(String);
#[derive(Reflect, Debug, PartialEq)]
struct SomeUnitStruct;
#[derive(Reflect, Debug, PartialEq)]
struct SomeIgnoredStruct {
#[reflect(ignore)]
ignored: i32,
}
#[derive(Reflect, Debug, PartialEq)]
struct SomeIgnoredTupleStruct(#[reflect(ignore)] i32);
#[derive(Reflect, Debug, PartialEq, Deserialize)]
struct SomeDeserializableStruct {
foo: i64,
}
/// Implements a custom deserialize using `#[reflect(Deserialize)]`.
///
/// For testing purposes, this is just the auto-generated one from deriving.
#[derive(Reflect, Debug, PartialEq, Deserialize)]
#[reflect(Deserialize)]
struct CustomDeserialize {
value: usize,
#[serde(alias = "renamed")]
inner_struct: SomeDeserializableStruct,
}
#[derive(Reflect, Debug, PartialEq)]
enum SomeEnum {
Unit,
NewType(usize),
Tuple(f32, f32),
Struct { foo: String },
}
#[derive(Reflect, Debug, PartialEq)]
enum SomeIgnoredEnum {
Tuple(#[reflect(ignore)] f32, #[reflect(ignore)] f32),
Struct {
#[reflect(ignore)]
foo: String,
},
}
fn get_registry() -> TypeRegistry {
let mut registry = TypeRegistry::default();
registry.register::<MyStruct>();
registry.register::<SomeStruct>();
registry.register::<SomeTupleStruct>();
registry.register::<SomeUnitStruct>();
registry.register::<SomeIgnoredStruct>();
registry.register::<SomeIgnoredTupleStruct>();
registry.register::<CustomDeserialize>();
registry.register::<SomeDeserializableStruct>();
registry.register::<SomeEnum>();
registry.register::<SomeIgnoredEnum>();
registry.register::<i8>();
registry.register::<String>();
registry.register::<i64>();
registry.register::<f32>();
registry.register::<usize>();
registry.register::<i32>();
registry.register::<u8>();
registry.register::<(f32, usize)>();
registry.register::<[i32; 5]>();
registry.register::<Vec<i32>>();
registry.register::<HashMap<u8, usize>>();
registry.register::<HashSet<u8>>();
registry.register::<Option<SomeStruct>>();
registry.register::<Option<String>>();
registry.register_type_data::<Option<String>, ReflectDeserialize>();
registry
}
fn get_my_struct() -> MyStruct {
let mut map = <HashMap<_, _>>::default();
map.insert(64, 32);
let mut set = <HashSet<_>>::default();
set.insert(64);
MyStruct {
primitive_value: 123,
option_value: Some(String::from("Hello world!")),
option_value_complex: Some(SomeStruct { foo: 123 }),
tuple_value: (PI, 1337),
list_value: vec![-2, -1, 0, 1, 2],
array_value: [-2, -1, 0, 1, 2],
map_value: map,
set_value: set,
struct_value: SomeStruct { foo: 999999999 },
tuple_struct_value: SomeTupleStruct(String::from("Tuple Struct")),
unit_struct: SomeUnitStruct,
unit_enum: SomeEnum::Unit,
newtype_enum: SomeEnum::NewType(123),
tuple_enum: SomeEnum::Tuple(1.23, 3.21),
struct_enum: SomeEnum::Struct {
foo: String::from("Struct variant value"),
},
ignored_struct: SomeIgnoredStruct { ignored: 0 },
ignored_tuple_struct: SomeIgnoredTupleStruct(0),
ignored_struct_variant: SomeIgnoredEnum::Struct {
foo: String::default(),
},
ignored_tuple_variant: SomeIgnoredEnum::Tuple(0.0, 0.0),
custom_deserialize: CustomDeserialize {
value: 100,
inner_struct: SomeDeserializableStruct { foo: 101 },
},
}
}
#[test]
fn should_deserialize() {
let expected = get_my_struct();
let registry = get_registry();
let input = r#"{
"bevy_reflect::serde::de::tests::MyStruct": (
primitive_value: 123,
option_value: Some("Hello world!"),
option_value_complex: Some((
foo: 123,
)),
tuple_value: (3.1415927, 1337),
list_value: [
-2,
-1,
0,
1,
2,
],
array_value: (-2, -1, 0, 1, 2),
map_value: {
64: 32,
},
set_value: [
64,
],
struct_value: (
foo: 999999999,
),
tuple_struct_value: ("Tuple Struct"),
unit_struct: (),
unit_enum: Unit,
newtype_enum: NewType(123),
tuple_enum: Tuple(1.23, 3.21),
struct_enum: Struct(
foo: "Struct variant value",
),
ignored_struct: (),
ignored_tuple_struct: (),
ignored_struct_variant: Struct(),
ignored_tuple_variant: Tuple(),
custom_deserialize: (
value: 100,
renamed: (
foo: 101,
),
),
),
}"#;
let reflect_deserializer = ReflectDeserializer::new(®istry);
let mut ron_deserializer = ron::de::Deserializer::from_str(input).unwrap();
let dynamic_output = reflect_deserializer
.deserialize(&mut ron_deserializer)
.unwrap();
let output = <MyStruct as FromReflect>::from_reflect(dynamic_output.as_ref()).unwrap();
assert_eq!(expected, output);
}
#[test]
fn should_deserialize_value() {
let input = r#"{
"f32": 1.23,
}"#;
let registry = get_registry();
let reflect_deserializer = ReflectDeserializer::new(®istry);
let mut ron_deserializer = ron::de::Deserializer::from_str(input).unwrap();
let dynamic_output = reflect_deserializer
.deserialize(&mut ron_deserializer)
.unwrap();
let output = dynamic_output
.try_take::<f32>()
.expect("underlying type should be f32");
assert_eq!(1.23, output);
}
#[test]
fn should_deserialized_typed() {
#[derive(Reflect, Debug, PartialEq)]
struct Foo {
bar: i32,
}
let expected = Foo { bar: 123 };
let input = r#"(
bar: 123
)"#;
let mut registry = get_registry();
registry.register::<Foo>();
let registration = registry.get(TypeId::of::<Foo>()).unwrap();
let reflect_deserializer = TypedReflectDeserializer::new(registration, ®istry);
let mut ron_deserializer = ron::de::Deserializer::from_str(input).unwrap();
let dynamic_output = reflect_deserializer
.deserialize(&mut ron_deserializer)
.unwrap();
let output =
<Foo as FromReflect>::from_reflect(dynamic_output.as_partial_reflect()).unwrap();
assert_eq!(expected, output);
}
#[test]
fn should_deserialize_option() {
#[derive(Reflect, Debug, PartialEq)]
struct OptionTest {
none: Option<()>,
simple: Option<String>,
complex: Option<SomeStruct>,
}
let expected = OptionTest {
none: None,
simple: Some(String::from("Hello world!")),
complex: Some(SomeStruct { foo: 123 }),
};
let mut registry = get_registry();
registry.register::<OptionTest>();
registry.register::<Option<()>>();
// === Normal === //
let input = r#"{
"bevy_reflect::serde::de::tests::OptionTest": (
none: None,
simple: Some("Hello world!"),
complex: Some((
foo: 123,
)),
),
}"#;
let reflect_deserializer = ReflectDeserializer::new(®istry);
let mut ron_deserializer = ron::de::Deserializer::from_str(input).unwrap();
let dynamic_output = reflect_deserializer
.deserialize(&mut ron_deserializer)
.unwrap();
let output = <OptionTest as FromReflect>::from_reflect(dynamic_output.as_ref()).unwrap();
assert_eq!(expected, output, "failed to deserialize Options");
// === Implicit Some === //
let input = r#"
#![enable(implicit_some)]
{
"bevy_reflect::serde::de::tests::OptionTest": (
none: None,
simple: "Hello world!",
complex: (
foo: 123,
),
),
}"#;
let reflect_deserializer = ReflectDeserializer::new(®istry);
let mut ron_deserializer = ron::de::Deserializer::from_str(input).unwrap();
let dynamic_output = reflect_deserializer
.deserialize(&mut ron_deserializer)
.unwrap();
let output = <OptionTest as FromReflect>::from_reflect(dynamic_output.as_ref()).unwrap();
assert_eq!(
expected, output,
"failed to deserialize Options with implicit Some"
);
}
#[test]
fn enum_should_deserialize() {
#[derive(Reflect)]
enum MyEnum {
Unit,
NewType(usize),
Tuple(f32, f32),
Struct { value: String },
}
let mut registry = get_registry();
registry.register::<MyEnum>();
// === Unit Variant === //
let input = r#"{
"bevy_reflect::serde::de::tests::MyEnum": Unit,
}"#;
let reflect_deserializer = ReflectDeserializer::new(®istry);
let mut deserializer = ron::de::Deserializer::from_str(input).unwrap();
let output = reflect_deserializer.deserialize(&mut deserializer).unwrap();
let expected = DynamicEnum::from(MyEnum::Unit);
assert!(expected.reflect_partial_eq(output.as_ref()).unwrap());
// === NewType Variant === //
let input = r#"{
"bevy_reflect::serde::de::tests::MyEnum": NewType(123),
}"#;
let reflect_deserializer = ReflectDeserializer::new(®istry);
let mut deserializer = ron::de::Deserializer::from_str(input).unwrap();
let output = reflect_deserializer.deserialize(&mut deserializer).unwrap();
let expected = DynamicEnum::from(MyEnum::NewType(123));
assert!(expected.reflect_partial_eq(output.as_ref()).unwrap());
// === Tuple Variant === //
let input = r#"{
"bevy_reflect::serde::de::tests::MyEnum": Tuple(1.23, 3.21),
}"#;
let reflect_deserializer = ReflectDeserializer::new(®istry);
let mut deserializer = ron::de::Deserializer::from_str(input).unwrap();
let output = reflect_deserializer.deserialize(&mut deserializer).unwrap();
let expected = DynamicEnum::from(MyEnum::Tuple(1.23, 3.21));
assert!(expected
.reflect_partial_eq(output.as_partial_reflect())
.unwrap());
// === Struct Variant === //
let input = r#"{
"bevy_reflect::serde::de::tests::MyEnum": Struct(
value: "I <3 Enums",
),
}"#;
let reflect_deserializer = ReflectDeserializer::new(®istry);
let mut deserializer = ron::de::Deserializer::from_str(input).unwrap();
let output = reflect_deserializer.deserialize(&mut deserializer).unwrap();
let expected = DynamicEnum::from(MyEnum::Struct {
value: String::from("I <3 Enums"),
});
assert!(expected
.reflect_partial_eq(output.as_partial_reflect())
.unwrap());
}
// Regression test for https://github.com/bevyengine/bevy/issues/12462
#[test]
fn should_reserialize() {
let registry = get_registry();
let input1 = get_my_struct();
let serializer1 = ReflectSerializer::new(&input1, ®istry);
let serialized1 = ron::ser::to_string(&serializer1).unwrap();
let mut deserializer = ron::de::Deserializer::from_str(&serialized1).unwrap();
let reflect_deserializer = ReflectDeserializer::new(®istry);
let input2 = reflect_deserializer.deserialize(&mut deserializer).unwrap();
let serializer2 = ReflectSerializer::new(input2.as_partial_reflect(), ®istry);
let serialized2 = ron::ser::to_string(&serializer2).unwrap();
assert_eq!(serialized1, serialized2);
}
#[test]
fn should_deserialize_non_self_describing_binary() {
let expected = get_my_struct();
let registry = get_registry();
let input = vec![
1, 0, 0, 0, 0, 0, 0, 0, 40, 0, 0, 0, 0, 0, 0, 0, 98, 101, 118, 121, 95, 114, 101, 102,
108, 101, 99, 116, 58, 58, 115, 101, 114, 100, 101, 58, 58, 100, 101, 58, 58, 116, 101,
115, 116, 115, 58, 58, 77, 121, 83, 116, 114, 117, 99, 116, 123, 1, 12, 0, 0, 0, 0, 0,
0, 0, 72, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100, 33, 1, 123, 0, 0, 0, 0, 0,
0, 0, 219, 15, 73, 64, 57, 5, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 254, 255, 255,
255, 255, 255, 255, 255, 0, 0, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 254, 255, 255, 255, 255,
255, 255, 255, 0, 0, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 64, 32, 0,
0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 64, 255, 201, 154, 59, 0, 0, 0, 0, 12, 0, 0,
0, 0, 0, 0, 0, 84, 117, 112, 108, 101, 32, 83, 116, 114, 117, 99, 116, 0, 0, 0, 0, 1,
0, 0, 0, 123, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 164, 112, 157, 63, 164, 112, 77, 64, 3,
0, 0, 0, 20, 0, 0, 0, 0, 0, 0, 0, 83, 116, 114, 117, 99, 116, 32, 118, 97, 114, 105,
97, 110, 116, 32, 118, 97, 108, 117, 101, 1, 0, 0, 0, 0, 0, 0, 0, 100, 0, 0, 0, 0, 0,
0, 0, 101, 0, 0, 0, 0, 0, 0, 0,
];
let deserializer = ReflectDeserializer::new(®istry);
let config = bincode::config::standard().with_fixed_int_encoding();
let (dynamic_output, _read_bytes) =
bincode::serde::seed_decode_from_slice(deserializer, &input, config).unwrap();
let output = <MyStruct as FromReflect>::from_reflect(dynamic_output.as_ref()).unwrap();
assert_eq!(expected, output);
}
#[test]
fn should_deserialize_self_describing_binary() {
let expected = get_my_struct();
let registry = get_registry();
let input = vec![
129, 217, 40, 98, 101, 118, 121, 95, 114, 101, 102, 108, 101, 99, 116, 58, 58, 115,
101, 114, 100, 101, 58, 58, 100, 101, 58, 58, 116, 101, 115, 116, 115, 58, 58, 77, 121,
83, 116, 114, 117, 99, 116, 220, 0, 20, 123, 172, 72, 101, 108, 108, 111, 32, 119, 111,
114, 108, 100, 33, 145, 123, 146, 202, 64, 73, 15, 219, 205, 5, 57, 149, 254, 255, 0,
1, 2, 149, 254, 255, 0, 1, 2, 129, 64, 32, 145, 64, 145, 206, 59, 154, 201, 255, 172,
84, 117, 112, 108, 101, 32, 83, 116, 114, 117, 99, 116, 144, 164, 85, 110, 105, 116,
129, 167, 78, 101, 119, 84, 121, 112, 101, 123, 129, 165, 84, 117, 112, 108, 101, 146,
202, 63, 157, 112, 164, 202, 64, 77, 112, 164, 129, 166, 83, 116, 114, 117, 99, 116,
145, 180, 83, 116, 114, 117, 99, 116, 32, 118, 97, 114, 105, 97, 110, 116, 32, 118, 97,
108, 117, 101, 144, 144, 129, 166, 83, 116, 114, 117, 99, 116, 144, 129, 165, 84, 117,
112, 108, 101, 144, 146, 100, 145, 101,
];
let mut reader = std::io::BufReader::new(input.as_slice());
let deserializer = ReflectDeserializer::new(®istry);
let dynamic_output = deserializer
.deserialize(&mut rmp_serde::Deserializer::new(&mut reader))
.unwrap();
let output = <MyStruct as FromReflect>::from_reflect(dynamic_output.as_ref()).unwrap();
assert_eq!(expected, output);
}
#[test]
fn should_return_error_if_missing_type_data() {
let mut registry = TypeRegistry::new();
registry.register::<RangeInclusive<f32>>();
let input = r#"{"core::ops::RangeInclusive<f32>":(start:0.0,end:1.0)}"#;
let mut deserializer = ron::de::Deserializer::from_str(input).unwrap();
let reflect_deserializer = ReflectDeserializer::new(®istry);
let error = reflect_deserializer
.deserialize(&mut deserializer)
.unwrap_err();
#[cfg(feature = "debug_stack")]
assert_eq!(error, ron::Error::Message("type `core::ops::RangeInclusive<f32>` did not register the `ReflectDeserialize` type data. For certain types, this may need to be registered manually using `register_type_data` (stack: `core::ops::RangeInclusive<f32>`)".to_string()));
#[cfg(not(feature = "debug_stack"))]
assert_eq!(error, ron::Error::Message("type `core::ops::RangeInclusive<f32>` did not register the `ReflectDeserialize` type data. For certain types, this may need to be registered manually using `register_type_data`".to_string()));
}
#[test]
fn should_use_processor_for_custom_deserialization() {
#[derive(Reflect, Debug, PartialEq)]
struct Foo {
bar: i32,
qux: i64,
}
struct FooProcessor;
impl ReflectDeserializerProcessor for FooProcessor {
fn try_deserialize<'de, D>(
&mut self,
registration: &TypeRegistration,
_: &TypeRegistry,
deserializer: D,
) -> Result<Result<Box<dyn PartialReflect>, D>, D::Error>
where
D: Deserializer<'de>,
{
if registration.type_id() == TypeId::of::<i64>() {
let _ = deserializer.deserialize_ignored_any(IgnoredAny);
Ok(Ok(Box::new(456_i64)))
} else {
Ok(Err(deserializer))
}
}
}
let expected = Foo { bar: 123, qux: 456 };
let input = r#"(
bar: 123,
qux: 123,
)"#;
let mut registry = get_registry();
registry.register::<Foo>();
let registration = registry.get(TypeId::of::<Foo>()).unwrap();
let mut processor = FooProcessor;
let reflect_deserializer =
TypedReflectDeserializer::with_processor(registration, ®istry, &mut processor);
let mut ron_deserializer = ron::de::Deserializer::from_str(input).unwrap();
let dynamic_output = reflect_deserializer
.deserialize(&mut ron_deserializer)
.unwrap();
let output =
<Foo as FromReflect>::from_reflect(dynamic_output.as_partial_reflect()).unwrap();
assert_eq!(expected, output);
}
#[test]
fn should_use_processor_for_multiple_registrations() {
#[derive(Reflect, Debug, PartialEq)]
struct Foo {
bar: i32,
qux: i64,
}
struct FooProcessor;
impl ReflectDeserializerProcessor for FooProcessor {
fn try_deserialize<'de, D>(
&mut self,
registration: &TypeRegistration,
_: &TypeRegistry,
deserializer: D,
) -> Result<Result<Box<dyn PartialReflect>, D>, D::Error>
where
D: Deserializer<'de>,
{
if registration.type_id() == TypeId::of::<i32>() {
let _ = deserializer.deserialize_ignored_any(IgnoredAny);
Ok(Ok(Box::new(123_i32)))
} else if registration.type_id() == TypeId::of::<i64>() {
let _ = deserializer.deserialize_ignored_any(IgnoredAny);
Ok(Ok(Box::new(456_i64)))
} else {
Ok(Err(deserializer))
}
}
}
let expected = Foo { bar: 123, qux: 456 };
let input = r#"(
bar: 0,
qux: 0,
)"#;
let mut registry = get_registry();
registry.register::<Foo>();
let registration = registry.get(TypeId::of::<Foo>()).unwrap();
let mut processor = FooProcessor;
let reflect_deserializer =
TypedReflectDeserializer::with_processor(registration, ®istry, &mut processor);
let mut ron_deserializer = ron::de::Deserializer::from_str(input).unwrap();
let dynamic_output = reflect_deserializer
.deserialize(&mut ron_deserializer)
.unwrap();
let output =
<Foo as FromReflect>::from_reflect(dynamic_output.as_partial_reflect()).unwrap();
assert_eq!(expected, output);
}
#[test]
fn should_propagate_processor_deserialize_error() {
struct ErroringProcessor;
impl ReflectDeserializerProcessor for ErroringProcessor {
fn try_deserialize<'de, D>(
&mut self,
registration: &TypeRegistration,
_: &TypeRegistry,
deserializer: D,
) -> Result<Result<Box<dyn PartialReflect>, D>, D::Error>
where
D: Deserializer<'de>,
{
if registration.type_id() == TypeId::of::<i32>() {
Err(serde::de::Error::custom("my custom deserialize error"))
} else {
Ok(Err(deserializer))
}
}
}
let registry = get_registry();
let input = r#"{"i32":123}"#;
let mut deserializer = ron::de::Deserializer::from_str(input).unwrap();
let mut processor = ErroringProcessor;
let reflect_deserializer = ReflectDeserializer::with_processor(®istry, &mut processor);
let error = reflect_deserializer
.deserialize(&mut deserializer)
.unwrap_err();
#[cfg(feature = "debug_stack")]
assert_eq!(
error,
ron::Error::Message("my custom deserialize error (stack: `i32`)".to_string())
);
#[cfg(not(feature = "debug_stack"))]
assert_eq!(
error,
ron::Error::Message("my custom deserialize error".to_string())
);
}
#[test]
fn should_access_local_scope_in_processor() {
struct ValueCountingProcessor<'a> {
values_found: &'a mut usize,
}
impl ReflectDeserializerProcessor for ValueCountingProcessor<'_> {
fn try_deserialize<'de, D>(
&mut self,
_: &TypeRegistration,
_: &TypeRegistry,
deserializer: D,
) -> Result<Result<Box<dyn PartialReflect>, D>, D::Error>
where
D: Deserializer<'de>,
{
let _ = deserializer.deserialize_ignored_any(IgnoredAny)?;
*self.values_found += 1;
Ok(Ok(Box::new(123_i32)))
}
}
let registry = get_registry();
let input = r#"{"i32":0}"#;
let mut values_found = 0_usize;
let mut deserializer_processor = ValueCountingProcessor {
values_found: &mut values_found,
};
let mut deserializer = ron::de::Deserializer::from_str(input).unwrap();
let reflect_deserializer =
ReflectDeserializer::with_processor(®istry, &mut deserializer_processor);
reflect_deserializer.deserialize(&mut deserializer).unwrap();
assert_eq!(1, values_found);
}
#[test]
fn should_fail_from_reflect_if_processor_returns_wrong_typed_value() {
#[derive(Reflect, Debug, PartialEq)]
struct Foo {
bar: i32,
qux: i64,
}
struct WrongTypeProcessor;
impl ReflectDeserializerProcessor for WrongTypeProcessor {
fn try_deserialize<'de, D>(
&mut self,
registration: &TypeRegistration,
_registry: &TypeRegistry,
deserializer: D,
) -> Result<Result<Box<dyn PartialReflect>, D>, D::Error>
where
D: Deserializer<'de>,
{
if registration.type_id() == TypeId::of::<i32>() {
let _ = deserializer.deserialize_ignored_any(IgnoredAny);
Ok(Ok(Box::new(42_i64)))
} else {
Ok(Err(deserializer))
}
}
}
let input = r#"(
bar: 123,
qux: 123,
)"#;
let mut registry = get_registry();
registry.register::<Foo>();
let registration = registry.get(TypeId::of::<Foo>()).unwrap();
let mut processor = WrongTypeProcessor;
let reflect_deserializer =
TypedReflectDeserializer::with_processor(registration, ®istry, &mut processor);
let mut ron_deserializer = ron::de::Deserializer::from_str(input).unwrap();
let dynamic_output = reflect_deserializer
.deserialize(&mut ron_deserializer)
.unwrap();
assert!(<Foo as FromReflect>::from_reflect(dynamic_output.as_partial_reflect()).is_none());
}
#[cfg(feature = "functions")]
mod functions {
use super::*;
use crate::func::DynamicFunction;
#[test]
fn should_not_deserialize_function() {
#[derive(Reflect)]
#[reflect(from_reflect = false)]
struct MyStruct {
func: DynamicFunction<'static>,
}
let mut registry = TypeRegistry::new();
registry.register::<MyStruct>();
let input = r#"{
"bevy_reflect::serde::de::tests::functions::MyStruct": (
func: (),
),
}"#;
let reflect_deserializer = ReflectDeserializer::new(®istry);
let mut ron_deserializer = ron::de::Deserializer::from_str(input).unwrap();
let error = reflect_deserializer
.deserialize(&mut ron_deserializer)
.unwrap_err();
#[cfg(feature = "debug_stack")]
assert_eq!(
error,
ron::Error::Message(
"no registration found for type `bevy_reflect::DynamicFunction` (stack: `bevy_reflect::serde::de::tests::functions::MyStruct`)"
.to_string()
)
);
#[cfg(not(feature = "debug_stack"))]
assert_eq!(
error,
ron::Error::Message(
"no registration found for type `bevy_reflect::DynamicFunction`".to_string()
)
);
}
}
#[cfg(feature = "debug_stack")]
mod debug_stack {
use super::*;
#[test]
fn should_report_context_in_errors() {
#[derive(Reflect)]
struct Foo {
bar: Bar,
}
#[derive(Reflect)]
struct Bar {
some_other_field: Option<u32>,
baz: Baz,
}
#[derive(Reflect)]
struct Baz {
value: Vec<RangeInclusive<f32>>,
}
let mut registry = TypeRegistry::new();
registry.register::<Foo>();
registry.register::<Bar>();
registry.register::<Baz>();
registry.register::<RangeInclusive<f32>>();
let input = r#"{"bevy_reflect::serde::de::tests::debug_stack::Foo":(bar:(some_other_field:Some(123),baz:(value:[(start:0.0,end:1.0)])))}"#;
let mut deserializer = ron::de::Deserializer::from_str(input).unwrap();
let reflect_deserializer = ReflectDeserializer::new(®istry);
let error = reflect_deserializer
.deserialize(&mut deserializer)
.unwrap_err();
assert_eq!(
error,
ron::Error::Message(
"type `core::ops::RangeInclusive<f32>` did not register the `ReflectDeserialize` type data. For certain types, this may need to be registered manually using `register_type_data` (stack: `bevy_reflect::serde::de::tests::debug_stack::Foo` -> `bevy_reflect::serde::de::tests::debug_stack::Bar` -> `bevy_reflect::serde::de::tests::debug_stack::Baz` -> `alloc::vec::Vec<core::ops::RangeInclusive<f32>>` -> `core::ops::RangeInclusive<f32>`)".to_string()
)
);
}
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/serde/de/deserialize_with_registry.rs | crates/bevy_reflect/src/serde/de/deserialize_with_registry.rs | use crate::serde::de::error_utils::make_custom_error;
use crate::{FromType, PartialReflect, TypeRegistry};
use alloc::boxed::Box;
use serde::Deserializer;
/// Trait used to provide finer control when deserializing a reflected type with one of
/// the reflection deserializers.
///
/// This trait is the reflection equivalent of `serde`'s [`Deserialize`] trait.
/// The main difference is that this trait provides access to the [`TypeRegistry`],
/// which means that we can use the registry and all its stored type information
/// to deserialize our type.
///
/// This can be useful when writing a custom reflection deserializer where we may
/// want to handle parts of the deserialization process, but temporarily pass control
/// to the standard reflection deserializer for other parts.
///
/// For the serialization equivalent of this trait, see [`SerializeWithRegistry`].
///
/// # Rationale
///
/// Without this trait and its associated [type data], such a deserializer would have to
/// write out all of the deserialization logic itself, possibly including
/// unnecessary code duplication and trivial implementations.
///
/// This is because a normal [`Deserialize`] implementation has no knowledge of the
/// [`TypeRegistry`] and therefore cannot create a reflection-based deserializer for
/// nested items.
///
/// # Implementors
///
/// In order for this to work with the reflection deserializers like [`TypedReflectDeserializer`]
/// and [`ReflectDeserializer`], implementors should be sure to register the
/// [`ReflectDeserializeWithRegistry`] type data.
/// This can be done [via the registry] or by adding `#[reflect(DeserializeWithRegistry)]` to
/// the type definition.
///
/// [`Deserialize`]: ::serde::Deserialize
/// [`SerializeWithRegistry`]: crate::serde::SerializeWithRegistry
/// [type data]: ReflectDeserializeWithRegistry
/// [`TypedReflectDeserializer`]: crate::serde::TypedReflectDeserializer
/// [`ReflectDeserializer`]: crate::serde::ReflectDeserializer
/// [via the registry]: TypeRegistry::register_type_data
pub trait DeserializeWithRegistry<'de>: Sized {
/// Deserialize this value using the given [Deserializer] and [`TypeRegistry`].
///
/// [`Deserializer`]: ::serde::Deserializer
fn deserialize<D>(deserializer: D, registry: &TypeRegistry) -> Result<Self, D::Error>
where
D: Deserializer<'de>;
}
/// Type data used to deserialize a [`PartialReflect`] type with a custom [`DeserializeWithRegistry`] implementation.
#[derive(Clone)]
pub struct ReflectDeserializeWithRegistry {
deserialize: fn(
deserializer: &mut dyn erased_serde::Deserializer,
registry: &TypeRegistry,
) -> Result<Box<dyn PartialReflect>, erased_serde::Error>,
}
impl ReflectDeserializeWithRegistry {
/// Deserialize a [`PartialReflect`] type with this type data's custom [`DeserializeWithRegistry`] implementation.
pub fn deserialize<'de, D>(
&self,
deserializer: D,
registry: &TypeRegistry,
) -> Result<Box<dyn PartialReflect>, D::Error>
where
D: Deserializer<'de>,
{
let mut erased = <dyn erased_serde::Deserializer>::erase(deserializer);
(self.deserialize)(&mut erased, registry).map_err(make_custom_error)
}
}
impl<T: PartialReflect + for<'de> DeserializeWithRegistry<'de>> FromType<T>
for ReflectDeserializeWithRegistry
{
fn from_type() -> Self {
Self {
deserialize: |deserializer, registry| {
Ok(Box::new(T::deserialize(deserializer, registry)?))
},
}
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/serde/de/error_utils.rs | crates/bevy_reflect/src/serde/de/error_utils.rs | use core::fmt::Display;
use serde::de::Error;
#[cfg(feature = "debug_stack")]
use std::thread_local;
#[cfg(feature = "debug_stack")]
thread_local! {
/// The thread-local [`TypeInfoStack`] used for debugging.
///
/// [`TypeInfoStack`]: crate::type_info_stack::TypeInfoStack
pub(super) static TYPE_INFO_STACK: core::cell::RefCell<crate::type_info_stack::TypeInfoStack> = const { core::cell::RefCell::new(
crate::type_info_stack::TypeInfoStack::new()
) };
}
/// A helper function for generating a custom deserialization error message.
///
/// This function should be preferred over [`Error::custom`] as it will include
/// other useful information, such as the [type info stack].
///
/// [type info stack]: crate::type_info_stack::TypeInfoStack
pub(super) fn make_custom_error<E: Error>(msg: impl Display) -> E {
#[cfg(feature = "debug_stack")]
return TYPE_INFO_STACK
.with_borrow(|stack| E::custom(format_args!("{msg} (stack: {stack:?})")));
#[cfg(not(feature = "debug_stack"))]
return E::custom(msg);
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/serde/de/tuples.rs | crates/bevy_reflect/src/serde/de/tuples.rs | use crate::{
serde::de::tuple_utils::visit_tuple, DynamicTuple, TupleInfo, TypeRegistration, TypeRegistry,
};
use core::{fmt, fmt::Formatter};
use serde::de::{SeqAccess, Visitor};
use super::ReflectDeserializerProcessor;
/// A [`Visitor`] for deserializing [`Tuple`] values.
///
/// [`Tuple`]: crate::Tuple
pub(super) struct TupleVisitor<'a, P> {
pub tuple_info: &'static TupleInfo,
pub registration: &'a TypeRegistration,
pub registry: &'a TypeRegistry,
pub processor: Option<&'a mut P>,
}
impl<'de, P: ReflectDeserializerProcessor> Visitor<'de> for TupleVisitor<'_, P> {
type Value = DynamicTuple;
fn expecting(&self, formatter: &mut Formatter) -> fmt::Result {
formatter.write_str("reflected tuple value")
}
fn visit_seq<V>(self, mut seq: V) -> Result<Self::Value, V::Error>
where
V: SeqAccess<'de>,
{
visit_tuple(
&mut seq,
self.tuple_info,
self.registration,
self.registry,
self.processor,
)
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/serde/de/struct_utils.rs | crates/bevy_reflect/src/serde/de/struct_utils.rs | use crate::{
serde::{
de::{
error_utils::make_custom_error,
helpers::{ExpectedValues, Ident},
registration_utils::try_get_registration,
},
SerializationData, TypedReflectDeserializer,
},
DynamicStruct, NamedField, StructInfo, StructVariantInfo, TypeRegistration, TypeRegistry,
};
use alloc::string::ToString;
use core::slice::Iter;
use serde::de::{Error, MapAccess, SeqAccess};
use super::ReflectDeserializerProcessor;
/// A helper trait for accessing type information from struct-like types.
pub(super) trait StructLikeInfo {
fn field<E: Error>(&self, name: &str) -> Result<&NamedField, E>;
fn field_at<E: Error>(&self, index: usize) -> Result<&NamedField, E>;
fn field_len(&self) -> usize;
fn iter_fields(&self) -> Iter<'_, NamedField>;
}
impl StructLikeInfo for StructInfo {
fn field<E: Error>(&self, name: &str) -> Result<&NamedField, E> {
Self::field(self, name).ok_or_else(|| {
make_custom_error(format_args!(
"no field named `{}` on struct `{}`",
name,
self.type_path(),
))
})
}
fn field_at<E: Error>(&self, index: usize) -> Result<&NamedField, E> {
Self::field_at(self, index).ok_or_else(|| {
make_custom_error(format_args!(
"no field at index `{}` on struct `{}`",
index,
self.type_path(),
))
})
}
fn field_len(&self) -> usize {
Self::field_len(self)
}
fn iter_fields(&self) -> Iter<'_, NamedField> {
self.iter()
}
}
impl StructLikeInfo for StructVariantInfo {
fn field<E: Error>(&self, name: &str) -> Result<&NamedField, E> {
Self::field(self, name).ok_or_else(|| {
make_custom_error(format_args!(
"no field named `{}` on variant `{}`",
name,
self.name(),
))
})
}
fn field_at<E: Error>(&self, index: usize) -> Result<&NamedField, E> {
Self::field_at(self, index).ok_or_else(|| {
make_custom_error(format_args!(
"no field at index `{}` on variant `{}`",
index,
self.name(),
))
})
}
fn field_len(&self) -> usize {
Self::field_len(self)
}
fn iter_fields(&self) -> Iter<'_, NamedField> {
self.iter()
}
}
/// Deserializes a [struct-like] type from a mapping of fields, returning a [`DynamicStruct`].
///
/// [struct-like]: StructLikeInfo
pub(super) fn visit_struct<'de, T, V, P>(
map: &mut V,
info: &'static T,
registration: &TypeRegistration,
registry: &TypeRegistry,
mut processor: Option<&mut P>,
) -> Result<DynamicStruct, V::Error>
where
T: StructLikeInfo,
V: MapAccess<'de>,
P: ReflectDeserializerProcessor,
{
let mut dynamic_struct = DynamicStruct::default();
while let Some(Ident(key)) = map.next_key::<Ident>()? {
let field = info.field::<V::Error>(&key).map_err(|_| {
let fields = info.iter_fields().map(NamedField::name);
make_custom_error(format_args!(
"unknown field `{}`, expected one of {:?}",
key,
ExpectedValues::from_iter(fields)
))
})?;
let registration = try_get_registration(*field.ty(), registry)?;
let value = map.next_value_seed(TypedReflectDeserializer::new_internal(
registration,
registry,
processor.as_deref_mut(),
))?;
dynamic_struct.insert_boxed(&key, value);
}
if let Some(serialization_data) = registration.data::<SerializationData>() {
for (skipped_index, skipped_field) in serialization_data.iter_skipped() {
let Ok(field) = info.field_at::<V::Error>(*skipped_index) else {
continue;
};
dynamic_struct.insert_boxed(
field.name(),
skipped_field.generate_default().into_partial_reflect(),
);
}
}
Ok(dynamic_struct)
}
/// Deserializes a [struct-like] type from a sequence of fields, returning a [`DynamicStruct`].
///
/// [struct-like]: StructLikeInfo
pub(super) fn visit_struct_seq<'de, T, V, P>(
seq: &mut V,
info: &T,
registration: &TypeRegistration,
registry: &TypeRegistry,
mut processor: Option<&mut P>,
) -> Result<DynamicStruct, V::Error>
where
T: StructLikeInfo,
V: SeqAccess<'de>,
P: ReflectDeserializerProcessor,
{
let mut dynamic_struct = DynamicStruct::default();
let len = info.field_len();
if len == 0 {
// Handle unit structs
return Ok(dynamic_struct);
}
let serialization_data = registration.data::<SerializationData>();
for index in 0..len {
let name = info.field_at::<V::Error>(index)?.name();
if serialization_data
.map(|data| data.is_field_skipped(index))
.unwrap_or_default()
{
if let Some(value) = serialization_data.unwrap().generate_default(index) {
dynamic_struct.insert_boxed(name, value.into_partial_reflect());
}
continue;
}
let value = seq
.next_element_seed(TypedReflectDeserializer::new_internal(
try_get_registration(*info.field_at(index)?.ty(), registry)?,
registry,
processor.as_deref_mut(),
))?
.ok_or_else(|| Error::invalid_length(index, &len.to_string().as_str()))?;
dynamic_struct.insert_boxed(name, value);
}
Ok(dynamic_struct)
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/serde/de/deserializer.rs | crates/bevy_reflect/src/serde/de/deserializer.rs | #[cfg(feature = "debug_stack")]
use crate::serde::de::error_utils::TYPE_INFO_STACK;
use crate::serde::{ReflectDeserializeWithRegistry, SerializationData};
use crate::ReflectFromReflect;
use crate::{
serde::{
de::{
arrays::ArrayVisitor, enums::EnumVisitor, error_utils::make_custom_error,
lists::ListVisitor, maps::MapVisitor, options::OptionVisitor, sets::SetVisitor,
structs::StructVisitor, tuple_structs::TupleStructVisitor, tuples::TupleVisitor,
},
TypeRegistrationDeserializer,
},
PartialReflect, ReflectDeserialize, TypeInfo, TypePath, TypeRegistration, TypeRegistry,
};
use alloc::boxed::Box;
use core::{fmt, fmt::Formatter};
use serde::de::{DeserializeSeed, Error, IgnoredAny, MapAccess, Visitor};
use super::ReflectDeserializerProcessor;
/// A general purpose deserializer for reflected types.
///
/// This is the deserializer counterpart to [`ReflectSerializer`].
///
/// See [`TypedReflectDeserializer`] for a deserializer that expects a known type.
///
/// # Input
///
/// This deserializer expects a map with a single entry,
/// where the key is the _full_ [type path] of the reflected type
/// and the value is the serialized data.
///
/// # Output
///
/// This deserializer will return a [`Box<dyn Reflect>`] containing the deserialized data.
///
/// For opaque types (i.e. [`ReflectKind::Opaque`]) or types that register [`ReflectDeserialize`] type data,
/// this `Box` will contain the expected type.
/// For example, deserializing an `i32` will return a `Box<i32>` (as a `Box<dyn Reflect>`).
///
/// Otherwise, this `Box` will contain the dynamic equivalent.
/// For example, a deserialized struct might return a [`Box<DynamicStruct>`]
/// and a deserialized `Vec` might return a [`Box<DynamicList>`].
///
/// This means that if the actual type is needed, these dynamic representations will need to
/// be converted to the concrete type using [`FromReflect`] or [`ReflectFromReflect`].
///
/// If you want to override deserialization for a specific [`TypeRegistration`],
/// you can pass in a reference to a [`ReflectDeserializerProcessor`] which will
/// take priority over all other deserialization methods - see [`with_processor`].
///
/// # Example
///
/// ```
/// # use serde::de::DeserializeSeed;
/// # use bevy_reflect::prelude::*;
/// # use bevy_reflect::{DynamicStruct, TypeRegistry, serde::ReflectDeserializer};
/// #[derive(Reflect, PartialEq, Debug)]
/// #[type_path = "my_crate"]
/// struct MyStruct {
/// value: i32
/// }
///
/// let mut registry = TypeRegistry::default();
/// registry.register::<MyStruct>();
///
/// let input = r#"{
/// "my_crate::MyStruct": (
/// value: 123
/// )
/// }"#;
///
/// let mut deserializer = ron::Deserializer::from_str(input).unwrap();
/// let reflect_deserializer = ReflectDeserializer::new(®istry);
///
/// let output: Box<dyn PartialReflect> = reflect_deserializer.deserialize(&mut deserializer).unwrap();
///
/// // Since `MyStruct` is not an opaque type and does not register `ReflectDeserialize`,
/// // we know that its deserialized value will be a `DynamicStruct`,
/// // although it will represent `MyStruct`.
/// assert!(output.as_partial_reflect().represents::<MyStruct>());
///
/// // We can convert back to `MyStruct` using `FromReflect`.
/// let value: MyStruct = <MyStruct as FromReflect>::from_reflect(output.as_partial_reflect()).unwrap();
/// assert_eq!(value, MyStruct { value: 123 });
///
/// // We can also do this dynamically with `ReflectFromReflect`.
/// let type_id = output.get_represented_type_info().unwrap().type_id();
/// let reflect_from_reflect = registry.get_type_data::<ReflectFromReflect>(type_id).unwrap();
/// let value: Box<dyn Reflect> = reflect_from_reflect.from_reflect(output.as_partial_reflect()).unwrap();
/// assert!(value.is::<MyStruct>());
/// assert_eq!(value.take::<MyStruct>().unwrap(), MyStruct { value: 123 });
/// ```
///
/// [`ReflectSerializer`]: crate::serde::ReflectSerializer
/// [type path]: crate::TypePath::type_path
/// [`Box<dyn Reflect>`]: crate::Reflect
/// [`ReflectKind::Opaque`]: crate::ReflectKind::Opaque
/// [`ReflectDeserialize`]: crate::ReflectDeserialize
/// [`Box<DynamicStruct>`]: crate::DynamicStruct
/// [`Box<DynamicList>`]: crate::DynamicList
/// [`FromReflect`]: crate::FromReflect
/// [`ReflectFromReflect`]: crate::ReflectFromReflect
/// [`with_processor`]: Self::with_processor
pub struct ReflectDeserializer<'a, P: ReflectDeserializerProcessor = ()> {
registry: &'a TypeRegistry,
processor: Option<&'a mut P>,
}
impl<'a> ReflectDeserializer<'a, ()> {
/// Creates a deserializer with no processor.
///
/// If you want to add custom logic for deserializing certain types, use
/// [`with_processor`].
///
/// [`with_processor`]: Self::with_processor
pub fn new(registry: &'a TypeRegistry) -> Self {
Self {
registry,
processor: None,
}
}
}
impl<'a, P: ReflectDeserializerProcessor> ReflectDeserializer<'a, P> {
/// Creates a deserializer with a processor.
///
/// If you do not need any custom logic for handling certain types, use
/// [`new`].
///
/// [`new`]: Self::new
pub fn with_processor(registry: &'a TypeRegistry, processor: &'a mut P) -> Self {
Self {
registry,
processor: Some(processor),
}
}
}
impl<'de, P: ReflectDeserializerProcessor> DeserializeSeed<'de> for ReflectDeserializer<'_, P> {
type Value = Box<dyn PartialReflect>;
fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
where
D: serde::Deserializer<'de>,
{
struct UntypedReflectDeserializerVisitor<'a, P> {
registry: &'a TypeRegistry,
processor: Option<&'a mut P>,
}
impl<'de, P: ReflectDeserializerProcessor> Visitor<'de>
for UntypedReflectDeserializerVisitor<'_, P>
{
type Value = Box<dyn PartialReflect>;
fn expecting(&self, formatter: &mut Formatter) -> fmt::Result {
formatter
.write_str("map containing `type` and `value` entries for the reflected value")
}
fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
where
A: MapAccess<'de>,
{
let registration = map
.next_key_seed(TypeRegistrationDeserializer::new(self.registry))?
.ok_or_else(|| Error::invalid_length(0, &"a single entry"))?;
let value = map.next_value_seed(TypedReflectDeserializer::new_internal(
registration,
self.registry,
self.processor,
))?;
if map.next_key::<IgnoredAny>()?.is_some() {
return Err(Error::invalid_length(2, &"a single entry"));
}
Ok(value)
}
}
deserializer.deserialize_map(UntypedReflectDeserializerVisitor {
registry: self.registry,
processor: self.processor,
})
}
}
/// A deserializer for reflected types whose [`TypeRegistration`] is known.
///
/// This is the deserializer counterpart to [`TypedReflectSerializer`].
///
/// See [`ReflectDeserializer`] for a deserializer that expects an unknown type.
///
/// # Input
///
/// Since the type is already known, the input is just the serialized data.
///
/// # Output
///
/// This deserializer will return a [`Box<dyn Reflect>`] containing the deserialized data.
///
/// For opaque types (i.e. [`ReflectKind::Opaque`]) or types that register [`ReflectDeserialize`] type data,
/// this `Box` will contain the expected type.
/// For example, deserializing an `i32` will return a `Box<i32>` (as a `Box<dyn Reflect>`).
///
/// Otherwise, this `Box` will contain the dynamic equivalent.
/// For example, a deserialized struct might return a [`Box<DynamicStruct>`]
/// and a deserialized `Vec` might return a [`Box<DynamicList>`].
///
/// This means that if the actual type is needed, these dynamic representations will need to
/// be converted to the concrete type using [`FromReflect`] or [`ReflectFromReflect`].
///
/// If you want to override deserialization for a specific [`TypeRegistration`],
/// you can pass in a reference to a [`ReflectDeserializerProcessor`] which will
/// take priority over all other deserialization methods - see [`with_processor`].
///
/// # Example
///
/// ```
/// # use core::any::TypeId;
/// # use serde::de::DeserializeSeed;
/// # use bevy_reflect::prelude::*;
/// # use bevy_reflect::{DynamicStruct, TypeRegistry, serde::TypedReflectDeserializer};
/// #[derive(Reflect, PartialEq, Debug)]
/// struct MyStruct {
/// value: i32
/// }
///
/// let mut registry = TypeRegistry::default();
/// registry.register::<MyStruct>();
///
/// let input = r#"(
/// value: 123
/// )"#;
///
/// let registration = registry.get(TypeId::of::<MyStruct>()).unwrap();
///
/// let mut deserializer = ron::Deserializer::from_str(input).unwrap();
/// let reflect_deserializer = TypedReflectDeserializer::new(registration, ®istry);
///
/// let output: Box<dyn PartialReflect> = reflect_deserializer.deserialize(&mut deserializer).unwrap();
///
/// // Since `MyStruct` is not an opaque type and does not register `ReflectDeserialize`,
/// // we know that its deserialized value will be a `DynamicStruct`,
/// // although it will represent `MyStruct`.
/// assert!(output.as_partial_reflect().represents::<MyStruct>());
///
/// // We can convert back to `MyStruct` using `FromReflect`.
/// let value: MyStruct = <MyStruct as FromReflect>::from_reflect(output.as_partial_reflect()).unwrap();
/// assert_eq!(value, MyStruct { value: 123 });
///
/// // We can also do this dynamically with `ReflectFromReflect`.
/// let type_id = output.get_represented_type_info().unwrap().type_id();
/// let reflect_from_reflect = registry.get_type_data::<ReflectFromReflect>(type_id).unwrap();
/// let value: Box<dyn Reflect> = reflect_from_reflect.from_reflect(output.as_partial_reflect()).unwrap();
/// assert!(value.is::<MyStruct>());
/// assert_eq!(value.take::<MyStruct>().unwrap(), MyStruct { value: 123 });
/// ```
///
/// [`TypedReflectSerializer`]: crate::serde::TypedReflectSerializer
/// [`Box<dyn Reflect>`]: crate::Reflect
/// [`ReflectKind::Opaque`]: crate::ReflectKind::Opaque
/// [`ReflectDeserialize`]: crate::ReflectDeserialize
/// [`Box<DynamicStruct>`]: crate::DynamicStruct
/// [`Box<DynamicList>`]: crate::DynamicList
/// [`FromReflect`]: crate::FromReflect
/// [`ReflectFromReflect`]: crate::ReflectFromReflect
/// [`with_processor`]: Self::with_processor
pub struct TypedReflectDeserializer<'a, P: ReflectDeserializerProcessor = ()> {
registration: &'a TypeRegistration,
registry: &'a TypeRegistry,
processor: Option<&'a mut P>,
}
impl<'a> TypedReflectDeserializer<'a, ()> {
/// Creates a typed deserializer with no processor.
///
/// If you want to add custom logic for deserializing certain types, use
/// [`with_processor`].
///
/// [`with_processor`]: Self::with_processor
pub fn new(registration: &'a TypeRegistration, registry: &'a TypeRegistry) -> Self {
#[cfg(feature = "debug_stack")]
TYPE_INFO_STACK.set(crate::type_info_stack::TypeInfoStack::new());
Self {
registration,
registry,
processor: None,
}
}
/// Creates a new [`TypedReflectDeserializer`] for the given type `T`
/// without a processor.
///
/// # Panics
///
/// Panics if `T` is not registered in the given [`TypeRegistry`].
pub fn of<T: TypePath>(registry: &'a TypeRegistry) -> Self {
let registration = registry
.get(core::any::TypeId::of::<T>())
.unwrap_or_else(|| panic!("no registration found for type `{}`", T::type_path()));
Self {
registration,
registry,
processor: None,
}
}
}
impl<'a, P: ReflectDeserializerProcessor> TypedReflectDeserializer<'a, P> {
/// Creates a typed deserializer with a processor.
///
/// If you do not need any custom logic for handling certain types, use
/// [`new`].
///
/// [`new`]: Self::new
pub fn with_processor(
registration: &'a TypeRegistration,
registry: &'a TypeRegistry,
processor: &'a mut P,
) -> Self {
#[cfg(feature = "debug_stack")]
TYPE_INFO_STACK.set(crate::type_info_stack::TypeInfoStack::new());
Self {
registration,
registry,
processor: Some(processor),
}
}
/// An internal constructor for creating a deserializer without resetting the type info stack.
pub(super) fn new_internal(
registration: &'a TypeRegistration,
registry: &'a TypeRegistry,
processor: Option<&'a mut P>,
) -> Self {
Self {
registration,
registry,
processor,
}
}
}
impl<'de, P: ReflectDeserializerProcessor> DeserializeSeed<'de>
for TypedReflectDeserializer<'_, P>
{
type Value = Box<dyn PartialReflect>;
fn deserialize<D>(mut self, deserializer: D) -> Result<Self::Value, D::Error>
where
D: serde::Deserializer<'de>,
{
let deserialize_internal = || -> Result<Self::Value, D::Error> {
// First, check if our processor wants to deserialize this type
// This takes priority over any other deserialization operations
let deserializer = if let Some(processor) = self.processor.as_deref_mut() {
match processor.try_deserialize(self.registration, self.registry, deserializer) {
Ok(Ok(value)) => {
return Ok(value);
}
Err(err) => {
return Err(make_custom_error(err));
}
Ok(Err(deserializer)) => deserializer,
}
} else {
deserializer
};
let type_path = self.registration.type_info().type_path();
// Handle both Value case and types that have a custom `ReflectDeserialize`
if let Some(deserialize_reflect) = self.registration.data::<ReflectDeserialize>() {
let value = deserialize_reflect.deserialize(deserializer)?;
return Ok(value.into_partial_reflect());
}
if let Some(deserialize_reflect) =
self.registration.data::<ReflectDeserializeWithRegistry>()
{
let value = deserialize_reflect.deserialize(deserializer, self.registry)?;
return Ok(value);
}
let dynamic_value: Box<dyn PartialReflect> = match self.registration.type_info() {
TypeInfo::Struct(struct_info) => {
let mut dynamic_struct = deserializer.deserialize_struct(
struct_info.type_path_table().ident().unwrap(),
struct_info.field_names(),
StructVisitor {
struct_info,
registration: self.registration,
registry: self.registry,
processor: self.processor,
},
)?;
dynamic_struct.set_represented_type(Some(self.registration.type_info()));
Box::new(dynamic_struct)
}
TypeInfo::TupleStruct(tuple_struct_info) => {
let mut dynamic_tuple_struct = if tuple_struct_info.field_len() == 1
&& self.registration.data::<SerializationData>().is_none()
{
deserializer.deserialize_newtype_struct(
tuple_struct_info.type_path_table().ident().unwrap(),
TupleStructVisitor {
tuple_struct_info,
registration: self.registration,
registry: self.registry,
processor: self.processor,
},
)?
} else {
deserializer.deserialize_tuple_struct(
tuple_struct_info.type_path_table().ident().unwrap(),
tuple_struct_info.field_len(),
TupleStructVisitor {
tuple_struct_info,
registration: self.registration,
registry: self.registry,
processor: self.processor,
},
)?
};
dynamic_tuple_struct.set_represented_type(Some(self.registration.type_info()));
Box::new(dynamic_tuple_struct)
}
TypeInfo::List(list_info) => {
let mut dynamic_list = deserializer.deserialize_seq(ListVisitor {
list_info,
registry: self.registry,
processor: self.processor,
})?;
dynamic_list.set_represented_type(Some(self.registration.type_info()));
Box::new(dynamic_list)
}
TypeInfo::Array(array_info) => {
let mut dynamic_array = deserializer.deserialize_tuple(
array_info.capacity(),
ArrayVisitor {
array_info,
registry: self.registry,
processor: self.processor,
},
)?;
dynamic_array.set_represented_type(Some(self.registration.type_info()));
Box::new(dynamic_array)
}
TypeInfo::Map(map_info) => {
let mut dynamic_map = deserializer.deserialize_map(MapVisitor {
map_info,
registry: self.registry,
processor: self.processor,
})?;
dynamic_map.set_represented_type(Some(self.registration.type_info()));
Box::new(dynamic_map)
}
TypeInfo::Set(set_info) => {
let mut dynamic_set = deserializer.deserialize_seq(SetVisitor {
set_info,
registry: self.registry,
processor: self.processor,
})?;
dynamic_set.set_represented_type(Some(self.registration.type_info()));
Box::new(dynamic_set)
}
TypeInfo::Tuple(tuple_info) => {
let mut dynamic_tuple = deserializer.deserialize_tuple(
tuple_info.field_len(),
TupleVisitor {
tuple_info,
registration: self.registration,
registry: self.registry,
processor: self.processor,
},
)?;
dynamic_tuple.set_represented_type(Some(self.registration.type_info()));
Box::new(dynamic_tuple)
}
TypeInfo::Enum(enum_info) => {
let mut dynamic_enum = if enum_info.type_path_table().module_path()
== Some("core::option")
&& enum_info.type_path_table().ident() == Some("Option")
{
deserializer.deserialize_option(OptionVisitor {
enum_info,
registry: self.registry,
processor: self.processor,
})?
} else {
deserializer.deserialize_enum(
enum_info.type_path_table().ident().unwrap(),
enum_info.variant_names(),
EnumVisitor {
enum_info,
registration: self.registration,
registry: self.registry,
processor: self.processor,
},
)?
};
dynamic_enum.set_represented_type(Some(self.registration.type_info()));
Box::new(dynamic_enum)
}
TypeInfo::Opaque(_) => {
// This case should already be handled
return Err(make_custom_error(format_args!(
"type `{type_path}` did not register the `ReflectDeserialize` type data. For certain types, this may need to be registered manually using `register_type_data`",
)));
}
};
// Try to produce a concrete instance of the type to deserialize by using the reflected `FromReflect`.
if let Some(from_reflect) = self.registration.data::<ReflectFromReflect>()
&& let Some(value) = from_reflect.from_reflect(&*dynamic_value)
{
return Ok(value);
}
Ok(dynamic_value)
};
#[cfg(feature = "debug_stack")]
TYPE_INFO_STACK.with_borrow_mut(|stack| stack.push(self.registration.type_info()));
let output = deserialize_internal();
#[cfg(feature = "debug_stack")]
TYPE_INFO_STACK.with_borrow_mut(crate::type_info_stack::TypeInfoStack::pop);
output
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/serde/de/registration_utils.rs | crates/bevy_reflect/src/serde/de/registration_utils.rs | use crate::{serde::de::error_utils::make_custom_error, Type, TypeRegistration, TypeRegistry};
use serde::de::Error;
/// Attempts to find the [`TypeRegistration`] for a given [type].
///
/// [type]: Type
pub(super) fn try_get_registration<E: Error>(
ty: Type,
registry: &TypeRegistry,
) -> Result<&TypeRegistration, E> {
let registration = registry.get(ty.id()).ok_or_else(|| {
make_custom_error(format_args!("no registration found for type `{ty:?}`"))
})?;
Ok(registration)
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/serde/de/maps.rs | crates/bevy_reflect/src/serde/de/maps.rs | use crate::{
serde::{de::registration_utils::try_get_registration, TypedReflectDeserializer},
DynamicMap, Map, MapInfo, TypeRegistry,
};
use core::{fmt, fmt::Formatter};
use serde::de::{MapAccess, Visitor};
use super::ReflectDeserializerProcessor;
/// A [`Visitor`] for deserializing [`Map`] values.
///
/// [`Map`]: crate::Map
pub(super) struct MapVisitor<'a, P> {
pub map_info: &'static MapInfo,
pub registry: &'a TypeRegistry,
pub processor: Option<&'a mut P>,
}
impl<'de, P: ReflectDeserializerProcessor> Visitor<'de> for MapVisitor<'_, P> {
type Value = DynamicMap;
fn expecting(&self, formatter: &mut Formatter) -> fmt::Result {
formatter.write_str("reflected map value")
}
fn visit_map<V>(mut self, mut map: V) -> Result<Self::Value, V::Error>
where
V: MapAccess<'de>,
{
let mut dynamic_map = DynamicMap::default();
let key_registration = try_get_registration(self.map_info.key_ty(), self.registry)?;
let value_registration = try_get_registration(self.map_info.value_ty(), self.registry)?;
while let Some(key) = map.next_key_seed(TypedReflectDeserializer::new_internal(
key_registration,
self.registry,
self.processor.as_deref_mut(),
))? {
let value = map.next_value_seed(TypedReflectDeserializer::new_internal(
value_registration,
self.registry,
self.processor.as_deref_mut(),
))?;
dynamic_map.insert_boxed(key, value);
}
Ok(dynamic_map)
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/serde/de/sets.rs | crates/bevy_reflect/src/serde/de/sets.rs | use crate::{
serde::{de::registration_utils::try_get_registration, TypedReflectDeserializer},
DynamicSet, Set, SetInfo, TypeRegistry,
};
use core::{fmt, fmt::Formatter};
use serde::de::{SeqAccess, Visitor};
use super::ReflectDeserializerProcessor;
/// A [`Visitor`] for deserializing [`Set`] values.
///
/// [`Set`]: crate::Set
pub(super) struct SetVisitor<'a, P> {
pub set_info: &'static SetInfo,
pub registry: &'a TypeRegistry,
pub processor: Option<&'a mut P>,
}
impl<'de, P: ReflectDeserializerProcessor> Visitor<'de> for SetVisitor<'_, P> {
type Value = DynamicSet;
fn expecting(&self, formatter: &mut Formatter) -> fmt::Result {
formatter.write_str("reflected set value")
}
fn visit_seq<V>(mut self, mut set: V) -> Result<Self::Value, V::Error>
where
V: SeqAccess<'de>,
{
let mut dynamic_set = DynamicSet::default();
let value_registration = try_get_registration(self.set_info.value_ty(), self.registry)?;
while let Some(value) = set.next_element_seed(TypedReflectDeserializer::new_internal(
value_registration,
self.registry,
self.processor.as_deref_mut(),
))? {
dynamic_set.insert_boxed(value);
}
Ok(dynamic_set)
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/serde/ser/serialize_with_registry.rs | crates/bevy_reflect/src/serde/ser/serialize_with_registry.rs | use crate::{FromType, Reflect, TypeRegistry};
use alloc::boxed::Box;
use serde::{Serialize, Serializer};
/// Trait used to provide finer control when serializing a reflected type with one of
/// the reflection serializers.
///
/// This trait is the reflection equivalent of `serde`'s [`Serialize`] trait.
/// The main difference is that this trait provides access to the [`TypeRegistry`],
/// which means that we can use the registry and all its stored type information
/// to serialize our type.
///
/// This can be useful when writing a custom reflection serializer where we may
/// want to handle parts of the serialization process, but temporarily pass control
/// to the standard reflection serializer for other parts.
///
/// For the deserialization equivalent of this trait, see [`DeserializeWithRegistry`].
///
/// # Rationale
///
/// Without this trait and its associated [type data], such a serializer would have to
/// write out all of the serialization logic itself, possibly including
/// unnecessary code duplication and trivial implementations.
///
/// This is because a normal [`Serialize`] implementation has no knowledge of the
/// [`TypeRegistry`] and therefore cannot create a reflection-based serializer for
/// nested items.
///
/// # Implementors
///
/// In order for this to work with the reflection serializers like [`TypedReflectSerializer`]
/// and [`ReflectSerializer`], implementors should be sure to register the
/// [`ReflectSerializeWithRegistry`] type data.
/// This can be done [via the registry] or by adding `#[reflect(SerializeWithRegistry)]` to
/// the type definition.
///
/// [`DeserializeWithRegistry`]: crate::serde::DeserializeWithRegistry
/// [type data]: ReflectSerializeWithRegistry
/// [`TypedReflectSerializer`]: crate::serde::TypedReflectSerializer
/// [`ReflectSerializer`]: crate::serde::ReflectSerializer
/// [via the registry]: TypeRegistry::register_type_data
pub trait SerializeWithRegistry {
/// Serialize this value using the given [Serializer] and [`TypeRegistry`].
///
/// [`Serializer`]: ::serde::Serializer
fn serialize<S>(&self, serializer: S, registry: &TypeRegistry) -> Result<S::Ok, S::Error>
where
S: Serializer;
}
/// Type data used to serialize a [`Reflect`] type with a custom [`SerializeWithRegistry`] implementation.
#[derive(Clone)]
pub struct ReflectSerializeWithRegistry {
serialize: for<'a> fn(
value: &'a dyn Reflect,
registry: &'a TypeRegistry,
) -> Box<dyn erased_serde::Serialize + 'a>,
}
impl ReflectSerializeWithRegistry {
/// Serialize a [`Reflect`] type with this type data's custom [`SerializeWithRegistry`] implementation.
pub fn serialize<S>(
&self,
value: &dyn Reflect,
serializer: S,
registry: &TypeRegistry,
) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
((self.serialize)(value, registry)).serialize(serializer)
}
}
impl<T: Reflect + SerializeWithRegistry> FromType<T> for ReflectSerializeWithRegistry {
fn from_type() -> Self {
Self {
serialize: |value: &dyn Reflect, registry| {
let value = value.downcast_ref::<T>().unwrap_or_else(|| {
panic!(
"Expected value to be of type {} but received {}",
core::any::type_name::<T>(),
value.reflect_type_path()
)
});
Box::new(SerializableWithRegistry { value, registry })
},
}
}
}
struct SerializableWithRegistry<'a, T: SerializeWithRegistry> {
value: &'a T,
registry: &'a TypeRegistry,
}
impl<'a, T: SerializeWithRegistry> Serialize for SerializableWithRegistry<'a, T> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
self.value.serialize(serializer, self.registry)
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/serde/ser/arrays.rs | crates/bevy_reflect/src/serde/ser/arrays.rs | use crate::{serde::TypedReflectSerializer, Array, TypeRegistry};
use serde::{ser::SerializeTuple, Serialize};
use super::ReflectSerializerProcessor;
/// A serializer for [`Array`] values.
pub(super) struct ArraySerializer<'a, P> {
pub array: &'a dyn Array,
pub registry: &'a TypeRegistry,
pub processor: Option<&'a P>,
}
impl<P: ReflectSerializerProcessor> Serialize for ArraySerializer<'_, P> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
let mut state = serializer.serialize_tuple(self.array.len())?;
for value in self.array.iter() {
state.serialize_element(&TypedReflectSerializer::new_internal(
value,
self.registry,
self.processor,
))?;
}
state.end()
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/serde/ser/serializer.rs | crates/bevy_reflect/src/serde/ser/serializer.rs | #[cfg(feature = "debug_stack")]
use crate::serde::ser::error_utils::TYPE_INFO_STACK;
use crate::{
serde::ser::{
arrays::ArraySerializer, custom_serialization::try_custom_serialize, enums::EnumSerializer,
error_utils::make_custom_error, lists::ListSerializer, maps::MapSerializer,
sets::SetSerializer, structs::StructSerializer, tuple_structs::TupleStructSerializer,
tuples::TupleSerializer,
},
PartialReflect, ReflectRef, TypeRegistry,
};
use serde::{ser::SerializeMap, Serialize, Serializer};
use super::ReflectSerializerProcessor;
/// A general purpose serializer for reflected types.
///
/// This is the serializer counterpart to [`ReflectDeserializer`].
///
/// See [`TypedReflectSerializer`] for a serializer that serializes a known type.
///
/// # Output
///
/// This serializer will output a map with a single entry,
/// where the key is the _full_ [type path] of the reflected type
/// and the value is the serialized data.
///
/// If you want to override serialization for specific values, you can pass in
/// a reference to a [`ReflectSerializerProcessor`] which will take priority
/// over all other serialization methods - see [`with_processor`].
///
/// # Example
///
/// ```
/// # use bevy_reflect::prelude::*;
/// # use bevy_reflect::{TypeRegistry, serde::ReflectSerializer};
/// #[derive(Reflect, PartialEq, Debug)]
/// #[type_path = "my_crate"]
/// struct MyStruct {
/// value: i32
/// }
///
/// let mut registry = TypeRegistry::default();
/// registry.register::<MyStruct>();
///
/// let input = MyStruct { value: 123 };
///
/// let reflect_serializer = ReflectSerializer::new(&input, ®istry);
/// let output = ron::to_string(&reflect_serializer).unwrap();
///
/// assert_eq!(output, r#"{"my_crate::MyStruct":(value:123)}"#);
/// ```
///
/// [`ReflectDeserializer`]: crate::serde::ReflectDeserializer
/// [type path]: crate::TypePath::type_path
/// [`with_processor`]: Self::with_processor
pub struct ReflectSerializer<'a, P = ()> {
value: &'a dyn PartialReflect,
registry: &'a TypeRegistry,
processor: Option<&'a P>,
}
impl<'a> ReflectSerializer<'a, ()> {
/// Creates a serializer with no processor.
///
/// If you want to add custom logic for serializing certain values, use
/// [`with_processor`].
///
/// [`with_processor`]: Self::with_processor
pub fn new(value: &'a dyn PartialReflect, registry: &'a TypeRegistry) -> Self {
Self {
value,
registry,
processor: None,
}
}
}
impl<'a, P: ReflectSerializerProcessor> ReflectSerializer<'a, P> {
/// Creates a serializer with a processor.
///
/// If you do not need any custom logic for handling certain values, use
/// [`new`].
///
/// [`new`]: Self::new
pub fn with_processor(
value: &'a dyn PartialReflect,
registry: &'a TypeRegistry,
processor: &'a P,
) -> Self {
Self {
value,
registry,
processor: Some(processor),
}
}
}
impl<P: ReflectSerializerProcessor> Serialize for ReflectSerializer<'_, P> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut state = serializer.serialize_map(Some(1))?;
state.serialize_entry(
self.value
.get_represented_type_info()
.ok_or_else(|| {
if self.value.is_dynamic() {
make_custom_error(format_args!(
"cannot serialize dynamic value without represented type: `{}`",
self.value.reflect_type_path()
))
} else {
make_custom_error(format_args!(
"cannot get type info for `{}`",
self.value.reflect_type_path()
))
}
})?
.type_path(),
&TypedReflectSerializer::new_internal(self.value, self.registry, self.processor),
)?;
state.end()
}
}
/// A serializer for reflected types whose type will be known during deserialization.
///
/// This is the serializer counterpart to [`TypedReflectDeserializer`].
///
/// See [`ReflectSerializer`] for a serializer that serializes an unknown type.
///
/// # Output
///
/// Since the type is expected to be known during deserialization,
/// this serializer will not output any additional type information,
/// such as the [type path].
///
/// Instead, it will output just the serialized data.
///
/// If you want to override serialization for specific values, you can pass in
/// a reference to a [`ReflectSerializerProcessor`] which will take priority
/// over all other serialization methods - see [`with_processor`].
///
/// # Example
///
/// ```
/// # use bevy_reflect::prelude::*;
/// # use bevy_reflect::{TypeRegistry, serde::TypedReflectSerializer};
/// #[derive(Reflect, PartialEq, Debug)]
/// #[type_path = "my_crate"]
/// struct MyStruct {
/// value: i32
/// }
///
/// let mut registry = TypeRegistry::default();
/// registry.register::<MyStruct>();
///
/// let input = MyStruct { value: 123 };
///
/// let reflect_serializer = TypedReflectSerializer::new(&input, ®istry);
/// let output = ron::to_string(&reflect_serializer).unwrap();
///
/// assert_eq!(output, r#"(value:123)"#);
/// ```
///
/// [`TypedReflectDeserializer`]: crate::serde::TypedReflectDeserializer
/// [type path]: crate::TypePath::type_path
/// [`with_processor`]: Self::with_processor
pub struct TypedReflectSerializer<'a, P = ()> {
value: &'a dyn PartialReflect,
registry: &'a TypeRegistry,
processor: Option<&'a P>,
}
impl<'a> TypedReflectSerializer<'a, ()> {
/// Creates a serializer with no processor.
///
/// If you want to add custom logic for serializing certain values, use
/// [`with_processor`].
///
/// [`with_processor`]: Self::with_processor
pub fn new(value: &'a dyn PartialReflect, registry: &'a TypeRegistry) -> Self {
#[cfg(feature = "debug_stack")]
TYPE_INFO_STACK.set(crate::type_info_stack::TypeInfoStack::new());
Self {
value,
registry,
processor: None,
}
}
}
impl<'a, P> TypedReflectSerializer<'a, P> {
/// Creates a serializer with a processor.
///
/// If you do not need any custom logic for handling certain values, use
/// [`new`].
///
/// [`new`]: Self::new
pub fn with_processor(
value: &'a dyn PartialReflect,
registry: &'a TypeRegistry,
processor: &'a P,
) -> Self {
#[cfg(feature = "debug_stack")]
TYPE_INFO_STACK.set(crate::type_info_stack::TypeInfoStack::new());
Self {
value,
registry,
processor: Some(processor),
}
}
/// An internal constructor for creating a serializer without resetting the type info stack.
pub(super) fn new_internal(
value: &'a dyn PartialReflect,
registry: &'a TypeRegistry,
processor: Option<&'a P>,
) -> Self {
Self {
value,
registry,
processor,
}
}
}
impl<P: ReflectSerializerProcessor> Serialize for TypedReflectSerializer<'_, P> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
#[cfg(feature = "debug_stack")]
{
if let Some(info) = self.value.get_represented_type_info() {
TYPE_INFO_STACK.with_borrow_mut(|stack| stack.push(info));
}
}
// First, check if our processor wants to serialize this type
// This takes priority over any other serialization operations
let serializer = if let Some(processor) = self.processor {
match processor.try_serialize(self.value, self.registry, serializer) {
Ok(Ok(value)) => {
return Ok(value);
}
Err(err) => {
return Err(make_custom_error(err));
}
Ok(Err(serializer)) => serializer,
}
} else {
serializer
};
// Handle both Value case and types that have a custom `Serialize`
let (serializer, error) = match try_custom_serialize(self.value, self.registry, serializer)
{
Ok(result) => return result,
Err(value) => value,
};
let output = match self.value.reflect_ref() {
ReflectRef::Struct(struct_value) => StructSerializer {
struct_value,
registry: self.registry,
processor: self.processor,
}
.serialize(serializer),
ReflectRef::TupleStruct(tuple_struct) => TupleStructSerializer {
tuple_struct,
registry: self.registry,
processor: self.processor,
}
.serialize(serializer),
ReflectRef::Tuple(tuple) => TupleSerializer {
tuple,
registry: self.registry,
processor: self.processor,
}
.serialize(serializer),
ReflectRef::List(list) => ListSerializer {
list,
registry: self.registry,
processor: self.processor,
}
.serialize(serializer),
ReflectRef::Array(array) => ArraySerializer {
array,
registry: self.registry,
processor: self.processor,
}
.serialize(serializer),
ReflectRef::Map(map) => MapSerializer {
map,
registry: self.registry,
processor: self.processor,
}
.serialize(serializer),
ReflectRef::Set(set) => SetSerializer {
set,
registry: self.registry,
processor: self.processor,
}
.serialize(serializer),
ReflectRef::Enum(enum_value) => EnumSerializer {
enum_value,
registry: self.registry,
processor: self.processor,
}
.serialize(serializer),
#[cfg(feature = "functions")]
ReflectRef::Function(_) => Err(make_custom_error("functions cannot be serialized")),
ReflectRef::Opaque(_) => Err(error),
};
#[cfg(feature = "debug_stack")]
TYPE_INFO_STACK.with_borrow_mut(crate::type_info_stack::TypeInfoStack::pop);
output
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/serde/ser/tuple_structs.rs | crates/bevy_reflect/src/serde/ser/tuple_structs.rs | use crate::{
serde::{ser::error_utils::make_custom_error, SerializationData, TypedReflectSerializer},
TupleStruct, TypeInfo, TypeRegistry,
};
use serde::{ser::SerializeTupleStruct, Serialize};
use super::ReflectSerializerProcessor;
/// A serializer for [`TupleStruct`] values.
pub(super) struct TupleStructSerializer<'a, P> {
pub tuple_struct: &'a dyn TupleStruct,
pub registry: &'a TypeRegistry,
pub processor: Option<&'a P>,
}
impl<P: ReflectSerializerProcessor> Serialize for TupleStructSerializer<'_, P> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
let type_info = self
.tuple_struct
.get_represented_type_info()
.ok_or_else(|| {
make_custom_error(format_args!(
"cannot get type info for `{}`",
self.tuple_struct.reflect_type_path()
))
})?;
let tuple_struct_info = match type_info {
TypeInfo::TupleStruct(tuple_struct_info) => tuple_struct_info,
info => {
return Err(make_custom_error(format_args!(
"expected tuple struct type but received {info:?}"
)));
}
};
let serialization_data = self
.registry
.get(type_info.type_id())
.and_then(|registration| registration.data::<SerializationData>());
let ignored_len = serialization_data.map(SerializationData::len).unwrap_or(0);
if self.tuple_struct.field_len() == 1 && serialization_data.is_none() {
let field = self.tuple_struct.field(0).unwrap();
return serializer.serialize_newtype_struct(
tuple_struct_info.type_path_table().ident().unwrap(),
&TypedReflectSerializer::new_internal(field, self.registry, self.processor),
);
}
let mut state = serializer.serialize_tuple_struct(
tuple_struct_info.type_path_table().ident().unwrap(),
self.tuple_struct.field_len() - ignored_len,
)?;
for (index, value) in self.tuple_struct.iter_fields().enumerate() {
if serialization_data.is_some_and(|data| data.is_field_skipped(index)) {
continue;
}
state.serialize_field(&TypedReflectSerializer::new_internal(
value,
self.registry,
self.processor,
))?;
}
state.end()
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/serde/ser/lists.rs | crates/bevy_reflect/src/serde/ser/lists.rs | use crate::{serde::TypedReflectSerializer, List, TypeRegistry};
use serde::{ser::SerializeSeq, Serialize};
use super::ReflectSerializerProcessor;
/// A serializer for [`List`] values.
pub(super) struct ListSerializer<'a, P> {
pub list: &'a dyn List,
pub registry: &'a TypeRegistry,
pub processor: Option<&'a P>,
}
impl<P: ReflectSerializerProcessor> Serialize for ListSerializer<'_, P> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
let mut state = serializer.serialize_seq(Some(self.list.len()))?;
for value in self.list.iter() {
state.serialize_element(&TypedReflectSerializer::new_internal(
value,
self.registry,
self.processor,
))?;
}
state.end()
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/serde/ser/structs.rs | crates/bevy_reflect/src/serde/ser/structs.rs | use crate::{
serde::{ser::error_utils::make_custom_error, SerializationData, TypedReflectSerializer},
Struct, TypeInfo, TypeRegistry,
};
use serde::{ser::SerializeStruct, Serialize};
use super::ReflectSerializerProcessor;
/// A serializer for [`Struct`] values.
pub(super) struct StructSerializer<'a, P> {
pub struct_value: &'a dyn Struct,
pub registry: &'a TypeRegistry,
pub processor: Option<&'a P>,
}
impl<P: ReflectSerializerProcessor> Serialize for StructSerializer<'_, P> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
let type_info = self
.struct_value
.get_represented_type_info()
.ok_or_else(|| {
make_custom_error(format_args!(
"cannot get type info for `{}`",
self.struct_value.reflect_type_path()
))
})?;
let struct_info = match type_info {
TypeInfo::Struct(struct_info) => struct_info,
info => {
return Err(make_custom_error(format_args!(
"expected struct type but received {info:?}"
)));
}
};
let serialization_data = self
.registry
.get(type_info.type_id())
.and_then(|registration| registration.data::<SerializationData>());
let ignored_len = serialization_data.map(SerializationData::len).unwrap_or(0);
let mut state = serializer.serialize_struct(
struct_info.type_path_table().ident().unwrap(),
self.struct_value.field_len() - ignored_len,
)?;
for (index, value) in self.struct_value.iter_fields().enumerate() {
if serialization_data.is_some_and(|data| data.is_field_skipped(index)) {
continue;
}
let key = struct_info.field_at(index).unwrap().name();
state.serialize_field(
key,
&TypedReflectSerializer::new_internal(value, self.registry, self.processor),
)?;
}
state.end()
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/serde/ser/processor.rs | crates/bevy_reflect/src/serde/ser/processor.rs | use serde::Serializer;
use crate::{PartialReflect, TypeRegistry};
/// Allows overriding the default serialization behavior of
/// [`ReflectSerializer`] and [`TypedReflectSerializer`] for specific values.
///
/// When serializing a reflected value, you may want to override the default
/// behavior and use your own logic for serialization. This logic may also be
/// context-dependent, and only apply for a single use of your
/// [`ReflectSerializer`]. To achieve this, you can create a processor and pass
/// it into your serializer.
///
/// Whenever the serializer attempts to serialize a value, it will first call
/// [`try_serialize`] on your processor, which may take ownership of the
/// serializer and write into the serializer (successfully or not), or return
/// ownership of the serializer back, and continue with the default logic.
///
/// The deserialization equivalent of this is [`ReflectDeserializerProcessor`].
///
/// # Compared to [`SerializeWithRegistry`]
///
/// [`SerializeWithRegistry`] allows you to define how your type will be
/// serialized by a [`TypedReflectSerializer`], given the extra context of the
/// [`TypeRegistry`]. If your type can be serialized entirely using that, then
/// you should prefer implementing that trait instead of using a processor.
///
/// However, you may need more context-dependent data which is only present in
/// the scope where you create the [`TypedReflectSerializer`]. For example, if
/// you need to use a reference to a value while serializing, then there is no
/// way to do this with [`SerializeWithRegistry`] as you can't pass that
/// reference into anywhere. This is where a processor is useful, as the
/// processor can capture local variables.
///
/// A [`ReflectSerializerProcessor`] always takes priority over a
/// [`SerializeWithRegistry`] implementation, so this is also useful for
/// overriding serialization behavior if you need to do something custom.
///
/// # Examples
///
/// Serializing a reflected value when saving an asset to disk, and replacing
/// asset handles with the handle path (if it has one):
///
/// ```
/// # use core::any::Any;
/// # use serde::Serialize;
/// # use bevy_reflect::{PartialReflect, Reflect, TypeData, TypeRegistry};
/// # use bevy_reflect::serde::{ReflectSerializer, ReflectSerializerProcessor};
/// #
/// # #[derive(Debug, Clone, Reflect)]
/// # struct Handle<T>(T);
/// # #[derive(Debug, Clone, Reflect)]
/// # struct Mesh;
/// #
/// # struct ReflectHandle;
/// # impl TypeData for ReflectHandle {
/// # fn clone_type_data(&self) -> Box<dyn TypeData> {
/// # unimplemented!()
/// # }
/// # }
/// # impl ReflectHandle {
/// # fn downcast_handle_untyped(&self, handle: &(dyn Any + 'static)) -> Option<UntypedHandle> {
/// # unimplemented!()
/// # }
/// # }
/// #
/// # #[derive(Debug, Clone)]
/// # struct UntypedHandle;
/// # impl UntypedHandle {
/// # fn path(&self) -> Option<&str> {
/// # unimplemented!()
/// # }
/// # }
/// # type AssetError = Box<dyn core::error::Error>;
/// #
/// #[derive(Debug, Clone, Reflect)]
/// struct MyAsset {
/// name: String,
/// mesh: Handle<Mesh>,
/// }
///
/// struct HandleProcessor;
///
/// impl ReflectSerializerProcessor for HandleProcessor {
/// fn try_serialize<S>(
/// &self,
/// value: &dyn PartialReflect,
/// registry: &TypeRegistry,
/// serializer: S,
/// ) -> Result<Result<S::Ok, S>, S::Error>
/// where
/// S: serde::Serializer,
/// {
/// let Some(value) = value.try_as_reflect() else {
/// // we don't have any info on this type; do the default serialization logic
/// return Ok(Err(serializer));
/// };
/// let type_id = value.reflect_type_info().type_id();
/// let Some(reflect_handle) = registry.get_type_data::<ReflectHandle>(type_id) else {
/// // this isn't a `Handle<T>`
/// return Ok(Err(serializer));
/// };
///
/// let untyped_handle = reflect_handle
/// .downcast_handle_untyped(value.as_any())
/// .unwrap();
/// if let Some(path) = untyped_handle.path() {
/// Ok(Ok(serializer.serialize_str(path)?))
/// } else {
/// Ok(Ok(serializer.serialize_unit()?))
/// }
/// }
/// }
///
/// fn save(type_registry: &TypeRegistry, asset: &MyAsset) -> Result<String, AssetError> {
/// let mut asset_string = String::new();
///
/// let processor = HandleProcessor;
/// let serializer = ReflectSerializer::with_processor(asset, type_registry, &processor);
/// let mut ron_serializer = ron::Serializer::new(&mut asset_string, None)?;
///
/// serializer.serialize(&mut ron_serializer)?;
/// Ok(asset_string)
/// }
/// ```
///
/// [`ReflectSerializer`]: crate::serde::ReflectSerializer
/// [`TypedReflectSerializer`]: crate::serde::TypedReflectSerializer
/// [`try_serialize`]: Self::try_serialize
/// [`SerializeWithRegistry`]: crate::serde::SerializeWithRegistry
/// [`ReflectDeserializerProcessor`]: crate::serde::ReflectDeserializerProcessor
pub trait ReflectSerializerProcessor {
/// Attempts to serialize the value which a [`TypedReflectSerializer`] is
/// currently looking at.
///
/// If you want to override the default serialization, return
/// `Ok(Ok(value))` with an `Ok` output from the serializer.
///
/// If you don't want to override the serialization, return ownership of
/// the serializer back via `Ok(Err(serializer))`.
///
/// You can use the type registry to read info about the type you're
/// serializing, or just try to downcast the value directly:
///
/// ```
/// # use bevy_reflect::{TypeRegistration, TypeRegistry, PartialReflect};
/// # use bevy_reflect::serde::ReflectSerializerProcessor;
/// # use core::any::TypeId;
/// struct I32AsStringProcessor;
///
/// impl ReflectSerializerProcessor for I32AsStringProcessor {
/// fn try_serialize<S>(
/// &self,
/// value: &dyn PartialReflect,
/// registry: &TypeRegistry,
/// serializer: S,
/// ) -> Result<Result<S::Ok, S>, S::Error>
/// where
/// S: serde::Serializer
/// {
/// if let Some(value) = value.try_downcast_ref::<i32>() {
/// let value_as_string = format!("{value:?}");
/// Ok(Ok(serializer.serialize_str(&value_as_string)?))
/// } else {
/// // Not an `i32`, just do the default serialization
/// Ok(Err(serializer))
/// }
/// }
/// }
/// ```
///
/// [`TypedReflectSerializer`]: crate::serde::TypedReflectSerializer
/// [`Reflect`]: crate::Reflect
fn try_serialize<S>(
&self,
value: &dyn PartialReflect,
registry: &TypeRegistry,
serializer: S,
) -> Result<Result<S::Ok, S>, S::Error>
where
S: Serializer;
}
impl ReflectSerializerProcessor for () {
fn try_serialize<S>(
&self,
_value: &dyn PartialReflect,
_registry: &TypeRegistry,
serializer: S,
) -> Result<Result<S::Ok, S>, S::Error>
where
S: Serializer,
{
Ok(Err(serializer))
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/serde/ser/enums.rs | crates/bevy_reflect/src/serde/ser/enums.rs | use crate::{
serde::{ser::error_utils::make_custom_error, TypedReflectSerializer},
Enum, TypeInfo, TypeRegistry, VariantInfo, VariantType,
};
use serde::{
ser::{SerializeStructVariant, SerializeTupleVariant},
Serialize,
};
use super::ReflectSerializerProcessor;
/// A serializer for [`Enum`] values.
pub(super) struct EnumSerializer<'a, P> {
pub enum_value: &'a dyn Enum,
pub registry: &'a TypeRegistry,
pub processor: Option<&'a P>,
}
impl<P: ReflectSerializerProcessor> Serialize for EnumSerializer<'_, P> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
let type_info = self.enum_value.get_represented_type_info().ok_or_else(|| {
make_custom_error(format_args!(
"cannot get type info for `{}`",
self.enum_value.reflect_type_path()
))
})?;
let enum_info = match type_info {
TypeInfo::Enum(enum_info) => enum_info,
info => {
return Err(make_custom_error(format_args!(
"expected enum type but received {info:?}"
)));
}
};
let enum_name = enum_info.type_path_table().ident().unwrap();
let variant_index = self.enum_value.variant_index() as u32;
let variant_info = enum_info
.variant_at(variant_index as usize)
.ok_or_else(|| {
make_custom_error(format_args!(
"variant at index `{variant_index}` does not exist",
))
})?;
let variant_name = variant_info.name();
let variant_type = self.enum_value.variant_type();
let field_len = self.enum_value.field_len();
match variant_type {
VariantType::Unit => {
if type_info.type_path_table().module_path() == Some("core::option")
&& type_info.type_path_table().ident() == Some("Option")
{
serializer.serialize_none()
} else {
serializer.serialize_unit_variant(enum_name, variant_index, variant_name)
}
}
VariantType::Struct => {
let struct_info = match variant_info {
VariantInfo::Struct(struct_info) => struct_info,
info => {
return Err(make_custom_error(format_args!(
"expected struct variant type but received {info:?}",
)));
}
};
let mut state = serializer.serialize_struct_variant(
enum_name,
variant_index,
variant_name,
field_len,
)?;
for (index, field) in self.enum_value.iter_fields().enumerate() {
let field_info = struct_info.field_at(index).unwrap();
state.serialize_field(
field_info.name(),
&TypedReflectSerializer::new_internal(
field.value(),
self.registry,
self.processor,
),
)?;
}
state.end()
}
VariantType::Tuple if field_len == 1 => {
let field = self.enum_value.field_at(0).unwrap();
if type_info.type_path_table().module_path() == Some("core::option")
&& type_info.type_path_table().ident() == Some("Option")
{
serializer.serialize_some(&TypedReflectSerializer::new_internal(
field,
self.registry,
self.processor,
))
} else {
serializer.serialize_newtype_variant(
enum_name,
variant_index,
variant_name,
&TypedReflectSerializer::new_internal(field, self.registry, self.processor),
)
}
}
VariantType::Tuple => {
let mut state = serializer.serialize_tuple_variant(
enum_name,
variant_index,
variant_name,
field_len,
)?;
for field in self.enum_value.iter_fields() {
state.serialize_field(&TypedReflectSerializer::new_internal(
field.value(),
self.registry,
self.processor,
))?;
}
state.end()
}
}
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/serde/ser/serializable.rs | crates/bevy_reflect/src/serde/ser/serializable.rs | use alloc::boxed::Box;
use core::ops::Deref;
/// A type-erased serializable value.
pub enum Serializable<'a> {
/// An owned serializable value.
Owned(Box<dyn erased_serde::Serialize + 'a>),
/// An immutable reference to a serializable value.
Borrowed(&'a dyn erased_serde::Serialize),
}
impl<'a> Deref for Serializable<'a> {
type Target = dyn erased_serde::Serialize + 'a;
fn deref(&self) -> &Self::Target {
match self {
Serializable::Borrowed(serialize) => serialize,
Serializable::Owned(serialize) => serialize,
}
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/serde/ser/custom_serialization.rs | crates/bevy_reflect/src/serde/ser/custom_serialization.rs | use crate::serde::ser::error_utils::make_custom_error;
#[cfg(feature = "debug_stack")]
use crate::serde::ser::error_utils::TYPE_INFO_STACK;
use crate::serde::ReflectSerializeWithRegistry;
use crate::{PartialReflect, ReflectSerialize, TypeRegistry};
use serde::Serializer;
/// Attempts to serialize a [`PartialReflect`] value with custom [`ReflectSerialize`]
/// or [`ReflectSerializeWithRegistry`] type data.
///
/// On success, returns the result of the serialization.
/// On failure, returns the original serializer and the error that occurred.
pub(super) fn try_custom_serialize<S: Serializer>(
value: &dyn PartialReflect,
type_registry: &TypeRegistry,
serializer: S,
) -> Result<Result<S::Ok, S::Error>, (S, S::Error)> {
let Some(value) = value.try_as_reflect() else {
return Err((
serializer,
make_custom_error(format_args!(
"type `{}` does not implement `Reflect`",
value.reflect_type_path()
)),
));
};
let info = value.reflect_type_info();
let Some(registration) = type_registry.get(info.type_id()) else {
return Err((
serializer,
make_custom_error(format_args!(
"type `{}` is not registered in the type registry",
info.type_path(),
)),
));
};
if let Some(reflect_serialize) = registration.data::<ReflectSerialize>() {
#[cfg(feature = "debug_stack")]
TYPE_INFO_STACK.with_borrow_mut(crate::type_info_stack::TypeInfoStack::pop);
Ok(reflect_serialize.serialize(value, serializer))
} else if let Some(reflect_serialize_with_registry) =
registration.data::<ReflectSerializeWithRegistry>()
{
#[cfg(feature = "debug_stack")]
TYPE_INFO_STACK.with_borrow_mut(crate::type_info_stack::TypeInfoStack::pop);
Ok(reflect_serialize_with_registry.serialize(value, serializer, type_registry))
} else {
Err((serializer, make_custom_error(format_args!(
"type `{}` did not register the `ReflectSerialize` or `ReflectSerializeWithRegistry` type data. For certain types, this may need to be registered manually using `register_type_data`",
info.type_path(),
))))
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/serde/ser/mod.rs | crates/bevy_reflect/src/serde/ser/mod.rs | pub use processor::*;
pub use serializable::*;
pub use serialize_with_registry::*;
pub use serializer::*;
mod arrays;
mod custom_serialization;
mod enums;
mod error_utils;
mod lists;
mod maps;
mod processor;
mod serializable;
mod serialize_with_registry;
mod serializer;
mod sets;
mod structs;
mod tuple_structs;
mod tuples;
#[cfg(test)]
mod tests {
use crate::{
serde::{ReflectSerializer, ReflectSerializerProcessor},
PartialReflect, Reflect, ReflectSerialize, Struct, TypeRegistry,
};
#[cfg(feature = "functions")]
use alloc::boxed::Box;
use alloc::{
string::{String, ToString},
vec,
vec::Vec,
};
use bevy_platform::collections::{HashMap, HashSet};
use core::{any::TypeId, f32::consts::PI, ops::RangeInclusive};
use ron::{extensions::Extensions, ser::PrettyConfig};
use serde::{Serialize, Serializer};
#[derive(Reflect, Debug, PartialEq)]
struct MyStruct {
primitive_value: i8,
option_value: Option<String>,
option_value_complex: Option<SomeStruct>,
tuple_value: (f32, usize),
list_value: Vec<i32>,
array_value: [i32; 5],
map_value: HashMap<u8, usize>,
set_value: HashSet<u8>,
struct_value: SomeStruct,
tuple_struct_value: SomeTupleStruct,
unit_struct: SomeUnitStruct,
unit_enum: SomeEnum,
newtype_enum: SomeEnum,
tuple_enum: SomeEnum,
struct_enum: SomeEnum,
ignored_struct: SomeIgnoredStruct,
ignored_tuple_struct: SomeIgnoredTupleStruct,
ignored_struct_variant: SomeIgnoredEnum,
ignored_tuple_variant: SomeIgnoredEnum,
custom_serialize: CustomSerialize,
}
#[derive(Reflect, Debug, PartialEq)]
struct SomeStruct {
foo: i64,
}
#[derive(Reflect, Debug, PartialEq)]
struct SomeTupleStruct(String);
#[derive(Reflect, Debug, PartialEq)]
struct SomeUnitStruct;
#[derive(Reflect, Debug, PartialEq)]
struct SomeIgnoredStruct {
#[reflect(ignore)]
ignored: i32,
}
#[derive(Reflect, Debug, PartialEq)]
struct SomeIgnoredTupleStruct(#[reflect(ignore)] i32);
#[derive(Reflect, Debug, PartialEq)]
enum SomeEnum {
Unit,
NewType(usize),
Tuple(f32, f32),
Struct { foo: String },
}
#[derive(Reflect, Debug, PartialEq)]
enum SomeIgnoredEnum {
Tuple(#[reflect(ignore)] f32, #[reflect(ignore)] f32),
Struct {
#[reflect(ignore)]
foo: String,
},
}
#[derive(Reflect, Debug, PartialEq, Serialize)]
struct SomeSerializableStruct {
foo: i64,
}
/// Implements a custom serialize using `#[reflect(Serialize)]`.
///
/// For testing purposes, this just uses the generated one from deriving Serialize.
#[derive(Reflect, Debug, PartialEq, Serialize)]
#[reflect(Serialize)]
struct CustomSerialize {
value: usize,
#[serde(rename = "renamed")]
inner_struct: SomeSerializableStruct,
}
fn get_registry() -> TypeRegistry {
let mut registry = TypeRegistry::default();
registry.register::<MyStruct>();
registry.register::<SomeStruct>();
registry.register::<SomeTupleStruct>();
registry.register::<SomeUnitStruct>();
registry.register::<SomeIgnoredStruct>();
registry.register::<SomeIgnoredTupleStruct>();
registry.register::<SomeIgnoredEnum>();
registry.register::<CustomSerialize>();
registry.register::<SomeEnum>();
registry.register::<SomeSerializableStruct>();
registry.register_type_data::<SomeSerializableStruct, ReflectSerialize>();
registry.register::<String>();
registry.register::<Option<String>>();
registry.register_type_data::<Option<String>, ReflectSerialize>();
registry
}
fn get_my_struct() -> MyStruct {
let mut map = <HashMap<_, _>>::default();
map.insert(64, 32);
let mut set = <HashSet<_>>::default();
set.insert(64);
MyStruct {
primitive_value: 123,
option_value: Some(String::from("Hello world!")),
option_value_complex: Some(SomeStruct { foo: 123 }),
tuple_value: (PI, 1337),
list_value: vec![-2, -1, 0, 1, 2],
array_value: [-2, -1, 0, 1, 2],
map_value: map,
set_value: set,
struct_value: SomeStruct { foo: 999999999 },
tuple_struct_value: SomeTupleStruct(String::from("Tuple Struct")),
unit_struct: SomeUnitStruct,
unit_enum: SomeEnum::Unit,
newtype_enum: SomeEnum::NewType(123),
tuple_enum: SomeEnum::Tuple(1.23, 3.21),
struct_enum: SomeEnum::Struct {
foo: String::from("Struct variant value"),
},
ignored_struct: SomeIgnoredStruct { ignored: 123 },
ignored_tuple_struct: SomeIgnoredTupleStruct(123),
ignored_struct_variant: SomeIgnoredEnum::Struct {
foo: String::from("Struct Variant"),
},
ignored_tuple_variant: SomeIgnoredEnum::Tuple(1.23, 3.45),
custom_serialize: CustomSerialize {
value: 100,
inner_struct: SomeSerializableStruct { foo: 101 },
},
}
}
#[test]
fn should_serialize() {
let input = get_my_struct();
let registry = get_registry();
let serializer = ReflectSerializer::new(&input, ®istry);
let config = PrettyConfig::default()
.new_line(String::from("\n"))
.indentor(String::from(" "));
let output = ron::ser::to_string_pretty(&serializer, config).unwrap();
let expected = r#"{
"bevy_reflect::serde::ser::tests::MyStruct": (
primitive_value: 123,
option_value: Some("Hello world!"),
option_value_complex: Some((
foo: 123,
)),
tuple_value: (3.1415927, 1337),
list_value: [
-2,
-1,
0,
1,
2,
],
array_value: (-2, -1, 0, 1, 2),
map_value: {
64: 32,
},
set_value: [
64,
],
struct_value: (
foo: 999999999,
),
tuple_struct_value: ("Tuple Struct"),
unit_struct: (),
unit_enum: Unit,
newtype_enum: NewType(123),
tuple_enum: Tuple(1.23, 3.21),
struct_enum: Struct(
foo: "Struct variant value",
),
ignored_struct: (),
ignored_tuple_struct: (),
ignored_struct_variant: Struct(),
ignored_tuple_variant: Tuple(),
custom_serialize: (
value: 100,
renamed: (
foo: 101,
),
),
),
}"#;
assert_eq!(expected, output);
}
#[test]
fn should_serialize_option() {
#[derive(Reflect, Debug, PartialEq)]
struct OptionTest {
none: Option<()>,
simple: Option<String>,
complex: Option<SomeStruct>,
}
let value = OptionTest {
none: None,
simple: Some(String::from("Hello world!")),
complex: Some(SomeStruct { foo: 123 }),
};
let registry = get_registry();
let serializer = ReflectSerializer::new(&value, ®istry);
// === Normal === //
let config = PrettyConfig::default()
.new_line(String::from("\n"))
.indentor(String::from(" "));
let output = ron::ser::to_string_pretty(&serializer, config).unwrap();
let expected = r#"{
"bevy_reflect::serde::ser::tests::OptionTest": (
none: None,
simple: Some("Hello world!"),
complex: Some((
foo: 123,
)),
),
}"#;
assert_eq!(expected, output);
// === Implicit Some === //
let config = PrettyConfig::default()
.new_line(String::from("\n"))
.extensions(Extensions::IMPLICIT_SOME)
.indentor(String::from(" "));
let output = ron::ser::to_string_pretty(&serializer, config).unwrap();
let expected = r#"#![enable(implicit_some)]
{
"bevy_reflect::serde::ser::tests::OptionTest": (
none: None,
simple: "Hello world!",
complex: (
foo: 123,
),
),
}"#;
assert_eq!(expected, output);
}
#[test]
fn enum_should_serialize() {
#[derive(Reflect)]
enum MyEnum {
Unit,
NewType(usize),
Tuple(f32, f32),
Struct { value: String },
}
let mut registry = get_registry();
registry.register::<MyEnum>();
let config = PrettyConfig::default().new_line(String::from("\n"));
// === Unit Variant === //
let value = MyEnum::Unit;
let serializer = ReflectSerializer::new(&value, ®istry);
let output = ron::ser::to_string_pretty(&serializer, config.clone()).unwrap();
let expected = r#"{
"bevy_reflect::serde::ser::tests::MyEnum": Unit,
}"#;
assert_eq!(expected, output);
// === NewType Variant === //
let value = MyEnum::NewType(123);
let serializer = ReflectSerializer::new(&value, ®istry);
let output = ron::ser::to_string_pretty(&serializer, config.clone()).unwrap();
let expected = r#"{
"bevy_reflect::serde::ser::tests::MyEnum": NewType(123),
}"#;
assert_eq!(expected, output);
// === Tuple Variant === //
let value = MyEnum::Tuple(1.23, 3.21);
let serializer = ReflectSerializer::new(&value, ®istry);
let output = ron::ser::to_string_pretty(&serializer, config.clone()).unwrap();
let expected = r#"{
"bevy_reflect::serde::ser::tests::MyEnum": Tuple(1.23, 3.21),
}"#;
assert_eq!(expected, output);
// === Struct Variant === //
let value = MyEnum::Struct {
value: String::from("I <3 Enums"),
};
let serializer = ReflectSerializer::new(&value, ®istry);
let output = ron::ser::to_string_pretty(&serializer, config).unwrap();
let expected = r#"{
"bevy_reflect::serde::ser::tests::MyEnum": Struct(
value: "I <3 Enums",
),
}"#;
assert_eq!(expected, output);
}
#[test]
fn should_serialize_non_self_describing_binary() {
let input = get_my_struct();
let registry = get_registry();
let serializer = ReflectSerializer::new(&input, ®istry);
let config = bincode::config::standard().with_fixed_int_encoding();
let bytes = bincode::serde::encode_to_vec(&serializer, config).unwrap();
let expected: Vec<u8> = vec![
1, 0, 0, 0, 0, 0, 0, 0, 41, 0, 0, 0, 0, 0, 0, 0, 98, 101, 118, 121, 95, 114, 101, 102,
108, 101, 99, 116, 58, 58, 115, 101, 114, 100, 101, 58, 58, 115, 101, 114, 58, 58, 116,
101, 115, 116, 115, 58, 58, 77, 121, 83, 116, 114, 117, 99, 116, 123, 1, 12, 0, 0, 0,
0, 0, 0, 0, 72, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100, 33, 1, 123, 0, 0, 0,
0, 0, 0, 0, 219, 15, 73, 64, 57, 5, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 254, 255,
255, 255, 255, 255, 255, 255, 0, 0, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 254, 255, 255, 255,
255, 255, 255, 255, 0, 0, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 64, 32,
0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 64, 255, 201, 154, 59, 0, 0, 0, 0, 12, 0,
0, 0, 0, 0, 0, 0, 84, 117, 112, 108, 101, 32, 83, 116, 114, 117, 99, 116, 0, 0, 0, 0,
1, 0, 0, 0, 123, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 164, 112, 157, 63, 164, 112, 77, 64,
3, 0, 0, 0, 20, 0, 0, 0, 0, 0, 0, 0, 83, 116, 114, 117, 99, 116, 32, 118, 97, 114, 105,
97, 110, 116, 32, 118, 97, 108, 117, 101, 1, 0, 0, 0, 0, 0, 0, 0, 100, 0, 0, 0, 0, 0,
0, 0, 101, 0, 0, 0, 0, 0, 0, 0,
];
assert_eq!(expected, bytes);
}
#[test]
fn should_serialize_self_describing_binary() {
let input = get_my_struct();
let registry = get_registry();
let serializer = ReflectSerializer::new(&input, ®istry);
let bytes: Vec<u8> = rmp_serde::to_vec(&serializer).unwrap();
let expected: Vec<u8> = vec![
129, 217, 41, 98, 101, 118, 121, 95, 114, 101, 102, 108, 101, 99, 116, 58, 58, 115,
101, 114, 100, 101, 58, 58, 115, 101, 114, 58, 58, 116, 101, 115, 116, 115, 58, 58, 77,
121, 83, 116, 114, 117, 99, 116, 220, 0, 20, 123, 172, 72, 101, 108, 108, 111, 32, 119,
111, 114, 108, 100, 33, 145, 123, 146, 202, 64, 73, 15, 219, 205, 5, 57, 149, 254, 255,
0, 1, 2, 149, 254, 255, 0, 1, 2, 129, 64, 32, 145, 64, 145, 206, 59, 154, 201, 255,
172, 84, 117, 112, 108, 101, 32, 83, 116, 114, 117, 99, 116, 144, 164, 85, 110, 105,
116, 129, 167, 78, 101, 119, 84, 121, 112, 101, 123, 129, 165, 84, 117, 112, 108, 101,
146, 202, 63, 157, 112, 164, 202, 64, 77, 112, 164, 129, 166, 83, 116, 114, 117, 99,
116, 145, 180, 83, 116, 114, 117, 99, 116, 32, 118, 97, 114, 105, 97, 110, 116, 32,
118, 97, 108, 117, 101, 144, 144, 129, 166, 83, 116, 114, 117, 99, 116, 144, 129, 165,
84, 117, 112, 108, 101, 144, 146, 100, 145, 101,
];
assert_eq!(expected, bytes);
}
#[test]
fn should_serialize_dynamic_option() {
#[derive(Default, Reflect)]
struct OtherStruct {
some: Option<SomeStruct>,
none: Option<SomeStruct>,
}
let value = OtherStruct {
some: Some(SomeStruct { foo: 999999999 }),
none: None,
};
let dynamic = value.to_dynamic_struct();
let reflect = dynamic.as_partial_reflect();
let registry = get_registry();
let serializer = ReflectSerializer::new(reflect, ®istry);
let mut buf = Vec::new();
let format = serde_json::ser::PrettyFormatter::with_indent(b" ");
let mut ser = serde_json::Serializer::with_formatter(&mut buf, format);
serializer.serialize(&mut ser).unwrap();
let output = core::str::from_utf8(&buf).unwrap();
let expected = r#"{
"bevy_reflect::serde::ser::tests::OtherStruct": {
"some": {
"foo": 999999999
},
"none": null
}
}"#;
assert_eq!(expected, output);
}
#[test]
fn should_return_error_if_missing_registration() {
let value = RangeInclusive::<f32>::new(0.0, 1.0);
let registry = TypeRegistry::new();
let serializer = ReflectSerializer::new(&value, ®istry);
let error = ron::ser::to_string(&serializer).unwrap_err();
#[cfg(feature = "debug_stack")]
assert_eq!(
error,
ron::Error::Message(
"type `core::ops::RangeInclusive<f32>` is not registered in the type registry (stack: `core::ops::RangeInclusive<f32>`)"
.to_string(),
)
);
#[cfg(not(feature = "debug_stack"))]
assert_eq!(
error,
ron::Error::Message(
"type `core::ops::RangeInclusive<f32>` is not registered in the type registry"
.to_string(),
)
);
}
#[test]
fn should_return_error_if_missing_type_data() {
let value = RangeInclusive::<f32>::new(0.0, 1.0);
let mut registry = TypeRegistry::new();
registry.register::<RangeInclusive<f32>>();
let serializer = ReflectSerializer::new(&value, ®istry);
let error = ron::ser::to_string(&serializer).unwrap_err();
#[cfg(feature = "debug_stack")]
assert_eq!(
error,
ron::Error::Message(
"type `core::ops::RangeInclusive<f32>` did not register the `ReflectSerialize` or `ReflectSerializeWithRegistry` type data. For certain types, this may need to be registered manually using `register_type_data` (stack: `core::ops::RangeInclusive<f32>`)".to_string()
)
);
#[cfg(not(feature = "debug_stack"))]
assert_eq!(
error,
ron::Error::Message(
"type `core::ops::RangeInclusive<f32>` did not register the `ReflectSerialize` type data. For certain types, this may need to be registered manually using `register_type_data`".to_string()
)
);
}
#[test]
fn should_use_processor_for_custom_serialization() {
#[derive(Reflect, Debug, PartialEq)]
struct Foo {
bar: i32,
qux: i64,
}
struct FooProcessor;
impl ReflectSerializerProcessor for FooProcessor {
fn try_serialize<S>(
&self,
value: &dyn PartialReflect,
_: &TypeRegistry,
serializer: S,
) -> Result<Result<S::Ok, S>, S::Error>
where
S: Serializer,
{
let Some(value) = value.try_as_reflect() else {
return Ok(Err(serializer));
};
let type_id = value.reflect_type_info().type_id();
if type_id == TypeId::of::<i64>() {
Ok(Ok(serializer.serialize_str("custom!")?))
} else {
Ok(Err(serializer))
}
}
}
let value = Foo { bar: 123, qux: 456 };
let mut registry = TypeRegistry::new();
registry.register::<Foo>();
let processor = FooProcessor;
let serializer = ReflectSerializer::with_processor(&value, ®istry, &processor);
let config = PrettyConfig::default().new_line(String::from("\n"));
let output = ron::ser::to_string_pretty(&serializer, config).unwrap();
let expected = r#"{
"bevy_reflect::serde::ser::tests::Foo": (
bar: 123,
qux: "custom!",
),
}"#;
assert_eq!(expected, output);
}
#[test]
fn should_use_processor_for_multiple_registrations() {
#[derive(Reflect, Debug, PartialEq)]
struct Foo {
bar: i32,
sub: SubFoo,
}
#[derive(Reflect, Debug, PartialEq)]
struct SubFoo {
val: i32,
}
struct FooProcessor;
impl ReflectSerializerProcessor for FooProcessor {
fn try_serialize<S>(
&self,
value: &dyn PartialReflect,
_: &TypeRegistry,
serializer: S,
) -> Result<Result<S::Ok, S>, S::Error>
where
S: Serializer,
{
let Some(value) = value.try_as_reflect() else {
return Ok(Err(serializer));
};
let type_id = value.reflect_type_info().type_id();
if type_id == TypeId::of::<i32>() {
Ok(Ok(serializer.serialize_str("an i32")?))
} else if type_id == TypeId::of::<SubFoo>() {
Ok(Ok(serializer.serialize_str("a SubFoo")?))
} else {
Ok(Err(serializer))
}
}
}
let value = Foo {
bar: 123,
sub: SubFoo { val: 456 },
};
let mut registry = TypeRegistry::new();
registry.register::<Foo>();
registry.register::<SubFoo>();
let processor = FooProcessor;
let serializer = ReflectSerializer::with_processor(&value, ®istry, &processor);
let config = PrettyConfig::default().new_line(String::from("\n"));
let output = ron::ser::to_string_pretty(&serializer, config).unwrap();
let expected = r#"{
"bevy_reflect::serde::ser::tests::Foo": (
bar: "an i32",
sub: "a SubFoo",
),
}"#;
assert_eq!(expected, output);
}
#[test]
fn should_propagate_processor_serialize_error() {
struct ErroringProcessor;
impl ReflectSerializerProcessor for ErroringProcessor {
fn try_serialize<S>(
&self,
value: &dyn PartialReflect,
_: &TypeRegistry,
serializer: S,
) -> Result<Result<S::Ok, S>, S::Error>
where
S: Serializer,
{
let Some(value) = value.try_as_reflect() else {
return Ok(Err(serializer));
};
let type_id = value.reflect_type_info().type_id();
if type_id == TypeId::of::<i32>() {
Err(serde::ser::Error::custom("my custom serialize error"))
} else {
Ok(Err(serializer))
}
}
}
let value = 123_i32;
let registry = TypeRegistry::new();
let processor = ErroringProcessor;
let serializer = ReflectSerializer::with_processor(&value, ®istry, &processor);
let error = ron::ser::to_string_pretty(&serializer, PrettyConfig::default()).unwrap_err();
#[cfg(feature = "debug_stack")]
assert_eq!(
error,
ron::Error::Message("my custom serialize error (stack: `i32`)".to_string())
);
#[cfg(not(feature = "debug_stack"))]
assert_eq!(
error,
ron::Error::Message("my custom serialize error".to_string())
);
}
#[cfg(feature = "functions")]
mod functions {
use super::*;
use crate::func::{DynamicFunction, IntoFunction};
use alloc::string::ToString;
#[test]
fn should_not_serialize_function() {
#[derive(Reflect)]
#[reflect(from_reflect = false)]
struct MyStruct {
func: DynamicFunction<'static>,
}
let value: Box<dyn Reflect> = Box::new(MyStruct {
func: String::new.into_function(),
});
let registry = TypeRegistry::new();
let serializer = ReflectSerializer::new(value.as_partial_reflect(), ®istry);
let error = ron::ser::to_string(&serializer).unwrap_err();
#[cfg(feature = "debug_stack")]
assert_eq!(
error,
ron::Error::Message("functions cannot be serialized (stack: `bevy_reflect::serde::ser::tests::functions::MyStruct`)".to_string())
);
#[cfg(not(feature = "debug_stack"))]
assert_eq!(
error,
ron::Error::Message("functions cannot be serialized".to_string())
);
}
}
#[cfg(feature = "debug_stack")]
mod debug_stack {
use super::*;
#[test]
fn should_report_context_in_errors() {
#[derive(Reflect)]
struct Foo {
bar: Bar,
}
#[derive(Reflect)]
struct Bar {
some_other_field: Option<u32>,
baz: Baz,
}
#[derive(Reflect)]
struct Baz {
value: Vec<RangeInclusive<f32>>,
}
let value = Foo {
bar: Bar {
some_other_field: Some(123),
baz: Baz {
value: vec![0.0..=1.0],
},
},
};
let registry = TypeRegistry::new();
let serializer = ReflectSerializer::new(&value, ®istry);
let error = ron::ser::to_string(&serializer).unwrap_err();
assert_eq!(
error,
ron::Error::Message(
"type `core::ops::RangeInclusive<f32>` is not registered in the type registry (stack: `bevy_reflect::serde::ser::tests::debug_stack::Foo` -> `bevy_reflect::serde::ser::tests::debug_stack::Bar` -> `bevy_reflect::serde::ser::tests::debug_stack::Baz` -> `alloc::vec::Vec<core::ops::RangeInclusive<f32>>` -> `core::ops::RangeInclusive<f32>`)".to_string()
)
);
}
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/serde/ser/error_utils.rs | crates/bevy_reflect/src/serde/ser/error_utils.rs | use core::fmt::Display;
use serde::ser::Error;
#[cfg(feature = "debug_stack")]
use std::thread_local;
#[cfg(feature = "debug_stack")]
thread_local! {
/// The thread-local [`TypeInfoStack`] used for debugging.
///
/// [`TypeInfoStack`]: crate::type_info_stack::TypeInfoStack
pub(super) static TYPE_INFO_STACK: core::cell::RefCell<crate::type_info_stack::TypeInfoStack> = const { core::cell::RefCell::new(
crate::type_info_stack::TypeInfoStack::new()
) };
}
/// A helper function for generating a custom serialization error message.
///
/// This function should be preferred over [`Error::custom`] as it will include
/// other useful information, such as the [type info stack].
///
/// [type info stack]: crate::type_info_stack::TypeInfoStack
pub(super) fn make_custom_error<E: Error>(msg: impl Display) -> E {
#[cfg(feature = "debug_stack")]
return TYPE_INFO_STACK
.with_borrow(|stack| E::custom(format_args!("{msg} (stack: {stack:?})")));
#[cfg(not(feature = "debug_stack"))]
return E::custom(msg);
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/serde/ser/tuples.rs | crates/bevy_reflect/src/serde/ser/tuples.rs | use crate::{serde::TypedReflectSerializer, Tuple, TypeRegistry};
use serde::{ser::SerializeTuple, Serialize};
use super::ReflectSerializerProcessor;
/// A serializer for [`Tuple`] values.
pub(super) struct TupleSerializer<'a, P> {
pub tuple: &'a dyn Tuple,
pub registry: &'a TypeRegistry,
pub processor: Option<&'a P>,
}
impl<P: ReflectSerializerProcessor> Serialize for TupleSerializer<'_, P> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
let mut state = serializer.serialize_tuple(self.tuple.field_len())?;
for value in self.tuple.iter_fields() {
state.serialize_element(&TypedReflectSerializer::new_internal(
value,
self.registry,
self.processor,
))?;
}
state.end()
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/serde/ser/maps.rs | crates/bevy_reflect/src/serde/ser/maps.rs | use crate::{serde::TypedReflectSerializer, Map, TypeRegistry};
use serde::{ser::SerializeMap, Serialize};
use super::ReflectSerializerProcessor;
/// A serializer for [`Map`] values.
pub(super) struct MapSerializer<'a, P> {
pub map: &'a dyn Map,
pub registry: &'a TypeRegistry,
pub processor: Option<&'a P>,
}
impl<P: ReflectSerializerProcessor> Serialize for MapSerializer<'_, P> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
let mut state = serializer.serialize_map(Some(self.map.len()))?;
for (key, value) in self.map.iter() {
state.serialize_entry(
&TypedReflectSerializer::new_internal(key, self.registry, self.processor),
&TypedReflectSerializer::new_internal(value, self.registry, self.processor),
)?;
}
state.end()
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/serde/ser/sets.rs | crates/bevy_reflect/src/serde/ser/sets.rs | use crate::{serde::TypedReflectSerializer, Set, TypeRegistry};
use serde::{ser::SerializeSeq, Serialize};
use super::ReflectSerializerProcessor;
/// A serializer for [`Set`] values.
pub(super) struct SetSerializer<'a, P> {
pub set: &'a dyn Set,
pub registry: &'a TypeRegistry,
pub processor: Option<&'a P>,
}
impl<P: ReflectSerializerProcessor> Serialize for SetSerializer<'_, P> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
let mut state = serializer.serialize_seq(Some(self.set.len()))?;
for value in self.set.iter() {
state.serialize_element(&TypedReflectSerializer::new_internal(
value,
self.registry,
self.processor,
))?;
}
state.end()
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/path/parse.rs | crates/bevy_reflect/src/path/parse.rs | use core::{
fmt::{self, Write},
num::ParseIntError,
str::from_utf8_unchecked,
};
use thiserror::Error;
use super::{Access, ReflectPathError};
/// An error that occurs when parsing reflect path strings.
#[derive(Debug, PartialEq, Eq, Error)]
#[error(transparent)]
pub struct ParseError<'a>(Error<'a>);
/// A parse error for a path string.
#[derive(Debug, PartialEq, Eq, Error)]
enum Error<'a> {
#[error("expected an identifier, but reached end of path string")]
NoIdent,
#[error("expected an identifier, got '{0}' instead")]
ExpectedIdent(Token<'a>),
#[error("failed to parse index as integer")]
InvalidIndex(#[from] ParseIntError),
#[error("a '[' wasn't closed, reached end of path string before finding a ']'")]
Unclosed,
#[error("a '[' wasn't closed properly, got '{0}' instead")]
BadClose(Token<'a>),
#[error("a ']' was found before an opening '['")]
CloseBeforeOpen,
}
pub(super) struct PathParser<'a> {
path: &'a str,
remaining: &'a [u8],
}
impl<'a> PathParser<'a> {
pub(super) fn new(path: &'a str) -> Self {
let remaining = path.as_bytes();
PathParser { path, remaining }
}
fn next_token(&mut self) -> Option<Token<'a>> {
let to_parse = self.remaining;
// Return with `None` if empty.
let (first_byte, remaining) = to_parse.split_first()?;
if let Some(token) = Token::symbol_from_byte(*first_byte) {
self.remaining = remaining; // NOTE: all symbols are ASCII
return Some(token);
}
// We are parsing either `0123` or `field`.
// If we do not find a subsequent token, we are at the end of the parse string.
let ident_len = to_parse.iter().position(|t| Token::SYMBOLS.contains(t));
let (ident, remaining) = to_parse.split_at(ident_len.unwrap_or(to_parse.len()));
#[expect(
unsafe_code,
reason = "We have fulfilled the Safety requirements for `from_utf8_unchecked`."
)]
// SAFETY: This relies on `self.remaining` always remaining valid UTF8:
// - self.remaining is a slice derived from self.path (valid &str)
// - The slice's end is either the same as the valid &str or
// the last byte before an ASCII utf-8 character (ie: it is a char
// boundary).
// - The slice always starts after a symbol ie: an ASCII character's boundary.
let ident = unsafe { from_utf8_unchecked(ident) };
self.remaining = remaining;
Some(Token::Ident(Ident(ident)))
}
fn next_ident(&mut self) -> Result<Ident<'a>, Error<'a>> {
match self.next_token() {
Some(Token::Ident(ident)) => Ok(ident),
Some(other) => Err(Error::ExpectedIdent(other)),
None => Err(Error::NoIdent),
}
}
fn access_following(&mut self, token: Token<'a>) -> Result<Access<'a>, Error<'a>> {
match token {
Token::Dot => Ok(self.next_ident()?.field()),
Token::Pound => self.next_ident()?.field_index(),
Token::Ident(ident) => Ok(ident.field()),
Token::CloseBracket => Err(Error::CloseBeforeOpen),
Token::OpenBracket => {
let index_ident = self.next_ident()?.list_index()?;
match self.next_token() {
Some(Token::CloseBracket) => Ok(index_ident),
Some(other) => Err(Error::BadClose(other)),
None => Err(Error::Unclosed),
}
}
}
}
fn offset(&self) -> usize {
self.path.len() - self.remaining.len()
}
}
impl<'a> Iterator for PathParser<'a> {
type Item = (Result<Access<'a>, ReflectPathError<'a>>, usize);
fn next(&mut self) -> Option<Self::Item> {
let token = self.next_token()?;
let offset = self.offset();
Some((
self.access_following(token)
.map_err(|error| ReflectPathError::ParseError {
offset,
path: self.path,
error: ParseError(error),
}),
offset,
))
}
}
#[derive(Debug, PartialEq, Eq)]
struct Ident<'a>(&'a str);
impl<'a> Ident<'a> {
fn field(self) -> Access<'a> {
let field = |_| Access::Field(self.0.into());
self.0.parse().map(Access::TupleIndex).unwrap_or_else(field)
}
fn field_index(self) -> Result<Access<'a>, Error<'a>> {
Ok(Access::FieldIndex(self.0.parse()?))
}
fn list_index(self) -> Result<Access<'a>, Error<'a>> {
Ok(Access::ListIndex(self.0.parse()?))
}
}
// NOTE: We use repr(u8) so that the `match byte` in `Token::symbol_from_byte`
// becomes a "check `byte` is one of SYMBOLS and forward its value" this makes
// the optimizer happy, and shaves off a few cycles.
#[derive(Debug, PartialEq, Eq)]
#[repr(u8)]
enum Token<'a> {
Dot = b'.',
Pound = b'#',
OpenBracket = b'[',
CloseBracket = b']',
Ident(Ident<'a>),
}
impl fmt::Display for Token<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Token::Dot => f.write_char('.'),
Token::Pound => f.write_char('#'),
Token::OpenBracket => f.write_char('['),
Token::CloseBracket => f.write_char(']'),
Token::Ident(ident) => f.write_str(ident.0),
}
}
}
impl<'a> Token<'a> {
const SYMBOLS: &'static [u8] = b".#[]";
fn symbol_from_byte(byte: u8) -> Option<Self> {
match byte {
b'.' => Some(Self::Dot),
b'#' => Some(Self::Pound),
b'[' => Some(Self::OpenBracket),
b']' => Some(Self::CloseBracket),
_ => None,
}
}
}
#[cfg(test)]
mod test {
use super::*;
use crate::path::ParsedPath;
#[test]
fn parse_invalid() {
assert_eq!(
ParsedPath::parse_static("x.."),
Err(ReflectPathError::ParseError {
error: ParseError(Error::ExpectedIdent(Token::Dot)),
offset: 2,
path: "x..",
}),
);
assert!(matches!(
ParsedPath::parse_static("y[badindex]"),
Err(ReflectPathError::ParseError {
error: ParseError(Error::InvalidIndex(_)),
offset: 2,
path: "y[badindex]",
}),
));
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/crates/bevy_reflect/src/path/error.rs | crates/bevy_reflect/src/path/error.rs | use core::fmt;
use super::Access;
use crate::{ReflectKind, VariantType};
/// The kind of [`AccessError`], along with some kind-specific information.
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum AccessErrorKind {
/// An error that occurs when a certain type doesn't
/// contain the value referenced by the [`Access`].
MissingField(ReflectKind),
/// An error that occurs when using an [`Access`] on the wrong type.
/// (i.e. a [`ListIndex`](Access::ListIndex) on a struct, or a [`TupleIndex`](Access::TupleIndex) on a list)
IncompatibleTypes {
/// The [`ReflectKind`] that was expected based on the [`Access`].
expected: ReflectKind,
/// The actual [`ReflectKind`] that was found.
actual: ReflectKind,
},
/// An error that occurs when using an [`Access`] on the wrong enum variant.
/// (i.e. a [`ListIndex`](Access::ListIndex) on a struct variant, or a [`TupleIndex`](Access::TupleIndex) on a unit variant)
IncompatibleEnumVariantTypes {
/// The [`VariantType`] that was expected based on the [`Access`].
expected: VariantType,
/// The actual [`VariantType`] that was found.
actual: VariantType,
},
}
impl AccessErrorKind {
pub(super) fn with_access(self, access: Access, offset: Option<usize>) -> AccessError {
AccessError {
kind: self,
access,
offset,
}
}
}
/// An error originating from an [`Access`] of an element within a type.
///
/// Use the `Display` impl of this type to get information on the error.
///
/// Some sample messages:
///
/// ```text
/// Error accessing element with `.alpha` access (offset 14): The struct accessed doesn't have an "alpha" field
/// Error accessing element with '[0]' access: Expected index access to access a list, found a struct instead.
/// Error accessing element with '.4' access: Expected variant index access to access a Tuple variant, found a Unit variant instead.
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AccessError<'a> {
pub(super) kind: AccessErrorKind,
pub(super) access: Access<'a>,
pub(super) offset: Option<usize>,
}
impl<'a> AccessError<'a> {
/// Returns the kind of [`AccessError`].
pub const fn kind(&self) -> &AccessErrorKind {
&self.kind
}
/// The returns the [`Access`] that this [`AccessError`] occurred in.
pub const fn access(&self) -> &Access<'_> {
&self.access
}
/// If the [`Access`] was created with a parser or an offset was manually provided,
/// returns the offset of the [`Access`] in its path string.
pub const fn offset(&self) -> Option<&usize> {
self.offset.as_ref()
}
}
impl fmt::Display for AccessError<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let AccessError {
kind,
access,
offset,
} = self;
write!(f, "Error accessing element with `{access}` access")?;
if let Some(offset) = offset {
write!(f, "(offset {offset})")?;
}
write!(f, ": ")?;
match kind {
AccessErrorKind::MissingField(type_accessed) => {
match access {
Access::Field(field) => write!(
f,
"The {type_accessed} accessed doesn't have {} `{}` field",
if let Some("a" | "e" | "i" | "o" | "u") = field.get(0..1) {
"an"
} else {
"a"
},
access.display_value()
),
Access::FieldIndex(_) => write!(
f,
"The {type_accessed} accessed doesn't have field index `{}`",
access.display_value(),
),
Access::TupleIndex(_) | Access::ListIndex(_) => write!(
f,
"The {type_accessed} accessed doesn't have index `{}`",
access.display_value()
)
}
}
AccessErrorKind::IncompatibleTypes { expected, actual } => write!(
f,
"Expected {} access to access a {expected}, found a {actual} instead.",
access.kind()
),
AccessErrorKind::IncompatibleEnumVariantTypes { expected, actual } => write!(
f,
"Expected variant {} access to access a {expected:?} variant, found a {actual:?} variant instead.",
access.kind()
),
}
}
}
impl core::error::Error for AccessError<'_> {}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.