Path: blob/main/crates/bevy_reflect/src/serde/ser/structs.rs
9374 views
use crate::{1serde::{ser::error_utils::make_custom_error, SerializationData, TypedReflectSerializer},2structs::Struct,3TypeInfo, TypeRegistry,4};5use serde::{ser::SerializeStruct, Serialize};67use super::ReflectSerializerProcessor;89/// A serializer for [`Struct`] values.10pub(super) struct StructSerializer<'a, P> {11pub struct_value: &'a dyn Struct,12pub registry: &'a TypeRegistry,13pub processor: Option<&'a P>,14}1516impl<P: ReflectSerializerProcessor> Serialize for StructSerializer<'_, P> {17fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>18where19S: serde::Serializer,20{21let type_info = self22.struct_value23.get_represented_type_info()24.ok_or_else(|| {25make_custom_error(format_args!(26"cannot get type info for `{}`",27self.struct_value.reflect_type_path()28))29})?;3031let struct_info = match type_info {32TypeInfo::Struct(struct_info) => struct_info,33info => {34return Err(make_custom_error(format_args!(35"expected struct type but received {info:?}"36)));37}38};3940let serialization_data = self41.registry42.get(type_info.type_id())43.and_then(|registration| registration.data::<SerializationData>());44let ignored_len = serialization_data.map(SerializationData::len).unwrap_or(0);45let mut state = serializer.serialize_struct(46struct_info.type_path_table().ident().unwrap(),47self.struct_value.field_len() - ignored_len,48)?;4950for (index, (_, value)) in self.struct_value.iter_fields().enumerate() {51if serialization_data.is_some_and(|data| data.is_field_skipped(index)) {52continue;53}54let key = struct_info.field_at(index).unwrap().name();55state.serialize_field(56key,57&TypedReflectSerializer::new_internal(value, self.registry, self.processor),58)?;59}60state.end()61}62}636465