Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Merged by Bors] - Add remove method to Map reflection trait. #6564

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 @@ -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>()
soqb marked this conversation as resolved.
Show resolved Hide resolved
.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