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
use std::collections::HashMap;
use std::sync::{Arc, Mutex};

use anyhow::Result;

/// A shared map that can be cloned and used in multiple threads
#[derive(Clone)]
pub struct BasicSharedMap<K, V> {
    inner: Arc<Mutex<SharedMapInner<K, V>>>,
}

/// The inner struct that holds the map
struct SharedMapInner<K, V> {
    /// The map
    map: HashMap<K, V>,
}

impl<K, V> Default for BasicSharedMap<K, V>
where
    K: Eq + std::hash::Hash,
{
    fn default() -> Self {
        Self::new()
    }
}

impl<K, V> BasicSharedMap<K, V>
where
    K: Eq + std::hash::Hash,
{
    /// Create a new shared map
    ///
    /// # Examples
    ///
    /// ```
    /// use lib_wc::sync::ds::BasicSharedMap;
    ///
    /// let m: BasicSharedMap<u32, String> = BasicSharedMap::new();
    /// ```
    pub fn new() -> Self {
        Self {
            inner: Arc::new(Mutex::new(SharedMapInner {
                map: HashMap::new(),
            })),
        }
    }

    /// Insert a key-value pair into the map
    ///
    /// # Examples
    ///
    /// ```
    /// use lib_wc::sync::ds::BasicSharedMap;
    ///
    /// let m: BasicSharedMap<u32, String> = BasicSharedMap::new();
    ///
    /// m.insert(1, "foo".to_string());
    /// ```
    pub fn insert(&self, key: K, value: V) {
        let mut inner = self.inner.lock().unwrap();
        inner.map.insert(key, value);
    }

    /// Get a value from the map
    ///
    /// # Examples
    ///
    /// ```
    /// use lib_wc::sync::ds::BasicSharedMap;    
    ///
    /// let m: BasicSharedMap<u32, String> = BasicSharedMap::new();
    ///
    /// m.insert(1, "foo".to_string());    
    ///
    /// assert_eq!(m.get(&1), Some("foo".to_string()));
    /// ```
    pub fn get(&self, key: &K) -> Option<V>
    where
        V: Clone,
    {
        let inner = self.inner.lock().unwrap();
        inner.map.get(key).cloned()
    }

    /// Atomically execute a function with a locked, mutable reference to the map
    ///
    /// # Examples
    ///
    /// ```
    ///   use lib_wc::sync::ds::BasicSharedMap;
    ///
    ///   let m: BasicSharedMap<u32, String> = BasicSharedMap::new();
    ///
    ///   m.with_map(|map| {
    ///     map.insert(1, "foo".to_string());
    ///     map.insert(2, "bar".to_string());
    ///   });
    ///
    ///   assert_eq!(m.get(&1), Some("foo".to_string()));
    ///   assert_eq!(m.get(&2), Some("bar".to_string()));
    ///
    /// ```
    pub fn with_map<F, R>(&self, func: F) -> Result<R>
    where
        F: FnOnce(&mut HashMap<K, V>) -> R,
    {
        match self.inner.lock() {
            Ok(mut inner) => Ok(func(&mut inner.map)),
            Err(_) => Err(anyhow::anyhow!("Failed to lock mutex")),
        }
    }
}

#[cfg(test)]
mod tests {
    use std::thread;

    use tokio::spawn;
    use tokio::time::sleep;

    use super::*;

    #[test]
    fn test_shared_map() {
        let map = BasicSharedMap::new();
        map.insert("foo", 42);
        assert_eq!(map.get(&"foo"), Some(42));
    }

    #[test]
    fn test_shared_map_clone() {
        let map = BasicSharedMap::new();
        map.insert("foo", 42);
        let map2 = map.clone();
        assert_eq!(map2.get(&"foo"), Some(42));
    }

    #[test]
    fn test_shared_map_clone2() {
        let map = BasicSharedMap::new();
        map.insert("foo", 42);
        let map2 = map.clone();
        map2.insert("bar", 43);
        assert_eq!(map.get(&"bar"), Some(43));
    }

    #[test]
    fn test_shared_map_clone3() {
        let map = BasicSharedMap::new();
        map.insert("foo", 42);
        let map2 = map.clone();
        map2.insert("bar", 43);
        assert_eq!(map.get(&"foo"), Some(42));
    }

    #[test]
    fn test_shared_map_clone4() {
        let map = BasicSharedMap::new();
        map.insert("foo", 42);
        let map2 = map.clone();
        map2.insert("bar", 43);
        let map3 = map2.clone();
        assert_eq!(map3.get(&"foo"), Some(42));
    }

    #[test]
    fn test_with_map() {
        let map = BasicSharedMap::new();
        map.insert("foo", 42);
        let r = map.with_map(|map| {
            assert_eq!(map.get(&"foo"), Some(&42));
        });
        assert!(r.is_ok());
    }

    #[test]
    fn test_with_map2() {
        let map = BasicSharedMap::new();
        map.insert("foo", 42);
        let r = map.with_map(|map| {
            map.insert("bar", 43);
        });
        assert!(r.is_ok());
        assert_eq!(map.get(&"bar"), Some(43));
    }

    #[test]
    fn test_with_map_multiple_threads() {
        let map = BasicSharedMap::new();

        thread::scope(|s| {
            for _ in 0..2 {
                let map = map.clone();
                s.spawn(move || {
                    map.with_map(|map| {
                        let value = map.entry("foo").or_insert(0);
                        if *value == 0 {
                            *value += 1;
                        }
                    })
                    .unwrap();
                });
            }
        });

        assert_eq!(map.get(&"foo"), Some(1))
    }

    #[test]
    fn test_with_map_race() {
        let map = BasicSharedMap::new();

        thread::spawn({
            let map = map.clone();
            move || {
                let _ = map.with_map(|map| {
                    map.insert("a", 1);
                    map.insert("b", 2);
                });
            }
        });

        // Race to see if the writes are visible; both or neither should be visible
        let _ = map.with_map(|map| {
            assert!(
                (map.contains_key("a") && map.contains_key("b"))
                    || (!map.contains_key("a") && !map.contains_key("b"))
            );
        });
    }

    #[tokio::test]
    async fn test_shared_map_with_map_asynchronous_execution() {
        let map = BasicSharedMap::new();

        let count = 100;

        let futures = (0..count).map(|_| {
            let map = map.clone();
            spawn(async move {
                let _ = map.with_map(|map| {
                    let value = map.entry("foo").or_insert(0);
                    *value += 1;
                });
                sleep(tokio::time::Duration::from_nanos(1)).await;
            })
        });

        for future in futures {
            let _ = future.await;
        }

        assert_eq!(map.get(&"foo"), Some(count))
    }
}