Skip to content

Added RefCell methods update and update_in_place #38741

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

Closed
wants to merge 1 commit into from
Closed
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
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