1//! `async` related
2//!
3//! `#[no_std]` compatible.
45//---------------------------------------------------------------------------------------------------- Use
6use core::{
7 future::Future,
8 pin::Pin,
9 task::{Context, Poll},
10};
1112use futures::{channel::oneshot, FutureExt};
1314//---------------------------------------------------------------------------------------------------- InfallibleOneshotReceiver
15/// A oneshot receiver channel that doesn't return an Error.
16///
17/// This requires the sender to always return a response.
18pub struct InfallibleOneshotReceiver<T>(oneshot::Receiver<T>);
1920impl<T> From<oneshot::Receiver<T>> for InfallibleOneshotReceiver<T> {
21fn from(value: oneshot::Receiver<T>) -> Self {
22Self(value)
23 }
24}
2526impl<T> Future for InfallibleOneshotReceiver<T> {
27type Output = T;
2829#[inline]
30fn poll(mut self: Pin<&mut Self>, ctx: &mut Context<'_>) -> Poll<Self::Output> {
31self.0
32.poll_unpin(ctx)
33 .map(|res| res.expect("Oneshot must not be cancelled before response!"))
34 }
35}
3637//---------------------------------------------------------------------------------------------------- rayon_spawn_async
38/// Spawns a task for the rayon thread pool and awaits the result without blocking the async runtime.
39pub async fn rayon_spawn_async<F, R>(f: F) -> R
40where
41F: FnOnce() -> R + Send + 'static,
42 R: Send + 'static,
43{
44let (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}
5051//---------------------------------------------------------------------------------------------------- Tests
52#[cfg(test)]
53mod test {
54use std::{
55 sync::{Arc, Barrier},
56 thread,
57 time::Duration,
58 };
5960use super::*;
6162#[tokio::test]
63// Assert that basic channel operations work.
64async fn infallible_oneshot_receiver() {
65let (tx, rx) = oneshot::channel::<String>();
66let msg = "hello world!".to_string();
6768 tx.send(msg.clone()).unwrap();
6970let oneshot = InfallibleOneshotReceiver::from(rx);
71assert_eq!(oneshot.await, msg);
72 }
7374#[test]
75fn rayon_spawn_async_does_not_block() {
76// There must be more than 1 rayon thread for this to work.
77rayon::ThreadPoolBuilder::new()
78 .num_threads(2)
79 .build_global()
80 .unwrap();
8182// We use a barrier to make sure both tasks are executed together, we block the rayon thread
83 // until both rayon threads are blocked.
84let barrier = Arc::new(Barrier::new(2));
85let task = |barrier: &Barrier| barrier.wait();
8687let b_2 = Arc::clone(&barrier);
8889let (tx, rx) = std::sync::mpsc::channel();
9091 thread::spawn(move || {
92let runtime = tokio::runtime::Builder::new_current_thread()
93 .enable_all()
94 .build()
95 .unwrap();
9697 runtime.block_on(async {
98tokio::join!(
99// This polls them concurrently in the same task, so if the first one blocks the task then
100 // the second wont run and if the second does not run the first does not unblock.
101rayon_spawn_async(move || task(&barrier)),
102 rayon_spawn_async(move || task(&b_2)),
103 )
104 });
105106// if we managed to get here then rayon_spawn_async didn't block.
107tx.send(()).unwrap();
108 });
109110 rx.recv_timeout(Duration::from_secs(2))
111 .expect("rayon_spawn_async blocked");
112 }
113}