• Home
  • History
  • Annotate
Name Date Size #Lines LOC

..--

src/23-Nov-2023-11841

.gitignoreD23-Nov-202330 43

.travis.ymlD23-Nov-2023217 1914

Android.bpD23-Nov-20232 KiB6760

Cargo.tomlD23-Nov-2023653 1513

LICENSED23-Nov-202310.6 KiB202169

LICENSE-APACHED23-Nov-202310.6 KiB202169

LICENSE-MITD23-Nov-20231 KiB2622

METADATAD23-Nov-2023641 2019

MODULE_LICENSE_APACHE2D23-Nov-20230

OWNERSD23-Nov-202340 21

README.mdD23-Nov-20232 KiB5943

TEST_MAPPINGD23-Nov-2023213 1211

README.md

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
18extern crate peeking_take_while;
19
20// Bring the `peeking_take_while` method for peekable iterators into
21// scope.
22use 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
30let xs: Vec<u8> = (0..100).collect();
31let ys = xs.clone();
32
33let mut iter_xs = xs.into_iter();
34let 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!
54assert_eq!(iter_xs.next(), Some(11));
55
56// However, when using `peeking_take_while` we did not! Great!
57assert_eq!(iter_ys.next(), Some(10));
58```
59