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::error;
use std::fs;

pub struct Config {
    pub fname: String,
}

impl Config {
    pub fn new(args: &Vec<String>) -> Result<Config, &'static str> {
        if args.len() < 2 {
            Result::Err("Please specify the file name")
        } else {
            Result::Ok(Config {
                fname: args[1].clone(),
            })
        }
    }
}

pub fn run(config: &Config) -> Result<usize, Box<dyn error::Error>> {
    let contents = fs::read_to_string(&config.fname)?;
    let count = word_count(&contents);
    Ok(count)
}

fn word_count<'a>(contents: &'a str) -> usize {
    let mut count = 0;

    for l in contents.lines().map(|l| l.trim()).filter(|l| !l.is_empty()) {
        let words: Vec<&str> = l.split(" ").collect();
        count += words.len();
    }

    count
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_word_count() {
        assert_eq!(word_count("hiii hhh\nsdfs\nsdfsf"), 4);
    }

    #[test]
    fn test_word_count_empty_lines() {
        assert_eq!(word_count("  \n     \n  "), 0);
    }

    #[test]
    fn test_word_count_empty_lines_1() {
        assert_eq!(word_count("  s s\n     \n  "), 2);
    }
}