Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
bevyengine
GitHub Repository: bevyengine/bevy
Path: blob/main/crates/bevy_reflect/src/serde/ser/tuple_structs.rs
9374 views
1
use crate::{
2
serde::{ser::error_utils::make_custom_error, SerializationData, TypedReflectSerializer},
3
tuple_struct::TupleStruct,
4
TypeInfo, TypeRegistry,
5
};
6
use serde::{ser::SerializeTupleStruct, Serialize};
7
8
use super::ReflectSerializerProcessor;
9
10
/// A serializer for [`TupleStruct`] values.
11
pub(super) struct TupleStructSerializer<'a, P> {
12
pub tuple_struct: &'a dyn TupleStruct,
13
pub registry: &'a TypeRegistry,
14
pub processor: Option<&'a P>,
15
}
16
17
impl<P: ReflectSerializerProcessor> Serialize for TupleStructSerializer<'_, 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
.tuple_struct
24
.get_represented_type_info()
25
.ok_or_else(|| {
26
make_custom_error(format_args!(
27
"cannot get type info for `{}`",
28
self.tuple_struct.reflect_type_path()
29
))
30
})?;
31
32
let tuple_struct_info = match type_info {
33
TypeInfo::TupleStruct(tuple_struct_info) => tuple_struct_info,
34
info => {
35
return Err(make_custom_error(format_args!(
36
"expected tuple 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
47
if self.tuple_struct.field_len() == 1 && serialization_data.is_none() {
48
let field = self.tuple_struct.field(0).unwrap();
49
return serializer.serialize_newtype_struct(
50
tuple_struct_info.type_path_table().ident().unwrap(),
51
&TypedReflectSerializer::new_internal(field, self.registry, self.processor),
52
);
53
}
54
55
let mut state = serializer.serialize_tuple_struct(
56
tuple_struct_info.type_path_table().ident().unwrap(),
57
self.tuple_struct.field_len() - ignored_len,
58
)?;
59
60
for (index, value) in self.tuple_struct.iter_fields().enumerate() {
61
if serialization_data.is_some_and(|data| data.is_field_skipped(index)) {
62
continue;
63
}
64
state.serialize_field(&TypedReflectSerializer::new_internal(
65
value,
66
self.registry,
67
self.processor,
68
))?;
69
}
70
state.end()
71
}
72
}
73
74