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