From c9ae249265c5da207ba0d8a2f8be95e58817e1dc Mon Sep 17 00:00:00 2001 From: Taylor Cramer Date: Thu, 4 Jan 2018 11:34:03 -0800 Subject: 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, E> instead of an Option> or vice versa. --- src/libcore/option.rs | 29 +++++++++++++++++++++++++++++ src/libcore/result.rs | 29 +++++++++++++++++++++++++++++ 2 files changed, 58 insertions(+) (limited to 'src/libcore') 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 Option { } } +impl Option> { + /// 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, SomeErr> = Ok(Some(5)); + /// let y: Option> = Some(Ok(5)); + /// assert_eq!(x, y.transpose()); + /// ``` + #[inline] + #[unstable(feature = "transpose_result", issue = "47338")] + pub fn transpose(self) -> Result, 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] diff --git a/src/libcore/result.rs b/src/libcore/result.rs index 2ace3d2aee8..3801db94e15 100644 --- a/src/libcore/result.rs +++ b/src/libcore/result.rs @@ -909,6 +909,35 @@ impl Result { } } +impl Result, E> { + /// Transposes a `Result` of an `Option` into an `Option` of a `Result`. + /// + /// `Ok(None)` will be mapped to `None`. + /// `Ok(Some(_))` and `Err(_)` will be mapped to `Some(Ok(_))` and `Some(Err(_))`. + /// + /// # Examples + /// + /// ``` + /// #![feature(transpose_result)] + /// + /// #[derive(Debug, Eq, PartialEq)] + /// struct SomeErr; + /// + /// let x: Result, SomeErr> = Ok(Some(5)); + /// let y: Option> = Some(Ok(5)); + /// assert_eq!(x.transpose(), y); + /// ``` + #[inline] + #[unstable(feature = "transpose_result", issue = "47338")] + pub fn transpose(self) -> Option> { + match self { + Ok(Some(x)) => Some(Ok(x)), + Ok(None) => None, + Err(e) => Some(Err(e)), + } + } +} + // This is a separate function to reduce the code size of the methods #[inline(never)] #[cold] -- cgit 1.4.1-3-g733a5