From 6ea2d1afcb89d3414312521a63a591d34ae5f8dd Mon Sep 17 00:00:00 2001 From: Wesley Norris Date: Thu, 23 Jan 2020 17:58:27 -0500 Subject: [PATCH 1/2] Add From<&[T]> and From<&mut [T]> for TinyVec This adds the From trait impls for `&[T]` and `&mut [T]` to `TinyVec`, though unfortunately until we get lazy normalization, it currently requires that the `A: Array` bound also be `Default`, so it does not work for array sizes > 32. --- src/tinyvec.rs | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/src/tinyvec.rs b/src/tinyvec.rs index ab4e5e4..c28e3ad 100644 --- a/src/tinyvec.rs +++ b/src/tinyvec.rs @@ -665,6 +665,37 @@ impl From> for TinyVec { } } +impl From<&'_ [T]> for TinyVec +where + T: Clone + Default, + A: Array + Default, +{ + #[inline] + #[must_use] + fn from(slice: &[T]) -> Self { + if slice.len() > A::CAPACITY { + TinyVec::Heap(slice.into()) + } else { + let mut arr = ArrayVec::new(); + arr.extend_from_slice(slice); + + TinyVec::Inline(arr) + } + } +} + +impl From<&'_ mut [T]> for TinyVec +where + T: Clone + Default, + A: Array + Default, +{ + #[inline] + #[must_use] + fn from(slice: &mut [T]) -> Self { + Self::from(&*slice) + } +} + impl FromIterator for TinyVec { #[inline] #[must_use] From 48905d9c43c1d71185199c5e6368eab1c668a827 Mon Sep 17 00:00:00 2001 From: Wesley Norris Date: Fri, 24 Jan 2020 08:24:44 -0500 Subject: [PATCH 2/2] Add TinyVec::from(slice) test --- tests/tinyvec.rs | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/tests/tinyvec.rs b/tests/tinyvec.rs index 705ab59..617193a 100644 --- a/tests/tinyvec.rs +++ b/tests/tinyvec.rs @@ -65,3 +65,22 @@ fn TinyVec_resize() { tv.resize(20, 5); assert_eq!(&tv[..], &[5; 20]); } + +#[test] +fn TinyVec_from_slice_impl() { + let bigger_slice: [u8; 11] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; + let tinyvec: TinyVec<[u8; 10]> = TinyVec::Heap((&bigger_slice[..]).into()); + assert_eq!(TinyVec::from(&bigger_slice[..]), tinyvec); + + let smaller_slice: [u8; 5] = [0, 1, 2, 3, 4]; + let tinyvec: TinyVec<[u8; 10]> = TinyVec::Inline(ArrayVec::from_array_len( + [0, 1, 2, 3, 4, 0, 0, 0, 0, 0], + 5, + )); + assert_eq!(TinyVec::from(&smaller_slice[..]), tinyvec); + + let same_size: [u8; 4] = [0, 1, 2, 3]; + let tinyvec: TinyVec<[u8; 4]> = + TinyVec::Inline(ArrayVec::from_array_len(same_size, 4)); + assert_eq!(TinyVec::from(&same_size[..]), tinyvec); +}