Advent of Code 2022
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

39 lines
886 B

//! Extends the BufReader Lines to support summing based on newlines.
use std::io::BufRead;
use std::io::Lines;
pub struct Accumulator<B> {
lines: Lines<B>,
current: u32,
}
pub trait Elvish<B> {
fn elf(self) -> Accumulator<B>;
}
impl<B> Elvish<B> for Lines<B> {
fn elf(self) -> Accumulator<B> {
Accumulator {
lines: self,
current: 0,
}
}
}
impl<B: BufRead> Iterator for Accumulator<B> {
type Item = u32;
fn next(&mut self) -> Option<Self::Item> {
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::<u32>().unwrap();
}
}
None
}
}