From 4b1753cbc332c116b51b3c52cbe144625077d038 Mon Sep 17 00:00:00 2001 From: Lars Wirzenius Date: Thu, 12 Jul 2018 20:17:27 +0300 Subject: Change: use Count methods for clarity --- src/main.rs | 58 +++++++++++++++++++++++++++++++++++++++++++++++++++------- 1 file changed, 51 insertions(+), 7 deletions(-) diff --git a/src/main.rs b/src/main.rs index bed40d9..32ffb18 100644 --- a/src/main.rs +++ b/src/main.rs @@ -12,6 +12,37 @@ struct Count { } +impl Count { + + fn new() -> Self { + Count { + lines: 0, + words: 0, + chars: 0, + } + } + + fn add(&mut self, c: &Count) { + self.lines += c.lines; + self.words += c.words; + self.chars += c.chars; + } + + fn incr_lines(&mut self) { + self.lines += 1; + } + + fn incr_words(&mut self, n: usize) { + self.words += n; + } + + fn incr_chars(&mut self, n: usize) { + self.chars += n; + } + +} + + fn main() -> Result<(), io::Error> { for filename in env::args().skip(1) { let mut f = File::open(&filename)?; @@ -24,32 +55,45 @@ fn main() -> Result<(), io::Error> { fn wc(reader: &mut io::BufReader) -> Result { - let mut count = Count {lines: 0, words: 0, chars: 0}; + let mut count = Count::new(); for line in reader.lines() { let line = line?; - count_line(&line, &mut count); + count.add(&count_line(&line)); } Ok(count) } -fn count_line(line: &str, count: &mut Count) { +fn count_line(line: &str) -> Count{ + let mut count = Count::new(); + // we have a line! - count.lines += 1; + count.incr_lines(); // add +1 for newline, which we ASSUME is there - count.chars += line.chars().count() + 1; + count.incr_chars(line.chars().count() + 1); // count words - let mut in_word: bool = false; + count.incr_words(count_line_words(line)); + + count +} + + +fn count_line_words(line: &str) -> usize { + let mut in_word = false; + let mut num_words = 0; + for c in line.chars() { if c.is_alphabetic() { if !in_word { in_word = true; - count.words += 1; + num_words += 1; } } else { in_word = false; } } + + num_words } -- cgit v1.2.1