Skip to content

Commit 5f78bb4

Browse files
committed
Better explanation
1 parent e898257 commit 5f78bb4

File tree

1 file changed

+7
-6
lines changed

1 file changed

+7
-6
lines changed

library/core/src/num/mod.rs

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1069,13 +1069,14 @@ fn from_str_radix<T: FromStrRadixHelper>(src: &str, radix: u32) -> Result<T, Par
10691069
let mut result = T::from_u32(0);
10701070

10711071
if radix <= 16 && digits.len() <= mem::size_of::<T>() * 2 - is_signed_ty as usize {
1072-
// SAFETY: We can take this fast path when `radix.pow(digits.len()) - 1 <= T::MAX`
1073-
// but the condition above is a faster (conservative) approximation of this.
1072+
// SAFETY: If the len of the str is short compared to the range of the type
1073+
// we are parsing into, then we can be certain that an overflow will not occur.
1074+
// This bound is when `radix.pow(digits.len()) - 1 <= T::MAX` but the condition
1075+
// above is a faster (conservative) approximation of this.
10741076
//
1075-
// Consider the highest radix of 16:
1076-
// `u8::MAX` is `ff` (2 characters), `u16::MAX` is `ffff` (4 characters)
1077-
// We can be sure that any src len of 2 would fit in a u8 so we don't need
1078-
// to check for overflow.
1077+
// Consider radix 16 as it has the most chance of overflow per digit:
1078+
// `u8::MAX` is `ff` - any str of len 2 is guaranteed to not overflow.
1079+
// `i8::MAX` is `7f` - only a str of len 1 is guaranteed to not overflow.
10791080
unsafe {
10801081
let unchecked_additive_op =
10811082
if is_positive { T::unchecked_add } else { T::unchecked_sub };

0 commit comments

Comments
 (0)