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
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
//! Platform-specific extensions for [`web-thread`](crate) on the Web platform.

#[cfg(any(feature = "audio-worklet", docsrs))]
pub mod audio_worklet;
#[cfg(any(feature = "message", docsrs))]
pub mod message;

use std::fmt::{self, Debug, Formatter};
use std::future::{Future, Ready};
use std::io;
use std::panic::RefUnwindSafe;
use std::pin::Pin;
use std::task::{Context, Poll};

#[cfg(any(feature = "message", docsrs))]
use self::message::MessageSend;

#[cfg(not(all(target_family = "wasm", target_os = "unknown")))]
mod thread {
	pub(super) struct ScopeFuture<'scope, 'env, F, T>(&'scope &'env (F, T));
	pub(super) struct YieldNowFuture;
}

#[cfg(all(target_family = "wasm", target_os = "unknown"))]
use pin_project::pin_project;

#[cfg(all(target_family = "wasm", target_os = "unknown"))]
use crate::thread;
use crate::{Builder, JoinHandle, Scope, ScopedJoinHandle};

/// Returns [`true`] if the current thread supports blocking.
///
/// # Notes
///
/// Very notably, the thread containing [`Window`] (often called the main thread
/// on Web), does not support blocking.
///
/// Currently known thread types to support blocking:
/// - [Dedicated worker].
/// - [Shared worker] (currently only on Chromium based browsers).
///
/// Currently known thread types to **not** support blocking:
/// - [`Window`] (often called the main thread on Web).
/// - [Service worker].
/// - [Worklet].
///
/// [Dedicated worker]: https://developer.mozilla.org/en-US/docs/Web/API/Worker
/// [Service worker]: https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API
/// [Shared worker]: https://developer.mozilla.org/en-US/docs/Web/API/SharedWorker
/// [Worklet]: https://developer.mozilla.org/en-US/docs/Web/API/Worklet
/// [`Window`]: https://developer.mozilla.org/en-US/docs/Web/API/Window
///
/// # Example
///
/// ```
/// # #[cfg(all(target_feature = "atomics", not(unsupported_spawn)))]
/// # wasm_bindgen_test::wasm_bindgen_test_configure!(run_in_browser);
/// # #[cfg_attr(all(target_feature = "atomics", not(unsupported_spawn)), wasm_bindgen_test::wasm_bindgen_test)]
/// # async fn test() {
/// use web_thread::web::{self, JoinHandleExt};
///
/// let mut handle = web_thread::spawn(|| String::from("test"));
///
/// let result = if web::has_block_support() {
/// 	handle.join().unwrap()
/// } else {
/// 	handle.join_async().await.unwrap()
/// };
/// # let _ = result;
/// # }
/// # #[cfg(not(all(target_feature = "atomics", not(unsupported_spawn))))]
/// # let _ = test();
/// ```
#[must_use]
pub fn has_block_support() -> bool {
	thread::has_block_support()
}

/// Returns [`true`] if the main thread supports spawning threads.
///
/// # Notes
///
/// [`web-thread`](crate) will consider the first thread it finds itself in the
/// "main thread". If Wasm is instantiated in a [dedicated worker], it will
/// consider it as the "main thread".
///
/// Currently only two thread types are known to support spawning threads:
/// - [`Window`] (often called the main thread on Web).
/// - [Dedicated worker].
///
/// Additionally, the following is required to allow spawning threads:
/// - The atomics target feature is enabled.
/// - The site needs to be [cross-origin isolated].
///
/// [cross-origin isolated]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer#security_requirements
/// [dedicated worker]: https://developer.mozilla.org/en-US/docs/Web/API/Worker
/// [`Window`]: https://developer.mozilla.org/en-US/docs/Web/API/Window
///
/// # Example
///
/// ```
/// # wasm_bindgen_test::wasm_bindgen_test_configure!(run_in_browser);
/// # #[wasm_bindgen_test::wasm_bindgen_test]
/// # fn test() {
/// fn schedule_fun(f: impl 'static + FnOnce() + Send) {
/// 	if web_thread::web::has_spawn_support() {
/// 		web_thread::spawn(f);
/// 	} else {
/// 		wasm_bindgen_futures::spawn_local(async { f() });
/// 	}
/// }
///
/// schedule_fun(|| web_sys::console::log_1(&"Are we having fun yet?".into()));
/// # }
/// ```
#[must_use]
pub fn has_spawn_support() -> bool {
	thread::has_spawn_support()
}

