Auto merge of #55278 - Centril:constification-1, r=alexcrichton

Minor standard library constification

This PR makes some bits of the standard library into `const fn`s.
I've tried to be as aggressive as I possibly could in the constification.
The list is rather small due to how restrictive `const fn` is at the moment.

r? @oli-obk cc @rust-lang/libs

Stable public APIs affected:
+ [x] `Cell::as_ptr`
+ [x] `UnsafeCell::get`
+ [x] `char::is_ascii`
+ [x] `iter::empty`
+ [x] `ManuallyDrop::{new, into_inner}`
+ [x] `RangeInclusive::{start, end}`
+ [x] `NonNull::as_ptr`
+ [x] `{[T], str}::as_ptr`
+ [x] `Duration::{as_secs, subsec_millis, subsec_micros, subsec_nanos}`
+ [x] `CStr::as_ptr`
+ [x] `Ipv4Addr::is_unspecified`
+ [x] `Ipv6Addr::new`
+ [x] `Ipv6Addr::octets`

Unstable public APIs affected:
+ [x] `Duration::{as_millis, as_micros, as_nanos, as_float_secs}`
+ [x] `Wrapping::{count_ones, count_zeros, trailing_zeros, rotate_left, rotate_right, swap_bytes, reverse_bits, from_be, from_le, to_be, to_le, leading_zeros, is_positive, is_negative, leading_zeros}`
+ [x] `core::convert::identity`

--------------------------

## Removed from list in first pass:

Stable public APIs affected:
+ [ ] `BTree{Map, Set}::{len, is_empty}`
+ [ ] `VecDeque::is_empty`
+ [ ] `String::{is_empty, len}`
+ [ ] `FromUtf8Error::utf8_error`
+ [ ] `Vec<T>::{is_empty, len}`
+ [ ] `Layout::size`
+ [ ] `DecodeUtf16Error::unpaired_surrogate`
+ [ ] `core::fmt::{fill, width, precision, sign_plus, sign_minus, alternate, sign_aware_zero_pad}`
+ [ ] `panic::Location::{file, line, column}`
+ [ ] `{ChunksExact, RChunksExact}::remainder`
+ [ ] `Utf8Error::valid_up_to`
+ [ ] `VacantEntry::key`
+ [ ] `NulError::nul_position`
+ [ ] `IntoStringError::utf8_error`
+ [ ] `IntoInnerError::error`
+ [ ] `io::Chain::get_ref`
+ [ ] `io::Take::{limit, get_ref}`
+ [ ] `SocketAddrV6::{flowinfo, scope_id}`
+ [ ] `PrefixComponent::{kind, as_os_str}`
+ [ ] `Path::{ancestors, display}`
+ [ ] `WaitTimeoutResult::timed_out`
+ [ ] `Receiver::{iter, try_iter}`
+ [ ] `thread::JoinHandle::thread`
+ [ ] `SystemTimeError::duration`

Unstable public APIs affected:
+ [ ] `core::fmt::Arguments::new_v1`
+ [ ] `core::fmt::Arguments::new_v1_formatted`
+ [ ] `Pin::{get_ref, into_ref}`
+ [ ] `Utf8Lossy::chunks`
+ [ ] `LocalWaker::as_waker`
+ [ ] `panic::PanicInfo::{internal_constructor, message, location}`
+ [ ] `panic::Location::{internal_constructor }`

## Removed from list in 2nd pass:

Stable public APIs affected:
+ [ ] `LinkedList::{new, iter, is_empty, len}`
+ [ ] `mem::forget`
+ [ ] `Cursor::{new, get_ref, position}`
+ [ ] `io::{empty, repeat, sink}`
+ [ ] `PoisonError::new`
+ [ ] `thread::Builder::new`
+ [ ] `process::Stdio::{piped, inherit, null}`

Unstable public APIs affected:
+ [ ] `io::Initializer::{zeroing, should_initialize}`
This commit is contained in:
bors 2018-11-12 18:54:11 +00:00
commit 65204a97d4
28 changed files with 118 additions and 85 deletions

View File

