Skip to content

Commit

Permalink
avoid check in vec deref
Browse files Browse the repository at this point in the history
  • Loading branch information
Noratrieb committed Feb 22, 2024
1 parent 3389c50 commit c38efd0
Showing 1 changed file with 7 additions and 2 deletions.
9 changes: 7 additions & 2 deletions library/alloc/src/vec/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2703,15 +2703,20 @@ impl<T, A: Allocator> ops::Deref for Vec<T, A> {

#[inline]
fn deref(&self) -> &[T] {
unsafe { slice::from_raw_parts(self.as_ptr(), self.len) }
// slice::from_raw_parts brings in an unsafe precondition check which we want to avoid
// here in this really hot functions. To forge an invalid pointer, users basically need
// to transmute to pass an unaligned pointer to from_raw_parts (WHICH SHOULD BE DETECTED THERE, FIXME).
// So the cost-benefit of this check leans towards not having it.
unsafe { &*ptr::slice_from_raw_parts(self.as_ptr(), self.len) }
}
}

#[stable(feature = "rust1", since = "1.0.0")]
impl<T, A: Allocator> ops::DerefMut for Vec<T, A> {
#[inline]
fn deref_mut(&mut self) -> &mut [T] {
unsafe { slice::from_raw_parts_mut(self.as_mut_ptr(), self.len) }
// See deref.
unsafe { &mut *ptr::slice_from_raw_parts_mut(self.as_mut_ptr(), self.len) }
}
}

Expand Down

0 comments on commit c38efd0

Please sign in to comment.