bevy_reflect/impls/
std.rs

1use crate::std_traits::ReflectDefault;
2use crate::utility::{
3    reflect_hasher, GenericTypeInfoCell, GenericTypePathCell, NonGenericTypeInfoCell,
4};
5use crate::{
6    self as bevy_reflect, impl_type_path, map_apply, map_partial_eq, map_try_apply, ApplyError,
7    Array, ArrayInfo, ArrayIter, DynamicMap, DynamicTypePath, FromReflect, FromType,
8    GetTypeRegistration, List, ListInfo, ListIter, Map, MapInfo, MapIter, Reflect,
9    ReflectDeserialize, ReflectFromPtr, ReflectFromReflect, ReflectKind, ReflectMut, ReflectOwned,
10    ReflectRef, ReflectSerialize, TypeInfo, TypePath, TypeRegistration, TypeRegistry, Typed,
11    ValueInfo,
12};
13use bevy_reflect_derive::{impl_reflect, impl_reflect_value};
14use std::fmt;
15use std::{
16    any::Any,
17    borrow::Cow,
18    collections::VecDeque,
19    hash::{BuildHasher, Hash, Hasher},
20    path::Path,
21};
22
23impl_reflect_value!(bool(
24    Debug,
25    Hash,
26    PartialEq,
27    Serialize,
28    Deserialize,
29    Default
30));
31impl_reflect_value!(char(
32    Debug,
33    Hash,
34    PartialEq,
35    Serialize,
36    Deserialize,
37    Default
38));
39impl_reflect_value!(u8(Debug, Hash, PartialEq, Serialize, Deserialize, Default));
40impl_reflect_value!(u16(Debug, Hash, PartialEq, Serialize, Deserialize, Default));
41impl_reflect_value!(u32(Debug, Hash, PartialEq, Serialize, Deserialize, Default));
42impl_reflect_value!(u64(Debug, Hash, PartialEq, Serialize, Deserialize, Default));
43impl_reflect_value!(u128(
44    Debug,
45    Hash,
46    PartialEq,
47    Serialize,
48    Deserialize,
49    Default
50));
51impl_reflect_value!(usize(
52    Debug,
53    Hash,
54    PartialEq,
55    Serialize,
56    Deserialize,
57    Default
58));
59impl_reflect_value!(i8(Debug, Hash, PartialEq, Serialize, Deserialize, Default));
60impl_reflect_value!(i16(Debug, Hash, PartialEq, Serialize, Deserialize, Default));
61impl_reflect_value!(i32(Debug, Hash, PartialEq, Serialize, Deserialize, Default));
62impl_reflect_value!(i64(Debug, Hash, PartialEq, Serialize, Deserialize, Default));
63impl_reflect_value!(i128(
64    Debug,
65    Hash,
66    PartialEq,
67    Serialize,
68    Deserialize,
69    Default
70));
71impl_reflect_value!(isize(
72    Debug,
73    Hash,
74    PartialEq,
75    Serialize,
76    Deserialize,
77    Default
78));
79impl_reflect_value!(f32(Debug, PartialEq, Serialize, Deserialize, Default));
80impl_reflect_value!(f64(Debug, PartialEq, Serialize, Deserialize, Default));
81impl_type_path!(str);
82impl_reflect_value!(::alloc::string::String(
83    Debug,
84    Hash,
85    PartialEq,
86    Serialize,
87    Deserialize,
88    Default
89));
90impl_reflect_value!(::std::path::PathBuf(
91    Debug,
92    Hash,
93    PartialEq,
94    Serialize,
95    Deserialize,
96    Default
97));
98impl_reflect_value!(::std::any::TypeId(Debug, Hash, PartialEq,));
99impl_reflect_value!(::std::collections::BTreeSet<T: Ord + Eq + Clone + Send + Sync>());
100impl_reflect_value!(::std::collections::HashSet<T: Hash + Eq + Clone + Send + Sync, S: TypePath + Clone + Send + Sync>());
101impl_reflect_value!(::bevy_utils::hashbrown::HashSet<T: Hash + Eq + Clone + Send + Sync, S: TypePath + Clone + Send + Sync>());
102impl_reflect_value!(::core::ops::Range<T: Clone + Send + Sync>());
103impl_reflect_value!(::core::ops::RangeInclusive<T: Clone + Send + Sync>());
104impl_reflect_value!(::core::ops::RangeFrom<T: Clone + Send + Sync>());
105impl_reflect_value!(::core::ops::RangeTo<T: Clone + Send + Sync>());
106impl_reflect_value!(::core::ops::RangeToInclusive<T: Clone + Send + Sync>());
107impl_reflect_value!(::core::ops::RangeFull());
108impl_reflect_value!(::bevy_utils::Duration(
109    Debug,
110    Hash,
111    PartialEq,
112    Serialize,
113    Deserialize,
114    Default
115));
116impl_reflect_value!(::bevy_utils::Instant(Debug, Hash, PartialEq));
117impl_reflect_value!(::core::num::NonZeroI128(
118    Debug,
119    Hash,
120    PartialEq,
121    Serialize,
122    Deserialize
123));
124impl_reflect_value!(::core::num::NonZeroU128(
125    Debug,
126    Hash,
127    PartialEq,
128    Serialize,
129    Deserialize
130));
131impl_reflect_value!(::core::num::NonZeroIsize(
132    Debug,
133    Hash,
134    PartialEq,
135    Serialize,
136    Deserialize
137));
138impl_reflect_value!(::core::num::NonZeroUsize(
139    Debug,
140    Hash,
141    PartialEq,
142    Serialize,
143    Deserialize
144));
145impl_reflect_value!(::core::num::NonZeroI64(
146    Debug,
147    Hash,
148    PartialEq,
149    Serialize,
150    Deserialize
151));
152impl_reflect_value!(::core::num::NonZeroU64(
153    Debug,
154    Hash,
155    PartialEq,
156    Serialize,
157    Deserialize
158));
159impl_reflect_value!(::core::num::NonZeroU32(
160    Debug,
161    Hash,
162    PartialEq,
163    Serialize,
164    Deserialize
165));
166impl_reflect_value!(::core::num::NonZeroI32(
167    Debug,
168    Hash,
169    PartialEq,
170    Serialize,
171    Deserialize
172));
173impl_reflect_value!(::core::num::NonZeroI16(
174    Debug,
175    Hash,
176    PartialEq,
177    Serialize,
178    Deserialize
179));
180impl_reflect_value!(::core::num::NonZeroU16(
181    Debug,
182    Hash,
183    PartialEq,
184    Serialize,
185    Deserialize
186));
187impl_reflect_value!(::core::num::NonZeroU8(
188    Debug,
189    Hash,
190    PartialEq,
191    Serialize,
192    Deserialize
193));
194impl_reflect_value!(::core::num::NonZeroI8(
195    Debug,
196    Hash,
197    PartialEq,
198    Serialize,
199    Deserialize
200));
201impl_reflect_value!(::core::num::Wrapping<T: Clone + Send + Sync>());
202impl_reflect_value!(::core::num::Saturating<T: Clone + Send + Sync>());
203impl_reflect_value!(::std::sync::Arc<T: Send + Sync>);
204
205// `Serialize` and `Deserialize` only for platforms supported by serde:
206// https://github.com/serde-rs/serde/blob/3ffb86fc70efd3d329519e2dddfa306cc04f167c/serde/src/de/impls.rs#L1732
207#[cfg(any(unix, windows))]
208impl_reflect_value!(::std::ffi::OsString(
209    Debug,
210    Hash,
211    PartialEq,
212    Serialize,
213    Deserialize
214));
215#[cfg(not(any(unix, windows)))]
216impl_reflect_value!(::std::ffi::OsString(Debug, Hash, PartialEq));
217impl_reflect_value!(::alloc::collections::BinaryHeap<T: Clone>);
218
219impl_type_path!(::bevy_utils::NoOpHash);
220impl_type_path!(::bevy_utils::EntityHash);
221impl_type_path!(::bevy_utils::FixedState);
222
223macro_rules! impl_reflect_for_veclike {
224    ($ty:path, $insert:expr, $remove:expr, $push:expr, $pop:expr, $sub:ty) => {
225        impl<T: FromReflect + TypePath + GetTypeRegistration> List for $ty {
226            #[inline]
227            fn get(&self, index: usize) -> Option<&dyn Reflect> {
228                <$sub>::get(self, index).map(|value| value as &dyn Reflect)
229            }
230
231            #[inline]
232            fn get_mut(&mut self, index: usize) -> Option<&mut dyn Reflect> {
233                <$sub>::get_mut(self, index).map(|value| value as &mut dyn Reflect)
234            }
235
236            fn insert(&mut self, index: usize, value: Box<dyn Reflect>) {
237                let value = value.take::<T>().unwrap_or_else(|value| {
238                    T::from_reflect(&*value).unwrap_or_else(|| {
239                        panic!(
240                            "Attempted to insert invalid value of type {}.",
241                            value.reflect_type_path()
242                        )
243                    })
244                });
245                $insert(self, index, value);
246            }
247
248            fn remove(&mut self, index: usize) -> Box<dyn Reflect> {
249                Box::new($remove(self, index))
250            }
251
252            fn push(&mut self, value: Box<dyn Reflect>) {
253                let value = T::take_from_reflect(value).unwrap_or_else(|value| {
254                    panic!(
255                        "Attempted to push invalid value of type {}.",
256                        value.reflect_type_path()
257                    )
258                });
259                $push(self, value);
260            }
261
262            fn pop(&mut self) -> Option<Box<dyn Reflect>> {
263                $pop(self).map(|value| Box::new(value) as Box<dyn Reflect>)
264            }
265
266            #[inline]
267            fn len(&self) -> usize {
268                <$sub>::len(self)
269            }
270
271            #[inline]
272            fn iter(&self) -> ListIter {
273                ListIter::new(self)
274            }
275
276            #[inline]
277            fn drain(self: Box<Self>) -> Vec<Box<dyn Reflect>> {
278                self.into_iter()
279                    .map(|value| Box::new(value) as Box<dyn Reflect>)
280                    .collect()
281            }
282        }
283
284        impl<T: FromReflect + TypePath + GetTypeRegistration> Reflect for $ty {
285            fn get_represented_type_info(&self) -> Option<&'static TypeInfo> {
286                Some(<Self as Typed>::type_info())
287            }
288
289            fn into_any(self: Box<Self>) -> Box<dyn Any> {
290                self
291            }
292
293            fn as_any(&self) -> &dyn Any {
294                self
295            }
296
297            fn as_any_mut(&mut self) -> &mut dyn Any {
298                self
299            }
300
301            fn into_reflect(self: Box<Self>) -> Box<dyn Reflect> {
302                self
303            }
304
305            fn as_reflect(&self) -> &dyn Reflect {
306                self
307            }
308
309            fn as_reflect_mut(&mut self) -> &mut dyn Reflect {
310                self
311            }
312
313            fn apply(&mut self, value: &dyn Reflect) {
314                crate::list_apply(self, value);
315            }
316
317            fn try_apply(&mut self, value: &dyn Reflect) -> Result<(), ApplyError> {
318                crate::list_try_apply(self, value)
319            }
320
321            fn set(&mut self, value: Box<dyn Reflect>) -> Result<(), Box<dyn Reflect>> {
322                *self = value.take()?;
323                Ok(())
324            }
325
326            fn reflect_kind(&self) -> ReflectKind {
327                ReflectKind::List
328            }
329
330            fn reflect_ref(&self) -> ReflectRef {
331                ReflectRef::List(self)
332            }
333
334            fn reflect_mut(&mut self) -> ReflectMut {
335                ReflectMut::List(self)
336            }
337
338            fn reflect_owned(self: Box<Self>) -> ReflectOwned {
339                ReflectOwned::List(self)
340            }
341
342            fn clone_value(&self) -> Box<dyn Reflect> {
343                Box::new(self.clone_dynamic())
344            }
345
346            fn reflect_hash(&self) -> Option<u64> {
347                crate::list_hash(self)
348            }
349
350            fn reflect_partial_eq(&self, value: &dyn Reflect) -> Option<bool> {
351                crate::list_partial_eq(self, value)
352            }
353        }
354
355        impl<T: FromReflect + TypePath + GetTypeRegistration> Typed for $ty {
356            fn type_info() -> &'static TypeInfo {
357                static CELL: GenericTypeInfoCell = GenericTypeInfoCell::new();
358                CELL.get_or_insert::<Self, _>(|| TypeInfo::List(ListInfo::new::<Self, T>()))
359            }
360        }
361
362        impl_type_path!($ty);
363
364        impl<T: FromReflect + TypePath + GetTypeRegistration> GetTypeRegistration for $ty {
365            fn get_type_registration() -> TypeRegistration {
366                let mut registration = TypeRegistration::of::<$ty>();
367                registration.insert::<ReflectFromPtr>(FromType::<$ty>::from_type());
368                registration
369            }
370
371            fn register_type_dependencies(registry: &mut TypeRegistry) {
372                registry.register::<T>();
373            }
374        }
375
376        impl<T: FromReflect + TypePath + GetTypeRegistration> FromReflect for $ty {
377            fn from_reflect(reflect: &dyn Reflect) -> Option<Self> {
378                if let ReflectRef::List(ref_list) = reflect.reflect_ref() {
379                    let mut new_list = Self::with_capacity(ref_list.len());
380                    for field in ref_list.iter() {
381                        $push(&mut new_list, T::from_reflect(field)?);
382                    }
383                    Some(new_list)
384                } else {
385                    None
386                }
387            }
388        }
389    };
390}
391
392impl_reflect_for_veclike!(
393    ::alloc::vec::Vec<T>,
394    Vec::insert,
395    Vec::remove,
396    Vec::push,
397    Vec::pop,
398    [T]
399);
400impl_reflect_for_veclike!(
401    ::alloc::collections::VecDeque<T>,
402    VecDeque::insert,
403    VecDeque::remove,
404    VecDeque::push_back,
405    VecDeque::pop_back,
406    VecDeque::<T>
407);
408
409macro_rules! impl_reflect_for_hashmap {
410    ($ty:path) => {
411        impl<K, V, S> Map for $ty
412        where
413            K: FromReflect + TypePath + GetTypeRegistration + Eq + Hash,
414            V: FromReflect + TypePath + GetTypeRegistration,
415            S: TypePath + BuildHasher + Send + Sync,
416        {
417            fn get(&self, key: &dyn Reflect) -> Option<&dyn Reflect> {
418                key.downcast_ref::<K>()
419                    .and_then(|key| Self::get(self, key))
420                    .map(|value| value as &dyn Reflect)
421            }
422
423            fn get_mut(&mut self, key: &dyn Reflect) -> Option<&mut dyn Reflect> {
424                key.downcast_ref::<K>()
425                    .and_then(move |key| Self::get_mut(self, key))
426                    .map(|value| value as &mut dyn Reflect)
427            }
428
429            fn get_at(&self, index: usize) -> Option<(&dyn Reflect, &dyn Reflect)> {
430                self.iter()
431                    .nth(index)
432                    .map(|(key, value)| (key as &dyn Reflect, value as &dyn Reflect))
433            }
434
435            fn get_at_mut(&mut self, index: usize) -> Option<(&dyn Reflect, &mut dyn Reflect)> {
436                self.iter_mut()
437                    .nth(index)
438                    .map(|(key, value)| (key as &dyn Reflect, value as &mut dyn Reflect))
439            }
440
441            fn len(&self) -> usize {
442                Self::len(self)
443            }
444
445            fn iter(&self) -> MapIter {
446                MapIter::new(self)
447            }
448
449            fn drain(self: Box<Self>) -> Vec<(Box<dyn Reflect>, Box<dyn Reflect>)> {
450                self.into_iter()
451                    .map(|(key, value)| {
452                        (
453                            Box::new(key) as Box<dyn Reflect>,
454                            Box::new(value) as Box<dyn Reflect>,
455                        )
456                    })
457                    .collect()
458            }
459
460            fn clone_dynamic(&self) -> DynamicMap {
461                let mut dynamic_map = DynamicMap::default();
462                dynamic_map.set_represented_type(self.get_represented_type_info());
463                for (k, v) in self {
464                    let key = K::from_reflect(k).unwrap_or_else(|| {
465                        panic!(
466                            "Attempted to clone invalid key of type {}.",
467                            k.reflect_type_path()
468                        )
469                    });
470                    dynamic_map.insert_boxed(Box::new(key), v.clone_value());
471                }
472                dynamic_map
473            }
474
475            fn insert_boxed(
476                &mut self,
477                key: Box<dyn Reflect>,
478                value: Box<dyn Reflect>,
479            ) -> Option<Box<dyn Reflect>> {
480                let key = K::take_from_reflect(key).unwrap_or_else(|key| {
481                    panic!(
482                        "Attempted to insert invalid key of type {}.",
483                        key.reflect_type_path()
484                    )
485                });
486                let value = V::take_from_reflect(value).unwrap_or_else(|value| {
487                    panic!(
488                        "Attempted to insert invalid value of type {}.",
489                        value.reflect_type_path()
490                    )
491                });
492                self.insert(key, value)
493                    .map(|old_value| Box::new(old_value) as Box<dyn Reflect>)
494            }
495
496            fn remove(&mut self, key: &dyn Reflect) -> Option<Box<dyn Reflect>> {
497                let mut from_reflect = None;
498                key.downcast_ref::<K>()
499                    .or_else(|| {
500                        from_reflect = K::from_reflect(key);
501                        from_reflect.as_ref()
502                    })
503                    .and_then(|key| self.remove(key))
504                    .map(|value| Box::new(value) as Box<dyn Reflect>)
505            }
506        }
507
508        impl<K, V, S> Reflect for $ty
509        where
510            K: FromReflect + TypePath + GetTypeRegistration + Eq + Hash,
511            V: FromReflect + TypePath + GetTypeRegistration,
512            S: TypePath + BuildHasher + Send + Sync,
513        {
514            fn get_represented_type_info(&self) -> Option<&'static TypeInfo> {
515                Some(<Self as Typed>::type_info())
516            }
517
518            fn into_any(self: Box<Self>) -> Box<dyn Any> {
519                self
520            }
521
522            fn as_any(&self) -> &dyn Any {
523                self
524            }
525
526            fn as_any_mut(&mut self) -> &mut dyn Any {
527                self
528            }
529
530            #[inline]
531            fn into_reflect(self: Box<Self>) -> Box<dyn Reflect> {
532                self
533            }
534
535            fn as_reflect(&self) -> &dyn Reflect {
536                self
537            }
538
539            fn as_reflect_mut(&mut self) -> &mut dyn Reflect {
540                self
541            }
542
543            fn apply(&mut self, value: &dyn Reflect) {
544                map_apply(self, value);
545            }
546
547            fn try_apply(&mut self, value: &dyn Reflect) -> Result<(), ApplyError> {
548                map_try_apply(self, value)
549            }
550
551            fn set(&mut self, value: Box<dyn Reflect>) -> Result<(), Box<dyn Reflect>> {
552                *self = value.take()?;
553                Ok(())
554            }
555
556            fn reflect_kind(&self) -> ReflectKind {
557                ReflectKind::Map
558            }
559
560            fn reflect_ref(&self) -> ReflectRef {
561                ReflectRef::Map(self)
562            }
563
564            fn reflect_mut(&mut self) -> ReflectMut {
565                ReflectMut::Map(self)
566            }
567
568            fn reflect_owned(self: Box<Self>) -> ReflectOwned {
569                ReflectOwned::Map(self)
570            }
571
572            fn clone_value(&self) -> Box<dyn Reflect> {
573                Box::new(self.clone_dynamic())
574            }
575
576            fn reflect_partial_eq(&self, value: &dyn Reflect) -> Option<bool> {
577                map_partial_eq(self, value)
578            }
579        }
580
581        impl<K, V, S> Typed for $ty
582        where
583            K: FromReflect + TypePath + GetTypeRegistration + Eq + Hash,
584            V: FromReflect + TypePath + GetTypeRegistration,
585            S: TypePath + BuildHasher + Send + Sync,
586        {
587            fn type_info() -> &'static TypeInfo {
588                static CELL: GenericTypeInfoCell = GenericTypeInfoCell::new();
589                CELL.get_or_insert::<Self, _>(|| TypeInfo::Map(MapInfo::new::<Self, K, V>()))
590            }
591        }
592
593        impl<K, V, S> GetTypeRegistration for $ty
594        where
595            K: FromReflect + TypePath + GetTypeRegistration + Eq + Hash,
596            V: FromReflect + TypePath + GetTypeRegistration,
597            S: TypePath + BuildHasher + Send + Sync,
598        {
599            fn get_type_registration() -> TypeRegistration {
600                let mut registration = TypeRegistration::of::<Self>();
601                registration.insert::<ReflectFromPtr>(FromType::<Self>::from_type());
602                registration
603            }
604
605            fn register_type_dependencies(registry: &mut TypeRegistry) {
606                registry.register::<K>();
607                registry.register::<V>();
608            }
609        }
610
611        impl<K, V, S> FromReflect for $ty
612        where
613            K: FromReflect + TypePath + GetTypeRegistration + Eq + Hash,
614            V: FromReflect + TypePath + GetTypeRegistration,
615            S: TypePath + BuildHasher + Default + Send + Sync,
616        {
617            fn from_reflect(reflect: &dyn Reflect) -> Option<Self> {
618                if let ReflectRef::Map(ref_map) = reflect.reflect_ref() {
619                    let mut new_map = Self::with_capacity_and_hasher(ref_map.len(), S::default());
620                    for (key, value) in ref_map.iter() {
621                        let new_key = K::from_reflect(key)?;
622                        let new_value = V::from_reflect(value)?;
623                        new_map.insert(new_key, new_value);
624                    }
625                    Some(new_map)
626                } else {
627                    None
628                }
629            }
630        }
631    };
632}
633
634impl_reflect_for_hashmap!(::std::collections::HashMap<K, V, S>);
635impl_type_path!(::std::collections::hash_map::RandomState);
636impl_type_path!(::std::collections::HashMap<K, V, S>);
637
638impl_reflect_for_hashmap!(bevy_utils::hashbrown::HashMap<K, V, S>);
639impl_type_path!(::bevy_utils::hashbrown::hash_map::DefaultHashBuilder);
640impl_type_path!(::bevy_utils::hashbrown::HashMap<K, V, S>);
641
642impl<K, V> Map for ::std::collections::BTreeMap<K, V>
643where
644    K: FromReflect + TypePath + GetTypeRegistration + Eq + Ord,
645    V: FromReflect + TypePath + GetTypeRegistration,
646{
647    fn get(&self, key: &dyn Reflect) -> Option<&dyn Reflect> {
648        key.downcast_ref::<K>()
649            .and_then(|key| Self::get(self, key))
650            .map(|value| value as &dyn Reflect)
651    }
652
653    fn get_mut(&mut self, key: &dyn Reflect) -> Option<&mut dyn Reflect> {
654        key.downcast_ref::<K>()
655            .and_then(move |key| Self::get_mut(self, key))
656            .map(|value| value as &mut dyn Reflect)
657    }
658
659    fn get_at(&self, index: usize) -> Option<(&dyn Reflect, &dyn Reflect)> {
660        self.iter()
661            .nth(index)
662            .map(|(key, value)| (key as &dyn Reflect, value as &dyn Reflect))
663    }
664
665    fn get_at_mut(&mut self, index: usize) -> Option<(&dyn Reflect, &mut dyn Reflect)> {
666        self.iter_mut()
667            .nth(index)
668            .map(|(key, value)| (key as &dyn Reflect, value as &mut dyn Reflect))
669    }
670
671    fn len(&self) -> usize {
672        Self::len(self)
673    }
674
675    fn iter(&self) -> MapIter {
676        MapIter::new(self)
677    }
678
679    fn drain(self: Box<Self>) -> Vec<(Box<dyn Reflect>, Box<dyn Reflect>)> {
680        self.into_iter()
681            .map(|(key, value)| {
682                (
683                    Box::new(key) as Box<dyn Reflect>,
684                    Box::new(value) as Box<dyn Reflect>,
685                )
686            })
687            .collect()
688    }
689
690    fn clone_dynamic(&self) -> DynamicMap {
691        let mut dynamic_map = DynamicMap::default();
692        dynamic_map.set_represented_type(self.get_represented_type_info());
693        for (k, v) in self {
694            let key = K::from_reflect(k).unwrap_or_else(|| {
695                panic!(
696                    "Attempted to clone invalid key of type {}.",
697                    k.reflect_type_path()
698                )
699            });
700            dynamic_map.insert_boxed(Box::new(key), v.clone_value());
701        }
702        dynamic_map
703    }
704
705    fn insert_boxed(
706        &mut self,
707        key: Box<dyn Reflect>,
708        value: Box<dyn Reflect>,
709    ) -> Option<Box<dyn Reflect>> {
710        let key = K::take_from_reflect(key).unwrap_or_else(|key| {
711            panic!(
712                "Attempted to insert invalid key of type {}.",
713                key.reflect_type_path()
714            )
715        });
716        let value = V::take_from_reflect(value).unwrap_or_else(|value| {
717            panic!(
718                "Attempted to insert invalid value of type {}.",
719                value.reflect_type_path()
720            )
721        });
722        self.insert(key, value)
723            .map(|old_value| Box::new(old_value) as Box<dyn Reflect>)
724    }
725
726    fn remove(&mut self, key: &dyn Reflect) -> Option<Box<dyn Reflect>> {
727        let mut from_reflect = None;
728        key.downcast_ref::<K>()
729            .or_else(|| {
730                from_reflect = K::from_reflect(key);
731                from_reflect.as_ref()
732            })
733            .and_then(|key| self.remove(key))
734            .map(|value| Box::new(value) as Box<dyn Reflect>)
735    }
736}
737
738impl<K, V> Reflect for ::std::collections::BTreeMap<K, V>
739where
740    K: FromReflect + TypePath + GetTypeRegistration + Eq + Ord,
741    V: FromReflect + TypePath + GetTypeRegistration,
742{
743    fn get_represented_type_info(&self) -> Option<&'static TypeInfo> {
744        Some(<Self as Typed>::type_info())
745    }
746
747    fn into_any(self: Box<Self>) -> Box<dyn Any> {
748        self
749    }
750
751    fn as_any(&self) -> &dyn Any {
752        self
753    }
754
755    fn as_any_mut(&mut self) -> &mut dyn Any {
756        self
757    }
758
759    #[inline]
760    fn into_reflect(self: Box<Self>) -> Box<dyn Reflect> {
761        self
762    }
763
764    fn as_reflect(&self) -> &dyn Reflect {
765        self
766    }
767
768    fn as_reflect_mut(&mut self) -> &mut dyn Reflect {
769        self
770    }
771
772    fn apply(&mut self, value: &dyn Reflect) {
773        map_apply(self, value);
774    }
775
776    fn try_apply(&mut self, value: &dyn Reflect) -> Result<(), ApplyError> {
777        map_try_apply(self, value)
778    }
779
780    fn set(&mut self, value: Box<dyn Reflect>) -> Result<(), Box<dyn Reflect>> {
781        *self = value.take()?;
782        Ok(())
783    }
784
785    fn reflect_kind(&self) -> ReflectKind {
786        ReflectKind::Map
787    }
788
789    fn reflect_ref(&self) -> ReflectRef {
790        ReflectRef::Map(self)
791    }
792
793    fn reflect_mut(&mut self) -> ReflectMut {
794        ReflectMut::Map(self)
795    }
796
797    fn reflect_owned(self: Box<Self>) -> ReflectOwned {
798        ReflectOwned::Map(self)
799    }
800
801    fn clone_value(&self) -> Box<dyn Reflect> {
802        Box::new(self.clone_dynamic())
803    }
804
805    fn reflect_partial_eq(&self, value: &dyn Reflect) -> Option<bool> {
806        map_partial_eq(self, value)
807    }
808}
809
810impl<K, V> Typed for ::std::collections::BTreeMap<K, V>
811where
812    K: FromReflect + TypePath + GetTypeRegistration + Eq + Ord,
813    V: FromReflect + TypePath + GetTypeRegistration,
814{
815    fn type_info() -> &'static TypeInfo {
816        static CELL: GenericTypeInfoCell = GenericTypeInfoCell::new();
817        CELL.get_or_insert::<Self, _>(|| TypeInfo::Map(MapInfo::new::<Self, K, V>()))
818    }
819}
820
821impl<K, V> GetTypeRegistration for ::std::collections::BTreeMap<K, V>
822where
823    K: FromReflect + TypePath + GetTypeRegistration + Eq + Ord,
824    V: FromReflect + TypePath + GetTypeRegistration,
825{
826    fn get_type_registration() -> TypeRegistration {
827        let mut registration = TypeRegistration::of::<Self>();
828        registration.insert::<ReflectFromPtr>(FromType::<Self>::from_type());
829        registration
830    }
831}
832
833impl<K, V> FromReflect for ::std::collections::BTreeMap<K, V>
834where
835    K: FromReflect + TypePath + GetTypeRegistration + Eq + Ord,
836    V: FromReflect + TypePath + GetTypeRegistration,
837{
838    fn from_reflect(reflect: &dyn Reflect) -> Option<Self> {
839        if let ReflectRef::Map(ref_map) = reflect.reflect_ref() {
840            let mut new_map = Self::new();
841            for (key, value) in ref_map.iter() {
842                let new_key = K::from_reflect(key)?;
843                let new_value = V::from_reflect(value)?;
844                new_map.insert(new_key, new_value);
845            }
846            Some(new_map)
847        } else {
848            None
849        }
850    }
851}
852
853impl_type_path!(::std::collections::BTreeMap<K, V>);
854
855impl<T: Reflect + TypePath + GetTypeRegistration, const N: usize> Array for [T; N] {
856    #[inline]
857    fn get(&self, index: usize) -> Option<&dyn Reflect> {
858        <[T]>::get(self, index).map(|value| value as &dyn Reflect)
859    }
860
861    #[inline]
862    fn get_mut(&mut self, index: usize) -> Option<&mut dyn Reflect> {
863        <[T]>::get_mut(self, index).map(|value| value as &mut dyn Reflect)
864    }
865
866    #[inline]
867    fn len(&self) -> usize {
868        N
869    }
870
871    #[inline]
872    fn iter(&self) -> ArrayIter {
873        ArrayIter::new(self)
874    }
875
876    #[inline]
877    fn drain(self: Box<Self>) -> Vec<Box<dyn Reflect>> {
878        self.into_iter()
879            .map(|value| Box::new(value) as Box<dyn Reflect>)
880            .collect()
881    }
882}
883
884impl<T: Reflect + TypePath + GetTypeRegistration, const N: usize> Reflect for [T; N] {
885    fn get_represented_type_info(&self) -> Option<&'static TypeInfo> {
886        Some(<Self as Typed>::type_info())
887    }
888
889    #[inline]
890    fn into_any(self: Box<Self>) -> Box<dyn Any> {
891        self
892    }
893
894    #[inline]
895    fn as_any(&self) -> &dyn Any {
896        self
897    }
898
899    #[inline]
900    fn as_any_mut(&mut self) -> &mut dyn Any {
901        self
902    }
903
904    #[inline]
905    fn into_reflect(self: Box<Self>) -> Box<dyn Reflect> {
906        self
907    }
908
909    #[inline]
910    fn as_reflect(&self) -> &dyn Reflect {
911        self
912    }
913
914    #[inline]
915    fn as_reflect_mut(&mut self) -> &mut dyn Reflect {
916        self
917    }
918
919    #[inline]
920    fn apply(&mut self, value: &dyn Reflect) {
921        crate::array_apply(self, value);
922    }
923
924    #[inline]
925    fn try_apply(&mut self, value: &dyn Reflect) -> Result<(), ApplyError> {
926        crate::array_try_apply(self, value)
927    }
928
929    #[inline]
930    fn set(&mut self, value: Box<dyn Reflect>) -> Result<(), Box<dyn Reflect>> {
931        *self = value.take()?;
932        Ok(())
933    }
934
935    #[inline]
936    fn reflect_kind(&self) -> ReflectKind {
937        ReflectKind::Array
938    }
939
940    #[inline]
941    fn reflect_ref(&self) -> ReflectRef {
942        ReflectRef::Array(self)
943    }
944
945    #[inline]
946    fn reflect_mut(&mut self) -> ReflectMut {
947        ReflectMut::Array(self)
948    }
949
950    #[inline]
951    fn reflect_owned(self: Box<Self>) -> ReflectOwned {
952        ReflectOwned::Array(self)
953    }
954
955    #[inline]
956    fn clone_value(&self) -> Box<dyn Reflect> {
957        Box::new(self.clone_dynamic())
958    }
959
960    #[inline]
961    fn reflect_hash(&self) -> Option<u64> {
962        crate::array_hash(self)
963    }
964
965    #[inline]
966    fn reflect_partial_eq(&self, value: &dyn Reflect) -> Option<bool> {
967        crate::array_partial_eq(self, value)
968    }
969}
970
971impl<T: FromReflect + TypePath + GetTypeRegistration, const N: usize> FromReflect for [T; N] {
972    fn from_reflect(reflect: &dyn Reflect) -> Option<Self> {
973        if let ReflectRef::Array(ref_array) = reflect.reflect_ref() {
974            let mut temp_vec = Vec::with_capacity(ref_array.len());
975            for field in ref_array.iter() {
976                temp_vec.push(T::from_reflect(field)?);
977            }
978            temp_vec.try_into().ok()
979        } else {
980            None
981        }
982    }
983}
984
985impl<T: Reflect + TypePath + GetTypeRegistration, const N: usize> Typed for [T; N] {
986    fn type_info() -> &'static TypeInfo {
987        static CELL: GenericTypeInfoCell = GenericTypeInfoCell::new();
988        CELL.get_or_insert::<Self, _>(|| TypeInfo::Array(ArrayInfo::new::<Self, T>(N)))
989    }
990}
991
992impl<T: TypePath, const N: usize> TypePath for [T; N] {
993    fn type_path() -> &'static str {
994        static CELL: GenericTypePathCell = GenericTypePathCell::new();
995        CELL.get_or_insert::<Self, _>(|| format!("[{t}; {N}]", t = T::type_path()))
996    }
997
998    fn short_type_path() -> &'static str {
999        static CELL: GenericTypePathCell = GenericTypePathCell::new();
1000        CELL.get_or_insert::<Self, _>(|| format!("[{t}; {N}]", t = T::short_type_path()))
1001    }
1002}
1003
1004impl<T: Reflect + TypePath + GetTypeRegistration, const N: usize> GetTypeRegistration for [T; N] {
1005    fn get_type_registration() -> TypeRegistration {
1006        TypeRegistration::of::<[T; N]>()
1007    }
1008
1009    fn register_type_dependencies(registry: &mut TypeRegistry) {
1010        registry.register::<T>();
1011    }
1012}
1013
1014impl_reflect! {
1015    #[type_path = "core::option"]
1016    enum Option<T> {
1017        None,
1018        Some(T),
1019    }
1020}
1021
1022impl_reflect! {
1023    #[type_path = "core::result"]
1024    enum Result<T, E> {
1025        Ok(T),
1026        Err(E),
1027    }
1028}
1029
1030impl<T: TypePath + ?Sized> TypePath for &'static T {
1031    fn type_path() -> &'static str {
1032        static CELL: GenericTypePathCell = GenericTypePathCell::new();
1033        CELL.get_or_insert::<Self, _>(|| format!("&{}", T::type_path()))
1034    }
1035
1036    fn short_type_path() -> &'static str {
1037        static CELL: GenericTypePathCell = GenericTypePathCell::new();
1038        CELL.get_or_insert::<Self, _>(|| format!("&{}", T::short_type_path()))
1039    }
1040}
1041
1042impl<T: TypePath + ?Sized> TypePath for &'static mut T {
1043    fn type_path() -> &'static str {
1044        static CELL: GenericTypePathCell = GenericTypePathCell::new();
1045        CELL.get_or_insert::<Self, _>(|| format!("&mut {}", T::type_path()))
1046    }
1047
1048    fn short_type_path() -> &'static str {
1049        static CELL: GenericTypePathCell = GenericTypePathCell::new();
1050        CELL.get_or_insert::<Self, _>(|| format!("&mut {}", T::short_type_path()))
1051    }
1052}
1053
1054impl Reflect for Cow<'static, str> {
1055    fn get_represented_type_info(&self) -> Option<&'static TypeInfo> {
1056        Some(<Self as Typed>::type_info())
1057    }
1058
1059    fn into_any(self: Box<Self>) -> Box<dyn Any> {
1060        self
1061    }
1062
1063    fn as_any(&self) -> &dyn Any {
1064        self
1065    }
1066
1067    fn as_any_mut(&mut self) -> &mut dyn Any {
1068        self
1069    }
1070
1071    fn into_reflect(self: Box<Self>) -> Box<dyn Reflect> {
1072        self
1073    }
1074
1075    fn as_reflect(&self) -> &dyn Reflect {
1076        self
1077    }
1078
1079    fn as_reflect_mut(&mut self) -> &mut dyn Reflect {
1080        self
1081    }
1082
1083    fn try_apply(&mut self, value: &dyn Reflect) -> Result<(), ApplyError> {
1084        let any = value.as_any();
1085        if let Some(value) = any.downcast_ref::<Self>() {
1086            self.clone_from(value);
1087        } else {
1088            return Err(ApplyError::MismatchedTypes {
1089                from_type: value.reflect_type_path().into(),
1090                // If we invoke the reflect_type_path on self directly the borrow checker complains that the lifetime of self must outlive 'static
1091                to_type: Self::type_path().into(),
1092            });
1093        }
1094        Ok(())
1095    }
1096
1097    fn set(&mut self, value: Box<dyn Reflect>) -> Result<(), Box<dyn Reflect>> {
1098        *self = value.take()?;
1099        Ok(())
1100    }
1101
1102    fn reflect_kind(&self) -> ReflectKind {
1103        ReflectKind::Value
1104    }
1105
1106    fn reflect_ref(&self) -> ReflectRef {
1107        ReflectRef::Value(self)
1108    }
1109
1110    fn reflect_mut(&mut self) -> ReflectMut {
1111        ReflectMut::Value(self)
1112    }
1113
1114    fn reflect_owned(self: Box<Self>) -> ReflectOwned {
1115        ReflectOwned::Value(self)
1116    }
1117
1118    fn clone_value(&self) -> Box<dyn Reflect> {
1119        Box::new(self.clone())
1120    }
1121
1122    fn reflect_hash(&self) -> Option<u64> {
1123        let mut hasher = reflect_hasher();
1124        Hash::hash(&std::any::Any::type_id(self), &mut hasher);
1125        Hash::hash(self, &mut hasher);
1126        Some(hasher.finish())
1127    }
1128
1129    fn reflect_partial_eq(&self, value: &dyn Reflect) -> Option<bool> {
1130        let value = value.as_any();
1131        if let Some(value) = value.downcast_ref::<Self>() {
1132            Some(std::cmp::PartialEq::eq(self, value))
1133        } else {
1134            Some(false)
1135        }
1136    }
1137
1138    fn debug(&self, f: &mut fmt::Formatter<'_>) -> core::fmt::Result {
1139        fmt::Debug::fmt(self, f)
1140    }
1141}
1142
1143impl Typed for Cow<'static, str> {
1144    fn type_info() -> &'static TypeInfo {
1145        static CELL: NonGenericTypeInfoCell = NonGenericTypeInfoCell::new();
1146        CELL.get_or_set(|| TypeInfo::Value(ValueInfo::new::<Self>()))
1147    }
1148}
1149
1150impl GetTypeRegistration for Cow<'static, str> {
1151    fn get_type_registration() -> TypeRegistration {
1152        let mut registration = TypeRegistration::of::<Cow<'static, str>>();
1153        registration.insert::<ReflectDeserialize>(FromType::<Cow<'static, str>>::from_type());
1154        registration.insert::<ReflectFromPtr>(FromType::<Cow<'static, str>>::from_type());
1155        registration.insert::<ReflectSerialize>(FromType::<Cow<'static, str>>::from_type());
1156        registration
1157    }
1158}
1159
1160impl FromReflect for Cow<'static, str> {
1161    fn from_reflect(reflect: &dyn crate::Reflect) -> Option<Self> {
1162        Some(
1163            reflect
1164                .as_any()
1165                .downcast_ref::<Cow<'static, str>>()?
1166                .clone(),
1167        )
1168    }
1169}
1170
1171impl<T: TypePath> TypePath for [T]
1172where
1173    [T]: ToOwned,
1174{
1175    fn type_path() -> &'static str {
1176        static CELL: GenericTypePathCell = GenericTypePathCell::new();
1177        CELL.get_or_insert::<Self, _>(|| format!("[{}]", <T>::type_path()))
1178    }
1179
1180    fn short_type_path() -> &'static str {
1181        static CELL: GenericTypePathCell = GenericTypePathCell::new();
1182        CELL.get_or_insert::<Self, _>(|| format!("[{}]", <T>::short_type_path()))
1183    }
1184}
1185
1186impl<T: FromReflect + Clone + TypePath + GetTypeRegistration> List for Cow<'static, [T]> {
1187    fn get(&self, index: usize) -> Option<&dyn Reflect> {
1188        self.as_ref().get(index).map(|x| x as &dyn Reflect)
1189    }
1190
1191    fn get_mut(&mut self, index: usize) -> Option<&mut dyn Reflect> {
1192        self.to_mut().get_mut(index).map(|x| x as &mut dyn Reflect)
1193    }
1194
1195    fn insert(&mut self, index: usize, element: Box<dyn Reflect>) {
1196        let value = element.take::<T>().unwrap_or_else(|value| {
1197            T::from_reflect(&*value).unwrap_or_else(|| {
1198                panic!(
1199                    "Attempted to insert invalid value of type {}.",
1200                    value.reflect_type_path()
1201                )
1202            })
1203        });
1204        self.to_mut().insert(index, value);
1205    }
1206
1207    fn remove(&mut self, index: usize) -> Box<dyn Reflect> {
1208        Box::new(self.to_mut().remove(index))
1209    }
1210
1211    fn push(&mut self, value: Box<dyn Reflect>) {
1212        let value = T::take_from_reflect(value).unwrap_or_else(|value| {
1213            panic!(
1214                "Attempted to push invalid value of type {}.",
1215                value.reflect_type_path()
1216            )
1217        });
1218        self.to_mut().push(value);
1219    }
1220
1221    fn pop(&mut self) -> Option<Box<dyn Reflect>> {
1222        self.to_mut()
1223            .pop()
1224            .map(|value| Box::new(value) as Box<dyn Reflect>)
1225    }
1226
1227    fn len(&self) -> usize {
1228        self.as_ref().len()
1229    }
1230
1231    fn iter(&self) -> ListIter {
1232        ListIter::new(self)
1233    }
1234
1235    fn drain(self: Box<Self>) -> Vec<Box<dyn Reflect>> {
1236        // into_owned() is not unnecessary here because it avoids cloning whenever you have a Cow::Owned already
1237        #[allow(clippy::unnecessary_to_owned)]
1238        self.into_owned()
1239            .into_iter()
1240            .map(|value| value.clone_value())
1241            .collect()
1242    }
1243}
1244
1245impl<T: FromReflect + Clone + TypePath + GetTypeRegistration> Reflect for Cow<'static, [T]> {
1246    fn get_represented_type_info(&self) -> Option<&'static TypeInfo> {
1247        Some(<Self as Typed>::type_info())
1248    }
1249
1250    fn into_any(self: Box<Self>) -> Box<dyn Any> {
1251        self
1252    }
1253
1254    fn as_any(&self) -> &dyn Any {
1255        self
1256    }
1257
1258    fn as_any_mut(&mut self) -> &mut dyn Any {
1259        self
1260    }
1261
1262    fn into_reflect(self: Box<Self>) -> Box<dyn Reflect> {
1263        self
1264    }
1265
1266    fn as_reflect(&self) -> &dyn Reflect {
1267        self
1268    }
1269
1270    fn as_reflect_mut(&mut self) -> &mut dyn Reflect {
1271        self
1272    }
1273
1274    fn apply(&mut self, value: &dyn Reflect) {
1275        crate::list_apply(self, value);
1276    }
1277
1278    fn try_apply(&mut self, value: &dyn Reflect) -> Result<(), ApplyError> {
1279        crate::list_try_apply(self, value)
1280    }
1281
1282    fn set(&mut self, value: Box<dyn Reflect>) -> Result<(), Box<dyn Reflect>> {
1283        *self = value.take()?;
1284        Ok(())
1285    }
1286
1287    fn reflect_kind(&self) -> ReflectKind {
1288        ReflectKind::List
1289    }
1290
1291    fn reflect_ref(&self) -> ReflectRef {
1292        ReflectRef::List(self)
1293    }
1294
1295    fn reflect_mut(&mut self) -> ReflectMut {
1296        ReflectMut::List(self)
1297    }
1298
1299    fn reflect_owned(self: Box<Self>) -> ReflectOwned {
1300        ReflectOwned::List(self)
1301    }
1302
1303    fn clone_value(&self) -> Box<dyn Reflect> {
1304        Box::new(List::clone_dynamic(self))
1305    }
1306
1307    fn reflect_hash(&self) -> Option<u64> {
1308        crate::list_hash(self)
1309    }
1310
1311    fn reflect_partial_eq(&self, value: &dyn Reflect) -> Option<bool> {
1312        crate::list_partial_eq(self, value)
1313    }
1314}
1315
1316impl<T: FromReflect + Clone + TypePath + GetTypeRegistration> Typed for Cow<'static, [T]> {
1317    fn type_info() -> &'static TypeInfo {
1318        static CELL: GenericTypeInfoCell = GenericTypeInfoCell::new();
1319        CELL.get_or_insert::<Self, _>(|| TypeInfo::List(ListInfo::new::<Self, T>()))
1320    }
1321}
1322
1323impl<T: FromReflect + Clone + TypePath + GetTypeRegistration> GetTypeRegistration
1324    for Cow<'static, [T]>
1325{
1326    fn get_type_registration() -> TypeRegistration {
1327        TypeRegistration::of::<Cow<'static, [T]>>()
1328    }
1329
1330    fn register_type_dependencies(registry: &mut TypeRegistry) {
1331        registry.register::<T>();
1332    }
1333}
1334
1335impl<T: FromReflect + Clone + TypePath + GetTypeRegistration> FromReflect for Cow<'static, [T]> {
1336    fn from_reflect(reflect: &dyn Reflect) -> Option<Self> {
1337        if let ReflectRef::List(ref_list) = reflect.reflect_ref() {
1338            let mut temp_vec = Vec::with_capacity(ref_list.len());
1339            for field in ref_list.iter() {
1340                temp_vec.push(T::from_reflect(field)?);
1341            }
1342            Some(temp_vec.into())
1343        } else {
1344            None
1345        }
1346    }
1347}
1348
1349impl Reflect for &'static str {
1350    fn get_represented_type_info(&self) -> Option<&'static TypeInfo> {
1351        Some(<Self as Typed>::type_info())
1352    }
1353
1354    fn into_any(self: Box<Self>) -> Box<dyn Any> {
1355        self
1356    }
1357
1358    fn as_any(&self) -> &dyn Any {
1359        self
1360    }
1361
1362    fn as_any_mut(&mut self) -> &mut dyn Any {
1363        self
1364    }
1365
1366    fn into_reflect(self: Box<Self>) -> Box<dyn Reflect> {
1367        self
1368    }
1369
1370    fn as_reflect(&self) -> &dyn Reflect {
1371        self
1372    }
1373
1374    fn as_reflect_mut(&mut self) -> &mut dyn Reflect {
1375        self
1376    }
1377
1378    fn try_apply(&mut self, value: &dyn Reflect) -> Result<(), ApplyError> {
1379        let any = value.as_any();
1380        if let Some(&value) = any.downcast_ref::<Self>() {
1381            *self = value;
1382        } else {
1383            return Err(ApplyError::MismatchedTypes {
1384                from_type: value.reflect_type_path().into(),
1385                to_type: Self::type_path().into(),
1386            });
1387        }
1388        Ok(())
1389    }
1390
1391    fn set(&mut self, value: Box<dyn Reflect>) -> Result<(), Box<dyn Reflect>> {
1392        *self = value.take()?;
1393        Ok(())
1394    }
1395
1396    fn reflect_ref(&self) -> ReflectRef {
1397        ReflectRef::Value(self)
1398    }
1399
1400    fn reflect_mut(&mut self) -> ReflectMut {
1401        ReflectMut::Value(self)
1402    }
1403
1404    fn reflect_owned(self: Box<Self>) -> ReflectOwned {
1405        ReflectOwned::Value(self)
1406    }
1407
1408    fn clone_value(&self) -> Box<dyn Reflect> {
1409        Box::new(*self)
1410    }
1411
1412    fn reflect_hash(&self) -> Option<u64> {
1413        let mut hasher = reflect_hasher();
1414        Hash::hash(&std::any::Any::type_id(self), &mut hasher);
1415        Hash::hash(self, &mut hasher);
1416        Some(hasher.finish())
1417    }
1418
1419    fn reflect_partial_eq(&self, value: &dyn Reflect) -> Option<bool> {
1420        let value = value.as_any();
1421        if let Some(value) = value.downcast_ref::<Self>() {
1422            Some(std::cmp::PartialEq::eq(self, value))
1423        } else {
1424            Some(false)
1425        }
1426    }
1427
1428    fn debug(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1429        fmt::Debug::fmt(&self, f)
1430    }
1431}
1432
1433impl Typed for &'static str {
1434    fn type_info() -> &'static TypeInfo {
1435        static CELL: NonGenericTypeInfoCell = NonGenericTypeInfoCell::new();
1436        CELL.get_or_set(|| TypeInfo::Value(ValueInfo::new::<Self>()))
1437    }
1438}
1439
1440impl GetTypeRegistration for &'static str {
1441    fn get_type_registration() -> TypeRegistration {
1442        let mut registration = TypeRegistration::of::<Self>();
1443        registration.insert::<ReflectFromPtr>(FromType::<Self>::from_type());
1444        registration.insert::<ReflectFromReflect>(FromType::<Self>::from_type());
1445        registration
1446    }
1447}
1448
1449impl FromReflect for &'static str {
1450    fn from_reflect(reflect: &dyn crate::Reflect) -> Option<Self> {
1451        reflect.as_any().downcast_ref::<Self>().copied()
1452    }
1453}
1454
1455impl Reflect for &'static Path {
1456    fn get_represented_type_info(&self) -> Option<&'static TypeInfo> {
1457        Some(<Self as Typed>::type_info())
1458    }
1459
1460    fn into_any(self: Box<Self>) -> Box<dyn Any> {
1461        self
1462    }
1463
1464    fn as_any(&self) -> &dyn Any {
1465        self
1466    }
1467
1468    fn as_any_mut(&mut self) -> &mut dyn Any {
1469        self
1470    }
1471
1472    fn into_reflect(self: Box<Self>) -> Box<dyn Reflect> {
1473        self
1474    }
1475
1476    fn as_reflect(&self) -> &dyn Reflect {
1477        self
1478    }
1479
1480    fn as_reflect_mut(&mut self) -> &mut dyn Reflect {
1481        self
1482    }
1483
1484    fn try_apply(&mut self, value: &dyn Reflect) -> Result<(), ApplyError> {
1485        let any = value.as_any();
1486        if let Some(&value) = any.downcast_ref::<Self>() {
1487            *self = value;
1488            Ok(())
1489        } else {
1490            Err(ApplyError::MismatchedTypes {
1491                from_type: value.reflect_type_path().into(),
1492                to_type: <Self as DynamicTypePath>::reflect_type_path(self).into(),
1493            })
1494        }
1495    }
1496
1497    fn set(&mut self, value: Box<dyn Reflect>) -> Result<(), Box<dyn Reflect>> {
1498        *self = value.take()?;
1499        Ok(())
1500    }
1501
1502    fn reflect_kind(&self) -> ReflectKind {
1503        ReflectKind::Value
1504    }
1505
1506    fn reflect_ref(&self) -> ReflectRef {
1507        ReflectRef::Value(self)
1508    }
1509
1510    fn reflect_mut(&mut self) -> ReflectMut {
1511        ReflectMut::Value(self)
1512    }
1513
1514    fn reflect_owned(self: Box<Self>) -> ReflectOwned {
1515        ReflectOwned::Value(self)
1516    }
1517
1518    fn clone_value(&self) -> Box<dyn Reflect> {
1519        Box::new(*self)
1520    }
1521
1522    fn reflect_hash(&self) -> Option<u64> {
1523        let mut hasher = reflect_hasher();
1524        Hash::hash(&std::any::Any::type_id(self), &mut hasher);
1525        Hash::hash(self, &mut hasher);
1526        Some(hasher.finish())
1527    }
1528
1529    fn reflect_partial_eq(&self, value: &dyn Reflect) -> Option<bool> {
1530        let value = value.as_any();
1531        if let Some(value) = value.downcast_ref::<Self>() {
1532            Some(std::cmp::PartialEq::eq(self, value))
1533        } else {
1534            Some(false)
1535        }
1536    }
1537}
1538
1539impl Typed for &'static Path {
1540    fn type_info() -> &'static TypeInfo {
1541        static CELL: NonGenericTypeInfoCell = NonGenericTypeInfoCell::new();
1542        CELL.get_or_set(|| TypeInfo::Value(ValueInfo::new::<Self>()))
1543    }
1544}
1545
1546impl GetTypeRegistration for &'static Path {
1547    fn get_type_registration() -> TypeRegistration {
1548        let mut registration = TypeRegistration::of::<Self>();
1549        registration.insert::<ReflectFromPtr>(FromType::<Self>::from_type());
1550        registration
1551    }
1552}
1553
1554impl FromReflect for &'static Path {
1555    fn from_reflect(reflect: &dyn crate::Reflect) -> Option<Self> {
1556        reflect.as_any().downcast_ref::<Self>().copied()
1557    }
1558}
1559
1560impl Reflect for Cow<'static, Path> {
1561    fn get_represented_type_info(&self) -> Option<&'static TypeInfo> {
1562        Some(<Self as Typed>::type_info())
1563    }
1564
1565    fn into_any(self: Box<Self>) -> Box<dyn Any> {
1566        self
1567    }
1568
1569    fn as_any(&self) -> &dyn Any {
1570        self
1571    }
1572
1573    fn as_any_mut(&mut self) -> &mut dyn Any {
1574        self
1575    }
1576
1577    fn into_reflect(self: Box<Self>) -> Box<dyn Reflect> {
1578        self
1579    }
1580
1581    fn as_reflect(&self) -> &dyn Reflect {
1582        self
1583    }
1584
1585    fn as_reflect_mut(&mut self) -> &mut dyn Reflect {
1586        self
1587    }
1588
1589    fn try_apply(&mut self, value: &dyn Reflect) -> Result<(), ApplyError> {
1590        let any = value.as_any();
1591        if let Some(value) = any.downcast_ref::<Self>() {
1592            self.clone_from(value);
1593            Ok(())
1594        } else {
1595            Err(ApplyError::MismatchedTypes {
1596                from_type: value.reflect_type_path().into(),
1597                to_type: <Self as DynamicTypePath>::reflect_type_path(self).into(),
1598            })
1599        }
1600    }
1601
1602    fn set(&mut self, value: Box<dyn Reflect>) -> Result<(), Box<dyn Reflect>> {
1603        *self = value.take()?;
1604        Ok(())
1605    }
1606
1607    fn reflect_kind(&self) -> ReflectKind {
1608        ReflectKind::Value
1609    }
1610
1611    fn reflect_ref(&self) -> ReflectRef {
1612        ReflectRef::Value(self)
1613    }
1614
1615    fn reflect_mut(&mut self) -> ReflectMut {
1616        ReflectMut::Value(self)
1617    }
1618
1619    fn reflect_owned(self: Box<Self>) -> ReflectOwned {
1620        ReflectOwned::Value(self)
1621    }
1622
1623    fn clone_value(&self) -> Box<dyn Reflect> {
1624        Box::new(self.clone())
1625    }
1626
1627    fn reflect_hash(&self) -> Option<u64> {
1628        let mut hasher = reflect_hasher();
1629        Hash::hash(&std::any::Any::type_id(self), &mut hasher);
1630        Hash::hash(self, &mut hasher);
1631        Some(hasher.finish())
1632    }
1633
1634    fn reflect_partial_eq(&self, value: &dyn Reflect) -> Option<bool> {
1635        let value = value.as_any();
1636        if let Some(value) = value.downcast_ref::<Self>() {
1637            Some(std::cmp::PartialEq::eq(self, value))
1638        } else {
1639            Some(false)
1640        }
1641    }
1642
1643    fn debug(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1644        fmt::Debug::fmt(&self, f)
1645    }
1646}
1647
1648impl Typed for Cow<'static, Path> {
1649    fn type_info() -> &'static TypeInfo {
1650        static CELL: NonGenericTypeInfoCell = NonGenericTypeInfoCell::new();
1651        CELL.get_or_set(|| TypeInfo::Value(ValueInfo::new::<Self>()))
1652    }
1653}
1654
1655impl_type_path!(::std::path::Path);
1656impl_type_path!(::alloc::borrow::Cow<'a: 'static, T: ToOwned + ?Sized>);
1657
1658impl FromReflect for Cow<'static, Path> {
1659    fn from_reflect(reflect: &dyn Reflect) -> Option<Self> {
1660        Some(reflect.as_any().downcast_ref::<Self>()?.clone())
1661    }
1662}
1663
1664impl GetTypeRegistration for Cow<'static, Path> {
1665    fn get_type_registration() -> TypeRegistration {
1666        let mut registration = TypeRegistration::of::<Self>();
1667        registration.insert::<ReflectDeserialize>(FromType::<Self>::from_type());
1668        registration.insert::<ReflectFromPtr>(FromType::<Self>::from_type());
1669        registration.insert::<ReflectSerialize>(FromType::<Self>::from_type());
1670        registration.insert::<ReflectFromReflect>(FromType::<Self>::from_type());
1671        registration
1672    }
1673}
1674
1675#[cfg(test)]
1676mod tests {
1677    use crate as bevy_reflect;
1678    use crate::{
1679        Enum, FromReflect, Reflect, ReflectSerialize, TypeInfo, TypeRegistry, Typed, VariantInfo,
1680        VariantType,
1681    };
1682    use bevy_utils::HashMap;
1683    use bevy_utils::{Duration, Instant};
1684    use static_assertions::assert_impl_all;
1685    use std::collections::BTreeMap;
1686    use std::f32::consts::{PI, TAU};
1687    use std::path::Path;
1688
1689    #[test]
1690    fn can_serialize_duration() {
1691        let mut type_registry = TypeRegistry::default();
1692        type_registry.register::<Duration>();
1693
1694        let reflect_serialize = type_registry
1695            .get_type_data::<ReflectSerialize>(std::any::TypeId::of::<Duration>())
1696            .unwrap();
1697        let _serializable = reflect_serialize.get_serializable(&Duration::ZERO);
1698    }
1699
1700    #[test]
1701    fn should_partial_eq_char() {
1702        let a: &dyn Reflect = &'x';
1703        let b: &dyn Reflect = &'x';
1704        let c: &dyn Reflect = &'o';
1705        assert!(a.reflect_partial_eq(b).unwrap_or_default());
1706        assert!(!a.reflect_partial_eq(c).unwrap_or_default());
1707    }
1708
1709    #[test]
1710    fn should_partial_eq_i32() {
1711        let a: &dyn Reflect = &123_i32;
1712        let b: &dyn Reflect = &123_i32;
1713        let c: &dyn Reflect = &321_i32;
1714        assert!(a.reflect_partial_eq(b).unwrap_or_default());
1715        assert!(!a.reflect_partial_eq(c).unwrap_or_default());
1716    }
1717
1718    #[test]
1719    fn should_partial_eq_f32() {
1720        let a: &dyn Reflect = &PI;
1721        let b: &dyn Reflect = &PI;
1722        let c: &dyn Reflect = &TAU;
1723        assert!(a.reflect_partial_eq(b).unwrap_or_default());
1724        assert!(!a.reflect_partial_eq(c).unwrap_or_default());
1725    }
1726
1727    #[test]
1728    fn should_partial_eq_string() {
1729        let a: &dyn Reflect = &String::from("Hello");
1730        let b: &dyn Reflect = &String::from("Hello");
1731        let c: &dyn Reflect = &String::from("World");
1732        assert!(a.reflect_partial_eq(b).unwrap_or_default());
1733        assert!(!a.reflect_partial_eq(c).unwrap_or_default());
1734    }
1735
1736    #[test]
1737    fn should_partial_eq_vec() {
1738        let a: &dyn Reflect = &vec![1, 2, 3];
1739        let b: &dyn Reflect = &vec![1, 2, 3];
1740        let c: &dyn Reflect = &vec![3, 2, 1];
1741        assert!(a.reflect_partial_eq(b).unwrap_or_default());
1742        assert!(!a.reflect_partial_eq(c).unwrap_or_default());
1743    }
1744
1745    #[test]
1746    fn should_partial_eq_hash_map() {
1747        let mut a = HashMap::new();
1748        a.insert(0usize, 1.23_f64);
1749        let b = a.clone();
1750        let mut c = HashMap::new();
1751        c.insert(0usize, 3.21_f64);
1752
1753        let a: &dyn Reflect = &a;
1754        let b: &dyn Reflect = &b;
1755        let c: &dyn Reflect = &c;
1756        assert!(a.reflect_partial_eq(b).unwrap_or_default());
1757        assert!(!a.reflect_partial_eq(c).unwrap_or_default());
1758    }
1759
1760    #[test]
1761    fn should_partial_eq_btree_map() {
1762        let mut a = BTreeMap::new();
1763        a.insert(0usize, 1.23_f64);
1764        let b = a.clone();
1765        let mut c = BTreeMap::new();
1766        c.insert(0usize, 3.21_f64);
1767
1768        let a: &dyn Reflect = &a;
1769        let b: &dyn Reflect = &b;
1770        let c: &dyn Reflect = &c;
1771        assert!(a.reflect_partial_eq(b).unwrap_or_default());
1772        assert!(!a.reflect_partial_eq(c).unwrap_or_default());
1773    }
1774
1775    #[test]
1776    fn should_partial_eq_option() {
1777        let a: &dyn Reflect = &Some(123);
1778        let b: &dyn Reflect = &Some(123);
1779        assert_eq!(Some(true), a.reflect_partial_eq(b));
1780    }
1781
1782    #[test]
1783    fn option_should_impl_enum() {
1784        assert_impl_all!(Option<()>: Enum);
1785
1786        let mut value = Some(123usize);
1787
1788        assert!(value
1789            .reflect_partial_eq(&Some(123usize))
1790            .unwrap_or_default());
1791        assert!(!value
1792            .reflect_partial_eq(&Some(321usize))
1793            .unwrap_or_default());
1794
1795        assert_eq!("Some", value.variant_name());
1796        assert_eq!("core::option::Option<usize>::Some", value.variant_path());
1797
1798        if value.is_variant(VariantType::Tuple) {
1799            if let Some(field) = value
1800                .field_at_mut(0)
1801                .and_then(|field| field.downcast_mut::<usize>())
1802            {
1803                *field = 321;
1804            }
1805        } else {
1806            panic!("expected `VariantType::Tuple`");
1807        }
1808
1809        assert_eq!(Some(321), value);
1810    }
1811
1812    #[test]
1813    fn option_should_from_reflect() {
1814        #[derive(Reflect, PartialEq, Debug)]
1815        struct Foo(usize);
1816
1817        let expected = Some(Foo(123));
1818        let output = <Option<Foo> as FromReflect>::from_reflect(&expected).unwrap();
1819
1820        assert_eq!(expected, output);
1821    }
1822
1823    #[test]
1824    fn option_should_apply() {
1825        #[derive(Reflect, PartialEq, Debug)]
1826        struct Foo(usize);
1827
1828        // === None on None === //
1829        let patch = None::<Foo>;
1830        let mut value = None::<Foo>;
1831        Reflect::apply(&mut value, &patch);
1832
1833        assert_eq!(patch, value, "None apply onto None");
1834
1835        // === Some on None === //
1836        let patch = Some(Foo(123));
1837        let mut value = None::<Foo>;
1838        Reflect::apply(&mut value, &patch);
1839
1840        assert_eq!(patch, value, "Some apply onto None");
1841
1842        // === None on Some === //
1843        let patch = None::<Foo>;
1844        let mut value = Some(Foo(321));
1845        Reflect::apply(&mut value, &patch);
1846
1847        assert_eq!(patch, value, "None apply onto Some");
1848
1849        // === Some on Some === //
1850        let patch = Some(Foo(123));
1851        let mut value = Some(Foo(321));
1852        Reflect::apply(&mut value, &patch);
1853
1854        assert_eq!(patch, value, "Some apply onto Some");
1855    }
1856
1857    #[test]
1858    fn option_should_impl_typed() {
1859        assert_impl_all!(Option<()>: Typed);
1860
1861        type MyOption = Option<i32>;
1862        let info = MyOption::type_info();
1863        if let TypeInfo::Enum(info) = info {
1864            assert_eq!(
1865                "None",
1866                info.variant_at(0).unwrap().name(),
1867                "Expected `None` to be variant at index `0`"
1868            );
1869            assert_eq!(
1870                "Some",
1871                info.variant_at(1).unwrap().name(),
1872                "Expected `Some` to be variant at index `1`"
1873            );
1874            assert_eq!("Some", info.variant("Some").unwrap().name());
1875            if let VariantInfo::Tuple(variant) = info.variant("Some").unwrap() {
1876                assert!(
1877                    variant.field_at(0).unwrap().is::<i32>(),
1878                    "Expected `Some` variant to contain `i32`"
1879                );
1880                assert!(
1881                    variant.field_at(1).is_none(),
1882                    "Expected `Some` variant to only contain 1 field"
1883                );
1884            } else {
1885                panic!("Expected `VariantInfo::Tuple`");
1886            }
1887        } else {
1888            panic!("Expected `TypeInfo::Enum`");
1889        }
1890    }
1891
1892    #[test]
1893    fn nonzero_usize_impl_reflect_from_reflect() {
1894        let a: &dyn Reflect = &std::num::NonZeroUsize::new(42).unwrap();
1895        let b: &dyn Reflect = &std::num::NonZeroUsize::new(42).unwrap();
1896        assert!(a.reflect_partial_eq(b).unwrap_or_default());
1897        let forty_two: std::num::NonZeroUsize = crate::FromReflect::from_reflect(a).unwrap();
1898        assert_eq!(forty_two, std::num::NonZeroUsize::new(42).unwrap());
1899    }
1900
1901    #[test]
1902    fn instant_should_from_reflect() {
1903        let expected = Instant::now();
1904        let output = <Instant as FromReflect>::from_reflect(&expected).unwrap();
1905        assert_eq!(expected, output);
1906    }
1907
1908    #[test]
1909    fn path_should_from_reflect() {
1910        let path = Path::new("hello_world.rs");
1911        let output = <&'static Path as FromReflect>::from_reflect(&path).unwrap();
1912        assert_eq!(path, output);
1913    }
1914
1915    #[test]
1916    fn type_id_should_from_reflect() {
1917        let type_id = std::any::TypeId::of::<usize>();
1918        let output = <std::any::TypeId as FromReflect>::from_reflect(&type_id).unwrap();
1919        assert_eq!(type_id, output);
1920    }
1921
1922    #[test]
1923    fn static_str_should_from_reflect() {
1924        let expected = "Hello, World!";
1925        let output = <&'static str as FromReflect>::from_reflect(&expected).unwrap();
1926        assert_eq!(expected, output);
1927    }
1928}