From f00091cbf03fcd3260742ab60ab421a3ec747085 Mon Sep 17 00:00:00 2001 From: Tyler Hallada Date: Fri, 4 Jan 2019 00:04:39 -0500 Subject: [PATCH] Switch to a less verbose input error handling --- src/day7.rs | 51 +++++++++++++-------------------------------------- 1 file changed, 13 insertions(+), 38 deletions(-) diff --git a/src/day7.rs b/src/day7.rs index f3c3af7..5dff572 100644 --- a/src/day7.rs +++ b/src/day7.rs @@ -2,45 +2,22 @@ extern crate regex; use std::collections::HashMap; use std::error::Error; -use std::fmt; use std::fs::File; use std::io::{BufRead, BufReader}; +use std::result; use regex::{Captures, Regex}; +type Result = result::Result>; + const INPUT: &str = "inputs/7.txt"; -#[derive(Debug, Clone, PartialEq)] -struct MalformedInstruction { - details: String, -} - -impl MalformedInstruction { - fn new(msg: &str) -> MalformedInstruction { - MalformedInstruction { - details: msg.to_string(), - } - } -} - -impl fmt::Display for MalformedInstruction { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "{}", self.details) - } -} - -impl Error for MalformedInstruction { - fn description(&self) -> &str { - &self.details - } -} - -pub fn solve_part1() -> Result> { +pub fn solve_part1() -> Result { let mut instructions = read_instructions(INPUT)?; Ok(get_step_sequence(&mut instructions)) } -fn read_instructions(filename: &str) -> Result>, Box> { +fn read_instructions(filename: &str) -> Result>> { let mut instructions: HashMap> = HashMap::new(); lazy_static! { static ref INSTRUCTION_REGEX: Regex = Regex::new( @@ -61,24 +38,22 @@ fn read_instructions(filename: &str) -> Result>, Box dependencies.push(dependency); } None => { - return Err(Box::new(MalformedInstruction { - details: "Malformed instruction line, no fields could be found".to_string(), - })) + return Err(From::from( + "Malformed instruction line, no fields could be found", + )) } }; } Ok(instructions) } -fn get_captured_field(captures: &Captures, field: &str) -> Result> { +fn get_captured_field(captures: &Captures, field: &str) -> Result { match captures.name(field) { Some(capture) => Ok(String::from(capture.as_str())), - None => Err(Box::new(MalformedInstruction { - details: format!( - "Malformed instruction line, field {} could not be found", - field - ), - })), + None => Err(From::from(format!( + "Malformed instruction line, field {} could not be found", + field + ))), } }