| 1 |
# `peeking_take_while` |
| 2 |
|
| 3 |
[](https://travis-ci.org/fitzgen/peeking_take_while) |
| 4 |
|
| 5 |
Provides the `peeking_take_while` iterator adaptor method. |
| 6 |
|
| 7 |
The `peeking_take_while` method is very similar to `take_while`, but behaves |
| 8 |
differently when used with a borrowed iterator (perhaps returned by |
| 9 |
`Iterator::by_ref`). |
| 10 |
|
| 11 |
`peeking_take_while` peeks at the next item in the iterator and runs the |
| 12 |
predicate on that peeked item. This avoids consuming the first item yielded by |
| 13 |
the underlying iterator for which the predicate returns `false`. On the other |
| 14 |
hand, `take_while` will consume that first item for which the predicate returns |
| 15 |
`false`, and it will be lost. |
| 16 |
|
| 17 |
```rust |
| 18 |
extern crate peeking_take_while; |
| 19 |
|
| 20 |
// Bring the `peeking_take_while` method for peekable iterators into |
| 21 |
// scope. |
| 22 |
use peeking_take_while::PeekableExt; |
| 23 |
|
| 24 |
// Let's say we have two collections we want to iterate through: `xs` and |
| 25 |
// `ys`. We want to perform one operation on all the leading contiguous |
| 26 |
// elements that match some predicate, and a different thing with the rest of |
| 27 |
// the elements. With the `xs`, we will use the normal `take_while`. With the |
| 28 |
// `ys`, we will use `peeking_take_while`. |
| 29 |
|
| 30 |
let xs: Vec<u8> = (0..100).collect(); |
| 31 |
let ys = xs.clone(); |
| 32 |
|
| 33 |
let mut iter_xs = xs.into_iter(); |
| 34 |
let mut iter_ys = ys.into_iter().peekable(); |
| 35 |
|
| 36 |
{ |
| 37 |
// Let's do one thing with all the items that are less than 10. |
| 38 |
|
| 39 |
let xs_less_than_ten = iter_xs.by_ref().take_while(|x| *x < 10); |
| 40 |
for x in xs_less_than_ten { |
| 41 |
do_things_with(x); |
| 42 |
} |
| 43 |
|
| 44 |
let ys_less_than_ten = iter_ys.by_ref().peeking_take_while(|y| *y < 10); |
| 45 |
for y in ys_less_than_ten { |
| 46 |
do_things_with(y); |
| 47 |
} |
| 48 |
} |
| 49 |
|
| 50 |
// And now we will do some other thing with the items that are greater than |
| 51 |
// or equal to 10. |
| 52 |
|
| 53 |
// ...except, when using plain old `take_while` we lost 10! |
| 54 |
assert_eq!(iter_xs.next(), Some(11)); |
| 55 |
|
| 56 |
// However, when using `peeking_take_while` we did not! Great! |
| 57 |
assert_eq!(iter_ys.next(), Some(10)); |
| 58 |
``` |