1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
use std::rc::Rc;
use std::sync::Arc;
use std::future::Future;
use std::cell::UnsafeCell;
use futures::{future::{FutureExt, BoxFuture}, task::ArcWake};
use crate::{AsyncTask, local_queue::LocalQueueSpawner};
pub struct LocalTask<O> {
future: UnsafeCell<Option<BoxFuture<'static, O>>>,
spawner: Rc<LocalQueueSpawner<Self, O>>,
}
unsafe impl<O> Send for LocalTask<O> {}
unsafe impl<O> Sync for LocalTask<O> {}
impl<O> ArcWake for LocalTask<O> {
fn wake_by_ref(arc_self: &Arc<Self>) {
let task = arc_self.clone();
arc_self.spawner.wakeup(task).unwrap();
}
}
impl<O> AsyncTask for LocalTask<O> {
type Out = O;
fn get_inner(&self) -> Option<BoxFuture<'static, Self::Out>> {
unsafe { (*self.future.get()).take() }
}
fn set_inner(&self, inner: Option<BoxFuture<'static, Self::Out>>) {
unsafe { *self.future.get() = inner; }
}
}
impl<O> LocalTask<O> {
pub fn new(spawner: Rc<LocalQueueSpawner<Self, O>>, future: impl Future<Output = O> + Send + 'static) -> Self {
LocalTask {
future: UnsafeCell::new(Some(future.boxed())),
spawner,
}
}
}