Skip to content

Commit

Permalink
Merge pull request fizyk20#104 from Robbepop/add-from-ref-impls
Browse files Browse the repository at this point in the history
Add From<&[T;N]> and From<&mut [T; N]> impls for &[mut] GenericArray
  • Loading branch information
novacrazy authored Jun 25, 2020
2 parents 1a55462 + fc0e3ee commit 8c5c0bf
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 deletions.
14 changes: 14 additions & 0 deletions src/impls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,20 @@ macro_rules! impl_from {
}
}

impl<'a, T> From<&'a [T; $n]> for &'a GenericArray<T, $ty> {
#[inline]
fn from(slice: &[T; $n]) -> &GenericArray<T, $ty> {
unsafe { &*(slice.as_ptr() as *const GenericArray<T, $ty>) }
}
}

impl<'a, T> From<&'a mut [T; $n]> for &'a mut GenericArray<T, $ty> {
#[inline]
fn from(slice: &mut [T; $n]) -> &mut GenericArray<T, $ty> {
unsafe { &mut *(slice.as_mut_ptr() as *mut GenericArray<T, $ty>) }
}
}

#[cfg(not(relaxed_coherence))]
impl<T> Into<[T; $n]> for GenericArray<T, $ty> {
#[inline(always)]
Expand Down
17 changes: 17 additions & 0 deletions tests/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -351,3 +351,20 @@ fn test_as_mut() {
assert_eq!(a_mut, &mut [1, 2, 0, 4]);
assert_eq!(a, arr![i32; 1, 2, 0, 4]);
}

#[test]
fn test_from_array_ref() {
let mut a = arr![i32; 1, 2, 3, 4];
let a_ref: &[i32; 4] = a.as_ref();
let a_from: &GenericArray<i32, U4> = a_ref.into();
assert_eq!(&a, a_from);
}

#[test]
fn test_from_array_mut() {
let mut a = arr![i32; 1, 2, 3, 4];
let mut a_copy = a;
let a_mut: &mut [i32; 4] = a.as_mut();
let a_from: &mut GenericArray<i32, U4> = a_mut.into();
assert_eq!(&mut a_copy, a_from);
}

0 comments on commit 8c5c0bf

Please sign in to comment.