Skip to content

Commit

Permalink
Added RefCell methods update and update_in_place
Browse files Browse the repository at this point in the history
  • Loading branch information
Peter committed Dec 31, 2016
1 parent ca0cc27 commit e2ba791
Showing 1 changed file with 48 additions and 0 deletions.
48 changes: 48 additions & 0 deletions src/libcore/cell.rs
Original file line number Diff line number Diff line change
Expand Up @@ -489,6 +489,30 @@ impl<T> RefCell<T> {
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<F> (&self, f: F) where F: Fn(&T) -> T {
let mut x = self.borrow_mut();
*x = f(&x);
}
}

impl<T: ?Sized> RefCell<T> {
Expand Down Expand Up @@ -741,6 +765,30 @@ impl<T: ?Sized> RefCell<T> {
&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<F> (&self, f: F) where F: Fn(&mut T) {
let mut x = self.borrow_mut();
f(&mut x);
}
}

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

0 comments on commit e2ba791

Please sign in to comment.