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
//! libです
#![warn(missing_docs)]
use regex::Regex;
use std::collections::HashMap;
use std::io::BufRead;
/**
count関数です
 */
pub fn count(input: impl BufRead, option: CountOption) -> HashMap<String, usize> {
    let re = Regex::new(r"\w+").unwrap();
    let mut fregs = HashMap::new();
    for line in input.lines() {
        use crate::CountOption::*;
        let line = line.unwrap();
        match option {
            Char => {
                for c in line.chars() {
                    *fregs.entry(c.to_string()).or_insert(0) += 1;
                }
            },
            Word => {
                for m in re.find_iter(&line) {
                    let word = m.as_str().to_string();
                    *fregs.entry(word).or_insert(0) += 1;
                }
            },
            Line => {
                *fregs.entry(line.to_string()).or_insert(0) += 1;
            }
        }
    }
    fregs
}
/// 列挙子です。
#[derive(Debug,Clone,Copy,PartialEq,Eq,Hash)]
pub enum CountOption {
    /// 文字
    Char,
    /// 単語
    Word,
    /// 行
    Line,
}
impl Default for CountOption {
    fn default() -> Self {
        CountOption::Word
    }
}

#[test]
fn word_count_works() {
    use std::io::Cursor;
    let mut exp = HashMap::new();
    exp.insert("aa".to_string(),1);
    exp.insert("bb".to_string(),2);
    assert_eq!(count(Cursor::new("aa bb bb"),CountOption::Word),exp);
}