reifydb-runtime 0.4.12

Runtime infrastructure for ReifyDB
Documentation
// SPDX-License-Identifier: Apache-2.0
// Copyright (c) 2025 ReifyDB

use std::{
	fmt,
	fmt::Debug,
	ops::{Deref, DerefMut},
};

use cfg_if::cfg_if;

#[cfg(not(reifydb_single_threaded))]
pub(crate) mod native;
#[cfg(reifydb_single_threaded)]
pub(crate) mod wasm;

cfg_if! {
	if #[cfg(not(reifydb_single_threaded))] {
		type MutexInnerImpl<T> = native::MutexInner<T>;
		type MutexGuardInnerImpl<'a, T> = native::MutexGuardInner<'a, T>;
	} else {
		type MutexInnerImpl<T> = wasm::MutexInner<T>;
		type MutexGuardInnerImpl<'a, T> = wasm::MutexGuardInner<'a, T>;
	}
}

/// A mutual exclusion primitive for protecting shared data.
pub struct Mutex<T> {
	inner: MutexInnerImpl<T>,
}

impl<T: Debug> Debug for Mutex<T> {
	#[inline]
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		self.inner.fmt(f)
	}
}

// SAFETY: Single-threaded targets (WASM/WASI) don't have real concurrency
#[cfg(reifydb_single_threaded)]
unsafe impl<T> Sync for Mutex<T> {}

impl<T> Mutex<T> {
	#[inline]
	pub fn new(value: T) -> Self {
		Self {
			inner: MutexInnerImpl::new(value),
		}
	}

	#[inline]
	pub fn lock(&self) -> MutexGuard<'_, T> {
		MutexGuard {
			inner: self.inner.lock(),
		}
	}

	#[inline]
	pub fn try_lock(&self) -> Option<MutexGuard<'_, T>> {
		self.inner.try_lock().map(|inner| MutexGuard {
			inner,
		})
	}
}

pub struct MutexGuard<'a, T> {
	pub(in crate::sync) inner: MutexGuardInnerImpl<'a, T>,
}

impl<'a, T> Deref for MutexGuard<'a, T> {
	type Target = T;

	#[inline]
	fn deref(&self) -> &T {
		&self.inner
	}
}

impl<'a, T> DerefMut for MutexGuard<'a, T> {
	#[inline]
	fn deref_mut(&mut self) -> &mut T {
		&mut self.inner
	}
}