Skip to content

Commit 55ad1b3

Browse files
tim-blackbirdItsDoot
authored andcommitted
Update codebase to use IntoIterator where possible. (bevyengine#5269)
Remove unnecessary calls to `iter()`/`iter_mut()`. Mainly updates the use of queries in our code, docs, and examples. ```rust // From for _ in list.iter() { for _ in list.iter_mut() { // To for _ in &list { for _ in &mut list { ``` We already enable the pedantic lint [clippy::explicit_iter_loop](https://rust-lang.github.io/rust-clippy/stable/) inside of Bevy. However, this only warns for a few known types from the standard library. ## Note for reviewers As you can see the additions and deletions are exactly equal. Maybe give it a quick skim to check I didn't sneak in a crypto miner, but you don't have to torture yourself by reading every line. I already experienced enough pain making this PR :) Co-authored-by: devil-ira <[email protected]>
1 parent 1744be3 commit 55ad1b3

File tree

95 files changed

+191
-191
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

95 files changed

+191
-191
lines changed

benches/benches/bevy_ecs/iteration/iter_simple_system.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ impl Benchmark {
3030
}
3131

3232
fn query_system(mut query: Query<(&Velocity, &mut Position)>) {
33-
for (velocity, mut position) in query.iter_mut() {
33+
for (velocity, mut position) in &mut query {
3434
position.0 += velocity.0;
3535
}
3636
}

benches/benches/bevy_ecs/world/commands.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -92,7 +92,7 @@ pub fn insert_commands(criterion: &mut Criterion) {
9292

9393
bencher.iter(|| {
9494
let mut commands = Commands::new(&mut command_queue, &world);
95-
for entity in entities.iter() {
95+
for entity in &entities {
9696
commands
9797
.entity(*entity)
9898
.insert_bundle((Matrix::default(), Vec3::default()));
@@ -112,7 +112,7 @@ pub fn insert_commands(criterion: &mut Criterion) {
112112
bencher.iter(|| {
113113
let mut commands = Commands::new(&mut command_queue, &world);
114114
let mut values = Vec::with_capacity(entity_count);
115-
for entity in entities.iter() {
115+
for entity in &entities {
116116
values.push((*entity, (Matrix::default(), Vec3::default())));
117117
}
118118
commands.insert_or_spawn_batch(values);

benches/benches/bevy_reflect/struct.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ fn concrete_struct_field(criterion: &mut Criterion) {
4343
.collect::<Vec<_>>();
4444

4545
bencher.iter(|| {
46-
for name in field_names.iter() {
46+
for name in &field_names {
4747
s.field(black_box(name));
4848
}
4949
});

crates/bevy_animation/src/lib.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -183,7 +183,7 @@ pub fn animation_player(
183183
mut transforms: Query<&mut Transform>,
184184
children: Query<&Children>,
185185
) {
186-
for (entity, mut player) in animation_players.iter_mut() {
186+
for (entity, mut player) in &mut animation_players {
187187
if let Some(animation_clip) = animations.get(&player.animation_clip) {
188188
// Continue if paused unless the `AnimationPlayer` was changed
189189
// This allow the animation to still be updated if the player.elapsed field was manually updated in pause

crates/bevy_asset/src/asset_server.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -110,7 +110,7 @@ impl AssetServer {
110110
{
111111
let mut loaders = self.server.loaders.write();
112112
let loader_index = loaders.len();
113-
for extension in loader.extensions().iter() {
113+
for extension in loader.extensions() {
114114
self.server
115115
.extension_to_loader_index
116116
.write()

crates/bevy_core_pipeline/src/core_3d/mod.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -236,7 +236,7 @@ pub fn prepare_core_3d_depth_textures(
236236
>,
237237
) {
238238
let mut textures = HashMap::default();
239-
for (entity, camera) in views_3d.iter() {
239+
for (entity, camera) in &views_3d {
240240
if let Some(physical_target_size) = camera.physical_target_size {
241241
let cached_texture = textures
242242
.entry(camera.target.clone())

crates/bevy_ecs/README.md

+5-5
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,7 @@ use bevy_ecs::prelude::*;
7878
struct Position { x: f32, y: f32 }
7979

8080
fn print_position(query: Query<(Entity, &Position)>) {
81-
for (entity, position) in query.iter() {
81+
for (entity, position) in &query {
8282
println!("Entity {:?} is at position: x {}, y {}", entity, position.x, position.y);
8383
}
8484
}
@@ -130,7 +130,7 @@ struct Velocity { x: f32, y: f32 }
130130

131131
// This system moves each entity with a Position and Velocity component
132132
fn movement(mut query: Query<(&mut Position, &Velocity)>) {
133-
for (mut position, velocity) in query.iter_mut() {
133+
for (mut position, velocity) in &mut query {
134134
position.x += velocity.x;
135135
position.y += velocity.y;
136136
}
@@ -176,7 +176,7 @@ struct Alive;
176176
// Gets the Position component of all Entities with Player component and without the Alive
177177
// component.
178178
fn system(query: Query<&Position, (With<Player>, Without<Alive>)>) {
179-
for position in query.iter() {
179+
for position in &query {
180180
}
181181
}
182182
```
@@ -197,13 +197,13 @@ struct Velocity { x: f32, y: f32 }
197197

198198
// Gets the Position component of all Entities whose Velocity has changed since the last run of the System
199199
fn system_changed(query: Query<&Position, Changed<Velocity>>) {
200-
for position in query.iter() {
200+
for position in &query {
201201
}
202202
}
203203

204204
// Gets the Position component of all Entities that had a Velocity component added since the last run of the System
205205
fn system_added(query: Query<&Position, Added<Velocity>>) {
206-
for position in query.iter() {
206+
for position in &query {
207207
}
208208
}
209209
```

crates/bevy_ecs/examples/change_detection.rs

+4-4
Original file line numberDiff line numberDiff line change
@@ -79,24 +79,24 @@ fn print_changed_entities(
7979
entity_with_added_component: Query<Entity, Added<Age>>,
8080
entity_with_mutated_component: Query<(Entity, &Age), Changed<Age>>,
8181
) {
82-
for entity in entity_with_added_component.iter() {
82+
for entity in &entity_with_added_component {
8383
println!(" {:?} has it's first birthday!", entity);
8484
}
85-
for (entity, value) in entity_with_mutated_component.iter() {
85+
for (entity, value) in &entity_with_mutated_component {
8686
println!(" {:?} is now {:?} frames old", entity, value);
8787
}
8888
}
8989

9090
// This system iterates over all entities and increases their age in every frame
9191
fn age_all_entities(mut entities: Query<&mut Age>) {
92-
for mut age in entities.iter_mut() {
92+
for mut age in &mut entities {
9393
age.frames += 1;
9494
}
9595
}
9696

9797
// This system iterates over all entities in every frame and despawns entities older than 2 frames
9898
fn remove_old_entities(mut commands: Commands, entities: Query<(Entity, &Age)>) {
99-
for (entity, age) in entities.iter() {
99+
for (entity, age) in &entities {
100100
if age.frames > 2 {
101101
println!(" despawning {:?} due to age > 2", entity);
102102
commands.entity(entity).despawn();

crates/bevy_ecs/macros/src/fetch.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -134,7 +134,7 @@ pub fn derive_world_query_impl(ast: DeriveInput) -> TokenStream {
134134
let mut field_idents = Vec::new();
135135
let mut field_types = Vec::new();
136136

137-
for field in fields.iter() {
137+
for field in fields {
138138
let WorldQueryFieldInfo { is_ignored, attrs } = read_world_query_field_info(field);
139139

140140
let field_ident = field.ident.as_ref().unwrap().clone();

crates/bevy_ecs/src/entity/mod.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -84,7 +84,7 @@ use std::{
8484
/// # struct Expired;
8585
/// #
8686
/// fn dispose_expired_food(mut commands: Commands, query: Query<Entity, With<Expired>>) {
87-
/// for food_entity in query.iter() {
87+
/// for food_entity in &query {
8888
/// commands.entity(food_entity).despawn();
8989
/// }
9090
/// }

crates/bevy_ecs/src/query/fetch.rs

+8-8
Original file line numberDiff line numberDiff line change
@@ -79,7 +79,7 @@ use std::{cell::UnsafeCell, marker::PhantomData};
7979
/// }
8080
///
8181
/// fn my_system(query: Query<MyQuery>) {
82-
/// for q in query.iter() {
82+
/// for q in &query {
8383
/// // Note the type of the returned item.
8484
/// let q: MyQueryItem<'_> = q;
8585
/// q.foo;
@@ -130,11 +130,11 @@ use std::{cell::UnsafeCell, marker::PhantomData};
130130
///
131131
/// fn my_system(mut health_query: Query<HealthQuery>) {
132132
/// // Iterator's item is `HealthQueryReadOnlyItem`.
133-
/// for health in health_query.iter() {
133+
/// for health in &health_query {
134134
/// println!("Total: {}", health.total());
135135
/// }
136136
/// // Iterator's item is `HealthQueryItem`.
137-
/// for mut health in health_query.iter_mut() {
137+
/// for mut health in &mut health_query {
138138
/// health.damage(1.0);
139139
/// println!("Total (mut): {}", health.total());
140140
/// }
@@ -158,7 +158,7 @@ use std::{cell::UnsafeCell, marker::PhantomData};
158158
/// }
159159
///
160160
/// fn my_system(mut my_query: Query<(FooReadOnly, FooReadOnly)>) {
161-
/// for (i1, i2) in my_query.iter_mut() {
161+
/// for (i1, i2) in &mut my_query {
162162
/// let _: FooReadOnlyItem<'_> = i1;
163163
/// let _: FooReadOnlyItem<'_> = i2;
164164
/// }
@@ -254,7 +254,7 @@ use std::{cell::UnsafeCell, marker::PhantomData};
254254
///
255255
/// // You can also compose derived queries with regular ones in tuples.
256256
/// fn my_system(query: Query<(&Foo, MyQuery, FooQuery)>) {
257-
/// for (foo, my_query, foo_query) in query.iter() {
257+
/// for (foo, my_query, foo_query) in &query {
258258
/// foo; my_query; foo_query;
259259
/// }
260260
/// }
@@ -279,7 +279,7 @@ use std::{cell::UnsafeCell, marker::PhantomData};
279279
/// }
280280
///
281281
/// fn my_system(query: Query<EmptyQuery>) {
282-
/// for _ in query.iter() {}
282+
/// for _ in &query {}
283283
/// }
284284
///
285285
/// # bevy_ecs::system::assert_is_system(my_system);
@@ -311,7 +311,7 @@ use std::{cell::UnsafeCell, marker::PhantomData};
311311
/// }
312312
///
313313
/// fn my_system(query: Query<Entity, MyFilter<Foo, Qux>>) {
314-
/// for _ in query.iter() {}
314+
/// for _ in &query {}
315315
/// }
316316
///
317317
/// # bevy_ecs::system::assert_is_system(my_system);
@@ -1087,7 +1087,7 @@ unsafe impl<'w, T: Fetch<'w>> Fetch<'w> for OptionFetch<T> {
10871087
/// # struct Transform {};
10881088
/// #
10891089
/// fn print_moving_objects_system(query: Query<(&Name, ChangeTrackers<Transform>)>) {
1090-
/// for (name, tracker) in query.iter() {
1090+
/// for (name, tracker) in &query {
10911091
/// if tracker.is_changed() {
10921092
/// println!("Entity moved: {:?}", name);
10931093
/// } else {

crates/bevy_ecs/src/query/filter.rs

+5-5
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ use super::ReadOnlyWorldQuery;
3636
/// # struct Name { name: &'static str };
3737
/// #
3838
/// fn compliment_entity_system(query: Query<&Name, With<IsBeautiful>>) {
39-
/// for name in query.iter() {
39+
/// for name in &query {
4040
/// println!("{} is looking lovely today!", name.name);
4141
/// }
4242
/// }
@@ -177,7 +177,7 @@ impl<T> Copy for WithFetch<T> {}
177177
/// # struct Name { name: &'static str };
178178
/// #
179179
/// fn no_permit_system(query: Query<&Name, Without<Permit>>) {
180-
/// for name in query.iter() {
180+
/// for name in &query{
181181
/// println!("{} has no permit!", name.name);
182182
/// }
183183
/// }
@@ -324,7 +324,7 @@ impl<T> Copy for WithoutFetch<T> {}
324324
/// # struct Style {};
325325
/// #
326326
/// fn print_cool_entity_system(query: Query<Entity, Or<(Changed<Color>, Changed<Style>)>>) {
327-
/// for entity in query.iter() {
327+
/// for entity in &query {
328328
/// println!("Entity {:?} got a new style or color", entity);
329329
/// }
330330
/// }
@@ -685,7 +685,7 @@ impl_tick_filter!(
685685
/// # struct Name {};
686686
///
687687
/// fn print_add_name_component(query: Query<&Name, Added<Name>>) {
688-
/// for name in query.iter() {
688+
/// for name in &query {
689689
/// println!("Named entity created: {:?}", name)
690690
/// }
691691
/// }
@@ -725,7 +725,7 @@ impl_tick_filter!(
725725
/// # struct Transform {};
726726
///
727727
/// fn print_moving_objects_system(query: Query<&Name, Changed<Transform>>) {
728-
/// for name in query.iter() {
728+
/// for name in &query {
729729
/// println!("Entity Moved: {:?}", name);
730730
/// }
731731
/// }

crates/bevy_ecs/src/query/state.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -264,7 +264,7 @@ impl<Q: WorldQuery, F: WorldQuery> QueryState<Q, F> {
264264
///
265265
/// let mut mutable_component_values = query_state.get_many_mut(&mut world, entities).unwrap();
266266
///
267-
/// for mut a in mutable_component_values.iter_mut(){
267+
/// for mut a in &mut mutable_component_values {
268268
/// a.0 += 5;
269269
/// }
270270
///
@@ -1074,7 +1074,7 @@ impl<Q: WorldQuery, F: WorldQuery> QueryState<Q, F> {
10741074

10751075
let tables = &world.storages.tables;
10761076

1077-
for entity in entity_list.into_iter() {
1077+
for entity in entity_list {
10781078
let location = match world.entities.get(*entity.borrow()) {
10791079
Some(location) => location,
10801080
None => continue,

crates/bevy_ecs/src/schedule/executor_parallel.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,7 @@ impl ParallelSystemExecutor for ParallelExecutor {
8181
self.should_run.grow(systems.len());
8282

8383
// Construct scheduling data for systems.
84-
for container in systems.iter() {
84+
for container in systems {
8585
let dependencies_total = container.dependencies().len();
8686
let system = container.system();
8787
let (start_sender, start_receiver) = async_channel::bounded(1);

crates/bevy_ecs/src/storage/table.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -492,7 +492,7 @@ impl Tables {
492492
.from_key(component_ids)
493493
.or_insert_with(|| {
494494
let mut table = Table::with_capacity(0, component_ids.len());
495-
for component_id in component_ids.iter() {
495+
for component_id in component_ids {
496496
table.add_column(components.get_info_unchecked(*component_id));
497497
}
498498
tables.push(table);

crates/bevy_ecs/src/system/commands/parallel_scope.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,7 @@ unsafe impl SystemParamState for ParallelCommandsState {
7575
}
7676

7777
fn apply(&mut self, world: &mut World) {
78-
for cq in self.thread_local_storage.iter_mut() {
78+
for cq in &mut self.thread_local_storage {
7979
cq.get_mut().apply(world);
8080
}
8181
}

crates/bevy_ecs/src/system/exclusive_system.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -128,7 +128,7 @@ mod tests {
128128
query: Query<Entity, With<Foo>>,
129129
mut counter: ResMut<usize>,
130130
) {
131-
for entity in query.iter() {
131+
for entity in &query {
132132
*counter += 1;
133133
commands.entity(entity).remove::<Foo>();
134134
}

crates/bevy_ecs/src/system/function_system.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -126,7 +126,7 @@ impl SystemMeta {
126126
/// world.resource_scope(|world, mut cached_state: Mut<CachedSystemState>| {
127127
/// let mut event_reader = cached_state.event_state.get_mut(world);
128128
///
129-
/// for events in event_reader.iter(){
129+
/// for events in event_reader.iter() {
130130
/// println!("Hello World!");
131131
/// };
132132
/// });

crates/bevy_ecs/src/system/mod.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@
2323
//! mut query: Query<(&Player, &mut Score)>,
2424
//! mut round: ResMut<Round>,
2525
//! ) {
26-
//! for (player, mut score) in query.iter_mut() {
26+
//! for (player, mut score) in &mut query {
2727
//! if player.alive {
2828
//! score.0 += round.0;
2929
//! }
@@ -135,7 +135,7 @@ mod tests {
135135
#[test]
136136
fn simple_system() {
137137
fn sys(query: Query<&A>) {
138-
for a in query.iter() {
138+
for a in &query {
139139
println!("{:?}", a);
140140
}
141141
}
@@ -598,7 +598,7 @@ mod tests {
598598
mut modified: ResMut<bool>,
599599
) {
600600
assert_eq!(query.iter().count(), 1, "entity exists");
601-
for entity in query.iter() {
601+
for entity in &query {
602602
let location = entities.get(entity).unwrap();
603603
let archetype = archetypes.get(location.archetype_id).unwrap();
604604
let archetype_components = archetype.components().collect::<Vec<_>>();

0 commit comments

Comments
 (0)