Integer stdin reading code

Hi everyone! I am quite new to Rust. I have been reading The Book, completing the rustlings exercises and would like to train with some 'codewars' and 'open.kattis' challenges.

Sometimes the code is required to read a given input from terminal. And when it is a number, usually I see this method which parses a string:

let mut input_text = String::new();
    io::stdin()
        .read_line(&mut input_text)
        .expect("failed to read from stdin");

After this I can extract the numeric value, if there is one, and make calculations with it.

I wonder, though, if it is possible to not have this conversion step. But to expect and integer and store it directly, like it is possible with C, with only standard libraries?

I usually start my kattis submissions with

let mut input = String::new();
io::stdin().read_to_string(&mut input).unwrap();
let mut input = input.split_ascii_whitespace();

then to read an integer, you just copy paste this:

let v: i32 = input.next().unwrap().parse().unwrap();

Note that the above does not care about newline vs space.

To make fast solutios to kattis problems, I generally read the entire input into a Vec<u8> with stdin().read_to_end(...), and then parse numbers (or other symbols) directly from the buffer, one byte at a time.

Handling one byte at a time (if its in (b'0'..=b'9') do result = result * 10 + (byte - b'0'), if it's a whitespace (or whatever) return result) is gonna be a lot faster than first finding out how long subslice of the data is a number and then do subslice.parse(). Splitting the input in lines is also often wasted, as well as checking that the input is valid utf-8.

(Yes, my kattis solutions are a lot different than my other rust code. Still, I rarely use any unsafe code or raw pointers, so I still think my solutions benefit from being writen in Rust rather than c++).

Hey @kaj what a nice performance you managed!

Those are some interesting ideas. Thank you for the quick response.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.