1use std::borrow::Borrow;
7use std::fmt::Debug;
8use std::fmt::Formatter;
9use std::hash::BuildHasher;
10use std::hash::Hash;
11use std::sync::Arc;
12
13use arc_swap::ArcSwap;
14use arc_swap::Guard;
15use vortex_utils::aliases::hash_map::DefaultHashBuilder;
16use vortex_utils::aliases::hash_map::HashMap;
17
18pub struct ArcSwapMap<K, V, S = DefaultHashBuilder> {
37 inner: Arc<ArcSwap<HashMap<K, V, S>>>,
38}
39
40impl<K, V, S: Default> Default for ArcSwapMap<K, V, S> {
41 fn default() -> Self {
42 Self {
43 inner: Arc::new(ArcSwap::from_pointee(HashMap::default())),
44 }
45 }
46}
47
48impl<K, V, S> Clone for ArcSwapMap<K, V, S> {
49 fn clone(&self) -> Self {
50 Self {
51 inner: Arc::clone(&self.inner),
52 }
53 }
54}
55
56impl<K: Debug, V: Debug, S> Debug for ArcSwapMap<K, V, S> {
57 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
58 self.read(|map| f.debug_tuple("ArcSwapMap").field(map).finish())
59 }
60}
61
62impl<K, V, S> ArcSwapMap<K, V, S> {
63 pub fn snapshot(&self) -> Arc<HashMap<K, V, S>> {
65 self.inner.load_full()
66 }
67
68 pub fn read<R>(&self, f: impl FnOnce(&HashMap<K, V, S>) -> R) -> R {
73 f(&self.inner.load())
74 }
75
76 pub(crate) fn load(&self) -> Guard<Arc<HashMap<K, V, S>>> {
83 self.inner.load()
84 }
85
86 fn modify(&self, f: impl Fn(&mut HashMap<K, V, S>))
91 where
92 K: Clone,
93 V: Clone,
94 S: Clone,
95 {
96 self.inner.rcu(|existing| {
97 let mut map = existing.as_ref().clone();
98 f(&mut map);
99 map
100 });
101 }
102}
103
104impl<K: Eq + Hash, V, S: BuildHasher> ArcSwapMap<K, V, S> {
105 pub fn get<Q>(&self, key: &Q) -> Option<V>
107 where
108 K: Borrow<Q>,
109 Q: Eq + Hash + ?Sized,
110 V: Clone,
111 {
112 self.inner.load().get(key).cloned()
113 }
114
115 pub fn contains_key<Q>(&self, key: &Q) -> bool
117 where
118 K: Borrow<Q>,
119 Q: Eq + Hash + ?Sized,
120 {
121 self.inner.load().contains_key(key)
122 }
123
124 pub fn insert(&self, key: K, value: V)
125 where
126 K: Clone,
127 V: Clone,
128 S: Clone,
129 {
130 self.modify(|map| {
131 map.insert(key.clone(), value.clone());
132 });
133 }
134
135 pub fn insert_if_absent(&self, key: K, value: V) -> bool
142 where
143 K: Clone,
144 V: Clone,
145 S: Clone,
146 {
147 let previous = self.inner.rcu(|existing| {
148 if existing.contains_key(&key) {
149 return Arc::clone(existing);
150 }
151 let mut map = existing.as_ref().clone();
152 map.insert(key.clone(), value.clone());
153 Arc::new(map)
154 });
155 !previous.contains_key(&key)
156 }
157}
158
159impl<K: Eq + Hash + Clone, T: Clone, S: BuildHasher + Clone> ArcSwapMap<K, Arc<[T]>, S> {
160 pub fn extend(&self, key: K, values: &[T]) {
165 self.modify(|map| {
166 let merged: Arc<[T]> = match map.get(&key) {
167 Some(existing) => existing.iter().chain(values).cloned().collect(),
168 None => values.into(),
169 };
170 map.insert(key.clone(), merged);
171 });
172 }
173
174 pub fn push(&self, key: K, value: T) {
177 self.extend(key, &[value]);
178 }
179}
180
181#[cfg(test)]
182mod tests {
183 use super::*;
184
185 #[test]
186 fn get_and_insert() {
187 let map = ArcSwapMap::<u32, i32>::default();
188 assert_eq!(map.get(&1), None);
189 assert!(!map.contains_key(&1));
190 map.insert(1, 10);
191 map.insert(1, 20);
192 assert_eq!(map.get(&1), Some(20));
193 assert!(map.contains_key(&1));
194 }
195
196 #[test]
197 fn insert_if_absent_keeps_first_value() {
198 let map = ArcSwapMap::<u32, i32>::default();
199 assert!(map.insert_if_absent(1, 10));
200 assert!(!map.insert_if_absent(1, 20));
201 assert_eq!(map.get(&1), Some(10));
202 }
203
204 #[test]
205 fn extend_appends_per_key() {
206 let map = ArcSwapMap::<u32, Arc<[i32]>>::default();
207 map.extend(1, &[1, 2]);
208 map.extend(1, &[3]);
209 map.extend(2, &[4]);
210 assert_eq!(map.get(&1).as_deref(), Some([1, 2, 3].as_slice()));
211 assert_eq!(map.get(&2).as_deref(), Some([4].as_slice()));
212 }
213
214 #[test]
215 fn push_appends_single_values() {
216 let map = ArcSwapMap::<u32, Arc<[i32]>>::default();
217 map.push(1, 1);
218 map.push(1, 2);
219 assert_eq!(map.get(&1).as_deref(), Some([1, 2].as_slice()));
220 }
221
222 #[test]
223 fn read_observes_a_single_snapshot() {
224 let map = ArcSwapMap::<u32, i32>::default();
225 map.insert(1, 1);
226 map.insert(2, 2);
227 let sum = map.read(|snapshot| {
228 map.insert(1, 10);
229 map.insert(2, 20);
230 snapshot.values().sum::<i32>()
231 });
232 assert_eq!(sum, 3);
233 assert_eq!(map.read(|snapshot| snapshot.values().sum::<i32>()), 30);
234 }
235
236 #[test]
237 fn snapshot_keeps_published_view() {
238 let map = ArcSwapMap::<u32, i32>::default();
239 map.insert(1, 10);
240
241 let snapshot = map.snapshot();
242 map.insert(1, 20);
243 map.insert(2, 30);
244
245 assert_eq!(snapshot.get(&1), Some(&10));
246 assert_eq!(snapshot.get(&2), None);
247 assert_eq!(map.get(&1), Some(20));
248 assert_eq!(map.get(&2), Some(30));
249 }
250
251 #[test]
252 fn clone_shares_the_same_cell() {
253 let map = ArcSwapMap::<u32, i32>::default();
254 let clone = map.clone();
255 map.insert(1, 10);
257 assert_eq!(clone.get(&1), Some(10));
258 clone.insert(2, 20);
259 assert_eq!(map.get(&2), Some(20));
260 }
261}