Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(futures-util/stream): unzip operator #2263

Merged
merged 4 commits into from
Nov 18, 2020
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions futures-util/src/stream/stream/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,10 @@ mod collect;
#[allow(unreachable_pub)] // https://github.com/rust-lang/rust/issues/57411
pub use self::collect::Collect;

mod unzip;
#[allow(unreachable_pub)] // https://github.com/rust-lang/rust/issues/57411
pub use self::unzip::Unzip;

mod concat;
#[allow(unreachable_pub)] // https://github.com/rust-lang/rust/issues/57411
pub use self::concat::Concat;
Expand Down Expand Up @@ -477,6 +481,45 @@ pub trait StreamExt: Stream {
assert_future::<C, _>(Collect::new(self))
}

/// Converts a stream of pairs into a future, which
/// resolves to pair of containers.
///
/// `unzip()` produces a future, which resolves to two
/// collections: one from the left elements of the pairs,
/// and one from the right elements.
///
/// The returned future will be resolved when the stream terminates.
///
/// # Examples
///
/// ```
/// # futures::executor::block_on(async {
/// use futures::channel::mpsc;
/// use futures::stream::StreamExt;
/// use std::thread;
///
/// let (tx, rx) = mpsc::unbounded();
///
/// thread::spawn(move || {
/// tx.unbounded_send((1, 2)).unwrap();
/// tx.unbounded_send((3, 4)).unwrap();
/// tx.unbounded_send((5, 6)).unwrap();
/// });
///
/// let (o1, o2): (Vec<_>, Vec<_>) = rx.unzip().await;
/// assert_eq!(o1, vec![1, 3, 5]);
/// assert_eq!(o2, vec![2, 4, 6]);
/// # });
/// ```
fn unzip<A, B, FromA, FromB>(self) -> Unzip<Self, FromA, FromB>
where
FromA: Default + Extend<A>,
FromB: Default + Extend<B>,
Self: Sized + Stream<Item = (A, B)>,
{
assert_future::<(FromA, FromB), _>(Unzip::new(self))
}

/// Concatenate all items of a stream into a single extendable
/// destination, returning a future representing the end result.
///
Expand Down
66 changes: 66 additions & 0 deletions futures-util/src/stream/stream/unzip.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
use core::mem;
use core::pin::Pin;
use futures_core::future::{FusedFuture, Future};
use futures_core::stream::{FusedStream, Stream};
use futures_core::task::{Context, Poll};
use pin_project::pin_project;

/// Future for the [`unzip`](super::StreamExt::unzip) method.
#[pin_project]
#[derive(Debug)]
#[must_use = "futures do nothing unless you `.await` or poll them"]
pub struct Unzip<St, FromA, FromB> {
#[pin]
stream: St,
left: FromA,
right: FromB,
}

impl<St: Stream, FromA: Default, FromB: Default> Unzip<St, FromA, FromB> {
fn finish(self: Pin<&mut Self>) -> (FromA, FromB) {
let this = self.project();
(
mem::take(this.left),
mem::take(this.right),
binier marked this conversation as resolved.
Show resolved Hide resolved
)
}

pub(super) fn new(stream: St) -> Self {
Self {
stream,
left: Default::default(),
right: Default::default(),
}
}
}

impl<St, A, B, FromA, FromB> FusedFuture for Unzip<St, FromA, FromB>
where St: FusedStream<Item = (A, B)>,
FromA: Default + Extend<A>,
FromB: Default + Extend<B>,
{
fn is_terminated(&self) -> bool {
self.stream.is_terminated()
}
}

impl<St, A, B, FromA, FromB> Future for Unzip<St, FromA, FromB>
where St: Stream<Item = (A, B)>,
FromA: Default + Extend<A>,
FromB: Default + Extend<B>,
{
type Output = (FromA, FromB);

fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<(FromA, FromB)> {
let mut this = self.as_mut().project();
loop {
match ready!(this.stream.as_mut().poll_next(cx)) {
Some(e) => {
this.left.extend(Some(e.0));
this.right.extend(Some(e.1));
},
None => return Poll::Ready(self.finish()),
}
}
}
}