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

impl TryFrom<{integer}> for NonZero{integer} #68825

Closed
wants to merge 5 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
16 changes: 15 additions & 1 deletion src/libcore/num/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

#![stable(feature = "rust1", since = "1.0.0")]

use crate::convert::Infallible;
use crate::convert::{Infallible, TryFrom};
use crate::fmt;
use crate::intrinsics;
use crate::mem;
Expand Down Expand Up @@ -100,6 +100,20 @@ assert_eq!(size_of::<Option<core::num::", stringify!($Ty), ">>(), size_of::<", s
}
}

#[stable(feature = "try_from_nonzero", since = "1.43.0")]
impl TryFrom<$Int> for $Ty {
type Error = ();
doc_comment! {
concat!(
"Converts a `", stringify!($Int), "` into an `", stringify!($Ty),
"` if it is non-zero"),
fn try_from(int: $Int) -> Result<Self, ()> {
Self::new(int).ok_or(())
}
}

}

impl_nonzero_fmt! {
#[$stability] (Debug, Display, Binary, Octal, LowerHex, UpperHex) for $Ty
}
Expand Down
10 changes: 10 additions & 0 deletions src/test/ui/numeric/numeric-cast-3.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
// make sure that TryInto is implemented for NonZero{integer}
//
// check-pass
use std::num::NonZeroUsize;
use std::convert::TryInto;

fn main() {
let a: NonZeroUsize = 1_usize.try_into().unwrap();
let b: NonZeroUsize = 0_usize.try_into().unwrap();
}