1use core::{
7 future::Future,
8 pin::Pin,
9 task::{Context, Poll},
10};
11
12use futures::{channel::oneshot, FutureExt};
13
14pub struct InfallibleOneshotReceiver<T>(oneshot::Receiver<T>);
19
20impl<T> From<oneshot::Receiver<T>> for InfallibleOneshotReceiver<T> {
21 fn from(value: oneshot::Receiver<T>) -> Self {
22 Self(value)
23 }
24}
25
26impl<T> Future for InfallibleOneshotReceiver<T> {
27 type Output = T;
28
29 #[inline]
30 fn poll(mut self: Pin<&mut Self>, ctx: &mut Context<'_>) -> Poll<Self::Output> {
31 self.0
32 .poll_unpin(ctx)
33 .map(|res| res.expect("Oneshot must not be cancelled before response!"))
34 }
35}
36
37pub async fn rayon_spawn_async<F, R>(f: F) -> R
40where
41 F: FnOnce() -> R + Send + 'static,
42 R: Send + 'static,
43{
44 let (tx, rx) = oneshot::channel();
45 rayon::spawn(move || {
46 drop(tx.send(f()));
47 });
48 rx.await.expect("The sender must not be dropped")
49}
50
51#[cfg(test)]
53mod test {
54 use std::{
55 sync::{Arc, Barrier},
56 thread,
57 time::Duration,
58 };
59
60 use super::*;
61
62 #[tokio::test]
63 async fn infallible_oneshot_receiver() {
65 let (tx, rx) = oneshot::channel::<String>();
66 let msg = "hello world!".to_string();
67
68 tx.send(msg.clone()).unwrap();
69
70 let oneshot = InfallibleOneshotReceiver::from(rx);
71 assert_eq!(oneshot.await, msg);
72 }
73
74 #[test]
75 fn rayon_spawn_async_does_not_block() {
76 rayon::ThreadPoolBuilder::new()
78 .num_threads(2)
79 .build_global()
80 .unwrap();
81
82 let barrier = Arc::new(Barrier::new(2));
85 let task = |barrier: &Barrier| barrier.wait();
86
87 let b_2 = Arc::clone(&barrier);
88
89 let (tx, rx) = std::sync::mpsc::channel();
90
91 thread::spawn(move || {
92 let runtime = tokio::runtime::Builder::new_current_thread()
93 .enable_all()
94 .build()
95 .unwrap();
96
97 runtime.block_on(async {
98 tokio::join!(
99 rayon_spawn_async(move || task(&barrier)),
102 rayon_spawn_async(move || task(&b_2)),
103 )
104 });
105
106 tx.send(()).unwrap();
108 });
109
110 rx.recv_timeout(Duration::from_secs(2))
111 .expect("rayon_spawn_async blocked");
112 }
113}