add: Add stream unzip

This commit is contained in:
k-nasa 2019-11-16 01:16:35 +09:00
parent 31cf932d80
commit 603b3c5085
2 changed files with 19 additions and 13 deletions

View file

@ -124,13 +124,13 @@ cfg_unstable! {
use count::CountFuture; use count::CountFuture;
use partition::PartitionFuture; use partition::PartitionFuture;
use unzip::UnzipFuture;
pub use merge::Merge; pub use merge::Merge;
pub use flatten::Flatten; pub use flatten::Flatten;
pub use flat_map::FlatMap; pub use flat_map::FlatMap;
pub use timeout::{TimeoutError, Timeout}; pub use timeout::{TimeoutError, Timeout};
pub use throttle::Throttle; pub use throttle::Throttle;
pub use unzip::UnzipFuture;
mod count; mod count;
mod merge; mod merge;

View file

@ -7,12 +7,13 @@ use crate::stream::Stream;
use crate::task::{Context, Poll}; use crate::task::{Context, Poll};
pin_project! { pin_project! {
#[derive(Clone, Debug)]
#[cfg(all(feature = "default", feature = "unstable"))] #[cfg(all(feature = "default", feature = "unstable"))]
#[cfg_attr(feature = "docs", doc(cfg(unstable)))] #[cfg_attr(feature = "docs", doc(cfg(unstable)))]
pub struct UnzipFuture<S: Stream, FromA, FromB> { pub struct UnzipFuture<S, FromA, FromB> {
#[pin] #[pin]
stream: S, stream: S,
res: (FromA, FromB), res: Option<(FromA, FromB)>,
} }
} }
@ -24,7 +25,7 @@ where
pub(super) fn new(stream: S) -> Self { pub(super) fn new(stream: S) -> Self {
UnzipFuture { UnzipFuture {
stream, stream,
res: (FromA::default(), FromB::default()), res: Some((FromA::default(), FromB::default())),
} }
} }
} }
@ -32,22 +33,27 @@ where
impl<S, A, B, FromA, FromB> Future for UnzipFuture<S, FromA, FromB> impl<S, A, B, FromA, FromB> Future for UnzipFuture<S, FromA, FromB>
where where
S: Stream<Item = (A, B)>, S: Stream<Item = (A, B)>,
FromA: Default + Extend<A> + Copy, FromA: Default + Extend<A>,
FromB: Default + Extend<B> + Copy, FromB: Default + Extend<B>,
{ {
type Output = (FromA, FromB); type Output = (FromA, FromB);
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let mut this = self.project(); let mut this = self.project();
let next = futures_core::ready!(this.stream.as_mut().poll_next(cx));
match next { loop {
Some((a, b)) => { let next = futures_core::ready!(this.stream.as_mut().poll_next(cx));
this.res.0.extend(Some(a));
this.res.1.extend(Some(b)); match next {
Poll::Pending Some((a, b)) => {
let mut res = this.res.take().unwrap();
res.0.extend(Some(a));
res.1.extend(Some(b));
*this.res = Some(res);
}
None => return Poll::Ready(this.res.take().unwrap()),
} }
None => Poll::Ready(*this.res),
} }
} }
} }