/// Web-specific extension for [`web_thread::JoinHandle`](crate::JoinHandle).
pub trait JoinHandleExt<T> {
	/// Async version of [`JoinHandle::join()`].
	///
	/// # Panics
	///
	/// - If called on the thread to join.
	/// - If it was already polled to completion by another call to
	///   [`JoinHandleExt::join_async()`].
	///
	/// # Example
	///
	/// ```
	/// # #[cfg(all(target_feature = "atomics", not(unsupported_spawn)))]
	/// # wasm_bindgen_test::wasm_bindgen_test_configure!(run_in_browser);
	/// # #[cfg_attr(all(target_feature = "atomics", not(unsupported_spawn)), wasm_bindgen_test::wasm_bindgen_test)]
	/// # async fn test() {
	/// use web_thread::web::JoinHandleExt;
	///
	/// web_thread::spawn(|| ()).join_async().await.unwrap();
	/// # }
	/// # #[cfg(not(all(target_feature = "atomics", not(unsupported_spawn))))]
	/// # let _ = test();
	/// ```
	fn join_async(&mut self) -> JoinHandleFuture<'_, T>;
}

impl<T> JoinHandleExt<T> for JoinHandle<T> {
	fn join_async(&mut self) -> JoinHandleFuture<'_, T> {
		JoinHandleFuture(self)
	}
}

/// Waits for the associated thread to finish. See
/// [`JoinHandleExt::join_async()`].
#[must_use = "does nothing if not polled"]
pub struct JoinHandleFuture<'handle, T>(&'handle mut JoinHandle<T>);

impl<T> Debug for JoinHandleFuture<'_, T> {
	fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
		formatter
			.debug_tuple("JoinHandleFuture")
			.field(&self.0)
			.finish()
	}
}

impl<T> Future for JoinHandleFuture<'_, T> {
	type Output = crate::Result<T>;

	fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
		JoinHandle::poll(self.0, cx)
	}
}

/// Async version of [`scope()`](crate::scope).
///
/// # Notes
///
/// Keep in mind that if [`ScopeFuture`] is dropped it will block, or spinloop
/// if blocking is not supported on this thread (see
/// [`has_block_support()`]), until all threads are joined but does not continue
/// polling the passed [`Future`].
///
/// # Example
///
/// ```
/// # #[cfg(all(target_feature = "atomics", not(unsupported_spawn)))]
/// # wasm_bindgen_test::wasm_bindgen_test_configure!(run_in_browser);
/// # #[cfg_attr(all(target_feature = "atomics", not(unsupported_spawn)), wasm_bindgen_test::wasm_bindgen_test)]
/// # async fn test() {
/// # use std::sync::atomic::{AtomicUsize, Ordering};
/// #
/// let value = AtomicUsize::new(0);
///
/// web_thread::web::scope_async(|scope| async {
/// 	(0..3).for_each(|_| {
/// 		scope.spawn(|| value.fetch_add(1, Ordering::Relaxed));
/// 	});
///
/// 	value.fetch_add(1, Ordering::Relaxed);
/// }).await;
///
/// assert_eq!(value.load(Ordering::Relaxed), 4);
/// # }
/// # #[cfg(not(all(target_feature = "atomics", not(unsupported_spawn))))]
/// # let _ = test();
/// ```
pub fn scope_async<'scope, 'env: 'scope, F1, F2, T>(
	#[allow(clippy::min_ident_chars)] f: F1,
) -> ScopeFuture<'scope, 'env, F2, T>
where
	F1: FnOnce(&'scope Scope<'scope, 'env>) -> F2,
	F2: Future<Output = T>,
{
	ScopeFuture(thread::scope_async(f))
}

/// Waits for the associated scope to finish. See [`scope_async()`].
///
/// # Notes
///
/// Keep in mind that if dropped it will block, or spinloop if blocking is not
/// supported on this thread (see [`has_block_support()`]), until all threads
/// are joined but does not continue polling the passed [`Future`].
#[must_use = "will block until all spawned threads are finished if not polled to completion"]
#[cfg_attr(all(target_family = "wasm", target_os = "unknown"), pin_project)]
pub struct ScopeFuture<'scope, 'env, F, T>(
	#[cfg_attr(all(target_family = "wasm", target_os = "unknown"), pin)]
	thread::ScopeFuture<'scope, 'env, F, T>,
);

impl<F, T> Debug for ScopeFuture<'_, '_, F, T> {
	fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
		formatter.debug_tuple("ScopeFuture").field(&self.0).finish()
	}
}

