diff --git a/src/lib.rs b/src/lib.rs index e66d8a65f1..a1ef4be266 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -517,6 +517,11 @@ where } } +/// Error returned from [`GenericArray::try_from_slice()`] and +/// [`GenericArray::try_from_mut_slice()`] when the length of the slice differs from +/// that of the array type. +pub struct IncorrectLength; + impl GenericArray where N: ArrayLength, @@ -541,6 +546,19 @@ where slice.into() } + /// Converts slice to a generic array reference with inferred length; + /// + /// If the length of the slice is not equal to the length of the array, returns + /// [`IncorrectLength`]. + pub fn try_from_slice(slice: &[T]) -> Result<&GenericArray, IncorrectLength> { + if slice.len() == N::USIZE { + Ok(Self::from_slice(slice)) + } + else { + Err(IncorrectLength) + } + } + /// Converts mutable slice to a mutable generic array reference /// /// Length of the slice must be equal to the length of the array. @@ -548,6 +566,19 @@ where pub fn from_mut_slice(slice: &mut [T]) -> &mut GenericArray { slice.into() } + + /// Converts mutable slice to a mutable generic array reference + /// + /// If the length of the slice is not equal to the length of the array, returns + /// [`IncorrectLength`]. + pub fn try_from_mut_slice(slice: &mut [T]) -> Result<&mut GenericArray, IncorrectLength> { + if slice.len() == N::USIZE { + Ok(Self::from_mut_slice(slice)) + } + else { + Err(IncorrectLength) + } + } } impl<'a, T, N: ArrayLength> From<&'a [T]> for &'a GenericArray {