Skip to content

Commit a290c37

Browse files
committed
Relax From<array> for SmallVec to allow different length arrays.
1 parent a0efe3c commit a290c37

File tree

2 files changed

+29
-3
lines changed

2 files changed

+29
-3
lines changed

src/lib.rs

+19-3
Original file line numberDiff line numberDiff line change
@@ -1909,9 +1909,25 @@ impl<'a, T: Clone, const N: usize> From<&'a [T]> for SmallVec<T, N> {
19091909
slice.iter().cloned().collect()
19101910
}
19111911
}
1912-
impl<T, const N: usize> From<[T; N]> for SmallVec<T, N> {
1913-
fn from(array: [T; N]) -> Self {
1914-
Self::from_buf(array)
1912+
1913+
impl<T, const N: usize, const M: usize> From<[T; M]> for SmallVec<T, N> {
1914+
fn from(array: [T; M]) -> Self {
1915+
if M > N {
1916+
// If M > N, we'd have to heap allocate anyway,
1917+
// so delegate for Vec for the allocation
1918+
Self::from(Vec::from(array))
1919+
} else {
1920+
// M <= N
1921+
let mut this = Self::new();
1922+
debug_assert!(M <= this.capacity());
1923+
let array = ManuallyDrop::new(array);
1924+
// SAFETY: M <= this.capacity()
1925+
unsafe {
1926+
copy_nonoverlapping(array.as_ptr(), this.as_mut_ptr(), M);
1927+
this.set_len(M);
1928+
}
1929+
this
1930+
}
19151931
}
19161932
}
19171933
impl<T, const N: usize> From<Vec<T>> for SmallVec<T, N> {

src/tests.rs

+10
Original file line numberDiff line numberDiff line change
@@ -656,6 +656,16 @@ fn test_from() {
656656
let small_vec: SmallVec<NoClone, 1> = SmallVec::from(vec);
657657
assert_eq!(&*small_vec, &[NoClone(42)]);
658658
drop(small_vec);
659+
660+
let array = [1; 128];
661+
let small_vec: SmallVec<u8, 1> = SmallVec::from(array);
662+
assert_eq!(&*small_vec, vec![1; 128].as_slice());
663+
drop(small_vec);
664+
665+
let array = [99];
666+
let small_vec: SmallVec<u8, 128> = SmallVec::from(array);
667+
assert_eq!(&*small_vec, &[99u8]);
668+
drop(small_vec);
659669
}
660670

661671
#[test]

0 commit comments

Comments
 (0)