Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Cell::update #49727

Merged
merged 5 commits into from Apr 24, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions src/libcore/cell.rs
Original file line number Diff line number Diff line change
Expand Up @@ -256,6 +256,33 @@ impl<T:Copy> Cell<T> {
pub fn get(&self) -> T {
unsafe{ *self.value.get() }
}

/// Updates the contained value using a function and returns the new value.
///
/// # Examples
///
/// ```
/// #![feature(cell_update)]
///
/// use std::cell::Cell;
///
/// let c = Cell::new(5);
/// let new = c.update(|x| x + 1);
///
/// assert_eq!(new, 6);
/// assert_eq!(c.get(), 6);
/// ```
#[inline]
#[unstable(feature = "cell_update", issue = "50186")]
pub fn update<F>(&self, f: F) -> T
where
F: FnOnce(T) -> T,
{
let old = self.get();
let new = f(old);
self.set(new);
new
}
}

#[stable(feature = "rust1", since = "1.0.0")]
Expand Down
11 changes: 11 additions & 0 deletions src/libcore/tests/cell.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,17 @@ fn smoketest_cell() {
assert!(y.get() == (30, 40));
}

#[test]
fn cell_update() {
let x = Cell::new(10);

assert_eq!(x.update(|x| x + 5), 15);
assert_eq!(x.get(), 15);

assert_eq!(x.update(|x| x / 3), 5);
assert_eq!(x.get(), 5);
}

#[test]
fn cell_has_sensible_show() {
let x = Cell::new("foo bar");
Expand Down
1 change: 1 addition & 0 deletions src/libcore/tests/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@

#![feature(ascii_ctype)]
#![feature(box_syntax)]
#![feature(cell_update)]
#![feature(core_float)]
#![feature(core_private_bignum)]
#![feature(core_private_diy_float)]
Expand Down