Skip to content
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
38 changes: 26 additions & 12 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<T, U>`, 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<T, U>`, 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
Expand Down Expand Up @@ -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<T, U> Array<MaybeUninit<T>, U>
Expand Down
10 changes: 10 additions & 0 deletions tests/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -144,3 +144,13 @@ fn clone_from_slice() {
let array = Array::<u8, U6>::clone_from_slice(EXAMPLE_SLICE);
assert_eq!(array.as_slice(), EXAMPLE_SLICE);
}

#[test]
fn slice_as_flattened() {
let slice: &mut [Array<u8, U4>] = &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]);
}