boomerang_tinymap 0.3.0

A tiny, fast, and simple Slotkey-type map implementation for Boomerang.
Documentation
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
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
use std::{
    fmt::Debug,
    iter::Enumerate,
    marker::PhantomData,
    ops::{Index, IndexMut},
};

use super::Key;

mod iter_many;

pub use iter_many::IterManyMut;

#[derive(Clone)]
pub struct TinySecondaryMap<K: Key, V> {
    data: Vec<Option<V>>,
    num_values: usize,
    _k: PhantomData<K>,
}

impl<K: Key + Debug, V: Debug> Debug for TinySecondaryMap<K, V> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_map().entries(self.iter()).finish()
    }
}

impl<K: Key, V> Default for TinySecondaryMap<K, V> {
    fn default() -> Self {
        Self {
            data: Vec::new(),
            num_values: 0,
            _k: PhantomData,
        }
    }
}

impl<K: Key, V> Index<K> for TinySecondaryMap<K, V> {
    type Output = V;

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

impl<K: Key, V> IndexMut<K> for TinySecondaryMap<K, V> {
    fn index_mut(&mut self, key: K) -> &mut Self::Output {
        self.data[key.index()].as_mut().unwrap()
    }
}

#[derive(Debug)]
pub struct Iter<'a, K: Key, V: 'a> {
    values_left: usize,
    inner: Enumerate<core::slice::Iter<'a, Option<V>>>,
    _k: PhantomData<K>,
}

#[derive(Debug)]
pub struct IterMut<'a, K: Key, V: 'a> {
    values_left: usize,
    inner: Enumerate<core::slice::IterMut<'a, Option<V>>>,
    _k: PhantomData<K>,
}

#[derive(Debug)]
pub struct IntoIter<K: Key, V> {
    values_left: usize,
    inner: Enumerate<std::vec::IntoIter<Option<V>>>,
    _k: PhantomData<(K, V)>,
}

#[derive(Debug)]
pub struct ValuesIter<'a, V: 'a> {
    num_values: usize,
    inner: std::iter::Flatten<std::slice::Iter<'a, Option<V>>>,
}

impl<K: Key, V> Iterator for IntoIter<K, V> {
    type Item = (K, V);

    fn next(&mut self) -> Option<Self::Item> {
        for (idx, v) in self.inner.by_ref() {
            if let Some(v) = v {
                self.values_left -= 1;
                return Some((K::from(idx), v));
            }
        }
        None
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        (self.values_left, Some(self.values_left))
    }
}

impl<K: Key, V> ExactSizeIterator for IntoIter<K, V> {
    fn len(&self) -> usize {
        self.values_left
    }
}

impl<'a, K: Key, V> Iterator for Iter<'a, K, V> {
    type Item = (K, &'a V);

    fn next(&mut self) -> Option<Self::Item> {
        for (idx, v) in self.inner.by_ref() {
            if let Some(v) = v {
                self.values_left -= 1;
                return Some((K::from(idx), v));
            }
        }
        None
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        (self.values_left, None)
    }
}

impl<'a, K: Key, V> ExactSizeIterator for Iter<'a, K, V> {
    fn len(&self) -> usize {
        self.values_left
    }
}

impl<'a, K: Key, V> Iterator for IterMut<'a, K, V> {
    type Item = (K, &'a mut V);

    fn next(&mut self) -> Option<Self::Item> {
        for (idx, v) in self.inner.by_ref() {
            if let Some(v) = v {
                self.values_left -= 1;
                return Some((K::from(idx), v));
            }
        }
        None
    }
}

impl<'a, K: Key, V> ExactSizeIterator for IterMut<'a, K, V> {
    fn len(&self) -> usize {
        self.values_left
    }
}

impl<'a, V: 'a> Iterator for ValuesIter<'a, V> {
    type Item = &'a V;

    fn next(&mut self) -> Option<Self::Item> {
        self.inner.next()
    }
}

impl<'a, V: 'a> ExactSizeIterator for ValuesIter<'a, V> {
    fn len(&self) -> usize {
        self.num_values
    }
}

impl<K: Key, V> TinySecondaryMap<K, V> {
    /// Construct a new, empty [`TinySecondaryMap`].
    pub fn new() -> Self {
        Self::default()
    }

