1#![doc = include_str!("../README.md")]
2#![cfg_attr(not(feature = "std"), no_std)]
3
4extern crate alloc;
5
6mod embassy;
7mod spawner;
8
9#[doc(hidden)]
10pub mod __private {
11 pub use alloc::boxed::Box;
12}
13
14use alloc::string::String;
15use core::fmt;
16use core::future::Future;
17
18use futures_channel::oneshot;
19use futures_util::future::{AbortHandle, Abortable};
20
21#[cfg(feature = "smol")]
22pub use spawner::Smol;
23#[cfg(feature = "tokio")]
24pub use spawner::Tokio;
25pub use spawner::{LocalSpawner, Spawner};
26
27type Outcome<T> = Result<(T, Option<String>), String>;
30
31#[derive(Debug, Clone, Copy, PartialEq, Eq)]
33pub enum State {
34 NotStarted,
36 Pending,
38 Completed,
40 TaskPanicked,
44 CallbackPanicked,
49 Cancelled,
51}
52
53#[derive(Debug, Clone, PartialEq, Eq)]
55pub enum Error {
56 NotStarted,
58 Panicked(String),
60 Cancelled,
62}
63
64impl fmt::Display for Error {
65 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
66 match self {
67 Error::NotStarted => f.write_str("no task has been started"),
68 Error::Panicked(msg) => write!(f, "task panicked: {msg}"),
69 Error::Cancelled => f.write_str("task was cancelled"),
70 }
71 }
72}
73
74#[cfg(feature = "std")]
75impl std::error::Error for Error {}
76
77#[derive(Debug)]
78enum Inner<T> {
79 NotStarted,
80 Running {
81 receiver: oneshot::Receiver<Outcome<T>>,
82 abort: AbortHandle,
83 },
84 Done {
85 value: T,
86 callback_panic: Option<String>,
87 },
88 Panicked(String),
89 Cancelled,
90}
91
92#[derive(Debug)]
115pub struct Deferred<T> {
116 inner: Inner<T>,
117}
118
119impl<T> Deferred<T> {
120 pub fn new() -> Self {
122 Self {
123 inner: Inner::NotStarted,
124 }
125 }
126
127 pub fn start_on<S, F>(spawner: &S, future: F) -> Self
140 where
141 S: Spawner,
142 F: Future<Output = T> + Send + 'static,
143 T: Send + 'static,
144 {
145 let mut deferred = Self::new();
146 deferred.begin_on(spawner, future);
147 deferred
148 }
149
150 pub fn start_with_callback_on<S, F, C>(spawner: &S, future: F, callback: C) -> Self
155 where
156 S: Spawner,
157 F: Future<Output = T> + Send + 'static,
158 C: FnOnce(&T) + Send + 'static,
159 T: Send + 'static,
160 {
161 let mut deferred = Self::new();
162 deferred.begin_with_callback_on(spawner, future, callback);
163 deferred
164 }
165
166 pub fn begin_on<S, F>(&mut self, spawner: &S, future: F) -> bool
171 where
172 S: Spawner,
173 F: Future<Output = T> + Send + 'static,
174 T: Send + 'static,
175 {
176 self.begin_with_callback_on(spawner, future, |_: &T| {})
177 }
178
179 pub fn begin_with_callback_on<S, F, C>(&mut self, spawner: &S, future: F, callback: C) -> bool
184 where
185 S: Spawner,
186 F: Future<Output = T> + Send + 'static,
187 C: FnOnce(&T) + Send + 'static,
188 T: Send + 'static,
189 {
190 if !self.is_not_started() {
191 return false;
192 }
193 let (task, running) = task(future, callback);
194 spawner.spawn(task);
195 self.inner = running;
196 true
197 }
198
199 pub fn start_local_on<S, F>(spawner: &S, future: F) -> Self
201 where
202 S: LocalSpawner,
203 F: Future<Output = T> + 'static,
204 T: 'static,
205 {
206 let mut deferred = Self::new();
207 deferred.begin_local_on(spawner, future);
208 deferred
209 }
210
211 pub fn start_with_callback_local_on<S, F, C>(spawner: &S, future: F, callback: C) -> Self
214 where
215 S: LocalSpawner,
216 F: Future<Output = T> + 'static,
217 C: FnOnce(&T) + 'static,
218 T: 'static,
219 {
220 let mut deferred = Self::new();
221 deferred.begin_with_callback_local_on(spawner, future, callback);
222 deferred
223 }
224
225 pub fn begin_local_on<S, F>(&mut self, spawner: &S, future: F) -> bool
227 where
228 S: LocalSpawner,
229 F: Future<Output = T> + 'static,
230 T: 'static,
231 {
232 self.begin_with_callback_local_on(spawner, future, |_: &T| {})
233 }
234
235 pub fn begin_with_callback_local_on<S, F, C>(
238 &mut self,
239 spawner: &S,
240 future: F,
241 callback: C,
242 ) -> bool
243 where
244 S: LocalSpawner,
245 F: Future<Output = T> + 'static,
246 C: FnOnce(&T) + 'static,
247 T: 'static,
248 {
249 if !self.is_not_started() {
250 return false;
251 }
252 let (task, running) = task(future, callback);
253 spawner.spawn_local(task);
254 self.inner = running;
255 true
256 }
257
258 fn poll_task(&mut self) {
260 let Inner::Running { receiver, .. } = &mut self.inner else {
261 return;
262 };
263 match receiver.try_recv() {
264 Ok(None) => {}
265 Ok(Some(outcome)) => self.inner = Inner::finished(Some(outcome)),
266 Err(oneshot::Canceled) => self.inner = Inner::finished(None),
267 }
268 }
269
270 pub async fn join(&mut self) -> Result<&T, Error> {
285 if let Inner::Running { receiver, .. } = &mut self.inner {
286 let outcome = receiver.await.ok();
287 self.inner = Inner::finished(outcome);
288 }
289 match &self.inner {
290 Inner::Done { value, .. } => Ok(value),
291 Inner::Panicked(msg) => Err(Error::Panicked(msg.clone())),
292 Inner::Cancelled => Err(Error::Cancelled),
293 Inner::NotStarted => Err(Error::NotStarted),
294 Inner::Running { .. } => unreachable!("the task was awaited above"),
295 }
296 }
297
298 pub fn state(&mut self) -> State {
300 self.poll_task();
301 match &self.inner {
302 Inner::NotStarted => State::NotStarted,
303 Inner::Running { .. } => State::Pending,
304 Inner::Done {
305 callback_panic: None,
306 ..
307 } => State::Completed,
308 Inner::Done {
309 callback_panic: Some(_),
310 ..
311 } => State::CallbackPanicked,
312 Inner::Panicked(_) => State::TaskPanicked,
313 Inner::Cancelled => State::Cancelled,
314 }
315 }
316
317 pub fn panic_message(&mut self) -> Option<&str> {
319 self.poll_task();
320 match &self.inner {
321 Inner::Panicked(msg)
322 | Inner::Done {
323 callback_panic: Some(msg),
324 ..
325 } => Some(msg),
326 _ => None,
327 }
328 }
329
330 pub fn try_get(&mut self) -> Option<&T> {
332 self.poll_task();
333 match &self.inner {
334 Inner::Done { value, .. } => Some(value),
335 _ => None,
336 }
337 }
338
339 pub fn take(&mut self) -> Option<T> {
354 self.poll_task();
355 if !matches!(self.inner, Inner::Done { .. }) {
356 return None;
357 }
358 match core::mem::replace(&mut self.inner, Inner::NotStarted) {
359 Inner::Done { value, .. } => Some(value),
360 _ => unreachable!("checked above"),
361 }
362 }
363
364 pub fn cancel(&mut self) -> bool {
379 self.poll_task();
380 let Inner::Running { abort, .. } = &self.inner else {
381 return false;
382 };
383 abort.abort();
384 self.inner = Inner::NotStarted;
385 true
386 }
387
388 pub fn is_ready(&mut self) -> bool {
390 self.try_get().is_some()
391 }
392
393 pub fn is_complete(&mut self) -> bool {
395 self.state() == State::Completed
396 }
397
398 pub fn is_pending(&mut self) -> bool {
400 self.state() == State::Pending
401 }
402
403 pub fn is_not_started(&mut self) -> bool {
405 self.state() == State::NotStarted
406 }
407
408 pub fn has_task_panicked(&mut self) -> bool {
410 self.state() == State::TaskPanicked
411 }
412}
413
414#[cfg(feature = "tokio")]
415impl<T> Deferred<T> {
416 pub fn start<F>(future: F) -> Self
423 where
424 F: Future<Output = T> + Send + 'static,
425 T: Send + 'static,
426 {
427 Self::start_on(&Tokio, future)
428 }
429
430 pub fn start_with_callback<F, C>(future: F, callback: C) -> Self
445 where
446 F: Future<Output = T> + Send + 'static,
447 C: FnOnce(&T) + Send + 'static,
448 T: Send + 'static,
449 {
450 Self::start_with_callback_on(&Tokio, future, callback)
451 }
452
453 pub fn begin<F>(&mut self, future: F) -> bool
472 where
473 F: Future<Output = T> + Send + 'static,
474 T: Send + 'static,
475 {
476 self.begin_on(&Tokio, future)
477 }
478
479 pub fn begin_with_callback<F, C>(&mut self, future: F, callback: C) -> bool
483 where
484 F: Future<Output = T> + Send + 'static,
485 C: FnOnce(&T) + Send + 'static,
486 T: Send + 'static,
487 {
488 self.begin_with_callback_on(&Tokio, future, callback)
489 }
490}
491
492impl<T> Default for Deferred<T> {
493 fn default() -> Self {
495 Self::new()
496 }
497}
498
499impl<T> Inner<T> {
500 fn finished(outcome: Option<Outcome<T>>) -> Self {
502 match outcome {
503 Some(Ok((value, callback_panic))) => Inner::Done {
504 value,
505 callback_panic,
506 },
507 Some(Err(msg)) => Inner::Panicked(msg),
508 None => Inner::Cancelled,
509 }
510 }
511}
512
513fn task<T, F, C>(future: F, callback: C) -> (impl Future<Output = ()>, Inner<T>)
517where
518 F: Future<Output = T> + 'static,
519 C: FnOnce(&T) + 'static,
520 T: 'static,
521{
522 let (sender, receiver) = oneshot::channel();
523 let (abort, abort_registration) = AbortHandle::new_pair();
524 let task = Abortable::new(
525 async move {
526 let outcome = match catch_unwind(future).await {
527 Ok(value) => {
528 let callback_panic = call_catching_panic(callback, &value).err();
530 Ok((value, callback_panic))
531 }
532 Err(msg) => Err(msg),
533 };
534 let _ = sender.send(outcome);
536 },
537 abort_registration,
538 );
539 let task = async move {
540 let _ = task.await;
541 };
542 (task, Inner::Running { receiver, abort })
543}
544
545#[cfg(feature = "std")]
547async fn catch_unwind<F: Future>(future: F) -> Result<F::Output, String> {
548 use futures_util::FutureExt;
549 std::panic::AssertUnwindSafe(future)
550 .catch_unwind()
551 .await
552 .map_err(|payload| panic_message(&*payload))
553}
554
555#[cfg(not(feature = "std"))]
557async fn catch_unwind<F: Future>(future: F) -> Result<F::Output, String> {
558 Ok(future.await)
559}
560
561#[cfg(feature = "std")]
563fn call_catching_panic<T, C: FnOnce(&T)>(callback: C, value: &T) -> Result<(), String> {
564 std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| callback(value)))
565 .map_err(|payload| panic_message(&*payload))
566}
567
568#[cfg(not(feature = "std"))]
570fn call_catching_panic<T, C: FnOnce(&T)>(callback: C, value: &T) -> Result<(), String> {
571 callback(value);
572 Ok(())
573}
574
575#[cfg(feature = "std")]
577fn panic_message(payload: &(dyn std::any::Any + Send)) -> String {
578 if let Some(s) = payload.downcast_ref::<&str>() {
579 s.to_string()
580 } else if let Some(s) = payload.downcast_ref::<String>() {
581 s.clone()
582 } else {
583 "unknown panic payload".to_string()
584 }
585}