From b6a38601f91247ca38aace801cec0d311cbdd223 Mon Sep 17 00:00:00 2001 From: Nikolai Vazquez Date: Wed, 9 Aug 2023 17:57:25 -0400 Subject: [PATCH] Add `[[T; N]; M]::flatten` conversion to `[T; N * M]` --- library/core/src/array/mod.rs | 31 +++++++++++++++++++++++++++++++ library/core/src/lib.rs | 1 + 2 files changed, 32 insertions(+) diff --git a/library/core/src/array/mod.rs b/library/core/src/array/mod.rs index ebd4a8c05fe30..f95c486decfa2 100644 --- a/library/core/src/array/mod.rs +++ b/library/core/src/array/mod.rs @@ -10,6 +10,7 @@ use crate::convert::{Infallible, TryFrom}; use crate::error::Error; use crate::fmt; use crate::hash::{self, Hash}; +use crate::intrinsics; use crate::iter::UncheckedIterator; use crate::mem::{self, MaybeUninit}; use crate::ops::{ @@ -451,6 +452,36 @@ macro_rules! array_impl_default { array_impl_default! {32, T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T} +impl [[T; N]; M] { + /// Converts from `[[T; N]; M]` to `[T; N * M]`. + /// + /// # Examples + /// + /// ``` + /// #![feature(array_flattening)] + /// + /// let x: [[i32; 3]; 3] = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]; + /// assert_eq!(x.flatten(), [1, 2, 3, 4, 5, 6, 7, 8, 9]); + /// ``` + /// + /// Flattening only removes one level of nesting at a time: + /// + /// ``` + /// #![feature(array_flattening)] + /// + /// let x: [[[i32; 2]; 2]; 2] = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]; + /// assert_eq!(x.flatten(), [[1, 2], [3, 4], [5, 6], [7, 8]]); + /// assert_eq!(x.flatten().flatten(), [1, 2, 3, 4, 5, 6, 7, 8]); + /// ``` + #[inline] + #[unstable(feature = "array_flattening", issue = "none")] + #[rustc_const_unstable(feature = "const_array_flattening", issue = "none")] + pub const fn flatten(self) -> [T; N * M] { + // SAFETY: `[[T; N]; M]` and `[T; N * M]` have the same layout. + unsafe { intrinsics::transmute_unchecked(self) } + } +} + impl [T; N] { /// Returns an array of the same size as `self`, with function `f` applied to each element /// in order. diff --git a/library/core/src/lib.rs b/library/core/src/lib.rs index ded799160bf89..6681932b86f3f 100644 --- a/library/core/src/lib.rs +++ b/library/core/src/lib.rs @@ -164,6 +164,7 @@ #![feature(const_waker)] #![feature(core_panic)] #![feature(duration_consts_float)] +#![feature(generic_const_exprs)] #![feature(internal_impls_macro)] #![feature(ip)] #![feature(ip_bits)]