kas_view/filter/
mod.rs

1// Licensed under the Apache License, Version 2.0 (the "License");
2// you may not use this file except in compliance with the License.
3// You may obtain a copy of the License in the LICENSE-APACHE file or at:
4//     https://www.apache.org/licenses/LICENSE-2.0
5
6//! Filters over data
7
8mod filter_list;
9pub use filter_list::*;
10
11/// Ability to set filter
12pub trait FilterValue: Default + 'static {
13    type Value: std::fmt::Debug;
14
15    /// Update the filter
16    fn set_filter(&mut self, value: Self::Value);
17}
18
19/// Types usable as a filter
20pub trait Filter<T: ?Sized>: FilterValue {
21    /// Returns true if the given item matches this filter
22    fn matches(&self, item: &T) -> bool;
23}
24
25/// Filter: target contains self (case-sensitive string match)
26#[derive(Debug, Default, Clone, PartialEq, Eq)]
27pub struct ContainsString(String);
28
29impl ContainsString {
30    /// Construct with empty text
31    pub fn new() -> Self {
32        ContainsString(String::new())
33    }
34}
35
36impl FilterValue for ContainsString {
37    type Value = String;
38    fn set_filter(&mut self, value: String) {
39        self.0 = value;
40    }
41}
42
43impl Filter<str> for ContainsString {
44    fn matches(&self, item: &str) -> bool {
45        item.contains(&self.0)
46    }
47}
48impl Filter<String> for ContainsString {
49    fn matches(&self, item: &String) -> bool {
50        Filter::<str>::matches(self, item.as_str())
51    }
52}
53
54/// Filter: target contains self (case-insensitive string match)
55///
56// Note: the implemented method of caseless matching is not unicode compliant,
57// however works in most cases (by converting both the source and the target to
58// upper case). See [question on StackOverflow].
59//
60// [question on StackOverflow]: https://stackoverflow.com/questions/47298336/case-insensitive-string-matching-in-rust
61#[derive(Debug, Default, Clone, PartialEq, Eq)]
62pub struct ContainsCaseInsensitive(String);
63
64impl ContainsCaseInsensitive {
65    /// Construct with empty text
66    pub fn new() -> Self {
67        ContainsCaseInsensitive(String::new())
68    }
69}
70
71impl FilterValue for ContainsCaseInsensitive {
72    type Value = String;
73    fn set_filter(&mut self, value: String) {
74        self.0 = value.to_uppercase();
75    }
76}
77
78impl Filter<str> for ContainsCaseInsensitive {
79    fn matches(&self, item: &str) -> bool {
80        item.to_string().to_uppercase().contains(&self.0)
81    }
82}
83impl Filter<String> for ContainsCaseInsensitive {
84    fn matches(&self, item: &String) -> bool {
85        Filter::<str>::matches(self, item.as_str())
86    }
87}