use std::hash::Hash;
use super::{
component::channel::{ComponentChannel, ComponentMap},
system::param::SystemParameter,
world::UnsafeWorldCell,
};
pub struct Query<'c, T> {
channel: Option<&'c ComponentChannel<T>>
}
impl<'c, T> Query<'c, T> {
pub const fn from_channel(channel: Option<&'c ComponentChannel<T>>) -> Self {
Self { channel }
}
pub fn iter(&self) -> impl Iterator<Item = &T> {
self.channel
.iter()
.flat_map(|c| c.iter())
}
pub fn first(&self) -> Option<&T> {
self.iter()
.next()
}
}
impl<'c, T> SystemParameter for Query<'c, T>
where
T: 'static,
{
fn fetch(cell: &UnsafeWorldCell) -> Self {
let world = cell.get();
let components = world.components();
components.query::<T>()
}
}
pub struct QueryMut<'c, T> {
channel: Option<&'c mut ComponentChannel<T>>,
}
impl<'c, T> QueryMut<'c, T> {
pub const fn from_channel(channel: Option<&'c mut ComponentChannel<T>>) -> Self {
Self { channel }
}
pub fn iter_mut(&mut self) -> impl Iterator<Item = &mut T> {
self.channel
.iter_mut()
.flat_map(|c| c.iter_mut())
}
pub fn first_mut(&mut self) -> Option<&mut T> {
self.iter_mut()
.next()
}
}
impl<'c, T> SystemParameter for QueryMut<'c, T>
where
T: 'static,
{
fn fetch(cell: &UnsafeWorldCell) -> Self {
let world = cell.get_mut();
let components = world.components_mut();
components.query_mut::<T>()
}
}
pub struct QueryIndexed<'c, K, V> {
channel: Option<&'c ComponentMap<K, V>>,
}
impl<'c, K, V> QueryIndexed<'c, K, V>
where
K: Eq + Hash,
{
pub const fn from_channel(channel: Option<&'c ComponentMap<K, V>>) -> Self {
Self { channel }
}
pub fn get(&self, key: &K) -> Option<&'c V> {
self.channel.and_then(|c| c.get(key))
}
pub fn iter(&self) -> impl Iterator<Item = (&'c K, &'c V)> {
self.channel
.iter()
.flat_map(|c| c.iter())
}
}
impl<'c, K, V> SystemParameter for QueryIndexed<'c, K, V>
where
K: Eq + Hash + 'static,
V: 'static,
{
fn fetch(cell: &UnsafeWorldCell) -> Self {
let world = cell.get();
let components = world.components();
components.query_indexed::<K, V>()
}
}
pub struct QueryIndexedMut<'c, TKey, TValue> {
channel: Option<&'c mut ComponentMap<TKey, TValue>>,
}
impl<'c, TKey, TValue> QueryIndexedMut<'c, TKey, TValue>
where
TKey: Eq + Hash,
{
pub const fn from_channel(channel: Option<&'c mut ComponentMap<TKey, TValue>>) -> Self {
Self { channel }
}
pub fn get_mut(&'c mut self, key: &TKey) -> Option<&'c mut TValue> {
self.channel
.as_mut()
.and_then(|c| c.get_mut(key))
}
pub fn iter_mut(&'c mut self) -> impl Iterator<Item = (&'c TKey, &'c mut TValue)> {
self.channel
.iter_mut()
.flat_map(|c| c.iter_mut())
}
}
impl<'c, K, V> SystemParameter for QueryIndexedMut<'c, K, V>
where
K: Eq + Hash + 'static,
V: 'static,
{
fn fetch(cell: &UnsafeWorldCell) -> Self {
let world = cell.get_mut();
let components = world.components_mut();
components.query_indexed_mut::<K, V>()
}
}