Skip to content

Commit

Permalink
Implement From<[T; M]> for SmallVec<T, N> for all M, N (v2) (#338)
Browse files Browse the repository at this point in the history
* Remove T: Clone bound from From<array/vec> for SmallVec

* Relax From<array> for SmallVec to allow different length arrays.
  • Loading branch information
zachs18 committed Feb 19, 2024
1 parent 8445d21 commit 74075e3
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 4 deletions.
24 changes: 20 additions & 4 deletions src/lib.rs
Expand Up @@ -1909,12 +1909,28 @@ impl<'a, T: Clone, const N: usize> From<&'a [T]> for SmallVec<T, N> {
slice.iter().cloned().collect()
}
}
impl<T: Clone, const N: usize> From<[T; N]> for SmallVec<T, N> {
fn from(array: [T; N]) -> Self {
Self::from_buf(array)

impl<T, const N: usize, const M: usize> From<[T; M]> for SmallVec<T, N> {
fn from(array: [T; M]) -> Self {
if M > N {
// If M > N, we'd have to heap allocate anyway,
// so delegate for Vec for the allocation
Self::from(Vec::from(array))
} else {
// M <= N
let mut this = Self::new();
debug_assert!(M <= this.capacity());
let array = ManuallyDrop::new(array);
// SAFETY: M <= this.capacity()
unsafe {
copy_nonoverlapping(array.as_ptr(), this.as_mut_ptr(), M);
this.set_len(M);
}
this
}
}
}
impl<T: Clone, const N: usize> From<Vec<T>> for SmallVec<T, N> {
impl<T, const N: usize> From<Vec<T>> for SmallVec<T, N> {
fn from(array: Vec<T>) -> Self {
Self::from_vec(array)
}
Expand Down
22 changes: 22 additions & 0 deletions src/tests.rs
Expand Up @@ -644,6 +644,28 @@ fn test_from() {
let small_vec: SmallVec<u8, 128> = SmallVec::from(array);
assert_eq!(&*small_vec, vec![99u8; 128].as_slice());
drop(small_vec);

#[derive(PartialEq, Eq, Debug)]
struct NoClone(u8);
let array = [NoClone(42)];
let small_vec: SmallVec<NoClone, 1> = SmallVec::from(array);
assert_eq!(&*small_vec, &[NoClone(42)]);
drop(small_vec);

let vec = vec![NoClone(42)];
let small_vec: SmallVec<NoClone, 1> = SmallVec::from(vec);
assert_eq!(&*small_vec, &[NoClone(42)]);
drop(small_vec);

let array = [1; 128];
let small_vec: SmallVec<u8, 1> = SmallVec::from(array);
assert_eq!(&*small_vec, vec![1; 128].as_slice());
drop(small_vec);

let array = [99];
let small_vec: SmallVec<u8, 128> = SmallVec::from(array);
assert_eq!(&*small_vec, &[99u8]);
drop(small_vec);
}

#[test]
Expand Down

0 comments on commit 74075e3

Please sign in to comment.