iroh/socket/
concurrent_read_map.rs

1//! This module implements a map that can be modified from only one task but read from many others.
2//!
3//! We ensure this map avoids race conditions from multiple writers by doing these two things:
4//! - We only allow writing from one owner of the `&mut self` [`ConcurrentReadMap`].
5//!   It cannot be cloned.
6//! - The read-only replicas [`ReadOnlyMap`] can only read, not write, but allow reading from
7//!   concurrent tasks.
8
9use std::{hash::Hash, sync::Arc};
10
11use rustc_hash::FxBuildHasher;
12
13/// A map that can be modified from only one task but read from many others.
14///
15/// Only the single `&mut self`-based "leader" which owns this map can modify it, but cheaply
16/// clonable "followers" can be created with [`ConcurrentReadMap::read_only`].
17/// These clones will update with recent writes from the leader.
18#[derive(Debug)]
19pub(crate) struct ConcurrentReadMap<K: Hash + Eq, V>(Arc<papaya::HashMap<K, V, FxBuildHasher>>);
20
21impl<K: Hash + Eq, V> Default for ConcurrentReadMap<K, V> {
22    fn default() -> Self {
23        Self(Default::default())
24    }
25}
26
27impl<K: Hash + Eq, V> ConcurrentReadMap<K, V> {
28    pub(crate) fn get_or_insert_with<F>(&mut self, key: K, f: F) -> V
29    where
30        F: FnOnce() -> V,
31        V: Clone,
32    {
33        self.0.get_or_insert_with(key, f, &self.0.guard()).clone()
34    }
35
36    pub(crate) fn insert(&mut self, key: K, value: V) {
37        self.0.insert(key, value, &self.0.guard());
38    }
39
40    pub(crate) fn remove(&mut self, key: &K) {
41        self.0.remove(key, &self.0.guard());
42    }
43
44    pub(crate) fn read_only(&self) -> ReadOnlyMap<K, V> {
45        ReadOnlyMap(self.0.clone())
46    }
47}
48
49/// A read replica for a [`ConcurrentReadMap`].
50///
51/// These can be cloned cheaply and will read recent writes from the original map.
52#[derive(Clone, Debug)]
53pub(crate) struct ReadOnlyMap<K: Hash + Eq, V>(Arc<papaya::HashMap<K, V, FxBuildHasher>>);
54
55impl<K: Hash + Eq, V> ReadOnlyMap<K, V> {
56    pub(crate) fn get(&self, key: &K) -> Option<V>
57    where
58        V: Clone,
59    {
60        self.0.get(key, &self.0.guard()).cloned()
61    }
62
63    pub(crate) fn guard(&self) -> papaya::LocalGuard<'_> {
64        self.0.guard()
65    }
66
67    pub(crate) fn values<'g, G: papaya::Guard>(&self, guard: &'g G) -> papaya::Values<'g, K, V, G> {
68        self.0.values(guard)
69    }
70}