use std::ops::Deref;
#[cfg(feature = "bevy_runtime_018")]
use bevy_tasks_018 as bevy_tasks;
use bevy_tasks::{AsyncComputeTaskPool, IoTaskPool, Task, TaskPool};
use crate::prelude::*;
impl<T: Send> crate::TaskHandle for Task<Result<T, Infallible>> {
type Output = T;
type JoinError = Infallible;
fn join(self) -> impl Future<Output = Result<Self::Output, Self::JoinError>> {
self
}
fn abort(self) {}
async fn cancel(self) {
self.cancel().await;
}
fn detach(self) {
self.detach()
}
}
pub struct Runtime<TP>
where
TP: Deref<Target = TaskPool> + Sync + 'static,
{
task_pool: &'static TP,
}
impl<TP> Clone for Runtime<TP>
where
TP: Deref<Target = TaskPool> + Sync + 'static,
{
fn clone(&self) -> Self {
Self {
task_pool: self.task_pool,
}
}
}
pub type AsyncComputeTaskRuntime = Runtime<AsyncComputeTaskPool>;
pub fn async_compute_task_pool() -> AsyncComputeTaskRuntime {
Runtime {
task_pool: AsyncComputeTaskPool::get(),
}
}
pub type IoTaskRuntime = Runtime<IoTaskPool>;
pub fn io_task_pool() -> IoTaskRuntime {
Runtime {
task_pool: IoTaskPool::get(),
}
}
impl<TP> TaskInterface for Runtime<TP>
where
TP: Deref<Target = TaskPool> + Sync + 'static,
{
type JoinError = Infallible;
type SpawnError = Infallible;
type TaskHandle<T: 'static + Send> = Task<Result<T, Infallible>>;
fn block_on<F: Future>(&self, future: F) -> F::Output {
bevy_tasks::block_on(future)
}
fn spawn_task<F, T>(
&self,
future: F,
) -> Result<crate::utils::TaskHandle<Self::TaskHandle<F::Output>>, Self::SpawnError>
where
F: Future<Output = T> + Send + 'static,
T: Send + 'static,
{
Ok(self.task_pool.spawn(async move { Ok(future.await) }).into())
}
}