Skip to content

Commit

Permalink
Auto merge of #46952 - SimonSapin:nonnull, r=alexcrichton
Browse files Browse the repository at this point in the history
Rename std::ptr::Shared to NonNull and stabilize it

This implements the changes proposed at #27730 (comment):

> * Rename `Shared<T>` to `NonNull<T>` and stabilize it. (Being in the `ptr` module is enough to say that it’s a pointer. I’m not very attached to this specific name though.)
> * Rename `Box<T>` methods ~~`from_unique`~~/`into_unique` to ~~`from_nonnull`~~/`into_nonnull` (or whatever names are deemed appropriate), replace `Unique<T>` with `NonNull<T>` in their signatures, and stabilize them.
> *  Replace `Unique<T>` with `NonNull<T>` in the signatures of methods of the `Alloc` trait.
> * Mark `Unique` “permanently-unstable” by replacing remaining occurrences of `#[unstable(feature = "unique", issue = "27730")]` with:
>
>   ```rust
>   #[unstable(feature = "ptr_internals", issue = "0", reason = "\
>       use NonNull instead and consider PhantomData<T> (if you also use #[may_dangle]), \
>       Send, and/or Sync")]
>   ```
>
>   (Maybe the `reason` string is only useful on the struct definition.) Ideally it would be made private to some crate instead, but it needs to be used in both liballoc and libstd.
> * (Leave `NonZero` and `Zeroable` unstable for now, and subject to future bikeshedding.)
  • Loading branch information
bors committed Jan 20, 2018
2 parents 816d765 + 602a445 commit bdda8d6
Show file tree
Hide file tree
Showing 22 changed files with 182 additions and 197 deletions.
2 changes: 1 addition & 1 deletion src/doc/nomicon
20 changes: 10 additions & 10 deletions src/liballoc/allocator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ use core::cmp;
use core::fmt;
use core::mem;
use core::usize;
use core::ptr::{self, Unique};
use core::ptr::{self, NonNull};

