dashmap/rayon/
read_only.rs

1use crate::mapref::multiple::RefMulti;
2use crate::rayon::map::Iter;
3use crate::ReadOnlyView;
4use core::hash::{BuildHasher, Hash};
5use rayon::iter::IntoParallelIterator;
6
7impl<K, V, S> IntoParallelIterator for ReadOnlyView<K, V, S>
8where
9    K: Send + Eq + Hash,
10    V: Send,
11    S: Send + Clone + BuildHasher,
12{
13    type Iter = super::map::OwningIter<K, V>;
14    type Item = (K, V);
15
16    fn into_par_iter(self) -> Self::Iter {
17        super::map::OwningIter {
18            shards: self.map.shards,
19        }
20    }
21}
22
23// This impl also enables `IntoParallelRefIterator::par_iter`
24impl<'a, K, V, S> IntoParallelIterator for &'a ReadOnlyView<K, V, S>
25where
26    K: Send + Sync + Eq + Hash,
27    V: Send + Sync,
28    S: Send + Sync + Clone + BuildHasher,
29{
30    type Iter = Iter<'a, K, V>;
31    type Item = RefMulti<'a, K, V>;
32
33    fn into_par_iter(self) -> Self::Iter {
34        Iter {
35            shards: &self.map.shards,
36        }
37    }
38}
39
40#[cfg(test)]
41mod tests {
42    use crate::DashMap;
43    use rayon::iter::{IntoParallelIterator, IntoParallelRefIterator, ParallelIterator};
44
45    fn construct_sample_map() -> DashMap<i32, String> {
46        let map = DashMap::new();
47
48        map.insert(1, "one".to_string());
49
50        map.insert(10, "ten".to_string());
51
52        map.insert(27, "twenty seven".to_string());
53
54        map.insert(45, "forty five".to_string());
55
56        map
57    }
58
59    #[test]
60    fn test_par_iter() {
61        let map = construct_sample_map();
62
63        let view = map.clone().into_read_only();
64
65        view.par_iter().for_each(|entry| {
66            let key = *entry.key();
67
68            assert!(view.contains_key(&key));
69
70            let map_entry = map.get(&key).unwrap();
71
72            assert_eq!(view.get(&key).unwrap(), map_entry.value());
73
74            let key_value: (&i32, &String) = view.get_key_value(&key).unwrap();
75
76            assert_eq!(key_value.0, map_entry.key());
77
78            assert_eq!(key_value.1, map_entry.value());
79        });
80    }
81
82    #[test]
83    fn test_into_par_iter() {
84        let map = construct_sample_map();
85
86        let view = map.clone().into_read_only();
87
88        view.into_par_iter().for_each(|(key, value)| {
89            let map_entry = map.get(&key).unwrap();
90
91            assert_eq!(&key, map_entry.key());
92
93            assert_eq!(&value, map_entry.value());
94        });
95    }
96}