Skip to content

Commit

Permalink
hybrid-array: factor SliceOps out from ArrayOps (#1004)
Browse files Browse the repository at this point in the history
Factors out a trait which can be impl'd on all three of `[T]`, `[T; N]`,
and `Array<T, U>` for operations which don't need a const generic
parameter.
  • Loading branch information
tarcieri authored Dec 30, 2023
1 parent 3a5f07c commit 8646acb
Showing 1 changed file with 19 additions and 9 deletions.
28 changes: 19 additions & 9 deletions hybrid-array/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -536,18 +536,13 @@ 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]>
+ AsMut<[T]>
+ Borrow<[T; N]>
Borrow<[T; N]>
+ BorrowMut<[T; N]>
+ From<[T; N]>
+ Index<usize>
+ Index<Range<usize>>
+ IndexMut<usize>
+ IndexMut<Range<usize>>
+ Into<[T; N]>
+ IntoIterator
+ IntoIterator<Item = T>
+ Sized
+ SliceOps<T>
{
/// Size of an array as a `usize`.
///
Expand Down Expand Up @@ -581,6 +576,21 @@ pub trait ArrayOps<T, const N: usize>:
F: FnMut(T) -> U;
}

/// Slice operations which don't have access to a const generic array size.
pub trait SliceOps<T>:
AsRef<[T]>
+ AsMut<[T]>
+ Index<usize>
+ Index<Range<usize>>
+ IndexMut<usize>
+ IndexMut<Range<usize>>
{
}

impl<T> SliceOps<T> for [T] {}
impl<T, const N: usize> SliceOps<T> for [T; N] {}
impl<T, U: ArraySize> SliceOps<T> for Array<T, U> {}

/// Extension trait with helper functions for core arrays.
pub trait ArrayExt<T>: Sized {
/// Create array using the given callback function for each element.
Expand Down Expand Up @@ -629,7 +639,7 @@ impl<T, const N: usize> ArrayExt<T> for [T; N] {
/// It is implemented only for a number of types defined in [`typenum::consts`].
pub unsafe trait ArraySize: Unsigned {
/// Array type which corresponds to this size.
type ArrayType<T>: ArrayExt<T> + AsRef<[T]> + AsMut<[T]> + IntoArray<T> + IntoIterator<Item = T>;
type ArrayType<T>: ArrayExt<T> + IntoArray<T> + IntoIterator<Item = T> + SliceOps<T>;
}

/// Convert the given type into an [`Array`].
Expand Down

0 comments on commit 8646acb

Please sign in to comment.