/// Represents the combination of a starting address and
/// a total capacity of the returned block.
Expand Down Expand Up @@ -895,12 +895,12 @@ pub unsafe trait Alloc {
/// Clients wishing to abort computation in response to an
/// allocation error are encouraged to call the allocator's `oom`
/// method, rather than directly invoking `panic!` or similar.
fn alloc_one<T>(&mut self) -> Result<Unique<T>, AllocErr>
fn alloc_one<T>(&mut self) -> Result<NonNull<T>, AllocErr>
where Self: Sized
{
let k = Layout::new::<T>();
if k.size() > 0 {
unsafe { self.alloc(k).map(|p| Unique::new_unchecked(p as *mut T)) }
unsafe { self.alloc(k).map(|p| NonNull::new_unchecked(p as *mut T)) }
} else {
Err(AllocErr::invalid_input("zero-sized type invalid for alloc_one"))
}
Expand All @@ -923,7 +923,7 @@ pub unsafe trait Alloc {
/// * `ptr` must denote a block of memory currently allocated via this allocator
///
/// * the layout of `T` must *fit* that block of memory.
unsafe fn dealloc_one<T>(&mut self, ptr: Unique<T>)
unsafe fn dealloc_one<T>(&mut self, ptr: NonNull<T>)
where Self: Sized
{
let raw_ptr = ptr.as_ptr() as *mut u8;
Expand Down Expand Up @@ -963,15 +963,15 @@ pub unsafe trait Alloc {
/// Clients wishing to abort computation in response to an
/// allocation error are encouraged to call the allocator's `oom`
/// method, rather than directly invoking `panic!` or similar.
fn alloc_array<T>(&mut self, n: usize) -> Result<Unique<T>, AllocErr>
fn alloc_array<T>(&mut self, n: usize) -> Result<NonNull<T>, AllocErr>
where Self: Sized
{
match Layout::array::<T>(n) {
Some(ref layout) if layout.size() > 0 => {
unsafe {
self.alloc(layout.clone())
.map(|p| {
Unique::new_unchecked(p as *mut T)
NonNull::new_unchecked(p as *mut T)
})
}
}
Expand Down Expand Up @@ -1012,15 +1012,15 @@ pub unsafe trait Alloc {
/// reallocation error are encouraged to call the allocator's `oom`
/// method, rather than directly invoking `panic!` or similar.
unsafe fn realloc_array<T>(&mut self,
ptr: Unique<T>,
ptr: NonNull<T>,
n_old: usize,
n_new: usize) -> Result<Unique<T>, AllocErr>
n_new: usize) -> Result<NonNull<T>, AllocErr>
where Self: Sized
{
match (Layout::array::<T>(n_old), Layout::array::<T>(n_new), ptr.as_ptr()) {
(Some(ref k_old), Some(ref k_new), ptr) if k_old.size() > 0 && k_new.size() > 0 => {
self.realloc(ptr as *mut u8, k_old.clone(), k_new.clone())
.map(|p|Unique::new_unchecked(p as *mut T))
.map(|p| NonNull::new_unchecked(p as *mut T))
}
_ => {
Err(AllocErr::invalid_input("invalid layout for realloc_array"))
Expand Down Expand Up @@ -1048,7 +1048,7 @@ pub unsafe trait Alloc {
/// constraints.
///
/// Always returns `Err` on arithmetic overflow.
unsafe fn dealloc_array<T>(&mut self, ptr: Unique<T>, n: usize) -> Result<(), AllocErr>
unsafe fn dealloc_array<T>(&mut self, ptr: NonNull<T>, n: usize) -> Result<(), AllocErr>
where Self: Sized
{
let raw_ptr = ptr.as_ptr() as *mut u8;
Expand Down
20 changes: 10 additions & 10 deletions src/liballoc/arc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ use core::intrinsics::abort;
use core::mem::{self, align_of_val, size_of_val, uninitialized};
use core::ops::Deref;
use core::ops::CoerceUnsized;
use core::ptr::{self, Shared};
use core::ptr::{self, NonNull};
use core::marker::{Unsize, PhantomData};
use core::hash::{Hash, Hasher};
use core::{isize, usize};
Expand Down Expand Up @@ -197,7 +197,7 @@ const MAX_REFCOUNT: usize = (isize::MAX) as usize;
/// [rc_examples]: ../../std/rc/index.html#examples
#[stable(feature = "rust1", since = "1.0.0")]
pub struct Arc<T: ?Sized> {
ptr: Shared<ArcInner<T>>,
ptr: NonNull<ArcInner<T>>,
phantom: PhantomData<T>,
}

Expand Down Expand Up @@ -234,7 +234,7 @@ impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Arc<U>> for Arc<T> {}
/// [`None`]: ../../std/option/enum.Option.html#variant.None
#[stable(feature = "arc_weak", since = "1.4.0")]
pub struct Weak<T: ?Sized> {
ptr: Shared<ArcInner<T>>,
ptr: NonNull<ArcInner<T>>,
}

#[stable(feature = "arc_weak", since = "1.4.0")]
Expand Down Expand Up @@ -286,7 +286,7 @@ impl<T> Arc<T> {
weak: atomic::AtomicUsize::new(1),
data,
};
Arc { ptr: Shared::from(Box::into_unique(x)), phantom: PhantomData }
Arc { ptr: Box::into_raw_non_null(x), phantom: PhantomData }
}

/// Returns the contained value, if the `Arc` has exactly one strong reference.
Expand Down Expand Up @@ -397,7 +397,7 @@ impl<T: ?Sized> Arc<T> {
let arc_ptr = set_data_ptr(fake_ptr, (ptr as *mut u8).offset(-offset));

Arc {
ptr: Shared::new_unchecked(arc_ptr),
ptr: NonNull::new_unchecked(arc_ptr),
phantom: PhantomData,
}
}
Expand Down Expand Up @@ -582,7 +582,7 @@ impl<T: ?Sized> Arc<T> {
// Free the allocation without dropping its contents
box_free(bptr);

Arc { ptr: Shared::new_unchecked(ptr), phantom: PhantomData }
Arc { ptr: NonNull::new_unchecked(ptr), phantom: PhantomData }
}
}
}
Expand All @@ -609,7 +609,7 @@ impl<T> Arc<[T]> {
&mut (*ptr).data as *mut [T] as *mut T,
v.len());

Arc { ptr: Shared::new_unchecked(ptr), phantom: PhantomData }
Arc { ptr: NonNull::new_unchecked(ptr), phantom: PhantomData }
}
}

Expand Down Expand Up @@ -669,7 +669,7 @@ impl<T: Clone> ArcFromSlice<T> for Arc<[T]> {
// All clear. Forget the guard so it doesn't free the new ArcInner.
mem::forget(guard);

Arc { ptr: Shared::new_unchecked(ptr), phantom: PhantomData }
Arc { ptr: NonNull::new_unchecked(ptr), phantom: PhantomData }
}
}
}
Expand Down Expand Up @@ -991,11 +991,11 @@ impl<T> Weak<T> {
pub fn new() -> Weak<T> {
unsafe {
Weak {
ptr: Shared::from(Box::into_unique(box ArcInner {
ptr: Box::into_raw_non_null(box ArcInner {
strong: atomic::AtomicUsize::new(0),
weak: atomic::AtomicUsize::new(1),
data: uninitialized(),
})),
}),
}
}
}
Expand Down
65 changes: 18 additions & 47 deletions src/liballoc/boxed.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ use core::marker::{self, Unsize};
use core::mem;
use core::ops::{CoerceUnsized, Deref, DerefMut, Generator, GeneratorState};
use core::ops::{BoxPlace, Boxed, InPlace, Place, Placer};
use core::ptr::{self, Unique};
use core::ptr::{self, NonNull, Unique};
use core::convert::From;
use str::from_boxed_utf8_unchecked;

Expand Down Expand Up @@ -269,38 +269,7 @@ impl<T: ?Sized> Box<T> {
#[stable(feature = "box_raw", since = "1.4.0")]
#[inline]
pub unsafe fn from_raw(raw: *mut T) -> Self {
Box::from_unique(Unique::new_unchecked(raw))
}

/// Constructs a `Box` from a `Unique<T>` pointer.
///
/// After calling this function, the memory is owned by a `Box` and `T` can
/// then be destroyed and released upon drop.
///
/// # Safety
///
/// A `Unique<T>` can be safely created via [`Unique::new`] and thus doesn't
/// necessarily own the data pointed to nor is the data guaranteed to live
/// as long as the pointer.
///
/// [`Unique::new`]: ../../core/ptr/struct.Unique.html#method.new
///
/// # Examples
///
/// ```
/// #![feature(unique)]
///
/// fn main() {
/// let x = Box::new(5);
/// let ptr = Box::into_unique(x);
/// let x = unsafe { Box::from_unique(ptr) };
/// }
/// ```
#[unstable(feature = "unique", reason = "needs an RFC to flesh out design",
issue = "27730")]
#[inline]
pub unsafe fn from_unique(u: Unique<T>) -> Self {
Box(u)
Box(Unique::new_unchecked(raw))
}

/// Consumes the `Box`, returning the wrapped raw pointer.
Expand All @@ -326,40 +295,42 @@ impl<T: ?Sized> Box<T> {
#[stable(feature = "box_raw", since = "1.4.0")]
#[inline]
pub fn into_raw(b: Box<T>) -> *mut T {
Box::into_unique(b).as_ptr()
Box::into_raw_non_null(b).as_ptr()
}

/// Consumes the `Box`, returning the wrapped pointer as `Unique<T>`.
/// Consumes the `Box`, returning the wrapped pointer as `NonNull<T>`.
///
/// After calling this function, the caller is responsible for the
/// memory previously managed by the `Box`. In particular, the
/// caller should properly destroy `T` and release the memory. The
/// proper way to do so is to either convert the `Unique<T>` pointer:
///
/// - Into a `Box` with the [`Box::from_unique`] function.
///
/// - Into a raw pointer and back into a `Box` with the [`Box::from_raw`]
/// function.
/// proper way to do so is to convert the `NonNull<T>` pointer
/// into a raw pointer and back into a `Box` with the [`Box::from_raw`]
/// function.
///
/// Note: this is an associated function, which means that you have
/// to call it as `Box::into_unique(b)` instead of `b.into_unique()`. This
/// to call it as `Box::into_raw_non_null(b)`
/// instead of `b.into_raw_non_null()`. This
/// is so that there is no conflict with a method on the inner type.
///
/// [`Box::from_unique`]: struct.Box.html#method.from_unique
/// [`Box::from_raw`]: struct.Box.html#method.from_raw
///
/// # Examples
///
/// ```
/// #![feature(unique)]
/// #![feature(box_into_raw_non_null)]
///
/// fn main() {
/// let x = Box::new(5);
/// let ptr = Box::into_unique(x);
/// let ptr = Box::into_raw_non_null(x);
/// }
/// ```
#[unstable(feature = "unique", reason = "needs an RFC to flesh out design",
issue = "27730")]
#[unstable(feature = "box_into_raw_non_null", issue = "47336")]
#[inline]
pub fn into_raw_non_null(b: Box<T>) -> NonNull<T> {
Box::into_unique(b).into()
}

#[unstable(feature = "ptr_internals", issue = "0", reason = "use into_raw_non_null instead")]
#[inline]
pub fn into_unique(b: Box<T>) -> Unique<T> {
let unique = b.0;
Expand Down
2 changes: 1 addition & 1 deletion src/liballoc/heap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -232,7 +232,7 @@ unsafe impl Alloc for Heap {
///
/// This preserves the non-null invariant for types like `Box<T>`. The address
/// may overlap with non-zero-size memory allocations.
#[rustc_deprecated(since = "1.19", reason = "Use Unique/Shared::empty() instead")]
#[rustc_deprecated(since = "1.19", reason = "Use Unique/NonNull::empty() instead")]
#[unstable(feature = "heap_api", issue = "27700")]
pub const EMPTY: *mut () = 1 as *mut ();

Expand Down
4 changes: 2 additions & 2 deletions src/liballoc/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,7 @@
#![cfg_attr(test, feature(rand, test))]
#![feature(allow_internal_unstable)]
#![feature(ascii_ctype)]
#![feature(box_into_raw_non_null)]
#![feature(box_patterns)]
#![feature(box_syntax)]
#![feature(cfg_target_has_atomic)]
Expand All @@ -109,8 +110,8 @@
#![feature(pattern)]
#![feature(placement_in_syntax)]
#![feature(placement_new_protocol)]
#![feature(ptr_internals)]
#![feature(rustc_attrs)]
#![feature(shared)]
#![feature(slice_get_slice)]
#![feature(slice_patterns)]
#![feature(slice_rsplit)]
Expand All @@ -120,7 +121,6 @@
#![feature(trusted_len)]
#![feature(unboxed_closures)]
#![feature(unicode)]
#![feature(unique)]
#![feature(unsize)]
#![feature(allocator_internals)]
#![feature(on_unimplemented)]
Expand Down
Loading

0 comments on commit bdda8d6

Please sign in to comment.