Skip to content

Instantly share code, notes, and snippets.

@daltonclaybrook
Created December 3, 2020 03:44
Show Gist options
  • Save daltonclaybrook/c28660818d220c5ea3c14d37eee28a9c to your computer and use it in GitHub Desktop.
Save daltonclaybrook/c28660818d220c5ea3c14d37eee28a9c to your computer and use it in GitHub Desktop.
#[macro_use]
extern crate lazy_static;
use regex::{Captures, Regex};
use std::fs;
use std::ops::Range;
use std::str::FromStr;
#[derive(Debug)]
enum AdventError {
Unknown,
InvalidRegex,
}
struct Day2Line {
count_range: Range<i32>,
character: char,
password: String,
}
impl FromStr for Day2Line {
type Err = AdventError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
lazy_static! {
static ref RE: Regex = Regex::new(r"^(\d+)\-(\d+) ([a-z])\: ([a-z]+)$").unwrap();
}
let captures = RE.captures(s).ok_or(AdventError::InvalidRegex)?;
let count_start = parse_from_captures(&captures, 1)?;
let count_end = parse_from_captures(&captures, 2)?;
Ok(Day2Line {
count_range: count_start..count_end,
character: parse_from_captures(&captures, 3)?,
password: parse_from_captures(&captures, 4)?,
})
}
}
fn parse_from_captures<T>(captures: &Captures, index: usize) -> Result<T, AdventError>
where
T: FromStr,
{
captures
.get(index)
.ok_or(AdventError::InvalidRegex)?
.as_str()
.parse::<T>()
.map_err(|_| AdventError::InvalidRegex)
}
pub fn read_input_for_day<T>(day: &str) -> std::io::Result<Vec<T>>
where
T: FromStr,
T::Err: std::fmt::Debug,
{
let path = format!("./src/bin/{}/INPUT", day);
let contents = fs::read_to_string(path)?;
let values = contents
.lines()
.map(|l| l.parse().unwrap())
.collect::<Vec<T>>();
Ok(values)
}
fn main() -> std::io::Result<()> {
let input = read_input_for_day::<Day2Line>("day-2")?;
Ok(())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment