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
/**************************************************************************************************
 *                                                                                                *
 * This Source Code Form is subject to the terms of the Mozilla Public                            *
 * License, v. 2.0. If a copy of the MPL was not distributed with this                            *
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.                                       *
 *                                                                                                *
 **************************************************************************************************/

// ======================================== Configuration ======================================= \\

#![no_std]

// ======================================== Documentation ======================================= \\

//! A way to poll two futures and get the output of the first one to complete.
//!
//! ## Example
//!
//! ```rust
//! use futures_race::{Race, RaceExt};
//! use smol::Timer;
//! use std::time::Duration;
//!
//! smol::run(async {
//!     let foo = async {
//!         Timer::new(Duration::from_millis(100)).await;
//!         42
//!     };
//!
//!     let bar = async {
//!         Timer::new(Duration::from_millis(250)).await;
//!         24
//!     };
//!
//!     let foobar = foo.race(bar).await;
//!     assert_eq!(foobar, 42);
//! });
//! ```

// =========================================== Imports ========================================== \\

use core::future::Future;
use core::pin::Pin;
use core::task::{Context, Poll};
use pin_project_lite::pin_project;

// ============================================ Types =========================================== \\

pin_project! {
    #[derive(Debug)]
    /// A future polling two other futures and returning the output of the first one to complete.
    ///
    /// ## Example
    ///
    /// ```
    /// use futures_race::{Race, RaceExt};
    /// # use smol::Timer;
    /// # use std::time::Duration;
    ///
    /// # smol::run(async {
    /// let foo = async {
    ///     Timer::new(Duration::from_millis(100)).await;
    ///     42
    /// };
    ///
    /// let bar = async {
    ///     Timer::new(Duration::from_millis(250)).await;
    ///     24
    /// };
    ///
    /// let foobar = foo.race(bar).await;
    /// assert_eq!(foobar, 42);
    /// # })
    /// ```
    pub struct Race<Left, Right>
    where
        Left: Future,
        Right: Future<Output = Left::Output>,
    {
        #[pin]
        left: Left,
        #[pin]
        right: Right,
    }
}

// ========================================= Interfaces ========================================= \\

/// An extension trait for [`Future`]s that provides a way to create [`Race`]s.
pub trait RaceExt: Future {
    /// Given a second future with the same output, creates and returns a new [`Race`] that will
    /// poll both futures and return the output of the first one to complete.
    ///
    /// ## Example
    ///
    /// ```
    /// use futures_race::{Race, RaceExt};
    /// # use smol::Timer;
    /// # use std::time::Duration;
    ///
    /// # smol::run(async {
    /// let foo = async {
    ///     Timer::new(Duration::from_millis(100)).await;
    ///     42
    /// };
    ///
    /// let bar = async {
    ///     Timer::new(Duration::from_millis(250)).await;
    ///     24
    /// };
    ///
    /// let foobar = foo.race(bar).await;
    /// assert_eq!(foobar, 42);
    /// # })
    /// ```
    fn race<With>(self, with: With) -> Race<Self, With>
    where
        Self: Sized,
        With: Future<Output = Self::Output>,
    {
        Race {
            left: self,
            right: with,
        }
    }
}

impl<Fut: Future> RaceExt for Fut {}

// ========================================= impl Future ======================================== \\

impl<Left, Right> Future for Race<Left, Right>
where
    Left: Future,
    Right: Future<Output = Left::Output>,
{
    type Output = Left::Output;

    fn poll(self: Pin<&mut Self>, ctx: &mut Context) -> Poll<Self::Output> {
        let this = self.project();

        if let poll @ Poll::Ready(_) = this.left.poll(ctx) {
            return poll;
        }

        if let poll @ Poll::Ready(_) = this.right.poll(ctx) {
            return poll;
        }

        Poll::Pending
    }
}