Skip to content

Commit 54e685d

Browse files
lilyballthestinger
authored andcommitted
option: mutate() and mutate_default() should return bool
Fixes #8047.
1 parent 1f9c392 commit 54e685d

File tree

2 files changed

+25
-6
lines changed

2 files changed

+25
-6
lines changed

src/librustc/middle/trans/_match.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1159,7 +1159,7 @@ fn store_non_ref_bindings(bcx: @mut Block,
11591159
add_clean_temp_mem(bcx, lldest, binding_info.ty);
11601160
temp_cleanups.push(lldest);
11611161
temp_cleanups
1162-
}
1162+
};
11631163
}
11641164
TrByRef => {}
11651165
}

src/libstd/option.rs

Lines changed: 24 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -235,19 +235,24 @@ impl<T> Option<T> {
235235
self.take().map_consume_default(def, blk)
236236
}
237237

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 {
240241
if self.is_some() {
241242
*self = Some(f(self.take_unwrap()));
242-
}
243+
true
244+
} else { false }
243245
}
244246

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 {
247250
if self.is_some() {
248251
*self = Some(f(self.take_unwrap()));
252+
true
249253
} else {
250254
*self = Some(def);
255+
false
251256
}
252257
}
253258

@@ -575,4 +580,18 @@ mod tests {
575580
assert_eq!(it.size_hint(), (0, Some(0)));
576581
assert!(it.next().is_none());
577582
}
583+
584+
#[test]
585+
fn test_mutate() {
586+
let mut x = Some(3i);
587+
assert!(x.mutate(|i| i+1));
588+
assert_eq!(x, Some(4i));
589+
assert!(x.mutate_default(0, |i| i+1));
590+
assert_eq!(x, Some(5i));
591+
x = None;
592+
assert!(!x.mutate(|i| i+1));
593+
assert_eq!(x, None);
594+
assert!(!x.mutate_default(0i, |i| i+1));
595+
assert_eq!(x, Some(0i));
596+
}
578597
}

0 commit comments

Comments
 (0)