From ac85bf356f3674ed0e0e79668b384141d38e0efe Mon Sep 17 00:00:00 2001 From: Daniel Micay Date: Sun, 13 Jan 2013 11:09:09 -0500 Subject: [PATCH] add Option methods for in-place mutation --- src/libcore/option.rs | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/src/libcore/option.rs b/src/libcore/option.rs index 3fb2acd3480..40c6315bfe9 100644 --- a/src/libcore/option.rs +++ b/src/libcore/option.rs @@ -284,6 +284,22 @@ impl Option { match self { None => def, Some(v) => f(v) } } + /// Apply a function to the contained value or do nothing + fn mutate(&mut self, f: fn(T) -> T) { + if self.is_some() { + *self = Some(f(self.swap_unwrap())); + } + } + + /// Apply a function to the contained value or set it to a default + fn mutate_default(&mut self, def: T, f: fn(T) -> T) { + if self.is_some() { + *self = Some(f(self.swap_unwrap())); + } else { + *self = Some(def); + } + } + /// Performs an operation on the contained value by reference #[inline(always)] pure fn iter(&self, f: fn(x: &T)) { iter(self, f) }