summaryrefslogtreecommitdiff
path: root/rust/theBook/chapter-12-command-line-project/minigrep/src/lib.rs
blob: 60057db2ad692293c6013f90973c6ac59966cfda (plain)
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
use std::{error::Error, fs, env};

pub struct Config {
    pub query: String,
    pub file_path: String,
    pub ignore_case: bool,
    pub case_option: bool,
}

impl Config {
    pub fn build(args: &[String]) -> Result<Config, &'static str> {
        if args.len() < 4 {
            return Err("Not enough arguments");
        }

        let query = args[1].clone();
        let file_path = args[2].clone(); // String
        let ignore_case = env::var("IGNORE_CASE").is_ok();
        let case_option = match args[3].as_str() {
            "true" => true,
            &_ => false
        };
    
        Ok(Config {query, file_path, ignore_case, case_option})
    }
}

// Box<dyn Error> means the function will return a type that implements the Error trait
// But we don’t have to specify what particular type the return value will be
// This gives us flexibility to return error values that may be of different types in different error cases
pub fn run(config: Config) -> Result<(), Box<dyn Error>>{ // dyn dynamic
    let contents = fs::read_to_string(config.file_path)?;

    let result = if config.ignore_case {
        search_case_insensitive(&config.query, &contents)
    }   else if config.case_option {
        search_case_insensitive(&config.query, &contents)
    }   else {
        search(&config.query, &contents)
    };

    for line in result {
        println!("{line}");
    }

    Ok(())
}

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

    #[test]
    fn case_sensitive() {
        let query = "duct";
        let content = "\
Rust:
safe, fast, productive.
Pick three.
Duck tape";

        assert_eq!(vec!["safe, fast, productive."], search(query,content));
    }

    #[test]
    fn case_insensitive() {
        let query = "rUsT";
        let content= "\
Rust:
safe, fast, productive.
Pick three.
Trust me.";

        assert_eq!(vec!["Rust:", "Trust me."], search_case_insensitive(query, content));
    }
}

pub fn search<'a>(query: &str, content: &'a str) -> Vec<&'a str> {
    let mut result = Vec::new();

    for line in content.lines() {
        if line.contains(query) {
            result.push(line);
        }
    }
    result
}

pub fn search_case_insensitive<'a>(query: &str, content: &'a str) -> Vec<&'a str> {
    let mut result = Vec::new();

    let query = query.to_lowercase();

    for line in content.lines() {
        if line.to_lowercase().contains(&query) {
            result.push(line);
        }
    }
    result
}