Skip to content

Commit

Permalink
Add IntoIterator impls for &Query and &mut Query (bevyengine#4692)
Browse files Browse the repository at this point in the history
# Objective

These types of IntoIterator impls are a common pattern in Rust, and these implementations make this common pattern work for bevy queries.
  • Loading branch information
TheRawMeatball authored and exjam committed May 22, 2022
1 parent fee641c commit 8d0067e
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
15 changes: 15 additions & 0 deletions crates/bevy_ecs/src/system/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -925,4 +925,19 @@ mod tests {
assert!(entity.contains::<A>());
assert!(entity.contains::<B>());
}

#[test]
fn into_iter_impl() {
let mut world = World::new();
world.spawn().insert(W(42u32));
run_system(&mut world, |mut q: Query<&mut W<u32>>| {
for mut a in &mut q {
assert_eq!(a.0, 42);
a.0 = 0;
}
for a in &q {
assert_eq!(a.0, 0);
}
});
}
}
18 changes: 18 additions & 0 deletions crates/bevy_ecs/src/system/query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1129,6 +1129,24 @@ impl<'w, 's, Q: WorldQuery, F: WorldQuery> Query<'w, 's, Q, F> {
}
}

impl<'w, 's, Q: WorldQuery, F: WorldQuery> IntoIterator for &'w Query<'_, 's, Q, F> {
type Item = ROQueryItem<'w, Q>;
type IntoIter = QueryIter<'w, 's, Q, ROQueryFetch<'w, Q>, F>;

fn into_iter(self) -> Self::IntoIter {
self.iter()
}
}

impl<'w, Q: WorldQuery, F: WorldQuery> IntoIterator for &'w mut Query<'_, '_, Q, F> {
type Item = QueryItem<'w, Q>;
type IntoIter = QueryIter<'w, 'w, Q, QueryFetch<'w, Q>, F>;

fn into_iter(self) -> Self::IntoIter {
self.iter_mut()
}
}

/// An error that occurs when retrieving a specific [`Entity`]'s component from a [`Query`]
#[derive(Debug)]
pub enum QueryComponentError {
Expand Down

0 comments on commit 8d0067e

Please sign in to comment.