Description
The from_str methods of all integer types, signed and unsigned, may return Some() values in the case of an overflow. For example, between 256 and 1000, u8::from_str() returns None for less than half of the values and Some(nonsense) for the rest.
Examples:
u8::from_str("1000"); // => Some(232)
u16::from_str("100000"); // => Some(34464)
u32::from_str("10000000000"); // => Some(1410065408)
u64::from_str("30000000000000000000"); // => Some(11553255926290448384)
i8::from_str("600"); // => Some(88)
i16::from_str("80000"); // => Some(14464)
i32::from_str("5000000000"); // => Some(705032704)
i64::from_str("21000000000000000000"); // => Some(2553255926290448384)
Floats don't seem to have this problem, but are inconsistent in their behavior on overflow:
f32::from_str("1000000000000000000000000000000000000000"); // => Some(inf)
f32::from_str("10000000000000000000000000000000000000000"); // => None
f32::from_str("1e40"); // same number as above => Some(inf)
Why this happens:
from_str_bytes_common (from strconv.rs), which is used by all these methods, does the following:
It converts the string byte by byte and keeps an accumulator (of the type it converts to) with the value of the bytes already converted. After every byte it tries to detect overflows by checking if the accumulator got smaller.
The problem is that this only works if the value added to the accumulator is less than the maximum value its type can hold. In cases where the added value is bigger, the accumulator can overflow and still end up larger than before.
Example:
u8::from_str("1000");
// byte 1: acc = 1, old = 0
// byte 2: acc = 10, old = 1
// byte 3: acc = 100, old = 10
// byte 4: acc = 232, old = 100