Skip to content

Commit

Permalink
hybrid-array: make ArrayOps better resemble core arrays (#1003)
Browse files Browse the repository at this point in the history
...and asserts as much by impl'ing the trait for core arrays.

The main notable change is bounding on `AsRef<[T]>`/`AsMut<[T]>`, which
core arrays do impl, however they *don't* actually impl
`AsRef<[T; N]>`/`AsMut<[T; N]>`.

Those impls are retained on `Array`, but new ones added for
`AsRef<[T]>`/`AsMut<[T]>`, providing better parity with core arrays.
  • Loading branch information
tarcieri authored Dec 30, 2023
1 parent 11f631c commit 3a5f07c
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 2 deletions.
41 changes: 41 additions & 0 deletions hybrid-array/src/impls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -166,3 +166,44 @@ impl_array_size! {
4096 => U4096,
8192 => U8192
}

impl<T, const N: usize> ArrayOps<T, N> for [T; N]
where
Self: IntoArray<T>,
{
const SIZE: usize = N;
type Size = <Self as IntoArray<T>>::Size;

#[inline]
fn as_core_array(&self) -> &[T; N] {
self
}

#[inline]
fn as_mut_core_array(&mut self) -> &mut [T; N] {
self
}

#[inline]
fn from_core_array(arr: [T; N]) -> Self {
arr
}

#[inline]
fn ref_from_core_array(array_ref: &[T; N]) -> &Self {
array_ref
}

#[inline]
fn ref_from_mut_core_array(array_ref: &mut [T; N]) -> &mut Self {
array_ref
}

#[inline]
fn map_to_core_array<F, U>(self, f: F) -> [U; N]
where
F: FnMut(T) -> U,
{
self.map(f)
}
}
25 changes: 23 additions & 2 deletions hybrid-array/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -204,6 +204,16 @@ where
}
}

impl<T, U> AsRef<[T]> for Array<T, U>
where
U: ArraySize,
{
#[inline]
fn as_ref(&self) -> &[T] {
self.0.as_ref()
}
}

impl<T, U, const N: usize> AsRef<[T; N]> for Array<T, U>
where
Self: ArrayOps<T, N>,
Expand All @@ -215,6 +225,16 @@ where
}
}

impl<T, U> AsMut<[T]> for Array<T, U>
where
U: ArraySize,
{
#[inline]
fn as_mut(&mut self) -> &mut [T] {
self.0.as_mut()
}
}

impl<T, U, const N: usize> AsMut<[T; N]> for Array<T, U>
where
Self: ArrayOps<T, N>,
Expand Down Expand Up @@ -516,15 +536,16 @@ fn check_slice_length<T, U: ArraySize>(slice: &[T]) -> Result<(), TryFromSliceEr

/// Array operations which are const generic over a given array size.
pub trait ArrayOps<T, const N: usize>:
AsRef<[T; N]>
+ AsMut<[T; N]>
AsRef<[T]>
+ AsMut<[T]>
+ Borrow<[T; N]>
+ BorrowMut<[T; N]>
+ From<[T; N]>
+ Index<usize>
+ Index<Range<usize>>
+ IndexMut<usize>
+ IndexMut<Range<usize>>
+ Into<[T; N]>
+ IntoIterator
+ Sized
{
Expand Down

0 comments on commit 3a5f07c

Please sign in to comment.