---
# System prepended metadata

title: Boilerplate Code Snippets

---

# Boilerplate Code Snippets

### Code benchmark

```
use std::time::{Instant};

let start = Instant::now();

// code to benchmark

let end = Instant::now();
println!("{:?}", (end - start).as_millis());
```

---

### Suppress warnings

Add at the beginning of the cargo source file:
```
#![allow(
    dead_code,
    unused_variables,
    unused_parens,
    unused_imports,
    unused_mut,
    unused_must_use
)]
``` 

---

### Reading command line arguments

Remember `args[0]` is program path like: `"project/code/target/debug/ghc-pr"`. You probably want `args[1]` etc.

```
use std::env;

fn get_cli_args() -> Result<(usize, usize, usize), Box<dyn Error>> {
    let args: Vec<String> = env::args().collect();

    let input_file_index = args[1].parse()?; // example variable names
    let some_other_arg = args[2].parse()?;
    let third_arg = args[3].parse()?;

    Ok((input_file_index, some_other_arg, third_arg))
}
```

---

### Parsing data files

```
fn get_filename(file_number: usize) -> Result<String, Box<dyn Error>> {
    match file_number {
        0 => Ok("data/input/a_example.txt".to_owned()),
        1 => Ok("data/input/b_little_bit_of_everything.txt".to_owned()),
        _ => bail!("Incorrect file number specified."),
    }
}

fn get_cli_args() -> Result<(usize), Box<dyn Error>> {
    let args: Vec<String> = env::args().collect();

    let input_file_index = args[1].parse()?;

    Ok((input_file_index))
}

fn read_input(file_path: &str) -> Result<Vec<String>, Box<dyn Error>> {
    let file = File::open(file_path)?;
    let reader = BufReader::new(file);
    let mut lines = Vec::new();

    for line in reader.lines() {
        let line = line?;
        let line = line.trim().parse()?;
        lines.push(line);
    }

    Ok(lines)
}

fn parse_input_data(input_data: &Vec<String>) -> Result<(u32, u32), Box<dyn Error>> {
    let mut line01 = input_data[0].split_whitespace();
    let line02 = input_data[1].split_whitespace();

    let total_pizzas = line01.next().unwrap().parse()?;
    let total_teams_of_two = line01.next().unwrap().parse()?;

    let book_scores: Vec<u32> = line02.map(|x| x.parse().unwrap()).collect();

    let mut libraries = vec![];
    for i in 0..total_libraries as usize {
        let mut line01 = input_data[i * 2 + 2].split_whitespace();
        let line02 = input_data[i * 2 + 3].split_whitespace();

        // ...
    }

    Ok((
        total_pizzas,
        total_teams_of_two,
    ))
}
```

### Main
```
fn main() -> Result<(), Box<dyn Error>> {
    let (input_file_index) = get_cli_args()?;
    let filename = get_filename(input_file_index)?;

    let input_data = read_input(&filename)?;

    let parsed_input = parse_input_data(&input_data);
}
```