impl<F, T> Future for ScopeFuture<'_, '_, F, T>
where
	F: Future<Output = T>,
{
	type Output = T;

	fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
		self.project().0.poll(cx)
	}
}

impl<'scope, 'env, F, T> ScopeFuture<'scope, 'env, F, T> {
	/// Converts this [`ScopeFuture`] to a [`ScopeJoinFuture`] by waiting until
	/// the given [`Future`] to [`scope_async()`] is finished.
	///
	/// This is useful to:
	/// - Use [`ScopeJoinFuture::join_all()`].
	/// - Be able to drop [`ScopeJoinFuture`] while guaranteeing that the given
	///   [`Future`] to [`scope_async()`] is finished.
	/// - Get rid of `F` which often prevents [`ScopeFuture`] from implementing
	///   [`Unpin`].
	///
	/// # Example
	///
	/// ```
	/// # #[cfg(all(target_feature = "atomics", not(unsupported_spawn), not(unsupported_spawn_then_block)))]
	/// # wasm_bindgen_test::wasm_bindgen_test_configure!(run_in_dedicated_worker);
	/// # #[cfg_attr(all(target_feature = "atomics", not(unsupported_spawn), not(unsupported_spawn_then_block)), wasm_bindgen_test::wasm_bindgen_test)]
	/// # async fn test() {
	/// # use std::sync::atomic::{AtomicUsize, Ordering};
	/// #
	/// let value = AtomicUsize::new(0);
	///
	/// let future = web_thread::web::scope_async(|scope| async {
	/// 	(0..3).for_each(|_| {
	/// 		scope.spawn(|| value.fetch_add(1, Ordering::Relaxed));
	/// 	});
	///
	/// 	value.fetch_add(1, Ordering::Relaxed);
	/// }).into_wait().await;
	///
	/// // This will block until all threads are done.
	/// drop(future);
	///
	/// assert_eq!(value.load(Ordering::Relaxed), 4);
	/// # }
	/// # #[cfg(not(all(target_feature = "atomics", not(unsupported_spawn), not(unsupported_spawn_then_block))))]
	/// # let _ = test();
	/// ```
	pub const fn into_wait(self) -> ScopeIntoJoinFuture<'scope, 'env, F, T> {
		ScopeIntoJoinFuture(self)
	}
}

/// Web-specific extension for
/// [`web_thread::ScopedJoinHandle`](crate::ScopedJoinHandle).
pub trait ScopedJoinHandleExt<'scope, T> {
	/// Async version of [`ScopedJoinHandle::join()`].
	///
	/// # Panics
	///
	/// - If called on the thread to join.
	/// - If it was already polled to completion by another call to
	///   [`ScopedJoinHandleExt::join_async()`].
	///
	/// # Example
	///
	/// ```
	/// # #[cfg(all(target_feature = "atomics", not(unsupported_spawn)))]
	/// # wasm_bindgen_test::wasm_bindgen_test_configure!(run_in_browser);
	/// # #[cfg_attr(all(target_feature = "atomics", not(unsupported_spawn)), wasm_bindgen_test::wasm_bindgen_test)]
	/// # async fn test() {
	/// use web_thread::web::{self, ScopedJoinHandleExt};
	///
	/// web::scope_async(|scope| async {
	/// 	scope.spawn(|| ()).join_async().await.unwrap();
	/// }).await;
	/// # }
	/// # #[cfg(not(all(target_feature = "atomics", not(unsupported_spawn))))]
	/// # let _ = test();
	/// ```
	fn join_async<'handle>(&'handle mut self) -> ScopedJoinHandleFuture<'handle, 'scope, T>;
}

impl<'scope, T> ScopedJoinHandleExt<'scope, T> for ScopedJoinHandle<'scope, T> {
	fn join_async<'handle>(&'handle mut self) -> ScopedJoinHandleFuture<'handle, 'scope, T> {
		ScopedJoinHandleFuture(self)
	}
}

/// Waits for the associated thread to finish. See
/// [`ScopedJoinHandleExt::join_async()`].
#[must_use = "does nothing if not polled"]
pub struct ScopedJoinHandleFuture<'handle, 'scope, T>(&'handle mut ScopedJoinHandle<'scope, T>);

