Skip to content

Add Peekable::until #75540

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

Closed
wants to merge 4 commits into from
Closed
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
104 changes: 104 additions & 0 deletions library/core/src/iter/adapters/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1687,6 +1687,110 @@ impl<I: Iterator> Peekable<I> {
{
self.next_if(|next| next == expected)
}

/// Creates an iterator that consumes elements until predicate is
/// true, without consuming the last matching element.
Copy link
Author

@apelisse apelisse Aug 15, 2020

Choose a reason for hiding this comment

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

Suggested change
/// true, without consuming the last matching element.
/// true, without consuming the last, matching element.

///
/// `until()` takes a closure as an argument. It will call this
/// closure on each element of the iterator, and consume elements
/// until it returns true.
///
/// After true is returned, until()'s job is over, and the iterator
Copy link
Contributor

Choose a reason for hiding this comment

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

Suggested change
/// After true is returned, until()'s job is over, and the iterator
/// After `true` is returned, `until()`'s job is over, and the iterator

/// is fused.
///
/// This is the exact opposite of [`skip_while`].
///
/// # Example
/// Consume numbers until you find a '5'.
/// ```
/// #![feature(peekable_next_if)]
/// let mut iter = (0..10).peekable();
/// assert_eq!(iter.until(|&x| x == 5).collect::<String>(), "1234".to_string());
/// assert_eq!(iter.next(), Some(5));
/// ```
/// [`skip_while`]: trait.Iterator.html#method.skip_while
#[unstable(feature = "peekable_next_if", issue = "72480")]
pub fn until<P: FnMut(&I::Item) -> bool>(&mut self, func: P) -> Until<'_, I, P> {
Copy link
Contributor

Choose a reason for hiding this comment

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

Shouldn't think be take_until? We should also link take_while here for a non-consuming version. This is what I am looking for.

Until::new(self, func)
}
}

/// An iterator that iterates over elements until `predicate` returns `false`.
///
/// This `struct` is created by the [`until`] method on [`Peekable`]. See its
/// documentation for more.
///
/// [`until`]: trait.Peekable.html#until
/// [`Iterator`]: trait.Iterator.html
Copy link
Contributor

Choose a reason for hiding this comment

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

cross doc link, we probably don't need this. @jyn514 would be happy if you remove this

#[must_use = "iterators are lazy and do nothing unless consumed"]
#[unstable(feature = "peekable_next_if", issue = "72480")]
pub struct Until<'a, I, P>
where
I: Iterator,
{
peekable: &'a mut Peekable<I>,
flag: bool,
Copy link
Contributor

Choose a reason for hiding this comment

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

Can we remove flag? And use predicate: Option<P> to indicate that it can still be iterated on?

predicate: P,
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Suggested change
}
}

impl<'a, I, P> Until<'a, I, P>
where
I: Iterator,
{
fn new(peekable: &'a mut Peekable<I>, predicate: P) -> Self {
Until { peekable, flag: false, predicate }
}
}

#[stable(feature = "core_impl_debug", since = "1.9.0")]
impl<I, P> fmt::Debug for Until<'_, I, P>
where
I: fmt::Debug + Iterator,
I::Item: fmt::Debug,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Until").field("peekable", self.peekable).field("flag", &self.flag).finish()
}
}

#[unstable(feature = "peekable_next_if", issue = "72480")]
impl<I: Iterator, P> Iterator for Until<'_, I, P>
where
P: FnMut(&I::Item) -> bool,
{
type Item = I::Item;

#[inline]
fn next(&mut self) -> Option<I::Item> {
Copy link
Contributor

@pickfire pickfire Aug 15, 2020

Choose a reason for hiding this comment

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

skip_while uses fn check most likely to optimized the assembly (size and cache), how does this assembly looks like? @lzutao do you think this will have an impact? SkipWhile

impl<I: Iterator, P> Iterator for SkipWhile<I, P>
where
    P: FnMut(&I::Item) -> bool,
{
    type Item = I::Item;

    #[inline]
    fn next(&mut self) -> Option<I::Item> {
        fn check<'a, T>(
            flag: &'a mut bool,
            pred: &'a mut impl FnMut(&T) -> bool,
        ) -> impl FnMut(&T) -> bool + 'a {
            move |x| {
                if *flag || !pred(x) {
                    *flag = true;
                    true
                } else {
                    false
                }
            }
        }

        let flag = &mut self.flag;
        let pred = &mut self.predicate;
        self.iter.find(check(flag, pred))
    }

if self.flag {
return None;
}
match self.peekable.peek() {
Some(matched) => {
if (self.predicate)(&matched) {
// matching value is not consumed.
self.flag = true;
None
} else {
self.peekable.next()
}
}
None => None,
}
}

#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
let (_, upper) = self.peekable.size_hint();
(0, upper) // can't know a lower bound, due to the predicate
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Shouldn't we override try_fold and fold too?

}

#[stable(feature = "fused", since = "1.26.0")]
impl<I, P> FusedIterator for Until<'_, I, P>
where
I: FusedIterator,
P: FnMut(&I::Item) -> bool,
{
}

/// An iterator that rejects elements while `predicate` returns `true`.
Expand Down
11 changes: 11 additions & 0 deletions library/core/tests/iter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -837,6 +837,17 @@ fn test_iterator_peekable_next_if_eq() {
assert_eq!(it.next_if_eq(""), None);
}

#[test]
fn test_until_iter() {
let xs = "Heart of Gold";
let mut it = xs.chars().peekable();
{
let until = it.until(|&c| c == ' ');
assert_eq!(until.collect::<String>(), "Heart".to_string());
}
assert_eq!(it.collect::<String>(), " of Gold".to_string());
}

/// This is an iterator that follows the Iterator contract,
/// but it is not fused. After having returned None once, it will start
/// producing elements if .next() is called again.
Expand Down