search/
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
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
use regex::Regex;

///#### Example to using this fn
/**```rust
 * use search::search;
 * 
 * fn main() {
 *     let query = "Rust";
 *     let contents = "Rust is good language";
 *     let results = search_case_instnsitive(query, contents, false, false);
 *     assert_eq!(results, vec!["Rust"]) // -> True
 * }
 * ```
*/

pub fn search<'a>(query: &str, contents: &'a str, number: bool, invert_match: bool) -> Vec<String> {
    let re = Regex::new(query).unwrap();
    let mut results = Vec::new();

    for (i, line) in contents.lines().enumerate() {
        if re.is_match(line) != invert_match {
            if number {
                results.push(format!("{}: {}", i + 1, line));
            } else {
                results.push(line.to_string());
            }
        }
    }

    results
}

///#### Example to using this fn
/**```rust
 * use search::search_case_insensitive;
 * 
 * fn main() {
 *     let query = "RUst";
 *     let contents = "Rust is good language";
 *     let results = search_case_insensitive(query, contents, false, false);
 *     assert_eq!(results, vec!["Rust"]) // -> True
 * }
 * ```
*/

pub fn search_case_insensitive<'a>(query: &str, contents: &'a str, number: bool, invert_match: bool) -> Vec<String> {
    let re = Regex::new(&format!("(?i){}", regex::escape(query))).unwrap();
    let mut results = Vec::new();

    for (i, line) in contents.lines().enumerate() {
        if re.is_match(line) != invert_match {
            if number {
                results.push(format!("{}: {}", i + 1, line));
            } else {
                results.push(line.to_string());
            }
        }
    }

    results
}

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

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

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

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

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