impl Reflect for std::collections::HashMap instead of only bevy::utils::HashMap (#7739) (#7782)

# Objective

Implement `Reflect` for `std::collections::HashMap<K, V, S>` as well as `hashbrown::HashMap<K, V, S>` rather than just for `hashbrown::HashMap<K, V, RandomState>`. Fixes #7739.

## Solution

Rather than implementing on `HashMap<K, V>` I instead implemented most of the related traits on `HashMap<K, V, S> where S: BuildHasher + Send + Sync + 'static` and then `FromReflect` also needs the extra bound `S: Default` because it needs to use `with_capacity_and_hasher` so needs to be able to generate a default hasher.

As the API of `hashbrown::HashMap` is identical to `collections::HashMap` making them both work just required creating an `impl_reflect_for_hashmap` macro like the `impl_reflect_for_veclike` above and then applying this to both HashMaps.

---

## Changelog

`std::collections::HashMap` can now be reflected. Also more `State` generics than just `RandomState` can now be reflected for both `hashbrown::HashMap` and `collections::HashMap`
This commit is contained in:
TheBigCheese 2023-02-27 21:37:36 +00:00
parent aba8e81481
commit 3d3444b981

View File

@ -10,14 +10,14 @@ use crate::{
use crate::utility::{reflect_hasher, GenericTypeInfoCell, NonGenericTypeInfoCell}; use crate::utility::{reflect_hasher, GenericTypeInfoCell, NonGenericTypeInfoCell};
use bevy_reflect_derive::{impl_from_reflect_value, impl_reflect_value}; use bevy_reflect_derive::{impl_from_reflect_value, impl_reflect_value};
use bevy_utils::HashSet;
use bevy_utils::{Duration, Instant}; use bevy_utils::{Duration, Instant};
use bevy_utils::{HashMap, HashSet};
use std::{ use std::{
any::Any, any::Any,
borrow::Cow, borrow::Cow,
collections::VecDeque, collections::VecDeque,
ffi::OsString, ffi::OsString,
hash::{Hash, Hasher}, hash::{BuildHasher, Hash, Hasher},
num::{ num::{
NonZeroI128, NonZeroI16, NonZeroI32, NonZeroI64, NonZeroI8, NonZeroIsize, NonZeroU128, NonZeroI128, NonZeroI16, NonZeroI32, NonZeroI64, NonZeroI8, NonZeroIsize, NonZeroU128,
NonZeroU16, NonZeroU32, NonZeroU64, NonZeroU8, NonZeroUsize, NonZeroU16, NonZeroU32, NonZeroU64, NonZeroU8, NonZeroUsize,
@ -347,188 +347,216 @@ impl_reflect_for_veclike!(
VecDeque::<T> VecDeque::<T>
); );
impl<K: FromReflect + Eq + Hash, V: FromReflect> Map for HashMap<K, V> { macro_rules! impl_reflect_for_hashmap {
fn get(&self, key: &dyn Reflect) -> Option<&dyn Reflect> { ($ty:ty) => {
key.downcast_ref::<K>() impl<K, V, S> Map for $ty
.and_then(|key| HashMap::get(self, key)) where
.map(|value| value as &dyn Reflect) K: FromReflect + Eq + Hash,
} V: FromReflect,
S: BuildHasher + Send + Sync + 'static,
fn get_mut(&mut self, key: &dyn Reflect) -> Option<&mut dyn Reflect> { {
key.downcast_ref::<K>() fn get(&self, key: &dyn Reflect) -> Option<&dyn Reflect> {
.and_then(move |key| HashMap::get_mut(self, key)) key.downcast_ref::<K>()
.map(|value| value as &mut dyn Reflect) .and_then(|key| Self::get(self, key))
} .map(|value| value as &dyn Reflect)
}
fn get_at(&self, index: usize) -> Option<(&dyn Reflect, &dyn Reflect)> {
self.iter() fn get_mut(&mut self, key: &dyn Reflect) -> Option<&mut dyn Reflect> {
.nth(index) key.downcast_ref::<K>()
.map(|(key, value)| (key as &dyn Reflect, value as &dyn Reflect)) .and_then(move |key| Self::get_mut(self, key))
} .map(|value| value as &mut dyn Reflect)
}
fn len(&self) -> usize {
Self::len(self) fn get_at(&self, index: usize) -> Option<(&dyn Reflect, &dyn Reflect)> {
} self.iter()
.nth(index)
fn iter(&self) -> MapIter { .map(|(key, value)| (key as &dyn Reflect, value as &dyn Reflect))
MapIter { }
map: self,
index: 0, fn len(&self) -> usize {
} Self::len(self)
} }
fn drain(self: Box<Self>) -> Vec<(Box<dyn Reflect>, Box<dyn Reflect>)> { fn iter(&self) -> MapIter {
self.into_iter() MapIter {
.map(|(key, value)| { map: self,
( index: 0,
Box::new(key) as Box<dyn Reflect>, }
Box::new(value) as Box<dyn Reflect>, }
)
}) fn drain(self: Box<Self>) -> Vec<(Box<dyn Reflect>, Box<dyn Reflect>)> {
.collect() self.into_iter()
} .map(|(key, value)| {
(
fn clone_dynamic(&self) -> DynamicMap { Box::new(key) as Box<dyn Reflect>,
let mut dynamic_map = DynamicMap::default(); Box::new(value) as Box<dyn Reflect>,
dynamic_map.set_name(self.type_name().to_string()); )
for (k, v) in self { })
dynamic_map.insert_boxed(k.clone_value(), v.clone_value()); .collect()
} }
dynamic_map
} fn clone_dynamic(&self) -> DynamicMap {
let mut dynamic_map = DynamicMap::default();
fn insert_boxed( dynamic_map.set_name(self.type_name().to_string());
&mut self, for (k, v) in self {
key: Box<dyn Reflect>, dynamic_map.insert_boxed(k.clone_value(), v.clone_value());
value: Box<dyn Reflect>, }
) -> Option<Box<dyn Reflect>> { dynamic_map
let key = K::take_from_reflect(key).unwrap_or_else(|key| { }
panic!(
"Attempted to insert invalid key of type {}.", fn insert_boxed(
key.type_name() &mut self,
) key: Box<dyn Reflect>,
}); value: Box<dyn Reflect>,
let value = V::take_from_reflect(value).unwrap_or_else(|value| { ) -> Option<Box<dyn Reflect>> {
panic!( let key = K::take_from_reflect(key).unwrap_or_else(|key| {
"Attempted to insert invalid value of type {}.", panic!(
value.type_name() "Attempted to insert invalid key of type {}.",
) key.type_name()
}); )
self.insert(key, value) });
.map(|old_value| Box::new(old_value) as Box<dyn Reflect>) let value = V::take_from_reflect(value).unwrap_or_else(|value| {
} panic!(
"Attempted to insert invalid value of type {}.",
fn remove(&mut self, key: &dyn Reflect) -> Option<Box<dyn Reflect>> { value.type_name()
let mut from_reflect = None; )
key.downcast_ref::<K>() });
.or_else(|| { self.insert(key, value)
from_reflect = K::from_reflect(key); .map(|old_value| Box::new(old_value) as Box<dyn Reflect>)
from_reflect.as_ref() }
})
.and_then(|key| self.remove(key)) fn remove(&mut self, key: &dyn Reflect) -> Option<Box<dyn Reflect>> {
.map(|value| Box::new(value) as Box<dyn Reflect>) let mut from_reflect = None;
} key.downcast_ref::<K>()
} .or_else(|| {
from_reflect = K::from_reflect(key);
impl<K: FromReflect + Eq + Hash, V: FromReflect> Reflect for HashMap<K, V> { from_reflect.as_ref()
fn type_name(&self) -> &str { })
std::any::type_name::<Self>() .and_then(|key| self.remove(key))
} .map(|value| Box::new(value) as Box<dyn Reflect>)
fn get_type_info(&self) -> &'static TypeInfo {
<Self as Typed>::type_info()
}
fn into_any(self: Box<Self>) -> Box<dyn Any> {
self
}
fn as_any(&self) -> &dyn Any {
self
}
fn as_any_mut(&mut self) -> &mut dyn Any {
self
}
#[inline]
fn into_reflect(self: Box<Self>) -> Box<dyn Reflect> {
self
}
fn as_reflect(&self) -> &dyn Reflect {
self
}
fn as_reflect_mut(&mut self) -> &mut dyn Reflect {
self
}
fn apply(&mut self, value: &dyn Reflect) {
map_apply(self, value);
}
fn set(&mut self, value: Box<dyn Reflect>) -> Result<(), Box<dyn Reflect>> {
*self = value.take()?;
Ok(())
}
fn reflect_ref(&self) -> ReflectRef {
ReflectRef::Map(self)
}
fn reflect_mut(&mut self) -> ReflectMut {
ReflectMut::Map(self)
}
fn reflect_owned(self: Box<Self>) -> ReflectOwned {
ReflectOwned::Map(self)
}
fn clone_value(&self) -> Box<dyn Reflect> {
Box::new(self.clone_dynamic())
}
fn reflect_partial_eq(&self, value: &dyn Reflect) -> Option<bool> {
map_partial_eq(self, value)
}
}
impl<K: FromReflect + Eq + Hash, V: FromReflect> Typed for HashMap<K, V> {
fn type_info() -> &'static TypeInfo {
static CELL: GenericTypeInfoCell = GenericTypeInfoCell::new();
CELL.get_or_insert::<Self, _>(|| TypeInfo::Map(MapInfo::new::<Self, K, V>()))
}
}
impl<K, V> GetTypeRegistration for HashMap<K, V>
where
K: FromReflect + Eq + Hash,
V: FromReflect,
{
fn get_type_registration() -> TypeRegistration {
let mut registration = TypeRegistration::of::<HashMap<K, V>>();
registration.insert::<ReflectFromPtr>(FromType::<HashMap<K, V>>::from_type());
registration
}
}
impl<K: FromReflect + Eq + Hash, V: FromReflect> FromReflect for HashMap<K, V> {
fn from_reflect(reflect: &dyn Reflect) -> Option<Self> {
if let ReflectRef::Map(ref_map) = reflect.reflect_ref() {
let mut new_map = Self::with_capacity(ref_map.len());
for (key, value) in ref_map.iter() {
let new_key = K::from_reflect(key)?;
let new_value = V::from_reflect(value)?;
new_map.insert(new_key, new_value);
} }
Some(new_map)
} else {
None
} }
}
impl<K, V, S> Reflect for $ty
where
K: FromReflect + Eq + Hash,
V: FromReflect,
S: BuildHasher + Send + Sync + 'static,
{
fn type_name(&self) -> &str {
std::any::type_name::<Self>()
}
fn get_type_info(&self) -> &'static TypeInfo {
<Self as Typed>::type_info()
}
fn into_any(self: Box<Self>) -> Box<dyn Any> {
self
}
fn as_any(&self) -> &dyn Any {
self
}
fn as_any_mut(&mut self) -> &mut dyn Any {
self
}
#[inline]
fn into_reflect(self: Box<Self>) -> Box<dyn Reflect> {
self
}
fn as_reflect(&self) -> &dyn Reflect {
self
}
fn as_reflect_mut(&mut self) -> &mut dyn Reflect {
self
}
fn apply(&mut self, value: &dyn Reflect) {
map_apply(self, value);
}
fn set(&mut self, value: Box<dyn Reflect>) -> Result<(), Box<dyn Reflect>> {
*self = value.take()?;
Ok(())
}
fn reflect_ref(&self) -> ReflectRef {
ReflectRef::Map(self)
}
fn reflect_mut(&mut self) -> ReflectMut {
ReflectMut::Map(self)
}
fn reflect_owned(self: Box<Self>) -> ReflectOwned {
ReflectOwned::Map(self)
}
fn clone_value(&self) -> Box<dyn Reflect> {
Box::new(self.clone_dynamic())
}
fn reflect_partial_eq(&self, value: &dyn Reflect) -> Option<bool> {
map_partial_eq(self, value)
}
}
impl<K, V, S> Typed for $ty
where
K: FromReflect + Eq + Hash,
V: FromReflect,
S: BuildHasher + Send + Sync + 'static,
{
fn type_info() -> &'static TypeInfo {
static CELL: GenericTypeInfoCell = GenericTypeInfoCell::new();
CELL.get_or_insert::<Self, _>(|| TypeInfo::Map(MapInfo::new::<Self, K, V>()))
}
}
impl<K, V, S> GetTypeRegistration for $ty
where
K: FromReflect + Eq + Hash,
V: FromReflect,
S: BuildHasher + Send + Sync + 'static,
{
fn get_type_registration() -> TypeRegistration {
let mut registration = TypeRegistration::of::<Self>();
registration.insert::<ReflectFromPtr>(FromType::<Self>::from_type());
registration
}
}
impl<K, V, S> FromReflect for $ty
where
K: FromReflect + Eq + Hash,
V: FromReflect,
S: BuildHasher + Default + Send + Sync + 'static,
{
fn from_reflect(reflect: &dyn Reflect) -> Option<Self> {
if let ReflectRef::Map(ref_map) = reflect.reflect_ref() {
let mut new_map = Self::with_capacity_and_hasher(ref_map.len(), S::default());
for (key, value) in ref_map.iter() {
let new_key = K::from_reflect(key)?;
let new_value = V::from_reflect(value)?;
new_map.insert(new_key, new_value);
}
Some(new_map)
} else {
None
}
}
}
};
} }
impl_reflect_for_hashmap!(bevy_utils::hashbrown::HashMap<K, V, S>);
impl_reflect_for_hashmap!(std::collections::HashMap<K, V, S>);
impl<T: Reflect, const N: usize> Array for [T; N] { impl<T: Reflect, const N: usize> Array for [T; N] {
#[inline] #[inline]
fn get(&self, index: usize) -> Option<&dyn Reflect> { fn get(&self, index: usize) -> Option<&dyn Reflect> {