Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add functions core::ptr::dangling/_mut<T>() -> *const/*mut T #45527

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/liballoc/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,7 @@
#![feature(pattern)]
#![feature(placement_in_syntax)]
#![feature(placement_new_protocol)]
#![feature(ptr_dangling)]
#![feature(rustc_attrs)]
#![feature(shared)]
#![feature(slice_get_slice)]
Expand Down
4 changes: 2 additions & 2 deletions src/liballoc/vec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2344,7 +2344,7 @@ impl<T> Iterator for IntoIter<T> {

// Use a non-null pointer value
// (self.ptr might be null because of wrapping)
Some(ptr::read(1 as *mut T))
Some(ptr::read(ptr::dangling()))
} else {
let old = self.ptr;
self.ptr = self.ptr.offset(1);
Expand Down Expand Up @@ -2384,7 +2384,7 @@ impl<T> DoubleEndedIterator for IntoIter<T> {

// Use a non-null pointer value
// (self.end might be null because of wrapping)
Some(ptr::read(1 as *mut T))
Some(ptr::read(ptr::dangling()))
} else {
self.end = self.end.offset(-1);

Expand Down
1 change: 1 addition & 0 deletions src/libcore/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,7 @@
#![feature(unboxed_closures)]
#![feature(untagged_unions)]
#![feature(unwind_attributes)]
#![feature(const_align_of)]
#![feature(const_min_value)]
#![feature(const_max_value)]
#![feature(const_atomic_bool_new)]
Expand Down
24 changes: 20 additions & 4 deletions src/libcore/ptr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2083,6 +2083,24 @@ impl<T: ?Sized> PartialEq for *mut T {
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: ?Sized> Eq for *mut T {}

#[unstable(feature = "ptr_dangling", issue = "45557")]
#[rustc_const_unstable(feature = "const_ptr_dangling")]
/// Returns a const raw pointer that is dangling, but well-aligned and not null.
///
/// This is used where a non-null pointer is required.
pub const fn dangling<T>() -> *const T {
mem::align_of::<T>() as *const T
}

#[unstable(feature = "ptr_dangling", issue = "45557")]
#[rustc_const_unstable(feature = "const_ptr_dangling_mut")]
/// Returns a mut raw pointer that is dangling, but well-aligned and not null.
///
/// This is used where a non-null pointer is required.
pub const fn dangling_mut<T>() -> *mut T {
mem::align_of::<T>() as *mut T
}

/// Compare raw pointers for equality.
///
/// This is the same as using the `==` operator, but less generic:
Expand Down Expand Up @@ -2325,8 +2343,7 @@ impl<T: Sized> Unique<T> {
/// `Vec::new` does.
pub fn empty() -> Self {
unsafe {
let ptr = mem::align_of::<T>() as *mut T;
Unique::new_unchecked(ptr)
Unique::new_unchecked(dangling_mut())
}
}
}
Expand Down Expand Up @@ -2460,8 +2477,7 @@ impl<T: Sized> Shared<T> {
/// `Vec::new` does.
pub fn empty() -> Self {
unsafe {
let ptr = mem::align_of::<T>() as *mut T;
Shared::new_unchecked(ptr)
Shared::new_unchecked(dangling_mut())
}
}
}
Expand Down
12 changes: 6 additions & 6 deletions src/libcore/slice/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -244,7 +244,7 @@ macro_rules! make_ref {
let ptr = $ptr;
if size_from_ptr(ptr) == 0 {
// Use a non-null pointer value
&*(1 as *mut _)
&*ptr::dangling()
} else {
&*ptr
}
Expand All @@ -257,7 +257,7 @@ macro_rules! make_ref_mut {
let ptr = $ptr;
if size_from_ptr(ptr) == 0 {
// Use a non-null pointer value
&mut *(1 as *mut _)
&mut *(ptr::dangling_mut())
} else {
&mut *ptr
}
Expand All @@ -279,7 +279,7 @@ impl<T> SliceExt for [T] {
fn iter(&self) -> Iter<T> {
unsafe {
let p = if mem::size_of::<T>() == 0 {
1 as *const _
ptr::dangling()
} else {
let p = self.as_ptr();
assume(!p.is_null());
Expand Down Expand Up @@ -443,7 +443,7 @@ impl<T> SliceExt for [T] {
fn iter_mut(&mut self) -> IterMut<T> {
unsafe {
let p = if mem::size_of::<T>() == 0 {
1 as *mut _
ptr::dangling_mut()
} else {
let p = self.as_mut_ptr();
assume(!p.is_null());
Expand Down Expand Up @@ -1259,7 +1259,7 @@ macro_rules! make_slice {
let diff = ($end as usize).wrapping_sub(start as usize);
if size_from_ptr(start) == 0 {
// use a non-null pointer value
unsafe { from_raw_parts(1 as *const _, diff) }
unsafe { from_raw_parts(ptr::dangling(), diff) }
} else {
let len = diff / size_from_ptr(start);
unsafe { from_raw_parts(start, len) }
Expand All @@ -1273,7 +1273,7 @@ macro_rules! make_mut_slice {
let diff = ($end as usize).wrapping_sub(start as usize);
if size_from_ptr(start) == 0 {
// use a non-null pointer value
unsafe { from_raw_parts_mut(1 as *mut _, diff) }
unsafe { from_raw_parts_mut(ptr::dangling_mut(), diff) }
} else {
let len = diff / size_from_ptr(start);
unsafe { from_raw_parts_mut(start, len) }
Expand Down
1 change: 1 addition & 0 deletions src/librustc/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@
#![feature(match_default_bindings)]
#![feature(never_type)]
#![feature(nonzero)]
#![feature(ptr_dangling)]
#![feature(quote)]
#![feature(refcell_replace_swap)]
#![feature(rustc_diagnostic_macros)]
Expand Down
3 changes: 2 additions & 1 deletion src/librustc/ty/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ use std::rc::Rc;
use std::slice;
use std::vec::IntoIter;
use std::mem;
use std::ptr;
use syntax::ast::{self, DUMMY_NODE_ID, Name, Ident, NodeId};
use syntax::attr;
use syntax::ext::hygiene::{Mark, SyntaxContext};
Expand Down Expand Up @@ -572,7 +573,7 @@ impl<'tcx> serialize::UseSpecializedDecodable for &'tcx Slice<Ty<'tcx>> {}
impl<T> Slice<T> {
pub fn empty<'a>() -> &'a Slice<T> {
unsafe {
mem::transmute(slice::from_raw_parts(0x1 as *const T, 0))
mem::transmute(slice::from_raw_parts(ptr::dangling::<T>(), 0))
}
}
}
Expand Down
4 changes: 2 additions & 2 deletions src/libstd/io/lazy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ impl<T: Send + Sync + 'static> Lazy<T> {
let ptr = self.ptr.get();
let ret = if ptr.is_null() {
Some(self.init())
} else if ptr as usize == 1 {
} else if ptr == ptr::dangling_mut() {
None
} else {
Some((*ptr).clone())
Expand All @@ -55,7 +55,7 @@ impl<T: Send + Sync + 'static> Lazy<T> {
let registered = sys_common::at_exit(move || {
self.lock.lock();
let ptr = self.ptr.get();
self.ptr.set(1 as *mut _);
self.ptr.set(ptr::dangling_mut());
self.lock.unlock();
drop(Box::from_raw(ptr))
});
Expand Down
1 change: 1 addition & 0 deletions src/libstd/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -301,6 +301,7 @@
#![feature(placement_in_syntax)]
#![feature(placement_new_protocol)]
#![feature(prelude_import)]
#![feature(ptr_dangling)]
#![feature(rand)]
#![feature(raw)]
#![feature(repr_align)]
Expand Down
8 changes: 4 additions & 4 deletions src/libstd/sys_common/thread_local.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@
//! ```ignore (cannot-doctest-private-modules)
//! let key = Key::new(None);
//! assert!(key.get().is_null());
//! key.set(1 as *mut u8);
//! key.set(std::ptr::dangling_mut::<u8>());
//! assert!(!key.get().is_null());
//!
//! drop(key); // deallocate this TLS slot.
Expand All @@ -50,7 +50,7 @@
//!
//! unsafe {
//! assert!(KEY.get().is_null());
//! KEY.set(1 as *mut u8);
//! KEY.set(std::ptr::dangling_mut::<u8>());
//! }
//! ```

Expand Down Expand Up @@ -81,7 +81,7 @@ use sys_common::mutex::Mutex;
///
/// unsafe {
/// assert!(KEY.get().is_null());
/// KEY.set(1 as *mut u8);
/// KEY.set(std::ptr::dangling_mut::<u8>());
/// }
/// ```
pub struct StaticKey {
Expand Down Expand Up @@ -110,7 +110,7 @@ pub struct StaticKey {
///
/// let key = Key::new(None);
/// assert!(key.get().is_null());
/// key.set(1 as *mut u8);
/// key.set(std::ptr::dangling_mut::<u8>());
/// assert!(!key.get().is_null());
///
/// drop(key); // deallocate this TLS slot.
Expand Down
4 changes: 2 additions & 2 deletions src/libstd/thread/local.rs
Original file line number Diff line number Diff line change
Expand Up @@ -492,7 +492,7 @@ pub mod os {
pub unsafe fn get(&'static self) -> Option<&'static UnsafeCell<Option<T>>> {
let ptr = self.os.get() as *mut Value<T>;
if !ptr.is_null() {
if ptr as usize == 1 {
if ptr == ptr::dangling_mut() {
return None
}
return Some(&(*ptr).value);
Expand Down Expand Up @@ -520,7 +520,7 @@ pub mod os {
// before we return from the destructor ourselves.
let ptr = Box::from_raw(ptr as *mut Value<T>);
let key = ptr.key;
key.os.set(1 as *mut u8);
key.os.set(ptr::dangling_mut());
drop(ptr);
key.os.set(ptr::null_mut());
}
Expand Down
41 changes: 41 additions & 0 deletions src/test/run-pass/zero-sized-by-ref-iterator.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
// Copyright 2017 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(repr_align, attr_literals, core_intrinsics)]

use std::mem::align_of;
use std::intrinsics::type_name;

fn has_aligned_refs<'a, I, T: 'a>(iterable: I)
where
I: Iterator<Item = &'a T>
{
for elt in iterable {
unsafe {
assert_eq!((elt as *const T as usize) % align_of::<T>(), 0,
"Assertion failed for type {}", type_name::<T>());
}
}
}

fn main() {
#[derive(Copy, Clone)]
struct Zst;

#[derive(Copy, Clone)]
#[repr(align(64))]
struct Aligned;

has_aligned_refs([Zst; 8].iter());
has_aligned_refs([[0f64; 0]; 8].iter());
has_aligned_refs([Aligned; 8].iter());
has_aligned_refs([Zst; 8].iter_mut().map(|t| &*t));
has_aligned_refs([[0f64; 0]; 8].iter_mut().map(|t| &*t));
has_aligned_refs([Aligned; 8].iter_mut().map(|t| &*t));
}