m6_key_set/
key_set.rs

1#![allow(dead_code)]
2
3use std::collections::hash_map::{ HashMap };
4use std::collections::hash_map;
5use std::hash::{ Hash };
6use std::iter:: { Map, IntoIterator };
7use std::fmt;
8use std::vec;
9
10pub type GetKeyType<T, K> = fn(&T) -> K;
11pub type Map2SetType<T, K> = fn((K, T)) -> T;
12
13
14////////////////////////////////////////////////////////////////////////////////
15/// KeySet
16
17pub trait KeySet <T, K> {
18    /**
19    * Create KeySet
20    */
21    fn new(get_key: GetKeyType<T, K>) -> Self;
22
23    fn from_intoiter(get_key: GetKeyType<T, K>, iter: impl IntoIterator<Item=T>) -> Self;
24
25    /**
26    * Operate KeySet elem
27    */
28    fn insert(&mut self, value: T);
29    fn contains(&self, value: &T) -> bool;
30    fn remove(&mut self, value: &T) -> bool;
31    fn take(&mut self, value: &T) -> Option<T>;
32    fn get(&mut self, value: &T) -> Option<&T>;
33    fn len(&self) -> usize;
34    fn iter(&self) -> vec::IntoIter<&T>;
35
36    /**
37    * Check KeySet relationship
38    */
39    fn is_subset(&self, other: &Self) -> bool {
40        self.iter().all(|x| other.contains(&x))
41    }
42
43    fn is_superset(&self, other: &Self) -> bool {
44        other.iter().all(|x| self.contains(&x))
45    }
46
47    fn is_empty(&self) -> bool {
48        self.len() == 0
49    }
50
51    fn is_disjoint(&self, other: &Self) -> bool {
52        other.iter().all(|x| !self.contains(x))
53    }
54
55    /**
56    * Operate with other KeySet
57    */
58    fn intersection<'a>(&'a self, other: &'a Self) -> Self;
59    fn union<'a>(&'a self, other: &'a Self) -> Self;
60    fn difference<'a>(&'a self, other: &'a Self) -> Self;
61    fn symmetric_difference<'a>(&'a self, other: &'a Self) -> Self;
62}
63
64
65////////////////////////////////////////////////////////////////////////////////
66/// Utils
67
68pub fn debug_key<T: fmt::Debug>(value: &T) -> String {
69    format!("{:?}", value)
70}
71
72
73////////////////////////////////////////////////////////////////////////////////
74/// KeyHashSet
75
76pub struct KeyHashSet<T, K: Hash> {
77    get_key: GetKeyType<T, K>,
78    _value_map: HashMap<K, T>,
79}
80
81impl <T, K> KeySet<T, K> for KeyHashSet<T, K> where T: Clone, K: Eq + Hash {
82    fn new(get_key: GetKeyType<T, K>) -> Self {
83        let _value_map:HashMap<K, T> = HashMap::new();
84
85        KeyHashSet {
86            get_key,
87            _value_map,
88        }
89    }
90
91    fn from_intoiter(get_key: GetKeyType<T, K>, iter: impl IntoIterator<Item=T>) -> Self {
92        let mut this = Self::new(get_key);
93        for e in iter {
94            this.insert(e);
95        }
96        this
97    }
98
99    fn insert(&mut self, value:T) {
100        let key = (self.get_key)(&value);
101
102        self._value_map.insert(key, value);
103    }
104
105    fn contains(&self, value: &T) -> bool {
106        let key = &(self.get_key)(value);
107
108        self._value_map.contains_key(key)
109    }
110
111    // Rust doesn't open the constructor method for struct Draw
112    // IndexHashMap drain range
113    // pub fn drain(&mut self) -> Map<HashMap::map::Drain<'_, K, T>, Map2SetType<T, K>> {
114    //     self._value_map.drain().map(|(_, v)| v)
115    // }
116
117    fn remove(&mut self, value:&T) -> bool {
118        let key = &(self.get_key)(value);
119
120        match self._value_map.remove(key) {
121            None => false,
122            _ => true
123        }
124    }
125
126    fn take(&mut self, value:&T) -> Option<T> {
127        let key = &(self.get_key)(value);
128
129        self._value_map.remove(key)
130    }
131
132    fn get(&mut self, value:&T) -> Option<&T> {
133        let key = &(self.get_key)(value);
134
135        self._value_map.get(key)
136    }
137
138    fn len(&self) -> usize {
139        return self._value_map.len();
140    }
141
142    fn iter(&self) -> vec::IntoIter<&T> {
143        let res: Vec<&T> = self._value_map.values ().collect();
144        res.into_iter()
145    }
146
147    fn intersection<'a>(&'a self, other: &'a Self) -> Self {
148        let mut new_set = KeyHashSet::new(self.get_key);
149        for v in self.iter().chain(other.iter()) {
150            new_set.insert(v.clone())
151        }
152
153        new_set
154    }
155
156    fn union<'a>(&'a self, other: &'a Self) -> Self {
157        let mut new_set = KeyHashSet::new(self.get_key);
158
159        for v in self.iter().filter(|v| other.contains(v)) {
160            new_set.insert(v.clone())
161        }
162
163        new_set
164    }
165
166    fn difference<'a>(&'a self, other: &'a Self) -> Self {
167        let mut new_set = KeyHashSet::new(self.get_key);
168
169        for v in self.iter().filter(|v| !other.contains(v)) {
170            new_set.insert(v.clone())
171        }
172
173        new_set
174    }
175
176    fn symmetric_difference<'a>(&'a self, other: &'a Self) -> Self {
177        let mut new_set = KeyHashSet::new(self.get_key);
178
179        for v in self.iter().filter(|v| !other.contains(v)) {
180            new_set.insert(v.clone())
181        }
182
183        for v in other.iter().filter(|v| !self.contains(v)) {
184            new_set.insert(v.clone())
185        }
186
187        new_set
188    }
189}
190
191/// IntoIterator for KeyHashSet
192impl<T, K> IntoIterator for KeyHashSet<T, K> where K: Hash {
193    type Item = T;
194    type IntoIter = Map<hash_map::IntoIter<K, T>, Map2SetType<T, K>>;
195
196    fn into_iter(self) -> Self::IntoIter {
197        self._value_map.into_iter().map(|(_, v)| v)
198    }
199}
200
201/// PartialEq for KeyHashSet
202impl<T, K> PartialEq for KeyHashSet<T, K> where T: Clone, K: Eq + Hash {
203    fn eq(&self, other: &Self) -> bool {
204        self.is_subset(other) && other.is_subset(self)
205    }
206}
207
208/// Debug for KeyHashSet
209impl<T, K> fmt::Debug for KeyHashSet<T, K> where T: Clone + fmt::Debug, K: fmt::Debug + Hash {
210    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
211        f.debug_struct("KeyHashSet")
212         .field("_value_map", &self._value_map)
213         .finish()
214    }
215}
216
217/// Extend for KeyHashSet
218
219impl<T, K> Extend<T> for KeyHashSet<T, K> where T: Clone, K: Hash + Eq {
220    fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
221        for item in iter {
222            self.insert(item);
223        }
224    }
225}
226
227
228////////////////////////////////////////////////////////////////////////////////
229/// IteratorWrapper
230/// Just for hide abstraction
231pub struct IteratorWrapper<I, T> where I: Iterator<Item=T> {
232    iter: I,
233}
234
235impl<I, T> IteratorWrapper<I, T> where I: Iterator<Item=T> {
236    pub fn new(iter: I) -> IteratorWrapper<I, T> where I: Iterator {
237        IteratorWrapper {
238            iter,
239        }
240    }
241}
242
243impl<I, T> Iterator for IteratorWrapper<I, T>  where I: Iterator<Item=T> {
244    type Item = T;
245
246    fn next(&mut self) -> Option<T> {
247        self.iter.next()
248    }
249}