Hi all,
trying to understand async, pin and streams I wrote this toy:
struct MyIntersperse<S: Stream<Item = String>> {
source: Pin<Box<S>>,
interspersed: bool,
}
impl<S: Stream<Item = String>> MyIntersperse<S> {
fn new(source: S) -> MyIntersperse<S> {
MyIntersperse {
source: Box::pin(source),
interspersed: false,
}
}
}
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>> {
if !self.interspersed {
self.interspersed = true;
Poll::Ready(Some(String::from("---")))
} else {
match Pin::new(&mut self.source).poll_next(cx) {
Poll::Pending => Poll::Pending,
Poll::Ready(None) => Poll::Ready(None),
Poll::Ready(Some(s)) => {
self.interspersed = false;
Poll::Ready(Some(s))
}
}
}
}
}
My question: Why do I need Pin<Box<S>>
in struct MyIntersperse
? I thought, when self
is pinned in poll_next()
I can also pin self.source
. But this does not work. I get a compiler error. I "fixed" this by trial and error and came across Pin<Box<S>>
. But maybe there is a better solution?
Thanks for help and some reading pointers!