Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

[Merged by Bors] - Add Query::contains #3090

Closed
wants to merge 11 commits into from
40 changes: 38 additions & 2 deletions crates/bevy_ecs/src/system/query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ use crate::{
component::Component,
entity::Entity,
query::{
Fetch, FilterFetch, QueryCombinationIter, QueryEntityError, QueryIter, QueryState,
WorldQuery,
Fetch, FilterFetch, NopFetch, QueryCombinationIter, QueryEntityError, QueryIter,
QueryState, WorldQuery,
},
world::{Mut, World},
};
Expand Down Expand Up @@ -961,6 +961,42 @@ where
self.state
.is_empty(self.world, self.last_change_tick, self.change_tick)
}

/// Returns `true` if the given [`Entity`] matches the query.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't propose that you take any action on this comment, just noting down my thoughts.

By a strict reading of these docs, a valid implementation of this function would be {true}; we don't specify the behaviour if the condition is false. It is however intended to be read as if and only if.

However, this fits the pattern of documentation in std, e.g. Vec::contains. I tried to find a rust-lang/rust issue on these doc items, but failed to do so.

///
/// # Example
///
/// ```
/// # use bevy_ecs::prelude::*;
/// #
/// # #[derive(Component)]
/// # struct InRange;
/// #
/// # struct Target {
/// # entity: Entity,
/// # }
/// #
/// fn targeting_system(in_range_query: Query<&InRange>, target: Res<Target>) {
/// if in_range_query.contains(target.entity) {
/// println!("Bam!")
/// }
/// }
/// # targeting_system.system();
/// ```
#[inline]
pub fn contains(&self, entity: Entity) -> bool {
// SAFE: NopFetch does not access any members while &self ensures no one has exclusive access
unsafe {
self.state
.get_unchecked_manual::<NopFetch<Q::State>>(
self.world,
entity,
self.last_change_tick,
self.change_tick,
)
.is_ok()
}
}
}

/// An error that occurs when retrieving a specific [`Entity`]'s component from a [`Query`]
Expand Down