yaaral 0.5.3

yet another async runtime abstraction library
Documentation
//! Implementation of the Runtime for the `bevy_tasks` runtime

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()
    }
}

/// Runtime for interfacing with bevy task pools.
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,
        }
    }
}

/// Runtime for the task of bevy
pub type AsyncComputeTaskRuntime = Runtime<AsyncComputeTaskPool>;

/// Create a runtime from the async compute task pool.
pub fn async_compute_task_pool() -> AsyncComputeTaskRuntime {
    Runtime {
        task_pool: AsyncComputeTaskPool::get(),
    }
}

/// Runtime for the IO task of bevy
pub type IoTaskRuntime = Runtime<IoTaskPool>;

/// Create a runtime from the IO task pool.
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())
    }
}