Skip to content
New issue

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

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

Already on GitHub? # to your account

Run destructors when clearing PinVec #21

Merged
merged 4 commits into from
Apr 26, 2022
Merged
Changes from 1 commit
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: 18 additions & 6 deletions src/pin_vec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,13 +23,25 @@ impl<T> PinVec<T> {
}

pub fn clear(&mut self) {
udoprog marked this conversation as resolved.
Show resolved Hide resolved
for i in 0..self.len {
// Safety: we know the pointer is initialized because its index is in bounds, and it
// can be dropped because we are emptying the container, which means these contents
// will not be accessed again.
unsafe { drop_in_place(self.get_mut(i).unwrap()) }
if mem::needs_drop::<T>() {
let (last_slot, offset, _) = calculate_key(self.len());
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh, this is really neat!

for (i, mut slot) in self.slots.drain(..).enumerate() {
let slice: &mut [MaybeUninit<T>] = if i < last_slot {
&mut *slot
} else {
&mut slot[0..offset]
};
// Safety: we initialized slice to only point to the already-initialized elements.
// It's safe to drop_in_place because we are draining the Vec.
unsafe {
let slice: &mut [T] = mem::transmute(slice);
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think I'm partial to casting to a pointer above and reconstituting it as a slice over transmuting a slice. But both are equally correct to me so I don't mind it.

Here's that version:

let len = if i < last_slot { slot.len() } else { offset };
drop_in_place(from_raw_parts_mut(slot.as_mut_ptr() as *mut T, len));

drop_in_place(slice);
}
}
} else {
self.slots.clear();
}
self.slots.clear();
debug_assert_eq!(self.slots.len(), 0);
self.len = 0;
}

Expand Down