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