Skip to main content

bevy_ecs/system/
query.rs

1use bevy_utils::prelude::DebugName;
2
3use crate::{
4    batching::BatchingStrategy,
5    change_detection::Tick,
6    entity::{Entity, EntityEquivalent, EntitySet, UniqueEntityArray},
7    query::{
8        ArchetypeFilter, ContiguousQueryData, DebugCheckedUnwrap, IterQueryData, NopWorldQuery,
9        QueryCombinationIter, QueryContiguousIter, QueryData, QueryEntityError, QueryFilter,
10        QueryIter, QueryManyIter, QueryManyUniqueIter, QueryNotDenseError, QueryParIter,
11        QueryParManyIter, QueryParManyUniqueIter, QuerySingleError, QueryState, ROQueryItem,
12        ReadOnlyQueryData, SingleEntityQueryData,
13    },
14    world::unsafe_world_cell::UnsafeWorldCell,
15};
16use core::{
17    marker::PhantomData,
18    mem::MaybeUninit,
19    ops::{Deref, DerefMut},
20};
21
22/// A [system parameter] that provides selective access to the [`Component`] data stored in a [`World`].
23///
24/// Queries enable systems to access [entity identifiers] and [components] without requiring direct access to the [`World`].
25/// Its iterators and getter methods return *query items*, which are types containing data related to an entity.
26///
27/// `Query` is a generic data structure that accepts two type parameters:
28///
29/// - **`D` (query data)**:
30///   The type of data fetched by the query, which will be returned as the query item.
31///   Only entities that match the requested data will generate an item.
32///   Must implement the [`QueryData`] trait.
33/// - **`F` (query filter)**:
34///   An optional set of conditions that determine whether query items should be kept or discarded.
35///   This defaults to [`unit`], which means no additional filters will be applied.
36///   Must implement the [`QueryFilter`] trait.
37///
38/// [system parameter]: crate::system::SystemParam
39/// [`Component`]: crate::component::Component
40/// [`World`]: crate::world::World
41/// [entity identifiers]: Entity
42/// [components]: crate::component::Component
43///
44/// # Similar parameters
45///
46/// `Query` has few sibling [`SystemParam`]s, which perform additional validation:
47///
48/// - [`Single`] - Exactly one matching query item.
49/// - [`Option<Single>`] - Zero or one matching query item.
50/// - [`Populated`] - At least one matching query item.
51///
52/// These parameters will prevent systems from running if their requirements are not met.
53///
54/// [`SystemParam`]: crate::system::system_param::SystemParam
55/// [`Option<Single>`]: Single
56///
57/// # System parameter declaration
58///
59/// A query should always be declared as a system parameter.
60/// This section shows the most common idioms involving the declaration of `Query`.
61///
62/// ## Component access
63///
64/// You can fetch an entity's component by specifying a reference to that component in the query's data parameter:
65///
66/// ```
67/// # use bevy_ecs::prelude::*;
68/// #
69/// # #[derive(Component)]
70/// # struct ComponentA;
71/// #
72/// // A component can be accessed by a shared reference...
73/// fn immutable_query(query: Query<&ComponentA>) {
74///     // ...
75/// }
76///
77/// // ...or by a mutable reference.
78/// fn mutable_query(query: Query<&mut ComponentA>) {
79///     // ...
80/// }
81/// #
82/// # bevy_ecs::system::assert_is_system(immutable_query);
83/// # bevy_ecs::system::assert_is_system(mutable_query);
84/// ```
85///
86/// Note that components need to be behind a reference (`&` or `&mut`), or the query will not compile:
87///
88/// ```compile_fail,E0277
89/// # use bevy_ecs::prelude::*;
90/// #
91/// # #[derive(Component)]
92/// # struct ComponentA;
93/// #
94/// // This needs to be `&ComponentA` or `&mut ComponentA` in order to compile.
95/// fn invalid_query(query: Query<ComponentA>) {
96///     // ...
97/// }
98/// ```
99///
100/// ## Query filtering
101///
102/// Setting the query filter type parameter will ensure that each query item satisfies the given condition:
103///
104/// ```
105/// # use bevy_ecs::prelude::*;
106/// #
107/// # #[derive(Component)]
108/// # struct ComponentA;
109/// #
110/// # #[derive(Component)]
111/// # struct ComponentB;
112/// #
113/// // `ComponentA` data will be accessed, but only for entities that also contain `ComponentB`.
114/// fn filtered_query(query: Query<&ComponentA, With<ComponentB>>) {
115///     // ...
116/// }
117/// #
118/// # bevy_ecs::system::assert_is_system(filtered_query);
119/// ```
120///
121/// Note that the filter is `With<ComponentB>`, not `With<&ComponentB>`. Unlike query data, `With`
122/// does not require components to be behind a reference.
123///
124/// ## `QueryData` or `QueryFilter` tuples
125///
126/// Using [`tuple`]s, each `Query` type parameter can contain multiple elements.
127///
128/// In the following example two components are accessed simultaneously, and the query items are
129/// filtered on two conditions:
130///
131/// ```
132/// # use bevy_ecs::prelude::*;
133/// #
134/// # #[derive(Component)]
135/// # struct ComponentA;
136/// #
137/// # #[derive(Component)]
138/// # struct ComponentB;
139/// #
140/// # #[derive(Component)]
141/// # struct ComponentC;
142/// #
143/// # #[derive(Component)]
144/// # struct ComponentD;
145/// #
146/// fn complex_query(
147///     query: Query<(&mut ComponentA, &ComponentB), (With<ComponentC>, Without<ComponentD>)>
148/// ) {
149///     // ...
150/// }
151/// #
152/// # bevy_ecs::system::assert_is_system(complex_query);
153/// ```
154///
155/// Note that this currently only works on tuples with 15 or fewer items. You may nest tuples to
156/// get around this limit:
157///
158/// ```
159/// # use bevy_ecs::prelude::*;
160/// #
161/// # #[derive(Component)]
162/// # struct ComponentA;
163/// #
164/// # #[derive(Component)]
165/// # struct ComponentB;
166/// #
167/// # #[derive(Component)]
168/// # struct ComponentC;
169/// #
170/// # #[derive(Component)]
171/// # struct ComponentD;
172/// #
173/// fn nested_query(
174///     query: Query<(&ComponentA, &ComponentB, (&mut ComponentC, &mut ComponentD))>
175/// ) {
176///     // ...
177/// }
178/// #
179/// # bevy_ecs::system::assert_is_system(nested_query);
180/// ```
181///
182/// ## Entity identifier access
183///
184/// You can access [`Entity`], the entity identifier, by including it in the query data parameter:
185///
186/// ```
187/// # use bevy_ecs::prelude::*;
188/// #
189/// # #[derive(Component)]
190/// # struct ComponentA;
191/// #
192/// fn entity_id_query(query: Query<(Entity, &ComponentA)>) {
193///     // ...
194/// }
195/// #
196/// # bevy_ecs::system::assert_is_system(entity_id_query);
197/// ```
198///
199/// Be aware that [`Entity`] is not a component, so it does not need to be behind a reference.
200///
201/// ## Optional component access
202///
203/// A component can be made optional by wrapping it into an [`Option`]. In the following example, a
204/// query item will still be generated even if the queried entity does not contain `ComponentB`.
205/// When this is the case, `Option<&ComponentB>`'s corresponding value will be `None`.
206///
207/// ```
208/// # use bevy_ecs::prelude::*;
209/// #
210/// # #[derive(Component)]
211/// # struct ComponentA;
212/// #
213/// # #[derive(Component)]
214/// # struct ComponentB;
215/// #
216/// // Queried items must contain `ComponentA`. If they also contain `ComponentB`, its value will
217/// // be fetched as well.
218/// fn optional_component_query(query: Query<(&ComponentA, Option<&ComponentB>)>) {
219///     // ...
220/// }
221/// #
222/// # bevy_ecs::system::assert_is_system(optional_component_query);
223/// ```
224///
225/// Optional components can hurt performance in some cases, so please read the [performance]
226/// section to learn more about them. Additionally, if you need to declare several optional
227/// components, you may be interested in using [`AnyOf`].
228///
229/// [performance]: #performance
230/// [`AnyOf`]: crate::query::AnyOf
231///
232/// ## Disjoint queries
233///
234/// A system cannot contain two queries that break Rust's mutability rules, or else it will panic
235/// when initialized. This can often be fixed with the [`Without`] filter, which makes the queries
236/// disjoint.
237///
238/// In the following example, the two queries can mutably access the same `&mut Health` component
239/// if an entity has both the `Player` and `Enemy` components. Bevy will catch this and panic,
240/// however, instead of breaking Rust's mutability rules:
241///
242/// ```should_panic
243/// # use bevy_ecs::prelude::*;
244/// #
245/// # #[derive(Component)]
246/// # struct Health;
247/// #
248/// # #[derive(Component)]
249/// # struct Player;
250/// #
251/// # #[derive(Component)]
252/// # struct Enemy;
253/// #
254/// fn randomize_health(
255///     player_query: Query<&mut Health, With<Player>>,
256///     enemy_query: Query<&mut Health, With<Enemy>>,
257/// ) {
258///     // ...
259/// }
260/// #
261/// # bevy_ecs::system::assert_system_does_not_conflict(randomize_health);
262/// ```
263///
264/// Adding a [`Without`] filter will disjoint the queries. In the following example, any entity
265/// that has both the `Player` and `Enemy` components will be excluded from _both_ queries:
266///
267/// ```
268/// # use bevy_ecs::prelude::*;
269/// #
270/// # #[derive(Component)]
271/// # struct Health;
272/// #
273/// # #[derive(Component)]
274/// # struct Player;
275/// #
276/// # #[derive(Component)]
277/// # struct Enemy;
278/// #
279/// fn randomize_health(
280///     player_query: Query<&mut Health, (With<Player>, Without<Enemy>)>,
281///     enemy_query: Query<&mut Health, (With<Enemy>, Without<Player>)>,
282/// ) {
283///     // ...
284/// }
285/// #
286/// # bevy_ecs::system::assert_system_does_not_conflict(randomize_health);
287/// ```
288///
289/// An alternative solution to this problem would be to wrap the conflicting queries in
290/// [`ParamSet`].
291///
292/// [`Without`]: crate::query::Without
293/// [`ParamSet`]: crate::system::ParamSet
294///
295/// ## Whole Entity Access
296///
297/// [`EntityRef`] can be used in a query to gain read-only access to all components of an entity.
298/// This is useful when dynamically fetching components instead of baking them into the query type.
299///
300/// ```
301/// # use bevy_ecs::prelude::*;
302/// #
303/// # #[derive(Component)]
304/// # struct ComponentA;
305/// #
306/// fn all_components_query(query: Query<(EntityRef, &ComponentA)>) {
307///     // ...
308/// }
309/// #
310/// # bevy_ecs::system::assert_is_system(all_components_query);
311/// ```
312///
313/// As [`EntityRef`] can read any component on an entity, a query using it will conflict with *any*
314/// mutable component access.
315///
316/// ```should_panic
317/// # use bevy_ecs::prelude::*;
318/// #
319/// # #[derive(Component)]
320/// # struct ComponentA;
321/// #
322/// // `EntityRef` provides read access to *all* components on an entity. When combined with
323/// // `&mut ComponentA` in the same query, it creates a conflict because `EntityRef` could read
324/// // `&ComponentA` while `&mut ComponentA` attempts to modify it - violating Rust's borrowing
325/// // rules.
326/// fn invalid_query(query: Query<(EntityRef, &mut ComponentA)>) {
327///     // ...
328/// }
329/// #
330/// # bevy_ecs::system::assert_system_does_not_conflict(invalid_query);
331/// ```
332///
333/// It is strongly advised to couple [`EntityRef`] queries with the use of either [`With`] /
334/// [`Without`] filters or [`ParamSet`]s. Not only does this improve the performance and
335/// parallelization of the system, but it enables systems to gain mutable access to other
336/// components:
337///
338/// ```
339/// # use bevy_ecs::prelude::*;
340/// #
341/// # #[derive(Component)]
342/// # struct ComponentA;
343/// #
344/// # #[derive(Component)]
345/// # struct ComponentB;
346/// #
347/// // The first query only reads entities that have `ComponentA`, while the second query only
348/// // modifies entities that *don't* have `ComponentA`. Because neither query will access the same
349/// // entity, this system does not conflict.
350/// fn disjoint_query(
351///     query_a: Query<EntityRef, With<ComponentA>>,
352///     query_b: Query<&mut ComponentB, Without<ComponentA>>,
353/// ) {
354///     // ...
355/// }
356/// #
357/// # bevy_ecs::system::assert_system_does_not_conflict(disjoint_query);
358/// ```
359///
360/// The fundamental rule: [`EntityRef`]'s ability to read all components means it can never
361/// coexist with mutable access. [`With`] / [`Without`] filters can guarantee this by keeping the
362/// queries on completely separate entities.
363///
364/// [`EntityRef`]: crate::world::EntityRef
365/// [`With`]: crate::query::With
366///
367/// # Accessing query items
368///
369/// The following table summarizes the behavior of safe methods that can be used to get query
370/// items:
371///
372/// |Query methods|Effect|
373/// |-|-|
374/// |[`iter`]\[[`_mut`][`iter_mut`]\]|Returns an iterator over all query items.|
375/// |[`iter[_mut]().for_each()`][`for_each`],<br />[`par_iter`]\[[`_mut`][`par_iter_mut`]\]|Runs a specified function for each query item.|
376/// |[`iter_many`]\[[`_unique`][`iter_many_unique`]\]\[[`_mut`][`iter_many_mut`]\]|Iterates over query items that match a list of entities.|
377/// |[`iter_combinations`]\[[`_mut`][`iter_combinations_mut`]\]|Iterates over all combinations of query items.|
378/// |[`single`](Self::single)\[[`_mut`][`single_mut`]\]|Returns a single query item if only one exists.|
379/// |[`get`]\[[`_mut`][`get_mut`]\]|Returns the query item for a specified entity.|
380/// |[`get_many`]\[[`_unique`][`get_many_unique`]\]\[[`_mut`][`get_many_mut`]\]|Returns all query items that match a list of entities.|
381///
382/// There are two methods for each type of query operation: immutable and mutable (ending with `_mut`).
383/// When using immutable methods, the query items returned are of type [`ROQueryItem`], a read-only version of the query item.
384/// In this circumstance, every mutable reference in the query fetch type parameter is substituted by a shared reference.
385///
386/// [`iter`]: Self::iter
387/// [`iter_mut`]: Self::iter_mut
388/// [`for_each`]: #iteratorfor_each
389/// [`par_iter`]: Self::par_iter
390/// [`par_iter_mut`]: Self::par_iter_mut
391/// [`iter_many`]: Self::iter_many
392/// [`iter_many_unique`]: Self::iter_many_unique
393/// [`iter_many_mut`]: Self::iter_many_mut
394/// [`iter_combinations`]: Self::iter_combinations
395/// [`iter_combinations_mut`]: Self::iter_combinations_mut
396/// [`single_mut`]: Self::single_mut
397/// [`get`]: Self::get
398/// [`get_mut`]: Self::get_mut
399/// [`get_many`]: Self::get_many
400/// [`get_many_unique`]: Self::get_many_unique
401/// [`get_many_mut`]: Self::get_many_mut
402///
403/// # Performance
404///
405/// Creating a `Query` is a low-cost constant operation. Iterating it, on the other hand, fetches
406/// data from the world and generates items, which can have a significant computational cost.
407///
408/// Two systems cannot be executed in parallel if both access the same component type where at
409/// least one of the accesses is mutable. Because of this, it is recommended for queries to only
410/// fetch mutable access to components when necessary, since immutable access can be parallelized.
411///
412/// Query filters ([`With`] / [`Without`]) can improve performance because they narrow the kinds of
413/// entities that can be fetched. Systems that access fewer kinds of entities are more likely to be
414/// parallelized by the scheduler.
415///
416/// On the other hand, be careful using optional components (`Option<&ComponentA>`) and
417/// [`EntityRef`] because they broaden the amount of entities kinds that can be accessed. This is
418/// especially true of a query that _only_ fetches optional components or [`EntityRef`], as the
419/// query would iterate over all entities in the world.
420///
421/// There are two types of [component storage types]: [`Table`] and [`SparseSet`]. [`Table`] offers
422/// fast iteration speeds, but slower insertion and removal speeds. [`SparseSet`] is the opposite:
423/// it offers fast component insertion and removal speeds, but slower iteration speeds.
424///
425/// The following table compares the computational complexity of the various methods and
426/// operations, where:
427///
428/// - **n** is the number of entities that match the query.
429/// - **r** is the number of elements in a combination.
430/// - **k** is the number of involved entities in the operation.
431/// - **a** is the number of archetypes in the world.
432/// - **C** is the [binomial coefficient], used to count combinations. <sub>n</sub>C<sub>r</sub> is
433///   read as "*n* choose *r*" and is equivalent to the number of distinct unordered subsets of *r*
434///   elements that can be taken from a set of *n* elements.
435///
436/// |Query operation|Computational complexity|
437/// |-|-|
438/// |[`iter`]\[[`_mut`][`iter_mut`]\]|O(n)|
439/// |[`iter[_mut]().for_each()`][`for_each`],<br/>[`par_iter`]\[[`_mut`][`par_iter_mut`]\]|O(n)|
440/// |[`iter_many`]\[[`_mut`][`iter_many_mut`]\]|O(k)|
441/// |[`iter_combinations`]\[[`_mut`][`iter_combinations_mut`]\]|O(<sub>n</sub>C<sub>r</sub>)|
442/// |[`single`](Self::single)\[[`_mut`][`single_mut`]\]|O(a)|
443/// |[`get`]\[[`_mut`][`get_mut`]\]|O(1)|
444/// |[`get_many`]|O(k)|
445/// |[`get_many_mut`]|O(k<sup>2</sup>)|
446/// |Archetype-based filtering ([`With`], [`Without`], [`Or`])|O(a)|
447/// |Change detection filtering ([`Added`], [`Changed`], [`Spawned`])|O(a + n)|
448///
449/// [component storage types]: crate::component::StorageType
450/// [`Table`]: crate::storage::Table
451/// [`SparseSet`]: crate::storage::SparseSet
452/// [binomial coefficient]: https://en.wikipedia.org/wiki/Binomial_coefficient
453/// [`Or`]: crate::query::Or
454/// [`Added`]: crate::query::Added
455/// [`Changed`]: crate::query::Changed
456/// [`Spawned`]: crate::query::Spawned
457///
458/// # `Iterator::for_each`
459///
460/// The `for_each` methods appear to be generally faster than `for`-loops when run on worlds with
461/// high archetype fragmentation, and may enable additional optimizations like [autovectorization]. It
462/// is strongly advised to only use [`Iterator::for_each`] if it tangibly improves performance.
463/// *Always* profile or benchmark before and after the change!
464///
465/// ```rust
466/// # use bevy_ecs::prelude::*;
467/// #
468/// # #[derive(Component)]
469/// # struct ComponentA;
470/// #
471/// fn system(query: Query<&ComponentA>) {
472///     // This may result in better performance...
473///     query.iter().for_each(|component| {
474///         // ...
475///     });
476///
477///     // ...than this. Always benchmark to validate the difference!
478///     for component in query.iter() {
479///         // ...
480///     }
481/// }
482/// #
483/// # bevy_ecs::system::assert_is_system(system);
484/// ```
485///
486/// [autovectorization]: https://en.wikipedia.org/wiki/Automatic_vectorization
487pub struct Query<'world, 'state, D: QueryData, F: QueryFilter = ()> {
488    // SAFETY: Must have access to the components registered in `state`.
489    world: UnsafeWorldCell<'world>,
490    state: &'state QueryState<D, F>,
491    last_run: Tick,
492    this_run: Tick,
493}
494
495impl<D: ReadOnlyQueryData, F: QueryFilter> Clone for Query<'_, '_, D, F> {
496    fn clone(&self) -> Self {
497        *self
498    }
499}
500
501impl<D: ReadOnlyQueryData, F: QueryFilter> Copy for Query<'_, '_, D, F> {}
502
503impl<D: QueryData, F: QueryFilter> core::fmt::Debug for Query<'_, '_, D, F> {
504    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
505        f.debug_struct("Query")
506            .field("matched_entities", &self.iter().count())
507            .field("state", &self.state)
508            .field("last_run", &self.last_run)
509            .field("this_run", &self.this_run)
510            .field("world", &self.world)
511            .finish()
512    }
513}
514
515impl<'w, 's, D: QueryData, F: QueryFilter> Query<'w, 's, D, F> {
516    /// Creates a new query.
517    ///
518    /// # Safety
519    ///
520    /// * This will create a query that could violate memory safety rules. Make sure that this is only
521    ///   called in ways that ensure the queries have unique mutable access.
522    /// * `world` must be the world used to create `state`.
523    #[inline]
524    pub(crate) unsafe fn new(
525        world: UnsafeWorldCell<'w>,
526        state: &'s QueryState<D, F>,
527        last_run: Tick,
528        this_run: Tick,
529    ) -> Self {
530        Self {
531            world,
532            state,
533            last_run,
534            this_run,
535        }
536    }
537
538    /// Returns another `Query` from this that fetches the read-only version of the query items.
539    ///
540    /// For example, `Query<(&mut D1, &D2, &mut D3), With<F>>` will become `Query<(&D1, &D2, &D3), With<F>>`.
541    /// This can be useful when working around the borrow checker,
542    /// or reusing functionality between systems via functions that accept query types.
543    ///
544    /// # See also
545    ///
546    /// [`into_readonly`](Self::into_readonly) for a version that consumes the `Query` to return one with the full `'world` lifetime.
547    pub fn as_readonly(&self) -> Query<'_, 's, D::ReadOnly, F> {
548        // SAFETY: The reborrowed query is converted to read-only, so it cannot perform mutable access,
549        // and the original query is held with a shared borrow, so it cannot perform mutable access either.
550        unsafe { self.reborrow_unsafe() }.into_readonly()
551    }
552
553    /// Returns another `Query` from this does not return any data, which can be faster.
554    ///
555    /// The resulting query will ignore any non-archetypal filters in `D`,
556    /// so this is only equivalent if `D::IS_ARCHETYPAL` is `true`.
557    fn as_nop(&self) -> Query<'_, 's, NopWorldQuery<D>, F> {
558        let new_state = self.state.as_nop();
559        // SAFETY:
560        // - The reborrowed query is converted to read-only, so it cannot perform mutable access,
561        //   and the original query is held with a shared borrow, so it cannot perform mutable access either.
562        //   Note that although `NopWorldQuery` itself performs *no* access and could soundly alias a mutable query,
563        //   it has the original `QueryState::component_access` and could be `transmute`d to a read-only query.
564        // - The world matches because it was the same one used to construct self.
565        unsafe { Query::new(self.world, new_state, self.last_run, self.this_run) }
566    }
567
568    /// Returns another `Query` from this that fetches the read-only version of the query items.
569    ///
570    /// For example, `Query<(&mut D1, &D2, &mut D3), With<F>>` will become `Query<(&D1, &D2, &D3), With<F>>`.
571    /// This can be useful when working around the borrow checker,
572    /// or reusing functionality between systems via functions that accept query types.
573    ///
574    /// # See also
575    ///
576    /// [`as_readonly`](Self::as_readonly) for a version that borrows the `Query` instead of consuming it.
577    pub fn into_readonly(self) -> Query<'w, 's, D::ReadOnly, F> {
578        let new_state = self.state.as_readonly();
579        // SAFETY:
580        // - This is memory safe because it turns the query immutable.
581        // - The world matches because it was the same one used to construct self.
582        unsafe { Query::new(self.world, new_state, self.last_run, self.this_run) }
583    }
584
585    /// Returns a new `Query` reborrowing the access from this one. The current query will be unusable
586    /// while the new one exists.
587    ///
588    /// # Example
589    ///
590    /// For example this allows to call other methods or other systems that require an owned `Query` without
591    /// completely giving up ownership of it.
592    ///
593    /// ```
594    /// # use bevy_ecs::prelude::*;
595    /// #
596    /// # #[derive(Component)]
597    /// # struct ComponentA;
598    ///
599    /// fn helper_system(query: Query<&ComponentA>) { /* ... */}
600    ///
601    /// fn system(mut query: Query<&ComponentA>) {
602    ///     helper_system(query.reborrow());
603    ///     // Can still use query here:
604    ///     for component in &query {
605    ///         // ...
606    ///     }
607    /// }
608    /// ```
609    pub fn reborrow(&mut self) -> Query<'_, 's, D, F> {
610        // SAFETY: this query is exclusively borrowed while the new one exists, so
611        // no overlapping access can occur.
612        unsafe { self.reborrow_unsafe() }
613    }
614
615    /// Returns a new `Query` reborrowing the access from this one.
616    /// The current query will still be usable while the new one exists, but must not be used in a way that violates aliasing.
617    ///
618    /// # Safety
619    ///
620    /// This function makes it possible to violate Rust's aliasing guarantees.
621    /// You must make sure this call does not result in a mutable or shared reference to a component with a mutable reference.
622    ///
623    /// # See also
624    ///
625    /// - [`reborrow`](Self::reborrow) for the safe versions.
626    pub unsafe fn reborrow_unsafe(&self) -> Query<'_, 's, D, F> {
627        // SAFETY:
628        // - This is memory safe because the caller ensures that there are no conflicting references.
629        // - The world matches because it was the same one used to construct self.
630        unsafe { self.copy_unsafe() }
631    }
632
633    /// Returns a new `Query` copying the access from this one.
634    /// The current query will still be usable while the new one exists, but must not be used in a way that violates aliasing.
635    ///
636    /// # Safety
637    ///
638    /// This function makes it possible to violate Rust's aliasing guarantees.
639    /// You must make sure this call does not result in a mutable or shared reference to a component with a mutable reference.
640    ///
641    /// # See also
642    ///
643    /// - [`reborrow_unsafe`](Self::reborrow_unsafe) for a safer version that constrains the returned `'w` lifetime to the length of the borrow.
644    unsafe fn copy_unsafe(&self) -> Query<'w, 's, D, F> {
645        // SAFETY:
646        // - This is memory safe because the caller ensures that there are no conflicting references.
647        // - The world matches because it was the same one used to construct self.
648        unsafe { Query::new(self.world, self.state, self.last_run, self.this_run) }
649    }
650
651    /// Returns an [`Iterator`] over the read-only query items.
652    ///
653    /// This iterator is always guaranteed to return results from each matching entity once and only once.
654    /// Iteration order is not guaranteed.
655    ///
656    /// # Example
657    ///
658    /// Here, the `report_names_system` iterates over the `Player` component of every entity that contains it:
659    ///
660    /// ```
661    /// # use bevy_ecs::prelude::*;
662    /// #
663    /// # #[derive(Component)]
664    /// # struct Player { name: String }
665    /// #
666    /// fn report_names_system(query: Query<&Player>) {
667    ///     for player in &query {
668    ///         println!("Say hello to {}!", player.name);
669    ///     }
670    /// }
671    /// # bevy_ecs::system::assert_is_system(report_names_system);
672    /// ```
673    ///
674    /// # See also
675    ///
676    /// [`iter_mut`](Self::iter_mut) for mutable query items.
677    #[inline]
678    pub fn iter(&self) -> QueryIter<'_, 's, D::ReadOnly, F> {
679        self.as_readonly().into_iter()
680    }
681
682    /// Returns an [`Iterator`] over the query items.
683    ///
684    /// This iterator is always guaranteed to return results from each matching entity once and only once.
685    /// Iteration order is not guaranteed.
686    ///
687    /// If the [`QueryData`] does not implement [`IterQueryData`],
688    /// then it is not sound to yield multiple items concurrently
689    /// and the resulting [`QueryIter`] will not implement [`Iterator`].
690    /// To iterate over the items in that case,
691    /// use the [`QueryIter::fetch_next()`](crate::query::QueryIter::fetch_next) method,
692    /// which ensures only one item is alive at a time.
693    ///
694    /// # Example
695    ///
696    /// Here, the `gravity_system` updates the `Velocity` component of every entity that contains it:
697    ///
698    /// ```
699    /// # use bevy_ecs::prelude::*;
700    /// #
701    /// # #[derive(Component)]
702    /// # struct Velocity { x: f32, y: f32, z: f32 }
703    /// fn gravity_system(mut query: Query<&mut Velocity>) {
704    ///     const DELTA: f32 = 1.0 / 60.0;
705    ///     for mut velocity in &mut query {
706    ///         velocity.y -= 9.8 * DELTA;
707    ///     }
708    /// }
709    /// # bevy_ecs::system::assert_is_system(gravity_system);
710    /// ```
711    ///
712    /// # See also
713    ///
714    /// [`iter`](Self::iter) for read-only query items.
715    #[inline]
716    pub fn iter_mut(&mut self) -> QueryIter<'_, 's, D, F> {
717        self.reborrow().iter_inner()
718    }
719
720    /// Returns an [`Iterator`] over the query items, with the actual "inner" world lifetime.
721    ///
722    /// This iterator is always guaranteed to return results from each matching entity once and only once.
723    /// Iteration order is not guaranteed.
724    ///
725    /// If the [`QueryData`] does not implement [`IterQueryData`],
726    /// then it is not sound to yield multiple items concurrently
727    /// and the resulting [`QueryIter`] will not implement [`Iterator`].
728    /// To iterate over the items in that case,
729    /// use the [`QueryIter::fetch_next()`](crate::query::QueryIter::fetch_next) method,
730    /// which ensures only one item is alive at a time.
731    ///
732    /// # Example
733    ///
734    /// Here, the `report_names_system` iterates over the `Player` component of every entity
735    /// that contains it:
736    ///
737    /// ```
738    /// # use bevy_ecs::prelude::*;
739    /// #
740    /// # #[derive(Component)]
741    /// # struct Player { name: String }
742    /// #
743    /// fn report_names_system(query: Query<&Player>) {
744    ///     for player in &query {
745    ///         println!("Say hello to {}!", player.name);
746    ///     }
747    /// }
748    /// # bevy_ecs::system::assert_is_system(report_names_system);
749    /// ```
750    #[inline]
751    pub fn iter_inner(self) -> QueryIter<'w, 's, D, F> {
752        // SAFETY:
753        // - `self.world` has permission to access the required components.
754        // - We consume the query, so mutable queries cannot alias.
755        //   Read-only queries are `Copy`, but may alias themselves.
756        unsafe { QueryIter::new(self.world, self.state, self.last_run, self.this_run) }
757    }
758
759    /// Returns a [`QueryCombinationIter`] over all combinations of `K` read-only query items without repetition.
760    ///
761    /// This iterator is always guaranteed to return results from each unique pair of matching entities.
762    /// Iteration order is not guaranteed.
763    ///
764    /// # Example
765    ///
766    /// ```
767    /// # use bevy_ecs::prelude::*;
768    /// # #[derive(Component)]
769    /// # struct ComponentA;
770    /// #
771    /// fn some_system(query: Query<&ComponentA>) {
772    ///     for [a1, a2] in query.iter_combinations() {
773    ///         // ...
774    ///     }
775    /// }
776    /// ```
777    ///
778    /// # See also
779    ///
780    /// - [`iter_combinations_mut`](Self::iter_combinations_mut) for mutable query item combinations.
781    /// - [`iter_combinations_inner`](Self::iter_combinations_inner) for mutable query item combinations with the full `'world` lifetime.
782    #[inline]
783    pub fn iter_combinations<const K: usize>(
784        &self,
785    ) -> QueryCombinationIter<'_, 's, D::ReadOnly, F, K> {
786        self.as_readonly().iter_combinations_inner()
787    }
788
789    /// Returns a [`QueryCombinationIter`] over all combinations of `K` query items without repetition.
790    ///
791    /// This iterator is always guaranteed to return results from each unique pair of matching entities.
792    /// Iteration order is not guaranteed.
793    ///
794    /// # Example
795    ///
796    /// ```
797    /// # use bevy_ecs::prelude::*;
798    /// # #[derive(Component)]
799    /// # struct ComponentA;
800    /// fn some_system(mut query: Query<&mut ComponentA>) {
801    ///     let mut combinations = query.iter_combinations_mut();
802    ///     while let Some([mut a1, mut a2]) = combinations.fetch_next() {
803    ///         // mutably access components data
804    ///     }
805    /// }
806    /// ```
807    ///
808    /// # See also
809    ///
810    /// - [`iter_combinations`](Self::iter_combinations) for read-only query item combinations.
811    /// - [`iter_combinations_inner`](Self::iter_combinations_inner) for mutable query item combinations with the full `'world` lifetime.
812    #[inline]
813    pub fn iter_combinations_mut<const K: usize>(&mut self) -> QueryCombinationIter<'_, 's, D, F, K>
814    where
815        D: IterQueryData,
816    {
817        self.reborrow().iter_combinations_inner()
818    }
819
820    /// Returns a [`QueryCombinationIter`] over all combinations of `K` query items without repetition.
821    /// This consumes the [`Query`] to return results with the actual "inner" world lifetime.
822    ///
823    /// This iterator is always guaranteed to return results from each unique pair of matching entities.
824    /// Iteration order is not guaranteed.
825    ///
826    /// # Example
827    ///
828    /// ```
829    /// # use bevy_ecs::prelude::*;
830    /// # #[derive(Component)]
831    /// # struct ComponentA;
832    /// fn some_system(query: Query<&mut ComponentA>) {
833    ///     let mut combinations = query.iter_combinations_inner();
834    ///     while let Some([mut a1, mut a2]) = combinations.fetch_next() {
835    ///         // mutably access components data
836    ///     }
837    /// }
838    /// ```
839    ///
840    /// # See also
841    ///
842    /// - [`iter_combinations`](Self::iter_combinations) for read-only query item combinations.
843    /// - [`iter_combinations_mut`](Self::iter_combinations_mut) for mutable query item combinations.
844    #[inline]
845    pub fn iter_combinations_inner<const K: usize>(self) -> QueryCombinationIter<'w, 's, D, F, K>
846    where
847        D: IterQueryData,
848    {
849        // SAFETY: `self.world` has permission to access the required components.
850        unsafe { QueryCombinationIter::new(self.world, self.state, self.last_run, self.this_run) }
851    }
852
853    /// Returns an [`Iterator`] over the read-only query items generated from an [`Entity`] list.
854    ///
855    /// Items are returned in the order of the list of entities, and may not be unique if the input
856    /// doesn't guarantee uniqueness. Entities that don't match the query are skipped.
857    ///
858    /// # Example
859    ///
860    /// ```
861    /// # use bevy_ecs::prelude::*;
862    /// # #[derive(Component)]
863    /// # struct Counter {
864    /// #     value: i32
865    /// # }
866    /// #
867    /// // A component containing an entity list.
868    /// #[derive(Component)]
869    /// struct Friends {
870    ///     list: Vec<Entity>,
871    /// }
872    ///
873    /// fn system(
874    ///     friends_query: Query<&Friends>,
875    ///     counter_query: Query<&Counter>,
876    /// ) {
877    ///     for friends in &friends_query {
878    ///         for counter in counter_query.iter_many(&friends.list) {
879    ///             println!("Friend's counter: {}", counter.value);
880    ///         }
881    ///     }
882    /// }
883    /// # bevy_ecs::system::assert_is_system(system);
884    /// ```
885    ///
886    /// # See also
887    ///
888    /// - [`iter_many_mut`](Self::iter_many_mut) to get mutable query items.
889    /// - [`iter_many_inner`](Self::iter_many_inner) to get mutable query items with the full `'world` lifetime.
890    #[inline]
891    pub fn iter_many<EntityList: IntoIterator<Item: EntityEquivalent>>(
892        &self,
893        entities: EntityList,
894    ) -> QueryManyIter<'_, 's, D::ReadOnly, F, EntityList::IntoIter> {
895        self.as_readonly().iter_many_inner(entities)
896    }
897
898    /// Returns an iterator over the query items generated from an [`Entity`] list.
899    ///
900    /// Items are returned in the order of the list of entities, and may not be unique if the input
901    /// doesn't guarantee uniqueness. Entities that don't match the query are skipped.
902    ///
903    /// # Examples
904    ///
905    /// ```
906    /// # use bevy_ecs::prelude::*;
907    /// #[derive(Component)]
908    /// struct Counter {
909    ///     value: i32
910    /// }
911    ///
912    /// #[derive(Component)]
913    /// struct Friends {
914    ///     list: Vec<Entity>,
915    /// }
916    ///
917    /// fn system(
918    ///     friends_query: Query<&Friends>,
919    ///     mut counter_query: Query<&mut Counter>,
920    /// ) {
921    ///     for friends in &friends_query {
922    ///         let mut iter = counter_query.iter_many_mut(&friends.list);
923    ///         while let Some(mut counter) = iter.fetch_next() {
924    ///             println!("Friend's counter: {}", counter.value);
925    ///             counter.value += 1;
926    ///         }
927    ///     }
928    /// }
929    /// # bevy_ecs::system::assert_is_system(system);
930    /// ```
931    /// # See also
932    ///
933    /// - [`iter_many`](Self::iter_many) to get read-only query items.
934    /// - [`iter_many_inner`](Self::iter_many_inner) to get mutable query items with the full `'world` lifetime.
935    #[inline]
936    pub fn iter_many_mut<EntityList: IntoIterator<Item: EntityEquivalent>>(
937        &mut self,
938        entities: EntityList,
939    ) -> QueryManyIter<'_, 's, D, F, EntityList::IntoIter> {
940        self.reborrow().iter_many_inner(entities)
941    }
942
943    /// Returns an iterator over the query items generated from an [`Entity`] list.
944    /// This consumes the [`Query`] to return results with the actual "inner" world lifetime.
945    ///
946    /// Items are returned in the order of the list of entities, and may not be unique if the input
947    /// doesn't guarantee uniqueness. Entities that don't match the query are skipped.
948    ///
949    /// # See also
950    ///
951    /// - [`iter_many`](Self::iter_many) to get read-only query items.
952    /// - [`iter_many_mut`](Self::iter_many_mut) to get mutable query items.
953    #[inline]
954    pub fn iter_many_inner<EntityList: IntoIterator<Item: EntityEquivalent>>(
955        self,
956        entities: EntityList,
957    ) -> QueryManyIter<'w, 's, D, F, EntityList::IntoIter> {
958        // SAFETY: `self.world` has permission to access the required components.
959        unsafe {
960            QueryManyIter::new(
961                self.world,
962                self.state,
963                entities,
964                self.last_run,
965                self.this_run,
966            )
967        }
968    }
969
970    /// Returns an [`Iterator`] over the unique read-only query items generated from an [`EntitySet`].
971    ///
972    /// Items are returned in the order of the list of entities. Entities that don't match the query are skipped.
973    ///
974    /// # Example
975    ///
976    /// ```
977    /// # use bevy_ecs::{prelude::*, entity::{EntitySet, UniqueEntityIter}};
978    /// # use core::slice;
979    /// # #[derive(Component)]
980    /// # struct Counter {
981    /// #     value: i32
982    /// # }
983    /// #
984    /// // `Friends` ensures that it only lists unique entities.
985    /// #[derive(Component)]
986    /// struct Friends {
987    ///     unique_list: Vec<Entity>,
988    /// }
989    ///
990    /// impl<'a> IntoIterator for &'a Friends {
991    ///
992    ///     type Item = &'a Entity;
993    ///     type IntoIter = UniqueEntityIter<slice::Iter<'a, Entity>>;
994    ///
995    ///     fn into_iter(self) -> Self::IntoIter {
996    ///         // SAFETY: `Friends` ensures that it unique_list contains only unique entities.
997    ///        unsafe { UniqueEntityIter::from_iter_unchecked(self.unique_list.iter()) }
998    ///     }
999    /// }
1000    ///
1001    /// fn system(
1002    ///     friends_query: Query<&Friends>,
1003    ///     counter_query: Query<&Counter>,
1004    /// ) {
1005    ///     for friends in &friends_query {
1006    ///         for counter in counter_query.iter_many_unique(friends) {
1007    ///             println!("Friend's counter: {:?}", counter.value);
1008    ///         }
1009    ///     }
1010    /// }
1011    /// # bevy_ecs::system::assert_is_system(system);
1012    /// ```
1013    ///
1014    /// # See also
1015    ///
1016    /// - [`iter_many_unique_mut`](Self::iter_many_unique_mut) to get mutable query items.
1017    /// - [`iter_many_unique_inner`](Self::iter_many_unique_inner) to get with the actual "inner" world lifetime.
1018    #[inline]
1019    pub fn iter_many_unique<EntityList: EntitySet>(
1020        &self,
1021        entities: EntityList,
1022    ) -> QueryManyUniqueIter<'_, 's, D::ReadOnly, F, EntityList::IntoIter> {
1023        self.as_readonly().iter_many_unique_inner(entities)
1024    }
1025
1026    /// Returns an iterator over the unique query items generated from an [`EntitySet`].
1027    ///
1028    /// Items are returned in the order of the list of entities. Entities that don't match the query are skipped.
1029    ///
1030    /// # Examples
1031    ///
1032    /// ```
1033    /// # use bevy_ecs::{prelude::*, entity::{EntitySet, UniqueEntityIter}};
1034    /// # use core::slice;
1035    /// #[derive(Component)]
1036    /// struct Counter {
1037    ///     value: i32
1038    /// }
1039    ///
1040    /// // `Friends` ensures that it only lists unique entities.
1041    /// #[derive(Component)]
1042    /// struct Friends {
1043    ///     unique_list: Vec<Entity>,
1044    /// }
1045    ///
1046    /// impl<'a> IntoIterator for &'a Friends {
1047    ///     type Item = &'a Entity;
1048    ///     type IntoIter = UniqueEntityIter<slice::Iter<'a, Entity>>;
1049    ///
1050    ///     fn into_iter(self) -> Self::IntoIter {
1051    ///         // SAFETY: `Friends` ensures that it unique_list contains only unique entities.
1052    ///         unsafe { UniqueEntityIter::from_iter_unchecked(self.unique_list.iter()) }
1053    ///     }
1054    /// }
1055    ///
1056    /// fn system(
1057    ///     friends_query: Query<&Friends>,
1058    ///     mut counter_query: Query<&mut Counter>,
1059    /// ) {
1060    ///     for friends in &friends_query {
1061    ///         for mut counter in counter_query.iter_many_unique_mut(friends) {
1062    ///             println!("Friend's counter: {:?}", counter.value);
1063    ///             counter.value += 1;
1064    ///         }
1065    ///     }
1066    /// }
1067    /// # bevy_ecs::system::assert_is_system(system);
1068    /// ```
1069    /// # See also
1070    ///
1071    /// - [`iter_many_unique`](Self::iter_many_unique) to get read-only query items.
1072    /// - [`iter_many_unique_inner`](Self::iter_many_unique_inner) to get with the actual "inner" world lifetime.
1073    #[inline]
1074    pub fn iter_many_unique_mut<EntityList: EntitySet>(
1075        &mut self,
1076        entities: EntityList,
1077    ) -> QueryManyUniqueIter<'_, 's, D, F, EntityList::IntoIter>
1078    where
1079        D: IterQueryData,
1080    {
1081        self.reborrow().iter_many_unique_inner(entities)
1082    }
1083
1084    /// Returns an iterator over the unique query items generated from an [`EntitySet`].
1085    /// This consumes the [`Query`] to return results with the actual "inner" world lifetime.
1086    ///
1087    /// Items are returned in the order of the list of entities. Entities that don't match the query are skipped.
1088    ///
1089    /// # Examples
1090    ///
1091    /// ```
1092    /// # use bevy_ecs::{prelude::*, entity::{EntitySet, UniqueEntityIter}};
1093    /// # use core::slice;
1094    /// #[derive(Component)]
1095    /// struct Counter {
1096    ///     value: i32
1097    /// }
1098    ///
1099    /// // `Friends` ensures that it only lists unique entities.
1100    /// #[derive(Component)]
1101    /// struct Friends {
1102    ///     unique_list: Vec<Entity>,
1103    /// }
1104    ///
1105    /// impl<'a> IntoIterator for &'a Friends {
1106    ///     type Item = &'a Entity;
1107    ///     type IntoIter = UniqueEntityIter<slice::Iter<'a, Entity>>;
1108    ///
1109    ///     fn into_iter(self) -> Self::IntoIter {
1110    ///         // SAFETY: `Friends` ensures that it unique_list contains only unique entities.
1111    ///         unsafe { UniqueEntityIter::from_iter_unchecked(self.unique_list.iter()) }
1112    ///     }
1113    /// }
1114    ///
1115    /// fn system(
1116    ///     friends_query: Query<&Friends>,
1117    ///     mut counter_query: Query<&mut Counter>,
1118    /// ) {
1119    ///     let friends = friends_query.single().unwrap();
1120    ///     for mut counter in counter_query.iter_many_unique_inner(friends) {
1121    ///         println!("Friend's counter: {:?}", counter.value);
1122    ///         counter.value += 1;
1123    ///     }
1124    /// }
1125    /// # bevy_ecs::system::assert_is_system(system);
1126    /// ```
1127    /// # See also
1128    ///
1129    /// - [`iter_many_unique`](Self::iter_many_unique) to get read-only query items.
1130    /// - [`iter_many_unique_mut`](Self::iter_many_unique_mut) to get mutable query items.
1131    #[inline]
1132    pub fn iter_many_unique_inner<EntityList: EntitySet>(
1133        self,
1134        entities: EntityList,
1135    ) -> QueryManyUniqueIter<'w, 's, D, F, EntityList::IntoIter>
1136    where
1137        D: IterQueryData,
1138    {
1139        // SAFETY: `self.world` has permission to access the required components.
1140        unsafe {
1141            QueryManyUniqueIter::new(
1142                self.world,
1143                self.state,
1144                entities,
1145                self.last_run,
1146                self.this_run,
1147            )
1148        }
1149    }
1150
1151    /// Returns an [`Iterator`] over the query items.
1152    ///
1153    /// This iterator is always guaranteed to return results from each matching entity once and only once.
1154    /// Iteration order is not guaranteed.
1155    ///
1156    /// If the [`QueryData`] does not implement [`IterQueryData`],
1157    /// then it is not sound to yield multiple items concurrently
1158    /// and the resulting [`QueryIter`] will not implement [`Iterator`].
1159    /// To iterate over the items in that case,
1160    /// use the [`QueryIter::fetch_next()`](crate::query::QueryIter::fetch_next) method,
1161    /// which ensures only one item is alive at a time.
1162    ///
1163    /// # Safety
1164    ///
1165    /// This function makes it possible to violate Rust's aliasing guarantees.
1166    /// You must make sure this call does not result in multiple mutable references to the same component.
1167    ///
1168    /// # See also
1169    ///
1170    /// - [`iter`](Self::iter) and [`iter_mut`](Self::iter_mut) for the safe versions.
1171    #[inline]
1172    pub unsafe fn iter_unsafe(&self) -> QueryIter<'_, 's, D, F>
1173    where
1174        D: IterQueryData,
1175    {
1176        // SAFETY: The caller promises that this will not result in multiple mutable references.
1177        unsafe { self.reborrow_unsafe() }.into_iter()
1178    }
1179
1180    /// Iterates over all possible combinations of `K` query items without repetition.
1181    ///
1182    /// This iterator is always guaranteed to return results from each unique pair of matching entities.
1183    /// Iteration order is not guaranteed.
1184    ///
1185    /// # Safety
1186    ///
1187    /// This allows aliased mutability.
1188    /// You must make sure this call does not result in multiple mutable references to the same component.
1189    ///
1190    /// # See also
1191    ///
1192    /// - [`iter_combinations`](Self::iter_combinations) and [`iter_combinations_mut`](Self::iter_combinations_mut) for the safe versions.
1193    #[inline]
1194    pub unsafe fn iter_combinations_unsafe<const K: usize>(
1195        &self,
1196    ) -> QueryCombinationIter<'_, 's, D, F, K>
1197    where
1198        D: IterQueryData,
1199    {
1200        // SAFETY: The caller promises that this will not result in multiple mutable references.
1201        unsafe { self.reborrow_unsafe() }.iter_combinations_inner()
1202    }
1203
1204    /// Returns an [`Iterator`] over the query items generated from an [`Entity`] list.
1205    ///
1206    /// Items are returned in the order of the list of entities, and may not be unique if the input
1207    /// doesnn't guarantee uniqueness. Entities that don't match the query are skipped.
1208    ///
1209    /// # Safety
1210    ///
1211    /// This allows aliased mutability and does not check for entity uniqueness.
1212    /// You must make sure this call does not result in multiple mutable references to the same component.
1213    /// Particular care must be taken when collecting the data (rather than iterating over it one item at a time) such as via [`Iterator::collect`].
1214    ///
1215    /// # See also
1216    ///
1217    /// - [`iter_many_mut`](Self::iter_many_mut) to safely access the query items.
1218    pub unsafe fn iter_many_unsafe<EntityList: IntoIterator<Item: EntityEquivalent>>(
1219        &self,
1220        entities: EntityList,
1221    ) -> QueryManyIter<'_, 's, D, F, EntityList::IntoIter> {
1222        // SAFETY: The caller promises that this will not result in multiple mutable references.
1223        unsafe { self.reborrow_unsafe() }.iter_many_inner(entities)
1224    }
1225
1226    /// Returns an [`Iterator`] over the unique query items generated from an [`Entity`] list.
1227    ///
1228    /// Items are returned in the order of the list of entities. Entities that don't match the query are skipped.
1229    ///
1230    /// # Safety
1231    ///
1232    /// This allows aliased mutability.
1233    /// You must make sure this call does not result in multiple mutable references to the same component.
1234    ///
1235    /// # See also
1236    ///
1237    /// - [`iter_many_unique`](Self::iter_many_unique) to get read-only query items.
1238    /// - [`iter_many_unique_mut`](Self::iter_many_unique_mut) to get mutable query items.
1239    /// - [`iter_many_unique_inner`](Self::iter_many_unique_inner) to get with the actual "inner" world lifetime.
1240    pub unsafe fn iter_many_unique_unsafe<EntityList: EntitySet>(
1241        &self,
1242        entities: EntityList,
1243    ) -> QueryManyUniqueIter<'_, 's, D, F, EntityList::IntoIter>
1244    where
1245        D: IterQueryData,
1246    {
1247        // SAFETY: The caller promises that this will not result in multiple mutable references.
1248        unsafe { self.reborrow_unsafe() }.iter_many_unique_inner(entities)
1249    }
1250
1251    /// Returns a parallel iterator over the query results for the given [`World`].
1252    ///
1253    /// This parallel iterator is always guaranteed to return results from each matching entity once and
1254    /// only once.  Iteration order and thread assignment is not guaranteed.
1255    ///
1256    /// If the `multithreaded` feature is disabled, iterating with this operates identically to [`Iterator::for_each`]
1257    /// on [`QueryIter`].
1258    ///
1259    /// This can only be called for read-only queries, see [`par_iter_mut`] for write-queries.
1260    ///
1261    /// Note that you must use the `for_each` method to iterate over the
1262    /// results, see [`par_iter_mut`] for an example.
1263    ///
1264    /// [`par_iter_mut`]: Self::par_iter_mut
1265    /// [`World`]: crate::world::World
1266    #[inline]
1267    pub fn par_iter(&self) -> QueryParIter<'_, 's, D::ReadOnly, F> {
1268        self.as_readonly().par_iter_inner()
1269    }
1270
1271    /// Returns a parallel iterator over the query results for the given [`World`].
1272    ///
1273    /// This parallel iterator is always guaranteed to return results from each matching entity once and
1274    /// only once.  Iteration order and thread assignment is not guaranteed.
1275    ///
1276    /// If the `multithreaded` feature is disabled, iterating with this operates identically to [`Iterator::for_each`]
1277    /// on [`QueryIter`].
1278    ///
1279    /// This can only be called for mutable queries, see [`par_iter`] for read-only-queries.
1280    ///
1281    /// # Example
1282    ///
1283    /// Here, the `gravity_system` updates the `Velocity` component of every entity that contains it:
1284    ///
1285    /// ```
1286    /// # use bevy_ecs::prelude::*;
1287    /// #
1288    /// # #[derive(Component)]
1289    /// # struct Velocity { x: f32, y: f32, z: f32 }
1290    /// fn gravity_system(mut query: Query<&mut Velocity>) {
1291    ///     const DELTA: f32 = 1.0 / 60.0;
1292    ///     query.par_iter_mut().for_each(|mut velocity| {
1293    ///         velocity.y -= 9.8 * DELTA;
1294    ///     });
1295    /// }
1296    /// # bevy_ecs::system::assert_is_system(gravity_system);
1297    /// ```
1298    ///
1299    /// [`par_iter`]: Self::par_iter
1300    /// [`World`]: crate::world::World
1301    #[inline]
1302    pub fn par_iter_mut(&mut self) -> QueryParIter<'_, 's, D, F>
1303    where
1304        D: IterQueryData,
1305    {
1306        self.reborrow().par_iter_inner()
1307    }
1308
1309    /// Returns a parallel iterator over the query results for the given [`World`](crate::world::World).
1310    /// This consumes the [`Query`] to return results with the actual "inner" world lifetime.
1311    ///
1312    /// This parallel iterator is always guaranteed to return results from each matching entity once and
1313    /// only once.  Iteration order and thread assignment is not guaranteed.
1314    ///
1315    /// If the `multithreaded` feature is disabled, iterating with this operates identically to [`Iterator::for_each`]
1316    /// on [`QueryIter`].
1317    ///
1318    /// # Example
1319    ///
1320    /// Here, the `gravity_system` updates the `Velocity` component of every entity that contains it:
1321    ///
1322    /// ```
1323    /// # use bevy_ecs::prelude::*;
1324    /// #
1325    /// # #[derive(Component)]
1326    /// # struct Velocity { x: f32, y: f32, z: f32 }
1327    /// fn gravity_system(query: Query<&mut Velocity>) {
1328    ///     const DELTA: f32 = 1.0 / 60.0;
1329    ///     query.par_iter_inner().for_each(|mut velocity| {
1330    ///         velocity.y -= 9.8 * DELTA;
1331    ///     });
1332    /// }
1333    /// # bevy_ecs::system::assert_is_system(gravity_system);
1334    /// ```
1335    #[inline]
1336    pub fn par_iter_inner(self) -> QueryParIter<'w, 's, D, F>
1337    where
1338        D: IterQueryData,
1339    {
1340        QueryParIter {
1341            world: self.world,
1342            state: self.state,
1343            last_run: self.last_run,
1344            this_run: self.this_run,
1345            batching_strategy: BatchingStrategy::new(),
1346        }
1347    }
1348
1349    /// Returns a parallel iterator over the read-only query items generated from an [`Entity`] list.
1350    ///
1351    /// Entities that don't match the query are skipped. Iteration order and thread assignment is not guaranteed.
1352    ///
1353    /// If the `multithreaded` feature is disabled, iterating with this operates identically to [`Iterator::for_each`]
1354    /// on [`QueryManyIter`].
1355    ///
1356    /// This can only be called for read-only queries. To avoid potential aliasing, there is no `par_iter_many_mut` equivalent.
1357    /// See [`par_iter_many_unique_mut`] for an alternative using [`EntitySet`].
1358    ///
1359    /// Note that you must use the `for_each` method to iterate over the
1360    /// results, see [`par_iter_mut`] for an example.
1361    ///
1362    /// [`par_iter_many_unique_mut`]: Self::par_iter_many_unique_mut
1363    /// [`par_iter_mut`]: Self::par_iter_mut
1364    #[inline]
1365    pub fn par_iter_many<EntityList: IntoIterator<Item: EntityEquivalent>>(
1366        &self,
1367        entities: EntityList,
1368    ) -> QueryParManyIter<'_, 's, D::ReadOnly, F, EntityList::Item> {
1369        QueryParManyIter {
1370            world: self.world,
1371            state: self.state.as_readonly(),
1372            entity_list: entities.into_iter().collect(),
1373            last_run: self.last_run,
1374            this_run: self.this_run,
1375            batching_strategy: BatchingStrategy::new(),
1376        }
1377    }
1378
1379    /// Returns a parallel iterator over the unique read-only query items generated from an [`EntitySet`].
1380    ///
1381    /// Entities that don't match the query are skipped. Iteration order and thread assignment is not guaranteed.
1382    ///
1383    /// If the `multithreaded` feature is disabled, iterating with this operates identically to [`Iterator::for_each`]
1384    /// on [`QueryManyUniqueIter`].
1385    ///
1386    /// This can only be called for read-only queries, see [`par_iter_many_unique_mut`] for write-queries.
1387    ///
1388    /// Note that you must use the `for_each` method to iterate over the
1389    /// results, see [`par_iter_mut`] for an example.
1390    ///
1391    /// [`par_iter_many_unique_mut`]: Self::par_iter_many_unique_mut
1392    /// [`par_iter_mut`]: Self::par_iter_mut
1393    #[inline]
1394    pub fn par_iter_many_unique<EntityList: EntitySet<Item: Sync>>(
1395        &self,
1396        entities: EntityList,
1397    ) -> QueryParManyUniqueIter<'_, 's, D::ReadOnly, F, EntityList::Item> {
1398        QueryParManyUniqueIter {
1399            world: self.world,
1400            state: self.state.as_readonly(),
1401            entity_list: entities.into_iter().collect(),
1402            last_run: self.last_run,
1403            this_run: self.this_run,
1404            batching_strategy: BatchingStrategy::new(),
1405        }
1406    }
1407
1408    /// Returns a parallel iterator over the unique query items generated from an [`EntitySet`].
1409    ///
1410    /// Entities that don't match the query are skipped. Iteration order and thread assignment is not guaranteed.
1411    ///
1412    /// If the `multithreaded` feature is disabled, iterating with this operates identically to [`Iterator::for_each`]
1413    /// on [`QueryManyUniqueIter`].
1414    ///
1415    /// This can only be called for mutable queries, see [`par_iter_many_unique`] for read-only-queries.
1416    ///
1417    /// Note that you must use the `for_each` method to iterate over the
1418    /// results, see [`par_iter_mut`] for an example.
1419    ///
1420    /// [`par_iter_many_unique`]: Self::par_iter_many_unique
1421    /// [`par_iter_mut`]: Self::par_iter_mut
1422    #[inline]
1423    pub fn par_iter_many_unique_mut<EntityList: EntitySet<Item: Sync>>(
1424        &mut self,
1425        entities: EntityList,
1426    ) -> QueryParManyUniqueIter<'_, 's, D, F, EntityList::Item>
1427    where
1428        D: IterQueryData,
1429    {
1430        QueryParManyUniqueIter {
1431            world: self.world,
1432            state: self.state,
1433            entity_list: entities.into_iter().collect(),
1434            last_run: self.last_run,
1435            this_run: self.this_run,
1436            batching_strategy: BatchingStrategy::new(),
1437        }
1438    }
1439
1440    /// Returns a contiguous iterator over the query results for the given
1441    /// [`World`](crate::world::World) or [`Err`] with [`QueryNotDenseError`] if the query is not dense hence not contiguously
1442    /// iterable.
1443    ///
1444    /// Contiguous iteration enables getting slices of contiguously lying components (which lie in the same table), which for example
1445    /// may be used for simd-operations, which may accelerate an algorithm.
1446    ///
1447    /// # Example
1448    ///
1449    /// The following system despawns all entities which health is negative.
1450    ///
1451    /// ```
1452    /// # use bevy_ecs::prelude::*;
1453    /// #
1454    /// # #[derive(Component)]
1455    /// # struct Health(pub f32);
1456    ///
1457    /// fn despawn_all_dead_entities(mut commands: Commands, query: Query<(Entity, &Health)>) {
1458    ///     for (entities, health) in query.contiguous_iter().unwrap() {
1459    ///         // For each entity there is one component, hence it always holds true
1460    ///         assert!(entities.len() == health.len());
1461    ///         for (entity, health) in entities.iter().zip(health.iter()) {
1462    ///             if health.0 < 0.0 {
1463    ///                 commands.entity(*entity).despawn();
1464    ///             }
1465    ///         }
1466    ///     }
1467    /// }
1468    ///
1469    /// ```
1470    ///
1471    /// A mutable version: [`Self::contiguous_iter_mut`]
1472    pub fn contiguous_iter(
1473        &self,
1474    ) -> Result<QueryContiguousIter<'_, 's, D::ReadOnly, F>, QueryNotDenseError>
1475    where
1476        D::ReadOnly: ContiguousQueryData,
1477        F: ArchetypeFilter,
1478    {
1479        self.as_readonly().contiguous_iter_inner()
1480    }
1481
1482    /// Returns a mutable contiguous iterator over the query results for the given
1483    /// [`World`](crate::world::World) or [`Err`] with [`QueryNotDenseError`] if the query is not dense hence not contiguously
1484    /// iterable.
1485    ///
1486    /// Contiguous iteration enables getting slices of contiguously lying components (which lie in the same table), which for example
1487    /// may be used for simd-operations, which may accelerate an algorithm.
1488    ///
1489    /// # Example
1490    ///
1491    /// The following system applies a "health decay" effect on all entities, which reduces their
1492    /// health by some fraction.
1493    ///
1494    /// ```
1495    /// # use bevy_ecs::prelude::*;
1496    /// #
1497    /// # #[derive(Component)]
1498    /// # struct Health(pub f32);
1499    /// #
1500    /// # #[derive(Component)]
1501    /// # struct HealthDecay(pub f32);
1502    ///
1503    /// fn apply_health_decay(mut query: Query<(&mut Health, &HealthDecay)>) {
1504    ///     for (mut health, decay) in query.contiguous_iter_mut().unwrap() {
1505    ///         // all data slices returned by component queries are the same size
1506    ///         assert!(health.len() == decay.len());
1507    ///         // we could have used health.bypass_change_detection() to do less work.
1508    ///         for (health, decay) in health.iter_mut().zip(decay) {
1509    ///             health.0 *= decay.0;
1510    ///         }
1511    ///     }
1512    /// }
1513    /// ```
1514    /// An immutable version: [`Self::contiguous_iter`]
1515    pub fn contiguous_iter_mut(
1516        &mut self,
1517    ) -> Result<QueryContiguousIter<'_, 's, D, F>, QueryNotDenseError>
1518    where
1519        D: ContiguousQueryData,
1520        F: ArchetypeFilter,
1521    {
1522        self.reborrow().contiguous_iter_inner()
1523    }
1524
1525    /// Returns a contiguous iterator over the query results for the given
1526    /// [`World`](crate::world::World) or [`Err`] with [`QueryNotDenseError`] if the query is not dense hence not contiguously
1527    /// iterable.
1528    /// This consumes the [`Query`] to return results with the actual "inner" world lifetime.
1529    pub fn contiguous_iter_inner(
1530        self,
1531    ) -> Result<QueryContiguousIter<'w, 's, D, F>, QueryNotDenseError>
1532    where
1533        D: ContiguousQueryData,
1534        F: ArchetypeFilter,
1535    {
1536        // SAFETY:
1537        // - `self.world` has permission to access the required components
1538        // - `self.world` was used to initialize `self.state`
1539        unsafe { QueryContiguousIter::new(self.world, self.state, self.last_run, self.this_run) }
1540            .ok_or(QueryNotDenseError(DebugName::type_name::<Self>()))
1541    }
1542
1543    /// Returns the read-only query item for the given [`Entity`].
1544    ///
1545    /// In case of a nonexisting entity or mismatched component, a [`QueryEntityError`] is returned instead.
1546    ///
1547    /// This is always guaranteed to run in `O(1)` time.
1548    ///
1549    /// # Example
1550    ///
1551    /// Here, `get` is used to retrieve the exact query item of the entity specified by the `SelectedCharacter` resource.
1552    ///
1553    /// ```
1554    /// # use bevy_ecs::prelude::*;
1555    /// #
1556    /// # #[derive(Resource)]
1557    /// # struct SelectedCharacter { entity: Entity }
1558    /// # #[derive(Component)]
1559    /// # struct Character { name: String }
1560    /// #
1561    /// fn print_selected_character_name_system(
1562    ///        query: Query<&Character>,
1563    ///        selection: Res<SelectedCharacter>
1564    /// )
1565    /// {
1566    ///     if let Ok(selected_character) = query.get(selection.entity) {
1567    ///         println!("{}", selected_character.name);
1568    ///     }
1569    /// }
1570    /// # bevy_ecs::system::assert_is_system(print_selected_character_name_system);
1571    /// ```
1572    ///
1573    /// # See also
1574    ///
1575    /// - [`get_mut`](Self::get_mut) to get a mutable query item.
1576    #[inline]
1577    pub fn get(&self, entity: Entity) -> Result<ROQueryItem<'_, 's, D>, QueryEntityError> {
1578        self.as_readonly().get_inner(entity)
1579    }
1580
1581    /// Returns the read-only query items for the given array of [`Entity`].
1582    ///
1583    /// The returned query items are in the same order as the input.
1584    /// In case of a nonexisting entity or mismatched component, a [`QueryEntityError`] is returned instead.
1585    /// The elements of the array do not need to be unique, unlike `get_many_mut`.
1586    ///
1587    /// # Examples
1588    ///
1589    /// ```
1590    /// use bevy_ecs::prelude::*;
1591    /// use bevy_ecs::query::QueryEntityError;
1592    ///
1593    /// #[derive(Component, PartialEq, Debug)]
1594    /// struct A(usize);
1595    ///
1596    /// let mut world = World::new();
1597    /// let entity_vec: Vec<Entity> = (0..3).map(|i| world.spawn(A(i)).id()).collect();
1598    /// let entities: [Entity; 3] = entity_vec.try_into().unwrap();
1599    ///
1600    /// world.spawn(A(73));
1601    ///
1602    /// let mut query_state = world.query::<&A>();
1603    /// let query = query_state.query(&world);
1604    ///
1605    /// let component_values = query.get_many(entities).unwrap();
1606    ///
1607    /// assert_eq!(component_values, [&A(0), &A(1), &A(2)]);
1608    ///
1609    /// let wrong_entity = Entity::from_raw_u32(365).unwrap();
1610    ///
1611    /// assert_eq!(
1612    ///     match query.get_many([wrong_entity]).unwrap_err() {
1613    ///         QueryEntityError::NotSpawned(error) => error.entity(),
1614    ///         _ => panic!(),
1615    ///     },
1616    ///     wrong_entity
1617    /// );
1618    /// ```
1619    ///
1620    /// # See also
1621    ///
1622    /// - [`get_many_mut`](Self::get_many_mut) to get mutable query items.
1623    /// - [`get_many_unique`](Self::get_many_unique) to only handle unique inputs.
1624    #[inline]
1625    pub fn get_many<const N: usize>(
1626        &self,
1627        entities: [Entity; N],
1628    ) -> Result<[ROQueryItem<'_, 's, D>; N], QueryEntityError> {
1629        // Note that we call a separate `*_inner` method from `get_many_mut`
1630        // because we don't need to check for duplicates.
1631        self.as_readonly().get_many_inner(entities)
1632    }
1633
1634    /// Returns the read-only query items for the given [`UniqueEntityArray`].
1635    ///
1636    /// The returned query items are in the same order as the input.
1637    /// In case of a nonexisting entity or mismatched component, a [`QueryEntityError`] is returned instead.
1638    ///
1639    /// # Examples
1640    ///
1641    /// ```
1642    /// use bevy_ecs::{prelude::*, query::QueryEntityError, entity::{EntitySetIterator, UniqueEntityArray, UniqueEntityVec}};
1643    ///
1644    /// #[derive(Component, PartialEq, Debug)]
1645    /// struct A(usize);
1646    ///
1647    /// let mut world = World::new();
1648    /// let entity_set: UniqueEntityVec = world.spawn_batch((0..3).map(A)).collect_set();
1649    /// let entity_set: UniqueEntityArray<3> = entity_set.try_into().unwrap();
1650    ///
1651    /// world.spawn(A(73));
1652    ///
1653    /// let mut query_state = world.query::<&A>();
1654    /// let query = query_state.query(&world);
1655    ///
1656    /// let component_values = query.get_many_unique(entity_set).unwrap();
1657    ///
1658    /// assert_eq!(component_values, [&A(0), &A(1), &A(2)]);
1659    ///
1660    /// let wrong_entity = Entity::from_raw_u32(365).unwrap();
1661    ///
1662    /// assert_eq!(
1663    ///     match query.get_many_unique(UniqueEntityArray::from([wrong_entity])).unwrap_err() {
1664    ///         QueryEntityError::NotSpawned(error) => error.entity(),
1665    ///         _ => panic!(),
1666    ///     },
1667    ///     wrong_entity
1668    /// );
1669    /// ```
1670    ///
1671    /// # See also
1672    ///
1673    /// - [`get_many_unique_mut`](Self::get_many_mut) to get mutable query items.
1674    /// - [`get_many`](Self::get_many) to handle inputs with duplicates.
1675    #[inline]
1676    pub fn get_many_unique<const N: usize>(
1677        &self,
1678        entities: UniqueEntityArray<N>,
1679    ) -> Result<[ROQueryItem<'_, 's, D>; N], QueryEntityError> {
1680        self.as_readonly().get_many_unique_inner(entities)
1681    }
1682
1683    /// Returns the query item for the given [`Entity`].
1684    ///
1685    /// In case of a nonexisting entity or mismatched component, a [`QueryEntityError`] is returned instead.
1686    ///
1687    /// This is always guaranteed to run in `O(1)` time.
1688    ///
1689    /// # Example
1690    ///
1691    /// Here, `get_mut` is used to retrieve the exact query item of the entity specified by the `PoisonedCharacter` resource.
1692    ///
1693    /// ```
1694    /// # use bevy_ecs::prelude::*;
1695    /// #
1696    /// # #[derive(Resource)]
1697    /// # struct PoisonedCharacter { character_id: Entity }
1698    /// # #[derive(Component)]
1699    /// # struct Health(u32);
1700    /// #
1701    /// fn poison_system(mut query: Query<&mut Health>, poisoned: Res<PoisonedCharacter>) {
1702    ///     if let Ok(mut health) = query.get_mut(poisoned.character_id) {
1703    ///         health.0 -= 1;
1704    ///     }
1705    /// }
1706    /// # bevy_ecs::system::assert_is_system(poison_system);
1707    /// ```
1708    ///
1709    /// # See also
1710    ///
1711    /// - [`get`](Self::get) to get a read-only query item.
1712    #[inline]
1713    pub fn get_mut(&mut self, entity: Entity) -> Result<D::Item<'_, 's>, QueryEntityError> {
1714        self.reborrow().get_inner(entity)
1715    }
1716
1717    /// Returns the query item for the given [`Entity`].
1718    /// This consumes the [`Query`] to return results with the actual "inner" world lifetime.
1719    ///
1720    /// In case of a nonexisting entity or mismatched component, a [`QueryEntityError`] is returned instead.
1721    ///
1722    /// This is always guaranteed to run in `O(1)` time.
1723    ///
1724    /// # See also
1725    ///
1726    /// - [`get_mut`](Self::get_mut) to get the item using a mutable borrow of the [`Query`].
1727    #[inline]
1728    pub fn get_inner(self, entity: Entity) -> Result<D::Item<'w, 's>, QueryEntityError> {
1729        // SAFETY: system runs without conflicts with other systems.
1730        // same-system queries have runtime borrow checks when they conflict
1731        unsafe {
1732            let location = self.world.entities().get_spawned(entity)?;
1733            if !self
1734                .state
1735                .matched_archetypes
1736                .contains(location.archetype_id.index())
1737            {
1738                return Err(QueryEntityError::QueryDoesNotMatch(
1739                    entity,
1740                    location.archetype_id,
1741                ));
1742            }
1743            let archetype = self
1744                .world
1745                .archetypes()
1746                .get(location.archetype_id)
1747                .debug_checked_unwrap();
1748            let mut fetch = D::init_fetch(
1749                self.world,
1750                &self.state.fetch_state,
1751                self.last_run,
1752                self.this_run,
1753            );
1754            let mut filter = F::init_fetch(
1755                self.world,
1756                &self.state.filter_state,
1757                self.last_run,
1758                self.this_run,
1759            );
1760
1761            let table = self
1762                .world
1763                .storages()
1764                .tables
1765                .get(location.table_id)
1766                .debug_checked_unwrap();
1767            D::set_archetype(&mut fetch, &self.state.fetch_state, archetype, table);
1768            F::set_archetype(&mut filter, &self.state.filter_state, archetype, table);
1769
1770            if F::filter_fetch(
1771                &self.state.filter_state,
1772                &mut filter,
1773                entity,
1774                location.table_row,
1775            ) && let Some(item) = D::fetch(
1776                &self.state.fetch_state,
1777                &mut fetch,
1778                entity,
1779                location.table_row,
1780            ) {
1781                Ok(item)
1782            } else {
1783                Err(QueryEntityError::QueryDoesNotMatch(
1784                    entity,
1785                    location.archetype_id,
1786                ))
1787            }
1788        }
1789    }
1790
1791    /// Returns the query items for the given array of [`Entity`].
1792    ///
1793    /// The returned query items are in the same order as the input.
1794    /// In case of a nonexisting entity, duplicate entities or mismatched component, a [`QueryEntityError`] is returned instead.
1795    ///
1796    /// # Examples
1797    ///
1798    /// ```
1799    /// use bevy_ecs::prelude::*;
1800    /// use bevy_ecs::query::QueryEntityError;
1801    ///
1802    /// #[derive(Component, PartialEq, Debug)]
1803    /// struct A(usize);
1804    ///
1805    /// let mut world = World::new();
1806    ///
1807    /// let entities: Vec<Entity> = (0..3).map(|i| world.spawn(A(i)).id()).collect();
1808    /// let entities: [Entity; 3] = entities.try_into().unwrap();
1809    ///
1810    /// world.spawn(A(73));
1811    /// let wrong_entity = Entity::from_raw_u32(57).unwrap();
1812    /// let invalid_entity = world.spawn_empty().id();
1813    ///
1814    ///
1815    /// let mut query_state = world.query::<&mut A>();
1816    /// let mut query = query_state.query_mut(&mut world);
1817    ///
1818    /// let mut mutable_component_values = query.get_many_mut(entities).unwrap();
1819    ///
1820    /// for mut a in &mut mutable_component_values {
1821    ///     a.0 += 5;
1822    /// }
1823    ///
1824    /// let component_values = query.get_many(entities).unwrap();
1825    ///
1826    /// assert_eq!(component_values, [&A(5), &A(6), &A(7)]);
1827    ///
1828    /// assert_eq!(
1829    ///     match query
1830    ///         .get_many_mut([wrong_entity])
1831    ///         .unwrap_err()
1832    ///     {
1833    ///         QueryEntityError::NotSpawned(error) => error.entity(),
1834    ///         _ => panic!(),
1835    ///     },
1836    ///     wrong_entity
1837    /// );
1838    /// assert_eq!(
1839    ///     match query
1840    ///         .get_many_mut([invalid_entity])
1841    ///         .unwrap_err()
1842    ///     {
1843    ///         QueryEntityError::QueryDoesNotMatch(entity, _) => entity,
1844    ///         _ => panic!(),
1845    ///     },
1846    ///     invalid_entity
1847    /// );
1848    /// assert_eq!(
1849    ///     query
1850    ///         .get_many_mut([entities[0], entities[0]])
1851    ///         .unwrap_err(),
1852    ///     QueryEntityError::AliasedMutability(entities[0])
1853    /// );
1854    /// ```
1855    /// # See also
1856    ///
1857    /// - [`get_many`](Self::get_many) to get read-only query items without checking for duplicate entities.
1858    #[inline]
1859    pub fn get_many_mut<const N: usize>(
1860        &mut self,
1861        entities: [Entity; N],
1862    ) -> Result<[D::Item<'_, 's>; N], QueryEntityError>
1863    where
1864        D: IterQueryData,
1865    {
1866        self.reborrow().get_many_mut_inner(entities)
1867    }
1868
1869    /// Returns the query items for the given [`UniqueEntityArray`].
1870    ///
1871    /// The returned query items are in the same order as the input.
1872    /// In case of a nonexisting entity or mismatched component, a [`QueryEntityError`] is returned instead.
1873    ///
1874    /// # Examples
1875    ///
1876    /// ```
1877    /// use bevy_ecs::{prelude::*, query::QueryEntityError, entity::{EntitySetIterator, UniqueEntityArray, UniqueEntityVec}};
1878    ///
1879    /// #[derive(Component, PartialEq, Debug)]
1880    /// struct A(usize);
1881    ///
1882    /// let mut world = World::new();
1883    ///
1884    /// let entity_set: UniqueEntityVec = world.spawn_batch((0..3).map(A)).collect_set();
1885    /// let entity_set: UniqueEntityArray<3> = entity_set.try_into().unwrap();
1886    ///
1887    /// world.spawn(A(73));
1888    /// let wrong_entity = Entity::from_raw_u32(57).unwrap();
1889    /// let invalid_entity = world.spawn_empty().id();
1890    ///
1891    ///
1892    /// let mut query_state = world.query::<&mut A>();
1893    /// let mut query = query_state.query_mut(&mut world);
1894    ///
1895    /// let mut mutable_component_values = query.get_many_unique_mut(entity_set).unwrap();
1896    ///
1897    /// for mut a in &mut mutable_component_values {
1898    ///     a.0 += 5;
1899    /// }
1900    ///
1901    /// let component_values = query.get_many_unique(entity_set).unwrap();
1902    ///
1903    /// assert_eq!(component_values, [&A(5), &A(6), &A(7)]);
1904    ///
1905    /// assert_eq!(
1906    ///     match query
1907    ///         .get_many_unique_mut(UniqueEntityArray::from([wrong_entity]))
1908    ///         .unwrap_err()
1909    ///     {
1910    ///         QueryEntityError::NotSpawned(error) => error.entity(),
1911    ///         _ => panic!(),
1912    ///     },
1913    ///     wrong_entity
1914    /// );
1915    /// assert_eq!(
1916    ///     match query
1917    ///         .get_many_unique_mut(UniqueEntityArray::from([invalid_entity]))
1918    ///         .unwrap_err()
1919    ///     {
1920    ///         QueryEntityError::QueryDoesNotMatch(entity, _) => entity,
1921    ///         _ => panic!(),
1922    ///     },
1923    ///     invalid_entity
1924    /// );
1925    /// ```
1926    /// # See also
1927    ///
1928    /// - [`get_many_unique`](Self::get_many) to get read-only query items.
1929    #[inline]
1930    pub fn get_many_unique_mut<const N: usize>(
1931        &mut self,
1932        entities: UniqueEntityArray<N>,
1933    ) -> Result<[D::Item<'_, 's>; N], QueryEntityError>
1934    where
1935        D: IterQueryData,
1936    {
1937        self.reborrow().get_many_unique_inner(entities)
1938    }
1939
1940    /// Returns the query items for the given array of [`Entity`].
1941    /// This consumes the [`Query`] to return results with the actual "inner" world lifetime.
1942    ///
1943    /// The returned query items are in the same order as the input.
1944    /// In case of a nonexisting entity, duplicate entities or mismatched component, a [`QueryEntityError`] is returned instead.
1945    ///
1946    /// # See also
1947    ///
1948    /// - [`get_many`](Self::get_many) to get read-only query items without checking for duplicate entities.
1949    /// - [`get_many_mut`](Self::get_many_mut) to get items using a mutable reference.
1950    /// - [`get_many_inner`](Self::get_many_mut_inner) to get read-only query items with the actual "inner" world lifetime.
1951    #[inline]
1952    pub fn get_many_mut_inner<const N: usize>(
1953        self,
1954        entities: [Entity; N],
1955    ) -> Result<[D::Item<'w, 's>; N], QueryEntityError>
1956    where
1957        D: IterQueryData,
1958    {
1959        // Verify that all entities are unique
1960        for i in 0..N {
1961            for j in 0..i {
1962                if entities[i] == entities[j] {
1963                    return Err(QueryEntityError::AliasedMutability(entities[i]));
1964                }
1965            }
1966        }
1967        // SAFETY: All entities are unique, so the results don't alias.
1968        unsafe { self.get_many_impl(entities) }
1969    }
1970
1971    /// Returns the query items for the given array of [`Entity`].
1972    /// This consumes the [`Query`] to return results with the actual "inner" world lifetime.
1973    ///
1974    /// The returned query items are in the same order as the input.
1975    /// In case of a nonexisting entity or mismatched component, a [`QueryEntityError`] is returned instead.
1976    ///
1977    /// # See also
1978    ///
1979    /// - [`get_many`](Self::get_many) to get read-only query items without checking for duplicate entities.
1980    /// - [`get_many_mut`](Self::get_many_mut) to get items using a mutable reference.
1981    /// - [`get_many_mut_inner`](Self::get_many_mut_inner) to get mutable query items with the actual "inner" world lifetime.
1982    #[inline]
1983    pub fn get_many_inner<const N: usize>(
1984        self,
1985        entities: [Entity; N],
1986    ) -> Result<[D::Item<'w, 's>; N], QueryEntityError>
1987    where
1988        D: ReadOnlyQueryData,
1989    {
1990        // SAFETY: The query results are read-only, so they don't conflict if there are duplicate entities.
1991        unsafe { self.get_many_impl(entities) }
1992    }
1993
1994    /// Returns the query items for the given [`UniqueEntityArray`].
1995    /// This consumes the [`Query`] to return results with the actual "inner" world lifetime.
1996    ///
1997    /// The returned query items are in the same order as the input.
1998    /// In case of a nonexisting entity, duplicate entities or mismatched component, a [`QueryEntityError`] is returned instead.
1999    ///
2000    /// # See also
2001    ///
2002    /// - [`get_many_unique`](Self::get_many_unique) to get read-only query items without checking for duplicate entities.
2003    /// - [`get_many_unique_mut`](Self::get_many_unique_mut) to get items using a mutable reference.
2004    #[inline]
2005    pub fn get_many_unique_inner<const N: usize>(
2006        self,
2007        entities: UniqueEntityArray<N>,
2008    ) -> Result<[D::Item<'w, 's>; N], QueryEntityError>
2009    where
2010        D: IterQueryData,
2011    {
2012        // SAFETY: All entities are unique, so the results don't alias.
2013        unsafe { self.get_many_impl(entities.into_inner()) }
2014    }
2015
2016    /// Returns the query items for the given array of [`Entity`].
2017    /// This consumes the [`Query`] to return results with the actual "inner" world lifetime.
2018    ///
2019    /// # Safety
2020    ///
2021    /// The caller must ensure that the query data returned for the entities does not conflict,
2022    /// either because they are all unique or because the data is read-only.
2023    unsafe fn get_many_impl<const N: usize>(
2024        self,
2025        entities: [Entity; N],
2026    ) -> Result<[D::Item<'w, 's>; N], QueryEntityError>
2027    where
2028        D: IterQueryData,
2029    {
2030        let mut values = [(); N].map(|_| MaybeUninit::uninit());
2031
2032        for (value, entity) in core::iter::zip(&mut values, entities) {
2033            // SAFETY: The caller asserts that the results don't alias,
2034            // and `D: IterQueryData` so its valid to have items alive for different entitiess
2035            let item = unsafe { self.copy_unsafe() }.get_inner(entity)?;
2036            *value = MaybeUninit::new(item);
2037        }
2038
2039        // SAFETY: Each value has been fully initialized.
2040        Ok(values.map(|x| unsafe { x.assume_init() }))
2041    }
2042
2043    /// Returns the query item for the given [`Entity`].
2044    ///
2045    /// In case of a nonexisting entity or mismatched component, a [`QueryEntityError`] is returned instead.
2046    ///
2047    /// This is always guaranteed to run in `O(1)` time.
2048    ///
2049    /// # Safety
2050    ///
2051    /// This function makes it possible to violate Rust's aliasing guarantees.
2052    /// You must make sure this call does not result in multiple mutable references to the same component.
2053    ///
2054    /// # See also
2055    ///
2056    /// - [`get_mut`](Self::get_mut) for the safe version.
2057    #[inline]
2058    pub unsafe fn get_unchecked(
2059        &self,
2060        entity: Entity,
2061    ) -> Result<D::Item<'_, 's>, QueryEntityError> {
2062        // SAFETY: The caller promises that this will not result in multiple mutable references.
2063        unsafe { self.reborrow_unsafe() }.get_inner(entity)
2064    }
2065
2066    /// Returns a single read-only query item when there is exactly one entity matching the query.
2067    ///
2068    /// If the number of query items is not exactly one, a [`QuerySingleError`] is returned instead.
2069    ///
2070    /// # Example
2071    ///
2072    /// ```
2073    /// # use bevy_ecs::prelude::*;
2074    /// # use bevy_ecs::query::QuerySingleError;
2075    /// # #[derive(Component)]
2076    /// # struct PlayerScore(i32);
2077    /// fn player_scoring_system(query: Query<&PlayerScore>) {
2078    ///     match query.single() {
2079    ///         Ok(PlayerScore(score)) => {
2080    ///             println!("Score: {}", score);
2081    ///         }
2082    ///         Err(QuerySingleError::NoEntities(_)) => {
2083    ///             println!("Error: There is no player!");
2084    ///         }
2085    ///         Err(QuerySingleError::MultipleEntities(_)) => {
2086    ///             println!("Error: There is more than one player!");
2087    ///         }
2088    ///     }
2089    /// }
2090    /// # bevy_ecs::system::assert_is_system(player_scoring_system);
2091    /// ```
2092    ///
2093    /// # See also
2094    ///
2095    /// - [`single_mut`](Self::single_mut) to get the mutable query item.
2096    #[inline]
2097    pub fn single(&self) -> Result<ROQueryItem<'_, 's, D>, QuerySingleError> {
2098        self.as_readonly().single_inner()
2099    }
2100
2101    /// Returns a single query item when there is exactly one entity matching the query.
2102    ///
2103    /// If the number of query items is not exactly one, a [`QuerySingleError`] is returned instead.
2104    ///
2105    /// # Example
2106    ///
2107    /// ```
2108    /// # use bevy_ecs::prelude::*;
2109    /// #
2110    /// # #[derive(Component)]
2111    /// # struct Player;
2112    /// # #[derive(Component)]
2113    /// # struct Health(u32);
2114    /// #
2115    /// fn regenerate_player_health_system(mut query: Query<&mut Health, With<Player>>) {
2116    ///     let mut health = query.single_mut().expect("Error: Could not find a single player.");
2117    ///     health.0 += 1;
2118    /// }
2119    /// # bevy_ecs::system::assert_is_system(regenerate_player_health_system);
2120    /// ```
2121    ///
2122    /// # See also
2123    ///
2124    /// - [`single`](Self::single) to get the read-only query item.
2125    #[inline]
2126    pub fn single_mut(&mut self) -> Result<D::Item<'_, 's>, QuerySingleError>
2127    where
2128        D: IterQueryData,
2129    {
2130        self.reborrow().single_inner()
2131    }
2132
2133    /// Returns a single query item when there is exactly one entity matching the query.
2134    /// This consumes the [`Query`] to return results with the actual "inner" world lifetime.
2135    ///
2136    /// If the number of query items is not exactly one, a [`QuerySingleError`] is returned instead.
2137    ///
2138    /// # Example
2139    ///
2140    /// ```
2141    /// # use bevy_ecs::prelude::*;
2142    /// #
2143    /// # #[derive(Component)]
2144    /// # struct Player;
2145    /// # #[derive(Component)]
2146    /// # struct Health(u32);
2147    /// #
2148    /// fn regenerate_player_health_system(query: Query<&mut Health, With<Player>>) {
2149    ///     let mut health = query.single_inner().expect("Error: Could not find a single player.");
2150    ///     health.0 += 1;
2151    /// }
2152    /// # bevy_ecs::system::assert_is_system(regenerate_player_health_system);
2153    /// ```
2154    ///
2155    /// # See also
2156    ///
2157    /// - [`single`](Self::single) to get the read-only query item.
2158    /// - [`single_mut`](Self::single_mut) to get the mutable query item.
2159    #[inline]
2160    pub fn single_inner(self) -> Result<D::Item<'w, 's>, QuerySingleError>
2161    where
2162        D: IterQueryData,
2163    {
2164        let mut query = self.into_iter();
2165        let first = query.next();
2166        let extra = query.next().is_some();
2167
2168        match (first, extra) {
2169            (Some(r), false) => Ok(r),
2170            (None, _) => Err(QuerySingleError::NoEntities(DebugName::type_name::<Self>())),
2171            (Some(_), _) => Err(QuerySingleError::MultipleEntities(DebugName::type_name::<
2172                Self,
2173            >())),
2174        }
2175    }
2176
2177    /// Returns `true` if there are no query items.
2178    ///
2179    /// This is equivalent to `self.iter().next().is_none()`, and thus the worst case runtime will be `O(n)`
2180    /// where `n` is the number of *potential* matches. This can be notably expensive for queries that rely
2181    /// on non-archetypal filters such as [`Added`], [`Changed`] or [`Spawned`] which must individually check
2182    /// each query result for a match.
2183    ///
2184    /// # Example
2185    ///
2186    /// Here, the score is increased only if an entity with a `Player` component is present in the world:
2187    ///
2188    /// ```
2189    /// # use bevy_ecs::prelude::*;
2190    /// #
2191    /// # #[derive(Component)]
2192    /// # struct Player;
2193    /// # #[derive(Resource)]
2194    /// # struct Score(u32);
2195    /// fn update_score_system(query: Query<(), With<Player>>, mut score: ResMut<Score>) {
2196    ///     if !query.is_empty() {
2197    ///         score.0 += 1;
2198    ///     }
2199    /// }
2200    /// # bevy_ecs::system::assert_is_system(update_score_system);
2201    /// ```
2202    ///
2203    /// [`Added`]: crate::query::Added
2204    /// [`Changed`]: crate::query::Changed
2205    /// [`Spawned`]: crate::query::Spawned
2206    #[inline]
2207    pub fn is_empty(&self) -> bool {
2208        // If the query data matches every entity, then `as_nop()` can safely
2209        // skip the cost of initializing the fetch for data that won't be used.
2210        if D::IS_ARCHETYPAL {
2211            self.as_nop().iter().next().is_none()
2212        } else {
2213            self.iter().next().is_none()
2214        }
2215    }
2216
2217    /// Returns `true` if the given [`Entity`] matches the query.
2218    ///
2219    /// This is always guaranteed to run in `O(1)` time.
2220    ///
2221    /// # Example
2222    ///
2223    /// ```
2224    /// # use bevy_ecs::prelude::*;
2225    /// #
2226    /// # #[derive(Component)]
2227    /// # struct InRange;
2228    /// #
2229    /// # #[derive(Resource)]
2230    /// # struct Target {
2231    /// #     entity: Entity,
2232    /// # }
2233    /// #
2234    /// fn targeting_system(in_range_query: Query<&InRange>, target: Res<Target>) {
2235    ///     if in_range_query.contains(target.entity) {
2236    ///         println!("Bam!")
2237    ///     }
2238    /// }
2239    /// # bevy_ecs::system::assert_is_system(targeting_system);
2240    /// ```
2241    #[inline]
2242    pub fn contains(&self, entity: Entity) -> bool {
2243        // If the query data matches every entity, then `as_nop()` can safely
2244        // skip the cost of initializing the fetch for data that won't be used.
2245        if D::IS_ARCHETYPAL {
2246            self.as_nop().get(entity).is_ok()
2247        } else {
2248            self.get(entity).is_ok()
2249        }
2250    }
2251
2252    /// Counts the number of entities that match the query.
2253    ///
2254    /// This is equivalent to `self.iter().count()` but may be more efficient in some cases.
2255    ///
2256    /// If [`D::IS_ARCHETYPAL`](QueryData::IS_ARCHETYPAL) && [`F::IS_ARCHETYPAL`](QueryFilter::IS_ARCHETYPAL) is `true`,
2257    /// this will do work proportional to the number of matched archetypes or tables, but will not iterate each entity.
2258    /// If it is `false`, it will have to do work for each entity.
2259    ///
2260    /// # Example
2261    ///
2262    /// ```
2263    /// # use bevy_ecs::prelude::*;
2264    /// #
2265    /// # #[derive(Component)]
2266    /// # struct InRange;
2267    /// #
2268    /// fn targeting_system(in_range_query: Query<&InRange>) {
2269    ///     let count = in_range_query.count();
2270    ///     println!("{count} targets in range!");
2271    /// }
2272    /// # bevy_ecs::system::assert_is_system(targeting_system);
2273    /// ```
2274    pub fn count(&self) -> usize {
2275        // If the query data matches every entity, then `as_nop()` can safely
2276        // skip the cost of initializing the fetch for data that won't be used.
2277        if !D::IS_ARCHETYPAL {
2278            self.into_iter().count()
2279        } else if !F::IS_ARCHETYPAL {
2280            // If we have non-archetypal filters, we have to check each entity.
2281            self.as_nop().into_iter().count()
2282        } else {
2283            // For archetypal queries, the `size_hint()` is exact,
2284            // and we can get the count from the archetype and table counts.
2285            self.as_nop().into_iter().size_hint().0
2286        }
2287    }
2288
2289    /// Returns a [`QueryLens`] that can be used to construct a new [`Query`] giving more
2290    /// restrictive access to the entities matched by the current query.
2291    ///
2292    /// A transmute is valid only if `NewD` has a subset of the read, write, and required access
2293    /// of the current query. A precise description of the access required by each parameter
2294    /// type is given in the table below, but typical uses are to:
2295    /// * Remove components, e.g. `Query<(&A, &B)>` to `Query<&A>`.
2296    /// * Retrieve an existing component with reduced or equal access, e.g. `Query<&mut A>` to `Query<&A>`
2297    ///   or `Query<&T>` to `Query<Ref<T>>`.
2298    /// * Add parameters with no new access, for example adding an `Entity` parameter.
2299    ///
2300    /// Note that since filter terms are dropped, non-archetypal filters like
2301    /// [`Added`], [`Changed`] and [`Spawned`] will not be respected. To maintain or change filter
2302    /// terms see [`Self::transmute_lens_filtered`].
2303    ///
2304    /// |`QueryData` parameter type|Access required|
2305    /// |----|----|
2306    /// |[`Entity`], [`EntityLocation`], [`SpawnDetails`], [`&Archetype`], [`Has<T>`], [`PhantomData<T>`]|No access|
2307    /// |[`EntityMut`]|Read and write access to all components, but no required access|
2308    /// |[`EntityRef`]|Read access to all components, but no required access|
2309    /// |`&T`, [`Ref<T>`]|Read and required access to `T`|
2310    /// |`&mut T`, [`Mut<T>`]|Read, write and required access to `T`|
2311    /// |[`Option<T>`], [`AnyOf<(D, ...)>`]|Read and write access to `T`, but no required access|
2312    /// |Tuples of query data and<br/>`#[derive(QueryData)]` structs|The union of the access of their subqueries|
2313    /// |[`FilteredEntityRef`], [`FilteredEntityMut`]|Determined by the [`QueryBuilder`] used to construct them. Any query can be transmuted to them, and they will receive the access of the source query. When combined with other `QueryData`, they will receive any access of the source query that does not conflict with the other data|
2314    ///
2315    /// `transmute_lens` drops filter terms, but [`Self::transmute_lens_filtered`] supports returning a [`QueryLens`] with a new
2316    /// filter type - the access required by filter parameters are as follows.
2317    ///
2318    /// |`QueryFilter` parameter type|Access required|
2319    /// |----|----|
2320    /// |[`Added<T>`], [`Changed<T>`]|Read and required access to `T`|
2321    /// |[`With<T>`], [`Without<T>`]|No access|
2322    /// |[`Or<(T, ...)>`]|Read access of the subqueries, but no required access|
2323    /// |Tuples of query filters and `#[derive(QueryFilter)]` structs|The union of the access of their subqueries|
2324    ///
2325    /// [`Added`]: crate::query::Added
2326    /// [`Added<T>`]: crate::query::Added
2327    /// [`AnyOf<(D, ...)>`]: crate::query::AnyOf
2328    /// [`&Archetype`]: crate::archetype::Archetype
2329    /// [`Changed`]: crate::query::Changed
2330    /// [`Changed<T>`]: crate::query::Changed
2331    /// [`EntityMut`]: crate::world::EntityMut
2332    /// [`EntityLocation`]: crate::entity::EntityLocation
2333    /// [`EntityRef`]: crate::world::EntityRef
2334    /// [`FilteredEntityRef`]: crate::world::FilteredEntityRef
2335    /// [`FilteredEntityMut`]: crate::world::FilteredEntityMut
2336    /// [`Has<T>`]: crate::query::Has
2337    /// [`Mut<T>`]: crate::world::Mut
2338    /// [`Or<(T, ...)>`]: crate::query::Or
2339    /// [`QueryBuilder`]: crate::query::QueryBuilder
2340    /// [`Ref<T>`]: crate::world::Ref
2341    /// [`SpawnDetails`]: crate::query::SpawnDetails
2342    /// [`Spawned`]: crate::query::Spawned
2343    /// [`With<T>`]: crate::query::With
2344    /// [`Without<T>`]: crate::query::Without
2345    ///
2346    /// ## Panics
2347    ///
2348    /// This will panic if the access required by `NewD` is not a subset of that required by
2349    /// the original fetch `D`.
2350    ///
2351    /// ## Example
2352    ///
2353    /// ```rust
2354    /// # use bevy_ecs::prelude::*;
2355    /// # use bevy_ecs::system::QueryLens;
2356    /// #
2357    /// # #[derive(Component)]
2358    /// # struct A(usize);
2359    /// #
2360    /// # #[derive(Component)]
2361    /// # struct B(usize);
2362    /// #
2363    /// # let mut world = World::new();
2364    /// #
2365    /// # world.spawn((A(10), B(5)));
2366    /// #
2367    /// fn reusable_function(lens: &mut QueryLens<&A>) {
2368    ///     assert_eq!(lens.query().single().unwrap().0, 10);
2369    /// }
2370    ///
2371    /// // We can use the function in a system that takes the exact query.
2372    /// fn system_1(mut query: Query<&A>) {
2373    ///     reusable_function(&mut query.as_query_lens());
2374    /// }
2375    ///
2376    /// // We can also use it with a query that does not match exactly
2377    /// // by transmuting it.
2378    /// fn system_2(mut query: Query<(&mut A, &B)>) {
2379    ///     let mut lens = query.transmute_lens::<&A>();
2380    ///     reusable_function(&mut lens);
2381    /// }
2382    ///
2383    /// # let mut schedule = Schedule::default();
2384    /// # schedule.add_systems((system_1, system_2));
2385    /// # schedule.run(&mut world);
2386    /// ```
2387    ///
2388    /// ### Examples of valid transmutes
2389    ///
2390    /// ```rust
2391    /// # use bevy_ecs::{
2392    /// #     prelude::*,
2393    /// #     archetype::Archetype,
2394    /// #     entity::EntityLocation,
2395    /// #     query::{QueryData, QueryFilter, SingleEntityQueryData},
2396    /// #     world::{FilteredEntityMut, FilteredEntityRef},
2397    /// # };
2398    /// # use std::marker::PhantomData;
2399    /// #
2400    /// # fn assert_valid_transmute<OldD: QueryData, NewD: SingleEntityQueryData>() {
2401    /// #     assert_valid_transmute_filtered::<OldD, (), NewD, ()>();
2402    /// # }
2403    /// #
2404    /// # fn assert_valid_transmute_filtered<OldD: QueryData, OldF: QueryFilter, NewD: SingleEntityQueryData, NewF: QueryFilter>() {
2405    /// #     let mut world = World::new();
2406    /// #     // Make sure all components in the new query are initialized
2407    /// #     let state = world.query_filtered::<NewD, NewF>();
2408    /// #     let state = world.query_filtered::<OldD, OldF>();
2409    /// #     state.transmute_filtered::<NewD, NewF>(&world);
2410    /// # }
2411    /// #
2412    /// # #[derive(Component)]
2413    /// # struct T;
2414    /// #
2415    /// # #[derive(Component)]
2416    /// # struct U;
2417    /// #
2418    /// # #[derive(Component)]
2419    /// # struct V;
2420    /// #
2421    /// // `&mut T` and `Mut<T>` access the same data and can be transmuted to each other,
2422    /// // `&T` and `Ref<T>` access the same data and can be transmuted to each other,
2423    /// // and mutable versions can be transmuted to read-only versions
2424    /// assert_valid_transmute::<&mut T, &T>();
2425    /// assert_valid_transmute::<&mut T, Mut<T>>();
2426    /// assert_valid_transmute::<Mut<T>, &mut T>();
2427    /// assert_valid_transmute::<&T, Ref<T>>();
2428    /// assert_valid_transmute::<Ref<T>, &T>();
2429    ///
2430    /// // The structure can be rearranged, or subqueries dropped
2431    /// assert_valid_transmute::<(&T, &U), &T>();
2432    /// assert_valid_transmute::<((&T, &U), &V), (&T, (&U, &V))>();
2433    /// assert_valid_transmute::<Option<(&T, &U)>, (Option<&T>, Option<&U>)>();
2434    ///
2435    /// // Queries with no access can be freely added
2436    /// assert_valid_transmute::<
2437    ///     &T,
2438    ///     (&T, Entity, EntityLocation, &Archetype, Has<U>, PhantomData<T>),
2439    /// >();
2440    ///
2441    /// // Required access can be transmuted to optional,
2442    /// // and optional access can be transmuted to other optional access
2443    /// assert_valid_transmute::<&T, Option<&T>>();
2444    /// assert_valid_transmute::<AnyOf<(&mut T, &mut U)>, Option<&T>>();
2445    /// // Note that removing subqueries from `AnyOf` will result
2446    /// // in an `AnyOf` where all subqueries can yield `None`!
2447    /// assert_valid_transmute::<AnyOf<(&T, &U, &V)>, AnyOf<(&T, &U)>>();
2448    /// assert_valid_transmute::<EntityMut, Option<&mut T>>();
2449    ///
2450    /// // Anything can be transmuted to `FilteredEntityRef` or `FilteredEntityMut`
2451    /// // This will create a `FilteredEntityMut` that only has read access to `T`
2452    /// assert_valid_transmute::<&T, FilteredEntityMut>();
2453    /// // This will create a `FilteredEntityMut` that has no access to `T`,
2454    /// // read access to `U`, and write access to `V`.
2455    /// assert_valid_transmute::<(&mut T, &mut U, &mut V), (&mut T, &U, FilteredEntityMut)>();
2456    ///
2457    /// // `Added<T>` and `Changed<T>` filters have the same access as `&T` data
2458    /// // Remember that they are only evaluated on the transmuted query, not the original query!
2459    /// assert_valid_transmute_filtered::<Entity, Changed<T>, &T, ()>();
2460    /// assert_valid_transmute_filtered::<&mut T, (), &T, Added<T>>();
2461    /// // Nested inside of an `Or` filter, they have the same access as `Option<&T>`.
2462    /// assert_valid_transmute_filtered::<Option<&T>, (), Entity, Or<(Changed<T>, With<U>)>>();
2463    /// ```
2464    #[track_caller]
2465    pub fn transmute_lens<NewD: SingleEntityQueryData>(&mut self) -> QueryLens<'_, NewD> {
2466        self.transmute_lens_filtered::<NewD, ()>()
2467    }
2468
2469    /// Returns a [`QueryLens`] that can be used to construct a new `Query` giving more restrictive
2470    /// access to the entities matched by the current query.
2471    ///
2472    /// This consumes the [`Query`] to return results with the actual "inner" world lifetime.
2473    ///
2474    /// See [`Self::transmute_lens`] for a description of allowed transmutes.
2475    ///
2476    /// ## Panics
2477    ///
2478    /// This will panic if `NewD` is not a subset of the original fetch `D`
2479    ///
2480    /// ## Example
2481    ///
2482    /// ```rust
2483    /// # use bevy_ecs::prelude::*;
2484    /// # use bevy_ecs::system::QueryLens;
2485    /// #
2486    /// # #[derive(Component)]
2487    /// # struct A(usize);
2488    /// #
2489    /// # #[derive(Component)]
2490    /// # struct B(usize);
2491    /// #
2492    /// # let mut world = World::new();
2493    /// #
2494    /// # world.spawn((A(10), B(5)));
2495    /// #
2496    /// fn reusable_function(mut lens: QueryLens<&A>) {
2497    ///     assert_eq!(lens.query().single().unwrap().0, 10);
2498    /// }
2499    ///
2500    /// // We can use the function in a system that takes the exact query.
2501    /// fn system_1(query: Query<&A>) {
2502    ///     reusable_function(query.into_query_lens());
2503    /// }
2504    ///
2505    /// // We can also use it with a query that does not match exactly
2506    /// // by transmuting it.
2507    /// fn system_2(query: Query<(&mut A, &B)>) {
2508    ///     let mut lens = query.transmute_lens_inner::<&A>();
2509    ///     reusable_function(lens);
2510    /// }
2511    ///
2512    /// # let mut schedule = Schedule::default();
2513    /// # schedule.add_systems((system_1, system_2));
2514    /// # schedule.run(&mut world);
2515    /// ```
2516    ///
2517    /// # See also
2518    ///
2519    /// - [`transmute_lens`](Self::transmute_lens) to convert to a lens using a mutable borrow of the [`Query`].
2520    #[track_caller]
2521    pub fn transmute_lens_inner<NewD: SingleEntityQueryData>(self) -> QueryLens<'w, NewD> {
2522        self.transmute_lens_filtered_inner::<NewD, ()>()
2523    }
2524
2525    /// Equivalent to [`Self::transmute_lens`] but also includes a [`QueryFilter`] type.
2526    ///
2527    /// See [`Self::transmute_lens`] for a description of allowed transmutes.
2528    ///
2529    /// Note that the lens will iterate the same tables and archetypes as the original query. This means that
2530    /// additional archetypal query terms like [`With`](crate::query::With) and [`Without`](crate::query::Without)
2531    /// will not necessarily be respected and non-archetypal terms like [`Added`](crate::query::Added),
2532    /// [`Changed`](crate::query::Changed) and [`Spawned`](crate::query::Spawned) will only be respected if they
2533    /// are in the type signature.
2534    #[track_caller]
2535    pub fn transmute_lens_filtered<NewD: SingleEntityQueryData, NewF: QueryFilter>(
2536        &mut self,
2537    ) -> QueryLens<'_, NewD, NewF> {
2538        self.reborrow().transmute_lens_filtered_inner()
2539    }
2540
2541    /// Equivalent to [`Self::transmute_lens_inner`] but also includes a [`QueryFilter`] type.
2542    /// This consumes the [`Query`] to return results with the actual "inner" world lifetime.
2543    ///
2544    /// See [`Self::transmute_lens`] for a description of allowed transmutes.
2545    ///
2546    /// Note that the lens will iterate the same tables and archetypes as the original query. This means that
2547    /// additional archetypal query terms like [`With`](crate::query::With) and [`Without`](crate::query::Without)
2548    /// will not necessarily be respected and non-archetypal terms like [`Added`](crate::query::Added),
2549    /// [`Changed`](crate::query::Changed) and [`Spawned`](crate::query::Spawned) will only be respected if they
2550    /// are in the type signature.
2551    ///
2552    /// # See also
2553    ///
2554    /// - [`transmute_lens_filtered`](Self::transmute_lens_filtered) to convert to a lens using a mutable borrow of the [`Query`].
2555    #[track_caller]
2556    pub fn transmute_lens_filtered_inner<NewD: SingleEntityQueryData, NewF: QueryFilter>(
2557        self,
2558    ) -> QueryLens<'w, NewD, NewF> {
2559        let state = self.state.transmute_filtered::<NewD, NewF>(self.world);
2560        QueryLens {
2561            world: self.world,
2562            state,
2563            last_run: self.last_run,
2564            this_run: self.this_run,
2565        }
2566    }
2567
2568    /// Gets a [`QueryLens`] with the same accesses as the existing query
2569    pub fn as_query_lens(&mut self) -> QueryLens<'_, D>
2570    where
2571        D: SingleEntityQueryData,
2572    {
2573        self.transmute_lens()
2574    }
2575
2576    /// Gets a [`QueryLens`] with the same accesses as the existing query
2577    ///
2578    /// # See also
2579    ///
2580    /// - [`as_query_lens`](Self::as_query_lens) to convert to a lens using a mutable borrow of the [`Query`].
2581    pub fn into_query_lens(self) -> QueryLens<'w, D>
2582    where
2583        D: SingleEntityQueryData,
2584    {
2585        self.transmute_lens_inner()
2586    }
2587
2588    /// Returns a [`QueryLens`] that can be used to get a query with the combined fetch.
2589    ///
2590    /// For example, this can take a `Query<&A>` and a `Query<&B>` and return a `Query<(&A, &B)>`.
2591    /// The returned query will only return items with both `A` and `B`. Note that since filters
2592    /// are dropped, non-archetypal filters like `Added`, `Changed` and `Spawned` will not be respected.
2593    /// To maintain or change filter terms see `Self::join_filtered`.
2594    ///
2595    /// ## Example
2596    ///
2597    /// ```rust
2598    /// # use bevy_ecs::prelude::*;
2599    /// # use bevy_ecs::system::QueryLens;
2600    /// #
2601    /// # #[derive(Component)]
2602    /// # struct Transform;
2603    /// #
2604    /// # #[derive(Component)]
2605    /// # struct Player;
2606    /// #
2607    /// # #[derive(Component)]
2608    /// # struct Enemy;
2609    /// #
2610    /// # let mut world = World::default();
2611    /// # world.spawn((Transform, Player));
2612    /// # world.spawn((Transform, Enemy));
2613    ///
2614    /// fn system(
2615    ///     mut transforms: Query<&Transform>,
2616    ///     mut players: Query<&Player>,
2617    ///     mut enemies: Query<&Enemy>
2618    /// ) {
2619    ///     let mut players_transforms: QueryLens<(&Transform, &Player)> = transforms.join(&mut players);
2620    ///     for (transform, player) in &players_transforms.query() {
2621    ///         // do something with a and b
2622    ///     }
2623    ///
2624    ///     let mut enemies_transforms: QueryLens<(&Transform, &Enemy)> = transforms.join(&mut enemies);
2625    ///     for (transform, enemy) in &enemies_transforms.query() {
2626    ///         // do something with a and b
2627    ///     }
2628    /// }
2629    ///
2630    /// # let mut schedule = Schedule::default();
2631    /// # schedule.add_systems(system);
2632    /// # schedule.run(&mut world);
2633    /// ```
2634    /// ## Panics
2635    ///
2636    /// This will panic if `NewD` is not a subset of the union of the original fetch `Q` and `OtherD`.
2637    ///
2638    /// ## Allowed Transmutes
2639    ///
2640    /// Like `transmute_lens` the query terms can be changed with some restrictions.
2641    /// See [`Self::transmute_lens`] for more details.
2642    pub fn join<'a, OtherD: QueryData, NewD: SingleEntityQueryData>(
2643        &'a mut self,
2644        other: &'a mut Query<OtherD>,
2645    ) -> QueryLens<'a, NewD> {
2646        self.join_filtered(other)
2647    }
2648
2649    /// Returns a [`QueryLens`] that can be used to get a query with the combined fetch.
2650    /// This consumes the [`Query`] to return results with the actual "inner" world lifetime.
2651    ///
2652    /// For example, this can take a `Query<&A>` and a `Query<&B>` and return a `Query<(&A, &B)>`.
2653    /// The returned query will only return items with both `A` and `B`. Note that since filters
2654    /// are dropped, non-archetypal filters like `Added`, `Changed` and `Spawned` will not be respected.
2655    /// To maintain or change filter terms see `Self::join_filtered`.
2656    ///
2657    /// ## Panics
2658    ///
2659    /// This will panic if `NewD` is not a subset of the union of the original fetch `Q` and `OtherD`.
2660    ///
2661    /// ## Allowed Transmutes
2662    ///
2663    /// Like `transmute_lens` the query terms can be changed with some restrictions.
2664    /// See [`Self::transmute_lens`] for more details.
2665    ///
2666    /// # See also
2667    ///
2668    /// - [`join`](Self::join) to join using a mutable borrow of the [`Query`].
2669    pub fn join_inner<OtherD: QueryData, NewD: SingleEntityQueryData>(
2670        self,
2671        other: Query<'w, '_, OtherD>,
2672    ) -> QueryLens<'w, NewD> {
2673        self.join_filtered_inner(other)
2674    }
2675
2676    /// Equivalent to [`Self::join`] but also includes a [`QueryFilter`] type.
2677    ///
2678    /// Note that the lens with iterate a subset of the original queries' tables
2679    /// and archetypes. This means that additional archetypal query terms like
2680    /// `With` and `Without` will not necessarily be respected and non-archetypal
2681    /// terms like `Added`, `Changed` and `Spawned` will only be respected if they
2682    /// are in the type signature.
2683    pub fn join_filtered<
2684        'a,
2685        OtherD: QueryData,
2686        OtherF: QueryFilter,
2687        NewD: SingleEntityQueryData,
2688        NewF: QueryFilter,
2689    >(
2690        &'a mut self,
2691        other: &'a mut Query<OtherD, OtherF>,
2692    ) -> QueryLens<'a, NewD, NewF> {
2693        self.reborrow().join_filtered_inner(other.reborrow())
2694    }
2695
2696    /// Equivalent to [`Self::join_inner`] but also includes a [`QueryFilter`] type.
2697    /// This consumes the [`Query`] to return results with the actual "inner" world lifetime.
2698    ///
2699    /// Note that the lens with iterate a subset of the original queries' tables
2700    /// and archetypes. This means that additional archetypal query terms like
2701    /// `With` and `Without` will not necessarily be respected and non-archetypal
2702    /// terms like `Added`, `Changed` and `Spawned` will only be respected if they
2703    /// are in the type signature.
2704    ///
2705    /// # See also
2706    ///
2707    /// - [`join_filtered`](Self::join_filtered) to join using a mutable borrow of the [`Query`].
2708    pub fn join_filtered_inner<
2709        OtherD: QueryData,
2710        OtherF: QueryFilter,
2711        NewD: SingleEntityQueryData,
2712        NewF: QueryFilter,
2713    >(
2714        self,
2715        other: Query<'w, '_, OtherD, OtherF>,
2716    ) -> QueryLens<'w, NewD, NewF> {
2717        let state = self
2718            .state
2719            .join_filtered::<OtherD, OtherF, NewD, NewF>(self.world, other.state);
2720        QueryLens {
2721            world: self.world,
2722            state,
2723            last_run: self.last_run,
2724            this_run: self.this_run,
2725        }
2726    }
2727}
2728
2729impl<'w, 's, D: IterQueryData, F: QueryFilter> IntoIterator for Query<'w, 's, D, F> {
2730    type Item = D::Item<'w, 's>;
2731    type IntoIter = QueryIter<'w, 's, D, F>;
2732
2733    fn into_iter(self) -> Self::IntoIter {
2734        self.iter_inner()
2735    }
2736}
2737
2738impl<'w, 's, D: QueryData, F: QueryFilter> IntoIterator for &'w Query<'_, 's, D, F> {
2739    type Item = ROQueryItem<'w, 's, D>;
2740    type IntoIter = QueryIter<'w, 's, D::ReadOnly, F>;
2741
2742    fn into_iter(self) -> Self::IntoIter {
2743        self.iter()
2744    }
2745}
2746
2747impl<'w, 's, D: IterQueryData, F: QueryFilter> IntoIterator for &'w mut Query<'_, 's, D, F> {
2748    type Item = D::Item<'w, 's>;
2749    type IntoIter = QueryIter<'w, 's, D, F>;
2750
2751    fn into_iter(self) -> Self::IntoIter {
2752        self.iter_mut()
2753    }
2754}
2755
2756/// Type returned from [`Query::transmute_lens`] containing the new [`QueryState`].
2757///
2758/// Call [`query`](QueryLens::query) or [`into`](Into::into) to construct the resulting [`Query`]
2759pub struct QueryLens<'w, Q: QueryData, F: QueryFilter = ()> {
2760    world: UnsafeWorldCell<'w>,
2761    state: QueryState<Q, F>,
2762    last_run: Tick,
2763    this_run: Tick,
2764}
2765
2766impl<'w, Q: QueryData, F: QueryFilter> QueryLens<'w, Q, F> {
2767    /// Create a [`Query`] from the underlying [`QueryState`].
2768    pub fn query(&mut self) -> Query<'_, '_, Q, F> {
2769        Query {
2770            world: self.world,
2771            state: &self.state,
2772            last_run: self.last_run,
2773            this_run: self.this_run,
2774        }
2775    }
2776}
2777
2778impl<'w, Q: ReadOnlyQueryData, F: QueryFilter> QueryLens<'w, Q, F> {
2779    /// Create a [`Query`] from the underlying [`QueryState`].
2780    /// This returns results with the actual "inner" world lifetime,
2781    /// so it may only be used with read-only queries to prevent mutable aliasing.
2782    pub fn query_inner(&self) -> Query<'w, '_, Q, F> {
2783        Query {
2784            world: self.world,
2785            state: &self.state,
2786            last_run: self.last_run,
2787            this_run: self.this_run,
2788        }
2789    }
2790}
2791
2792impl<'w, 's, Q: QueryData, F: QueryFilter> From<&'s mut QueryLens<'w, Q, F>>
2793    for Query<'s, 's, Q, F>
2794{
2795    fn from(value: &'s mut QueryLens<'w, Q, F>) -> Query<'s, 's, Q, F> {
2796        value.query()
2797    }
2798}
2799
2800impl<'w, 'q, Q: SingleEntityQueryData, F: QueryFilter> From<&'q mut Query<'w, '_, Q, F>>
2801    for QueryLens<'q, Q, F>
2802{
2803    fn from(value: &'q mut Query<'w, '_, Q, F>) -> QueryLens<'q, Q, F> {
2804        value.transmute_lens_filtered()
2805    }
2806}
2807
2808/// [System parameter] that provides access to single entity's components, much like [`Query::single`]/[`Query::single_mut`].
2809///
2810/// This [`SystemParam`](crate::system::SystemParam) fails validation if zero or more than one matching entity exists.
2811/// This will cause the system to be skipped, according to the rules laid out in [`SystemParamValidationError`](crate::system::SystemParamValidationError).
2812///
2813/// Use [`Option<Single<D, F>>`] instead if zero or one matching entities can exist.
2814///
2815/// Note that [`Single`] is not used as a search optimization. It is used as a validation with slight overhead compared to [`Query`].
2816///
2817/// See [`Query`] for more details.
2818///
2819/// [System parameter]: crate::system::SystemParam
2820///
2821/// # Example
2822/// ```
2823/// # use bevy_ecs::prelude::*;
2824/// #[derive(Component)]
2825/// struct Hiding;
2826///
2827/// #[derive(Component)]
2828/// struct Boss {
2829///    health: f32
2830/// };
2831///
2832/// #[derive(Component)]
2833/// struct EnemySize {
2834///    height: f32
2835/// };
2836///
2837/// fn hurt_boss(mut boss: Single<&mut Boss, Without<Hiding>>) {
2838///    boss.health -= 4.0;
2839/// }
2840///
2841/// fn hurt_and_shrink_boss(mut boss_and_size: Single<(&mut Boss, &mut EnemySize)>) {
2842///    let (mut boss, mut size) = boss_and_size.into_inner();
2843///    boss.health -= 4.0;
2844///    size.height *= 0.5;
2845/// }
2846/// ```
2847/// Note that because [`Single`] implements [`Deref`] and [`DerefMut`], methods and fields like `health` can be accessed directly.
2848/// You can also access the underlying data manually, by calling `.deref`/`.deref_mut`, or by using the `*` operator.
2849/// When mutable elements appear in [`Single`], use `.into_inner` to extract the tuple elements to mutate them.
2850pub struct Single<'w, 's, D: IterQueryData, F: QueryFilter = ()> {
2851    pub(crate) item: D::Item<'w, 's>,
2852    pub(crate) _filter: PhantomData<F>,
2853}
2854
2855impl<'w, 's, D: IterQueryData, F: QueryFilter> Deref for Single<'w, 's, D, F> {
2856    type Target = D::Item<'w, 's>;
2857
2858    fn deref(&self) -> &Self::Target {
2859        &self.item
2860    }
2861}
2862
2863impl<'w, 's, D: IterQueryData, F: QueryFilter> DerefMut for Single<'w, 's, D, F> {
2864    fn deref_mut(&mut self) -> &mut Self::Target {
2865        &mut self.item
2866    }
2867}
2868
2869impl<'w, 's, D: IterQueryData, F: QueryFilter> Single<'w, 's, D, F> {
2870    /// Returns the inner item with ownership.
2871    pub fn into_inner(self) -> D::Item<'w, 's> {
2872        self.item
2873    }
2874}
2875
2876/// [System parameter] that works very much like [`Query`] except it always contains at least one matching entity.
2877///
2878/// This [`SystemParam`](crate::system::SystemParam) fails validation if no matching entities exist.
2879/// This will cause the system to be skipped, according to the rules laid out in [`SystemParamValidationError`](crate::system::SystemParamValidationError).
2880///
2881/// Much like [`Query::is_empty`] the worst case runtime will be `O(n)` where `n` is the number of *potential* matches.
2882/// This can be notably expensive for queries that rely on non-archetypal filters such as [`Added`](crate::query::Added),
2883/// [`Changed`](crate::query::Changed) of [`Spawned`](crate::query::Spawned) which must individually check each query
2884/// result for a match.
2885///
2886/// See [`Query`] for more details.
2887///
2888/// If the system doesn't need to perform the query but should still be skipped if it is empty,
2889/// you may use the [`any_with_component`](crate::schedule::common_conditions::any_with_component) or [`any_match_filter`](crate::schedule::common_conditions::any_match_filter) run conditions.
2890///
2891/// [System parameter]: crate::system::SystemParam
2892pub struct Populated<'w, 's, D: QueryData, F: QueryFilter = ()>(pub(crate) Query<'w, 's, D, F>);
2893
2894impl<'w, 's, D: QueryData, F: QueryFilter> Deref for Populated<'w, 's, D, F> {
2895    type Target = Query<'w, 's, D, F>;
2896
2897    fn deref(&self) -> &Self::Target {
2898        &self.0
2899    }
2900}
2901
2902impl<D: QueryData, F: QueryFilter> DerefMut for Populated<'_, '_, D, F> {
2903    fn deref_mut(&mut self) -> &mut Self::Target {
2904        &mut self.0
2905    }
2906}
2907
2908impl<'w, 's, D: QueryData, F: QueryFilter> Populated<'w, 's, D, F> {
2909    /// Returns the inner item with ownership.
2910    pub fn into_inner(self) -> Query<'w, 's, D, F> {
2911        self.0
2912    }
2913}
2914
2915impl<'w, 's, D: IterQueryData, F: QueryFilter> IntoIterator for Populated<'w, 's, D, F> {
2916    type Item = <Query<'w, 's, D, F> as IntoIterator>::Item;
2917
2918    type IntoIter = <Query<'w, 's, D, F> as IntoIterator>::IntoIter;
2919
2920    fn into_iter(self) -> Self::IntoIter {
2921        self.0.into_iter()
2922    }
2923}
2924
2925impl<'a, 'w, 's, D: QueryData, F: QueryFilter> IntoIterator for &'a Populated<'w, 's, D, F> {
2926    type Item = <&'a Query<'w, 's, D, F> as IntoIterator>::Item;
2927
2928    type IntoIter = <&'a Query<'w, 's, D, F> as IntoIterator>::IntoIter;
2929
2930    fn into_iter(self) -> Self::IntoIter {
2931        self.deref().into_iter()
2932    }
2933}
2934
2935impl<'a, 'w, 's, D: IterQueryData, F: QueryFilter> IntoIterator
2936    for &'a mut Populated<'w, 's, D, F>
2937{
2938    type Item = <&'a mut Query<'w, 's, D, F> as IntoIterator>::Item;
2939
2940    type IntoIter = <&'a mut Query<'w, 's, D, F> as IntoIterator>::IntoIter;
2941
2942    fn into_iter(self) -> Self::IntoIter {
2943        self.deref_mut().into_iter()
2944    }
2945}
2946
2947#[cfg(test)]
2948mod tests {
2949    use crate::{prelude::*, query::QueryEntityError};
2950    use alloc::vec::Vec;
2951
2952    #[test]
2953    fn get_many_uniqueness() {
2954        let mut world = World::new();
2955
2956        let entities: Vec<Entity> = (0..10).map(|_| world.spawn_empty().id()).collect();
2957
2958        let mut query_state = world.query::<Entity>();
2959
2960        // It's best to test get_many_mut_inner directly, as it is shared
2961        // We don't care about aliased mutability for the read-only equivalent
2962
2963        // SAFETY: Query does not access world data.
2964        assert!(query_state
2965            .query_mut(&mut world)
2966            .get_many_mut_inner::<10>(entities.clone().try_into().unwrap())
2967            .is_ok());
2968
2969        assert_eq!(
2970            query_state
2971                .query_mut(&mut world)
2972                .get_many_mut_inner([entities[0], entities[0]])
2973                .unwrap_err(),
2974            QueryEntityError::AliasedMutability(entities[0])
2975        );
2976
2977        assert_eq!(
2978            query_state
2979                .query_mut(&mut world)
2980                .get_many_mut_inner([entities[0], entities[1], entities[0]])
2981                .unwrap_err(),
2982            QueryEntityError::AliasedMutability(entities[0])
2983        );
2984
2985        assert_eq!(
2986            query_state
2987                .query_mut(&mut world)
2988                .get_many_mut_inner([entities[9], entities[9]])
2989                .unwrap_err(),
2990            QueryEntityError::AliasedMutability(entities[9])
2991        );
2992    }
2993}