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

no-std build peeking_take_while

类似于 Iterator::take_while,但在预览的值上调用谓词。这允许您同时使用 Iterator::by_refIterator::take_while,并且仍然得到 take_while 谓词返回 false 后丢弃的 by_ref 的第一个值。

4个版本 (1 个稳定版)

1.0.0 2021年9月3日
0.1.2 2017年5月17日
0.1.1 2017年5月17日
0.1.0 2017年5月17日

#191Rust模式

Download history 530197/week @ 2024-03-14 521554/week @ 2024-03-21 514202/week @ 2024-03-28 543289/week @ 2024-04-04 518969/week @ 2024-04-11 529268/week @ 2024-04-18 520126/week @ 2024-04-25 517888/week @ 2024-05-02 495484/week @ 2024-05-09 521741/week @ 2024-05-16 492160/week @ 2024-05-23 557266/week @ 2024-05-30 519397/week @ 2024-06-06 522738/week @ 2024-06-13 479879/week @ 2024-06-20 404285/week @ 2024-06-27

2,037,643 每月下载量
用于 3,466 个crate (6 个直接使用)

MIT/Apache

11KB
120

peeking_take_while

Build Status

提供 peeking_take_while 迭代器适配器方法。

peeking_take_while 方法与 take_while 非常相似,但在使用借用迭代器(可能由 Iterator::by_ref 返回)时表现不同。

peeking_take_while 预览迭代器的下一个项目并在该预览项上运行谓词。这避免了消耗由基础迭代器产生的第一个谓词返回 false 的项。另一方面,take_while 会消耗那个谓词返回 false 的第一个项,并且它将会丢失。

// 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));

无运行时依赖