diff --git a/README.md b/README.md index 2fd0ca4..134eeda 100644 --- a/README.md +++ b/README.md @@ -2,6 +2,7 @@ https://adventofcode.com/2021 +Error handling: http://web.mit.edu/rust-lang_v1.25/arch/amd64_ubuntu1404/share/doc/rust/html/book/first-edition/error-handling.html#a-brief-interlude-unwrapping-isnt-evil ## Resources * https://github.com/ithinuel/advent-of-code-rust/tree/2020/src/bin diff --git a/src/day1.rs b/src/day1.rs index 2b4ccad..6fbbdf4 100644 --- a/src/day1.rs +++ b/src/day1.rs @@ -1,13 +1,22 @@ use std::fs::File; -use std::io::prelude::*; +use std::io::{prelude::*, self}; +use std::num::ParseIntError; -pub fn input_from_file(filename: &str) -> Vec { - let mut file = File::open(filename).expect("Can't open file"); +#[derive(Debug)] +pub enum InputFromFileError { + ParseIntError(ParseIntError), + IoError(io::Error), +} + +pub fn input_from_file(filename: &str) -> Result, InputFromFileError> { + let mut file = File::open(filename).map_err(InputFromFileError::IoError)?; let mut contents = String::new(); - file.read_to_string(&mut contents).expect("Oops! Can not read the file..."); + file.read_to_string(&mut contents).map_err(InputFromFileError::IoError)?; - return contents.split_whitespace().map(|s| s.parse::().unwrap()).collect(); + contents.split_whitespace() + .map(|s| s.parse().map_err(InputFromFileError::ParseIntError)) + .collect() } pub fn part1(depths: &[u32]) -> u32 { diff --git a/src/main.rs b/src/main.rs index 3a1ef99..a65299e 100644 --- a/src/main.rs +++ b/src/main.rs @@ -2,7 +2,8 @@ mod day1; fn main() { let input_filename = "input.txt"; - let input = day1::input_from_file(input_filename); + let input = day1::input_from_file(input_filename) + .expect("Failed to read input.txt"); let result1 = day1::part1(&input); let result2 = day1::part2(&input); println!("Part 1 result: {}", result1);