]> git.lizzy.rs Git - rust.git/commit - src/tools/rustfmt
Rollup merge of #49727 - stjepang:cell-update, r=SimonSapin
authorkennytm <kennytm@gmail.com>
Tue, 24 Apr 2018 03:57:00 +0000 (11:57 +0800)
committerGitHub <noreply@github.com>
Tue, 24 Apr 2018 03:57:00 +0000 (11:57 +0800)
commit91cc872987da776874021d985f08a4262ac07396
treeef1155a6ed17d4c4df03df892e102c6974d0ac36
parentcefdd6d5e99618f193c1cd3365aa18b786731d97
parent29e9de85d6ae185d7d66c7ba0f2c418082d2df5f
Rollup merge of #49727 - stjepang:cell-update, r=SimonSapin

Add Cell::update

This commit adds a new method `Cell::update`, which applies a function to the value inside the cell.

Previously discussed in: https://github.com/rust-lang/rfcs/issues/2171

### Motivation

Updating `Cell`s is currently a bit verbose. Here are several real examples (taken from rustc and crossbeam):

```rust
self.print_fuel.set(self.print_fuel.get() + 1);

self.diverges.set(self.diverges.get() | Diverges::Always);

let guard_count = self.guard_count.get();
self.guard_count.set(guard_count.checked_add(1).unwrap());
if guard_count == 0 {
    // ...
}
```

With the addition of the new method `Cell::update`, this code can be simplified to:

```rust
self.print_fuel.update(|x| x + 1);

self.diverges.update(|x| x | Diverges::Always);

if self.guard_count.update(|x| x.checked_add(1).unwrap()) == 1 {
    // ...
}
```

### Unresolved questions

1. Should we return the old value instead of the new value (like in `fetch_add` and `fetch_update`)?
2. Should the return type simply be `()`?
3. Naming: `update` vs `modify` vs `mutate` etc.

cc @SimonSapin
src/libcore/tests/lib.rs