use hecs::{Query, QueryBorrow};
#[cfg(feature = "parallel")]
use hecs::Entity;
pub trait View<'a> {
type Superset;
fn split(orig: Self::Superset) -> Self;
}
impl<'a, T> View<'a> for &'a T {
type Superset = Self;
fn split(orig: Self::Superset) -> Self {
orig
}
}
impl<'a, T> View<'a> for &'a mut T {
type Superset = Self;
fn split(orig: Self::Superset) -> Self {
orig
}
}
pub trait QueryExt {
type Item<'a>;
#[cfg(feature = "parallel")]
fn par_for_each<'a>(self, batch_size: u32, func: impl Fn((Entity, Self::Item<'a>)) + Send + Sync);
#[cfg(feature = "parallel")]
fn try_par_for_each<'a, E: Send>(
self,
batch_size: u32,
func: impl Fn((Entity, Self::Item<'a>)) -> Result<(), E> + Send + Sync,
) -> Result<(), E>;
}
impl<'w, 'q, Q> QueryExt for &'q mut QueryBorrow<'w, Q>
where
Q: Query,
for <'a> Q::Item<'a>: Send,
{
type Item<'a> = Q::Item<'q>;
#[cfg(feature = "parallel")]
fn par_for_each<'a>(self, batch_size: u32, func: impl Fn((Entity, Self::Item<'a>)) + Send + Sync) {
use rayon::iter::{ParallelBridge, ParallelIterator};
self.iter_batched(batch_size)
.par_bridge()
.for_each(|batch| batch.for_each(&func))
}
#[cfg(feature = "parallel")]
fn try_par_for_each<'a, E: Send>(
self,
batch_size: u32,
func: impl Fn((Entity, Self::Item<'a>)) -> Result<(), E> + Send + Sync,
) -> Result<(), E> {
use rayon::iter::{ParallelBridge, ParallelIterator};
self.iter_batched(batch_size)
.par_bridge()
.try_for_each(|mut batch| batch.try_for_each(&func))
}
}