Skip to content

Commit cda2ad8

Browse files
committed
implement Future::select
Signed-off-by: Yoshua Wuyts <yoshuawuyts@gmail.com>
1 parent ce81336 commit cda2ad8

File tree

2 files changed

+64
-4
lines changed

2 files changed

+64
-4
lines changed

src/future/future.rs renamed to src/future/future/mod.rs

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
11
cfg_unstable! {
22
mod delay;
3+
mod select;
34

45
use std::time::Duration;
56

7+
use select::Select;
68
use delay::DelayFuture;
79
}
810

@@ -147,9 +149,9 @@ extension_trait! {
147149
# Examples
148150
149151
```
150-
#![feature(async_await)]
151152
# futures::executor::block_on(async {
152-
use futures::future;
153+
use async_std::prelude::*;
154+
use async_std::future;
153155
154156
let a = future::pending();
155157
let b = future::ready(1u8);
@@ -160,8 +162,12 @@ extension_trait! {
160162
# });
161163
```
162164
"#]
163-
fn select(&mut self) -> () {
164-
()
165+
fn select<F>(self, other: F) -> Select<Self, F>
166+
where
167+
Self: Sized,
168+
F: Future<Output = Self::Output>,
169+
{
170+
Select::new(self, other)
165171
}
166172
}
167173

src/future/future/select.rs

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
use std::pin::Pin;
2+
3+
use pin_project_lite::pin_project;
4+
use async_macros::MaybeDone;
5+
6+
use crate::future::Future;
7+
// use crate::future::MaybeDone;
8+
use crate::task::{Context, Poll};
9+
10+
pin_project! {
11+
#[allow(missing_docs)]
12+
#[allow(missing_debug_implementations)]
13+
pub struct Select<L, R> where L: Future, R: Future<Output = L::Output> {
14+
#[pin] left: MaybeDone<L>,
15+
#[pin] right: MaybeDone<R>,
16+
}
17+
}
18+
19+
impl<L, R> Select<L, R>
20+
where
21+
L: Future,
22+
R: Future<Output = L::Output>,
23+
{
24+
pub(crate) fn new(left: L, right: R) -> Self {
25+
Self {
26+
left: MaybeDone::new(left),
27+
right: MaybeDone::new(right),
28+
}
29+
}
30+
}
31+
32+
impl<L, R> Future for Select<L, R>
33+
where
34+
L: Future,
35+
R: Future<Output = L::Output>,
36+
{
37+
type Output = L::Output;
38+
39+
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
40+
let this = self.project();
41+
42+
let mut left = this.left;
43+
if Future::poll(Pin::new(&mut left), cx).is_ready() {
44+
return Poll::Ready(left.take().unwrap());
45+
}
46+
47+
let mut right = this.right;
48+
if Future::poll(Pin::new(&mut right), cx).is_ready() {
49+
return Poll::Ready(right.take().unwrap());
50+
}
51+
52+
Poll::Pending
53+
}
54+
}

0 commit comments

Comments
 (0)