Skip to content

Commit f86deef

Browse files
author
Stjepan Glavina
committed
Add Cell::update
1 parent a143462 commit f86deef

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

src/libcore/cell.rs

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -256,6 +256,30 @@ impl<T:Copy> Cell<T> {
256256
pub fn get(&self) -> T {
257257
unsafe{ *self.value.get() }
258258
}
259+
260+
/// Applies a function to the contained value.
261+
///
262+
/// # Examples
263+
///
264+
/// ```
265+
/// use std::cell::Cell;
266+
///
267+
/// let c = Cell::new(5);
268+
/// c.update(|x| x + 1);
269+
///
270+
/// assert_eq!(c.get(), 6);
271+
/// ```
272+
#[inline]
273+
#[unstable(feature = "cell_update", issue = "0")] // TODO: issue
274+
pub fn update<F>(&self, f: F) -> T
275+
where
276+
F: FnOnce(T) -> T,
277+
{
278+
let old = self.get();
279+
let new = f(old);
280+
self.set(new);
281+
new
282+
}
259283
}
260284

261285
#[stable(feature = "rust1", since = "1.0.0")]

src/libcore/tests/cell.rs

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,17 @@ fn smoketest_cell() {
2626
assert!(y.get() == (30, 40));
2727
}
2828

29+
#[test]
30+
fn cell_update() {
31+
let x = Cell::new(10);
32+
33+
assert_eq!(x.update(|x| x + 5), 15);
34+
assert_eq!(x.get(), 15);
35+
36+
assert_eq!(x.update(|x| x / 3), 5);
37+
assert_eq!(x.get(), 5);
38+
}
39+
2940
#[test]
3041
fn cell_has_sensible_show() {
3142
let x = Cell::new("foo bar");

0 commit comments

Comments
 (0)