mirror of
https://github.com/bevyengine/bevy
synced 2024-11-10 07:04:33 +00:00
Add remove
method to Map
reflection trait. (#6564)
# Objective - Implements removal of entries from a `dyn Map` - Fixes #6563 ## Solution - Adds a `remove` method to the `Map` trait which takes in a `&dyn Reflect` key and returns the value removed if it was present. --- ## Changelog - Added `Map::remove` ## Migration Guide - Implementors of `Map` will need to implement the `remove` method. Co-authored-by: radiish <thesethskigamer@gmail.com>
This commit is contained in:
parent
1967c3ddef
commit
9498bfffcb
2 changed files with 25 additions and 0 deletions
|
@ -394,6 +394,17 @@ impl<K: FromReflect + Eq + Hash, V: FromReflect> Map for HashMap<K, V> {
|
|||
self.insert(key, value)
|
||||
.map(|old_value| Box::new(old_value) as Box<dyn Reflect>)
|
||||
}
|
||||
|
||||
fn remove(&mut self, key: &dyn Reflect) -> Option<Box<dyn Reflect>> {
|
||||
let mut from_reflect = None;
|
||||
key.downcast_ref::<K>()
|
||||
.or_else(|| {
|
||||
from_reflect = K::from_reflect(key);
|
||||
from_reflect.as_ref()
|
||||
})
|
||||
.and_then(|key| self.remove(key))
|
||||
.map(|value| Box::new(value) as Box<dyn Reflect>)
|
||||
}
|
||||
}
|
||||
|
||||
impl<K: FromReflect + Eq + Hash, V: FromReflect> Reflect for HashMap<K, V> {
|
||||
|
|
|
@ -57,6 +57,12 @@ pub trait Map: Reflect {
|
|||
key: Box<dyn Reflect>,
|
||||
value: Box<dyn Reflect>,
|
||||
) -> Option<Box<dyn Reflect>>;
|
||||
|
||||
/// Removes an entry from the map.
|
||||
///
|
||||
/// If the map did not have this key present, `None` is returned.
|
||||
/// If the map did have this key present, the removed value is returned.
|
||||
fn remove(&mut self, key: &dyn Reflect) -> Option<Box<dyn Reflect>>;
|
||||
}
|
||||
|
||||
/// A container for compile-time map info.
|
||||
|
@ -246,6 +252,14 @@ impl Map for DynamicMap {
|
|||
}
|
||||
}
|
||||
|
||||
fn remove(&mut self, key: &dyn Reflect) -> Option<Box<dyn Reflect>> {
|
||||
let index = self
|
||||
.indices
|
||||
.remove(&key.reflect_hash().expect(HASH_ERROR))?;
|
||||
let (_key, value) = self.values.remove(index);
|
||||
Some(value)
|
||||
}
|
||||
|
||||
fn drain(self: Box<Self>) -> Vec<(Box<dyn Reflect>, Box<dyn Reflect>)> {
|
||||
self.values
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue