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
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
#[cfg(feature = "time")]
mod timeout;
#[cfg(feature = "time")]
pub use timeout::*;

#[cfg(feature = "time")]
mod after;
#[cfg(feature = "time")]
pub use after::*;

#[cfg(feature = "time")]
mod sleep;
#[cfg(feature = "time")]
pub use sleep::*;

#[cfg(feature = "time")]
mod interval;
#[cfg(feature = "time")]
pub use interval::*;

#[cfg(feature = "time")]
mod delay;
#[cfg(feature = "time")]
pub use delay::*;

use core::{
  future::Future,
  pin::Pin,
  task::{Context, Poll},
};

#[cfg(feature = "time")]
use std::time::{Duration, Instant};

use wasm::channel::*;

use crate::{AsyncBlockingSpawner, AsyncLocalSpawner, AsyncSpawner, Yielder};

impl<T> super::Detach for WasmJoinHandle<T> {}

/// The join handle returned by [`WasmSpawner`].
pub struct WasmJoinHandle<F> {
  pub(crate) stop_tx: oneshot::Sender<bool>,
  pub(crate) rx: oneshot::Receiver<F>,
}

impl<F> Future for WasmJoinHandle<F> {
  type Output = Result<F, oneshot::Canceled>;

  fn poll(
    mut self: core::pin::Pin<&mut Self>,
    cx: &mut core::task::Context<'_>,
  ) -> core::task::Poll<Self::Output> {
    core::pin::Pin::new(&mut self.rx).poll(cx)
  }
}

impl<F> WasmJoinHandle<F> {
  /// Detach the future from the spawner.
  #[inline]
  pub fn detach(self) {
    let _ = self.stop_tx.send(false);
  }

  /// Cancel the future.
  #[inline]
  pub fn cancel(self) {
    let _ = self.stop_tx.send(true);
  }
}

/// A [`AsyncSpawner`] that uses the [`wasm-bindgen-futures`](wasm_bindgen_futures) runtime.
#[derive(Debug, Clone, Copy)]
pub struct WasmSpawner;

impl AsyncSpawner for WasmSpawner {
  type JoinHandle<F> = WasmJoinHandle<F> where F: Send + 'static;

  fn spawn<F>(future: F) -> Self::JoinHandle<F::Output>
  where
    F::Output: Send + 'static,
    F: core::future::Future + Send + 'static,
  {
    <Self as super::AsyncLocalSpawner>::spawn_local(future)
  }
}

impl AsyncLocalSpawner for WasmSpawner {
  type JoinHandle<F> = WasmJoinHandle<F> where F: 'static;

  fn spawn_local<F>(future: F) -> Self::JoinHandle<F::Output>
  where
    F::Output: 'static,
    F: core::future::Future + 'static,
  {
    use futures_util::FutureExt;

    let (tx, rx) = oneshot::channel();
    let (stop_tx, stop_rx) = oneshot::channel();
    wasm::spawn_local(async {
      futures_util::pin_mut!(future);

      futures_util::select! {
        sig = stop_rx.fuse() => {
          match sig {
            Ok(true) => {
              // if we receive a stop signal, we just stop this task.
            },
            Ok(false) | Err(_) => {
              let _ = future.await;
            },
          }
        },
        future = (&mut future).fuse() => {
          let _ = tx.send(future);
        }
      }
    });
    WasmJoinHandle { stop_tx, rx }
  }
}

impl AsyncBlockingSpawner for WasmSpawner {
  type JoinHandle<R> = std::thread::JoinHandle<R>
  where
    R: Send + 'static;

  fn spawn_blocking<F, R>(f: F) -> Self::JoinHandle<R>
  where
    F: FnOnce() -> R + Send + 'static,
    R: Send + 'static,
  {
    std::thread::spawn(f)
  }
}

impl Yielder for WasmSpawner {
  async fn yield_now() {
    YieldNow(false).await
  }
}

/// Future for the [`yield_now`](RuntimeLite::yield_now) function.
#[derive(Debug)]
#[must_use = "futures do nothing unless you `.await` or poll them"]
struct YieldNow(bool);

impl Future for YieldNow {
  type Output = ();

  fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
    if !self.0 {
      self.0 = true;
      cx.waker().wake_by_ref();
      Poll::Pending
    } else {
      Poll::Ready(())
    }
  }
}

/// Concrete [`RuntimeLite`](crate::RuntimeLite) implementation based on [`tokio`](::tokio) runtime.
#[derive(Debug, Clone, Copy)]
pub struct WasmRuntime;

