unit12/
lib.rs

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
use std::{env, fs};
use std::error::Error;

pub struct Config {
    keyword: String,
    file_path: String,
    case_insensitive: bool,
}

impl Config {
    pub fn new(mut args: env::Args) -> Result<Self, &'static str> {
        args.next();
        let keyword = match args.next() {
            None => return Err("not find 'keyword' arguments"),
            Some(keyword) => keyword
        };
        let file_path = match args.next() {
            None => return Err("not find 'file_path' arguments"),
            Some(file_path) => file_path
        };
        Ok(Config {
            keyword,
            file_path,
            //std::env::var(key:<K>)用来获取操作系统环境变量参数
            case_insensitive: env::var("CASE_INSENSITIVE").is_err(),
        })
    }
}

pub fn run(config: Config) -> Result<(), Box<dyn Error>> {
    let content = fs::read_to_string(&config.file_path)?;
    let result = if config.case_insensitive {
        search_case_insensitive(&config.keyword, &content)
    } else {
        search(&config.keyword, &content)
    };
    for line in result {
        println!("{}", line);
    }
    Ok(())
}

pub fn search<'a>(query: &str, content: &'a str) -> Vec<&'a str> {
    content.lines()
        .filter(|line| line.contains(query))
        .collect()
}

pub fn search_case_insensitive<'a>(query: &str, content: &'a str) -> Vec<&'a str> {
    content.lines()
        .filter(|line| line.to_lowercase().contains(&query.to_lowercase()))
        .collect()
}

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

    #[test]
    fn one_result() {
        let query = "duct";
        let content = "Rust\nsafe, fast, productive.\nPick three.";
        assert_eq!(vec!["safe, fast, productive."], search(query, content));
    }
}