Skip to content

Commit ea72066

Browse files
committed
Avoid some bounds checks in binary_heap::{PeekMut,Hole}
1 parent fc6e9a2 commit ea72066

File tree

1 file changed

+8
-3
lines changed

1 file changed

+8
-3
lines changed

src/liballoc/collections/binary_heap.rs

+8-3
Original file line numberDiff line numberDiff line change
@@ -248,14 +248,18 @@ impl<'a, T: Ord> Drop for PeekMut<'a, T> {
248248
impl<'a, T: Ord> Deref for PeekMut<'a, T> {
249249
type Target = T;
250250
fn deref(&self) -> &T {
251-
&self.heap.data[0]
251+
debug_assert!(!self.heap.is_empty());
252+
// SAFE: PeekMut is only instantiated for non-empty heaps
253+
unsafe { self.heap.data.get_unchecked(0) }
252254
}
253255
}
254256

255257
#[stable(feature = "binary_heap_peek_mut", since = "1.12.0")]
256258
impl<'a, T: Ord> DerefMut for PeekMut<'a, T> {
257259
fn deref_mut(&mut self) -> &mut T {
258-
&mut self.heap.data[0]
260+
debug_assert!(!self.heap.is_empty());
261+
// SAFE: PeekMut is only instantiated for non-empty heaps
262+
unsafe { self.heap.data.get_unchecked_mut(0) }
259263
}
260264
}
261265

@@ -865,7 +869,8 @@ impl<'a, T> Hole<'a, T> {
865869
#[inline]
866870
unsafe fn new(data: &'a mut [T], pos: usize) -> Self {
867871
debug_assert!(pos < data.len());
868-
let elt = ptr::read(&data[pos]);
872+
// SAFE: pos should be inside the slice
873+
let elt = ptr::read(data.get_unchecked(pos));
869874
Hole {
870875
data,
871876
elt: ManuallyDrop::new(elt),

0 commit comments

Comments
 (0)