bevy_reflect/impls/
indexmap.rs

1use crate::{
2    utility::GenericTypeInfoCell, FromReflect, FromType, Generics, GetTypeRegistration,
3    PartialReflect, Reflect, ReflectCloneError, ReflectFromPtr, ReflectMut, ReflectOwned,
4    ReflectRef, Set, SetInfo, TypeInfo, TypeParamInfo, TypePath, TypeRegistration,
5};
6use bevy_platform::prelude::{Box, Vec};
7use bevy_reflect::{
8    DynamicMap, Map, MapInfo, MaybeTyped, ReflectFromReflect, ReflectKind, TypeRegistry, Typed,
9};
10use bevy_reflect_derive::impl_type_path;
11use core::{any::Any, hash::BuildHasher, hash::Hash};
12use indexmap::{IndexMap, IndexSet};
13
14impl<K, V, S> Map for IndexMap<K, V, S>
15where
16    K: FromReflect + MaybeTyped + TypePath + GetTypeRegistration + Eq + Hash,
17    V: FromReflect + MaybeTyped + TypePath + GetTypeRegistration,
18    S: TypePath + BuildHasher + Default + Send + Sync,
19{
20    fn get(&self, key: &dyn PartialReflect) -> Option<&dyn PartialReflect> {
21        key.try_downcast_ref::<K>()
22            .and_then(|key| Self::get(self, key))
23            .map(|value| value as &dyn PartialReflect)
24    }
25
26    fn get_mut(&mut self, key: &dyn PartialReflect) -> Option<&mut dyn PartialReflect> {
27        key.try_downcast_ref::<K>()
28            .and_then(move |key| Self::get_mut(self, key))
29            .map(|value| value as &mut dyn PartialReflect)
30    }
31
32    fn len(&self) -> usize {
33        Self::len(self)
34    }
35
36    fn iter(&self) -> Box<dyn Iterator<Item = (&dyn PartialReflect, &dyn PartialReflect)> + '_> {
37        Box::new(
38            self.iter()
39                .map(|(k, v)| (k as &dyn PartialReflect, v as &dyn PartialReflect)),
40        )
41    }
42
43    fn drain(&mut self) -> Vec<(Box<dyn PartialReflect>, Box<dyn PartialReflect>)> {
44        self.drain(..)
45            .map(|(key, value)| {
46                (
47                    Box::new(key) as Box<dyn PartialReflect>,
48                    Box::new(value) as Box<dyn PartialReflect>,
49                )
50            })
51            .collect()
52    }
53
54    fn retain(&mut self, f: &mut dyn FnMut(&dyn PartialReflect, &mut dyn PartialReflect) -> bool) {
55        self.retain(move |key, value| f(key, value));
56    }
57
58    fn to_dynamic_map(&self) -> DynamicMap {
59        let mut dynamic_map = DynamicMap::default();
60        dynamic_map.set_represented_type(PartialReflect::get_represented_type_info(self));
61        for (k, v) in self {
62            let key = K::from_reflect(k).unwrap_or_else(|| {
63                panic!(
64                    "Attempted to clone invalid key of type {}.",
65                    k.reflect_type_path()
66                )
67            });
68            dynamic_map.insert_boxed(Box::new(key), v.to_dynamic());
69        }
70        dynamic_map
71    }
72
73    fn insert_boxed(
74        &mut self,
75        key: Box<dyn PartialReflect>,
76        value: Box<dyn PartialReflect>,
77    ) -> Option<Box<dyn PartialReflect>> {
78        let key = K::take_from_reflect(key).unwrap_or_else(|key| {
79            panic!(
80                "Attempted to insert invalid key of type {}.",
81                key.reflect_type_path()
82            )
83        });
84        let value = V::take_from_reflect(value).unwrap_or_else(|value| {
85            panic!(
86                "Attempted to insert invalid value of type {}.",
87                value.reflect_type_path()
88            )
89        });
90        self.insert(key, value)
91            .map(|old_value| Box::new(old_value) as Box<dyn PartialReflect>)
92    }
93
94    fn remove(&mut self, key: &dyn PartialReflect) -> Option<Box<dyn PartialReflect>> {
95        let mut from_reflect = None;
96        key.try_downcast_ref::<K>()
97            .or_else(|| {
98                from_reflect = K::from_reflect(key);
99                from_reflect.as_ref()
100            })
101            .and_then(|key| self.shift_remove(key))
102            .map(|value| Box::new(value) as Box<dyn PartialReflect>)
103    }
104}
105
106impl<K, V, S> PartialReflect for IndexMap<K, V, S>
107where
108    K: FromReflect + MaybeTyped + TypePath + GetTypeRegistration + Eq + Hash,
109    V: FromReflect + MaybeTyped + TypePath + GetTypeRegistration,
110    S: TypePath + BuildHasher + Default + Send + Sync,
111{
112    fn get_represented_type_info(&self) -> Option<&'static TypeInfo> {
113        Some(<Self as Typed>::type_info())
114    }
115
116    #[inline]
117    fn into_partial_reflect(self: Box<Self>) -> Box<dyn PartialReflect> {
118        self
119    }
120
121    fn as_partial_reflect(&self) -> &dyn PartialReflect {
122        self
123    }
124
125    fn as_partial_reflect_mut(&mut self) -> &mut dyn PartialReflect {
126        self
127    }
128
129    #[inline]
130    fn try_into_reflect(self: Box<Self>) -> Result<Box<dyn Reflect>, Box<dyn PartialReflect>> {
131        Ok(self)
132    }
133
134    fn try_as_reflect(&self) -> Option<&dyn Reflect> {
135        Some(self)
136    }
137
138    fn try_as_reflect_mut(&mut self) -> Option<&mut dyn Reflect> {
139        Some(self)
140    }
141
142    fn apply(&mut self, value: &dyn PartialReflect) {
143        crate::map_apply(self, value);
144    }
145
146    fn try_apply(&mut self, value: &dyn PartialReflect) -> Result<(), crate::ApplyError> {
147        crate::map_try_apply(self, value)
148    }
149
150    fn reflect_kind(&self) -> ReflectKind {
151        ReflectKind::Map
152    }
153
154    fn reflect_ref(&self) -> ReflectRef<'_> {
155        ReflectRef::Map(self)
156    }
157
158    fn reflect_mut(&mut self) -> ReflectMut<'_> {
159        ReflectMut::Map(self)
160    }
161
162    fn reflect_owned(self: Box<Self>) -> ReflectOwned {
163        ReflectOwned::Map(self)
164    }
165
166    fn reflect_clone(&self) -> Result<Box<dyn Reflect>, ReflectCloneError> {
167        let mut map = Self::with_capacity_and_hasher(self.len(), S::default());
168        for (key, value) in self.iter() {
169            let key = key.reflect_clone_and_take()?;
170            let value = value.reflect_clone_and_take()?;
171            map.insert(key, value);
172        }
173
174        Ok(Box::new(map))
175    }
176
177    fn reflect_partial_eq(&self, value: &dyn PartialReflect) -> Option<bool> {
178        crate::map_partial_eq(self, value)
179    }
180}
181
182impl<K, V, S> Reflect for IndexMap<K, V, S>
183where
184    K: FromReflect + MaybeTyped + TypePath + GetTypeRegistration + Eq + Hash,
185    V: FromReflect + MaybeTyped + TypePath + GetTypeRegistration,
186    S: TypePath + BuildHasher + Default + Send + Sync,
187{
188    fn into_any(self: Box<Self>) -> Box<dyn Any> {
189        self
190    }
191
192    fn as_any(&self) -> &dyn Any {
193        self
194    }
195
196    fn as_any_mut(&mut self) -> &mut dyn Any {
197        self
198    }
199
200    fn into_reflect(self: Box<Self>) -> Box<dyn Reflect> {
201        self
202    }
203
204    fn as_reflect(&self) -> &dyn Reflect {
205        self
206    }
207
208    fn as_reflect_mut(&mut self) -> &mut dyn Reflect {
209        self
210    }
211
212    fn set(&mut self, value: Box<dyn Reflect>) -> Result<(), Box<dyn Reflect>> {
213        *self = value.take()?;
214        Ok(())
215    }
216}
217
218impl<K, V, S> Typed for IndexMap<K, V, S>
219where
220    K: FromReflect + MaybeTyped + TypePath + GetTypeRegistration + Eq + Hash,
221    V: FromReflect + MaybeTyped + TypePath + GetTypeRegistration,
222    S: TypePath + BuildHasher + Default + Send + Sync,
223{
224    fn type_info() -> &'static TypeInfo {
225        static CELL: GenericTypeInfoCell = GenericTypeInfoCell::new();
226        CELL.get_or_insert::<Self, _>(|| {
227            TypeInfo::Map(
228                MapInfo::new::<Self, K, V>().with_generics(Generics::from_iter([
229                    TypeParamInfo::new::<K>("K"),
230                    TypeParamInfo::new::<V>("V"),
231                ])),
232            )
233        })
234    }
235}
236
237impl<K, V, S> FromReflect for IndexMap<K, V, S>
238where
239    K: FromReflect + MaybeTyped + TypePath + GetTypeRegistration + Eq + Hash,
240    V: FromReflect + MaybeTyped + TypePath + GetTypeRegistration,
241    S: TypePath + BuildHasher + Default + Send + Sync,
242{
243    fn from_reflect(reflect: &dyn PartialReflect) -> Option<Self> {
244        let ref_map = reflect.reflect_ref().as_map().ok()?;
245
246        let mut new_map = Self::with_capacity_and_hasher(ref_map.len(), S::default());
247
248        for (key, value) in ref_map.iter() {
249            let new_key = K::from_reflect(key)?;
250            let new_value = V::from_reflect(value)?;
251            new_map.insert(new_key, new_value);
252        }
253
254        Some(new_map)
255    }
256}
257
258impl<K, V, S> GetTypeRegistration for IndexMap<K, V, S>
259where
260    K: Hash + Eq + FromReflect + MaybeTyped + TypePath + GetTypeRegistration,
261    V: FromReflect + MaybeTyped + TypePath + GetTypeRegistration,
262    S: TypePath + BuildHasher + Send + Sync + Default,
263{
264    fn get_type_registration() -> TypeRegistration {
265        let mut registration = TypeRegistration::of::<Self>();
266        registration.insert::<ReflectFromPtr>(FromType::<Self>::from_type());
267        registration.insert::<ReflectFromReflect>(FromType::<Self>::from_type());
268        registration
269    }
270
271    fn register_type_dependencies(registry: &mut TypeRegistry) {
272        registry.register::<K>();
273        registry.register::<V>();
274    }
275}
276
277impl_type_path!(::indexmap::IndexMap<K, V, S>);
278
279impl<T, S> Set for IndexSet<T, S>
280where
281    T: FromReflect + TypePath + GetTypeRegistration + Eq + Hash,
282    S: TypePath + BuildHasher + Default + Send + Sync,
283{
284    fn get(&self, value: &dyn PartialReflect) -> Option<&dyn PartialReflect> {
285        value
286            .try_downcast_ref::<T>()
287            .and_then(|value| Self::get(self, value))
288            .map(|value| value as &dyn PartialReflect)
289    }
290
291    fn len(&self) -> usize {
292        self.len()
293    }
294
295    fn iter(&self) -> Box<dyn Iterator<Item = &dyn PartialReflect> + '_> {
296        let iter = self.iter().map(|v| v as &dyn PartialReflect);
297        Box::new(iter)
298    }
299
300    fn drain(&mut self) -> Vec<Box<dyn PartialReflect>> {
301        self.drain(..)
302            .map(|value| Box::new(value) as Box<dyn PartialReflect>)
303            .collect()
304    }
305
306    fn retain(&mut self, f: &mut dyn FnMut(&dyn PartialReflect) -> bool) {
307        self.retain(move |value| f(value));
308    }
309
310    fn insert_boxed(&mut self, value: Box<dyn PartialReflect>) -> bool {
311        let value = T::take_from_reflect(value).unwrap_or_else(|value| {
312            panic!(
313                "Attempted to insert invalid value of type {}.",
314                value.reflect_type_path()
315            )
316        });
317        self.insert(value)
318    }
319
320    fn remove(&mut self, value: &dyn PartialReflect) -> bool {
321        let mut from_reflect = None;
322        value
323            .try_downcast_ref::<T>()
324            .or_else(|| {
325                from_reflect = T::from_reflect(value);
326                from_reflect.as_ref()
327            })
328            .is_some_and(|value| self.shift_remove(value))
329    }
330
331    fn contains(&self, value: &dyn PartialReflect) -> bool {
332        let mut from_reflect = None;
333        value
334            .try_downcast_ref::<T>()
335            .or_else(|| {
336                from_reflect = T::from_reflect(value);
337                from_reflect.as_ref()
338            })
339            .is_some_and(|value| self.contains(value))
340    }
341}
342
343impl<T, S> PartialReflect for IndexSet<T, S>
344where
345    T: FromReflect + TypePath + GetTypeRegistration + Eq + Hash,
346    S: TypePath + BuildHasher + Default + Send + Sync,
347{
348    fn get_represented_type_info(&self) -> Option<&'static TypeInfo> {
349        Some(<Self as Typed>::type_info())
350    }
351
352    #[inline]
353    fn into_partial_reflect(self: Box<Self>) -> Box<dyn PartialReflect> {
354        self
355    }
356
357    fn as_partial_reflect(&self) -> &dyn PartialReflect {
358        self
359    }
360
361    fn as_partial_reflect_mut(&mut self) -> &mut dyn PartialReflect {
362        self
363    }
364
365    #[inline]
366    fn try_into_reflect(self: Box<Self>) -> Result<Box<dyn Reflect>, Box<dyn PartialReflect>> {
367        Ok(self)
368    }
369
370    fn try_as_reflect(&self) -> Option<&dyn Reflect> {
371        Some(self)
372    }
373
374    fn try_as_reflect_mut(&mut self) -> Option<&mut dyn Reflect> {
375        Some(self)
376    }
377
378    fn apply(&mut self, value: &dyn PartialReflect) {
379        crate::set_apply(self, value);
380    }
381
382    fn try_apply(&mut self, value: &dyn PartialReflect) -> Result<(), crate::ApplyError> {
383        crate::set_try_apply(self, value)
384    }
385
386    fn reflect_kind(&self) -> ReflectKind {
387        ReflectKind::Set
388    }
389
390    fn reflect_ref(&self) -> ReflectRef<'_> {
391        ReflectRef::Set(self)
392    }
393
394    fn reflect_mut(&mut self) -> ReflectMut<'_> {
395        ReflectMut::Set(self)
396    }
397
398    fn reflect_owned(self: Box<Self>) -> ReflectOwned {
399        ReflectOwned::Set(self)
400    }
401
402    fn reflect_clone(&self) -> Result<Box<dyn Reflect>, ReflectCloneError> {
403        Ok(Box::new(
404            self.iter()
405                .map(PartialReflect::reflect_clone_and_take)
406                .collect::<Result<Self, ReflectCloneError>>()?,
407        ))
408    }
409
410    fn reflect_partial_eq(&self, value: &dyn PartialReflect) -> Option<bool> {
411        crate::set_partial_eq(self, value)
412    }
413}
414
415impl<T, S> Reflect for IndexSet<T, S>
416where
417    T: FromReflect + TypePath + GetTypeRegistration + Eq + Hash,
418    S: TypePath + BuildHasher + Default + Send + Sync,
419{
420    fn into_any(self: Box<Self>) -> Box<dyn Any> {
421        self
422    }
423
424    fn as_any(&self) -> &dyn Any {
425        self
426    }
427
428    fn as_any_mut(&mut self) -> &mut dyn Any {
429        self
430    }
431
432    fn into_reflect(self: Box<Self>) -> Box<dyn Reflect> {
433        self
434    }
435
436    fn as_reflect(&self) -> &dyn Reflect {
437        self
438    }
439
440    fn as_reflect_mut(&mut self) -> &mut dyn Reflect {
441        self
442    }
443
444    fn set(&mut self, value: Box<dyn Reflect>) -> Result<(), Box<dyn Reflect>> {
445        *self = value.take()?;
446        Ok(())
447    }
448}
449
450impl<T, S> Typed for IndexSet<T, S>
451where
452    T: FromReflect + TypePath + GetTypeRegistration + Eq + Hash,
453    S: TypePath + BuildHasher + Default + Send + Sync,
454{
455    fn type_info() -> &'static TypeInfo {
456        static CELL: GenericTypeInfoCell = GenericTypeInfoCell::new();
457        CELL.get_or_insert::<Self, _>(|| {
458            TypeInfo::Set(
459                SetInfo::new::<Self, T>()
460                    .with_generics(Generics::from_iter([TypeParamInfo::new::<T>("T")])),
461            )
462        })
463    }
464}
465
466impl<T, S> FromReflect for IndexSet<T, S>
467where
468    T: FromReflect + TypePath + GetTypeRegistration + Eq + Hash,
469    S: TypePath + BuildHasher + Default + Send + Sync,
470{
471    fn from_reflect(reflect: &dyn PartialReflect) -> Option<Self> {
472        let ref_set = reflect.reflect_ref().as_set().ok()?;
473
474        let mut new_set = Self::with_capacity_and_hasher(ref_set.len(), S::default());
475
476        for field in ref_set.iter() {
477            new_set.insert(T::from_reflect(field)?);
478        }
479
480        Some(new_set)
481    }
482}
483
484impl<T, S> GetTypeRegistration for IndexSet<T, S>
485where
486    T: FromReflect + TypePath + GetTypeRegistration + Eq + Hash,
487    S: TypePath + BuildHasher + Default + Send + Sync,
488{
489    fn get_type_registration() -> TypeRegistration {
490        let mut registration = TypeRegistration::of::<Self>();
491        registration.insert::<ReflectFromPtr>(FromType::<Self>::from_type());
492        registration
493    }
494}
495
496impl_type_path!(::indexmap::IndexSet<T, S>);