Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement From<[T; M]> for SmallVec<T, N> for all M, N (v2) #338

Merged
merged 2 commits into from
Feb 19, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 20 additions & 4 deletions src/lib.rs
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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