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

add stream::min_by method #146

Merged
merged 2 commits into from
Sep 6, 2019
Merged
Show file tree
Hide file tree
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
54 changes: 54 additions & 0 deletions src/stream/min_by.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
use std::cmp::Ordering;
use std::pin::Pin;

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

/// A future that yields the minimum item in a stream by a given comparison function.
#[derive(Clone, Debug)]
pub struct MinBy<S: Stream, F> {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since MinBy is here in a separate file, it'd be a good idea to move Take and others into their own files, too.

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

But we can do that in a follow-up PR :)

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

See #150!

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since this is a future, it should be named MinByFuture just like AllFuture and AnyFuture.

stream: S,
compare: F,
min: Option<S::Item>,
}

impl<S: Stream + Unpin, F> Unpin for MinBy<S, F> {}

impl<S: Stream + Unpin, F> MinBy<S, F> {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Instead of requiring Unpin, we should use unsafe_pinner like for the Take struct.

pub(super) fn new(stream: S, compare: F) -> Self {
MinBy {
stream,
compare,
min: None,
}
}
}

impl<S, F> Future for MinBy<S, F>
where
S: futures_core::stream::Stream + Unpin,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah, this bound may need to be updated to just be Stream as #140 was merged.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

hmmm, you probably mean #145 ?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah yes indeed

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this still unresolved?

S::Item: Copy,
F: FnMut(&S::Item, &S::Item) -> Ordering,
{
type Output = Option<S::Item>;

fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let next = futures_core::ready!(Pin::new(&mut self.stream).poll_next(cx));

match next {
Some(new) => {
cx.waker().wake_by_ref();
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this line needed at all? I believe it can be deleted.

match self.as_mut().min.take() {
None => self.as_mut().min = Some(new),
Some(old) => match (&mut self.as_mut().compare)(&new, &old) {
Ordering::Less => self.as_mut().min = Some(new),
_ => self.as_mut().min = Some(old),
},
}
Poll::Pending
}
None => Poll::Ready(self.min),
}
}
}
1 change: 1 addition & 0 deletions src/stream/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ pub use repeat::{repeat, Repeat};
pub use stream::{Stream, Take};

mod empty;
mod min_by;
mod once;
mod repeat;
mod stream;
35 changes: 35 additions & 0 deletions src/stream/stream.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,12 @@
//! # }) }
//! ```

use std::cmp::Ordering;
use std::pin::Pin;

use cfg_if::cfg_if;

use super::min_by::MinBy;
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since min_by should ideally be an async fn, let's make MinBy a hidden type and not even implement Debug (because async fn desugaring doesn't implement Debug for its future).

use crate::future::Future;
use crate::task::{Context, Poll};
use std::marker::PhantomData;
Expand Down Expand Up @@ -118,6 +120,39 @@ pub trait Stream {
}
}

/// Returns the element that gives the minimum value with respect to the
/// specified comparison function. If several elements are equally minimum,
/// the first element is returned. If the stream is empty, `None` is returned.
///
/// # Examples
///
/// ```
/// # fn main() { async_std::task::block_on(async {
/// #
/// use std::collections::VecDeque;
/// use async_std::stream::Stream;
///
/// let s: VecDeque<usize> = vec![1, 2, 3].into_iter().collect();
///
/// let min = Stream::min_by(s.clone(), |x, y| x.cmp(y)).await;
/// assert_eq!(min, Some(1));
///
/// let min = Stream::min_by(s, |x, y| y.cmp(x)).await;
/// assert_eq!(min, Some(3));
///
/// let min = Stream::min_by(VecDeque::<usize>::new(), |x, y| x.cmp(y)).await;
/// assert_eq!(min, None);
/// #
/// # }) }
/// ```
fn min_by<F>(self, compare: F) -> MinBy<Self, F>
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The return type here should use ret! like in fn any, for example. This function would ideally be an async fn if Rust supported that syntax in traits today.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How is ret! supposed to work for

  1. Futures that take self instead of &mut self and thus should have no lifetime parameters
  2. Streams
    ?

where
Self: Sized + Unpin,
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The Unpin bound here is not necessary because we're taking ownership of self in this method.

F: FnMut(&Self::Item, &Self::Item) -> Ordering,
{
MinBy::new(self, compare)
}

/// Tests if every element of the stream matches a predicate.
///
/// `all()` takes a closure that returns `true` or `false`. It applies
Expand Down