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
101
102
103
104
use std::collections::{HashMap, HashSet};
use std::sync::atomic::{AtomicU32, Ordering};
pub use sync15_traits::ServerTimestamp;
pub(crate) fn atomic_update_max(v: &AtomicU32, new: u32) {
let mut cur = v.load(Ordering::SeqCst);
while cur < new {
match v.compare_exchange_weak(cur, new, Ordering::SeqCst, Ordering::SeqCst) {
Ok(_) => {
break;
}
Err(new_cur) => {
cur = new_cur
}
}
}
}
pub(crate) fn set_union(a: &HashSet<String>, b: &HashSet<String>) -> HashSet<String> {
a.union(b).cloned().collect()
}
pub(crate) fn set_difference(a: &HashSet<String>, b: &HashSet<String>) -> HashSet<String> {
a.difference(b).cloned().collect()
}
pub(crate) fn set_intersection(a: &HashSet<String>, b: &HashSet<String>) -> HashSet<String> {
a.intersection(b).cloned().collect()
}
pub(crate) fn partition_by_value(v: &HashMap<String, bool>) -> (HashSet<String>, HashSet<String>) {
let mut true_: HashSet<String> = HashSet::new();
let mut false_: HashSet<String> = HashSet::new();
for (s, val) in v {
if *val {
true_.insert(s.clone());
} else {
false_.insert(s.clone());
}
}
(true_, false_)
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_set_ops() {
fn hash_set(s: &[&str]) -> HashSet<String> {
s.iter()
.copied()
.map(ToOwned::to_owned)
.collect::<HashSet<_>>()
}
assert_eq!(
set_union(&hash_set(&["a", "b", "c"]), &hash_set(&["b", "d"])),
hash_set(&["a", "b", "c", "d"]),
);
assert_eq!(
set_difference(&hash_set(&["a", "b", "c"]), &hash_set(&["b", "d"])),
hash_set(&["a", "c"]),
);
assert_eq!(
set_intersection(&hash_set(&["a", "b", "c"]), &hash_set(&["b", "d"])),
hash_set(&["b"]),
);
let m: HashMap<String, bool> = [
("foo", true),
("bar", true),
("baz", false),
("quux", false),
]
.iter()
.copied()
.map(|(a, b)| (a.to_owned(), b))
.collect();
assert_eq!(
partition_by_value(&m),
(hash_set(&["foo", "bar"]), hash_set(&["baz", "quux"])),
);
}
}