impl<T> Debug for ScopedJoinHandleFuture<'_, '_, T> {
	fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
		formatter
			.debug_tuple("JoinHandleFuture")
			.field(&self.0)
			.finish()
	}
}

impl<T> Future for ScopedJoinHandleFuture<'_, '_, T> {
	type Output = crate::Result<T>;

	fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
		ScopedJoinHandle::poll(self.0, cx)
	}
}

/// Poll to completion to get a [`ScopeJoinFuture`]. See
/// [`ScopeFuture::into_wait()`].
///
/// # Notes
///
/// Keep in mind that if dropped it will block, or spinloop if blocking is not
/// supported on this thread (see [`has_block_support()`]), until all threads
/// are joined but does not continue polling the [`Future`] passed into
/// [`scope_async()`].
#[must_use = "will block until all spawned threads are finished if not polled to completion"]
#[cfg_attr(all(target_family = "wasm", target_os = "unknown"), pin_project)]
pub struct ScopeIntoJoinFuture<'scope, 'env, F, T>(
	#[cfg_attr(all(target_family = "wasm", target_os = "unknown"), pin)]
	ScopeFuture<'scope, 'env, F, T>,
);

impl<F, T> Debug for ScopeIntoJoinFuture<'_, '_, F, T> {
	fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
		formatter
			.debug_tuple("ScopeIntoJoinFuture")
			.field(&self.0)
			.finish()
	}
}

impl<'scope, 'env, F, T> Future for ScopeIntoJoinFuture<'scope, 'env, F, T>
where
	F: Future<Output = T>,
{
	type Output = ScopeJoinFuture<'scope, 'env, T>;

	fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
		self.project()
			.0
			.project()
			.0
			.poll_into_wait(cx)
			.map(ScopeFuture)
			.map(ScopeJoinFuture)
	}
}

impl<'scope, 'env, F, T> ScopeIntoJoinFuture<'scope, 'env, F, T> {
	/// Reverts back to [`ScopeFuture`]. See [`ScopeFuture::into_wait()`].
	pub fn revert(self) -> ScopeFuture<'scope, 'env, F, T> {
		self.0
	}
}

/// Waits for the associated scope to finish. See [`ScopeFuture::into_wait()`].
///
/// # Notes
///
/// Keep in mind that if dropped it will block, or spinloop if blocking is not
/// supported on this thread (see [`has_block_support()`]), until all threads
/// are joined.
#[must_use = "will block until all spawned threads are finished if not polled to completion"]
pub struct ScopeJoinFuture<'scope, 'env, T>(ScopeFuture<'scope, 'env, Ready<T>, T>);

impl<T> Debug for ScopeJoinFuture<'_, '_, T> {
	fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
		formatter
			.debug_tuple("ScopeJoinFuture")
			.field(&self.0)
			.finish()
	}
}

impl<T> Future for ScopeJoinFuture<'_, '_, T> {
	type Output = T;

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

impl<T> ScopeJoinFuture<'_, '_, T> {
	/// Returns [`true`] if all threads have finished.
	///
	/// # Notes
	///
	/// When this returns [`true`] it guarantees [`ScopeJoinFuture::join_all()`]
	/// not to block.
	#[must_use]
	pub fn is_finished(&self) -> bool {
		self.0 .0.is_finished()
	}

