|
| 1 | +use std::fmt; |
| 2 | +use std::pin::Pin; |
| 3 | + |
| 4 | +use crate::stream::Stream; |
| 5 | +use crate::task::{Context, Poll}; |
| 6 | + |
| 7 | +/// An iterator that iterates two other iterators simultaneously. |
| 8 | +pub struct Zip<A: Stream, B> { |
| 9 | + item_slot: Option<A::Item>, |
| 10 | + first: A, |
| 11 | + second: B, |
| 12 | +} |
| 13 | + |
| 14 | +impl<A: fmt::Debug + Stream, B: fmt::Debug> fmt::Debug for Zip<A, B> { |
| 15 | + fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 16 | + fmt.debug_struct("Zip") |
| 17 | + .field("first", &self.first) |
| 18 | + .field("second", &self.second) |
| 19 | + .finish() |
| 20 | + } |
| 21 | +} |
| 22 | + |
| 23 | +impl<A: Unpin + Stream, B: Unpin> Unpin for Zip<A, B> {} |
| 24 | + |
| 25 | +impl<A: Stream, B> Zip<A, B> { |
| 26 | + pub(crate) fn new(first: A, second: B) -> Self { |
| 27 | + Zip { |
| 28 | + item_slot: None, |
| 29 | + first, |
| 30 | + second, |
| 31 | + } |
| 32 | + } |
| 33 | + |
| 34 | + pin_utils::unsafe_unpinned!(item_slot: Option<A::Item>); |
| 35 | + pin_utils::unsafe_pinned!(first: A); |
| 36 | + pin_utils::unsafe_pinned!(second: B); |
| 37 | +} |
| 38 | + |
| 39 | +impl<A: Stream, B: Stream> futures_core::stream::Stream for Zip<A, B> { |
| 40 | + type Item = (A::Item, B::Item); |
| 41 | + |
| 42 | + fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> { |
| 43 | + if self.as_mut().item_slot().is_none() { |
| 44 | + match self.as_mut().first().poll_next(cx) { |
| 45 | + Poll::Pending => return Poll::Pending, |
| 46 | + Poll::Ready(None) => return Poll::Ready(None), |
| 47 | + Poll::Ready(Some(item)) => *self.as_mut().item_slot() = Some(item), |
| 48 | + } |
| 49 | + } |
| 50 | + let second_item = futures_core::ready!(self.as_mut().second().poll_next(cx)); |
| 51 | + let first_item = self.as_mut().item_slot().take().unwrap(); |
| 52 | + Poll::Ready(second_item.map(|second_item| (first_item, second_item))) |
| 53 | + } |
| 54 | +} |
0 commit comments