Skip to content

Instantly share code, notes, and snippets.

@rust-play
Created May 7, 2023 20:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rust-play/bcf31b3d376d0a951c50c9e2bfe25b5e to your computer and use it in GitHub Desktop.
Save rust-play/bcf31b3d376d0a951c50c9e2bfe25b5e to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
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