Skip to main content

reifydb_runtime/sync/map/
mod.rs

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