Skip to content

Use ManuallyDrop instead of Option in BinaryHeap Hole implementation #50487

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 1 commit into from
May 7, 2018
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
11 changes: 5 additions & 6 deletions src/liballoc/binary_heap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,7 @@

use core::ops::{Deref, DerefMut};
use core::iter::{FromIterator, FusedIterator};
use core::mem::{swap, size_of};
use core::mem::{swap, size_of, ManuallyDrop};
use core::ptr;
use core::fmt;

Expand Down Expand Up @@ -864,8 +864,7 @@ impl<T: Ord> BinaryHeap<T> {
/// position with the value that was originally removed.
struct Hole<'a, T: 'a> {
data: &'a mut [T],
/// `elt` is always `Some` from new until drop.
elt: Option<T>,
elt: ManuallyDrop<T>,
pos: usize,
}

Expand All @@ -879,7 +878,7 @@ impl<'a, T> Hole<'a, T> {
let elt = ptr::read(&data[pos]);
Hole {
data,
elt: Some(elt),
elt: ManuallyDrop::new(elt),
pos,
}
}
Expand All @@ -892,7 +891,7 @@ impl<'a, T> Hole<'a, T> {
/// Returns a reference to the element removed.
#[inline]
fn element(&self) -> &T {
self.elt.as_ref().unwrap()
&self.elt
}

/// Returns a reference to the element at `index`.
Expand Down Expand Up @@ -925,7 +924,7 @@ impl<'a, T> Drop for Hole<'a, T> {
// fill the hole again
unsafe {
let pos = self.pos;
ptr::write(self.data.get_unchecked_mut(pos), self.elt.take().unwrap());
ptr::copy_nonoverlapping(&*self.elt, self.data.get_unchecked_mut(pos), 1);
}
}
}
Expand Down