]> git.lizzy.rs Git - rust.git/commitdiff
Add Cell::update
authorStjepan Glavina <stjepang@gmail.com>
Fri, 6 Apr 2018 13:02:21 +0000 (15:02 +0200)
committerStjepan Glavina <stjepang@gmail.com>
Fri, 6 Apr 2018 13:15:28 +0000 (15:15 +0200)
src/libcore/cell.rs
src/libcore/tests/cell.rs

index c8ee166fee3e9240383a7ff37c77a0c2e15be536..2ea1b84d0340169643fcafc255a850f5cc02e6cb 100644 (file)
@@ -256,6 +256,30 @@ impl<T:Copy> Cell<T> {
     pub fn get(&self) -> T {
         unsafe{ *self.value.get() }
     }
+
+    /// Applies a function to the contained value.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use std::cell::Cell;
+    ///
+    /// let c = Cell::new(5);
+    /// c.update(|x| x + 1);
+    ///
+    /// assert_eq!(c.get(), 6);
+    /// ```
+    #[inline]
+    #[unstable(feature = "cell_update", issue = "0")] // TODO: issue
+    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")]
index cc0ef6a6f17e04b5e7358040d0ef689cb73ea871..962fb2f0e027b3924507205b43145beccef82485 100644 (file)
@@ -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");