superior_minigrep/
lib.rs

1use std::{env, error::Error, fs};
2
3/// The main function of the program.
4pub fn run(config: &Config) -> Result<(), Box<dyn Error>> {
5    let contents = fs::read_to_string(&config.file_path)?;
6
7    let results = if config.ignore_case {
8        search_case_insensitive(&config.query, &contents)
9    } else {
10        search(&config.query, &contents)
11    };
12
13    for line in results {
14        println!("{line}");
15    }
16
17    Ok(())
18}
19
20/// Config is a struct that holds the config of the program.
21pub struct Config {
22    /// The query to search for.
23    query: String,
24    /// The path to the file to search.
25    file_path: String,
26    /// Whether to ignore case when searching. If "IGNORE_CASE" is _defined_ in the environment, this will be true.
27    ignore_case: bool,
28}
29
30impl Config {
31    /// Creates a new Config struct.
32    /// # Example
33    /// ```
34    /// use minigrep::Config;
35    /// use std::env;
36    ///
37    /// let config = Config::new(env::args()).unwrap();
38    /// ```
39    pub fn build(mut args: impl Iterator<Item = String>) -> Result<Self, &'static str> {
40        args.next();
41
42        let query = match args.next() {
43            Some(arg) => arg,
44            None => return Err("Didn't get a query string"),
45        };
46
47        let file_path = match args.next() {
48            Some(arg) => arg,
49            None => return Err("Didn't get a file path"),
50        };
51
52        let ignore_case = env::var("IGNORE_CASE").is_ok();
53
54        Ok(Self {
55            query,
56            file_path,
57            ignore_case,
58        })
59    }
60}
61
62/// Searches for the query in the contents.
63fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
64    contents
65        .lines()
66        .filter(|line| line.contains(query))
67        .collect()
68}
69
70/// Searches for the query in the contents, ignoring case.
71fn search_case_insensitive<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
72    let query = query.to_lowercase();
73    contents
74        .lines()
75        .filter(|line| line.to_lowercase().contains(&query))
76        .collect()
77}
78
79#[cfg(test)]
80mod tests {
81    use super::*;
82
83    #[test]
84    fn case_sensitive() {
85        let query = "duct";
86        let contents = "\
87Rust:
88safe, fast, productive.
89Pick three.
90Duct tape.";
91
92        assert_eq!(vec!["safe, fast, productive."], search(query, contents));
93    }
94
95    #[test]
96    fn case_insensitive() {
97        let query = "rUsT";
98        let contents = "\
99Rust:
100safe, fast, productive.
101Pick three.
102Trust me.";
103
104        assert_eq!(
105            vec!["Rust:", "Trust me."],
106            search_case_insensitive(query, contents)
107        );
108    }
109}