summaryrefslogtreecommitdiff
path: root/src/main.rs
blob: 4404d8b5ae97ef23a65d59a19551283cd30ba890 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
use std::env;
use std::fs::File;
use std::io;
use std::io::BufRead;
use std::result::Result;


struct Count {
    lines: usize,
    words: usize,
    chars: usize,
}


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 count(&mut self, line: &str) {
        self.count_line();
        self.count_words_in_line(line);
        self.count_chars_in_line(line);
    }

    fn count_line(&mut self) {
        self.lines += 1;
    }

    fn count_words_in_line(&mut self, line: &str) {
        let mut in_word = false;

        for c in line.chars() {
            if c.is_alphabetic() {
                if !in_word {
                    in_word = true;
                    self.words += 1;
                }
            } else {
                in_word = false;
            }
        }
    }

    fn count_chars_in_line(&mut self, line: &str) {
        // add +1 for newline, which we ASSUME is there
        self.chars += line.chars().count() + 1;
    }

}


fn main() -> Result<(), io::Error> {
    let mut total = Count::new();
    for filename in env::args().skip(1) {
        let mut f = File::open(&filename)?;
        let mut reader = io::BufReader::new(f);
        let c = wc(&mut reader)?;
        total.add(&c);
        println!("{:>5} {:>5} {:>5} {}", c.lines, c.words, c.chars, filename);
    }
    if env::args().skip(1).count() > 1 {
        println!("{:>5} {:>5} {:>5} {}", total.lines, total.words, total.chars, "total");
    }
    Ok(())
}


fn wc(reader: &mut io::BufReader<File>) -> Result<Count, io::Error> {
    let mut count = Count::new();
    for line in reader.lines() {
        let line = line?;
        count.count(&line);
    }
    Ok(count)
}