File tree Expand file tree Collapse file tree 2 files changed +35
-0
lines changed Expand file tree Collapse file tree 2 files changed +35
-0
lines changed Original file line number Diff line number Diff line change @@ -256,6 +256,30 @@ impl<T:Copy> Cell<T> {
256
256
pub fn get ( & self ) -> T {
257
257
unsafe { * self . value . get ( ) }
258
258
}
259
+
260
+ /// Applies a function to the contained value.
261
+ ///
262
+ /// # Examples
263
+ ///
264
+ /// ```
265
+ /// use std::cell::Cell;
266
+ ///
267
+ /// let c = Cell::new(5);
268
+ /// c.update(|x| x + 1);
269
+ ///
270
+ /// assert_eq!(c.get(), 6);
271
+ /// ```
272
+ #[ inline]
273
+ #[ unstable( feature = "cell_update" , issue = "0" ) ] // TODO: issue
274
+ pub fn update < F > ( & self , f : F ) -> T
275
+ where
276
+ F : FnOnce ( T ) -> T ,
277
+ {
278
+ let old = self . get ( ) ;
279
+ let new = f ( old) ;
280
+ self . set ( new) ;
281
+ new
282
+ }
259
283
}
260
284
261
285
#[ stable( feature = "rust1" , since = "1.0.0" ) ]
Original file line number Diff line number Diff line change @@ -26,6 +26,17 @@ fn smoketest_cell() {
26
26
assert ! ( y. get( ) == ( 30 , 40 ) ) ;
27
27
}
28
28
29
+ #[ test]
30
+ fn cell_update ( ) {
31
+ let x = Cell :: new ( 10 ) ;
32
+
33
+ assert_eq ! ( x. update( |x| x + 5 ) , 15 ) ;
34
+ assert_eq ! ( x. get( ) , 15 ) ;
35
+
36
+ assert_eq ! ( x. update( |x| x / 3 ) , 5 ) ;
37
+ assert_eq ! ( x. get( ) , 5 ) ;
38
+ }
39
+
29
40
#[ test]
30
41
fn cell_has_sensible_show ( ) {
31
42
let x = Cell :: new ( "foo bar" ) ;
You can’t perform that action at this time.
0 commit comments