Skip to main content

reifydb_runtime/sync/mutex/
mod.rs

1// SPDX-License-Identifier: MIT
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 native;
14#[cfg(reifydb_single_threaded)]
15pub(crate) mod wasm;
16
17cfg_if! {
18	if #[cfg(not(reifydb_single_threaded))] {
19		type MutexInnerImpl<T> = native::MutexInner<T>;
20		type MutexGuardInnerImpl<'a, T> = native::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: Single-threaded targets (WASM/WASI) don't have real concurrency
39#[cfg(reifydb_single_threaded)]
40unsafe impl<T> Sync for Mutex<T> {}
41
42impl<T> Mutex<T> {
43	#[inline]
44	pub fn new(value: T) -> Self {
45		Self {
46			inner: MutexInnerImpl::new(value),
47		}
48	}
49
50	#[inline]
51	pub fn lock(&self) -> MutexGuard<'_, T> {
52		MutexGuard {
53			inner: self.inner.lock(),
54		}
55	}
56
57	#[inline]
58	pub fn try_lock(&self) -> Option<MutexGuard<'_, T>> {
59		self.inner.try_lock().map(|inner| MutexGuard {
60			inner,
61		})
62	}
63}
64
65impl<T: Default> Default for Mutex<T> {
66	#[inline]
67	fn default() -> Self {
68		Self::new(T::default())
69	}
70}
71
72pub struct MutexGuard<'a, T> {
73	pub(in crate::sync) inner: MutexGuardInnerImpl<'a, T>,
74}
75
76impl<'a, T> Deref for MutexGuard<'a, T> {
77	type Target = T;
78
79	#[inline]
80	fn deref(&self) -> &T {
81		&self.inner
82	}
83}
84
85impl<'a, T> DerefMut for MutexGuard<'a, T> {
86	#[inline]
87	fn deref_mut(&mut self) -> &mut T {
88		&mut self.inner
89	}
90}
91
92impl<'a, T: Debug> Debug for MutexGuard<'a, T> {
93	#[inline]
94	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
95		(**self).fmt(f)
96	}
97}