Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<T, N> GenericArray<T, N>
where
N: ArrayLength<T>,
Expand All @@ -541,13 +546,39 @@ 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<T, N>, 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.
#[inline]
pub fn from_mut_slice(slice: &mut [T]) -> &mut GenericArray<T, N> {
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<T, N>, IncorrectLength> {
if slice.len() == N::USIZE {
Ok(Self::from_mut_slice(slice))
}
else {
Err(IncorrectLength)
}
}
}

impl<'a, T, N: ArrayLength<T>> From<&'a [T]> for &'a GenericArray<T, N> {
Expand Down