#iterator #peek #take-while #by-ref

no-std build peeking_take_while

Like Iterator::take_while, but calls the predicate on a peeked value. This allows you to use Iterator::by_ref and Iterator::take_while together, and still get the first value for which the take_while predicate returned false after dropping the by_ref.

4 releases (1 stable)

1.0.0 Sep 3, 2021
0.1.2 May 17, 2017
0.1.1 May 17, 2017
0.1.0 May 17, 2017

#209 in Rust patterns

Download history 510006/week @ 2024-08-12 532543/week @ 2024-08-19 525382/week @ 2024-08-26 480419/week @ 2024-09-02 526752/week @ 2024-09-09 571451/week @ 2024-09-16 563074/week @ 2024-09-23 887986/week @ 2024-09-30 1224543/week @ 2024-10-07 1054392/week @ 2024-10-14 657226/week @ 2024-10-21 501111/week @ 2024-10-28 502439/week @ 2024-11-04 509786/week @ 2024-11-11 491960/week @ 2024-11-18 371223/week @ 2024-11-25

1,891,750 downloads per month
Used in 3,464 crates (8 directly)

MIT/Apache

11KB
120 lines

peeking_take_while

Build Status

Provides the peeking_take_while iterator adaptor method.

The peeking_take_while method is very similar to take_while, but behaves differently when used with a borrowed iterator (perhaps returned by Iterator::by_ref).

peeking_take_while peeks at the next item in the iterator and runs the predicate on that peeked item. This avoids consuming the first item yielded by the underlying iterator for which the predicate returns false. On the other hand, take_while will consume that first item for which the predicate returns false, and it will be lost.

// Bring the `peeking_take_while` method for peekable iterators into
// scope.
use peeking_take_while::PeekableExt;

// Let's say we have two collections we want to iterate through: `xs` and
// `ys`. We want to perform one operation on all the leading contiguous
// elements that match some predicate, and a different thing with the rest of
// the elements. With the `xs`, we will use the normal `take_while`. With the
// `ys`, we will use `peeking_take_while`.

let xs: Vec<u8> = (0..100).collect();
let ys = xs.clone();

let mut iter_xs = xs.into_iter();
let mut iter_ys = ys.into_iter().peekable();

{
    // Let's do one thing with all the items that are less than 10.

    let xs_less_than_ten = iter_xs.by_ref().take_while(|x| *x < 10);
    for x in xs_less_than_ten {
        do_things_with(x);
    }

    let ys_less_than_ten = iter_ys.by_ref().peeking_take_while(|y| *y < 10);
    for y in ys_less_than_ten {
        do_things_with(y);
    }
}

// And now we will do some other thing with the items that are greater than
// or equal to 10.

// ...except, when using plain old `take_while` we lost 10!
assert_eq!(iter_xs.next(), Some(11));

// However, when using `peeking_take_while` we did not! Great!
assert_eq!(iter_ys.next(), Some(10));

No runtime deps