Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
bevyengine
GitHub Repository: bevyengine/bevy
Path: blob/main/crates/bevy_reflect/src/serde/ser/structs.rs
9374 views
1
use crate::{
2
serde::{ser::error_utils::make_custom_error, SerializationData, TypedReflectSerializer},
3
structs::Struct,
4
TypeInfo, TypeRegistry,
5
};
6
use serde::{ser::SerializeStruct, Serialize};
7
8
use super::ReflectSerializerProcessor;
9
10
/// A serializer for [`Struct`] values.
11
pub(super) struct StructSerializer<'a, P> {
12
pub struct_value: &'a dyn Struct,
13
pub registry: &'a TypeRegistry,
14
pub processor: Option<&'a P>,
15
}
16
17
impl<P: ReflectSerializerProcessor> Serialize for StructSerializer<'_, P> {
18
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
19
where
20
S: serde::Serializer,
21
{
22
let type_info = self
23
.struct_value
24
.get_represented_type_info()
25
.ok_or_else(|| {
26
make_custom_error(format_args!(
27
"cannot get type info for `{}`",
28
self.struct_value.reflect_type_path()
29
))
30
})?;
31
32
let struct_info = match type_info {
33
TypeInfo::Struct(struct_info) => struct_info,
34
info => {
35
return Err(make_custom_error(format_args!(
36
"expected struct type but received {info:?}"
37
)));
38
}
39
};
40
41
let serialization_data = self
42
.registry
43
.get(type_info.type_id())
44
.and_then(|registration| registration.data::<SerializationData>());
45
let ignored_len = serialization_data.map(SerializationData::len).unwrap_or(0);
46
let mut state = serializer.serialize_struct(
47
struct_info.type_path_table().ident().unwrap(),
48
self.struct_value.field_len() - ignored_len,
49
)?;
50
51
for (index, (_, value)) in self.struct_value.iter_fields().enumerate() {
52
if serialization_data.is_some_and(|data| data.is_field_skipped(index)) {
53
continue;
54
}
55
let key = struct_info.field_at(index).unwrap().name();
56
state.serialize_field(
57
key,
58
&TypedReflectSerializer::new_internal(value, self.registry, self.processor),
59
)?;
60
}
61
state.end()
62
}
63
}
64
65