minigrep_vietnv/
lib.rs

1use std::{env, error::Error, fs};
2
3pub struct Config {
4    pub query: String,
5    pub file_path: String,
6    pub ignore_case: bool,
7}
8
9impl Config {
10    pub fn build(mut args: impl Iterator<Item = String>) -> Result<Config, &'static str> {
11        args.next();
12
13        let query = match args.next() {
14            Some(arg) => arg,
15            None => return Err("Didn't get a query string"),
16        };
17
18        let file_path = match args.next() {
19            Some(arg) => arg,
20            None => return Err("Didn't get a file path"),
21        };
22
23        let ignore_case = env::var("IGNORE_CASE").is_ok();
24
25        Ok(Config {
26            query,
27            file_path,
28            ignore_case,
29        })
30    }
31}
32
33pub fn run(config: Config) -> Result<(), Box<dyn Error>> {
34    let contents = fs::read_to_string(config.file_path)?;
35
36    let results = if config.ignore_case {
37        search_case_insensitive(&config.query, &contents)
38    } else {
39        search(&config.query, &contents)
40    };
41
42    for line in results {
43        println!("{}", line);
44    }
45
46    Ok(())
47}
48
49pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
50    contents.lines().filter(|x| x.contains(query)).collect()
51}
52
53pub fn search_case_insensitive<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
54    let query = query.to_lowercase();
55    contents.lines().filter(|x| x.contains(&query)).collect()
56}
57
58#[cfg(test)]
59mod test {
60    use std::vec;
61
62    use super::*;
63
64    #[test]
65    fn case_sensitive() {
66        let query = "duct";
67        let contents = "\
68Rust:
69safe, fast, productive.
70Pick three.
71Duct tape.";
72
73        assert_eq!(vec!["safe, fast, productive."], search(query, contents));
74    }
75
76    #[test]
77    fn case_insensitive() {
78        let query = "rUsT";
79        let contents = "\
80Rust:
81safe, fast, productive.
82Pick three.
83Trust me.";
84
85        assert_eq!(
86            vec!["Rust:", "Trust me."],
87            search_case_insensitive(query, contents)
88        );
89    }
90}