diff --git a/day1/src/elven_calories.rs b/day1/src/elven_calories.rs new file mode 100644 index 0000000..f360195 --- /dev/null +++ b/day1/src/elven_calories.rs @@ -0,0 +1,39 @@ +//! Extends the BufReader Lines to support summing based on newlines. +use std::io::BufRead; +use std::io::Lines; + +pub struct Accumulator { + lines: Lines, + current: u32, +} + +pub trait Elvish { + fn elf(self) -> Accumulator; +} + +impl Elvish for Lines { + fn elf(self) -> Accumulator { + Accumulator { + lines: self, + current: 0, + } + } +} + +impl Iterator for Accumulator { + type Item = u32; + + fn next(&mut self) -> Option { + while let Some(Ok(line)) = self.lines.next() { + let line = line.trim(); + if line.is_empty() { + let result = self.current; + self.current = 0; + return Some(result); + } else { + self.current += line.parse::().unwrap(); + } + } + None + } +} diff --git a/day1/src/step1.rs b/day1/src/step1.rs index 062dbea..5182861 100644 --- a/day1/src/step1.rs +++ b/day1/src/step1.rs @@ -1,46 +1,13 @@ +mod elven_calories; + use std::fs::File; use std::io::BufRead; use std::io::BufReader; -use std::io::Lines; use clap::Arg; use clap::Command; -struct Accumulator { - lines: Lines, - current: u32, -} - -trait Elvish { - fn elf(self) -> Accumulator; -} - -impl Elvish for Lines { - fn elf(self) -> Accumulator { - Accumulator { - lines: self, - current: 0, - } - } -} - -impl Iterator for Accumulator { - type Item = u32; - - fn next(&mut self) -> Option { - while let Some(Ok(line)) = self.lines.next() { - let line = line.trim(); - if line.is_empty() { - let result = self.current; - self.current = 0; - return Some(result); - } else { - self.current += line.parse::().unwrap(); - } - } - None - } -} +use elven_calories::Elvish; fn main() { let matches = Command::new("Day1").arg(Arg::new("filename")).get_matches(); diff --git a/day1/src/step2.rs b/day1/src/step2.rs index 293753b..9e090a6 100644 --- a/day1/src/step2.rs +++ b/day1/src/step2.rs @@ -1,48 +1,14 @@ +mod elven_calories; + use std::fs::File; use std::io::BufRead; use std::io::BufReader; -use std::io::Lines; use clap::Arg; use clap::Command; - use itertools::Itertools; -struct Accumulator { - lines: Lines, - current: u32, -} - -trait Elvish { - fn elf(self) -> Accumulator; -} - -impl Elvish for Lines { - fn elf(self) -> Accumulator { - Accumulator { - lines: self, - current: 0, - } - } -} - -impl Iterator for Accumulator { - type Item = u32; - - fn next(&mut self) -> Option { - while let Some(Ok(line)) = self.lines.next() { - let line = line.trim(); - if line.is_empty() { - let result = self.current; - self.current = 0; - return Some(result); - } else { - self.current += line.parse::().unwrap(); - } - } - None - } -} +use elven_calories::Elvish; fn main() { let matches = Command::new("Day1").arg(Arg::new("filename")).get_matches();