-
-
Save rust-play/bcf31b3d376d0a951c50c9e2bfe25b5e to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
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
pub struct MyIntersperse<S> { | |
source: S, | |
interspersed: bool, | |
} | |
struct MyIntersperseProject<'a, S> { | |
source: Pin<&'a mut S>, | |
interspersed: &'a mut bool, | |
} | |
impl<S: Stream<Item = String>> MyIntersperse<S> { | |
pub fn new(source: S) -> MyIntersperse<S> { | |
MyIntersperse { | |
source: Box::pin(source), | |
interspersed: false, | |
} | |
} | |
fn project(self: Pin<&mut Self>) -> MyIntersperseProject<'_, S> { | |
let this = unsafe { Pin::into_inner_unchecked(self) }; | |
MyIntersperseProject { | |
source: unsafe { Pin::new_unchecked(&mut this.source) }, | |
interspersed: &mut this.interspersed, | |
} | |
} | |
} | |
impl<S: Stream<Item = String>> Stream for MyIntersperse<S> { | |
type Item = String; | |
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> { | |
let this = self.project(); | |
if !this.interspersed { | |
this.interspersed = true; | |
Poll::Ready(Some(String::from("---"))) | |
} else { | |
match this.source.poll_next(cx) { | |
Poll::Pending => Poll::Pending, | |
Poll::Ready(None) => Poll::Ready(None), | |
Poll::Ready(Some(s)) => { | |
this.interspersed = false; | |
Poll::Ready(Some(s)) | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment