about summary refs log tree commit diff
path: root/src/libcore/option.rs
diff options
context:
space:
mode:
authorTaylor Cramer <cramertj@google.com>2018-01-04 11:34:03 -0800
committerTaylor Cramer <cramertj@google.com>2018-01-10 17:42:47 -0800
commitc9ae249265c5da207ba0d8a2f8be95e58817e1dc (patch)
treec56ad0103df2c2fafe1eaaef4f7f53286d897f25 /src/libcore/option.rs
parent8e7a609e635b728eba65d471c985ab462dc4cfc7 (diff)
downloadrust-c9ae249265c5da207ba0d8a2f8be95e58817e1dc.tar.gz
rust-c9ae249265c5da207ba0d8a2f8be95e58817e1dc.zip
Add transpose conversions for Option and Result
These impls are useful when working with combinator
methods that expect an option or a result, but you
have a Result<Option<T>, E> instead of an Option<Result<T, E>>
or vice versa.
Diffstat (limited to 'src/libcore/option.rs')
-rw-r--r--src/libcore/option.rs29
1 files changed, 29 insertions, 0 deletions
diff --git a/src/libcore/option.rs b/src/libcore/option.rs
index d8f3ec38cf3..76cea587038 100644
--- a/src/libcore/option.rs
+++ b/src/libcore/option.rs
@@ -884,6 +884,35 @@ impl<T: Default> Option<T> {
     }
 }
 
+impl<T, E> Option<Result<T, E>> {
+    /// Transposes an `Option` of a `Result` into a `Result` of an `Option`.
+    ///
+    /// `None` will be mapped to `Ok(None)`.
+    /// `Some(Ok(_))` and `Some(Err(_))` will be mapped to `Ok(Some(_))` and `Err(_)`.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// #![feature(transpose_result)]
+    ///
+    /// #[derive(Debug, Eq, PartialEq)]
+    /// struct SomeErr;
+    ///
+    /// let x: Result<Option<i32>, SomeErr> = Ok(Some(5));
+    /// let y: Option<Result<i32, SomeErr>> = Some(Ok(5));
+    /// assert_eq!(x, y.transpose());
+    /// ```
+    #[inline]
+    #[unstable(feature = "transpose_result", issue = "47338")]
+    pub fn transpose(self) -> Result<Option<T>, E> {
+        match self {
+            Some(Ok(x)) => Ok(Some(x)),
+            Some(Err(e)) => Err(e),
+            None => Ok(None),
+        }
+    }
+}
+
 // This is a separate function to reduce the code size of .expect() itself.
 #[inline(never)]
 #[cold]