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 2 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
6 changes: 6 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,12 @@ 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>> {
key.downcast_ref::<K>()
soqb marked this conversation as resolved.
Show resolved Hide resolved
.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
18 changes: 18 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,18 @@ impl Map for DynamicMap {
}
}

fn remove(&mut self, key: &dyn Reflect) -> Option<Box<dyn Reflect>> {
match self.indices.entry(key.reflect_hash().expect(HASH_ERROR)) {
Entry::Occupied(entry) => {
let index = *entry.get();
entry.remove();
let (_key, value) = self.values.remove(index);
Some(value)
},
Entry::Vacant(_) => None,
}
soqb marked this conversation as resolved.
Show resolved Hide resolved
}

fn drain(self: Box<Self>) -> Vec<(Box<dyn Reflect>, Box<dyn Reflect>)> {
self.values
}
Expand Down