Skip to main content

reifydb_runtime/sync/map/
mod.rs

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