From a8f09d90593de872feff8c42b3fa3b4f4b67cf2b Mon Sep 17 00:00:00 2001
From: Chaichontat Sriworarat <34997334+chaichontat@users.noreply.github.com>
Date: Mon, 23 Aug 2021 10:58:03 -0400
Subject: [PATCH] Day 1 error handling.

Signed-off-by: Chaichontat Sriworarat <34997334+chaichontat@users.noreply.github.com>
---
 src/main.rs        | 25 ++++++++++++++++---------
 src/y2018/day01.rs | 19 ++++++++++---------
 2 files changed, 26 insertions(+), 18 deletions(-)

diff --git a/src/main.rs b/src/main.rs
index 00bf8be..7e01a1b 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -1,17 +1,22 @@
 use std::env;
 
-use advent_of_code::utils::read;
+use advent_of_code::utils::{read, GenericResult};
+use anyhow::Context;
 use itertools::Itertools;
 use paste::paste;
 
-fn main() {
+fn main() -> GenericResult<()> {
     let args = env::args().collect_vec();
     if args.len() != 3 {
         panic!("Invalid arguments.");
     }
 
-    let year = args[1].parse::<u16>().unwrap();
-    let day = args[2].parse::<u16>().unwrap();
+    let year = args[1]
+        .parse::<u16>()
+        .with_context(|| format!("Cannot parse year \"{}\".", args[1]))?;
+    let day = args[2]
+        .parse::<u16>()
+        .with_context(|| format!("Cannot parse day \"{}\".", args[2]))?;
 
     macro_rules! gen_match {
         ($year:expr; $($n:expr)+ ) => {
@@ -21,8 +26,9 @@ fn main() {
                 #[allow(clippy::zero_prefixed_literal)]
                 $(
                     if day == $n {
-                        println!("{:?}", [<day$n>]::combi(&[<day$n>]::parse(&read($year, concat!(stringify!([<day$n>]), ".txt")))));
-                        return;
+                        let data = read($year, concat!(stringify!([<day$n>]), ".txt"));
+                        println!("{:?}", [<day$n>]::combi(&[<day$n>]::parse(&data)?));
+                        return Ok(());
                     }
                 )+
                 panic!(concat!("Invalid day for ", stringify!($year), "."));
@@ -31,9 +37,10 @@ fn main() {
     }
 
     if year == 2018 {
-        gen_match! {2018; 01 18 22};
+        gen_match! {2018; 01};
     } else if year == 2019 {
-    } else {
-        panic!("Invalid year");
+        panic!("Not implemented");
     }
+
+    panic!("Invalid year");
 }
diff --git a/src/y2018/day01.rs b/src/y2018/day01.rs
index 9993223..08084c2 100644
--- a/src/y2018/day01.rs
+++ b/src/y2018/day01.rs
@@ -1,12 +1,12 @@
-use std::iter;
+use std::{iter, num::ParseIntError};
 
 use itertools::Itertools;
 use num::Integer;
 
 type Parsed = i32;
 
-pub fn parse(raw: &str) -> Vec<Parsed> {
-    raw.split('\n').map(|x| x.parse().unwrap()).collect()
+pub fn parse(raw: &str) -> Result<Vec<Parsed>, ParseIntError> {
+    raw.split('\n').map(|x| x.parse()).try_collect()
 }
 
 #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
@@ -16,7 +16,7 @@ struct Div {
     idx: i16,
 }
 
-pub fn combi(parsed: &[Parsed]) -> (u32, u32) {
+pub fn combi(parsed: &[Parsed]) -> Option<(u32, u32)> {
     let mut freq = iter::once(0).chain(parsed.iter().copied()).collect_vec();
 
     freq.iter_mut().fold(0, |acc, i| {
@@ -24,7 +24,7 @@ pub fn combi(parsed: &[Parsed]) -> (u32, u32) {
         *i
     });
 
-    let sum = freq.pop().unwrap();
+    let sum = freq.pop()?;
 
     // Assuming that the answer is not in the first iteration.
     // Otherwise,
@@ -77,9 +77,9 @@ pub fn combi(parsed: &[Parsed]) -> (u32, u32) {
                 None
             }
         })
-        .min();
+        .min()?;
 
-    (sum as u32, freq[idx.unwrap().2 as usize] as u32)
+    Some((sum as u32, freq[idx.2 as usize] as u32))
 }
 
 #[cfg(test)]
@@ -87,7 +87,8 @@ mod tests {
     use super::*;
     use crate::utils::*;
     #[test]
-    fn test() {
-        assert_eq!(combi(&parse(&read(2018, "day01.txt"))), (454, 566));
+    fn test() -> GenericResult<()> {
+        assert_eq!(combi(&parse(&read(2018, "day01.txt"))?), Some((454, 566)));
+        Ok(())
     }
 }