about summary refs log tree commit diff
path: root/src/libstd/option.rs
diff options
context:
space:
mode:
authorErick Tryzelaar <erick.tryzelaar@gmail.com>2013-09-11 09:33:45 -0700
committerErick Tryzelaar <erick.tryzelaar@gmail.com>2013-09-12 18:54:12 -0700
commite03d60e9ebf2dbc2d18ab9919f905c17b967fcde (patch)
treed80ca6146eb66e930b1063c6929bb1b09e90b1e6 /src/libstd/option.rs
parent12e0d7ecf061313d02a4647db8c1b30aad2ae53d (diff)
std: Add ToEither/IntoEither/AsEither
Diffstat (limited to 'src/libstd/option.rs')
-rw-r--r--src/libstd/option.rs42
1 files changed, 42 insertions, 0 deletions
diff --git a/src/libstd/option.rs b/src/libstd/option.rs
index 83bc7856098..cd9e3980716 100644
--- a/src/libstd/option.rs
+++ b/src/libstd/option.rs
@@ -44,6 +44,7 @@ let unwrapped_msg = match msg {
 use clone::Clone;
 use cmp::{Eq,Ord};
 use default::Default;
+use either;
 use util;
 use num::Zero;
 use iter;
@@ -447,6 +448,26 @@ impl<T> result::IntoResult<T, ()> for Option<T> {
     }
 }
 
+impl<T: Clone> either::ToEither<(), T> for Option<T> {
+    #[inline]
+    fn to_either(&self) -> either::Either<(), T> {
+        match *self {
+            Some(ref x) => either::Right(x.clone()),
+            None => either::Left(()),
+        }
+    }
+}
+
+impl<T> either::IntoEither<(), T> for Option<T> {
+    #[inline]
+    fn into_either(self) -> either::Either<(), T> {
+        match self {
+            Some(x) => either::Right(x),
+            None => either::Left(()),
+        }
+    }
+}
+
 impl<T: Default> Option<T> {
     /// Returns the contained value or default (for this type)
     #[inline]
@@ -529,6 +550,9 @@ impl<A> ExactSize<A> for OptionIterator<A> {}
 #[cfg(test)]
 mod tests {
     use super::*;
+
+    use either::{IntoEither, ToEither};
+    use either;
     use result::{IntoResult, ToResult};
     use result;
     use util;
@@ -817,4 +841,22 @@ mod tests {
         assert_eq!(some.into_result(), result::Ok(100));
         assert_eq!(none.into_result(), result::Err(()));
     }
+
+    #[test]
+    pub fn test_to_either() {
+        let some: Option<int> = Some(100);
+        let none: Option<int> = None;
+
+        assert_eq!(some.to_either(), either::Right(100));
+        assert_eq!(none.to_either(), either::Left(()));
+    }
+
+    #[test]
+    pub fn test_into_either() {
+        let some: Option<int> = Some(100);
+        let none: Option<int> = None;
+
+        assert_eq!(some.into_either(), either::Right(100));
+        assert_eq!(none.into_either(), either::Left(()));
+    }
 }