summaryrefslogtreecommitdiff
path: root/src/main.rs
blob: bed40d963e7e607e1c2996811c1f576cd7780829 (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
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,
}


fn main() -> Result<(), io::Error> {
    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)?;
        println!("{:>5} {:>5} {:>5} {}", c.lines, c.words, c.chars, filename);
    }
    Ok(())
}


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


fn count_line(line: &str, count: &mut Count) {
    // we have a line!
    count.lines += 1;

    // add +1 for newline, which we ASSUME is there
    count.chars += line.chars().count() + 1;

    // count words
    let mut in_word: bool = false;
    for c in line.chars() {
        if c.is_alphabetic() {
            if !in_word {
                in_word = true;
                count.words += 1;
            }
        } else {
            in_word = false;
        }
    }
}