Skip to content

Handle drop zst #425

New issue

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

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

Already on GitHub? Sign in to your account

Merged
merged 7 commits into from
Jul 5, 2025
Merged
Changes from all commits
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
17 changes: 17 additions & 0 deletions src/vec/vec-zsts.md
Original file line number Diff line number Diff line change
Expand Up @@ -214,3 +214,20 @@ impl<T> DoubleEndedIterator for RawValIter<T> {
```

And that's it. Iteration works!

One last thing we need to consider is that when our vector is dropped, it deallocates the memory that was allocated while it was alive. With ZSTs, we didn't allocate any memory; in fact, we never do. So, right now, our code has unsoundness: we're still trying to deallocate a `NonNull::dangling()` pointer that we use to simulate the ZST in our vector. This means we'd cause undefined behavior if we tried to deallocate something we never allocated (obviously, and for good reasons). To fix this, in our `RawVec`'s `Drop` trait, we're going to tweak it to ensure we only deallocate types that are sized.

```rust,ignore
impl<T> Drop for RawVec<T> {
fn drop(&mut self) {
println!("RawVec<T> Drop called, deallocating memory");
if self.cap != 0 && std::mem::size_of::<T>() > 0 {
let layout = std::alloc::Layout::array::<T>(self.cap).unwrap();
unsafe {
std::alloc::dealloc(self.ptr.as_ptr() as *mut _, layout);
}
}
}
}
```