Skip to content

Commit 8c5c0bf

Browse files
authored
Merge pull request #104 from Robbepop/add-from-ref-impls
Add From<&[T;N]> and From<&mut [T; N]> impls for &[mut] GenericArray
2 parents 1a55462 + fc0e3ee commit 8c5c0bf

File tree

2 files changed

+31
-0
lines changed

2 files changed

+31
-0
lines changed

src/impls.rs

+14
Original file line numberDiff line numberDiff line change
@@ -141,6 +141,20 @@ macro_rules! impl_from {
141141
}
142142
}
143143

144+
impl<'a, T> From<&'a [T; $n]> for &'a GenericArray<T, $ty> {
145+
#[inline]
146+
fn from(slice: &[T; $n]) -> &GenericArray<T, $ty> {
147+
unsafe { &*(slice.as_ptr() as *const GenericArray<T, $ty>) }
148+
}
149+
}
150+
151+
impl<'a, T> From<&'a mut [T; $n]> for &'a mut GenericArray<T, $ty> {
152+
#[inline]
153+
fn from(slice: &mut [T; $n]) -> &mut GenericArray<T, $ty> {
154+
unsafe { &mut *(slice.as_mut_ptr() as *mut GenericArray<T, $ty>) }
155+
}
156+
}
157+
144158
#[cfg(not(relaxed_coherence))]
145159
impl<T> Into<[T; $n]> for GenericArray<T, $ty> {
146160
#[inline(always)]

tests/mod.rs

+17
Original file line numberDiff line numberDiff line change
@@ -351,3 +351,20 @@ fn test_as_mut() {
351351
assert_eq!(a_mut, &mut [1, 2, 0, 4]);
352352
assert_eq!(a, arr![i32; 1, 2, 0, 4]);
353353
}
354+
355+
#[test]
356+
fn test_from_array_ref() {
357+
let mut a = arr![i32; 1, 2, 3, 4];
358+
let a_ref: &[i32; 4] = a.as_ref();
359+
let a_from: &GenericArray<i32, U4> = a_ref.into();
360+
assert_eq!(&a, a_from);
361+
}
362+
363+
#[test]
364+
fn test_from_array_mut() {
365+
let mut a = arr![i32; 1, 2, 3, 4];
366+
let mut a_copy = a;
367+
let a_mut: &mut [i32; 4] = a.as_mut();
368+
let a_from: &mut GenericArray<i32, U4> = a_mut.into();
369+
assert_eq!(&mut a_copy, a_from);
370+
}

0 commit comments

Comments
 (0)