Skip to main content

reifydb_runtime/sync/mutex/
mod.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2026 ReifyDB
3
4use std::{
5	fmt,
6	fmt::Debug,
7	ops::{Deref, DerefMut},
8};
9
10use cfg_if::cfg_if;
11
12#[cfg(all(not(reifydb_single_threaded), not(loom)))]
13pub(crate) mod host;
14#[cfg(loom)]
15pub(crate) mod loom;
16#[cfg(reifydb_single_threaded)]
17pub(crate) mod wasm;
18
19cfg_if! {
20	if #[cfg(loom)] {
21		type MutexInnerImpl<T> = loom::MutexInner<T>;
22		type MutexGuardInnerImpl<'a, T> = loom::MutexGuardInner<'a, T>;
23	} else if #[cfg(not(reifydb_single_threaded))] {
24		type MutexInnerImpl<T> = host::MutexInner<T>;
25		type MutexGuardInnerImpl<'a, T> = host::MutexGuardInner<'a, T>;
26	} else {
27		type MutexInnerImpl<T> = wasm::MutexInner<T>;
28		type MutexGuardInnerImpl<'a, T> = wasm::MutexGuardInner<'a, T>;
29	}
30}
31
32pub struct Mutex<T> {
33	inner: MutexInnerImpl<T>,
34}
35
36impl<T: Debug> Debug for Mutex<T> {
37	#[inline]
38	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
39		self.inner.fmt(f)
40	}
41}
42
43// SAFETY: under reifydb_single_threaded there is no second thread, so the RefCell-backed inner can never
44// be reached concurrently. The impl only satisfies Sync bounds and never backs a real cross-thread share.
45#[cfg(reifydb_single_threaded)]
46unsafe impl<T> Sync for Mutex<T> {}
47
48impl<T> Mutex<T> {
49	#[inline]
50	pub fn new(value: T) -> Self {
51		Self {
52			inner: MutexInnerImpl::new(value),
53		}
54	}
55
56	#[inline]
57	pub fn lock(&self) -> MutexGuard<'_, T> {
58		MutexGuard {
59			inner: self.inner.lock(),
60		}
61	}
62
63	#[inline]
64	pub fn try_lock(&self) -> Option<MutexGuard<'_, T>> {
65		self.inner.try_lock().map(|inner| MutexGuard {
66			inner,
67		})
68	}
69}
70
71impl<T: Default> Default for Mutex<T> {
72	#[inline]
73	fn default() -> Self {
74		Self::new(T::default())
75	}
76}
77
78pub struct MutexGuard<'a, T> {
79	pub(in crate::sync) inner: MutexGuardInnerImpl<'a, T>,
80}
81
82impl<'a, T> Deref for MutexGuard<'a, T> {
83	type Target = T;
84
85	#[inline]
86	fn deref(&self) -> &T {
87		&self.inner
88	}
89}
90
91impl<'a, T> DerefMut for MutexGuard<'a, T> {
92	#[inline]
93	fn deref_mut(&mut self) -> &mut T {
94		&mut self.inner
95	}
96}
97
98impl<'a, T: Debug> Debug for MutexGuard<'a, T> {
99	#[inline]
100	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
101		(**self).fmt(f)
102	}
103}