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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
#[cfg(not(target_arch = "wasm32"))]
use crate::futures::executor::ThreadPool;
use parking_lot::Mutex;
use std::{
    any::Any,
    future::Future,
    sync::mpsc::{self, Receiver, Sender},
};
use uuid::Uuid;

// ========
// Non-WASM
#[cfg(not(target_arch = "wasm32"))]
pub trait AsyncTaskResult: Any + Send + 'static {
    fn into_any(self: Box<Self>) -> Box<dyn Any>;
}

#[cfg(not(target_arch = "wasm32"))]
impl<T> AsyncTaskResult for T
where
    T: Any + Send + 'static,
{
    fn into_any(self: Box<Self>) -> Box<dyn Any> {
        self
    }
}

#[cfg(not(target_arch = "wasm32"))]
pub trait AsyncTask<R: AsyncTaskResult>: Future<Output = R> + Send + 'static {}

#[cfg(not(target_arch = "wasm32"))]
impl<T, R: AsyncTaskResult> AsyncTask<R> for T where T: Future<Output = R> + Send + 'static {}

// ========
// WASM
#[cfg(target_arch = "wasm32")]
pub trait AsyncTaskResult: Any + 'static {
    fn into_any(self: Box<Self>) -> Box<dyn Any>;
}

#[cfg(target_arch = "wasm32")]
impl<T> AsyncTaskResult for T
where
    T: Any + 'static,
{
    fn into_any(self: Box<Self>) -> Box<dyn Any> {
        self
    }
}

#[cfg(target_arch = "wasm32")]
pub trait AsyncTask<R: AsyncTaskResult>: Future<Output = R> + 'static {}

#[cfg(target_arch = "wasm32")]
impl<T, R: AsyncTaskResult> AsyncTask<R> for T where T: Future<Output = R> + 'static {}

// ========
// Common
impl dyn AsyncTaskResult {
    pub fn downcast<T: AsyncTaskResult>(self: Box<Self>) -> Result<Box<T>, Box<dyn Any>> {
        self.into_any().downcast()
    }
}

pub struct TaskResult {
    pub id: Uuid,
    pub payload: Box<dyn AsyncTaskResult>,
}

pub struct TaskPool {
    #[cfg(not(target_arch = "wasm32"))]
    thread_pool: ThreadPool,
    sender: Sender<TaskResult>,
    receiver: Mutex<Receiver<TaskResult>>,
}

impl Default for TaskPool {
    fn default() -> Self {
        Self::new()
    }
}

impl TaskPool {
    #[inline]
    pub fn new() -> Self {
        let (sender, receiver) = mpsc::channel();
        Self {
            #[cfg(not(target_arch = "wasm32"))]
            thread_pool: ThreadPool::new().unwrap(),
            sender,
            receiver: Mutex::new(receiver),
        }
    }

    #[inline]
    #[cfg(target_arch = "wasm32")]
    pub fn spawn_task<F>(&self, future: F)
    where
        F: Future<Output = ()> + 'static,
    {
        crate::wasm_bindgen_futures::spawn_local(future);
    }

    #[inline]
    #[cfg(not(target_arch = "wasm32"))]
    pub fn spawn_task<F>(&self, future: F)
    where
        F: Future<Output = ()> + Send + 'static,
    {
        self.thread_pool.spawn_ok(future);
    }

    #[inline]
    pub fn spawn_with_result<F, T>(&self, future: F) -> Uuid
    where
        F: AsyncTask<T>,
        T: AsyncTaskResult,
    {
        let id = Uuid::new_v4();
        let sender = self.sender.clone();
        self.spawn_task(async move {
            let result = future.await;
            sender
                .send(TaskResult {
                    id,
                    payload: Box::new(result),
                })
                .unwrap();
        });
        id
    }

    #[inline]
    pub fn next_task_result(&self) -> Option<TaskResult> {
        self.receiver.lock().try_recv().ok()
    }
}