Rollup merge of #68976 - ecstatic-morse:const-non-zero, r=dtolnay

Make `num::NonZeroX::new` an unstable `const fn`

cc #53718

These require `#[feature(const_if_match)]`, meaning they must remain unstable for the time being.
This commit is contained in:
Dylan DPC 2020-02-10 01:54:18 +01:00 committed by GitHub
commit e3315f6742
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 12 additions and 2 deletions

View File

@ -69,8 +69,9 @@ assert_eq!(size_of::<Option<core::num::", stringify!($Ty), ">>(), size_of::<", s
/// Creates a non-zero if the given value is not zero.
#[$stability]
#[rustc_const_unstable(feature = "const_nonzero_int_methods", issue = "53718")]
#[inline]
pub fn new(n: $Int) -> Option<Self> {
pub const fn new(n: $Int) -> Option<Self> {
if n != 0 {
// SAFETY: we just checked that there's no `0`
Some(unsafe { Self(n) })

View File

@ -1,9 +1,18 @@
// build-pass (FIXME(62277): could be check-pass?)
// run-pass
#![feature(const_nonzero_int_methods)]
use std::num::NonZeroU8;
const X: NonZeroU8 = unsafe { NonZeroU8::new_unchecked(5) };
const Y: u8 = X.get();
const ZERO: Option<NonZeroU8> = NonZeroU8::new(0);
const ONE: Option<NonZeroU8> = NonZeroU8::new(1);
fn main() {
assert_eq!(Y, 5);
assert!(ZERO.is_none());
assert_eq!(ONE.unwrap().get(), 1);
}