diff --git a/library/core/src/option.rs b/library/core/src/option.rs index d4e9c384f9302..3f9f04606b36a 100644 --- a/library/core/src/option.rs +++ b/library/core/src/option.rs @@ -1399,6 +1399,33 @@ impl Option { } } +impl Option<(T, U)> { + /// Unzips an option containing a tuple of two options + /// + /// If `self` is `Some((a, b))` this method returns `(Some(a), Some(b))`. + /// Otherwise, `(None, None)` is returned. + /// + /// # Examples + /// + /// ``` + /// #![feature(unzip_option)] + /// + /// let x = Some((1, "hi")); + /// let y = None::<(u8, u32)>; + /// + /// assert_eq!(x.unzip(), (Some(1), Some("hi"))); + /// assert_eq!(y.unzip(), (None, None)); + /// ``` + #[inline] + #[unstable(feature = "unzip_option", issue = "87800", reason = "recently added")] + pub const fn unzip(self) -> (Option, Option) { + match self { + Some((a, b)) => (Some(a), Some(b)), + None => (None, None), + } + } +} + impl Option<&T> { /// Maps an `Option<&T>` to an `Option` by copying the contents of the /// option. diff --git a/library/core/tests/lib.rs b/library/core/tests/lib.rs index c7756a503c3e9..cc3527f98ec65 100644 --- a/library/core/tests/lib.rs +++ b/library/core/tests/lib.rs @@ -66,6 +66,7 @@ #![feature(slice_group_by)] #![feature(trusted_random_access)] #![feature(unsize)] +#![feature(unzip_option)] #![deny(unsafe_op_in_unsafe_fn)] extern crate test; diff --git a/library/core/tests/option.rs b/library/core/tests/option.rs index 88ea15a3b33fa..cd8fdebe36a05 100644 --- a/library/core/tests/option.rs +++ b/library/core/tests/option.rs @@ -399,7 +399,7 @@ fn test_unwrap_drop() { } #[test] -pub fn option_ext() { +fn option_ext() { let thing = "{{ f }}"; let f = thing.find("{{"); @@ -407,3 +407,35 @@ pub fn option_ext() { println!("None!"); } } + +#[test] +fn zip_options() { + let x = Some(10); + let y = Some("foo"); + let z: Option = None; + + assert_eq!(x.zip(y), Some((10, "foo"))); + assert_eq!(x.zip(z), None); + assert_eq!(z.zip(x), None); +} + +#[test] +fn unzip_options() { + let x = Some((10, "foo")); + let y = None::<(bool, i32)>; + + assert_eq!(x.unzip(), (Some(10), Some("foo"))); + assert_eq!(y.unzip(), (None, None)); +} + +#[test] +fn zip_unzip_roundtrip() { + let x = Some(10); + let y = Some("foo"); + + let z = x.zip(y); + assert_eq!(z, Some((10, "foo"))); + + let a = z.unzip(); + assert_eq!(a, (x, y)); +}