impl core::fmt::Display for WasmRuntime {
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    write!(f, "wasm-bindgen-futures")
  }
}

impl super::RuntimeLite for WasmRuntime {
  type Spawner = WasmSpawner;
  type LocalSpawner = WasmSpawner;
  type BlockingSpawner = WasmSpawner;

  #[cfg(feature = "time")]
  type AfterSpawner = WasmSpawner;
  #[cfg(feature = "time")]
  type LocalAfterSpawner = WasmSpawner;

  #[cfg(feature = "time")]
  type Interval = WasmInterval;
  #[cfg(feature = "time")]
  type LocalInterval = WasmInterval;
  #[cfg(feature = "time")]
  type Sleep = WasmSleep;
  #[cfg(feature = "time")]
  type LocalSleep = WasmSleep;
  #[cfg(feature = "time")]
  type Delay<F> = WasmDelay<F> where F: Future + Send;
  #[cfg(feature = "time")]
  type LocalDelay<F> = WasmDelay<F> where F: Future;
  #[cfg(feature = "time")]
  type Timeout<F> = WasmTimeout<F> where F: Future + Send;
  #[cfg(feature = "time")]
  type LocalTimeout<F> = WasmTimeout<F> where F: Future;

  fn new() -> Self {
    Self
  }

  fn block_on<F: Future>(_f: F) -> F::Output {
    panic!("RuntimeLite::block_on is not supported on wasm")
  }

  #[cfg(feature = "time")]
  fn interval(interval: Duration) -> Self::Interval {
    use crate::time::AsyncIntervalExt;

    WasmInterval::interval(interval)
  }

  #[cfg(feature = "time")]
  fn interval_at(start: Instant, period: Duration) -> Self::Interval {
    use crate::time::AsyncIntervalExt;

    WasmInterval::interval_at(start, period)
  }

  #[cfg(feature = "time")]
  fn interval_local(interval: Duration) -> Self::LocalInterval {
    use crate::time::AsyncIntervalExt;

    WasmInterval::interval(interval)
  }

  #[cfg(feature = "time")]
  fn interval_local_at(start: Instant, period: Duration) -> Self::LocalInterval {
    use crate::time::AsyncIntervalExt;

    WasmInterval::interval_at(start, period)
  }

  #[cfg(feature = "time")]
  fn sleep(duration: Duration) -> Self::Sleep {
    use crate::time::AsyncSleepExt;

    WasmSleep::sleep(duration)
  }

  #[cfg(feature = "time")]
  fn sleep_until(instant: Instant) -> Self::Sleep {
    use crate::time::AsyncSleepExt;

    WasmSleep::sleep_until(instant)
  }

  #[cfg(feature = "time")]
  fn sleep_local(duration: Duration) -> Self::LocalSleep {
    use crate::time::AsyncSleepExt;

    WasmSleep::sleep(duration)
  }

  #[cfg(feature = "time")]
  fn sleep_local_until(instant: Instant) -> Self::LocalSleep {
    use crate::time::AsyncSleepExt;

    WasmSleep::sleep_until(instant)
  }

  async fn yield_now() {
    YieldNow(false).await
  }

  #[cfg(feature = "time")]
  fn delay<F>(duration: Duration, fut: F) -> Self::Delay<F>
  where
    F: Future + Send,
  {
    use crate::time::AsyncDelayExt;

    <WasmDelay<F> as AsyncDelayExt<F>>::delay(duration, fut)
  }

  #[cfg(feature = "time")]
  fn delay_local<F>(duration: Duration, fut: F) -> Self::LocalDelay<F>
  where
    F: Future,
  {
    use crate::time::AsyncLocalDelayExt;

    <WasmDelay<F> as AsyncLocalDelayExt<F>>::delay(duration, fut)
  }

  #[cfg(feature = "time")]
  fn delay_at<F>(deadline: Instant, fut: F) -> Self::Delay<F>
  where
    F: Future + Send,
  {
    use crate::time::AsyncDelayExt;

    <WasmDelay<F> as AsyncDelayExt<F>>::delay_at(deadline, fut)
  }

  #[cfg(feature = "time")]
  fn delay_local_at<F>(deadline: Instant, fut: F) -> Self::LocalDelay<F>
  where
    F: Future,
  {
    use crate::time::AsyncLocalDelayExt;

    <WasmDelay<F> as AsyncLocalDelayExt<F>>::delay_at(deadline, fut)
  }
}