    /// Creates an emtpy `TinySecondaryMap` with the given capacity.
    pub fn with_capacity(capacity: usize) -> Self {
        Self {
            data: Vec::with_capacity(capacity),
            num_values: 0,
            _k: PhantomData,
        }
    }

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

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

    /// Inserts or replaces a value into the secondary map at the given `key`. Returns [`None`] if
    /// the key was not present, otherwise returns the previous value.
    pub fn insert(&mut self, key: K, value: V) -> Option<V> {
        self.data
            .extend((self.data.len()..=key.index()).map(|_| None));
        if let Some(v) = &mut self.data[key.index()] {
            Some(std::mem::replace(v, value))
        } else {
            self.num_values += 1;
            self.data[key.index()] = Some(value);
            None
        }
    }

    pub fn extend(&mut self, values: impl IntoIterator<Item = (K, V)>) {
        for (key, value) in values {
            self.insert(key, value);
        }
    }

    pub fn contains_key(&self, key: K) -> bool {
        self.data.get(key.index()).map_or(false, Option::is_some)
    }

    /// Returns a reference to the value corresponding to the key.
    pub fn get(&self, key: K) -> Option<&V> {
        self.data.get(key.index())?.as_ref()
    }

    /// Returns a mutable reference to the value corresponding to the key.
    pub fn get_mut(&mut self, key: K) -> Option<&mut V> {
        self.data.get_mut(key.index())?.as_mut()
    }

    /// Returns the first non-empty key in the map.
    pub fn first_key(&self) -> Option<K> {
        self.data.iter().position(Option::is_some).map(K::from)
    }

    /// Returns an iterator over the (`K`, `V`) entries in the map.
    pub fn iter(&self) -> Iter<'_, K, V> {
        Iter {
            inner: self.data.iter().enumerate(),
            values_left: self.num_values,
            _k: PhantomData,
        }
    }

    pub fn iter_mut(&mut self) -> IterMut<'_, K, V> {
        IterMut {
            inner: self.data.iter_mut().enumerate(),
            values_left: self.num_values,
            _k: PhantomData,
        }
    }

    /// Returns an iterator over the keys in the map.
    pub fn keys(&self) -> impl Iterator<Item = K> + '_ {
        self.data
            .iter()
            .enumerate()
            .filter_map(|(idx, v)| v.as_ref().map(|_| K::from(idx)))
    }

    /// Turns the map into a vector of the keys in the map.
    pub fn into_keys(self) -> Vec<K> {
        self.data
            .into_iter()
            .enumerate()
            .filter_map(|(idx, v)| v.map(|_| K::from(idx)))
            .collect()
    }

    /// Returns an iterator over the values in the map, ordered by key.
    pub fn values(&self) -> ValuesIter<V> {
        ValuesIter {
            num_values: self.num_values,
            inner: self.data.iter().flatten(),
        }
    }
}

impl<K: Key, V> Extend<(K, V)> for TinySecondaryMap<K, V> {
    fn extend<T: IntoIterator<Item = (K, V)>>(&mut self, iter: T) {
        for (key, value) in iter {
            self.insert(key, value);
        }
    }
}

impl<K: Key, V> FromIterator<(K, V)> for TinySecondaryMap<K, V> {
    fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> Self {
        let mut map = Self::new();
        map.extend(iter);
        map
    }
}

impl<K: Key, V> IntoIterator for TinySecondaryMap<K, V> {
    type Item = (K, V);
    type IntoIter = IntoIter<K, V>;

    fn into_iter(self) -> Self::IntoIter {
        IntoIter {
            values_left: self.num_values,
            inner: self.data.into_iter().enumerate(),
            _k: PhantomData,
        }
    }
}

#[cfg(test)]
mod tests {
    use crate::DefaultKey;

    use super::*;

