mirror_mirror/
tuple_struct.rs

1use alloc::boxed::Box;
2use core::any::Any;
3use core::fmt;
4use core::iter::FusedIterator;
5
6use crate::iter::ValueIterMut;
7use crate::tuple::TupleValue;
8use crate::type_info::graph::NodeId;
9use crate::type_info::graph::OpaqueNode;
10use crate::type_info::graph::TypeGraph;
11use crate::DescribeType;
12use crate::FromReflect;
13use crate::Reflect;
14use crate::ReflectMut;
15use crate::ReflectOwned;
16use crate::ReflectRef;
17use crate::Tuple;
18use crate::Value;
19
20/// A reflected tuple struct type.
21///
22/// Will be implemented by `#[derive(Reflect)]` on tuple structs.
23pub trait TupleStruct: Reflect {
24    fn field_at(&self, index: usize) -> Option<&dyn Reflect>;
25
26    fn field_at_mut(&mut self, index: usize) -> Option<&mut dyn Reflect>;
27
28    fn fields(&self) -> Iter<'_>;
29
30    fn fields_mut(&mut self) -> ValueIterMut<'_>;
31
32    fn fields_len(&self) -> usize;
33}
34
35impl fmt::Debug for dyn TupleStruct {
36    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
37        self.as_reflect().debug(f)
38    }
39}
40
41#[derive(Default, Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
42#[cfg_attr(feature = "speedy", derive(speedy::Readable, speedy::Writable))]
43#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
44pub struct TupleStructValue {
45    tuple: TupleValue,
46}
47
48impl TupleStructValue {
49    pub fn new() -> Self {
50        Self::default()
51    }
52
53    pub fn with_capacity(capacity: usize) -> Self {
54        Self {
55            tuple: TupleValue::with_capacity(capacity),
56        }
57    }
58
59    pub fn with_field(self, value: impl Into<Value>) -> Self {
60        Self {
61            tuple: self.tuple.with_field(value),
62        }
63    }
64
65    pub fn push_field(&mut self, value: impl Into<Value>) {
66        self.tuple.push_field(value);
67    }
68}
69
70impl DescribeType for TupleStructValue {
71    fn build(graph: &mut TypeGraph) -> NodeId {
72        graph.get_or_build_node_with::<Self, _>(|graph| {
73            OpaqueNode::new::<Self>(Default::default(), graph)
74        })
75    }
76}
77
78impl Reflect for TupleStructValue {
79    trivial_reflect_methods!();
80
81    fn patch(&mut self, value: &dyn Reflect) {
82        if let Some(tuple) = value.reflect_ref().as_tuple_struct() {
83            for (index, value) in self.fields_mut().enumerate() {
84                if let Some(new_value) = tuple.field_at(index) {
85                    value.patch(new_value);
86                }
87            }
88        }
89    }
90
91    fn to_value(&self) -> Value {
92        self.clone().into()
93    }
94
95    fn clone_reflect(&self) -> Box<dyn Reflect> {
96        Box::new(self.clone())
97    }
98
99    fn debug(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
100        if f.alternate() {
101            write!(f, "{self:#?}")
102        } else {
103            write!(f, "{self:?}")
104        }
105    }
106
107    fn reflect_owned(self: Box<Self>) -> ReflectOwned {
108        ReflectOwned::TupleStruct(self)
109    }
110
111    fn reflect_ref(&self) -> ReflectRef<'_> {
112        ReflectRef::TupleStruct(self)
113    }
114
115    fn reflect_mut(&mut self) -> ReflectMut<'_> {
116        ReflectMut::TupleStruct(self)
117    }
118}
119
120impl TupleStruct for TupleStructValue {
121    fn field_at(&self, index: usize) -> Option<&dyn Reflect> {
122        self.tuple.field_at(index)
123    }
124
125    fn field_at_mut(&mut self, index: usize) -> Option<&mut dyn Reflect> {
126        self.tuple.field_at_mut(index)
127    }
128
129    fn fields(&self) -> Iter<'_> {
130        Iter::new(self)
131    }
132
133    fn fields_mut(&mut self) -> ValueIterMut<'_> {
134        self.tuple.fields_mut()
135    }
136
137    fn fields_len(&self) -> usize {
138        self.tuple.fields_len()
139    }
140}
141
142impl FromReflect for TupleStructValue {
143    fn from_reflect(reflect: &dyn Reflect) -> Option<Self> {
144        let tuple_struct = reflect.reflect_ref().as_tuple_struct()?;
145        let this = tuple_struct
146            .fields()
147            .fold(TupleStructValue::default(), |builder, value| {
148                builder.with_field(value.to_value())
149            });
150        Some(this)
151    }
152}
153
154impl<V> FromIterator<V> for TupleStructValue
155where
156    V: Reflect,
157{
158    fn from_iter<T>(iter: T) -> Self
159    where
160        T: IntoIterator<Item = V>,
161    {
162        let mut out = Self::default();
163        for value in iter {
164            out.push_field(value.to_value());
165        }
166        out
167    }
168}
169
170#[derive(Debug)]
171pub struct Iter<'a> {
172    tuple_struct: &'a dyn TupleStruct,
173    index: usize,
174}
175
176impl<'a> Iter<'a> {
177    pub fn new(tuple_struct: &'a dyn TupleStruct) -> Self {
178        Self {
179            tuple_struct,
180            index: 0,
181        }
182    }
183}
184
185impl<'a> Iterator for Iter<'a> {
186    type Item = &'a dyn Reflect;
187
188    fn next(&mut self) -> Option<Self::Item> {
189        let value = self.tuple_struct.field_at(self.index)?;
190        self.index += 1;
191        Some(value)
192    }
193}
194
195impl<'a> ExactSizeIterator for Iter<'a> {
196    fn len(&self) -> usize {
197        self.tuple_struct.fields_len()
198    }
199}
200
201impl<'a> FusedIterator for Iter<'a> {}