Skip to main content

bevy_reflect/impls/
indexmap.rs

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