Skip to main content

reifydb_runtime/sync/rwlock/
mod.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2025 ReifyDB
3
4use std::ops::{Deref, DerefMut};
5
6use cfg_if::cfg_if;
7
8#[cfg(not(reifydb_single_threaded))]
9pub(crate) mod native;
10#[cfg(reifydb_single_threaded)]
11pub(crate) mod wasm;
12
13cfg_if! {
14	if #[cfg(not(reifydb_single_threaded))] {
15		type RwLockInnerImpl<T> = native::RwLockInner<T>;
16		type RwLockReadGuardInnerImpl<'a, T> = native::RwLockReadGuardInner<'a, T>;
17		type RwLockWriteGuardInnerImpl<'a, T> = native::RwLockWriteGuardInner<'a, T>;
18	} else {
19		type RwLockInnerImpl<T> = wasm::RwLockInner<T>;
20		type RwLockReadGuardInnerImpl<'a, T> = wasm::RwLockReadGuardInner<'a, T>;
21		type RwLockWriteGuardInnerImpl<'a, T> = wasm::RwLockWriteGuardInner<'a, T>;
22	}
23}
24
25pub struct RwLock<T> {
26	inner: RwLockInnerImpl<T>,
27}
28
29// SAFETY: Single-threaded targets (WASM/WASI) don't have real concurrency
30#[cfg(reifydb_single_threaded)]
31unsafe impl<T> Sync for RwLock<T> {}
32
33impl<T> RwLock<T> {
34	#[inline]
35	pub fn new(value: T) -> Self {
36		Self {
37			inner: RwLockInnerImpl::new(value),
38		}
39	}
40
41	#[inline]
42	pub fn read(&self) -> RwLockReadGuard<'_, T> {
43		RwLockReadGuard {
44			inner: self.inner.read(),
45		}
46	}
47
48	#[inline]
49	pub fn write(&self) -> RwLockWriteGuard<'_, T> {
50		RwLockWriteGuard {
51			inner: self.inner.write(),
52		}
53	}
54
55	#[inline]
56	pub fn try_read(&self) -> Option<RwLockReadGuard<'_, T>> {
57		self.inner.try_read().map(|inner| RwLockReadGuard {
58			inner,
59		})
60	}
61
62	#[inline]
63	pub fn try_write(&self) -> Option<RwLockWriteGuard<'_, T>> {
64		self.inner.try_write().map(|inner| RwLockWriteGuard {
65			inner,
66		})
67	}
68}
69
70pub struct RwLockReadGuard<'a, T> {
71	inner: RwLockReadGuardInnerImpl<'a, T>,
72}
73
74impl<'a, T> Deref for RwLockReadGuard<'a, T> {
75	type Target = T;
76
77	#[inline]
78	fn deref(&self) -> &T {
79		&self.inner
80	}
81}
82
83pub struct RwLockWriteGuard<'a, T> {
84	inner: RwLockWriteGuardInnerImpl<'a, T>,
85}
86
87impl<'a, T> Deref for RwLockWriteGuard<'a, T> {
88	type Target = T;
89
90	#[inline]
91	fn deref(&self) -> &T {
92		&self.inner
93	}
94}
95
96impl<'a, T> DerefMut for RwLockWriteGuard<'a, T> {
97	#[inline]
98	fn deref_mut(&mut self) -> &mut T {
99		&mut self.inner
100	}
101}