Julio Biason
1 year ago
3 changed files with 45 additions and 73 deletions
@ -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<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 |
||||||
|
} |
||||||
|
} |
Loading…
Reference in new issue