-
Notifications
You must be signed in to change notification settings - Fork 341
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
* add stream::min_by method * Update src/stream/stream.rs Co-Authored-By: Yoshua Wuyts <[email protected]>
- Loading branch information
1 parent
bac74c2
commit 7e3599a
Showing
3 changed files
with
90 additions
and
0 deletions.
There are no files selected for viewing
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
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> { | ||
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> { | ||
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, | ||
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(); | ||
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), | ||
} | ||
} | ||
} |
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
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