Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix double drop in StreamExt::cycle #903

Merged
merged 1 commit into from
Nov 5, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 18 additions & 24 deletions src/stream/stream/cycle.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,19 @@
use core::mem::ManuallyDrop;
use core::pin::Pin;

use futures_core::ready;
use pin_project_lite::pin_project;

use crate::stream::Stream;
use crate::task::{Context, Poll};

/// A stream that will repeatedly yield the same list of elements.
#[derive(Debug)]
pub struct Cycle<S> {
orig: S,
source: ManuallyDrop<S>,
pin_project! {
/// A stream that will repeatedly yield the same list of elements.
#[derive(Debug)]
pub struct Cycle<S> {
orig: S,
#[pin]
source: S,
}
}

impl<S> Cycle<S>
Expand All @@ -18,15 +23,7 @@ where
pub(crate) fn new(source: S) -> Self {
Self {
orig: source.clone(),
source: ManuallyDrop::new(source),
}
}
}

impl<S> Drop for Cycle<S> {
fn drop(&mut self) {
unsafe {
ManuallyDrop::drop(&mut self.source);
source,
}
}
}
Expand All @@ -38,17 +35,14 @@ where
type Item = S::Item;

fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
unsafe {
let this = self.get_unchecked_mut();
let mut this = self.project();

match futures_core::ready!(Pin::new_unchecked(&mut *this.source).poll_next(cx)) {
Some(item) => Poll::Ready(Some(item)),
None => {
ManuallyDrop::drop(&mut this.source);
this.source = ManuallyDrop::new(this.orig.clone());
Pin::new_unchecked(&mut *this.source).poll_next(cx)
}
match ready!(this.source.as_mut().poll_next(cx)) {
None => {
this.source.set(this.orig.clone());
this.source.poll_next(cx)
}
item => Poll::Ready(item),
}
}
}