From e2ba7915e50f90641e8b4427eba20eb32295fa02 Mon Sep 17 00:00:00 2001 From: Peter Date: Sat, 31 Dec 2016 14:44:49 +0000 Subject: [PATCH] Added RefCell methods update and update_in_place --- src/libcore/cell.rs | 48 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/src/libcore/cell.rs b/src/libcore/cell.rs index c3f862e7c5418..a8aca4a406a0f 100644 --- a/src/libcore/cell.rs +++ b/src/libcore/cell.rs @@ -489,6 +489,30 @@ impl RefCell { debug_assert!(self.borrow.get() == UNUSED); unsafe { self.value.into_inner() } } + + /// Updates the underlying data by applying the supplied function, which must return a new + /// value without mutating the old value. + /// + /// This lets you treat an update atomically, which helps prevent accidentally borrowing the + /// data twice, avoiding possible panics. + /// + /// # Examples + /// + /// ``` + /// #![feature(refcell_update)] + /// use std::cell::RefCell; + /// + /// let c = RefCell::new(5); + /// c.update(|n| n + 1); + /// + /// assert_eq!(c, RefCell::new(6)); + /// ``` + #[unstable(feature = "refcell_update", issue = "38741")] + #[inline] + pub fn update (&self, f: F) where F: Fn(&T) -> T { + let mut x = self.borrow_mut(); + *x = f(&x); + } } impl RefCell { @@ -741,6 +765,30 @@ impl RefCell { &mut *self.value.get() } } + + /// Updates the underlying data by applying the supplied function, which is expected to mutate + /// the data. + /// + /// This lets you treat an update atomically, which helps prevent accidentally borrowing the + /// data twice, avoiding possible panics. + /// + /// # Examples + /// + /// ``` + /// #![feature(refcell_update)] + /// use std::cell::RefCell; + /// + /// let c = RefCell::new(5); + /// c.update_in_place(|n| *n += 1); + /// + /// assert_eq!(c, RefCell::new(6)); + /// ``` + #[unstable(feature = "refcell_update", issue = "38741")] + #[inline] + pub fn update_in_place (&self, f: F) where F: Fn(&mut T) { + let mut x = self.borrow_mut(); + f(&mut x); + } } #[stable(feature = "rust1", since = "1.0.0")]