use alloc::rc::Rc;
use core::{cell::Cell, fmt, future::Future};
use futures::task::{LocalSpawnExt, SpawnExt};
type PoolHandle = Rc<Cell<Option<futures::executor::LocalPool>>>;
#[derive(Clone)]
pub struct LocalSpawner(PoolHandle, futures::executor::LocalSpawner);
impl fmt::Debug for LocalSpawner {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_tuple("LocalSpawner")
.field(&"..")
.field(&self.1)
.finish()
}
}
impl Default for LocalSpawner {
fn default() -> Self {
let local_pool = futures::executor::LocalPool::new();
let local_spawner = local_pool.spawner();
Self(Rc::new(Cell::new(Some(local_pool))), local_spawner)
}
}
impl LocalSpawner {
pub fn block_on(self, f: impl Future<Output = ()> + 'static) {
self.1.spawn_local(f).unwrap();
self.0.take().unwrap().run();
}
}
impl super::Spawn for LocalSpawner {
#[inline(always)]
fn spawn_local(&self, f: impl Future<Output = ()> + 'static) {
self.1.spawn_local(f).unwrap();
}
#[inline(always)]
fn spawn(&self, f: impl Future<Output = ()> + Send + 'static) {
self.1.spawn(f).unwrap();
}
}