mirror of
https://github.com/rust-lang/rust.git
synced 2024-11-01 23:12:02 +00:00
VecDeque: improve performance for From<[T; N]>
Create VecDeque directly from the array instead of inserting items one-by-one.
This commit is contained in:
parent
2ab73cf63d
commit
c3cff0a754
@ -3003,6 +3003,16 @@ impl<T, const N: usize> From<[T; N]> for VecDeque<T> {
|
||||
/// assert_eq!(deq1, deq2);
|
||||
/// ```
|
||||
fn from(arr: [T; N]) -> Self {
|
||||
core::array::IntoIter::new(arr).collect()
|
||||
let mut deq = VecDeque::with_capacity(N);
|
||||
let arr = ManuallyDrop::new(arr);
|
||||
if mem::size_of::<T>() != 0 {
|
||||
// SAFETY: VecDeque::with_capacity ensures that there is enough capacity.
|
||||
unsafe {
|
||||
ptr::copy_nonoverlapping(arr.as_ptr(), deq.ptr(), N);
|
||||
}
|
||||
}
|
||||
deq.tail = 0;
|
||||
deq.head = N;
|
||||
deq
|
||||
}
|
||||
}
|
||||
|
@ -507,6 +507,36 @@ fn test_from_vec_zst_overflow() {
|
||||
assert_eq!(vd.len(), vec.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_from_array() {
|
||||
fn test<const N: usize>() {
|
||||
let mut array: [usize; N] = [0; N];
|
||||
|
||||
for i in 0..N {
|
||||
array[i] = i;
|
||||
}
|
||||
|
||||
let deq: VecDeque<_> = array.into();
|
||||
|
||||
for i in 0..N {
|
||||
assert_eq!(deq[i], i);
|
||||
}
|
||||
|
||||
assert!(deq.cap().is_power_of_two());
|
||||
assert_eq!(deq.len(), N);
|
||||
}
|
||||
test::<0>();
|
||||
test::<1>();
|
||||
test::<2>();
|
||||
test::<32>();
|
||||
test::<35>();
|
||||
|
||||
let array = [(); MAXIMUM_ZST_CAPACITY - 1];
|
||||
let deq = VecDeque::from(array);
|
||||
assert!(deq.cap().is_power_of_two());
|
||||
assert_eq!(deq.len(), MAXIMUM_ZST_CAPACITY - 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_vec_from_vecdeque() {
|
||||
use crate::vec::Vec;
|
||||
|
Loading…
Reference in New Issue
Block a user