|
| 1 | +#[derive(Clone)] |
| 2 | +pub struct VecMap<K, V> { |
| 3 | + vec: Vec<(K, V)>, |
| 4 | +} |
| 5 | + |
| 6 | +impl<K: PartialEq, V> VecMap<K, V> { |
| 7 | + pub fn new() -> VecMap<K, V> { |
| 8 | + VecMap { |
| 9 | + vec: Vec::new() |
| 10 | + } |
| 11 | + } |
| 12 | + |
| 13 | + pub fn insert(&mut self, key: K, value: V) { |
| 14 | + match self.find(&key) { |
| 15 | + Some(pos) => self.vec[pos] = (key, value), |
| 16 | + None => self.vec.push((key, value)) |
| 17 | + } |
| 18 | + } |
| 19 | + |
| 20 | + pub fn entry(&mut self, key: K) -> Entry<K, V> { |
| 21 | + match self.find(&key) { |
| 22 | + Some(pos) => Entry::Occupied(OccupiedEntry { |
| 23 | + vec: self, |
| 24 | + pos: pos, |
| 25 | + }), |
| 26 | + None => Entry::Vacant(VacantEntry { |
| 27 | + vec: self, |
| 28 | + key: key, |
| 29 | + }) |
| 30 | + } |
| 31 | + } |
| 32 | + |
| 33 | + pub fn get(&self, key: &K) -> Option<&V> { |
| 34 | + self.find(key).map(move |pos| &self.vec[pos].1) |
| 35 | + } |
| 36 | + |
| 37 | + pub fn get_mut(&mut self, key: &K) -> Option<&mut V> { |
| 38 | + self.find(key).map(move |pos| &mut self.vec[pos].1) |
| 39 | + } |
| 40 | + |
| 41 | + pub fn contains_key(&self, key: &K) -> bool { |
| 42 | + self.find(key).is_some() |
| 43 | + } |
| 44 | + |
| 45 | + pub fn len(&self) -> usize { self.vec.len() } |
| 46 | + pub fn iter(&self) -> ::std::slice::Iter<(K, V)> { |
| 47 | + self.vec.iter() |
| 48 | + } |
| 49 | + pub fn remove(&mut self, key: &K) -> Option<V> { |
| 50 | + self.find(key).map(|pos| self.vec.remove(pos)).map(|(_, v)| v) |
| 51 | + } |
| 52 | + pub fn clear(&mut self) { |
| 53 | + self.vec.clear(); |
| 54 | + } |
| 55 | + |
| 56 | + fn find(&self, key: &K) -> Option<usize> { |
| 57 | + self.vec.iter().position(|entry| key == &entry.0) |
| 58 | + } |
| 59 | +} |
| 60 | + |
| 61 | +pub enum Entry<'a, K: 'a, V: 'a> { |
| 62 | + Vacant(VacantEntry<'a, K, V>), |
| 63 | + Occupied(OccupiedEntry<'a, K, V>) |
| 64 | +} |
| 65 | + |
| 66 | +pub struct VacantEntry<'a, K: 'a, V: 'a> { |
| 67 | + vec: &'a mut VecMap<K, V>, |
| 68 | + key: K, |
| 69 | +} |
| 70 | + |
| 71 | +impl<'a, K, V> VacantEntry<'a, K, V> { |
| 72 | + pub fn insert(self, val: V) -> &'a mut V { |
| 73 | + let mut vec = self.vec; |
| 74 | + vec.vec.push((self.key, val)); |
| 75 | + let pos = vec.vec.len() - 1; |
| 76 | + &mut vec.vec[pos].1 |
| 77 | + } |
| 78 | +} |
| 79 | + |
| 80 | +pub struct OccupiedEntry<'a, K: 'a, V: 'a> { |
| 81 | + vec: &'a mut VecMap<K, V>, |
| 82 | + pos: usize, |
| 83 | +} |
| 84 | + |
| 85 | +impl<'a, K, V> OccupiedEntry<'a, K, V> { |
| 86 | + pub fn into_mut(self) -> &'a mut V { |
| 87 | + &mut self.vec.vec[self.pos].1 |
| 88 | + } |
| 89 | +} |
0 commit comments