diff --git a/crates/bevy_reflect/src/impls/std.rs b/crates/bevy_reflect/src/impls/std.rs index 6e94741f638b9..61352302fa67b 100644 --- a/crates/bevy_reflect/src/impls/std.rs +++ b/crates/bevy_reflect/src/impls/std.rs @@ -1,6 +1,6 @@ use crate as bevy_reflect; use crate::{ - map_partial_eq, Array, ArrayInfo, ArrayIter, DynamicMap, FromReflect, FromType, + map_apply, map_partial_eq, Array, ArrayInfo, ArrayIter, DynamicMap, FromReflect, FromType, GetTypeRegistration, List, ListInfo, Map, MapInfo, MapIter, Reflect, ReflectDeserialize, ReflectMut, ReflectRef, ReflectSerialize, TypeInfo, TypeRegistration, Typed, ValueInfo, }; @@ -193,7 +193,7 @@ impl FromReflect for Vec { } } -impl Map for HashMap { +impl Map for HashMap { fn get(&self, key: &dyn Reflect) -> Option<&dyn Reflect> { key.downcast_ref::() .and_then(|key| HashMap::get(self, key)) @@ -231,9 +231,34 @@ impl Map for HashMap { } dynamic_map } + + fn insert_boxed( + &mut self, + key: Box, + value: Box, + ) -> Option> { + let key = key.take::().unwrap_or_else(|key| { + K::from_reflect(&*key).unwrap_or_else(|| { + panic!( + "Attempted to insert invalid key of type {}.", + key.type_name() + ) + }) + }); + let value = value.take::().unwrap_or_else(|value| { + V::from_reflect(&*value).unwrap_or_else(|| { + panic!( + "Attempted to insert invalid value of type {}.", + value.type_name() + ) + }) + }); + self.insert(key, value) + .map(|old_value| Box::new(old_value) as Box) + } } -impl Reflect for HashMap { +impl Reflect for HashMap { fn type_name(&self) -> &str { std::any::type_name::() } @@ -263,15 +288,7 @@ impl Reflect for HashMap { } fn apply(&mut self, value: &dyn Reflect) { - if let ReflectRef::Map(map_value) = value.reflect_ref() { - for (key, value) in map_value.iter() { - if let Some(v) = Map::get_mut(self, key) { - v.apply(value); - } - } - } else { - panic!("Attempted to apply a non-map type to a map type."); - } + map_apply(self, value); } fn set(&mut self, value: Box) -> Result<(), Box> { @@ -296,7 +313,7 @@ impl Reflect for HashMap { } } -impl Typed for HashMap { +impl Typed for HashMap { fn type_info() -> &'static TypeInfo { static CELL: GenericTypeInfoCell = GenericTypeInfoCell::new(); CELL.get_or_insert::(|| TypeInfo::Map(MapInfo::new::())) @@ -305,8 +322,8 @@ impl Typed for HashMap { impl GetTypeRegistration for HashMap where - K: Reflect + Clone + Eq + Hash + for<'de> Deserialize<'de>, - V: Reflect + Clone + for<'de> Deserialize<'de>, + K: FromReflect + Clone + Eq + Hash + for<'de> Deserialize<'de>, + V: FromReflect + Clone + for<'de> Deserialize<'de>, { fn get_type_registration() -> TypeRegistration { let mut registration = TypeRegistration::of::(); diff --git a/crates/bevy_reflect/src/lib.rs b/crates/bevy_reflect/src/lib.rs index 927aafe4cc834..602ea2d11eee9 100644 --- a/crates/bevy_reflect/src/lib.rs +++ b/crates/bevy_reflect/src/lib.rs @@ -353,6 +353,7 @@ mod tests { let mut map = DynamicMap::default(); map.insert(2usize, 3i8); + map.insert(3usize, 4i8); foo_patch.insert("d", map); let mut bar_patch = DynamicStruct::default(); @@ -394,6 +395,7 @@ mod tests { let mut hash_map = HashMap::default(); hash_map.insert(1, 1); hash_map.insert(2, 3); + hash_map.insert(3, 4); let mut hash_map_baz = HashMap::default(); hash_map_baz.insert(1, Bar { x: 7 }); @@ -416,6 +418,7 @@ mod tests { let mut hash_map = HashMap::default(); hash_map.insert(2, 3); + hash_map.insert(3, 4); let expected_new_foo = Foo { a: 2, diff --git a/crates/bevy_reflect/src/map.rs b/crates/bevy_reflect/src/map.rs index 89f499731f50b..5824ba05a82d9 100644 --- a/crates/bevy_reflect/src/map.rs +++ b/crates/bevy_reflect/src/map.rs @@ -44,6 +44,16 @@ pub trait Map: Reflect { /// Clones the map, producing a [`DynamicMap`]. fn clone_dynamic(&self) -> DynamicMap; + + /// Inserts a key-value pair into the map. + /// + /// If the map did not have this key present, `None` is returned. + /// If the map did have this key present, the value is updated, and the old value is returned. + fn insert_boxed( + &mut self, + key: Box, + value: Box, + ) -> Option>; } /// A container for compile-time map info. @@ -153,19 +163,6 @@ impl DynamicMap { pub fn insert(&mut self, key: K, value: V) { self.insert_boxed(Box::new(key), Box::new(value)); } - - /// Inserts a key-value pair of [`Reflect`] values into the map. - pub fn insert_boxed(&mut self, key: Box, value: Box) { - match self.indices.entry(key.reflect_hash().expect(HASH_ERROR)) { - Entry::Occupied(entry) => { - self.values[*entry.get()] = (key, value); - } - Entry::Vacant(entry) => { - entry.insert(self.values.len()); - self.values.push((key, value)); - } - } - } } impl Map for DynamicMap { @@ -210,6 +207,25 @@ impl Map for DynamicMap { .get(index) .map(|(key, value)| (&**key, &**value)) } + + fn insert_boxed( + &mut self, + key: Box, + mut value: Box, + ) -> Option> { + match self.indices.entry(key.reflect_hash().expect(HASH_ERROR)) { + Entry::Occupied(entry) => { + let (_old_key, old_value) = self.values.get_mut(*entry.get()).unwrap(); + std::mem::swap(old_value, &mut value); + Some(value) + } + Entry::Vacant(entry) => { + entry.insert(self.values.len()); + self.values.push((key, value)); + None + } + } + } } impl Reflect for DynamicMap { @@ -245,15 +261,7 @@ impl Reflect for DynamicMap { } fn apply(&mut self, value: &dyn Reflect) { - if let ReflectRef::Map(map_value) = value.reflect_ref() { - for (key, value) in map_value.iter() { - if let Some(v) = self.get_mut(key) { - v.apply(value); - } - } - } else { - panic!("Attempted to apply a non-map type to a map type."); - } + map_apply(self, value); } fn set(&mut self, value: Box) -> Result<(), Box> { @@ -387,6 +395,28 @@ pub fn map_debug(dyn_map: &dyn Map, f: &mut std::fmt::Formatter<'_>) -> std::fmt debug.finish() } +/// Applies the elements of reflected map `b` to the corresponding elements of map `a`. +/// +/// If a key from `b` does not exist in `a`, the value is cloned and inserted. +/// +/// # Panics +/// +/// This function panics if `b` is not a reflected map. +#[inline] +pub fn map_apply(a: &mut M, b: &dyn Reflect) { + if let ReflectRef::Map(map_value) = b.reflect_ref() { + for (key, b_value) in map_value.iter() { + if let Some(a_value) = a.get_mut(key) { + a_value.apply(b_value); + } else { + a.insert_boxed(key.clone_value(), b_value.clone_value()); + } + } + } else { + panic!("Attempted to apply a non-map type to a map type."); + } +} + #[cfg(test)] mod tests { use super::DynamicMap; diff --git a/crates/bevy_reflect/src/reflect.rs b/crates/bevy_reflect/src/reflect.rs index 1e4d31449b2c8..c1d41710e6f0d 100644 --- a/crates/bevy_reflect/src/reflect.rs +++ b/crates/bevy_reflect/src/reflect.rs @@ -93,17 +93,18 @@ pub trait Reflect: Any + Send + Sync { /// and excess elements in `value` are appended to `self`. /// - If `T` is a [`Map`], then for each key in `value`, the associated /// value is applied to the value associated with the same key in `self`. - /// Keys which are not present in both maps are ignored. + /// Keys which are not present in `self` are inserted. /// - If `T` is none of these, then `value` is downcast to `T`, cloned, and /// assigned to `self`. /// /// Note that `Reflect` must be implemented manually for [`List`]s and /// [`Map`]s in order to achieve the correct semantics, as derived /// implementations will have the semantics for [`Struct`], [`TupleStruct`] - /// or none of the above depending on the kind of type. For lists, use the - /// [`list_apply`] helper function when implementing this method. + /// or none of the above depending on the kind of type. For lists and maps, use the + /// [`list_apply`] and [`map_apply`] helper functions when implementing this method. /// /// [`list_apply`]: crate::list_apply + /// [`map_apply`]: crate::map_apply /// /// # Panics /// diff --git a/crates/bevy_reflect/src/serde/de.rs b/crates/bevy_reflect/src/serde/de.rs index 5ffc141c6a178..950208fbea8e3 100644 --- a/crates/bevy_reflect/src/serde/de.rs +++ b/crates/bevy_reflect/src/serde/de.rs @@ -1,6 +1,6 @@ use crate::{ serde::type_fields, DynamicArray, DynamicList, DynamicMap, DynamicStruct, DynamicTuple, - DynamicTupleStruct, Reflect, ReflectDeserialize, TypeRegistry, + DynamicTupleStruct, Map, Reflect, ReflectDeserialize, TypeRegistry, }; use erased_serde::Deserializer; use serde::de::{self, DeserializeSeed, MapAccess, SeqAccess, Visitor};