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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
use std::cmp::Ord;
use std::collections::{BTreeMap, BTreeSet};
use std::marker::PhantomData;

use itertools::Itertools;
use serde::{Deserialize, Serialize};

// 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 fn borrow(&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: FnMut(&K, &V) -> bool>(
    map: &mut BTreeMap<K, V>,
    mut 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)
    }

    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

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

/// Use with `FixedMap`. From a particular key, extract a `usize`. These values should be
/// roughly contiguous; the space used by the `FixedMap` will be `O(n)` with respect to the largest
/// value returned here.
pub trait IndexableKey {
    fn index(&self) -> usize;
}

/// A drop-in replacement for `BTreeMap`, where the keys have the property of being array indices.
/// Some values may be missing. Much more efficient at operations on individual objects, because
/// it just becomes a simple array lookup.
#[derive(Serialize, Deserialize, Clone)]
pub struct FixedMap<K: IndexableKey, V> {
    inner: Vec<Option<V>>,
    key_type: PhantomData<K>,
}

impl<K: IndexableKey, V> FixedMap<K, V> {
    pub fn new() -> FixedMap<K, V> {
        FixedMap {
            inner: Vec::new(),
            key_type: PhantomData,
        }
    }

    pub fn insert(&mut self, key: K, value: V) {
        let idx = key.index();
        // Depending on the order of calls, this could wind up pushing one value at a time. It may
        // be more efficient to resize less times and allocate more, but it'll require the caller
        // to know about how many values it'll need.
        if idx >= self.inner.len() {
            self.inner.resize_with(idx + 1, || None);
        }
        self.inner[idx] = Some(value);
    }

    pub fn get(&self, key: &K) -> Option<&V> {
        self.inner.get(key.index())?.as_ref()
    }

    pub fn get_mut(&mut self, key: &K) -> Option<&mut V> {
        self.inner.get_mut(key.index())?.as_mut()
    }

    pub fn contains_key(&self, key: &K) -> bool {
        self.inner
            .get(key.index())
            .map(|x| x.is_some())
            .unwrap_or(false)
    }

    pub fn remove(&mut self, key: &K) -> Option<V> {
        self.inner.get_mut(key.index())?.take()
    }

    pub fn values(&self) -> std::iter::Flatten<std::slice::Iter<'_, std::option::Option<V>>> {
        self.inner.iter().flatten()
    }
}

impl<K: IndexableKey, V> std::ops::Index<&K> for FixedMap<K, V> {
    type Output = V;

    fn index(&self, key: &K) -> &Self::Output {
        self.inner[key.index()].as_ref().unwrap()
    }
}