Skip to content

Commit 6b05894

Browse files
Fix memory leak on VecView drop
Drop must also be implemented on `VecView` for the cases wher the `VecView` is owned even if it is `!Sized`. This can happen when it is boxed.
1 parent c118d70 commit 6b05894

File tree

1 file changed

+34
-7
lines changed

1 file changed

+34
-7
lines changed

src/vec.rs

Lines changed: 34 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -15,12 +15,6 @@ pub trait VecDrop {
1515
}
1616

1717
impl<T> VecDrop for [MaybeUninit<T>] {
18-
unsafe fn drop_with_len(&mut self, _len: usize) {
19-
// Case of a view, drop does nothing
20-
}
21-
}
22-
23-
impl<T, const N: usize> VecDrop for [MaybeUninit<T>; N] {
2418
unsafe fn drop_with_len(&mut self, len: usize) {
2519
// NOTE(unsafe) avoid bound checks in the slicing operation
2620
// &mut buffer[..len]
@@ -31,6 +25,12 @@ impl<T, const N: usize> VecDrop for [MaybeUninit<T>; N] {
3125
}
3226
}
3327

28+
impl<T, const N: usize> VecDrop for [MaybeUninit<T>; N] {
29+
unsafe fn drop_with_len(&mut self, len: usize) {
30+
VecDrop::drop_with_len(self.as_mut_slice(), len)
31+
}
32+
}
33+
3434
/// <div class="warn">This is private API and should not be used</div>
3535
pub struct VecInner<B: ?Sized + VecDrop> {
3636
len: usize,
@@ -1953,7 +1953,7 @@ mod tests {
19531953

19541954
use static_assertions::assert_not_impl_any;
19551955

1956-
use crate::Vec;
1956+
use super::{Vec, VecView};
19571957

19581958
// Ensure a `Vec` containing `!Send` values stays `!Send` itself.
19591959
assert_not_impl_any!(Vec<*const (), 4>: Send);
@@ -2014,6 +2014,33 @@ mod tests {
20142014
assert_eq!(Droppable::count(), 0);
20152015
}
20162016

2017+
#[test]
2018+
fn drop_vecview() {
2019+
droppable!();
2020+
2021+
{
2022+
let v: Vec<Droppable, 2> = Vec::new();
2023+
let mut v: Box<VecView<Droppable>> = Box::new(v);
2024+
v.push(Droppable::new()).ok().unwrap();
2025+
v.push(Droppable::new()).ok().unwrap();
2026+
assert_eq!(Droppable::count(), 2);
2027+
v.pop().unwrap();
2028+
assert_eq!(Droppable::count(), 1);
2029+
}
2030+
2031+
assert_eq!(Droppable::count(), 0);
2032+
2033+
{
2034+
let v: Vec<Droppable, 2> = Vec::new();
2035+
let mut v: Box<VecView<Droppable>> = Box::new(v);
2036+
v.push(Droppable::new()).ok().unwrap();
2037+
v.push(Droppable::new()).ok().unwrap();
2038+
assert_eq!(Droppable::count(), 2);
2039+
}
2040+
2041+
assert_eq!(Droppable::count(), 0);
2042+
}
2043+
20172044
#[test]
20182045
fn eq() {
20192046
let mut xs: Vec<i32, 4> = Vec::new();

0 commit comments

Comments
 (0)