Path: blob/main/crates/bevy_reflect/src/serde/ser/custom_serialization.rs
6600 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 core::borrow::Borrow;6use serde::{Serialize, Serializer};78/// Attempts to serialize a [`PartialReflect`] value with custom [`ReflectSerialize`]9/// or [`ReflectSerializeWithRegistry`] type data.10///11/// On success, returns the result of the serialization.12/// On failure, returns the original serializer and the error that occurred.13pub(super) fn try_custom_serialize<S: Serializer>(14value: &dyn PartialReflect,15type_registry: &TypeRegistry,16serializer: S,17) -> Result<Result<S::Ok, S::Error>, (S, S::Error)> {18let Some(value) = value.try_as_reflect() else {19return Err((20serializer,21make_custom_error(format_args!(22"type `{}` does not implement `Reflect`",23value.reflect_type_path()24)),25));26};2728let info = value.reflect_type_info();2930let Some(registration) = type_registry.get(info.type_id()) else {31return Err((32serializer,33make_custom_error(format_args!(34"type `{}` is not registered in the type registry",35info.type_path(),36)),37));38};3940if let Some(reflect_serialize) = registration.data::<ReflectSerialize>() {41#[cfg(feature = "debug_stack")]42TYPE_INFO_STACK.with_borrow_mut(crate::type_info_stack::TypeInfoStack::pop);4344Ok(reflect_serialize45.get_serializable(value)46.borrow()47.serialize(serializer))48} else if let Some(reflect_serialize_with_registry) =49registration.data::<ReflectSerializeWithRegistry>()50{51#[cfg(feature = "debug_stack")]52TYPE_INFO_STACK.with_borrow_mut(crate::type_info_stack::TypeInfoStack::pop);5354Ok(reflect_serialize_with_registry.serialize(value, serializer, type_registry))55} else {56Err((serializer, make_custom_error(format_args!(57"type `{}` did not register the `ReflectSerialize` or `ReflectSerializeWithRegistry` type data. For certain types, this may need to be registered manually using `register_type_data`",58info.type_path(),59))))60}61}626364