Skip to content

Commit e2ba791

Browse files
author
Peter
committed
Added RefCell methods update and update_in_place
1 parent ca0cc27 commit e2ba791

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

src/libcore/cell.rs

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -489,6 +489,30 @@ impl<T> RefCell<T> {
489489
debug_assert!(self.borrow.get() == UNUSED);
490490
unsafe { self.value.into_inner() }
491491
}
492+
493+
/// Updates the underlying data by applying the supplied function, which must return a new
494+
/// value without mutating the old value.
495+
///
496+
/// This lets you treat an update atomically, which helps prevent accidentally borrowing the
497+
/// data twice, avoiding possible panics.
498+
///
499+
/// # Examples
500+
///
501+
/// ```
502+
/// #![feature(refcell_update)]
503+
/// use std::cell::RefCell;
504+
///
505+
/// let c = RefCell::new(5);
506+
/// c.update(|n| n + 1);
507+
///
508+
/// assert_eq!(c, RefCell::new(6));
509+
/// ```
510+
#[unstable(feature = "refcell_update", issue = "38741")]
511+
#[inline]
512+
pub fn update<F> (&self, f: F) where F: Fn(&T) -> T {
513+
let mut x = self.borrow_mut();
514+
*x = f(&x);
515+
}
492516
}
493517

494518
impl<T: ?Sized> RefCell<T> {
@@ -741,6 +765,30 @@ impl<T: ?Sized> RefCell<T> {
741765
&mut *self.value.get()
742766
}
743767
}
768+
769+
/// Updates the underlying data by applying the supplied function, which is expected to mutate
770+
/// the data.
771+
///
772+
/// This lets you treat an update atomically, which helps prevent accidentally borrowing the
773+
/// data twice, avoiding possible panics.
774+
///
775+
/// # Examples
776+
///
777+
/// ```
778+
/// #![feature(refcell_update)]
779+
/// use std::cell::RefCell;
780+
///
781+
/// let c = RefCell::new(5);
782+
/// c.update_in_place(|n| *n += 1);
783+
///
784+
/// assert_eq!(c, RefCell::new(6));
785+
/// ```
786+
#[unstable(feature = "refcell_update", issue = "38741")]
787+
#[inline]
788+
pub fn update_in_place<F> (&self, f: F) where F: Fn(&mut T) {
789+
let mut x = self.borrow_mut();
790+
f(&mut x);
791+
}
744792
}
745793

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

0 commit comments

Comments
 (0)