Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added the Option::unzip() method #87636

Merged
merged 4 commits into from
Aug 11, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions library/core/src/option.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1399,6 +1399,33 @@ impl<T> Option<T> {
}
}

impl<T, U> 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<T>, Option<U>) {
match self {
Some((a, b)) => (Some(a), Some(b)),
None => (None, None),
}
}
}

impl<T: Copy> Option<&T> {
/// Maps an `Option<&T>` to an `Option<T>` by copying the contents of the
/// option.
Expand Down
1 change: 1 addition & 0 deletions library/core/tests/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
34 changes: 33 additions & 1 deletion library/core/tests/option.rs
Original file line number Diff line number Diff line change
Expand Up @@ -399,11 +399,43 @@ fn test_unwrap_drop() {
}

#[test]
pub fn option_ext() {
fn option_ext() {
let thing = "{{ f }}";
let f = thing.find("{{");

if f.is_none() {
println!("None!");
}
}

#[test]
fn zip_options() {
let x = Some(10);
let y = Some("foo");
let z: Option<usize> = 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));
}