	/// This will block until all associated threads are finished.
	///
	/// # Panics
	///
	/// - If the calling thread doesn't support blocking, see
	///   [`web::has_block_support()`](has_block_support). Though it is
	///   guaranteed to not block if [`ScopeJoinFuture::is_finished()`] returns
	///   [`true`]. Alternatively consider just polling this [`Future`] to
	///   completion.
	/// - If called after being polled to completion.
	///
	/// # Example
	///
	/// ```
	/// # #[cfg(all(target_feature = "atomics", not(unsupported_spawn), not(unsupported_spawn_then_block)))]
	/// # wasm_bindgen_test::wasm_bindgen_test_configure!(run_in_dedicated_worker);
	/// # #[cfg_attr(all(target_feature = "atomics", not(unsupported_spawn), not(unsupported_spawn_then_block)), wasm_bindgen_test::wasm_bindgen_test)]
	/// # async fn test() {
	/// # use std::sync::atomic::{AtomicUsize, Ordering};
	/// #
	/// let value = AtomicUsize::new(0);
	///
	/// let future = web_thread::web::scope_async(|scope| async {
	/// 	(0..3).for_each(|_| {
	/// 		scope.spawn(|| value.fetch_add(1, Ordering::Relaxed));
	/// 	});
	///
	/// 	value.fetch_add(1, Ordering::Relaxed);
	/// }).into_wait().await;
	///
	/// // This will block until all threads are done.
	/// future.join_all();
	///
	/// assert_eq!(value.load(Ordering::Relaxed), 4);
	/// # }
	/// # #[cfg(not(all(target_feature = "atomics", not(unsupported_spawn), not(unsupported_spawn_then_block))))]
	/// # let _ = test();
	/// ```
	pub fn join_all(self) -> T {
		self.0 .0.join_all()
	}
}

/// Web-specific extension for [`web_thread::Builder`](crate::Builder).
pub trait BuilderExt {
	/// Async version of [`Builder::spawn()`].
	///
	/// For a more complete documentation see [`spawn_async()`].
	///
	/// # Errors
	///
	/// If the main thread does not support spawning threads, see
	/// [`has_spawn_support()`].
	fn spawn_async<F1, F2, T>(self, f: F1) -> io::Result<JoinHandle<T>>
	where
		F1: 'static + FnOnce() -> F2 + Send,
		F2: 'static + Future<Output = T>,
		T: 'static + Send;

	/// [`spawn_async()`] with [message](MessageSend).
	///
	/// For a more complete documentation see [`spawn_with_message()`].
	///
	/// # Errors
	///
	/// - If the main thread does not support spawning threads, see
	///   [`has_spawn_support()`].
	/// - If `message` was unable to be cloned.
	#[cfg(any(feature = "message", docsrs))]
	fn spawn_with_message<F1, F2, T, M>(self, f: F1, message: M) -> io::Result<JoinHandle<T>>
	where
		F1: 'static + FnOnce(M) -> F2 + Send,
		F2: 'static + Future<Output = T>,
		T: 'static + Send,
		M: 'static + MessageSend;

	/// Async version of [`Builder::spawn_scoped()`].
	///
	/// For a more complete documentation see [`Scope::spawn_async()`].
	///
	/// # Errors
	///
	/// If the main thread does not support spawning threads, see
	/// [`has_spawn_support()`].
	fn spawn_scoped_async<'scope, #[allow(single_use_lifetimes)] 'env, F1, F2, T>(
		self,
		scope: &'scope Scope<'scope, 'env>,
		f: F1,
	) -> io::Result<ScopedJoinHandle<'scope, T>>
	where
		F1: 'scope + FnOnce() -> F2 + Send,
		F2: 'scope + Future<Output = T>,
		T: 'scope + Send;

	/// [`BuilderExt::spawn_scoped_async()`] with [message](MessageSend).
	///
	/// For a more complete documentation see [`Scope::spawn_with_message()`].
	///
	/// # Errors
	///
	/// - If the main thread does not support spawning threads, see
	///   [`has_spawn_support()`].
	/// - If `message` was unable to be cloned.
	#[cfg(any(feature = "message", docsrs))]
	fn spawn_scoped_with_message<'scope, #[allow(single_use_lifetimes)] 'env, F1, F2, T, M>(
		self,
		scope: &'scope Scope<'scope, 'env>,
		f: F1,
		message: M,
	) -> io::Result<ScopedJoinHandle<'scope, T>>
	where
		F1: 'scope + FnOnce(M) -> F2 + Send,
		F2: 'scope + Future<Output = T>,
		T: 'scope + Send,
		M: 'scope + MessageSend;
}

impl BuilderExt for Builder {
	fn spawn_async<F1, F2, T>(
		self,
		#[allow(clippy::min_ident_chars)] f: F1,
	) -> io::Result<JoinHandle<T>>
	where
		F1: 'static + FnOnce() -> F2 + Send,
		F2: 'static + Future<Output = T>,
		T: 'static + Send,
	{
		self.spawn_async_internal(f)
	}

	#[cfg(any(feature = "message", docsrs))]
	fn spawn_with_message<F1, F2, T, M>(
		self,
		#[allow(clippy::min_ident_chars)] f: F1,
		message: M,
	) -> io::Result<JoinHandle<T>>
	where
		F1: 'static + FnOnce(M) -> F2 + Send,
		F2: 'static + Future<Output = T>,
		T: 'static + Send,
		M: 'static + MessageSend,
	{
		self.spawn_with_message_internal(f, message)
	}

