Skip to content

Commit

Permalink
Rollup merge of rust-lang#53574 - vorner:ptr_as_ref_unchecked, r=Mark…
Browse files Browse the repository at this point in the history
…-Simulacrum

Suggest direct raw-pointer dereference

People often come looking for some kind of `as_ref_unchecked` method on
raw pointers that would give them `&T` and not `Option<&T>` when they
are sure the pointer is not NULL.

There's no such method, but taking a reference of the dereferenced
pointer accomplishes the same thing. Therefore, suggest using that, at
the `as_ref` site ‒ it's a place people are likely going to look into.
  • Loading branch information
GuillaumeGomez authored Aug 22, 2018
2 parents ef4b2ed + 18f41e5 commit 4f78a2d
Showing 1 changed file with 30 additions and 0 deletions.
30 changes: 30 additions & 0 deletions src/libcore/ptr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -582,6 +582,21 @@ impl<T: ?Sized> *const T {
/// }
/// }
/// ```
///
/// # Null-unchecked version
///
/// If you are sure the pointer can never be null and are looking for some kind of
/// `as_ref_unchecked` that returns the `&T` instead of `Option<&T>, know that you can
/// dereference the pointer directly.
///
/// ```
/// let ptr: *const u8 = &10u8 as *const u8;
///
/// unsafe {
/// let val_back = &*ptr;
/// println!("We got back the value: {}!", val_back);
/// }
/// ```
#[stable(feature = "ptr_as_ref", since = "1.9.0")]
#[inline]
pub unsafe fn as_ref<'a>(self) -> Option<&'a T> {
Expand Down Expand Up @@ -1303,6 +1318,21 @@ impl<T: ?Sized> *mut T {
/// }
/// }
/// ```
///
/// # Null-unchecked version
///
/// If you are sure the pointer can never be null and are looking for some kind of
/// `as_ref_unchecked` that returns the `&T` instead of `Option<&T>, know that you can
/// dereference the pointer directly.
///
/// ```
/// let ptr: *mut u8 = &mut 10u8 as *mut u8;
///
/// unsafe {
/// let val_back = &*ptr;
/// println!("We got back the value: {}!", val_back);
/// }
/// ```
#[stable(feature = "ptr_as_ref", since = "1.9.0")]
#[inline]
pub unsafe fn as_ref<'a>(self) -> Option<&'a T> {
Expand Down

0 comments on commit 4f78a2d

Please sign in to comment.