@@ -489,6 +489,30 @@ impl<T> RefCell<T> {
489
489
debug_assert ! ( self . borrow. get( ) == UNUSED ) ;
490
490
unsafe { self . value . into_inner ( ) }
491
491
}
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
+ }
492
516
}
493
517
494
518
impl < T : ?Sized > RefCell < T > {
@@ -741,6 +765,30 @@ impl<T: ?Sized> RefCell<T> {
741
765
& mut * self . value . get ( )
742
766
}
743
767
}
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
+ }
744
792
}
745
793
746
794
#[ stable( feature = "rust1" , since = "1.0.0" ) ]
0 commit comments