reifydb_runtime/sync/mutex/
mod.rs1use 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#[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
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}