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