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::Debug,
6	ops::{Deref, DerefMut},
7};
8
9use cfg_if::cfg_if;
10
11#[cfg(reifydb_target = "native")]
12pub(crate) mod native;
13#[cfg(reifydb_target = "wasm")]
14pub(crate) mod wasm;
15
16cfg_if! {
17	if #[cfg(reifydb_target = "native")] {
18		type MutexInnerImpl<T> = native::MutexInner<T>;
19		type MutexGuardInnerImpl<'a, T> = native::MutexGuardInner<'a, T>;
20	} else {
21		type MutexInnerImpl<T> = wasm::MutexInner<T>;
22		type MutexGuardInnerImpl<'a, T> = wasm::MutexGuardInner<'a, T>;
23	}
24}
25
26/// A mutual exclusion primitive for protecting shared data.
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 std::fmt::Formatter<'_>) -> std::fmt::Result {
34		self.inner.fmt(f)
35	}
36}
37
38// SAFETY: WASM is single-threaded, so Sync is safe
39#[cfg(reifydb_target = "wasm")]
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
65pub struct MutexGuard<'a, T> {
66	pub(in crate::sync) inner: MutexGuardInnerImpl<'a, T>,
67}
68
69impl<'a, T> Deref for MutexGuard<'a, T> {
70	type Target = T;
71
72	#[inline]
73	fn deref(&self) -> &T {
74		&self.inner
75	}
76}
77
78impl<'a, T> DerefMut for MutexGuard<'a, T> {
79	#[inline]
80	fn deref_mut(&mut self) -> &mut T {
81		&mut self.inner
82	}
83}