	fn spawn_scoped_async<'scope, #[allow(single_use_lifetimes)] 'env, F1, F2, T>(
		self,
		scope: &'scope Scope<'scope, 'env>,
		#[allow(clippy::min_ident_chars)] f: F1,
	) -> io::Result<ScopedJoinHandle<'scope, T>>
	where
		F1: 'scope + FnOnce() -> F2 + Send,
		F2: 'scope + Future<Output = T>,
		T: 'scope + Send,
	{
		self.spawn_scoped_async_internal(scope, f)
	}

	#[cfg(any(feature = "message", docsrs))]
	fn spawn_scoped_with_message<'scope, #[allow(single_use_lifetimes)] 'env, F1, F2, T, M>(
		self,
		scope: &'scope Scope<'scope, 'env>,
		#[allow(clippy::min_ident_chars)] f: F1,
		message: M,
	) -> io::Result<ScopedJoinHandle<'scope, T>>
	where
		F1: 'scope + FnOnce(M) -> F2 + Send,
		F2: 'scope + Future<Output = T>,
		T: 'scope + Send,
		M: 'scope + MessageSend,
	{
		self.spawn_scoped_with_message_internal(scope, f, message)
	}
}

/// Web-specific extension for [`web_thread::Scope`](crate::Scope).
pub trait ScopeExt<'scope> {
	/// Async version of [`Scope::spawn()`].
	///
	/// # Notes
	///
	/// Commonly a long-running thread is used by sending messages or tasks to
	/// it and blocking it when there is no work. Unfortunately this is often
	/// undesirable on the Web platform as it prevents yielding to the event
	/// loop.
	///
	/// Therefor being able to `await` the next task instead of blocking the
	/// thread is essential to build long-running threads on the Web platform.
	///
	/// # Panics
	///
	/// If the main thread does not support spawning threads, see
	/// [`has_spawn_support()`].
	///
	/// # Example
	///
	/// ```
	/// # #[cfg(all(target_feature = "atomics", not(unsupported_spawn)))]
	/// # wasm_bindgen_test::wasm_bindgen_test_configure!(run_in_browser);
	/// # #[cfg_attr(all(target_feature = "atomics", not(unsupported_spawn)), wasm_bindgen_test::wasm_bindgen_test)]
	/// # async fn test() {
	/// use web_thread::web::{self, ScopeExt};
	///
	/// let (sender, receiver) = async_channel::unbounded::<usize>();
	///
	/// # let handle =
	/// web::scope_async(move |scope| async move {
	/// 	scope.spawn_async(move || async move {
	/// 		while let Ok(message) = receiver.recv().await {
	/// 			web_sys::console::log_1(&message.into());
	/// 		}
	/// 	});
	/// });
	///
	/// for message in 0..10 {
	/// 	sender.try_send(message).unwrap();
	/// }
	///
	/// # drop(sender);
	/// # handle.await;
	/// # }
	/// # #[cfg(not(all(target_feature = "atomics", not(unsupported_spawn))))]
	/// # let _ = test();
	/// ```
	fn spawn_async<F1, F2, T>(&'scope self, f: F1) -> ScopedJoinHandle<'scope, T>
	where
		F1: 'scope + FnOnce() -> F2 + Send,
		F2: 'scope + Future<Output = T>,
		T: 'scope + Send;

	/// [`ScopeExt::spawn_async()`] with [message](MessageSend).
	///
	/// For a more complete documentation see [`ScopeExt::spawn_async()`] and
	/// [`spawn_with_message()`].
	///
	/// # Panics
	///
	/// - If the main thread does not support spawning threads, see
	///   [`has_spawn_support()`].
	/// - If `message` was unable to be cloned.
	#[cfg(any(feature = "message", docsrs))]
	fn spawn_with_message<F1, F2, T, M>(
		&'scope self,
		f: F1,
		message: M,
	) -> ScopedJoinHandle<'scope, T>
	where
		F1: 'scope + FnOnce(M) -> F2 + Send,
		F2: 'scope + Future<Output = T>,
		T: 'scope + Send,
		M: 'scope + MessageSend;
}

impl<'scope> ScopeExt<'scope> for Scope<'scope, '_> {
	fn spawn_async<F1, F2, T>(
		&'scope self,
		#[allow(clippy::min_ident_chars)] f: F1,
	) -> ScopedJoinHandle<'scope, T>
	where
		F1: 'scope + FnOnce() -> F2 + Send,
		F2: 'scope + Future<Output = T>,
		T: 'scope + Send,
	{
		self.spawn_async_internal(f)
	}

