Skip to content

Commit

Permalink
Impl From<Array<T, U>> for [T; N] generically (#1010)
Browse files Browse the repository at this point in the history
Uses a const generic implementation bounded on `ArrayOps<T, N>` rather
than using a macro to write a separate one for each array size.
  • Loading branch information
tarcieri authored Dec 31, 2023
1 parent 5669e29 commit fc5d614
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 7 deletions.
6 changes: 0 additions & 6 deletions hybrid-array/src/impls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -75,12 +75,6 @@ macro_rules! impl_array_size {
impl<T> AssociatedArraySize for Array<T, typenum::$ty> {
type Size = typenum::$ty;
}

impl<T> From<Array<T, typenum::$ty>> for [T; $len] {
fn from(arr: Array<T, typenum::$ty>) -> [T; $len] {
arr.0
}
}
)+
};
}
Expand Down
15 changes: 14 additions & 1 deletion hybrid-array/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -348,6 +348,18 @@ where
}
}

impl<T, U, const N: usize> From<Array<T, U>> for [T; N]
where
Array<T, U>: ArrayOps<T, N>,
U: ArraySize,
{
#[inline]
fn from(arr: Array<T, U>) -> [T; N] {
let mut items = arr.0.into_iter();
core::array::from_fn(|_| items.next().expect("should always have item"))
}
}

impl<'a, T, U, const N: usize> From<&'a [T; N]> for &'a Array<T, U>
where
Array<T, U>: ArrayOps<T, N>,
Expand Down Expand Up @@ -543,6 +555,7 @@ pub trait ArrayOps<T, const N: usize>:
+ Borrow<[T; N]>
+ BorrowMut<[T; N]>
+ From<[T; N]>
+ FromFn<T>
+ Into<[T; N]>
+ IntoIterator<Item = T>
+ Sized
Expand Down Expand Up @@ -616,8 +629,8 @@ impl<T, U: ArraySize> SliceOps<T> for Array<T, U> {}
pub unsafe trait ArraySize: Unsigned {
/// Array type which corresponds to this size.
type ArrayType<T>: AssociatedArraySize<Size = Self>
+ FromFn<T>
+ From<Array<T, Self>>
+ FromFn<T>
+ Into<Array<T, Self>>
+ IntoIterator<Item = T>
+ SliceOps<T>;
Expand Down

0 comments on commit fc5d614

Please sign in to comment.