    #[test]
    fn test_tiny_secondary_map() {
        let mut map = TinySecondaryMap::<DefaultKey, _>::new();
        map.insert(DefaultKey(3), 4);
        map.insert(DefaultKey(0), 1);
        map.insert(DefaultKey(2), 3);
        map.insert(DefaultKey(1), 2);

        for i in 0..4 {
            assert_eq!(map.get(DefaultKey(i)), Some(&(i + 1)));
        }

        // test insert with existing key
        assert_eq!(map.insert(DefaultKey(0), 10), Some(1));
        assert_eq!(map.get(DefaultKey(0)), Some(&10));

        // test contains_key
        assert!(map.contains_key(DefaultKey(0)));
        assert!(!map.contains_key(DefaultKey(4)));

        // test first_key
        assert_eq!(map.first_key(), Some(DefaultKey(0)));

        // test iter()
        let keys: Vec<_> = map.iter().map(|(k, _)| k).collect();
        assert_eq!(
            keys,
            vec![DefaultKey(0), DefaultKey(1), DefaultKey(2), DefaultKey(3)]
        );

        // test keys()
        let keys: Vec<_> = map.keys().collect();
        assert_eq!(
            keys,
            vec![DefaultKey(0), DefaultKey(1), DefaultKey(2), DefaultKey(3)]
        );

        // test values()
        let values: Vec<_> = map.values().collect();
        assert_eq!(values, vec![&10, &2, &3, &4]);

        // test into_keys()
        let keys: Vec<_> = map.into_keys();
        assert_eq!(
            keys,
            vec![DefaultKey(0), DefaultKey(1), DefaultKey(2), DefaultKey(3)]
        );
    }

    #[test]
    fn test_with_capacity() {
        let mut map = TinySecondaryMap::<DefaultKey, _>::with_capacity(10);
        assert!(map.is_empty());
        map.insert(DefaultKey(3), 4);
        map.insert(DefaultKey(0), 1);
        map.insert(DefaultKey(2), 3);
        map.insert(DefaultKey(1), 2);
        assert_eq!(map.len(), 4);

        // test get_mut
        assert_eq!(map.get_mut(DefaultKey(0)), Some(&mut 1));
        assert_eq!(map.get_mut(DefaultKey(1)), Some(&mut 2));
        assert_eq!(map.get_mut(DefaultKey(2)), Some(&mut 3));
        assert_eq!(map.get_mut(DefaultKey(3)), Some(&mut 4));
    }

    #[test]
    fn test_extend() {
        let mut map = TinySecondaryMap::<DefaultKey, _>::new();
        map.extend(vec![
            (DefaultKey(0), 1),
            (DefaultKey(1), 2),
            (DefaultKey(2), 3),
        ]);
        assert_eq!(map.len(), 3);
        assert_eq!(map.get(DefaultKey(0)), Some(&1));
        assert_eq!(map.get(DefaultKey(1)), Some(&2));
        assert_eq!(map.get(DefaultKey(2)), Some(&3));
    }

    #[test]
    fn test_values_iter() {
        let mut map = TinySecondaryMap::<DefaultKey, _>::with_capacity(10);
        map.insert(DefaultKey(3), 4);
        map.insert(DefaultKey(0), 1);
        map.insert(DefaultKey(2), 3);
        map.insert(DefaultKey(1), 2);

        let mut vals = map.values();
        assert_eq!(vals.len(), 4);
        assert_eq!(vals.next(), Some(&1));
        assert_eq!(vals.next(), Some(&2));
        assert_eq!(vals.next(), Some(&3));
        assert_eq!(vals.next(), Some(&4));
        assert_eq!(vals.next(), None);
    }

    #[test]
    fn test_iter() {
        let mut map = TinySecondaryMap::<DefaultKey, _>::new();
        map.insert(DefaultKey(3), 4);
        map.insert(DefaultKey(0), 1);
        map.insert(DefaultKey(2), 3);
        map.insert(DefaultKey(1), 2);

        let mut iter = map.iter();
        assert_eq!(iter.len(), 4);
        assert_eq!(iter.next(), Some((DefaultKey(0), &1)));
        assert_eq!(iter.next(), Some((DefaultKey(1), &2)));
        assert_eq!(iter.len(), 2);
        assert_eq!(iter.next(), Some((DefaultKey(2), &3)));
        assert_eq!(iter.next(), Some((DefaultKey(3), &4)));
        assert_eq!(iter.next(), None);
        assert_eq!(iter.len(), 0);

        let mut iter_mut = map.iter_mut();
        assert_eq!(iter_mut.len(), 4);
        assert_eq!(iter_mut.next(), Some((DefaultKey(0), &mut 1)));
        assert_eq!(iter_mut.next(), Some((DefaultKey(1), &mut 2)));
        assert_eq!(iter_mut.len(), 2);
        assert_eq!(iter_mut.next(), Some((DefaultKey(2), &mut 3)));
        assert_eq!(iter_mut.next(), Some((DefaultKey(3), &mut 4)));
        assert_eq!(iter_mut.next(), None);
        assert_eq!(iter_mut.len(), 0);
    }
}