diff --git a/src/lib.rs b/src/lib.rs index 15bab70..e14319b 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -331,6 +331,32 @@ where } } + /// Obtain a flattened slice from a slice of array chunks. + #[inline] + pub const fn slice_as_flattened(slice: &[Self]) -> &[T] { + let len = slice + .len() + .checked_mul(U::USIZE) + .expect("slice len overflow"); + + // SAFETY: `[T]` is layout-identical to `Array`, which is a `repr(transparent)` + // newtype for `[T; N]`. + unsafe { slice::from_raw_parts(slice.as_ptr().cast(), len) } + } + + /// Obtain a mutable flattened slice from a mutable slice of array chunks. + #[inline] + pub const fn slice_as_flattened_mut(slice: &mut [Self]) -> &mut [T] { + let len = slice + .len() + .checked_mul(U::USIZE) + .expect("slice len overflow"); + + // SAFETY: `[T]` is layout-identical to `Array`, which is a `repr(transparent)` + // newtype for `[T; N]`. + unsafe { slice::from_raw_parts_mut(slice.as_mut_ptr().cast(), len) } + } + /// Convert the given slice into a reference to a hybrid array. /// /// # Panics @@ -400,18 +426,6 @@ where // SAFETY: `Self` is a `repr(transparent)` newtype for `[T; N]` unsafe { slice::from_raw_parts_mut(slice.as_mut_ptr().cast(), slice.len()) } } - - /// Obtain a flattened slice from a slice of array chunks. - #[inline] - pub fn slice_as_flattened(slice: &[Self]) -> &[T] { - Self::cast_slice_to_core(slice).as_flattened() - } - - /// Obtain a mutable flattened slice from a mutable slice of array chunks. - #[inline] - pub fn slice_as_flattened_mut(slice: &mut [Self]) -> &mut [T] { - Self::cast_slice_to_core_mut(slice).as_flattened_mut() - } } impl Array, U> diff --git a/tests/mod.rs b/tests/mod.rs index 3ecf313..aad7cd3 100644 --- a/tests/mod.rs +++ b/tests/mod.rs @@ -144,3 +144,13 @@ fn clone_from_slice() { let array = Array::::clone_from_slice(EXAMPLE_SLICE); assert_eq!(array.as_slice(), EXAMPLE_SLICE); } + +#[test] +fn slice_as_flattened() { + let slice: &mut [Array] = &mut [Array([1, 2, 3, 4]), Array([5, 6, 7, 8])]; + assert_eq!( + Array::slice_as_flattened_mut(slice), + &mut [1, 2, 3, 4, 5, 6, 7, 8] + ); + assert_eq!(Array::slice_as_flattened(slice), &[1, 2, 3, 4, 5, 6, 7, 8]); +}