fix panic if converting ZST Vec to VecDeque

This commit is contained in:
Justus K 2020-12-13 10:02:36 +01:00
parent 7efc097c4f
commit 0f30b7dd87
No known key found for this signature in database
GPG Key ID: 8C62FE98A62FC462
2 changed files with 13 additions and 2 deletions

View File

@ -2793,8 +2793,12 @@ impl<T> From<Vec<T>> for VecDeque<T> {
let len = other.len();
// We need to extend the buf if it's not a power of two, too small
// or doesn't have at least one free space
if !buf.capacity().is_power_of_two()
// or doesn't have at least one free space.
// We check if `T` is a ZST in the first condition,
// because `usize::MAX` (the capacity returned by `capacity()` for ZST)
// is not a power of zero and thus it'll always try
// to reserve more memory which will panic for ZST (rust-lang/rust#78532)
if (!buf.capacity().is_power_of_two() && mem::size_of::<T>() != 0)
|| (buf.capacity() < (MINIMUM_CAPACITY + 1))
|| (buf.capacity() == len)
{

View File

@ -1728,3 +1728,10 @@ fn test_zero_sized_push() {
}
}
}
#[test]
fn test_from_zero_sized_vec() {
let v = vec![(); 100];
let queue = VecDeque::from(v);
assert!(queue.len(), 100);
}