Skip to content

option: mutate() and mutate_default() should return bool #8200

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/librustc/middle/trans/_match.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1159,7 +1159,7 @@ fn store_non_ref_bindings(bcx: @mut Block,
add_clean_temp_mem(bcx, lldest, binding_info.ty);
temp_cleanups.push(lldest);
temp_cleanups
}
};
}
TrByRef => {}
}
Expand Down
29 changes: 24 additions & 5 deletions src/libstd/option.rs
Original file line number Diff line number Diff line change
Expand Up @@ -235,19 +235,24 @@ impl<T> Option<T> {
self.take().map_consume_default(def, blk)
}

/// Apply a function to the contained value or do nothing
pub fn mutate(&mut self, f: &fn(T) -> T) {
/// Apply a function to the contained value or do nothing.
/// Returns true if the contained value was mutated.
pub fn mutate(&mut self, f: &fn(T) -> T) -> bool {
if self.is_some() {
*self = Some(f(self.take_unwrap()));
}
true
} else { false }
}

/// Apply a function to the contained value or set it to a default
pub fn mutate_default(&mut self, def: T, f: &fn(T) -> T) {
/// Apply a function to the contained value or set it to a default.
/// Returns true if the contained value was mutated, or false if set to the default.
pub fn mutate_default(&mut self, def: T, f: &fn(T) -> T) -> bool {
if self.is_some() {
*self = Some(f(self.take_unwrap()));
true
} else {
*self = Some(def);
false
}
}

Expand Down Expand Up @@ -575,4 +580,18 @@ mod tests {
assert_eq!(it.size_hint(), (0, Some(0)));
assert!(it.next().is_none());
}

#[test]
fn test_mutate() {
let mut x = Some(3i);
assert!(x.mutate(|i| i+1));
assert_eq!(x, Some(4i));
assert!(x.mutate_default(0, |i| i+1));
assert_eq!(x, Some(5i));
x = None;
assert!(!x.mutate(|i| i+1));
assert_eq!(x, None);
assert!(!x.mutate_default(0i, |i| i+1));
assert_eq!(x, Some(0i));
}
}