about summary refs log tree commit diff
path: root/src/test/incremental/thinlto
diff options
context:
space:
mode:
authorkennytm <kennytm@gmail.com>2018-11-24 01:31:50 +0800
committerGitHub <noreply@github.com>2018-11-24 01:31:50 +0800
commitef2cbec5a601f7f4414808034c93a8cbbb2066f7 (patch)
tree252f1df7df1a39b46056fbde0ad1251291c1e5c5 /src/test/incremental/thinlto
parent738afd4f69587791a779e583969034edc569541c (diff)
parenta4279a07e29091fd8a72b13b2109c8969e713ffd (diff)
downloadrust-ef2cbec5a601f7f4414808034c93a8cbbb2066f7.tar.gz
rust-ef2cbec5a601f7f4414808034c93a8cbbb2066f7.zip
Rollup merge of #55869 - SimonSapin:iterate, r=alexcrichton
Add std::iter::unfold

This adds an **unstable** ~`std::iter::iterate`~ `std::iter::unfold` function and ~`std::iter::Iterate`~ `std::iter::Unfold` type that trivially wrap a ~`FnMut() -> Option<T>`~ `FnMut(&mut State) -> Option<T>` closure to create an iterator. ~Iterator state can be kept in the closure’s environment or captures.~

This is intended to help reduce amount of boilerplate needed when defining an iterator that is only created in one place. Compare the existing example of the `std::iter` module: (explanatory comments elided)

```rust
struct Counter {
    count: usize,
}

impl Counter {
    fn new() -> Counter {
        Counter { count: 0 }
    }
}

impl Iterator for Counter {
    type Item = usize;

    fn next(&mut self) -> Option<usize> {
        self.count += 1;
        if self.count < 6 {
            Some(self.count)
        } else {
            None
        }
    }
}
```

… with the same algorithm rewritten to use this new API:

```rust
fn counter() -> impl Iterator<Item=usize> {
    std::iter::unfold(0, |count| {
        *count += 1;
        if *count < 6 {
            Some(*count)
        } else {
            None
        }
    })
}
```

-----

This also add unstable `std::iter::successors` which takes an (optional) initial item and a closure that takes an item and computes the next one (its successor).

```rust
let powers_of_10 = successors(Some(1_u16), |n| n.checked_mul(10));
assert_eq!(powers_of_10.collect::<Vec<_>>(), &[1, 10, 100, 1_000, 10_000]);
```
Diffstat (limited to 'src/test/incremental/thinlto')
0 files changed, 0 insertions, 0 deletions