pacman82 / atoi-rs

Parse integers directly from `[u8]` slices in safe code

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Panics on overflow

niklasf opened this issue · comments

Hi, I just stumbled on a problem with overflows. I was expecting:

assert_eq!(None, atoi::<u8>(b"256"));

Instead it panics in debug mode and wraps around in release mode. I am not sure how to fix this, since there do not seem to be generic traits that provide checked addition/multiplication.

Tough. Would switching to u32 and testing size afterwards do the trick for you?

Can your use case be supported by choosing a larger type to read the value? Let's say you want to parse an u8:

if let Some(input) = atoi::<u32>(b"256"){
    if input > std::u8::Max as u32{
        // Deal with overflow
    }
}

If you are in doubt u32 might also not be large enough, to hold the ... wait a moment ...

... I just realised that we would only need to check for the overflow after adding the third digit (for u8) or the say the tenth digit (for u32). Every number of digits smaller won't overflow and every number larger than that is guaranteed to do so. This just might be reasonable cheap.

Closing this issue. Users can now opt into overflow checking using the checked crate. This also allows to distinguish between an overflow and not finding a number.

extern crate atoi;
extern crate checked;

fn main() {
    let number = atoi::atoi::<checked::Checked<u8>>(b"256");
    println!("Result: {:?}", number);
}

Prints: Result: Some("overflow").

Looks good. Thanks