From 69eea45244fad553994b19da27be4cae86bb3387 Mon Sep 17 00:00:00 2001 From: heca-project <47336222+heca-project@users.noreply.github.com> Date: Sun, 31 May 2020 20:08:08 -0700 Subject: [PATCH 1/3] impl TryFrom from native to NonZero You can now do the following: ``` let p: u8 = 5; let q: NonZeroU8 = p.try_into()?; ``` Which improves API design a bit nicer. --- src/libcore/num/mod.rs | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/src/libcore/num/mod.rs b/src/libcore/num/mod.rs index c164e893b4fbf..83ad452a0877c 100644 --- a/src/libcore/num/mod.rs +++ b/src/libcore/num/mod.rs @@ -5,6 +5,7 @@ #![stable(feature = "rust1", since = "1.0.0")] use crate::convert::Infallible; +use crate::convert::TryFrom; use crate::fmt; use crate::intrinsics; use crate::mem; @@ -110,6 +111,20 @@ assert_eq!(size_of::>(), size_of::<", s } } } + + #[stable(feature = "try_from", since = "1.34.0")] + impl TryFrom<$Int> for $Ty { + type Error = TryFromIntError; + fn try_from(n: $Int) -> Result { + if n != 0 { + // SAFETY: we just checked that there's no `0` + Ok(unsafe { Self(n) }) + } else { + Err(TryFromIntError(())) + } + } + } + #[stable(feature = "nonzero_bitor", since = "1.45.0")] impl BitOr for $Ty { From 1adb74b7c0fc3b0125d2bd0ebb77472bfec43840 Mon Sep 17 00:00:00 2001 From: heca-project <47336222+heca-project@users.noreply.github.com> Date: Mon, 1 Jun 2020 10:30:25 -0700 Subject: [PATCH 2/3] Update src/libcore/num/mod.rs Remove not needed unsafe Co-authored-by: kennytm --- src/libcore/num/mod.rs | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/src/libcore/num/mod.rs b/src/libcore/num/mod.rs index 83ad452a0877c..e4861cc61d196 100644 --- a/src/libcore/num/mod.rs +++ b/src/libcore/num/mod.rs @@ -116,12 +116,7 @@ assert_eq!(size_of::>(), size_of::<", s impl TryFrom<$Int> for $Ty { type Error = TryFromIntError; fn try_from(n: $Int) -> Result { - if n != 0 { - // SAFETY: we just checked that there's no `0` - Ok(unsafe { Self(n) }) - } else { - Err(TryFromIntError(())) - } + Self::new(n).ok_or(TryFromIntError(())) } } From 03b23e9db845ebc4ae4b087cd5f11b92e6225007 Mon Sep 17 00:00:00 2001 From: heca-project <47336222+heca-project@users.noreply.github.com> Date: Mon, 1 Jun 2020 11:49:11 -0700 Subject: [PATCH 3/3] Removed a whitespace --- src/libcore/num/mod.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/libcore/num/mod.rs b/src/libcore/num/mod.rs index e4861cc61d196..d73ec11d2e5d6 100644 --- a/src/libcore/num/mod.rs +++ b/src/libcore/num/mod.rs @@ -111,7 +111,7 @@ assert_eq!(size_of::>(), size_of::<", s } } } - + #[stable(feature = "try_from", since = "1.34.0")] impl TryFrom<$Int> for $Ty { type Error = TryFromIntError; @@ -120,7 +120,6 @@ assert_eq!(size_of::>(), size_of::<", s } } - #[stable(feature = "nonzero_bitor", since = "1.45.0")] impl BitOr for $Ty { type Output = Self;