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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
use itertools::Itertools;
use serde::{Deserialize, Serialize};
use std::cmp::Ord;
use std::collections::{BTreeMap, BTreeSet};

// TODO Ideally derive Serialize and Deserialize, but I can't seem to express the lifetimes
// correctly.
#[derive(PartialEq, Clone)]
pub struct MultiMap<K, V>
where
    K: Ord + PartialEq + Clone,
    V: Ord + PartialEq + Clone,
{
    map: BTreeMap<K, BTreeSet<V>>,
    empty: BTreeSet<V>,
}

impl<K, V> MultiMap<K, V>
where
    K: Ord + PartialEq + Clone,
    V: Ord + PartialEq + Clone,
{
    pub fn new() -> MultiMap<K, V> {
        MultiMap {
            map: BTreeMap::new(),
            empty: BTreeSet::new(),
        }
    }

    pub fn insert(&mut self, key: K, value: V) {
        self.map
            .entry(key)
            .or_insert_with(BTreeSet::new)
            .insert(value);
    }

    pub fn remove(&mut self, key: K, value: V) {
        if !self.map.contains_key(&key) {
            return;
        }
        self.map.get_mut(&key).unwrap().remove(&value);
        if self.map[&key].is_empty() {
            self.map.remove(&key);
        }
    }

    pub fn get(&self, key: K) -> &BTreeSet<V> {
        self.map.get(&key).unwrap_or(&self.empty)
    }

    pub fn len(&self) -> usize {
        self.map.len()
    }

    pub(crate) fn raw_map(&self) -> &BTreeMap<K, BTreeSet<V>> {
        &self.map
    }

    pub fn consume(self) -> BTreeMap<K, BTreeSet<V>> {
        self.map
    }
}

#[derive(Clone)]
pub struct Counter<T: Ord + PartialEq + Clone> {
    map: BTreeMap<T, usize>,
    sum: usize,
}

impl<T: Ord + PartialEq + Clone> Default for Counter<T> {
    fn default() -> Counter<T> {
        Counter::new()
    }
}

impl<T: Ord + PartialEq + Clone> Counter<T> {
    pub fn new() -> Counter<T> {
        Counter {
            map: BTreeMap::new(),
            sum: 0,
        }
    }

    pub fn add(&mut self, val: T, amount: usize) -> usize {
        let entry = self.map.entry(val).or_insert(0);
        *entry += amount;
        self.sum += amount;
        *entry
    }
    pub fn inc(&mut self, val: T) -> usize {
        self.add(val, 1)
    }

    pub fn get(&self, val: T) -> usize {
        self.map.get(&val).cloned().unwrap_or(0)
    }

    // Values with the same count are grouped together
    pub fn sorted_asc(&self) -> Vec<Vec<T>> {
        let mut list = self.map.iter().collect::<Vec<_>>();
        list.sort_by_key(|(_, cnt)| *cnt);
        list.into_iter()
            .group_by(|(_, cnt)| *cnt)
            .into_iter()
            .map(|(_, group)| group.into_iter().map(|(val, _)| val.clone()).collect())
            .collect()
    }

    pub fn max(&self) -> usize {
        self.map.values().max().cloned().unwrap_or(0)
    }
    pub fn sum(&self) -> usize {
        self.sum
    }

    pub fn compare(mut self, mut other: Counter<T>) -> Vec<(T, usize, usize)> {
        for key in self.map.keys() {
            other.map.entry(key.clone()).or_insert(0);
        }
        for key in other.map.keys() {
            self.map.entry(key.clone()).or_insert(0);
        }
        self.map
            .into_iter()
            .map(|(k, cnt)| (k.clone(), cnt, other.map[&k]))
            .collect()
    }

    pub fn borrow(&self) -> &BTreeMap<T, usize> {
        &self.map
    }
    pub fn consume(self) -> BTreeMap<T, usize> {
        self.map
    }
}

pub fn wraparound_get<T>(vec: &Vec<T>, idx: isize) -> &T {
    let len = vec.len() as isize;
    let idx = idx % len;
    let idx = if idx >= 0 { idx } else { idx + len };
    &vec[idx as usize]
}

pub fn retain_btreemap<K: Ord + Clone, V, F: Fn(&K, &V) -> bool>(
    map: &mut BTreeMap<K, V>,
    keep: F,
) {
    let mut remove_keys: Vec<K> = Vec::new();
    for (k, v) in map.iter() {
        if !keep(k, v) {
            remove_keys.push(k.clone());
        }
    }
    for k in remove_keys {
        map.remove(&k);
    }
}

pub fn retain_btreeset<K: Ord + Clone, F: FnMut(&K) -> bool>(set: &mut BTreeSet<K>, mut keep: F) {
    let mut remove: Vec<K> = Vec::new();
    for k in set.iter() {
        if !keep(k) {
            remove.push(k.clone());
        }
    }
    for k in remove {
        set.remove(&k);
    }
}

pub fn contains_duplicates<T: Ord>(vec: &Vec<T>) -> bool {
    let mut set = BTreeSet::new();
    for item in vec {
        if set.contains(item) {
            return true;
        }
        set.insert(item);
    }
    false
}

// Use when your key is just PartialEq, not Ord or Hash.
pub struct VecMap<K, V> {
    inner: Vec<(K, V)>,
}

impl<K: Clone + PartialEq, V> VecMap<K, V> {
    pub fn new() -> VecMap<K, V> {
        VecMap { inner: Vec::new() }
    }

    pub fn consume(self) -> Vec<(K, V)> {
        self.inner
    }

    pub fn mut_or_insert<F: Fn() -> V>(&mut self, key: K, ctor: F) -> &mut V {
        if let Some(idx) = self.inner.iter().position(|(k, _)| key == *k) {
            return &mut self.inner[idx].1;
        }
        self.inner.push((key, ctor()));
        &mut self.inner.last_mut().unwrap().1
    }
}

// Convenience functions around a string->string map
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Tags(BTreeMap<String, String>);

impl Tags {
    pub fn new(map: BTreeMap<String, String>) -> Tags {
        Tags(map)
    }

    pub fn get(&self, k: &str) -> Option<&String> {
        self.0.get(k)
    }

    pub fn contains_key(&self, k: &str) -> bool {
        self.0.contains_key(k)
    }

    pub fn is(&self, k: &str, v: &str) -> bool {
        self.0.get(k) == Some(&v.to_string())
    }

    pub fn is_any(&self, k: &str, values: Vec<&str>) -> bool {
        if let Some(v) = self.0.get(k) {
            values.contains(&v.as_ref())
        } else {
            false
        }
    }

    pub fn insert<K: Into<String>, V: Into<String>>(&mut self, k: K, v: V) {
        self.0.insert(k.into(), v.into());
    }
    pub fn remove(&mut self, k: &str) -> Option<String> {
        self.0.remove(k)
    }

    // TODO Really just iter()
    pub fn inner(&self) -> &BTreeMap<String, String> {
        &self.0
    }
}