@ -474,7 +474,7 @@ impl<T: ?Sized> Cell<T> {
/// ```
#[inline]
#[stable(feature = "cell_as_ptr", since = "1.12.0")]
pub fn as_ptr(&self) -> *mut T {
pub const fn as_ptr(&self) -> *mut T {
self.value.get()
}
@ -1508,7 +1508,7 @@ impl<T: ?Sized> UnsafeCell<T> {
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn get(&self) -> *mut T {
pub const fn get(&self) -> *mut T {
&self.value as *const T as *mut T
}
}

View File

@ -903,7 +903,7 @@ impl char {
/// ```
#[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
#[inline]
pub fn is_ascii(&self) -> bool {
pub const fn is_ascii(&self) -> bool {
*self as u32 <= 0x7F
}

View File

@ -104,7 +104,6 @@
/// assert_eq!(vec![1, 3], filtered);
/// ```
#[unstable(feature = "convert_id", issue = "53500")]
#[rustc_const_unstable(feature = "const_convert_id")]
#[inline]
pub const fn identity<T>(x: T) -> T { x }

View File

@ -283,7 +283,7 @@ impl<T> Default for Empty<T> {
/// assert_eq!(None, nope.next());
/// ```
#[stable(feature = "iter_empty", since = "1.2.0")]
pub fn empty<T>() -> Empty<T> {
pub const fn empty<T>() -> Empty<T> {
Empty(marker::PhantomData)
}

View File

@ -82,7 +82,6 @@
#![feature(const_fn)]
#![feature(const_int_ops)]
#![feature(const_fn_union)]
#![feature(const_manually_drop_new)]
#![feature(custom_attribute)]
#![feature(doc_cfg)]
#![feature(doc_spotlight)]

View File

@ -942,7 +942,6 @@ impl<T> ManuallyDrop<T> {
/// ManuallyDrop::new(Box::new(()));
/// ```
#[stable(feature = "manually_drop", since = "1.20.0")]
#[rustc_const_unstable(feature = "const_manually_drop_new")]
#[inline]
pub const fn new(value: T) -> ManuallyDrop<T> {
ManuallyDrop { value }
@ -961,7 +960,7 @@ impl<T> ManuallyDrop<T> {
/// ```
#[stable(feature = "manually_drop", since = "1.20.0")]
#[inline]
pub fn into_inner(slot: ManuallyDrop<T>) -> T {
pub const fn into_inner(slot: ManuallyDrop<T>) -> T {
slot.value
}

View File

@ -22,4 +22,3 @@ pub fn estimate_scaling_factor(mant: u64, exp: i16) -> i16 {
// therefore this always underestimates (or is exact), but not much.
(((nbits + exp as i64) * 1292913986) >> 32) as i16
}

View File

@ -658,4 +658,3 @@ pub fn to_exact_fixed_str<'a, T, F>(mut format_exact: F, v: T,
}
}
}

View File

@ -387,7 +387,7 @@ assert_eq!(n.count_ones(), 3);
```"),
#[inline]
#[unstable(feature = "wrapping_int_impl", issue = "32463")]
pub fn count_ones(self) -> u32 {
pub const fn count_ones(self) -> u32 {
self.0.count_ones()
}
}
@ -407,7 +407,7 @@ assert_eq!(Wrapping(!0", stringify!($t), ").count_zeros(), 0);
```"),
#[inline]
#[unstable(feature = "wrapping_int_impl", issue = "32463")]
pub fn count_zeros(self) -> u32 {
pub const fn count_zeros(self) -> u32 {
self.0.count_zeros()
}
}
@ -430,7 +430,7 @@ assert_eq!(n.trailing_zeros(), 3);
```"),
#[inline]
#[unstable(feature = "wrapping_int_impl", issue = "32463")]
pub fn trailing_zeros(self) -> u32 {
pub const fn trailing_zeros(self) -> u32 {
self.0.trailing_zeros()
}
}
@ -456,7 +456,7 @@ assert_eq!(n.trailing_zeros(), 3);
/// ```
#[inline]
#[unstable(feature = "wrapping_int_impl", issue = "32463")]
pub fn rotate_left(self, n: u32) -> Self {
pub const fn rotate_left(self, n: u32) -> Self {
Wrapping(self.0.rotate_left(n))
}
@ -481,7 +481,7 @@ assert_eq!(n.trailing_zeros(), 3);
/// ```
#[inline]
#[unstable(feature = "wrapping_int_impl", issue = "32463")]
pub fn rotate_right(self, n: u32) -> Self {
pub const fn rotate_right(self, n: u32) -> Self {
Wrapping(self.0.rotate_right(n))
}
@ -505,7 +505,7 @@ assert_eq!(n.trailing_zeros(), 3);
/// ```
#[inline]
#[unstable(feature = "wrapping_int_impl", issue = "32463")]
pub fn swap_bytes(self) -> Self {
pub const fn swap_bytes(self) -> Self {
Wrapping(self.0.swap_bytes())
}
@ -532,7 +532,7 @@ assert_eq!(n.trailing_zeros(), 3);
/// ```
#[unstable(feature = "reverse_bits", issue = "48763")]
#[inline]
pub fn reverse_bits(self) -> Self {
pub const fn reverse_bits(self) -> Self {
Wrapping(self.0.reverse_bits())
}
@ -560,7 +560,7 @@ if cfg!(target_endian = \"big\") {
```"),
#[inline]
#[unstable(feature = "wrapping_int_impl", issue = "32463")]
pub fn from_be(x: Self) -> Self {
pub const fn from_be(x: Self) -> Self {
Wrapping(<$t>::from_be(x.0))
}
}
@ -589,7 +589,7 @@ if cfg!(target_endian = \"little\") {
```"),
#[inline]
#[unstable(feature = "wrapping_int_impl", issue = "32463")]
pub fn from_le(x: Self) -> Self {
pub const fn from_le(x: Self) -> Self {
Wrapping(<$t>::from_le(x.0))
}
}
@ -618,7 +618,7 @@ if cfg!(target_endian = \"big\") {
```"),
#[inline]
#[unstable(feature = "wrapping_int_impl", issue = "32463")]
pub fn to_be(self) -> Self {
pub const fn to_be(self) -> Self {
Wrapping(self.0.to_be())
}
}
@ -647,7 +647,7 @@ if cfg!(target_endian = \"little\") {
```"),
#[inline]
#[unstable(feature = "wrapping_int_impl", issue = "32463")]
pub fn to_le(self) -> Self {
pub const fn to_le(self) -> Self {
Wrapping(self.0.to_le())
}
}
@ -707,7 +707,7 @@ assert_eq!(n.leading_zeros(), 3);
```"),
#[inline]
#[unstable(feature = "wrapping_int_impl", issue = "32463")]
pub fn leading_zeros(self) -> u32 {
pub const fn leading_zeros(self) -> u32 {
self.0.leading_zeros()
}
}
@ -784,7 +784,7 @@ assert!(!Wrapping(-10", stringify!($t), ").is_positive());
```"),
#[inline]
#[unstable(feature = "wrapping_int_impl", issue = "32463")]
pub fn is_positive(self) -> bool {
pub const fn is_positive(self) -> bool {
self.0.is_positive()
}
}
@ -806,7 +806,7 @@ assert!(!Wrapping(10", stringify!($t), ").is_negative());
```"),
#[inline]
#[unstable(feature = "wrapping_int_impl", issue = "32463")]
pub fn is_negative(self) -> bool {
pub const fn is_negative(self) -> bool {
self.0.is_negative()
}
}
@ -836,7 +836,7 @@ assert_eq!(n.leading_zeros(), 2);
```"),
#[inline]
#[unstable(feature = "wrapping_int_impl", issue = "32463")]
pub fn leading_zeros(self) -> u32 {
pub const fn leading_zeros(self) -> u32 {
self.0.leading_zeros()
}
}

View File

@ -416,7 +416,7 @@ impl<Idx> RangeInclusive<Idx> {
/// ```
#[stable(feature = "inclusive_range_methods", since = "1.27.0")]
#[inline]
pub fn start(&self) -> &Idx {
pub const fn start(&self) -> &Idx {
&self.start
}
@ -440,7 +440,7 @@ impl<Idx> RangeInclusive<Idx> {
/// ```
#[stable(feature = "inclusive_range_methods", since = "1.27.0")]
#[inline]
pub fn end(&self) -> &Idx {
pub const fn end(&self) -> &Idx {
&self.end
}

View File

@ -2905,7 +2905,7 @@ impl<T: ?Sized> NonNull<T> {
/// Acquires the underlying `*mut` pointer.
#[stable(feature = "nonnull", since = "1.25.0")]
#[inline]
pub fn as_ptr(self) -> *mut T {
pub const fn as_ptr(self) -> *mut T {
self.pointer.0 as *mut T
}

View File

@ -385,7 +385,6 @@ impl<T> [T] {
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
#[rustc_const_unstable(feature = "const_slice_as_ptr")]
pub const fn as_ptr(&self) -> *const T {
self as *const [T] as *const T
}

View File

@ -2277,7 +2277,6 @@ impl str {
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
#[rustc_const_unstable(feature = "const_str_as_ptr")]
pub const fn as_ptr(&self) -> *const u8 {
self as *const str as *const u8
}

View File

@ -209,7 +209,6 @@ impl Duration {
///
/// [`subsec_nanos`]: #method.subsec_nanos
#[stable(feature = "duration", since = "1.3.0")]
#[rustc_const_unstable(feature="duration_getters")]
#[inline]
pub const fn as_secs(&self) -> u64 { self.secs }
@ -229,7 +228,6 @@ impl Duration {
/// assert_eq!(duration.subsec_millis(), 432);
/// ```
#[stable(feature = "duration_extras", since = "1.27.0")]
#[rustc_const_unstable(feature="duration_getters")]
#[inline]
pub const fn subsec_millis(&self) -> u32 { self.nanos / NANOS_PER_MILLI }
@ -249,7 +247,6 @@ impl Duration {
/// assert_eq!(duration.subsec_micros(), 234_567);
/// ```
#[stable(feature = "duration_extras", since = "1.27.0")]
#[rustc_const_unstable(feature="duration_getters")]
#[inline]
pub const fn subsec_micros(&self) -> u32 { self.nanos / NANOS_PER_MICRO }
@ -269,7 +266,6 @@ impl Duration {
/// assert_eq!(duration.subsec_nanos(), 10_000_000);
/// ```
#[stable(feature = "duration", since = "1.3.0")]
#[rustc_const_unstable(feature="duration_getters")]
#[inline]
pub const fn subsec_nanos(&self) -> u32 { self.nanos }
@ -286,7 +282,7 @@ impl Duration {
/// ```
#[unstable(feature = "duration_as_u128", issue = "50202")]
#[inline]
pub fn as_millis(&self) -> u128 {
pub const fn as_millis(&self) -> u128 {
self.secs as u128 * MILLIS_PER_SEC as u128 + (self.nanos / NANOS_PER_MILLI) as u128
}
@ -303,7 +299,7 @@ impl Duration {
/// ```
#[unstable(feature = "duration_as_u128", issue = "50202")]
#[inline]
pub fn as_micros(&self) -> u128 {
pub const fn as_micros(&self) -> u128 {
self.secs as u128 * MICROS_PER_SEC as u128 + (self.nanos / NANOS_PER_MICRO) as u128
}
@ -320,7 +316,7 @@ impl Duration {
/// ```
#[unstable(feature = "duration_as_u128", issue = "50202")]
#[inline]
pub fn as_nanos(&self) -> u128 {
pub const fn as_nanos(&self) -> u128 {
self.secs as u128 * NANOS_PER_SEC as u128 + self.nanos as u128
}
@ -478,7 +474,7 @@ impl Duration {
/// ```
#[unstable(feature = "duration_float", issue = "54361")]
#[inline]
pub fn as_float_secs(&self) -> f64 {
pub const fn as_float_secs(&self) -> f64 {
(self.secs as f64) + (self.nanos as f64) / (NANOS_PER_SEC as f64)
}

View File

@ -2598,4 +2598,3 @@ pub mod conversions {
];
}

View File

@ -1091,7 +1091,7 @@ impl CStr {
/// [`CString`]: struct.CString.html
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn as_ptr(&self) -> *const c_char {
pub const fn as_ptr(&self) -> *const c_char {
self.inner.as_ptr()
}

View File

@ -424,7 +424,7 @@ impl Ipv4Addr {
/// assert_eq!(Ipv4Addr::new(45, 22, 13, 197).is_unspecified(), false);
/// ```
#[stable(feature = "ip_shared", since = "1.12.0")]
pub fn is_unspecified(&self) -> bool {
pub const fn is_unspecified(&self) -> bool {
self.inner.s_addr == 0
}
@ -862,7 +862,6 @@ impl Ipv6Addr {
/// let addr = Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_unstable(feature = "const_ip")]
pub const fn new(a: u16, b: u16, c: u16, d: u16, e: u16, f: u16,
g: u16, h: u16) -> Ipv6Addr {
Ipv6Addr {
@ -1224,7 +1223,7 @@ impl Ipv6Addr {
/// [255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
/// ```
#[stable(feature = "ipv6_to_octets", since = "1.12.0")]
pub fn octets(&self) -> [u8; 16] {
pub const fn octets(&self) -> [u8; 16] {
self.inner.s6_addr
}
}

View File

@ -10,8 +10,6 @@
// compile-pass
#![feature(duration_getters)]
use std::time::Duration;
fn main() {

View File

@ -23,13 +23,16 @@ unsafe impl Sync for Foo {}
static FOO: Foo = Foo(UnsafeCell::new(42));
fn foo() {}
static BAR: () = unsafe {
*FOO.0.get() = 5;
//~^ ERROR calls in statics are limited to constant functions, tuple structs and tuple variants
//~^ ERROR statements in statics are unstable (see issue #48821)
// This error is caused by a separate bug that the feature gate error is reported
// even though the feature gate "const_let" is active.
//~| statements in statics are unstable (see issue #48821)
foo();
//~^ ERROR calls in statics are limited to constant functions, tuple structs and tuple variants
};
fn main() {

View File

@ -1,17 +1,17 @@
error[E0015]: calls in statics are limited to constant functions, tuple structs and tuple variants
--> $DIR/mod-static-with-const-fn.rs:27:6
|
LL | *FOO.0.get() = 5;
| ^^^^^^^^^^^
error[E0658]: statements in statics are unstable (see issue #48821)
--> $DIR/mod-static-with-const-fn.rs:27:5
--> $DIR/mod-static-with-const-fn.rs:29:5
|
LL | *FOO.0.get() = 5;
| ^^^^^^^^^^^^^^^^
|
= help: add #![feature(const_let)] to the crate attributes to enable
error[E0015]: calls in statics are limited to constant functions, tuple structs and tuple variants
--> $DIR/mod-static-with-const-fn.rs:34:5
|
LL | foo();
| ^^^^^
error: aborting due to 2 previous errors
Some errors occurred: E0015, E0658.

View File

@ -0,0 +1,30 @@
use std::cell::*;
// not ok, because this would create a silent constant with interior mutability.
// the rules could be relaxed in the future
static FOO: Wrap<*mut u32> = Wrap(Cell::new(42).as_ptr());
//~^ ERROR cannot borrow a constant which may contain interior mutability
static FOO3: Wrap<Cell<u32>> = Wrap(Cell::new(42));
// ok
static FOO4: Wrap<*mut u32> = Wrap(FOO3.0.as_ptr());
// not ok, because the `as_ptr` call takes a reference to a type with interior mutability
// which is not allowed in constants
const FOO2: *mut u32 = Cell::new(42).as_ptr();
//~^ ERROR cannot borrow a constant which may contain interior mutability
struct IMSafeTrustMe(UnsafeCell<u32>);
unsafe impl Send for IMSafeTrustMe {}
unsafe impl Sync for IMSafeTrustMe {}
static BAR: IMSafeTrustMe = IMSafeTrustMe(UnsafeCell::new(5));
struct Wrap<T>(T);
unsafe impl<T> Send for Wrap<T> {}
unsafe impl<T> Sync for Wrap<T> {}
static BAR_PTR: Wrap<*mut u32> = Wrap(BAR.0.get());
fn main() {}

View File

@ -0,0 +1,15 @@
error[E0492]: cannot borrow a constant which may contain interior mutability, create a static instead
--> $DIR/cell.rs:5:35
|
LL | static FOO: Wrap<*mut u32> = Wrap(Cell::new(42).as_ptr());
| ^^^^^^^^^^^^^
error[E0492]: cannot borrow a constant which may contain interior mutability, create a static instead
--> $DIR/cell.rs:14:24
|
LL | const FOO2: *mut u32 = Cell::new(42).as_ptr();
| ^^^^^^^^^^^^^
error: aborting due to 2 previous errors
For more information about this error, try `rustc --explain E0492`.

View File

@ -0,0 +1,9 @@
// run-pass
static X: bool = 'a'.is_ascii();
static Y: bool = 'ä'.is_ascii();
fn main() {
assert!(X);
assert!(!Y);
}

View File

@ -0,0 +1,9 @@
// run-pass
const I: std::iter::Empty<u32> = std::iter::empty();
fn main() {
for i in I {
panic!("magical value creation: {}", i);
}
}

View File

@ -0,0 +1,10 @@
// compile-pass
struct Wrap<T>(T);
unsafe impl<T> Send for Wrap<T> {}
unsafe impl<T> Sync for Wrap<T> {}
static FOO: Wrap<*const u32> = Wrap([42, 44, 46].as_ptr());
static BAR: Wrap<*const u8> = Wrap("hello".as_ptr());
fn main() {}

View File

@ -1,17 +0,0 @@
// Copyright 2018 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.
// This test should fail since identity is not stable as a const fn yet.
#![feature(convert_id)]
fn main() {
const _FOO: u8 = ::std::convert::identity(42u8);
}

View File

@ -1,10 +0,0 @@
error: `std::convert::identity` is not yet stable as a const fn
--> $DIR/convert-id-const-no-gate.rs:16:22
|
LL | const _FOO: u8 = ::std::convert::identity(42u8);
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
= help: in Nightly builds, add `#![feature(const_convert_id)]` to the crate attributes to enable
error: aborting due to previous error

View File

@ -8,12 +8,11 @@
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// This test should pass since we've opted into 'identity' as an
// unstable const fn.
// This test should pass since 'identity' is const fn.
// compile-pass
#![feature(convert_id, const_convert_id)]
#![feature(convert_id)]
fn main() {
const _FOO: u8 = ::std::convert::identity(42u8);