I'm making a small program to benchmark Rust's performance compared to some other languages. The idea I came up with, was to take a file (with the numbers 1 to 10000000 written to it in separate lines) as a command line argument:
1
2
3
...
9999999
10000000
read the file, and then multiple every line in that file by two and write those back to the same file, so the end result would look like this:
2
4
6
...
19999998
20000000
My code works, and does exactly what it should do. I am especially looking for ways how I could make the code cleaner while also making it run faster. I'm currently running it with:
$ cargo run --release numbers.txt
The program:
use std::env;
use std::fs::OpenOptions;
use std::io::Read;
use std::io::Write;
fn main() {
let args: Vec<String> = env::args().collect();
let file_path = &args[1];
let mut file = OpenOptions::new().read(true).open(file_path).unwrap();
let mut contents = String::new();
file.read_to_string(&mut contents).unwrap();
let vec: Vec<i32> = contents.lines()
.map(|line| line.trim().parse::<i32>().unwrap() * 2)
.collect();
let mut file = OpenOptions::new().write(true).open(file_path).unwrap();
for line in vec {
write!(file, "{}\n", line).unwrap();
}
}