shipyard/views/serde/ser/
view.rs

1use crate::component::Component;
2use crate::iter::IntoIter;
3use crate::tracking::Tracking;
4use crate::views::View;
5use alloc::vec::Vec;
6use serde::ser::SerializeSeq;
7use serde::{Serialize, Serializer};
8
9/// Builder to customize [`View`]'s serialization format.
10///
11/// Make sure to match the configuration when deserializing.
12pub struct ViewSerializer<'tmp, 'view, T: Component, Track> {
13    #[allow(missing_docs)]
14    pub view: &'tmp View<'view, T, Track>,
15    /// Serializes the component's type name in addition to the ids and components.
16    pub type_names: bool,
17}
18
19impl<'tmp, 'view, T: Component, Track> ViewSerializer<'tmp, 'view, T, Track> {
20    #[allow(missing_docs)]
21    pub fn new(view: &'tmp View<'view, T, Track>) -> ViewSerializer<'tmp, 'view, T, Track> {
22        ViewSerializer {
23            view,
24            type_names: false,
25        }
26    }
27
28    /// Serializes the component's type name in addition to the ids and components.
29    pub fn type_names(&mut self, type_names: bool) -> &mut Self {
30        self.type_names = type_names;
31
32        self
33    }
34}
35
36impl<'a, T: Component + Serialize, Track: Tracking> Serialize for View<'a, T, Track> {
37    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
38    where
39        S: Serializer,
40    {
41        let mut seq = serializer.serialize_seq(Some(self.len()))?;
42
43        self.iter()
44            .with_id()
45            .try_for_each(|(eid, component)| seq.serialize_element(&(eid, component)))?;
46
47        seq.end()
48    }
49}
50
51impl<'tmp, 'view, T: Component + Serialize, Track: Tracking> Serialize
52    for ViewSerializer<'tmp, 'view, T, Track>
53{
54    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
55    where
56        S: Serializer,
57    {
58        if self.type_names {
59            use serde::ser::SerializeStruct as _;
60
61            let mut state = serializer.serialize_struct("View", 2)?;
62            state.serialize_field("type_name", &std::any::type_name::<T>())?;
63
64            let data = self.view.iter().with_id().collect::<Vec<_>>();
65            state.serialize_field("data", &data)?;
66
67            state.end()
68        } else {
69            let mut seq = serializer.serialize_seq(Some(self.view.len()))?;
70
71            self.view
72                .iter()
73                .with_id()
74                .try_for_each(|(eid, component)| seq.serialize_element(&(eid, component)))?;
75
76            seq.end()
77        }
78    }
79}