Skip to content

Commit fe2af20

Browse files
authored
Rollup merge of rust-lang#80003 - Stupremee:fix-zst-vecdeque-conversion-panic, r=dtolnay
Fix overflow when converting ZST Vec to VecDeque ```rust let v = vec![(); 100]; let queue = VecDeque::from(v); println!("{:?}", queue); ``` This code will currently panic with a capacity overflow. This PR resolves this issue and makes the code run fine. Resolves rust-lang#78532
2 parents 6a19c06 + 09d528e commit fe2af20

File tree

2 files changed

+13
-2
lines changed

2 files changed

+13
-2
lines changed

library/alloc/src/collections/vec_deque/mod.rs

+6-2
Original file line numberDiff line numberDiff line change
@@ -2793,8 +2793,12 @@ impl<T> From<Vec<T>> for VecDeque<T> {
27932793
let len = other.len();
27942794

27952795
// We need to extend the buf if it's not a power of two, too small
2796-
// or doesn't have at least one free space
2797-
if !buf.capacity().is_power_of_two()
2796+
// or doesn't have at least one free space.
2797+
// We check if `T` is a ZST in the first condition,
2798+
// because `usize::MAX` (the capacity returned by `capacity()` for ZST)
2799+
// is not a power of two and thus it'll always try
2800+
// to reserve more memory which will panic for ZST (rust-lang/rust#78532)
2801+
if (!buf.capacity().is_power_of_two() && mem::size_of::<T>() != 0)
27982802
|| (buf.capacity() < (MINIMUM_CAPACITY + 1))
27992803
|| (buf.capacity() == len)
28002804
{

library/alloc/tests/vec_deque.rs

+7
Original file line numberDiff line numberDiff line change
@@ -1728,3 +1728,10 @@ fn test_zero_sized_push() {
17281728
}
17291729
}
17301730
}
1731+
1732+
#[test]
1733+
fn test_from_zero_sized_vec() {
1734+
let v = vec![(); 100];
1735+
let queue = VecDeque::from(v);
1736+
assert_eq!(queue.len(), 100);
1737+
}

0 commit comments

Comments
 (0)