summaryrefslogtreecommitdiffstats
path: root/src/app/filter.rs
blob: b9695268cb47d3ed4861c081a0b8340e03a9dd1b (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
#[derive(Debug, Clone)]
pub struct Filter {
    // TODO: Maybe change to "ignore_matches"?
    pub is_list_ignored: bool,
    pub list: Vec<regex::Regex>,
}

impl Filter {
    /// Whether the filter should keep the entry or reject it.
    #[inline]
    pub(crate) fn keep_entry(&self, value: &str) -> bool {
        self.list
            .iter()
            .find(|regex| regex.is_match(value))
            .map(|_| !self.is_list_ignored)
            .unwrap_or(self.is_list_ignored)
    }
}

#[cfg(test)]
mod test {
    use regex::Regex;

    use super::*;

    /// Test based on the issue in <https://github.com/ClementTsang/bottom/pull/1037>.
    #[test]
    fn filter_is_list_ignored() {
        let results = [
            "CPU socket temperature",
            "wifi_0",
            "motherboard temperature",
            "amd gpu",
        ];

        let ignore_true = Filter {
            is_list_ignored: true,
            list: vec![Regex::new("temperature").unwrap()],
        };

        assert_eq!(
            results
                .into_iter()
                .filter(|r| ignore_true.keep_entry(r))
                .collect::<Vec<_>>(),
            vec!["wifi_0", "amd gpu"]
        );

        let ignore_false = Filter {
            is_list_ignored: false,
            list: vec![Regex::new("temperature").unwrap()],
        };

        assert_eq!(
            results
                .into_iter()
                .filter(|r| ignore_false.keep_entry(r))
                .collect::<Vec<_>>(),
            vec!["CPU socket temperature", "motherboard temperature"]
        );
    }
}