|
| 1 | +use std::borrow::Borrow; |
| 2 | +use std::cell::RefCell; |
| 3 | +use std::cmp::{Eq, PartialEq}; |
| 4 | +use std::fmt::Debug; |
| 5 | +use std::hash::Hash; |
| 6 | +use std::slice::Iter as SliceIter; |
| 7 | + |
| 8 | +use ahash::AHashMap; |
| 9 | + |
| 10 | +#[derive(Debug, Clone, Default)] |
| 11 | +pub struct LazyIndexMap<K, V> { |
| 12 | + vec: Vec<(K, V)>, |
| 13 | + map: RefCell<Option<AHashMap<K, usize>>>, |
| 14 | +} |
| 15 | + |
| 16 | +/// Like [IndexMap](https://docs.rs/indexmap/latest/indexmap/) but only builds the lookup map when it's needed. |
| 17 | +impl<K, V> LazyIndexMap<K, V> |
| 18 | +where |
| 19 | + K: Clone + Debug + Eq + Hash, |
| 20 | + V: Clone + Debug, |
| 21 | +{ |
| 22 | + pub fn new() -> Self { |
| 23 | + Self { |
| 24 | + vec: Vec::new(), |
| 25 | + map: RefCell::new(None), |
| 26 | + } |
| 27 | + } |
| 28 | + |
| 29 | + pub fn insert(&mut self, key: K, value: V) { |
| 30 | + self.vec.push((key, value)) |
| 31 | + } |
| 32 | + |
| 33 | + pub fn len(&self) -> usize { |
| 34 | + self.vec.len() |
| 35 | + } |
| 36 | + |
| 37 | + pub fn get<Q: ?Sized>(&self, key: &Q) -> Option<&V> |
| 38 | + where |
| 39 | + K: Borrow<Q> + PartialEq<Q>, |
| 40 | + Q: Hash + Eq, |
| 41 | + { |
| 42 | + let mut map = self.map.borrow_mut(); |
| 43 | + if let Some(map) = map.as_ref() { |
| 44 | + map.get(key).map(|&i| &self.vec[i].1) |
| 45 | + } else { |
| 46 | + let mut new_map = AHashMap::with_capacity(self.vec.len()); |
| 47 | + let mut value = None; |
| 48 | + // reverse here so the last value is the one that's returned |
| 49 | + for (index, (k, v)) in self.vec.iter().enumerate().rev() { |
| 50 | + if value.is_none() && k == key { |
| 51 | + value = Some(v); |
| 52 | + } |
| 53 | + new_map.insert(k.clone(), index); |
| 54 | + } |
| 55 | + *map = Some(new_map); |
| 56 | + value |
| 57 | + } |
| 58 | + } |
| 59 | + |
| 60 | + pub fn keys(&self) -> impl Iterator<Item = &K> { |
| 61 | + self.vec.iter().map(|(k, _)| k) |
| 62 | + } |
| 63 | + |
| 64 | + pub fn iter(&self) -> SliceIter<'_, (K, V)> { |
| 65 | + self.vec.iter() |
| 66 | + } |
| 67 | +} |
0 commit comments