-
-
Notifications
You must be signed in to change notification settings - Fork 2.5k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
881b510
commit 567c1c5
Showing
2 changed files
with
78 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,50 @@ | ||
use std::pin::Pin; | ||
use std::task::{Context, Poll}; | ||
|
||
use futures_core::Stream; | ||
use pin_project_lite::pin_project; | ||
|
||
use crate::StreamExt; | ||
|
||
pin_project! { | ||
/// Stream returned by the [`chain`](super::StreamExt::peekable) method. | ||
pub struct Peekable<T: Stream> { | ||
peek: Option<T::Item>, | ||
#[pin] | ||
stream: T, | ||
} | ||
} | ||
|
||
impl<T: Stream> Peekable<T> { | ||
pub(crate) fn new(stream: T) -> Self { | ||
Self { | ||
peek: None, | ||
stream, | ||
} | ||
} | ||
|
||
/// Peek at the next item in the stream. | ||
pub async fn peek(&mut self) -> Option<&T::Item> | ||
where T: Unpin, | ||
{ | ||
if let Some(ref it) = self.peek { | ||
Some(it) | ||
} else { | ||
self.peek = self.next().await; | ||
self.peek.as_ref() | ||
} | ||
} | ||
} | ||
|
||
impl<T: Stream> Stream for Peekable<T> { | ||
type Item = T::Item; | ||
|
||
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> { | ||
let this = self.project(); | ||
if let Some(it) = this.peek.take() { | ||
Poll::Ready(Some(it)) | ||
} else { | ||
this.stream.poll_next(cx) | ||
} | ||
} | ||
} |