Skip to content

Commit

Permalink
Rollup merge of #91086 - rhysd:issue-91085, r=m-ou-se
Browse files Browse the repository at this point in the history
Implement `TryFrom<&'_ mut [T]>` for `[T; N]`

Fixes #91085.
  • Loading branch information
matthiaskrgr authored Dec 12, 2021
2 parents 6bda5b3 + 16711fe commit 42f8d48
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 1 deletion.
12 changes: 12 additions & 0 deletions library/core/src/array/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,18 @@ where
}
}

#[stable(feature = "try_from_mut_slice_to_array", since = "1.59.0")]
impl<T, const N: usize> TryFrom<&mut [T]> for [T; N]
where
T: Copy,
{
type Error = TryFromSliceError;

fn try_from(slice: &mut [T]) -> Result<[T; N], TryFromSliceError> {
<Self>::try_from(&*slice)
}
}

#[stable(feature = "try_from", since = "1.34.0")]
impl<'a, T, const N: usize> TryFrom<&'a [T]> for &'a [T; N] {
type Error = TryFromSliceError;
Expand Down
13 changes: 12 additions & 1 deletion library/core/tests/array.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,11 +28,22 @@ fn array_try_from() {
($($N:expr)+) => {
$({
type Array = [u8; $N];
let array: Array = [0; $N];
let mut array: Array = [0; $N];
let slice: &[u8] = &array[..];

let result = <&Array>::try_from(slice);
assert_eq!(&array, result.unwrap());

let result = <Array>::try_from(slice);
assert_eq!(&array, &result.unwrap());

let mut_slice: &mut [u8] = &mut array[..];
let result = <&mut Array>::try_from(mut_slice);
assert_eq!(&[0; $N], result.unwrap());

let mut_slice: &mut [u8] = &mut array[..];
let result = <Array>::try_from(mut_slice);
assert_eq!(&array, &result.unwrap());
})+
}
}
Expand Down

0 comments on commit 42f8d48

Please sign in to comment.