minigrep_by_gaaavr/
lib.rs

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