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