1use core::fmt::{Debug, Formatter};
2
3use bevy_reflect_derive::impl_type_path;
4use bevy_utils::hashbrown::HashTable;
5
6use crate::generics::impl_generic_info_methods;
7use crate::{
8 self as bevy_reflect, type_info::impl_type_methods, ApplyError, Generics, MaybeTyped,
9 PartialReflect, Reflect, ReflectKind, ReflectMut, ReflectOwned, ReflectRef, Type, TypeInfo,
10 TypePath,
11};
12
13pub trait Map: PartialReflect {
49 fn get(&self, key: &dyn PartialReflect) -> Option<&dyn PartialReflect>;
53
54 fn get_mut(&mut self, key: &dyn PartialReflect) -> Option<&mut dyn PartialReflect>;
58
59 fn get_at(&self, index: usize) -> Option<(&dyn PartialReflect, &dyn PartialReflect)>;
61
62 fn get_at_mut(
64 &mut self,
65 index: usize,
66 ) -> Option<(&dyn PartialReflect, &mut dyn PartialReflect)>;
67
68 fn len(&self) -> usize;
70
71 fn is_empty(&self) -> bool {
73 self.len() == 0
74 }
75
76 fn iter(&self) -> MapIter;
78
79 fn drain(&mut self) -> Vec<(Box<dyn PartialReflect>, Box<dyn PartialReflect>)>;
83
84 fn clone_dynamic(&self) -> DynamicMap;
86
87 fn insert_boxed(
92 &mut self,
93 key: Box<dyn PartialReflect>,
94 value: Box<dyn PartialReflect>,
95 ) -> Option<Box<dyn PartialReflect>>;
96
97 fn remove(&mut self, key: &dyn PartialReflect) -> Option<Box<dyn PartialReflect>>;
102
103 fn get_represented_map_info(&self) -> Option<&'static MapInfo> {
105 self.get_represented_type_info()?.as_map().ok()
106 }
107}
108
109#[derive(Clone, Debug)]
111pub struct MapInfo {
112 ty: Type,
113 generics: Generics,
114 key_info: fn() -> Option<&'static TypeInfo>,
115 key_ty: Type,
116 value_info: fn() -> Option<&'static TypeInfo>,
117 value_ty: Type,
118 #[cfg(feature = "documentation")]
119 docs: Option<&'static str>,
120}
121
122impl MapInfo {
123 pub fn new<
125 TMap: Map + TypePath,
126 TKey: Reflect + MaybeTyped + TypePath,
127 TValue: Reflect + MaybeTyped + TypePath,
128 >() -> Self {
129 Self {
130 ty: Type::of::<TMap>(),
131 generics: Generics::new(),
132 key_info: TKey::maybe_type_info,
133 key_ty: Type::of::<TKey>(),
134 value_info: TValue::maybe_type_info,
135 value_ty: Type::of::<TValue>(),
136 #[cfg(feature = "documentation")]
137 docs: None,
138 }
139 }
140
141 #[cfg(feature = "documentation")]
143 pub fn with_docs(self, docs: Option<&'static str>) -> Self {
144 Self { docs, ..self }
145 }
146
147 impl_type_methods!(ty);
148
149 pub fn key_info(&self) -> Option<&'static TypeInfo> {
154 (self.key_info)()
155 }
156
157 pub fn key_ty(&self) -> Type {
161 self.key_ty
162 }
163
164 pub fn value_info(&self) -> Option<&'static TypeInfo> {
169 (self.value_info)()
170 }
171
172 pub fn value_ty(&self) -> Type {
176 self.value_ty
177 }
178
179 #[cfg(feature = "documentation")]
181 pub fn docs(&self) -> Option<&'static str> {
182 self.docs
183 }
184
185 impl_generic_info_methods!(generics);
186}
187
188#[macro_export]
189macro_rules! hash_error {
190 ( $key:expr ) => {{
191 let type_path = (*$key).reflect_type_path();
192 if !$key.is_dynamic() {
193 format!(
194 "the given key of type `{}` does not support hashing",
195 type_path
196 )
197 } else {
198 match (*$key).get_represented_type_info() {
199 None => format!("the dynamic type `{}` does not support hashing", type_path),
201 Some(s) => format!(
203 "the dynamic type `{}` (representing `{}`) does not support hashing",
204 type_path,
205 s.type_path()
206 ),
207 }
208 }
209 .as_str()
210 }}
211}
212
213#[derive(Default)]
215pub struct DynamicMap {
216 represented_type: Option<&'static TypeInfo>,
217 values: Vec<(Box<dyn PartialReflect>, Box<dyn PartialReflect>)>,
218 indices: HashTable<usize>,
219}
220
221impl DynamicMap {
222 pub fn set_represented_type(&mut self, represented_type: Option<&'static TypeInfo>) {
230 if let Some(represented_type) = represented_type {
231 assert!(
232 matches!(represented_type, TypeInfo::Map(_)),
233 "expected TypeInfo::Map but received: {:?}",
234 represented_type
235 );
236 }
237
238 self.represented_type = represented_type;
239 }
240
241 pub fn insert<K: PartialReflect, V: PartialReflect>(&mut self, key: K, value: V) {
243 self.insert_boxed(Box::new(key), Box::new(value));
244 }
245
246 fn internal_hash(value: &dyn PartialReflect) -> u64 {
247 value.reflect_hash().expect(hash_error!(value))
248 }
249
250 fn internal_eq<'a>(
251 value: &'a dyn PartialReflect,
252 values: &'a [(Box<dyn PartialReflect>, Box<dyn PartialReflect>)],
253 ) -> impl FnMut(&usize) -> bool + 'a {
254 |&index| {
255 value
256 .reflect_partial_eq(&*values[index].0)
257 .expect("underlying type does not reflect `PartialEq` and hence doesn't support equality checks")
258 }
259 }
260}
261
262impl Map for DynamicMap {
263 fn get(&self, key: &dyn PartialReflect) -> Option<&dyn PartialReflect> {
264 let hash = Self::internal_hash(key);
265 let eq = Self::internal_eq(key, &self.values);
266 self.indices
267 .find(hash, eq)
268 .map(|&index| &*self.values[index].1)
269 }
270
271 fn get_mut(&mut self, key: &dyn PartialReflect) -> Option<&mut dyn PartialReflect> {
272 let hash = Self::internal_hash(key);
273 let eq = Self::internal_eq(key, &self.values);
274 self.indices
275 .find(hash, eq)
276 .map(|&index| &mut *self.values[index].1)
277 }
278
279 fn get_at(&self, index: usize) -> Option<(&dyn PartialReflect, &dyn PartialReflect)> {
280 self.values
281 .get(index)
282 .map(|(key, value)| (&**key, &**value))
283 }
284
285 fn get_at_mut(
286 &mut self,
287 index: usize,
288 ) -> Option<(&dyn PartialReflect, &mut dyn PartialReflect)> {
289 self.values
290 .get_mut(index)
291 .map(|(key, value)| (&**key, &mut **value))
292 }
293
294 fn len(&self) -> usize {
295 self.values.len()
296 }
297
298 fn iter(&self) -> MapIter {
299 MapIter::new(self)
300 }
301
302 fn drain(&mut self) -> Vec<(Box<dyn PartialReflect>, Box<dyn PartialReflect>)> {
303 self.values.drain(..).collect()
304 }
305
306 fn clone_dynamic(&self) -> DynamicMap {
307 DynamicMap {
308 represented_type: self.represented_type,
309 values: self
310 .values
311 .iter()
312 .map(|(key, value)| (key.clone_value(), value.clone_value()))
313 .collect(),
314 indices: self.indices.clone(),
315 }
316 }
317
318 fn insert_boxed(
319 &mut self,
320 key: Box<dyn PartialReflect>,
321 value: Box<dyn PartialReflect>,
322 ) -> Option<Box<dyn PartialReflect>> {
323 assert_eq!(
324 key.reflect_partial_eq(&*key),
325 Some(true),
326 "keys inserted in `Map`-like types are expected to reflect `PartialEq`"
327 );
328
329 let hash = Self::internal_hash(&*key);
330 let eq = Self::internal_eq(&*key, &self.values);
331 match self.indices.find(hash, eq) {
332 Some(&index) => {
333 let (key_ref, value_ref) = &mut self.values[index];
334 *key_ref = key;
335 let old_value = core::mem::replace(value_ref, value);
336 Some(old_value)
337 }
338 None => {
339 let index = self.values.len();
340 self.values.push((key, value));
341 self.indices.insert_unique(hash, index, |&index| {
342 Self::internal_hash(&*self.values[index].0)
343 });
344 None
345 }
346 }
347 }
348
349 fn remove(&mut self, key: &dyn PartialReflect) -> Option<Box<dyn PartialReflect>> {
350 let hash = Self::internal_hash(key);
351 let eq = Self::internal_eq(key, &self.values);
352 match self.indices.find_entry(hash, eq) {
353 Ok(entry) => {
354 let (index, _) = entry.remove();
355 let (_, old_value) = self.values.swap_remove(index);
356
357 if let Some((moved_key, _)) = self.values.get(index) {
363 let hash = Self::internal_hash(&**moved_key);
364 let moved_index = self
365 .indices
366 .find_mut(hash, |&moved_index| moved_index == self.values.len())
367 .expect("key inserted in a `DynamicMap` is no longer present, this means its reflected `Hash` might be incorrect");
368 *moved_index = index;
369 }
370
371 Some(old_value)
372 }
373 Err(_) => None,
374 }
375 }
376}
377
378impl PartialReflect for DynamicMap {
379 #[inline]
380 fn get_represented_type_info(&self) -> Option<&'static TypeInfo> {
381 self.represented_type
382 }
383
384 #[inline]
385 fn into_partial_reflect(self: Box<Self>) -> Box<dyn PartialReflect> {
386 self
387 }
388
389 #[inline]
390 fn as_partial_reflect(&self) -> &dyn PartialReflect {
391 self
392 }
393
394 #[inline]
395 fn as_partial_reflect_mut(&mut self) -> &mut dyn PartialReflect {
396 self
397 }
398
399 fn try_into_reflect(self: Box<Self>) -> Result<Box<dyn Reflect>, Box<dyn PartialReflect>> {
400 Err(self)
401 }
402
403 fn try_as_reflect(&self) -> Option<&dyn Reflect> {
404 None
405 }
406
407 fn try_as_reflect_mut(&mut self) -> Option<&mut dyn Reflect> {
408 None
409 }
410
411 fn apply(&mut self, value: &dyn PartialReflect) {
412 map_apply(self, value);
413 }
414
415 fn try_apply(&mut self, value: &dyn PartialReflect) -> Result<(), ApplyError> {
416 map_try_apply(self, value)
417 }
418
419 fn reflect_kind(&self) -> ReflectKind {
420 ReflectKind::Map
421 }
422
423 fn reflect_ref(&self) -> ReflectRef {
424 ReflectRef::Map(self)
425 }
426
427 fn reflect_mut(&mut self) -> ReflectMut {
428 ReflectMut::Map(self)
429 }
430
431 fn reflect_owned(self: Box<Self>) -> ReflectOwned {
432 ReflectOwned::Map(self)
433 }
434
435 fn clone_value(&self) -> Box<dyn PartialReflect> {
436 Box::new(self.clone_dynamic())
437 }
438
439 fn reflect_partial_eq(&self, value: &dyn PartialReflect) -> Option<bool> {
440 map_partial_eq(self, value)
441 }
442
443 fn debug(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
444 write!(f, "DynamicMap(")?;
445 map_debug(self, f)?;
446 write!(f, ")")
447 }
448
449 #[inline]
450 fn is_dynamic(&self) -> bool {
451 true
452 }
453}
454
455impl_type_path!((in bevy_reflect) DynamicMap);
456
457impl Debug for DynamicMap {
458 fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
459 self.debug(f)
460 }
461}
462
463pub struct MapIter<'a> {
465 map: &'a dyn Map,
466 index: usize,
467}
468
469impl MapIter<'_> {
470 #[inline]
472 pub const fn new(map: &dyn Map) -> MapIter {
473 MapIter { map, index: 0 }
474 }
475}
476
477impl<'a> Iterator for MapIter<'a> {
478 type Item = (&'a dyn PartialReflect, &'a dyn PartialReflect);
479
480 fn next(&mut self) -> Option<Self::Item> {
481 let value = self.map.get_at(self.index);
482 self.index += value.is_some() as usize;
483 value
484 }
485
486 fn size_hint(&self) -> (usize, Option<usize>) {
487 let size = self.map.len();
488 (size, Some(size))
489 }
490}
491
492impl FromIterator<(Box<dyn PartialReflect>, Box<dyn PartialReflect>)> for DynamicMap {
493 fn from_iter<I: IntoIterator<Item = (Box<dyn PartialReflect>, Box<dyn PartialReflect>)>>(
494 items: I,
495 ) -> Self {
496 let mut map = Self::default();
497 for (key, value) in items.into_iter() {
498 map.insert_boxed(key, value);
499 }
500 map
501 }
502}
503
504impl<K: Reflect, V: Reflect> FromIterator<(K, V)> for DynamicMap {
505 fn from_iter<I: IntoIterator<Item = (K, V)>>(items: I) -> Self {
506 let mut map = Self::default();
507 for (key, value) in items.into_iter() {
508 map.insert(key, value);
509 }
510 map
511 }
512}
513
514impl IntoIterator for DynamicMap {
515 type Item = (Box<dyn PartialReflect>, Box<dyn PartialReflect>);
516 type IntoIter = alloc::vec::IntoIter<Self::Item>;
517
518 fn into_iter(self) -> Self::IntoIter {
519 self.values.into_iter()
520 }
521}
522
523impl<'a> IntoIterator for &'a DynamicMap {
524 type Item = (&'a dyn PartialReflect, &'a dyn PartialReflect);
525 type IntoIter = MapIter<'a>;
526
527 fn into_iter(self) -> Self::IntoIter {
528 self.iter()
529 }
530}
531
532impl<'a> ExactSizeIterator for MapIter<'a> {}
533
534#[inline]
544pub fn map_partial_eq<M: Map + ?Sized>(a: &M, b: &dyn PartialReflect) -> Option<bool> {
545 let ReflectRef::Map(map) = b.reflect_ref() else {
546 return Some(false);
547 };
548
549 if a.len() != map.len() {
550 return Some(false);
551 }
552
553 for (key, value) in a.iter() {
554 if let Some(map_value) = map.get(key) {
555 let eq_result = value.reflect_partial_eq(map_value);
556 if let failed @ (Some(false) | None) = eq_result {
557 return failed;
558 }
559 } else {
560 return Some(false);
561 }
562 }
563
564 Some(true)
565}
566
567#[inline]
585pub fn map_debug(dyn_map: &dyn Map, f: &mut Formatter<'_>) -> core::fmt::Result {
586 let mut debug = f.debug_map();
587 for (key, value) in dyn_map.iter() {
588 debug.entry(&key as &dyn Debug, &value as &dyn Debug);
589 }
590 debug.finish()
591}
592
593#[inline]
601pub fn map_apply<M: Map>(a: &mut M, b: &dyn PartialReflect) {
602 if let Err(err) = map_try_apply(a, b) {
603 panic!("{err}");
604 }
605}
606
607#[inline]
617pub fn map_try_apply<M: Map>(a: &mut M, b: &dyn PartialReflect) -> Result<(), ApplyError> {
618 let map_value = b.reflect_ref().as_map()?;
619
620 for (key, b_value) in map_value.iter() {
621 if let Some(a_value) = a.get_mut(key) {
622 a_value.try_apply(b_value)?;
623 } else {
624 a.insert_boxed(key.clone_value(), b_value.clone_value());
625 }
626 }
627
628 Ok(())
629}
630
631#[cfg(test)]
632mod tests {
633 use super::{DynamicMap, Map};
634
635 #[test]
636 fn test_into_iter() {
637 let expected = ["foo", "bar", "baz"];
638
639 let mut map = DynamicMap::default();
640 map.insert(0usize, expected[0].to_string());
641 map.insert(1usize, expected[1].to_string());
642 map.insert(2usize, expected[2].to_string());
643
644 for (index, item) in map.into_iter().enumerate() {
645 let key = item
646 .0
647 .try_take::<usize>()
648 .expect("couldn't downcast to usize");
649 let value = item
650 .1
651 .try_take::<String>()
652 .expect("couldn't downcast to String");
653 assert_eq!(index, key);
654 assert_eq!(expected[index], value);
655 }
656 }
657
658 #[test]
659 fn test_map_get_at() {
660 let values = ["first", "second", "third"];
661 let mut map = DynamicMap::default();
662 map.insert(0usize, values[0].to_string());
663 map.insert(1usize, values[1].to_string());
664 map.insert(1usize, values[2].to_string());
665
666 let (key_r, value_r) = map.get_at(1).expect("Item wasn't found");
667 let value = value_r
668 .try_downcast_ref::<String>()
669 .expect("Couldn't downcast to String");
670 let key = key_r
671 .try_downcast_ref::<usize>()
672 .expect("Couldn't downcast to usize");
673 assert_eq!(key, &1usize);
674 assert_eq!(value, &values[2].to_owned());
675
676 assert!(map.get_at(2).is_none());
677 map.remove(&1usize);
678 assert!(map.get_at(1).is_none());
679 }
680
681 #[test]
682 fn test_map_get_at_mut() {
683 let values = ["first", "second", "third"];
684 let mut map = DynamicMap::default();
685 map.insert(0usize, values[0].to_string());
686 map.insert(1usize, values[1].to_string());
687 map.insert(1usize, values[2].to_string());
688
689 let (key_r, value_r) = map.get_at_mut(1).expect("Item wasn't found");
690 let value = value_r
691 .try_downcast_mut::<String>()
692 .expect("Couldn't downcast to String");
693 let key = key_r
694 .try_downcast_ref::<usize>()
695 .expect("Couldn't downcast to usize");
696 assert_eq!(key, &1usize);
697 assert_eq!(value, &mut values[2].to_owned());
698
699 value.clone_from(&values[0].to_owned());
700
701 assert_eq!(
702 map.get(&1usize)
703 .expect("Item wasn't found")
704 .try_downcast_ref::<String>()
705 .expect("Couldn't downcast to String"),
706 &values[0].to_owned()
707 );
708
709 assert!(map.get_at(2).is_none());
710 }
711
712 #[test]
713 fn next_index_increment() {
714 let values = ["first", "last"];
715 let mut map = DynamicMap::default();
716 map.insert(0usize, values[0]);
717 map.insert(1usize, values[1]);
718
719 let mut iter = map.iter();
720 let size = iter.len();
721
722 for _ in 0..2 {
723 let prev_index = iter.index;
724 assert!(iter.next().is_some());
725 assert_eq!(prev_index, iter.index - 1);
726 }
727
728 for _ in 0..2 {
730 assert!(iter.next().is_none());
731 assert_eq!(size, iter.index);
732 }
733 }
734
735 #[test]
736 fn remove() {
737 let mut map = DynamicMap::default();
738 map.insert(0, 0);
739 map.insert(1, 1);
740
741 assert_eq!(map.remove(&0).unwrap().try_downcast_ref(), Some(&0));
742 assert!(map.get(&0).is_none());
743 assert_eq!(map.get(&1).unwrap().try_downcast_ref(), Some(&1));
744
745 assert_eq!(map.remove(&1).unwrap().try_downcast_ref(), Some(&1));
746 assert!(map.get(&1).is_none());
747
748 assert!(map.remove(&1).is_none());
749 assert!(map.get(&1).is_none());
750 }
751}