@@ -235,19 +235,24 @@ impl<T> Option<T> {
235
235
self . take ( ) . map_consume_default ( def, blk)
236
236
}
237
237
238
- /// Apply a function to the contained value or do nothing
239
- pub fn mutate ( & mut self , f : & fn ( T ) -> T ) {
238
+ /// Apply a function to the contained value or do nothing.
239
+ /// Returns true if the contained value was mutated.
240
+ pub fn mutate ( & mut self , f : & fn ( T ) -> T ) -> bool {
240
241
if self . is_some ( ) {
241
242
* self = Some ( f ( self . take_unwrap ( ) ) ) ;
242
- }
243
+ true
244
+ } else { false }
243
245
}
244
246
245
- /// Apply a function to the contained value or set it to a default
246
- pub fn mutate_default ( & mut self , def : T , f : & fn ( T ) -> T ) {
247
+ /// Apply a function to the contained value or set it to a default.
248
+ /// Returns true if the contained value was mutated, or false if set to the default.
249
+ pub fn mutate_default ( & mut self , def : T , f : & fn ( T ) -> T ) -> bool {
247
250
if self . is_some ( ) {
248
251
* self = Some ( f ( self . take_unwrap ( ) ) ) ;
252
+ true
249
253
} else {
250
254
* self = Some ( def) ;
255
+ false
251
256
}
252
257
}
253
258
@@ -575,4 +580,18 @@ mod tests {
575
580
assert_eq ! ( it. size_hint( ) , ( 0 , Some ( 0 ) ) ) ;
576
581
assert ! ( it. next( ) . is_none( ) ) ;
577
582
}
583
+
584
+ #[ test]
585
+ fn test_mutate ( ) {
586
+ let mut x = Some ( 3 i) ;
587
+ assert ! ( x. mutate( |i| i+1 ) ) ;
588
+ assert_eq ! ( x, Some ( 4 i) ) ;
589
+ assert ! ( x. mutate_default( 0 , |i| i+1 ) ) ;
590
+ assert_eq ! ( x, Some ( 5 i) ) ;
591
+ x = None ;
592
+ assert ! ( !x. mutate( |i| i+1 ) ) ;
593
+ assert_eq ! ( x, None ) ;
594
+ assert ! ( !x. mutate_default( 0 i, |i| i+1 ) ) ;
595
+ assert_eq ! ( x, Some ( 0 i) ) ;
596
+ }
578
597
}
0 commit comments