Skip to content

Commit

Permalink
Relax From<array> for SmallVec to allow different length arrays.
Browse files Browse the repository at this point in the history
  • Loading branch information
zachs18 committed Feb 19, 2024
1 parent a0efe3c commit db63036
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 3 deletions.
14 changes: 11 additions & 3 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1909,9 +1909,17 @@ impl<'a, T: Clone, const N: usize> From<&'a [T]> for SmallVec<T, N> {
slice.iter().cloned().collect()
}
}
impl<T, 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 {
let mut this = Self::with_capacity(M);
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, const N: usize> From<Vec<T>> for SmallVec<T, N> {
Expand Down
10 changes: 10 additions & 0 deletions src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -656,6 +656,16 @@ fn test_from() {
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 db63036

Please sign in to comment.