#[cfg(not(feature = "std"))]
use spin::{Mutex as MutexImported, MutexGuard, Once as OnceImported, RwLock as RwLockImported};
#[cfg(feature = "std")]
use std::sync::{
Mutex as MutexImported, MutexGuard, OnceLock as OnceImported, RwLock as RwLockImported,
};
#[cfg(not(feature = "std"))]
pub use spin::{RwLockReadGuard, RwLockWriteGuard};
#[cfg(feature = "std")]
pub use std::sync::{RwLockReadGuard, RwLockWriteGuard};
#[cfg(target_has_atomic = "ptr")]
pub use alloc::sync::Arc;
#[cfg(not(target_has_atomic = "ptr"))]
pub use portable_atomic_util::Arc;
#[derive(Debug)]
pub struct Mutex<T> {
inner: MutexImported<T>,
}
impl<T> Mutex<T> {
#[inline(always)]
pub const fn new(value: T) -> Self {
Self {
inner: MutexImported::new(value),
}
}
#[inline(always)]
pub fn lock(&self) -> Result<MutexGuard<'_, T>, alloc::string::String> {
#[cfg(not(feature = "std"))]
{
Ok(self.inner.lock())
}
#[cfg(feature = "std")]
{
self.inner.lock().map_err(|err| err.to_string())
}
}
}
#[derive(Debug)]
pub struct RwLock<T> {
inner: RwLockImported<T>,
}
impl<T> RwLock<T> {
#[inline(always)]
pub const fn new(value: T) -> Self {
Self {
inner: RwLockImported::new(value),
}
}
#[inline(always)]
pub fn read(&self) -> Result<RwLockReadGuard<'_, T>, alloc::string::String> {
#[cfg(not(feature = "std"))]
{
Ok(self.inner.read())
}
#[cfg(feature = "std")]
{
self.inner.read().map_err(|err| err.to_string())
}
}
#[inline(always)]
pub fn write(&self) -> Result<RwLockWriteGuard<'_, T>, alloc::string::String> {
#[cfg(not(feature = "std"))]
{
Ok(self.inner.write())
}
#[cfg(feature = "std")]
{
self.inner.write().map_err(|err| err.to_string())
}
}
}
#[allow(dead_code)]
#[derive(Eq, PartialEq, Clone, Copy, Hash, Debug)]
pub struct ThreadId(core::num::NonZeroU64);
pub struct SyncOnceCell<T>(OnceImported<T>);
impl<T: core::fmt::Debug> Default for SyncOnceCell<T> {
fn default() -> Self {
Self::new()
}
}
impl<T: core::fmt::Debug> SyncOnceCell<T> {
#[inline(always)]
pub fn new() -> Self {
Self(OnceImported::new())
}
#[inline(always)]
pub fn initialized(value: T) -> Self {
#[cfg(not(feature = "std"))]
{
let cell = OnceImported::initialized(value);
Self(cell)
}
#[cfg(feature = "std")]
{
let cell = OnceImported::new();
cell.set(value).unwrap();
Self(cell)
}
}
#[inline(always)]
pub fn get_or_init<F>(&self, f: F) -> &T
where
F: FnOnce() -> T,
{
#[cfg(not(feature = "std"))]
{
self.0.call_once(f)
}
#[cfg(feature = "std")]
{
self.0.get_or_init(f)
}
}
}