1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525
//! A very small, no-std compatible toolbox of async utilities. #![no_std] #![warn(missing_docs, missing_debug_implementations, rust_2018_idioms)] pub mod prelude; #[doc(no_inline)] pub use core::future::Future; #[doc(no_inline)] pub use core::pin::Pin; #[doc(no_inline)] pub use core::task::{Context, Poll, Waker}; use core::fmt; use core::marker::PhantomData; // ---------- futures using the poll api ----------- /// Creates a future from a function returning [`Poll`]. /// /// # Examples /// /// ``` /// use futures_lite::future::block_on; /// use futures_micro::poll_fn; /// use std::task::{Context, Poll}; /// /// # block_on(async { /// fn f(_ctx: &mut Context<'_>) -> Poll<i32> { /// Poll::Ready(7) /// } /// /// assert_eq!(poll_fn(f).await, 7); /// # }) /// ``` pub fn poll_fn<F, T>(inner: F) -> PollFn<F> where F: FnMut(&mut Context<'_>) -> Poll<T> { PollFn { inner } } /// Creates a future from a function returning [`Poll`] that has /// access to a provided state value. /// /// # Examples /// /// ``` /// use futures_lite::future::block_on; /// use futures_micro::poll_state; /// use std::task::{Context, Poll}; /// /// # block_on(async { /// fn f(state: &mut i32, _ctx: &mut Context<'_>) -> Poll<i32> { /// Poll::Ready(*state + 1) /// } /// /// assert_eq!(poll_state(7, f).await, 8); /// # }) /// ``` pub fn poll_state<F, S, T>(state: S, fun: F) -> PollState<F, S> where F: FnMut(&mut S, &mut Context<'_>) -> Poll<T> { PollState { state, fun } } /// Future for the [`poll_fn()`] function. #[must_use = "futures do nothing unless you `.await` or poll them"] pub struct PollFn<F> { inner: F } impl<F> fmt::Debug for PollFn<F> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("PollFn").finish() } } impl<F, T> Future for PollFn<F> where F: FnMut(&mut Context<'_>) -> Poll<T> { type Output = T; fn poll(self: Pin<&mut Self>, ctx: &mut Context<'_> ) -> Poll<T> { let this = unsafe { self.get_unchecked_mut() }; (this.inner)(ctx) } } /// Future for the [`poll_state()`] function. #[must_use = "futures do nothing unless you `.await` or poll them"] pub struct PollState<F, S> { fun: F, state: S, } impl<F, S> fmt::Debug for PollState<F, S> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("PollState").finish() } } impl<F, S, T> Future for PollState<F, S> where F: FnMut(&mut S, &mut Context<'_>) -> Poll<T> { type Output = T; fn poll(self: Pin<&mut Self>, ctx: &mut Context<'_>) -> Poll<T> { let this = unsafe { Pin::get_unchecked_mut(self) }; (this.fun)(&mut this.state, ctx) } } /// Returns the result of `left` or `right` future, preferring `left` if both are ready. #[derive(Debug)] #[must_use = "futures do nothing unless you `.await` or poll them"] pub struct Or<F1, F2> { future1: F1, future2: F2, } impl<F1, F2> Or<F1, F2> where F1: Future, F2: Future, { /// Returns the result of `left` or `right` future, preferring `left` if both are ready. /// /// # Examples /// /// ``` /// use futures_micro::prelude::{Or, pending, ready}; /// /// # futures_lite::future::block_on(async { /// assert_eq!(Or::new(ready(1), pending::<i32>()).await, 1); /// assert_eq!(Or::new(pending::<i32>(), ready(2)).await, 2); /// /// // The first future wins. /// assert_eq!(Or::new(ready(1), ready(2)).await, 1); /// # }) /// ``` pub fn new(future1: F1, future2: F2) -> Self { Or { future1, future2 } } } impl<T, F1, F2> Future for Or<F1, F2> where F1: Future<Output = T>, F2: Future<Output = T>, { type Output = T; fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { let this = unsafe { self.get_unchecked_mut() }; if let Poll::Ready(t) = unsafe { Pin::new_unchecked(&mut this.future1) }.poll(cx) { return Poll::Ready(t); } if let Poll::Ready(t) = unsafe { Pin::new_unchecked(&mut this.future2) }.poll(cx) { return Poll::Ready(t); } Poll::Pending } } /// Waits for two [`Future`]s to complete, returning both results. #[derive(Debug)] #[must_use = "futures do nothing unless you `.await` or poll them"] pub struct Zip<F1, F2> where F1: Future, F2: Future, { future1: F1, output1: Option<F1::Output>, future2: F2, output2: Option<F2::Output>, } impl<F1, F2> Zip<F1, F2> where F1: Future, F2: Future, { /// Zips two futures, waiting for both to complete. /// /// # Examples /// /// ``` /// use futures_micro::Zip; /// /// # futures_lite::future::block_on(async { /// let a = async { 1 }; /// let b = async { 2 }; /// /// assert_eq!(Zip::new(a, b).await, (1, 2)); /// # }) /// ``` pub fn new(future1: F1, future2: F2) -> Self { Zip { future1, future2, output1: None, output2: None, } } } impl<F1, F2> Future for Zip<F1, F2> where F1: Future, F2: Future, { type Output = (F1::Output, F2::Output); fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { let mut this = unsafe { self.get_unchecked_mut() }; if this.output1.is_none() { if let Poll::Ready(out) = unsafe { Pin::new_unchecked(&mut this.future1) }.poll(cx) { this.output1 = Some(out); } } if this.output2.is_none() { if let Poll::Ready(out) = unsafe { Pin::new_unchecked(&mut this.future2) }.poll(cx) { this.output2 = Some(out); } } if this.output1.is_some() && this.output2.is_some() { Poll::Ready((this.output1.take().unwrap(), this.output2.take().unwrap())) } else { Poll::Pending } } } /// Creates a future that is always pending. /// /// # Examples /// /// ```no_run /// use futures_micro::pending; /// /// # futures_lite::future::block_on(async { /// pending::<()>().await; /// unreachable!(); /// # }) /// ``` pub fn pending<T>() -> Pending<T> { Pending { _marker: PhantomData, } } /// Future for the [`pending()`] function. #[must_use = "futures do nothing unless you `.await` or poll them"] pub struct Pending<T> { _marker: PhantomData<T>, } impl<T> Unpin for Pending<T> {} impl<T> fmt::Debug for Pending<T> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("Pending").finish() } } impl<T> Future for Pending<T> { type Output = T; fn poll(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<T> { Poll::Pending } } /// A future that resolves to the provided value. #[derive(Debug)] #[must_use = "futures do nothing unless you `.await` or poll them"] pub struct Ready<T>(Option<T>); impl<T> Ready<T> { /// Creates a future that resolves to the provided value. /// /// # Examples /// /// ``` /// use futures_micro::Ready; /// /// # futures_lite::future::block_on(async { /// assert_eq!(Ready::new(7).await, 7); /// # }) /// ``` pub fn new(value: T) -> Self { Ready(Some(value)) } } impl<T> Unpin for Ready<T> {} impl<T> Future for Ready<T> { type Output = T; fn poll(mut self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<T> { Poll::Ready(self.0.take().expect("`Ready` polled after completion")) } } /// Get the [`Waker`] inside an async fn where you aren't supposed to /// have it. /// /// This is a low level primitive for implementing more complex /// patterns while avoiding the [`Poll`] API. /// /// # Examples /// /// ``` /// use futures_micro::{sleep, waker}; /// /// # futures_lite::future::block_on(async { /// let waker = waker().await; /// assert_eq!(async { waker.wake(); sleep().await; 1 }.await, 1) /// # }) /// ``` pub async fn waker() -> Waker { poll_fn(|ctx| Poll::Ready(ctx.waker().clone())).await } /// Goes to sleep until woken by its [`Waker`] being called. /// /// This is a low level primitive for implementing more complex /// patterns while avoiding the [`Poll`] API. /// /// # Examples /// /// ``` /// use futures_micro::{sleep, waker}; /// /// # futures_lite::future::block_on(async { /// let waker = waker().await; /// assert_eq!(async { waker.wake(); sleep().await; 1 }.await, 1) /// # }) /// ``` pub async fn sleep() { poll_state(false, |done, _| { if *done { Poll::Ready(()) } else { *done = true; Poll::Pending } }).await } /// Polls a future once. If it does not succeed, return it to try again /// /// # Examples /// /// ``` /// use futures_micro::*; /// /// # futures_lite::future::block_on(async { /// let f = poll_state(false, |done: &mut bool, ctx: &mut Context<'_>| { /// if *done { Poll::Ready(1) } else { *done = true; Poll::Pending } /// }); /// let f = next_poll(f).await.unwrap_err(); /// assert_eq!(f.await, 1); /// # }) /// ``` pub async fn next_poll<F: Future>(mut f: F) -> Result<F::Output, F> { { let mut pin = unsafe { Pin::new_unchecked(&mut f) }; poll_fn(|ctx| { match pin.as_mut().poll(ctx) { Poll::Ready(val) => Poll::Ready(Ok(val)), Poll::Pending => Poll::Ready(Err(())), } }).await }.map_err(|_| f) } /// Pushes itself to the back of the executor queue so some other /// tasks can do some work. pub async fn yield_once() { poll_state(false, |done, ctx| { if *done { Poll::Ready(()) } else { *done = true; ctx.waker().wake_by_ref(); Poll::Pending } }).await } // --------- MACROS --------- // Helper for `or!` #[doc(hidden)] #[macro_export] macro_rules! __internal_fold_with { ($func:path, $e:expr) => { $e }; ($func:path, $e:expr, $($es:expr),+) => { $func($e, $crate::__internal_fold_with!($func, $($es),+)) }; } /// Polls arbitrarily many futures, returning the first ready value. /// /// All futures must have the same output type. Left biased when more /// than one Future is ready at the same time. /// # Examples /// /// ``` /// use futures_micro::prelude::*; /// /// # futures_lite::future::block_on(async { /// assert_eq!(or!(ready(1), pending::<i32>()).await, 1); /// assert_eq!(or!(pending::<i32>(), ready(2)).await, 2); /// /// // The first ready future wins. /// assert_eq!(or!(ready(1), ready(2), ready(3)).await, 1); /// # }) #[macro_export] macro_rules! or { ($($es:expr),+$(,)?) => { $crate::__internal_fold_with!($crate::Or::new, $($es),+) }; } /// Pins a variable of type `T` on the stack and rebinds it as `Pin<&mut T>`. /// /// ``` /// use futures_micro::*; /// use std::fmt::Debug; /// use std::time::Instant; /// /// // Inspects each invocation of `Future::poll()`. /// async fn inspect<T: Debug>(f: impl Future<Output = T>) -> T { /// pin!(f); /// poll_fn(|cx| dbg!(f.as_mut().poll(cx))).await /// } /// /// # futures_lite::future::block_on(async { /// let f = async { 1 + 2 }; /// inspect(f).await; /// # }) /// ``` #[macro_export] macro_rules! pin { ($($x:ident),* $(,)?) => { $( let mut $x = $x; #[allow(unused_mut)] let mut $x = unsafe { core::pin::Pin::new_unchecked(&mut $x) }; )* } } /// Unwraps `Poll<T>` or returns [`Pending`][`Poll::Pending`]. /// /// # Examples /// /// ``` /// use futures_micro::*; /// /// // Polls two futures and sums their results. /// fn poll_sum( /// cx: &mut Context<'_>, /// mut a: impl Future<Output = i32> + Unpin, /// mut b: impl Future<Output = i32> + Unpin, /// ) -> Poll<i32> { /// let x = ready!(Pin::new(&mut a).poll(cx)); /// let y = ready!(Pin::new(&mut b).poll(cx)); /// Poll::Ready(x + y) /// } /// ``` #[macro_export] macro_rules! ready { ($e:expr $(,)?) => { match $e { core::task::Poll::Ready(t) => t, core::task::Poll::Pending => return core::task::Poll::Pending, } }; } /// Zips arbitrarily many futures, waiting for all to complete. /// /// # Examples /// /// ``` /// use futures_micro::zip; /// /// # futures_lite::future::block_on(async { /// let a = async { 1 }; /// let b = async { 2 }; /// /// assert_eq!(zip!(a, b).await, (1, 2)); /// # }) /// ``` #[macro_export] macro_rules! zip { ($($es:expr),+ $(,)?) => { $crate::poll_state( $crate::__internal_fold_with!($crate::Zip::new, $($es),+), |zips, ctx| { use ::core::future::Future; use ::core::pin::Pin; use ::core::task::Poll; let zips = unsafe { Pin::new_unchecked(zips) }; if let Poll::Ready(val) = zips.poll(ctx) { Poll::Ready($crate::zip!(@flatten; ; val; $($es),+)) } else { Poll::Pending } }, ) }; (@flatten; $($prev:expr,)*; $tuple:expr; $e:expr) => { ($($prev,)* $tuple) }; (@flatten; $($prev:expr,)*; $tuple:expr; $e:expr, $($es:expr),+) => { $crate::zip!(@flatten; $($prev,)* $tuple.0,; $tuple.1; $($es),+) }; }