Skip to main content

reifydb_runtime/sync/mutex/
mod.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later
2// Copyright (c) 2025 ReifyDB
3
4use std::{
5	fmt,
6	fmt::Debug,
7	ops::{Deref, DerefMut},
8};
9
10use cfg_if::cfg_if;
11
12#[cfg(reifydb_target = "native")]
13pub(crate) mod native;
14#[cfg(reifydb_target = "wasm")]
15pub(crate) mod wasm;
16
17cfg_if! {
18	if #[cfg(reifydb_target = "native")] {
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
27/// A mutual exclusion primitive for protecting shared data.
28pub struct Mutex<T> {
29	inner: MutexInnerImpl<T>,
30}
31
32impl<T: Debug> Debug for Mutex<T> {
33	#[inline]
34	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
35		self.inner.fmt(f)
36	}
37}
38
39// SAFETY: WASM is single-threaded, so Sync is safe
40#[cfg(reifydb_target = "wasm")]
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
66pub struct MutexGuard<'a, T> {
67	pub(in crate::sync) inner: MutexGuardInnerImpl<'a, T>,
68}
69
70impl<'a, T> Deref for MutexGuard<'a, T> {
71	type Target = T;
72
73	#[inline]
74	fn deref(&self) -> &T {
75		&self.inner
76	}
77}
78
79impl<'a, T> DerefMut for MutexGuard<'a, T> {
80	#[inline]
81	fn deref_mut(&mut self) -> &mut T {
82		&mut self.inner
83	}
84}