	#[cfg(any(feature = "message", docsrs))]
	fn spawn_with_message<F1, F2, T, M>(
		&'scope self,
		#[allow(clippy::min_ident_chars)] f: F1,
		message: M,
	) -> ScopedJoinHandle<'scope, T>
	where
		F1: 'scope + FnOnce(M) -> F2 + Send,
		F2: 'scope + Future<Output = T>,
		T: 'scope + Send,
		M: 'scope + MessageSend,
	{
		self.spawn_with_message_internal(f, message)
	}
}

/// Async version of [`spawn()`](std::thread::spawn).
///
/// # Notes
///
/// Commonly a long-running thread is used by sending messages or tasks to
/// it and blocking it when there is no work. Unfortunately this is often
/// undesirable on the Web platform as it prevents yielding to the event
/// loop.
///
/// Therefor being able to `await` the next task instead of blocking the
/// thread is essential to build long-running threads on the Web platform.
///
/// # Panics
///
/// If the main thread does not support spawning threads, see
/// [`has_spawn_support()`].
///
/// # Example
///
/// ```
/// # #[cfg(all(target_feature = "atomics", not(unsupported_spawn)))]
/// # wasm_bindgen_test::wasm_bindgen_test_configure!(run_in_browser);
/// # #[cfg_attr(all(target_feature = "atomics", not(unsupported_spawn)), wasm_bindgen_test::wasm_bindgen_test)]
/// # async fn test() {
/// # use web_thread::web::JoinHandleExt;
/// #
/// let (sender, receiver) = async_channel::unbounded::<usize>();
///
/// # let mut handle =
/// web_thread::web::spawn_async(move || async move {
/// 	while let Ok(message) = receiver.recv().await {
/// 		web_sys::console::log_1(&message.into());
/// 	}
/// });
///
/// for message in 0..10 {
/// 	sender.try_send(message).unwrap();
/// }
///
/// # drop(sender);
/// # handle.join_async().await.unwrap();
/// # }
/// # #[cfg(not(all(target_feature = "atomics", not(unsupported_spawn))))]
/// # let _ = test();
/// ```
pub fn spawn_async<F1, F2, T>(#[allow(clippy::min_ident_chars)] f: F1) -> JoinHandle<T>
where
	F1: 'static + FnOnce() -> F2 + Send,
	F2: 'static + Future<Output = T>,
	T: 'static + Send,
{
	Builder::new()
		.spawn_async(f)
		.expect("failed to spawn thread")
}

/// [`spawn_async()`] with [message](MessageSend).
///
/// For a more complete documentation see [`spawn_async()`].
///
/// # Panics
///
/// - If the main thread does not support spawning threads, see
///   [`has_spawn_support()`].
/// - If `message` was unable to be cloned.
///
/// # Example
///
/// ```
/// # #[cfg(all(target_feature = "atomics", not(unsupported_spawn)))]
/// # wasm_bindgen_test::wasm_bindgen_test_configure!(run_in_browser);
/// # #[cfg_attr(all(target_feature = "atomics", not(unsupported_spawn)), wasm_bindgen_test::wasm_bindgen_test)]
/// # async fn test() {
/// # use wasm_bindgen::JsCast;
/// use web_sys::{HtmlCanvasElement, OffscreenCanvas};
/// use web_thread::web::{self, JoinHandleExt};
/// use web_thread::web::message::TransferableWrapper;
///
/// # let canvas = web_sys::window().unwrap().document().unwrap().create_element("canvas").unwrap().unchecked_into();
/// let canvas: HtmlCanvasElement = canvas;
/// let message = TransferableWrapper(canvas.transfer_control_to_offscreen().unwrap());
/// web::spawn_with_message(
/// 	|message| async move {
/// 		let canvas: OffscreenCanvas = message.0;
/// 		// Do work.
/// #       let _ = canvas;
/// 	},
/// 	message,
/// )
/// .join_async()
/// .await
/// .unwrap();
/// # }
/// # #[cfg(not(all(target_feature = "atomics", not(unsupported_spawn))))]
/// # let _ = test();
/// ```
#[cfg(any(feature = "message", docsrs))]
pub fn spawn_with_message<F1, F2, T, M>(
	#[allow(clippy::min_ident_chars)] f: F1,
	message: M,
) -> JoinHandle<T>
where
	F1: 'static + FnOnce(M) -> F2 + Send,
	F2: 'static + Future<Output = T>,
	T: 'static + Send,
	M: 'static + MessageSend,
{
	Builder::new()
		.spawn_with_message(f, message)
		.expect("failed to spawn thread")
}

/// Async version of [`yield_now()`](std::thread::yield_now). This yields
/// execution to the [event loop].
///
/// # Notes
///
/// This is no-op in worklets.
///
/// # Example
///
/// ```
/// # wasm_bindgen_test::wasm_bindgen_test_configure!(run_in_browser);
/// # #[wasm_bindgen_test::wasm_bindgen_test]
/// # async fn test() {
/// use web_thread::web::{self, YieldTime};
///
/// # fn long_running_task() -> bool { false }
/// while long_running_task() {
/// 	web::yield_now_async(YieldTime::default()).await
/// }
/// # }
/// ```
///
/// [event loop]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Event_loop
pub fn yield_now_async(time: YieldTime) -> YieldNowFuture {
	YieldNowFuture(thread::YieldNowFuture::new(time))
}

/// How long [`yield_now_async()`] should yield execution to the event loop. See
/// [`yield_now_async()`] for more information.
#[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub enum YieldTime {
	/// Shortest execution yield to the event loop. Translates to
	/// [`TaskPriority."user-blocking"`].
	///
	/// # Notes
	///
	/// Will fall back to [`MessagePort.postMessage()`] when [`Scheduler`] is
	/// not supported, which is at least as short as
	/// [`UserVisible`](Self::UserVisible).
	///
	/// [`MessagePort.postMessage()`]: https://developer.mozilla.org/en-US/docs/Web/API/MessagePort/postMessage
	/// [`Scheduler`]: https://developer.mozilla.org/en-US/docs/Web/API/Scheduler
	/// [`TaskPriority."user-blocking"`]: https://developer.mozilla.org/en-US/docs/Web/API/Prioritized_Task_Scheduling_API#user-blocking
	UserBlocking,
	/// Default. Translates to [`TaskPriority."user-visible"`].
	///
	/// # Notes
	///
	/// Will fall back to [`MessagePort.postMessage()`] when [`Scheduler`] is
	/// not supported, which is at least as short as
	/// [`UserVisible`](Self::UserVisible).
	///
	/// [`MessagePort.postMessage()`]: https://developer.mozilla.org/en-US/docs/Web/API/MessagePort/postMessage
	/// [`Scheduler`]: https://developer.mozilla.org/en-US/docs/Web/API/Scheduler
	/// [`TaskPriority."user-visible"`]: https://developer.mozilla.org/en-US/docs/Web/API/Prioritized_Task_Scheduling_API#user-visible
	#[default]
	UserVisible,
	/// Translates to [`TaskPriority."background"`].
	///
	/// # Notes
	///
	/// Will fall back to [`MessagePort.postMessage()`] when [`Scheduler`] is
	/// not supported, which is at least as short as
	/// [`UserVisible`](Self::UserVisible).
	///
	/// [`MessagePort.postMessage()`]: https://developer.mozilla.org/en-US/docs/Web/API/MessagePort/postMessage
	/// [`Scheduler`]: https://developer.mozilla.org/en-US/docs/Web/API/Scheduler
	/// [`TaskPriority."background"`]: https://developer.mozilla.org/en-US/docs/Web/API/Prioritized_Task_Scheduling_API#background
	Background,
	/// Longest execution yield to the event loop. Uses
	/// [`Window.requestIdleCallback()`].
	///
	/// # Notes
	///
	/// Will fall back to [`MessagePort.postMessage()`] when
	/// [`Window.requestIdleCallback()`] is not supported, which is at least as
	/// short as [`UserVisible`](Self::UserVisible).
	///
	/// [`MessagePort.postMessage()`]: https://developer.mozilla.org/en-US/docs/Web/API/MessagePort/postMessage
	/// [`Window.requestIdleCallback()`]: https://developer.mozilla.org/en-US/docs/Web/API/Window/requestIdleCallback
	Idle,
}

/// Waits for yielding to the event loop to happen. See [`yield_now_async()`].
#[derive(Debug)]
#[must_use = "does nothing if not polled"]
pub struct YieldNowFuture(thread::YieldNowFuture);

impl Future for YieldNowFuture {
	type Output = ();

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

impl RefUnwindSafe for YieldNowFuture {}