From 50bca2ae8676c3162677460a9eb935dc3a6334e5 Mon Sep 17 00:00:00 2001 From: Leonora Tindall Date: Fri, 10 Sep 2021 15:39:21 -0500 Subject: [PATCH] feat: from_array for ExactSlice --- Cargo.lock | 5 +++++ src/lib.rs | 34 +++++++++++++++++++++++++++++++++- 2 files changed, 38 insertions(+), 1 deletion(-) create mode 100644 Cargo.lock diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..42eeac7 --- /dev/null +++ b/Cargo.lock @@ -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" diff --git a/src/lib.rs b/src/lib.rs index a444568..ebde3ce 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -82,6 +82,16 @@ impl MinSlice { } impl ExactSlice { + /// Produce a `&ExactSlice` from an array of `N` `T`s. + pub fn from_array(array: &[T; N]) -> &ExactSlice { + 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 { + unsafe { Self::from_mut_unchecked(&mut array[..]) } + } + /// Produce an `&ExactSlice` from a slice of `T`s. /// Returns `None` if there are not the correct number of elements in `slice`. pub fn from_slice(slice: &[T]) -> Option<&ExactSlice> { @@ -142,7 +152,6 @@ fn basic_min_success() { assert_eq!(minslice.tail[2], 6); } - #[test] fn basic_min_failure() { let slice = &[1, 2, 3, 4, 5, 6]; @@ -150,3 +159,26 @@ fn basic_min_failure() { 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); +} +