diff --git a/library/core/src/num/mod.rs b/library/core/src/num/mod.rs index 5eb7b9096bc5..12ab12d7ee03 100644 --- a/library/core/src/num/mod.rs +++ b/library/core/src/num/mod.rs @@ -1035,6 +1035,11 @@ macro_rules! impl_helper_for { } impl_helper_for! { i8 i16 i32 i64 i128 isize u8 u16 u32 u64 u128 usize } +#[inline(always)] +pub(crate) fn can_not_overflow(radix: u32, is_signed_ty: bool, digits:&[u8]) -> bool { + radix <= 16 && digits.len() <= mem::size_of::() * 2 - is_signed_ty as usize +} + fn from_str_radix(src: &str, radix: u32) -> Result { use self::IntErrorKind::*; use self::ParseIntError as PIE; @@ -1068,7 +1073,7 @@ fn from_str_radix(src: &str, radix: u32) -> Result() * 2 - is_signed_ty as usize { + if can_not_overflow::(radix, is_signed_ty, digits) { // SAFETY: If the len of the str is short compared to the range of the type // we are parsing into, then we can be certain that an overflow will not occur. // This bound is when `radix.pow(digits.len()) - 1 <= T::MAX` but the condition @@ -1093,9 +1098,9 @@ fn from_str_radix(src: &str, radix: u32) -> Result { + ($checked_additive_op:ident, $overflow_err:expr) => { for &c in digits { // When `radix` is passed in as a literal, rather than doing a slow `imul` // the compiler can use shifts if `radix` can be expressed as a @@ -1110,17 +1115,23 @@ fn from_str_radix(src: &str, radix: u32) -> Result(10, true, "99".as_bytes()), true); + assert_eq!(can_not_overflow::(10, true, "129".as_bytes()), false); + } +} \ No newline at end of file