Skip to main content

reifydb_runtime/sync/map/
mod.rs

1//! Concurrent map abstraction that provides a unified API across native and WASM targets.
2//!
3//! On native platforms, this wraps `DashMap` for high-performance concurrent access.
4//! On WASM platforms, this wraps `Arc<RwLock<HashMap>>` to provide similar semantics.
5
6use std::{borrow::Borrow, hash::Hash};
7
8use cfg_if::cfg_if;
9
10#[cfg(reifydb_target = "native")]
11pub(crate) mod native;
12
13#[cfg(reifydb_target = "wasm")]
14pub(crate) mod wasm;
15
16cfg_if! {
17    if #[cfg(reifydb_target = "native")] {
18	type MapInnerImpl<K, V> = native::MapInner<K, V>;
19    } else {
20	type MapInnerImpl<K, V> = wasm::MapInner<K, V>;
21    }
22}
23
24/// A concurrent map that provides a unified API across native and WASM targets.
25pub struct Map<K, V>
26where
27	K: Eq + Hash,
28{
29	inner: MapInnerImpl<K, V>,
30}
31
32impl<K, V> Map<K, V>
33where
34	K: Eq + Hash,
35{
36	#[inline]
37	pub fn new() -> Self {
38		Self {
39			inner: MapInnerImpl::new(),
40		}
41	}
42
43	#[inline]
44	pub fn get_or_insert_with<F>(&self, key: K, f: F) -> V
45	where
46		F: FnOnce() -> V,
47		V: Clone,
48		K: Clone,
49	{
50		self.inner.get_or_insert_with(key, f)
51	}
52
53	#[inline]
54	pub fn get<Q>(&self, key: &Q) -> Option<V>
55	where
56		K: Borrow<Q>,
57		Q: Hash + Eq + ?Sized,
58		V: Clone,
59	{
60		self.inner.get(key)
61	}
62
63	#[inline]
64	pub fn contains_key<Q>(&self, key: &Q) -> bool
65	where
66		K: Borrow<Q>,
67		Q: Hash + Eq + ?Sized,
68	{
69		self.inner.contains_key(key)
70	}
71
72	#[inline]
73	pub fn with_read<Q, R, F>(&self, key: &Q, f: F) -> Option<R>
74	where
75		K: Borrow<Q>,
76		Q: Hash + Eq + ?Sized,
77		F: FnOnce(&V) -> R,
78	{
79		self.inner.with_read(key, f)
80	}
81
82	#[inline]
83	pub fn insert(&self, key: K, value: V)
84	where
85		K: Clone,
86	{
87		self.inner.insert(key, value);
88	}
89
90	#[inline]
91	pub fn remove<Q>(&self, key: &Q) -> Option<V>
92	where
93		K: Borrow<Q>,
94		Q: Hash + Eq + ?Sized,
95	{
96		self.inner.remove(key)
97	}
98
99	#[inline]
100	pub fn keys(&self) -> Vec<K>
101	where
102		K: Clone,
103	{
104		self.inner.keys()
105	}
106
107	/// Clears `buf` and fills it with all keys in the map, reusing the buffer's allocation.
108	#[inline]
109	pub fn keys_into(&self, buf: &mut Vec<K>)
110	where
111		K: Clone,
112	{
113		self.inner.keys_into(buf)
114	}
115
116	#[inline]
117	pub fn with_write<Q, R, F>(&self, key: &Q, f: F) -> Option<R>
118	where
119		K: Borrow<Q>,
120		Q: Hash + Eq + ?Sized,
121		F: FnOnce(&mut V) -> R,
122	{
123		self.inner.with_write(key, f)
124	}
125
126	#[inline]
127	pub fn clear(&self) {
128		self.inner.clear();
129	}
130}
131
132impl<K, V> Default for Map<K, V>
133where
134	K: Eq + Hash,
135{
136	#[inline]
137	fn default() -> Self {
138		Self::new()
139	}
140}