use core::fmt::{Debug, Formatter};
use bevy_platform::collections::HashTable;
use bevy_reflect_derive::impl_type_path;
use crate::{
generics::impl_generic_info_methods, type_info::impl_type_methods, ApplyError, Generics,
MaybeTyped, PartialReflect, Reflect, ReflectKind, ReflectMut, ReflectOwned, ReflectRef, Type,
TypeInfo, TypePath,
};
use alloc::{boxed::Box, format, vec::Vec};
pub trait Map: PartialReflect {
fn get(&self, key: &dyn PartialReflect) -> Option<&dyn PartialReflect>;
fn get_mut(&mut self, key: &dyn PartialReflect) -> Option<&mut dyn PartialReflect>;
fn len(&self) -> usize;
fn is_empty(&self) -> bool {
self.len() == 0
}
fn iter(&self) -> Box<dyn Iterator<Item = (&dyn PartialReflect, &dyn PartialReflect)> + '_>;
fn drain(&mut self) -> Vec<(Box<dyn PartialReflect>, Box<dyn PartialReflect>)>;
fn retain(&mut self, f: &mut dyn FnMut(&dyn PartialReflect, &mut dyn PartialReflect) -> bool);
fn to_dynamic_map(&self) -> DynamicMap {
let mut map = DynamicMap::default();
map.set_represented_type(self.get_represented_type_info());
for (key, value) in self.iter() {
map.insert_boxed(key.to_dynamic(), value.to_dynamic());
}
map
}
fn insert_boxed(
&mut self,
key: Box<dyn PartialReflect>,
value: Box<dyn PartialReflect>,
) -> Option<Box<dyn PartialReflect>>;
fn remove(&mut self, key: &dyn PartialReflect) -> Option<Box<dyn PartialReflect>>;
fn get_represented_map_info(&self) -> Option<&'static MapInfo> {
self.get_represented_type_info()?.as_map().ok()
}
}
#[derive(Clone, Debug)]
pub struct MapInfo {
ty: Type,
generics: Generics,
key_info: fn() -> Option<&'static TypeInfo>,
key_ty: Type,
value_info: fn() -> Option<&'static TypeInfo>,
value_ty: Type,
#[cfg(feature = "documentation")]
docs: Option<&'static str>,
}
impl MapInfo {
pub fn new<
TMap: Map + TypePath,
TKey: Reflect + MaybeTyped + TypePath,
TValue: Reflect + MaybeTyped + TypePath,
>() -> Self {
Self {
ty: Type::of::<TMap>(),
generics: Generics::new(),
key_info: TKey::maybe_type_info,
key_ty: Type::of::<TKey>(),
value_info: TValue::maybe_type_info,
value_ty: Type::of::<TValue>(),
#[cfg(feature = "documentation")]
docs: None,
}
}
#[cfg(feature = "documentation")]
pub fn with_docs(self, docs: Option<&'static str>) -> Self {
Self { docs, ..self }
}
impl_type_methods!(ty);
pub fn key_info(&self) -> Option<&'static TypeInfo> {
(self.key_info)()
}
pub fn key_ty(&self) -> Type {
self.key_ty
}
pub fn value_info(&self) -> Option<&'static TypeInfo> {
(self.value_info)()
}
pub fn value_ty(&self) -> Type {
self.value_ty
}
#[cfg(feature = "documentation")]
pub fn docs(&self) -> Option<&'static str> {
self.docs
}
impl_generic_info_methods!(generics);
}
#[macro_export]
macro_rules! hash_error {
( $key:expr ) => {{
let type_path = (*$key).reflect_type_path();
if !$key.is_dynamic() {
format!(
"the given key of type `{}` does not support hashing",
type_path
)
} else {
match (*$key).get_represented_type_info() {
None => format!("the dynamic type `{}` does not support hashing", type_path),
Some(s) => format!(
"the dynamic type `{}` (representing `{}`) does not support hashing",
type_path,
s.type_path()
),
}
}
}}
}
#[derive(Default)]
pub struct DynamicMap {
represented_type: Option<&'static TypeInfo>,
hash_table: HashTable<(Box<dyn PartialReflect>, Box<dyn PartialReflect>)>,
}
impl DynamicMap {
pub fn set_represented_type(&mut self, represented_type: Option<&'static TypeInfo>) {
if let Some(represented_type) = represented_type {
assert!(
matches!(represented_type, TypeInfo::Map(_)),
"expected TypeInfo::Map but received: {represented_type:?}"
);
}
self.represented_type = represented_type;
}
pub fn insert<K: PartialReflect, V: PartialReflect>(&mut self, key: K, value: V) {
self.insert_boxed(Box::new(key), Box::new(value));
}
fn internal_hash(value: &dyn PartialReflect) -> u64 {
value.reflect_hash().expect(&hash_error!(value))
}
fn internal_eq(
key: &dyn PartialReflect,
) -> impl FnMut(&(Box<dyn PartialReflect>, Box<dyn PartialReflect>)) -> bool + '_ {
|(other, _)| {
key
.reflect_partial_eq(&**other)
.expect("underlying type does not reflect `PartialEq` and hence doesn't support equality checks")
}
}
}
impl Map for DynamicMap {
fn get(&self, key: &dyn PartialReflect) -> Option<&dyn PartialReflect> {
self.hash_table
.find(Self::internal_hash(key), Self::internal_eq(key))
.map(|(_, value)| &**value)
}
fn get_mut(&mut self, key: &dyn PartialReflect) -> Option<&mut dyn PartialReflect> {
self.hash_table
.find_mut(Self::internal_hash(key), Self::internal_eq(key))
.map(|(_, value)| &mut **value)
}
fn len(&self) -> usize {
self.hash_table.len()
}
fn iter(&self) -> Box<dyn Iterator<Item = (&dyn PartialReflect, &dyn PartialReflect)> + '_> {
let iter = self.hash_table.iter().map(|(k, v)| (&**k, &**v));
Box::new(iter)
}
fn drain(&mut self) -> Vec<(Box<dyn PartialReflect>, Box<dyn PartialReflect>)> {
self.hash_table.drain().collect()
}
fn retain(&mut self, f: &mut dyn FnMut(&dyn PartialReflect, &mut dyn PartialReflect) -> bool) {
self.hash_table
.retain(move |(key, value)| f(&**key, &mut **value));
}
fn insert_boxed(
&mut self,
key: Box<dyn PartialReflect>,
value: Box<dyn PartialReflect>,
) -> Option<Box<dyn PartialReflect>> {
assert_eq!(
key.reflect_partial_eq(&*key),
Some(true),
"keys inserted in `Map`-like types are expected to reflect `PartialEq`"
);
let hash = Self::internal_hash(&*key);
let eq = Self::internal_eq(&*key);
match self.hash_table.find_mut(hash, eq) {
Some((_, old)) => Some(core::mem::replace(old, value)),
None => {
self.hash_table.insert_unique(
Self::internal_hash(key.as_ref()),
(key, value),
|(key, _)| Self::internal_hash(&**key),
);
None
}
}
}
fn remove(&mut self, key: &dyn PartialReflect) -> Option<Box<dyn PartialReflect>> {
let hash = Self::internal_hash(key);
let eq = Self::internal_eq(key);
match self.hash_table.find_entry(hash, eq) {
Ok(entry) => {
let ((_, old_value), _) = entry.remove();
Some(old_value)
}
Err(_) => None,
}
}
}
impl PartialReflect for DynamicMap {
#[inline]
fn get_represented_type_info(&self) -> Option<&'static TypeInfo> {
self.represented_type
}
#[inline]
fn into_partial_reflect(self: Box<Self>) -> Box<dyn PartialReflect> {
self
}
#[inline]
fn as_partial_reflect(&self) -> &dyn PartialReflect {
self
}
#[inline]
fn as_partial_reflect_mut(&mut self) -> &mut dyn PartialReflect {
self
}
fn try_into_reflect(self: Box<Self>) -> Result<Box<dyn Reflect>, Box<dyn PartialReflect>> {
Err(self)
}
fn try_as_reflect(&self) -> Option<&dyn Reflect> {
None
}
fn try_as_reflect_mut(&mut self) -> Option<&mut dyn Reflect> {
None
}
fn apply(&mut self, value: &dyn PartialReflect) {
map_apply(self, value);
}
fn try_apply(&mut self, value: &dyn PartialReflect) -> Result<(), ApplyError> {
map_try_apply(self, value)
}
fn reflect_kind(&self) -> ReflectKind {
ReflectKind::Map
}
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 reflect_partial_eq(&self, value: &dyn PartialReflect) -> Option<bool> {
map_partial_eq(self, value)
}
fn debug(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
write!(f, "DynamicMap(")?;
map_debug(self, f)?;
write!(f, ")")
}
#[inline]
fn is_dynamic(&self) -> bool {
true
}
}
impl_type_path!((in bevy_reflect) DynamicMap);
impl Debug for DynamicMap {
fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
self.debug(f)
}
}
impl FromIterator<(Box<dyn PartialReflect>, Box<dyn PartialReflect>)> for DynamicMap {
fn from_iter<I: IntoIterator<Item = (Box<dyn PartialReflect>, Box<dyn PartialReflect>)>>(
items: I,
) -> Self {
let mut map = Self::default();
for (key, value) in items.into_iter() {
map.insert_boxed(key, value);
}
map
}
}
impl<K: Reflect, V: Reflect> FromIterator<(K, V)> for DynamicMap {
fn from_iter<I: IntoIterator<Item = (K, V)>>(items: I) -> Self {
let mut map = Self::default();
for (key, value) in items.into_iter() {
map.insert(key, value);
}
map
}
}
impl IntoIterator for DynamicMap {
type Item = (Box<dyn PartialReflect>, Box<dyn PartialReflect>);
type IntoIter = bevy_platform::collections::hash_table::IntoIter<Self::Item>;
fn into_iter(self) -> Self::IntoIter {
self.hash_table.into_iter()
}
}
impl<'a> IntoIterator for &'a DynamicMap {
type Item = (&'a dyn PartialReflect, &'a dyn PartialReflect);
type IntoIter = core::iter::Map<
bevy_platform::collections::hash_table::Iter<
'a,
(Box<dyn PartialReflect>, Box<dyn PartialReflect>),
>,
fn(&'a (Box<dyn PartialReflect>, Box<dyn PartialReflect>)) -> Self::Item,
>;
fn into_iter(self) -> Self::IntoIter {
self.hash_table
.iter()
.map(|(k, v)| (k.as_ref(), v.as_ref()))
}
}
#[inline]
pub fn map_partial_eq<M: Map + ?Sized>(a: &M, b: &dyn PartialReflect) -> Option<bool> {
let ReflectRef::Map(map) = b.reflect_ref() else {
return Some(false);
};
if a.len() != map.len() {
return Some(false);
}
for (key, value) in a.iter() {
if let Some(map_value) = map.get(key) {
let eq_result = value.reflect_partial_eq(map_value);
if let failed @ (Some(false) | None) = eq_result {
return failed;
}
} else {
return Some(false);
}
}
Some(true)
}
#[inline]
pub fn map_debug(dyn_map: &dyn Map, f: &mut Formatter<'_>) -> core::fmt::Result {
let mut debug = f.debug_map();
for (key, value) in dyn_map.iter() {
debug.entry(&key as &dyn Debug, &value as &dyn Debug);
}
debug.finish()
}
#[inline]
pub fn map_apply<M: Map>(a: &mut M, b: &dyn PartialReflect) {
if let Err(err) = map_try_apply(a, b) {
panic!("{err}");
}
}
#[inline]
pub fn map_try_apply<M: Map>(a: &mut M, b: &dyn PartialReflect) -> Result<(), ApplyError> {
let map_value = b.reflect_ref().as_map()?;
for (key, b_value) in map_value.iter() {
if let Some(a_value) = a.get_mut(key) {
a_value.try_apply(b_value)?;
} else {
a.insert_boxed(key.to_dynamic(), b_value.to_dynamic());
}
}
a.retain(&mut |key, _| map_value.get(key).is_some());
Ok(())
}
#[cfg(test)]
mod tests {
use crate::PartialReflect;
use super::{DynamicMap, Map};
#[test]
fn remove() {
let mut map = DynamicMap::default();
map.insert(0, 0);
map.insert(1, 1);
assert_eq!(map.remove(&0).unwrap().try_downcast_ref(), Some(&0));
assert!(map.get(&0).is_none());
assert_eq!(map.get(&1).unwrap().try_downcast_ref(), Some(&1));
assert_eq!(map.remove(&1).unwrap().try_downcast_ref(), Some(&1));
assert!(map.get(&1).is_none());
assert!(map.remove(&1).is_none());
assert!(map.get(&1).is_none());
}
#[test]
fn apply() {
let mut map_a = DynamicMap::default();
map_a.insert(0, 0);
map_a.insert(1, 1);
let mut map_b = DynamicMap::default();
map_b.insert(10, 10);
map_b.insert(1, 5);
map_a.apply(&map_b);
assert!(map_a.get(&0).is_none());
assert_eq!(map_a.get(&1).unwrap().try_downcast_ref(), Some(&5));
assert_eq!(map_a.get(&10).unwrap().try_downcast_ref(), Some(&10));
}
}