1mod chain;
2mod reader_stream;
3mod join;
4mod waker;
5
6#[cfg(unix)]
7pub mod unix;
8
9pub use chain::Chain;
10pub use reader_stream::ReaderStream;
11pub use join::join;
12pub use waker::RuntimeWaker;
13
14#[track_caller]
15pub fn spawn_inspect<E, F, Fut>(or: F, future: Fut)
16 where F: FnOnce(&E) + Send + Sync + 'static,
17 E: Send + Sync + 'static,
18 Fut: std::future::Future<Output = Result<(), E>> + Send + 'static,
19{
20 use futures::TryFutureExt;
21 tokio::spawn(future.inspect_err(or));
22}
23
24use std::{fmt, io};
25use std::pin::{pin, Pin};
26use std::future::Future;
27use std::task::{ready, Context, Poll};
28use either::Either;
29use futures::future;
30use tokio::runtime::Handle;
31
32pub trait FutureExt: Future + Sized {
33 async fn race<B: Future>(self, other: B) -> Either<Self::Output, B::Output> {
35 match future::select(pin!(self), pin!(other)).await {
36 future::Either::Left((v, _)) => Either::Left(v),
37 future::Either::Right((v, _)) => Either::Right(v),
38 }
39 }
40
41 async fn race_io<T, K: Future>(self, trigger: K) -> io::Result<T>
42 where Self: Future<Output = io::Result<T>>
43 {
44 match future::select(pin!(self), pin!(trigger)).await {
45 future::Either::Left((v, _)) => v,
46 future::Either::Right((_, _)) => Err(io::Error::other("i/o terminated")),
47 }
48 }
49}
50
51impl<F: Future + Sized> FutureExt for F { }
52
53pub struct Detach<F: Future + Send + 'static>(Option<Pin<Box<F>>>);
56
57impl<F: Future + Send + 'static> Detach<F> {
58 pub fn new(future: F) -> Self {
59 Detach(Some(Box::pin(future)))
60 }
61}
62
63impl<F: Future + Send + 'static> Future for Detach<F> {
64 type Output = F::Output;
65
66 fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
67 let future = self.0.as_mut().expect("`Detach` polled after completion");
68 let output = ready!(future.as_mut().poll(cx));
69 self.0 = None;
70 Poll::Ready(output)
71 }
72}
73
74impl<F: Future + Send + 'static> Drop for Detach<F> {
75 fn drop(&mut self) {
76 if let (Some(future), Ok(runtime)) = (self.0.take(), Handle::try_current()) {
77 runtime.spawn(async move { future.await; });
78 }
79 }
80}
81
82pub struct Formatter<F: Fn(&mut fmt::Formatter<'_>) -> fmt::Result>(pub F);
83
84impl<F: Fn(&mut fmt::Formatter<'_>) -> fmt::Result> fmt::Debug for Formatter<F> {
85 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
86 (self.0)(f)
87 }
88}
89
90impl<F: Fn(&mut fmt::Formatter<'_>) -> fmt::Result> fmt::Display for Formatter<F> {
91 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
92 (self.0)(f)
93 }
94}
95
96#[doc(hidden)]
97#[macro_export]
98macro_rules! for_both {
99 ($value:expr, $pattern:pat => $result:expr) => {
100 match $value {
101 tokio_util::either::Either::Left($pattern) => $result,
102 tokio_util::either::Either::Right($pattern) => $result,
103 }
104 };
105}
106
107pub use for_both;