quickscope/
map.rs

1use std::{
2  borrow::Borrow,
3  collections::{hash_map::RandomState, HashSet},
4  hash::{Hash, BuildHasher},
5  ops::Index
6};
7
8use indexmap::{IndexMap};
9use smallvec::{smallvec, SmallVec};
10
11type ScopeMapValueStack<V> = SmallVec<[V; 1]>;
12
13#[inline(always)]
14fn invert_index(index: usize, n: usize) -> usize {
15  if index >= n {
16    0
17  } else {
18    n - index - 1
19  }
20}
21
22#[derive(Clone)]
23struct Var<T> {
24  value: T,
25  layer: usize,
26}
27
28/// A layered hash map for representing scoped variables and their values.
29#[derive(Clone)]
30pub struct ScopeMap<K, V, S: BuildHasher = RandomState> {
31  /// Stores a value stack for each variable.
32  ///
33  /// The bottom of a variable's stack corresponds to the lowest layer on which the variable appears.
34  map: IndexMap<K, ScopeMapValueStack<Var<V>>, S>,
35  /// Stores the layers of the stack.
36  ///
37  /// Each layer contains map indices indicating which variables are created or updated in that layer.
38  layers: SmallVec<[HashSet<usize>; 1]>,
39  /// The number of currently empty variable stacks.
40  ///
41  /// Used internally to accurately calculate the number of active variables.
42  empty_key_count: usize,
43}
44
45impl<K, V, S: Default + BuildHasher> Default for ScopeMap<K, V, S> {
46  /// Creates a new `ScopeMap` with the default configuration.
47  #[inline]
48  fn default() -> Self {
49    Self::with_hasher(Default::default())
50  }
51}
52
53impl<K, Q: ?Sized, V, S> Index<&Q> for ScopeMap<K, V, S>
54where 
55  K: Eq + Hash + Borrow<Q>,
56  Q: Eq + Hash,
57  S: BuildHasher,
58{
59  type Output = V;
60
61  /// Returns a reference to the value associated with the provided key.
62  ///
63  /// # Panics
64  ///
65  /// Panics if the key does not exist in the `ScopeMap`.
66  #[inline]
67  fn index(&self, index: &Q) -> &Self::Output {
68    self.get(index).expect("key not found in map")
69  }
70}
71
72impl<K, V> ScopeMap<K, V, RandomState> {
73
74  /// Creates an empty `ScopeMap` with a default hasher and capacity.
75  #[inline]
76  pub fn new() -> ScopeMap<K, V, RandomState> {
77    Self {
78      map: Default::default(),
79      layers: smallvec![Default::default()],
80      empty_key_count: 0,
81    }
82  }
83  
84  /// Creates an empty `ScopeMap` with a default hasher and the specified capacity.
85  #[inline]
86  pub fn with_capacity(capacity: usize) -> ScopeMap<K, V, RandomState> {
87    Self::with_capacity_and_hasher(capacity, Default::default())
88  }
89}
90
91impl<K, V, S: BuildHasher> ScopeMap<K, V, S> {
92  /// Creates an empty `ScopeMap` with the specified hasher and a default capacity.
93  #[inline]
94  pub fn with_hasher(hash_builder: S) -> Self {
95    Self {
96      map: IndexMap::with_hasher(hash_builder),
97      layers: smallvec![Default::default()],
98      empty_key_count: 0,
99    }
100  }
101  
102  /// Creates an empty `ScopeMap` with the specified hasher and capacity.
103  #[inline]
104  pub fn with_capacity_and_hasher(capacity: usize, hash_builder: S) -> Self {
105    Self {
106      map: IndexMap::with_capacity_and_hasher(capacity, hash_builder),
107      layers: smallvec![Default::default()],
108      empty_key_count: 0,
109    }
110  }
111  
112  /// Gets the number of elements the map can hold without reallocating.
113  #[inline]
114  pub fn capacity(&self) -> usize {
115    self.map.capacity()
116  }
117
118  /// Returns `true` if the map is empty.
119  #[inline]
120  pub fn is_empty(&self) -> bool {
121    self.map.is_empty()
122  }
123  
124  /// Gets the number of unique keys in the map.
125  #[inline]
126  pub fn len(&self) -> usize {
127    self.map.len() - self.empty_key_count
128  }
129  
130  /// Gets the number of layers in the map.
131  #[inline]
132  pub fn depth(&self) -> usize {
133    self.layers.len()
134  }
135}
136
137impl<K, V, S> ScopeMap<K, V, S> 
138where 
139  S: BuildHasher,
140{
141  /// Adds a new, empty layer.
142  ///
143  /// Computes in **O(1)** time.
144  #[inline]
145  pub fn push_layer(&mut self) {
146    self.layers.push(Default::default())
147  }
148  
149  /// Removes the topmost layer (if it isn't the bottom layer) and all associated keys/values.
150  /// Returns `true` if a layer was removed.
151  ///
152  /// Computes in **O(n)** time in relation to the number of keys stored in the removed layer.
153  #[inline]
154  pub fn pop_layer(&mut self) -> bool {
155    // Don't allow the base layer to be popped
156    if self.layers.len() > 1 {
157      // Pop the keys found in the removed layer
158      for stack_index in self.layers.pop().unwrap() {
159        if let Some((_key, stack)) = self.map.get_index_mut(stack_index) {
160          let stack_just_emptied = stack.pop().is_some() && stack.is_empty();
161          if stack_just_emptied {
162            self.empty_key_count += 1;
163          }
164        }
165      }
166      return true;
167    }
168    false
169  }
170}
171
172impl<K: Eq + Hash, V, S: BuildHasher> ScopeMap<K, V, S> {
173  
174  /// Returns `true` if the map contains the specified key in any layer.
175  ///
176  /// Computes in **O(1)** time.
177  #[inline]
178  pub fn contains_key<Q: ?Sized>(&self, key: &Q) -> bool
179  where
180    K: Borrow<Q>,
181    Q: Eq + Hash,
182  {
183    if let Some(stack) = self.map.get(key) {
184      !stack.is_empty()
185    } else {
186      false
187    }
188  } 
189
190  /// Returns `true` if the map contains the specified key at the top layer.
191  ///
192  /// Computes in **O(1)** time.
193  #[inline]
194  pub fn contains_key_at_top<Q: ?Sized>(&self, key: &Q) -> bool
195  where
196    K: Borrow<Q>,
197    Q: Eq + Hash,
198  {
199    self.map.get_index_of(key).map_or(false, |i| self.layers.last().unwrap().contains(&i))
200  }
201  
202  /// Gets a reference to the topmost value associated with a key.
203  ///
204  /// Computes in **O(1)** time.
205  #[inline]
206  pub fn get<Q: ?Sized>(&self, key: &Q) -> Option<&V>
207  where
208  K: Borrow<Q>,
209  Q: Eq + Hash,
210  {
211    self.map.get(key).and_then(|v| v.last().map(|v| &v.value))
212  }
213
214  /// Gets an iterator over references to all the values associated with a key, starting with the topmost and going down.
215  ///
216  /// Computes in **O(1)** time.
217  #[inline]
218  pub fn get_all<Q: ?Sized>(&self, key: &Q) -> Option<impl Iterator<Item = &V>>
219  where K: Borrow<Q>,
220  Q: Eq + Hash
221  {
222    self.map.get(key).map(|stack| stack.iter().rev().map(|v| &v.value))
223  }
224  
225  /// Gets a mutable reference to the topmost value associated with a key.
226  ///
227  /// Computes in **O(1)** time.
228  #[inline]
229  pub fn get_mut<Q: ?Sized>(&mut self, key: &Q) -> Option<&mut V>
230  where
231  K: Borrow<Q>,
232  Q: Eq + Hash,
233  {
234    self.map.get_mut(key).and_then(|v| v.last_mut().map(|v| &mut v.value))
235  }
236
237  /// Gets an iterator over mutable references to all the values associated with a key, starting with the topmost and going down.
238  ///
239  /// Computes in **O(1)** time.
240  #[inline]
241  pub fn get_all_mut<Q: ?Sized>(&mut self, key: &Q) -> Option<impl Iterator<Item = &mut V>>
242  where K: Borrow<Q>,
243  Q: Eq + Hash
244  {
245    self.map.get_mut(key).map(|stack| stack.iter_mut().rev().map(|v| &mut v.value))
246  }
247  
248  /// Gets a reference to a value `min_depth` layers below the topmost value associated with a key.
249  /// Saturates to base layer.
250  ///
251  /// Computes in **O(n)** time (worst-case) in relation to `min_depth`.
252  #[inline]
253  pub fn get_parent<Q: ?Sized>(&self, key: &Q, min_depth: usize) -> Option<&V>
254  where
255  K: Borrow<Q>,
256  Q: Eq + Hash,
257  {
258    if let Some((var_index, _key, stack)) = self.map.get_full(key) { 
259      // If the skip count exceeds the stack size, it shouldn't matter because take() is self-truncating
260      let stack_skip_count = self
261      .layers
262      .iter()
263      .rev()
264      .take(min_depth)
265      .filter(|layer| layer.contains(&var_index))
266      .count();
267      return stack.iter().rev().nth(stack_skip_count).map(|v| &v.value)
268    }
269    None
270  }
271
272  /// Gets a reference to the value associated with a key at least `min_depth` layers below the topmost layer, as well as its associated depth.
273  /// Saturates to base layer.
274  ///
275  /// Computes in **O(n)** time (worst-case) in relation to `min_depth`.
276  #[inline]
277  pub fn get_parent_depth<Q: ?Sized>(&self, key: &Q, min_depth: usize) -> Option<(&V, usize)>
278  where
279  K: Borrow<Q>,
280  Q: Eq + Hash,
281  {
282    if let Some((var_index, _key, stack)) = self.map.get_full(key) {
283      // If the skip count exceeds the stack size, it shouldn't matter because take() is self-truncating
284      let stack_skip_count = self
285      .layers
286      .iter()
287      .rev()
288      .take(min_depth)
289      .filter(|layer| layer.contains(&var_index))
290      .count();
291      return stack.iter().rev().nth(stack_skip_count).map(|v| (&v.value, invert_index(v.layer, self.depth())))
292    }
293    None
294  }
295
296  /// Gets a reference to the value associated with a key at least `min_depth` layers below the topmost layer, as well as its associated height.
297  /// Saturates to base layer.
298  ///
299  /// Computes in **O(n)** time (worst-case) in relation to `min_depth`.
300  #[inline]
301  pub fn get_parent_height<Q: ?Sized>(&self, key: &Q, min_depth: usize) -> Option<(&V, usize)>
302  where
303  K: Borrow<Q>,
304  Q: Eq + Hash,
305  {
306    if let Some((var_index, _key, stack)) = self.map.get_full(key) {
307      // If the skip count exceeds the stack size, it shouldn't matter because take() is self-truncating
308      let stack_skip_count = self
309      .layers
310      .iter()
311      .rev()
312      .take(min_depth)
313      .filter(|layer| layer.contains(&var_index))
314      .count();
315      return stack.iter().rev().nth(stack_skip_count).map(|v| (&v.value, v.layer))
316    }
317    None
318  }
319
320  /// Gets an iterator over references to all values `min_depth` layers below the topmost value associated with a key.
321  /// Saturates to base layer.
322  ///
323  /// Computes in **O(n)** time (worst-case) in relation to `min_depth`.
324  #[inline]
325  pub fn get_parents<Q: ?Sized>(&self, key: &Q, min_depth: usize) -> Option<impl Iterator<Item = &V>>
326  where
327  K: Borrow<Q>,
328  Q: Eq + Hash,
329  {
330    if let Some((var_index, _key, stack)) = self.map.get_full(key) {
331      // If the skip count exceeds the stack size, it shouldn't matter because take() is self-truncating
332      let stack_skip_count = self
333      .layers
334      .iter()
335      .rev()
336      .take(min_depth)
337      .filter(|layer| layer.contains(&var_index))
338      .count();
339      return Some(stack.iter().rev().skip(stack_skip_count).map(|v| &v.value))
340    }
341    None
342  }
343  
344  /// Gets a mutable reference to a value `min_depth` layers below the topmost value associated with a key.
345  /// Saturates to base layer.
346  ///
347  /// Computes in **O(n)** time (worst-case) in relation to `min_depth`.
348  #[inline]
349  pub fn get_parent_mut<Q: ?Sized>(&mut self, key: &Q, min_depth: usize) -> Option<&mut V>
350  where
351    K: Borrow<Q>,
352    Q: Eq + Hash,
353  {
354    if let Some((var_index, _key, stack)) = self.map.get_full_mut(key) {
355      // If the skip count exceeds the stack size, it shouldn't matter because take() is self-truncating
356      let stack_skip_count = self
357      .layers
358      .iter()
359      .rev()
360      .take(min_depth)
361      .filter(|layer| layer.contains(&var_index))
362      .count();
363      return stack.iter_mut().rev().nth(stack_skip_count).map(|v| &mut v.value)
364    }
365    None
366  }
367
368  /// Gets an iterator over mutable references to all values `min_depth` layers below the topmost value associated with a key.
369  /// Saturates to base layer.
370  ///
371  /// Computes in **O(n)** time (worst-case) in relation to `min_depth`.
372  #[inline]
373  pub fn get_parents_mut<Q: ?Sized>(&mut self, key: &Q, min_depth: usize) -> Option<impl Iterator<Item = &mut V>>
374  where
375    K: Borrow<Q>,
376    Q: Eq + Hash,
377  {
378    if let Some((var_index, _key, stack)) = self.map.get_full_mut(key) {
379      // If the skip count exceeds the stack size, it shouldn't matter because take() is self-truncating
380      let stack_skip_count = self
381      .layers
382      .iter()
383      .rev()
384      .take(min_depth)
385      .filter(|layer| layer.contains(&var_index))
386      .count();
387      return Some(stack.iter_mut().rev().skip(stack_skip_count).map(|v| &mut v.value))
388    }
389    None
390  }
391
392  /// Gets the depth of the specified key (i.e. how many layers down from the top that the key first appears).
393  /// A depth of 0 refers to the top layer.
394  ///
395  /// Returns `None` if the key does not exist.
396  ///
397  /// Computes in **O(n)** time (worst-case) in relation to layer count.
398  #[inline]
399  pub fn depth_of<Q: ?Sized>(&self, key: &Q) -> Option<usize> 
400  where
401    K: Borrow<Q>,
402    Q: Eq + Hash,
403  {
404    if let Some(index) = self.map.get_index_of(key) {
405      for (depth, layer) in self.layers.iter().rev().enumerate() {
406        if layer.contains(&index) {
407          return Some(depth);
408        }
409      }
410    }
411    None
412  }
413
414  /// Gets the height of the specified key (i.e. how many layers up from the bottom that the key last appears).
415  /// A height of 0 refers to the bottom layer.
416  ///
417  /// Returns `None` if the key does not exist.
418  ///
419  /// Computes in **O(n)** time (worst-case) in relation to layer count.
420  #[inline]
421  pub fn height_of<Q: ?Sized>(&self, key: &Q) -> Option<usize> 
422  where
423    K: Borrow<Q>,
424    Q: Eq + Hash,
425  {
426    if let Some(index) = self.map.get_index_of(key) {
427      for (height, layer) in self.layers.iter().enumerate().rev() {
428        if layer.contains(&index) {
429          return Some(height);
430        }
431      }
432    }
433    None
434  }
435  
436  /// Adds the specified entry to the topmost layer.
437  #[inline]
438  pub fn define(&mut self, key: K, value: V) {
439    let height = self.depth();
440    let entry = self.map.entry(key);
441    let var_index = entry.index();
442    let is_stack_new = matches!(entry, indexmap::map::Entry::Vacant(..));
443    let stack = entry.or_insert_with(Default::default);
444    let is_new_in_layer = self.layers.last_mut().unwrap().insert(var_index);
445    let was_stack_empty = stack.is_empty();
446    
447    if is_new_in_layer {
448      stack.push(Var {
449        value,
450        layer: height - 1,
451      });
452      if was_stack_empty && !is_stack_new {
453        self.empty_key_count -= 1;
454      }
455    } else {
456      stack.last_mut().unwrap().value = value;
457    }
458  }
459
460  /// Adds the specified entry in the layer `min_depth` layers from the top. Saturates to base layer.
461  #[inline]
462  pub fn define_parent(&mut self, key: K, value: V, min_depth: usize) {
463    let height = self.depth();
464    let entry = self.map.entry(key);
465    let stack_index = entry.index();
466    let is_stack_new = matches!(entry, indexmap::map::Entry::Vacant(..));
467    let stack = entry.or_insert_with(Default::default);
468    let is_new_in_layer = self.layers
469      .iter_mut()
470      .nth_back(min_depth.min(height - 1))
471      .unwrap()
472      .insert(stack_index);
473    let was_stack_empty = stack.is_empty();
474
475    let stack_skip_count = self
476    .layers
477    .iter()
478    .rev()
479    .take(min_depth)
480    .filter(|layer| layer.contains(&stack_index))
481    .count();
482
483    let index_in_stack = invert_index(stack_skip_count, stack.len());
484
485    if is_new_in_layer {
486      // If the key is new in this layer, we need to insert the value into the key's stack
487      stack.insert(index_in_stack, Var {
488        value,
489        layer: height.saturating_sub(min_depth + 1),
490      });
491
492      if was_stack_empty && !is_stack_new {
493        self.empty_key_count -= 1;
494      }
495    } else {
496      // If the key is already in the layer, just replace the value
497      stack[index_in_stack].value = value;
498    }
499  }
500
501  /// Removes the entry with the specified key from the topmost layer and returns its value.
502  #[inline]
503  pub fn remove<Q: ?Sized>(&mut self, key: &Q) -> Option<V>
504  where
505    K: Borrow<Q>,
506    Q: Eq + Hash, 
507  {
508    if let Some((index, _key, stack)) = self.map.get_full_mut(key) {
509      if self.layers.last_mut().unwrap().remove(&index) {
510        let taken = stack.pop();
511        let stack_just_emptied = taken.is_some() && stack.is_empty();
512        if stack_just_emptied {
513          self.empty_key_count += 1;
514        }
515        return taken.map(|v| v.value)
516      }
517    }
518    None
519  }
520  
521  /// Removes all entries in the topmost layer.
522  #[inline]
523  pub fn clear_top(&mut self) {
524    for stack_index in self.layers.last_mut().unwrap().drain() {
525      let stack = self.map.get_index_mut(stack_index).unwrap().1;
526      let stack_just_emptied = stack.pop().is_some() && stack.is_empty();
527      if stack_just_emptied {
528        self.empty_key_count += 1;
529      }
530    }
531  }
532  
533  /// Removes all elements and additional layers.
534  #[inline]
535  pub fn clear_all(&mut self) {
536    self.map.clear();
537    self.layers.clear();
538    self.layers.push(Default::default());
539    self.empty_key_count = 0;
540  }
541
542  /// Iterates over all key-value pairs in arbitrary order.
543  ///
544  /// The iterator element type is `(&'a K, &'a V)`.
545  #[inline]
546  pub fn iter(&self) -> impl Iterator<Item = (&'_ K, &'_ V)> {
547    self.map
548      .iter()
549      .filter_map(|(key, stack)| stack.last().map(|var| (key, &var.value)))
550  }
551
552  /// Iterates over all key-value pairs in the topmost layer in arbitrary order.
553  ///
554  /// The iterator element type is `(&'a K, &'a V)`.
555  #[inline]
556  pub fn iter_top(&self) -> impl Iterator<Item = (&'_ K, &'_ V)> {
557    self.layers
558      .last()
559      .unwrap()
560      .iter()
561      .filter_map(move |i| self.map
562        .get_index(*i)
563        .map(|(key, stack)| (key, &stack.last().unwrap().value))
564      )
565  }
566
567  /// Iterates over all key-value pairs in arbitrary order, allowing mutation of the values.
568  ///
569  /// The iterator element type is `(&'a K, &'a mut V)`.
570  #[inline]
571  pub fn iter_mut(&mut self) -> impl Iterator<Item = (&'_ K, &'_ mut V)> {
572    self.map
573      .iter_mut()
574      .filter_map(|(key, stack)| stack.last_mut().map(|var| (key, &mut var.value)))
575  }
576
577  /// Iterates over all keys in arbitrary order.
578  ///
579  /// The iterator element type is `&'a K`.
580  #[inline]
581  pub fn keys(&self) -> impl Iterator<Item = &'_ K> {
582    self.map
583      .iter()
584      .filter(|(_, stack)| !stack.is_empty())
585      .map(|(key, _)| key)
586  }
587
588  /// Iterates over all keys in the topmost layer in arbitrary order.
589  ///
590  /// The iterator element type is `&'a K`.
591  #[inline]
592  pub fn keys_top(&self) -> impl Iterator<Item = &'_ K> {
593    self.layers
594      .last()
595      .unwrap()
596      .iter()
597      .map(move |i| self.map.get_index(*i).unwrap().0)
598  }
599}
600
601#[cfg(test)]
602mod test {
603  use super::*;
604
605  #[test]
606  fn map_init() {
607    let map: ScopeMap<String, i32> = ScopeMap::new();
608    assert_eq!(0, map.len());
609    assert_eq!(1, map.depth());
610    assert!(map.is_empty());
611  }
612
613  #[test]
614  fn map_default() {
615    let map: ScopeMap<String, i32> = Default::default();
616    assert_eq!(0, map.len());
617    assert_eq!(1, map.depth());
618    assert!(map.is_empty());
619  }
620
621  #[test]
622  fn map_capacity() {
623    let map: ScopeMap<String, i32> = ScopeMap::with_capacity(32);
624    assert_eq!(32, map.capacity());
625  }
626
627  #[test]
628  fn map_define() {
629    let mut map = ScopeMap::new();
630    map.define("foo", 123);
631    assert_eq!(1, map.len());
632    assert_eq!(Some(&123), map.get("foo"));
633  }
634
635  #[test]
636  fn map_define_parent() {
637    let mut map = ScopeMap::new();
638    map.push_layer();
639    map.define_parent("foo", 123, 1);
640    assert_eq!(Some(1), map.depth_of("foo"));
641    assert_eq!(Some(&123), map.get_parent("foo", 1));
642    assert_eq!(None, map.get_parent("foo", 2));
643  }
644
645  #[test]
646  fn map_define_parent_after_child() {
647    let mut map = ScopeMap::new();
648    map.push_layer();
649    map.define("foo", 456);
650    map.define_parent("foo", 123, 1);
651    assert_eq!(Some(&456), map.get("foo"));
652    assert_eq!(Some(&123), map.get_parent("foo", 1));
653    map.pop_layer();
654    assert_eq!(Some(&123), map.get("foo"));
655  }
656
657  #[test]
658  fn map_define_parent_saturated() {
659    let mut map = ScopeMap::new();
660    map.push_layer();
661    map.define_parent("foo", 123, 3);
662    assert_eq!(Some(1), map.depth_of("foo"));
663    assert_eq!(Some(&123), map.get("foo"));
664  }
665
666  #[test]
667  fn map_remove() {
668    let mut map = ScopeMap::new();
669    map.define("foo", 123);
670    let removed = map.remove("foo");
671    assert_eq!(0, map.len());
672    assert_eq!(None, map.get("foo"));
673    assert_eq!(Some(123), removed);
674    assert!(!map.contains_key("foo"));
675  }
676
677  #[test]
678  fn map_layer_count() {
679    let mut map: ScopeMap<String, i32> = Default::default();
680    map.push_layer();
681    assert_eq!(2, map.depth());
682    map.pop_layer();
683    assert_eq!(1, map.depth());
684  }
685
686  #[test]
687  fn map_try_pop_first_layer() {
688    let mut map: ScopeMap<String, i32> = Default::default();
689    assert_eq!(false, map.pop_layer());
690    assert_eq!(1, map.depth());
691  }
692
693  #[test]
694  fn map_get_none() {
695    let mut map = ScopeMap::new();
696    map.define("foo", 123);
697    assert_eq!(None, map.get("bar"));
698  }
699
700  #[test]
701  fn map_get_multi_layer() {
702    let mut map = ScopeMap::new();
703    map.define("foo", 123);
704    map.push_layer();
705    map.define("bar", 456);
706    assert_eq!(Some(&123), map.get("foo"));
707    assert_eq!(Some(&456), map.get("bar"));
708  }
709
710  #[test]
711  fn map_get_parent() {
712    let mut map = ScopeMap::new();
713    map.define("foo", 123);
714    map.push_layer();
715    map.define("foo", 456);
716    assert_eq!(Some(&456), map.get_parent("foo", 0));
717    assert_eq!(Some(&123), map.get_parent("foo", 1));
718  }
719
720  #[test]
721  fn map_get_parent_none() {
722    let mut map = ScopeMap::new();
723    map.push_layer();
724    map.define("foo", 123);
725    assert_eq!(None, map.get_parent("foo", 1));
726  }
727
728  #[test]
729  fn map_get_parent_depth() {
730    let mut map = ScopeMap::new();
731    map.define("foo", 123);
732    map.push_layer();
733    map.push_layer();
734    map.define("foo", 456);
735    assert_eq!(Some((&456, 0)), map.get_parent_depth("foo", 0));
736    assert_eq!(Some((&123, 2)), map.get_parent_depth("foo", 1));
737    assert_eq!(Some((&123, 2)), map.get_parent_depth("foo", 2));
738  }
739
740  #[test]
741  fn map_get_parent_height() {
742    let mut map = ScopeMap::new();
743    map.define("foo", 123);
744    map.push_layer();
745    map.push_layer();
746    map.define("foo", 456);
747    assert_eq!(Some((&456, 2)), map.get_parent_height("foo", 0));
748    assert_eq!(Some((&123, 0)), map.get_parent_height("foo", 1));
749    assert_eq!(Some((&123, 0)), map.get_parent_height("foo", 2));
750  }
751
752  #[test]
753  fn map_get_all() {
754    let mut map = ScopeMap::new();
755    map.define("foo", 1);
756    map.push_layer();
757    map.define("foo", 2);
758    map.push_layer();
759    map.define("foo", 3);
760    let values = map.get_all("foo").map(|values| values.cloned().collect::<Vec<i32>>());
761    assert_eq!(Some(vec![3, 2, 1]), values);
762  }
763
764  #[test]
765  fn map_get_parents() {
766    let mut map = ScopeMap::new();
767    map.define("foo", 1);
768    map.push_layer();
769    map.define("foo", 2);
770    map.push_layer();
771    map.define("foo", 3);
772    let values = map.get_parents("foo", 1).map(|values| values.cloned().collect::<Vec<i32>>());
773    assert_eq!(Some(vec![2, 1]), values);
774  }
775
776  #[test]
777  fn map_define_override() {
778    let mut map = ScopeMap::new();
779    map.define("foo", 123);
780    map.push_layer();
781    map.define("foo", 456);
782    assert_eq!(Some(&456), map.get("foo"));
783  }
784
785  #[test]
786  fn map_delete_override() {
787    let mut map = ScopeMap::new();
788    map.define("foo", 123);
789    map.push_layer();
790    map.define("foo", 456);
791    map.remove("foo");
792    assert_eq!(Some(&123), map.get("foo"));
793  }
794
795  #[test]
796  fn map_pop_override() {
797    let mut map = ScopeMap::new();
798    map.define("foo", 123);
799    map.push_layer();
800    map.define("foo", 456);
801    map.pop_layer();
802    assert_eq!(Some(&123), map.get("foo"));
803  }
804
805  #[test]
806  fn map_get_mut() {
807    let mut map = ScopeMap::new();
808    map.define("foo", 123);
809    if let Some(foo) = map.get_mut("foo") {
810      *foo = 456;
811    }
812    assert_eq!(Some(&456), map.get("foo"));
813  }
814
815  #[test]
816  fn map_contains_key() {
817    let mut map = ScopeMap::new();
818    map.define("foo", 123);
819    assert!(map.contains_key("foo"));
820  }
821
822  #[test]
823  fn map_not_contains_key() {
824    let mut map = ScopeMap::new();
825    map.define("foo", 123);
826    assert!(!map.contains_key("bar"));
827  }
828
829  #[test]
830  fn map_depth_of() {
831    let mut map = ScopeMap::new();
832    map.define("foo", 123);
833    map.push_layer();
834    map.define("bar", 456);
835    assert_eq!(Some(1), map.depth_of("foo"));
836    assert_eq!(Some(0), map.depth_of("bar"));
837    assert_eq!(None, map.depth_of("baz"));
838  }
839
840  #[test]
841  fn map_height_of() {
842    let mut map = ScopeMap::new();
843    map.define("foo", 123);
844    map.push_layer();
845    map.define("bar", 456);
846    assert_eq!(Some(0), map.height_of("foo"));
847    assert_eq!(Some(1), map.height_of("bar"));
848    assert_eq!(None, map.height_of("baz"));
849  }
850
851  #[test]
852  fn map_keys() {
853    let mut map = ScopeMap::new();
854    map.define("foo", 123);
855    map.push_layer();
856    map.define("bar", 456);
857    map.push_layer();
858    map.define("baz", 789);
859
860    let expected_keys: HashSet<&str> = ["foo", "bar", "baz"].iter().cloned().collect();
861    let actual_keys: HashSet<&str> = map.keys().cloned().collect();
862    assert_eq!(expected_keys, actual_keys);
863  }
864
865  #[test]
866  fn map_keys_top() {
867    let mut map = ScopeMap::new();
868    map.define("foo", 123);
869    map.push_layer();
870    map.define("bar", 456);
871    map.push_layer();
872    map.define("baz", 789);
873    map.define("qux", 999);
874
875    let expected_keys: HashSet<&str> = ["baz", "qux"].iter().cloned().collect();
876    let actual_keys: HashSet<&str> = map.keys_top().cloned().collect();
877    assert_eq!(expected_keys, actual_keys);
878  }
879
880  #[test]
881  fn map_iter() {
882    let mut map = ScopeMap::new();
883    map.define("foo", 123);
884    map.define("bar", 123);
885    map.define("baz", 123);
886    map.push_layer();
887    map.define("bar", 456);
888    map.push_layer();
889    map.define("baz", 789);
890
891    let expected_keys: HashSet<(&str, i32)> = [("foo", 123), ("bar", 456), ("baz", 789)].iter().cloned().collect();
892    let actual_keys: HashSet<(&str, i32)> = map.iter().map(|(key, val)| (*key, *val)).collect();
893    assert_eq!(expected_keys, actual_keys);
894  }
895
896  #[test]
897  fn map_iter_top() {
898    let mut map = ScopeMap::new();
899    map.define("foo", 123);
900    map.define("bar", 123);
901    map.define("baz", 123);
902    map.push_layer();
903    map.define("bar", 456);
904    map.push_layer();
905    map.define("baz", 789);
906    map.define("qux", 999);
907
908    let expected_keys: HashSet<(&str, i32)> = [("baz", 789), ("qux", 999)].iter().cloned().collect();
909    let actual_keys: HashSet<(&str, i32)> = map.iter_top().map(|(key, val)| (*key, *val)).collect();
910    assert_eq!(expected_keys, actual_keys);
911  }
912
913  #[test]
914  fn map_iter_mut() {
915    let mut map = ScopeMap::new();
916    map.define("foo", 123);
917    map.define("bar", 123);
918    map.define("baz", 123);
919    map.push_layer();
920    map.define("bar", 456);
921    map.push_layer();
922    map.define("baz", 789);
923
924    for (_k, v) in map.iter_mut() {
925      *v = 999;
926    }
927
928    let expected_keys: HashSet<(&str, i32)> = [("foo", 999), ("bar", 999), ("baz", 999)].iter().cloned().collect();
929    let actual_keys: HashSet<(&str, i32)> = map.iter().map(|(key, val)| (*key, *val)).collect();
930    assert_eq!(expected_keys, actual_keys);
931  }
932}