Skip to content

Commit

Permalink
Add remove method to Map reflection trait. (bevyengine#6564)
Browse files Browse the repository at this point in the history
# Objective

- Implements removal of entries from a `dyn Map`
- Fixes bevyengine#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>
  • Loading branch information
2 people authored and alradish committed Jan 22, 2023
1 parent aae55d9 commit dc65ead
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 0 deletions.
11 changes: 11 additions & 0 deletions crates/bevy_reflect/src/impls/std.rs
Original file line number Diff line number Diff line change
Expand Up @@ -397,6 +397,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> {
Expand Down
14 changes: 14 additions & 0 deletions crates/bevy_reflect/src/map.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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
}
Expand Down

0 comments on commit dc65ead

Please sign in to comment.