Path: blob/main/crates/bevy_reflect/src/serde/ser/custom_serialization.rs
6849 views
use crate::serde::ser::error_utils::make_custom_error;1#[cfg(feature = "debug_stack")]2use crate::serde::ser::error_utils::TYPE_INFO_STACK;3use crate::serde::ReflectSerializeWithRegistry;4use crate::{PartialReflect, ReflectSerialize, TypeRegistry};5use serde::Serializer;67/// Attempts to serialize a [`PartialReflect`] value with custom [`ReflectSerialize`]8/// or [`ReflectSerializeWithRegistry`] type data.9///10/// On success, returns the result of the serialization.11/// On failure, returns the original serializer and the error that occurred.12pub(super) fn try_custom_serialize<S: Serializer>(13value: &dyn PartialReflect,14type_registry: &TypeRegistry,15serializer: S,16) -> Result<Result<S::Ok, S::Error>, (S, S::Error)> {17let Some(value) = value.try_as_reflect() else {18return Err((19serializer,20make_custom_error(format_args!(21"type `{}` does not implement `Reflect`",22value.reflect_type_path()23)),24));25};2627let info = value.reflect_type_info();2829let Some(registration) = type_registry.get(info.type_id()) else {30return Err((31serializer,32make_custom_error(format_args!(33"type `{}` is not registered in the type registry",34info.type_path(),35)),36));37};3839if let Some(reflect_serialize) = registration.data::<ReflectSerialize>() {40#[cfg(feature = "debug_stack")]41TYPE_INFO_STACK.with_borrow_mut(crate::type_info_stack::TypeInfoStack::pop);4243Ok(reflect_serialize.serialize(value, serializer))44} else if let Some(reflect_serialize_with_registry) =45registration.data::<ReflectSerializeWithRegistry>()46{47#[cfg(feature = "debug_stack")]48TYPE_INFO_STACK.with_borrow_mut(crate::type_info_stack::TypeInfoStack::pop);4950Ok(reflect_serialize_with_registry.serialize(value, serializer, type_registry))51} else {52Err((serializer, make_custom_error(format_args!(53"type `{}` did not register the `ReflectSerialize` or `ReflectSerializeWithRegistry` type data. For certain types, this may need to be registered manually using `register_type_data`",54info.type_path(),55))))56}57}585960