Skip to content

Commit

Permalink
Rollup merge of #79841 - fintelia:patch-6, r=kennytm
Browse files Browse the repository at this point in the history
More clear documentation for NonNull<T>

Rephrase and hopefully clarify the discussion of covariance in `NonNull<T>` documentation.

I'm very much not an expert so someone should definitely double check the correctness of what I'm saying. At the same time, the new language makes more sense to me, so hopefully it also is more logical to others whose knowledge of covariance basically begins and ends with the [Rustonomicon chapter](https://doc.rust-lang.org/nomicon/subtyping.html).

Related to #48929.
  • Loading branch information
jonas-schievink committed Jan 23, 2021
2 parents 4d0dd02 + 0392085 commit 7635462
Showing 1 changed file with 13 additions and 6 deletions.
19 changes: 13 additions & 6 deletions library/core/src/ptr/non_null.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,19 @@ use crate::slice::{self, SliceIndex};
/// as a discriminant -- `Option<NonNull<T>>` has the same size as `*mut T`.
/// However the pointer may still dangle if it isn't dereferenced.
///
/// Unlike `*mut T`, `NonNull<T>` is covariant over `T`. If this is incorrect
/// for your use case, you should include some [`PhantomData`] in your type to
/// provide invariance, such as `PhantomData<Cell<T>>` or `PhantomData<&'a mut T>`.
/// Usually this won't be necessary; covariance is correct for most safe abstractions,
/// such as `Box`, `Rc`, `Arc`, `Vec`, and `LinkedList`. This is the case because they
/// provide a public API that follows the normal shared XOR mutable rules of Rust.
/// Unlike `*mut T`, `NonNull<T>` was chosen to be covariant over `T`. This makes it
/// possible to use `NonNull<T>` when building covariant types, but introduces the
/// risk of unsoundness if used in a type that shouldn't actually be covariant.
/// (The opposite choice was made for `*mut T` even though technically the unsoundness
/// could only be caused by calling unsafe functions.)
///
/// Covariance is correct for most safe abstractions, such as `Box`, `Rc`, `Arc`, `Vec`,
/// and `LinkedList`. This is the case because they provide a public API that follows the
/// normal shared XOR mutable rules of Rust.
///
/// If your type cannot safely be covariant, you must ensure it contains some
/// additional field to provide invariance. Often this field will be a [`PhantomData`]
/// type like `PhantomData<Cell<T>>` or `PhantomData<&'a mut T>`.
///
/// Notice that `NonNull<T>` has a `From` instance for `&T`. However, this does
/// not change the fact that mutating through a (pointer derived from a) shared
Expand Down

0 comments on commit 7635462

Please sign in to comment.