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
//! A `Future` value that resolves once it's explicitly completed, potentially
//! from a different thread or task, similar to Java's `CompletableFuture`.
//!
//! Currently, this is implemented using the `BiLock` from the `futures` crate.
//!
//! # Examples
//!
//! Create an incomplete `ManualFuture` and explicitly complete it with the
//! completer:
//! ```
//! # use manual_future::ManualFuture;
//! # use futures::executor::block_on;
//! let (future, completer) = ManualFuture::<i32>::new();
//! block_on(async { completer.complete(5).await });
//! assert_eq!(block_on(future), 5);
//! ```
//!
//! Create an initially complete `ManualFuture` that can be immediately
//! resolved:
//! ```
//! # use manual_future::ManualFuture;
//! # use futures::executor::block_on;
//! assert_eq!(block_on(ManualFuture::new_completed(10)), 10);
//! ```

#![warn(clippy::pedantic)]

use futures::lock::BiLock;
use std::future::Future;
use std::marker::Unpin;
use std::pin::Pin;
use std::task::Waker;
use std::task::{Context, Poll};

enum State<T> {
    Incomplete,
    Waiting(Waker),
    Complete(Option<T>),
}

impl<T> State<T> {
    fn new(value: Option<T>) -> Self {
        match value {
            None => Self::Incomplete,
            v @ Some(_) => Self::Complete(v),
        }
    }
}

/// A value that may or may not be completed yet.
///
/// This future will not resolve until it's been explicitly completed, either
/// with `new_completed` or with `ManualFutureCompleter::complete`.
pub struct ManualFuture<T: Unpin> {
    state: BiLock<State<T>>,
}

/// Used to complete a `ManualFuture` so it can be resolved to a given value.
///
/// Dropping a `ManualFutureCompleter` will cause the associated `ManualFuture`
/// to never complete.
pub struct ManualFutureCompleter<T: Unpin> {
    state: BiLock<State<T>>,
}

impl<T: Unpin> ManualFutureCompleter<T> {
    /// Complete the `ManualFuture` associated with this
    ///
    /// `ManualFutureCompleter`. To prevent cases where a `ManualFuture` is
    /// completed twice, this takes the completer by value.
    pub async fn complete(self, value: T) {
        let mut state = self.state.lock().await;

        match std::mem::replace(&mut *state, State::Complete(Some(value))) {
            State::Incomplete => {}
            State::Waiting(w) => w.wake(),
            _ => panic!("future already completed"),
        }
    }
}

impl<T: Unpin> ManualFuture<T> {
    /// Create a new `ManualFuture` which will be resolved once the associated
    /// `ManualFutureCompleter` is used to set the value.
    pub fn new() -> (Self, ManualFutureCompleter<T>) {
        let (a, b) = BiLock::new(State::new(None));
        (Self { state: a }, ManualFutureCompleter { state: b })
    }

    /// Create a new `ManualFuture` which has already been completed with the
    /// given value.
    ///
    /// Because the `ManualFuture` is already completed, a
    /// `ManualFutureCompleter` won't be returned.
    pub fn new_completed(value: T) -> Self {
        let (state, _) = BiLock::new(State::new(Some(value)));
        Self { state }
    }
}

impl<T: Unpin> Future for ManualFuture<T> {
    type Output = T;

    fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
        let mut state = match self.state.poll_lock(cx) {
            Poll::Pending => return Poll::Pending,
            Poll::Ready(v) => v,
        };

        match &mut *state {
            s @ State::Incomplete => *s = State::Waiting(cx.waker().clone()),
            State::Waiting(w) if w.will_wake(cx.waker()) => {}
            s @ State::Waiting(_) => *s = State::Waiting(cx.waker().clone()),
            State::Complete(v) => match v.take() {
                Some(v) => return Poll::Ready(v),
                None => panic!("future already polled to completion"),
            },
        }

        Poll::Pending
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use futures::executor::block_on;
    use futures::future::join;
    use std::thread::sleep;
    use std::thread::spawn;
    use std::time::Duration;
    use tokio::time::timeout;

    #[tokio::test]
    async fn test_not_completed() {
        let (future, _) = ManualFuture::<()>::new();
        timeout(Duration::from_millis(100), future)
            .await
            .expect_err("should not complete");
    }

    #[tokio::test]
    async fn test_manual_completed() {
        let (future, completer) = ManualFuture::<()>::new();
        assert_eq!(join(future, completer.complete(())).await, ((), ()));
    }

    #[tokio::test]
    async fn test_pre_completed() {
        assert_eq!(ManualFuture::new_completed(()).await, ());
    }

    #[test]
    fn test_threaded() {
        let (future, completer) = ManualFuture::<()>::new();

        let t1 = spawn(move || {
            assert_eq!(block_on(future), ());
        });

        let t2 = spawn(move || {
            sleep(Duration::from_millis(100));
            block_on(async {
                completer.complete(()).await;
            });
        });

        t1.join().unwrap();
        t2.join().unwrap();
    }
}