feat: from_array for ExactSlice

This commit is contained in:
Leonora Tindall 2021-09-10 15:39:21 -05:00
parent 620f926fdd
commit 50bca2ae86
Signed by: nora
GPG Key ID: 7A8B52EC67E09AAF
2 changed files with 38 additions and 1 deletions

5
Cargo.lock generated Normal file
View File

@ -0,0 +1,5 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
[[package]]
name = "nslice"
version = "0.1.0"

View File

@ -82,6 +82,16 @@ impl<T, const N: usize> MinSlice<T, N> {
} }
impl<T, const N: usize> ExactSlice<T, N> { impl<T, const N: usize> ExactSlice<T, N> {
/// Produce a `&ExactSlice` from an array of `N` `T`s.
pub fn from_array(array: &[T; N]) -> &ExactSlice<T, N> {
unsafe { Self::from_slice_unchecked(&array[..]) }
}
/// Produce a `&mut ExactSlice` from an array of `N` `T`s.
pub fn from_mut_array(array: &mut [T; N]) -> &mut ExactSlice<T, N> {
unsafe { Self::from_mut_unchecked(&mut array[..]) }
}
/// Produce an `&ExactSlice` from a slice of `T`s. /// Produce an `&ExactSlice` from a slice of `T`s.
/// Returns `None` if there are not the correct number of elements in `slice`. /// Returns `None` if there are not the correct number of elements in `slice`.
pub fn from_slice(slice: &[T]) -> Option<&ExactSlice<T, N>> { pub fn from_slice(slice: &[T]) -> Option<&ExactSlice<T, N>> {
@ -142,7 +152,6 @@ fn basic_min_success() {
assert_eq!(minslice.tail[2], 6); assert_eq!(minslice.tail[2], 6);
} }
#[test] #[test]
fn basic_min_failure() { fn basic_min_failure() {
let slice = &[1, 2, 3, 4, 5, 6]; let slice = &[1, 2, 3, 4, 5, 6];
@ -150,3 +159,26 @@ fn basic_min_failure() {
assert!(minslice.is_none()); assert!(minslice.is_none());
} }
#[test]
fn basic_exact_success() {
let slice = &[1, 2, 3, 4, 5, 6];
let exactslice: &ExactSlice<_, 6> = ExactSlice::from_slice(slice).unwrap();
assert_eq!(exactslice.head[0], 1);
}
#[test]
fn basic_exact_failure() {
let slice = &[1, 2, 3, 4, 5, 6];
let exactslice: Option<&ExactSlice<_, 3>> = ExactSlice::from_slice(slice);
assert!(exactslice.is_none());
}
#[test]
fn array_exact_success() {
let array = [1, 2, 3, 4, 5, 6];
let exactslice: &ExactSlice<_, 6> = ExactSlice::from_array(&array);
assert_eq!(exactslice.head[0], 1);
assert_eq!(exactslice.head[5], 6);
}