const generic expr based fixed length array manipulation crate
array flatten
bendn 2024-03-25
parent 0dcf26d · commit e6ef24d
-rw-r--r--Cargo.toml2
-rw-r--r--src/lib.rs34
2 files changed, 34 insertions, 2 deletions
diff --git a/Cargo.toml b/Cargo.toml
index 3c615c8..fec07da 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "atools"
-version = "0.1.1"
+version = "0.1.2"
edition = "2021"
description = "const generic expr based fixed length array manipulation"
authors = ["bend-n <[email protected]>"]
diff --git a/src/lib.rs b/src/lib.rs
index dcc52d9..80eeede 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -29,7 +29,7 @@ pub mod prelude {
#[doc(inline)]
pub use super::{
pervasive::prelude::*, range, splat, Array, ArrayTools, Chunked, CollectArray, Couple,
- DropFront, Join, Pop, Trunc, Tuple,
+ DropFront, Flatten, Join, Pop, Trunc, Tuple,
};
#[doc(inline)]
pub use core::array::from_fn;
@@ -226,6 +226,38 @@ impl<const N: usize, T> Chunked<T, N> for [T; N] {
}
}
+/// Flatten arrays.
+pub trait Flatten<T, const N: usize, const N2: usize> {
+ /// Takes a `[[T; N]; N2]`, and flattens it to a `[T; N * N2]`.
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// # #![feature(generic_const_exprs)]
+ /// # use atools::prelude::*;
+ /// assert_eq!([[1, 2, 3], [4, 5, 6]].flatten(), [1, 2, 3, 4, 5, 6]);
+ ///
+ /// assert_eq!(
+ /// [[1, 2, 3], [4, 5, 6]].flatten(),
+ /// [[1, 2], [3, 4], [5, 6]].flatten(),
+ /// );
+ ///
+ /// let array_of_empty_arrays: [[i32; 0]; 5] = [[], [], [], [], []];
+ /// assert!(array_of_empty_arrays.flatten().is_empty());
+ ///
+ /// let empty_array_of_arrays: [[u32; 10]; 0] = [];
+ /// assert!(empty_array_of_arrays.flatten().is_empty());
+ /// ```
+ fn flatten(self) -> [T; N * N2];
+}
+
+impl<T, const N: usize, const N2: usize> Flatten<T, N, N2> for [[T; N]; N2] {
+ fn flatten(self) -> [T; N * N2] {
+ // SAFETY: layout is the same.
+ unsafe { core::intrinsics::transmute_unchecked(self) }
+ }
+}
+
/// Array tools.
pub trait ArrayTools<T, const N: usize> {
/// Skip `BY` elements.