Skip to content

Commit

Permalink
Auto merge of rust-lang#130829 - Urgau:option_array_transpose, r=ibra…
Browse files Browse the repository at this point in the history
…heemdev

Add `[Option<T>; N]::transpose`

This PR as a new unstable libs API, `[Option<T>; N]::transpose`, which permits going from `[Option<T>; N]` to `Option<[T; N]>`.

This new API doesn't have an ACP as it was directly asked by T-libs-api in rust-lang#97601 (comment):

> [..] but it'd be trivial to provide a helper method `.transpose()` that turns array-of-Option into Option-of-array (**and we think that method should exist**; it already does for array-of-MaybeUninit).

r? libs
  • Loading branch information
bors committed Oct 2, 2024
2 parents 7c896fc + 0580e66 commit a7d53da
Showing 1 changed file with 24 additions and 0 deletions.
24 changes: 24 additions & 0 deletions core/src/option.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2543,3 +2543,27 @@ impl<T> Option<Option<T>> {
}
}
}

impl<T, const N: usize> [Option<T>; N] {
/// Transposes a `[Option<T>; N]` into a `Option<[T; N]>`.
///
/// # Examples
///
/// ```
/// #![feature(option_array_transpose)]
/// # use std::option::Option;
///
/// let data = [Some(0); 1000];
/// let data: Option<[u8; 1000]> = data.transpose();
/// assert_eq!(data, Some([0; 1000]));
///
/// let data = [Some(0), None];
/// let data: Option<[u8; 2]> = data.transpose();
/// assert_eq!(data, None);
/// ```
#[inline]
#[unstable(feature = "option_array_transpose", issue = "130828")]
pub fn transpose(self) -> Option<[T; N]> {
self.try_map(core::convert::identity)
}
}

0 comments on commit a7d53da

Please sign in to comment.