summary refs log tree commit diff
path: root/src/libstd
diff options
context:
space:
mode:
authorErick Tryzelaar <erick.tryzelaar@gmail.com>2013-09-10 19:03:35 -0700
committerErick Tryzelaar <erick.tryzelaar@gmail.com>2013-09-12 18:54:12 -0700
commit7380b1ce7f7538ca6f6f61cc442f45e64622b902 (patch)
treec0bcbcfca6f6898f68ba1fa4185ecbcfdc6bddc6 /src/libstd
parent2bd87ad432901f3baeab2fc1f2aa8aa328f04ea7 (diff)
downloadrust-7380b1ce7f7538ca6f6f61cc442f45e64622b902.tar.gz
rust-7380b1ce7f7538ca6f6f61cc442f45e64622b902.zip
std: Add Option.unwrap_or_else and a couple tests
Diffstat (limited to 'src/libstd')
-rw-r--r--src/libstd/option.rs47
1 files changed, 47 insertions, 0 deletions
diff --git a/src/libstd/option.rs b/src/libstd/option.rs
index 84d8a3aa188..55d5cb27923 100644
--- a/src/libstd/option.rs
+++ b/src/libstd/option.rs
@@ -340,6 +340,15 @@ impl<T> Option<T> {
         }
     }
 
+    /// Returns the contained value or computes it from a closure
+    #[inline]
+    pub fn unwrap_or_else(self, f: &fn() -> T) -> T {
+        match self {
+            Some(x) => x,
+            None => f()
+        }
+    }
+
     /// Applies a function zero or more times until the result is `None`.
     #[inline]
     pub fn while_some(self, blk: &fn(v: T) -> Option<T>) {
@@ -515,6 +524,44 @@ mod tests {
     }
 
     #[test]
+    fn test_unwrap() {
+        assert_eq!(Some(1).unwrap(), 1);
+        assert_eq!(Some(~"hello").unwrap(), ~"hello");
+    }
+
+    #[test]
+    #[should_fail]
+    fn test_unwrap_fail1() {
+        let x: Option<int> = None;
+        x.unwrap();
+    }
+
+    #[test]
+    #[should_fail]
+    fn test_unwrap_fail2() {
+        let x: Option<~str> = None;
+        x.unwrap();
+    }
+
+    #[test]
+    fn test_unwrap_or() {
+        let x: Option<int> = Some(1);
+        assert_eq!(x.unwrap_or(2), 1);
+
+        let x: Option<int> = None;
+        assert_eq!(x.unwrap_or(2), 2);
+    }
+
+    #[test]
+    fn test_unwrap_or_else() {
+        let x: Option<int> = Some(1);
+        assert_eq!(x.unwrap_or_else(|| 2), 1);
+
+        let x: Option<int> = None;
+        assert_eq!(x.unwrap_or_else(|| 2), 2);
+    }
+
+    #[test]
     fn test_unwrap_or_zero() {
         let some_stuff = Some(42);
         assert_eq!(some_stuff.unwrap_or_zero(), 42);