1#![allow(clippy::missing_panics_doc)]
2
3use std::{
15 pin::Pin,
16 task::{Context, Poll},
17};
18
19use futures::{
20 channel::{mpsc, oneshot},
21 future::FutureExt as _,
22 task::LocalFutureObj,
23};
24
25#[derive(Debug, thiserror::Error)]
27#[non_exhaustive]
28pub enum Error {
29 #[error("thread killed before task completed")]
30 Killed(#[from] oneshot::Canceled),
31}
32
33pub type Result<T, E = Error> = std::result::Result<T, E>;
35
36pub struct Thread {
38 sender: mpsc::UnboundedSender<Request>,
39}
40
41type Request = Box<dyn FnOnce() -> LocalFutureObj<'static, ()> + Send>;
42
43pub struct Task<T> {
46 receiver: oneshot::Receiver<T>,
47}
48
49pub struct SendTask<T>(Task<T>);
52
53impl<T: Send> Future for SendTask<T> {
54 type Output = Result<T>;
55
56 fn poll(mut self: Pin<&mut Self>, context: &mut Context<'_>) -> Poll<Self::Output> {
57 self.0.poll_unpin(context)
58 }
59}
60
61impl<T> Future for Task<T> {
62 type Output = Result<T>;
63
64 fn poll(mut self: Pin<&mut Self>, context: &mut Context<'_>) -> Poll<Self::Output> {
65 self.receiver
66 .poll_unpin(context)
67 .map(|ready| ready.map_err(Into::into))
68 }
69}
70
71impl Thread {
72 pub fn new() -> Self {
74 let (sender, mut receiver) = mpsc::unbounded::<Request>();
75 std::thread::spawn(|| {
76 use futures::{StreamExt as _, executor::LocalPool, task::LocalSpawn as _};
77 let mut executor = LocalPool::new();
78 let spawner = executor.spawner();
79 executor.run_until(async move {
80 while let Some(task) = receiver.next().await {
81 spawner
82 .spawn_local_obj(task())
83 .expect("executor should exist until destroyed");
84 }
85 });
86 });
87 Self { sender }
88 }
89
90 pub fn run<Context: Post, F: Future<Output: Post> + 'static>(
95 &self,
96 context: Context,
97 code: impl FnOnce(Context) -> F + Send + 'static,
98 ) -> Task<F::Output> {
99 let (sender, receiver) = oneshot::channel::<F::Output>();
100 self.sender
101 .unbounded_send(Box::new(move || {
102 Box::new(async move {
103 let _ = sender.send(code(context).await);
104 })
105 .into()
106 }))
107 .unwrap_or_else(|_| panic!("worker shouldn't die unless dropped"));
108 Task { receiver }
109 }
110
111 pub fn run_send<Context: Post, F: Future<Output: Send> + 'static>(
116 &self,
117 context: Context,
118 code: impl FnOnce(Context) -> F + Send + 'static,
119 ) -> SendTask<F::Output> {
120 SendTask(self.run(context, code))
121 }
122}
123
124pub trait Post: Send + 'static {}
129impl<T: Send + 'static> Post for T {}
130
131#[test]
132fn basic_functionality() {
133 assert_eq!(
134 8u8,
135 futures::executor::LocalPool::new()
136 .run_until(
137 Thread::new()
138 .unwrap()
139 .run(3u8, |three| async move { three + 5 })
140 )
141 .unwrap(),
142 );
143}