Skip to content

Commit 9498bff

Browse files
committed
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 <[email protected]>
1 parent 1967c3d commit 9498bff

File tree

2 files changed

+25
-0
lines changed

2 files changed

+25
-0
lines changed

crates/bevy_reflect/src/impls/std.rs

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -394,6 +394,17 @@ impl<K: FromReflect + Eq + Hash, V: FromReflect> Map for HashMap<K, V> {
394394
self.insert(key, value)
395395
.map(|old_value| Box::new(old_value) as Box<dyn Reflect>)
396396
}
397+
398+
fn remove(&mut self, key: &dyn Reflect) -> Option<Box<dyn Reflect>> {
399+
let mut from_reflect = None;
400+
key.downcast_ref::<K>()
401+
.or_else(|| {
402+
from_reflect = K::from_reflect(key);
403+
from_reflect.as_ref()
404+
})
405+
.and_then(|key| self.remove(key))
406+
.map(|value| Box::new(value) as Box<dyn Reflect>)
407+
}
397408
}
398409

399410
impl<K: FromReflect + Eq + Hash, V: FromReflect> Reflect for HashMap<K, V> {

crates/bevy_reflect/src/map.rs

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,12 @@ pub trait Map: Reflect {
5757
key: Box<dyn Reflect>,
5858
value: Box<dyn Reflect>,
5959
) -> Option<Box<dyn Reflect>>;
60+
61+
/// Removes an entry from the map.
62+
///
63+
/// If the map did not have this key present, `None` is returned.
64+
/// If the map did have this key present, the removed value is returned.
65+
fn remove(&mut self, key: &dyn Reflect) -> Option<Box<dyn Reflect>>;
6066
}
6167

6268
/// A container for compile-time map info.
@@ -246,6 +252,14 @@ impl Map for DynamicMap {
246252
}
247253
}
248254

255+
fn remove(&mut self, key: &dyn Reflect) -> Option<Box<dyn Reflect>> {
256+
let index = self
257+
.indices
258+
.remove(&key.reflect_hash().expect(HASH_ERROR))?;
259+
let (_key, value) = self.values.remove(index);
260+
Some(value)
261+
}
262+
249263
fn drain(self: Box<Self>) -> Vec<(Box<dyn Reflect>, Box<dyn Reflect>)> {
250264
self.values
251265
}

0 commit comments

Comments
 (0)