asr/
sync.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
//! Useful synchronization primitives.

use core::{
    cell::{RefCell, RefMut, UnsafeCell},
    marker::PhantomData,
    ops::{Deref, DerefMut},
};

/// A mutual exclusion primitive useful for protecting shared data. This mutex
/// is specifically for single-threaded WebAssembly.
pub struct Mutex<T: ?Sized>(RefCell<T>);

/// An RAII implementation of a “scoped lock” of a mutex. When this structure is
/// dropped (falls out of scope), the lock will be unlocked.
///
/// The data protected by the mutex can be accessed through this guard via its
/// [`Deref`] and [`DerefMut`] implementations.
///
/// This structure is created by the [`lock`](Mutex::<T>::lock) and
/// [`try_lock`](Mutex::<T>::try_lock) methods on Mutex.
pub struct MutexGuard<'a, T: ?Sized>(RefMut<'a, T>);

/// A type alias for the result of a nonblocking locking method.
pub type TryLockResult<Guard> = Result<Guard, TryLockError<Guard>>;

/// An enumeration of possible errors associated with a [`TryLockResult`] which
/// can occur while trying to acquire a lock, from the
/// [`try_lock`](Mutex::<T>::try_lock) method on a Mutex.
pub struct TryLockError<T> {
    _private: PhantomData<T>,
}

impl<T> Mutex<T> {
    /// Creates a new mutex in an unlocked state ready for use.
    #[inline]
    pub const fn new(value: T) -> Self {
        Self(RefCell::new(value))
    }
}

impl<T: ?Sized> Mutex<T> {
    /// Acquires a mutex, panics if it is unable to do so.
    #[track_caller]
    #[inline]
    pub fn lock(&self) -> MutexGuard<'_, T> {
        MutexGuard(self.0.borrow_mut())
    }

    /// Attempts to acquire this lock.
    ///
    /// If the lock could not be acquired at this time, then Err is returned.
    /// Otherwise, an RAII guard is returned. The lock will be unlocked when the
    /// guard is dropped.
    //
    /// This function does not block.
    #[inline]
    pub fn try_lock(&self) -> TryLockResult<MutexGuard<'_, T>> {
        Ok(MutexGuard(self.0.try_borrow_mut().map_err(|_| {
            TryLockError {
                _private: PhantomData,
            }
        })?))
    }

    /// Consumes this mutex, returning the underlying data.
    #[inline]
    pub fn into_inner(self) -> T
    where
        T: Sized,
    {
        self.0.into_inner()
    }

    /// Returns a mutable reference to the underlying data.
    #[inline]
    pub fn get_mut(&mut self) -> &mut T {
        self.0.get_mut()
    }
}

impl<T: ?Sized> Deref for MutexGuard<'_, T> {
    type Target = T;

    #[inline]
    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl<T: ?Sized> DerefMut for MutexGuard<'_, T> {
    #[inline]
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

#[cfg(not(target_feature = "atomics"))]
// SAFETY: This is the same as std's Mutex, but it can only be safe in
// single-threaded WASM, because we use RefCell underneath.
unsafe impl<T: ?Sized + Send> Send for Mutex<T> {}

#[cfg(not(target_feature = "atomics"))]
// SAFETY: This is the same as std's Mutex, but it can only be safe in
// single-threaded WASM, because we use RefCell underneath.
unsafe impl<T: ?Sized + Send> Sync for Mutex<T> {}

// TODO: Currently not possible in stable Rust.
// impl<T: ?Sized> !Send for MutexGuard<'_, T>
#[cfg(not(target_feature = "atomics"))]
// SAFETY: This is the same as std's MutexGuard, but it can only be safe in
// single-threaded WASM, because we use RefMut underneath.
unsafe impl<T: ?Sized + Sync> Sync for MutexGuard<'_, T> {}

/// A wrapper type that can be used for creating mutable global variables. It
/// does not by itself provide any thread safety.
#[repr(transparent)]
pub struct RacyCell<T>(UnsafeCell<T>);

// SAFETY: The thread unsafety is delegated to the user of this type.
unsafe impl<T> Sync for RacyCell<T> {}
// SAFETY: The thread unsafety is delegated to the user of this type.
unsafe impl<T> Send for RacyCell<T> {}

impl<T> RacyCell<T> {
    /// Creates a new `RacyCell` containing the given value.
    #[inline(always)]
    pub const fn new(value: T) -> Self {
        RacyCell(UnsafeCell::new(value))
    }

    /// Accesses the inner value as mutable pointer. There is no synchronization
    /// provided by this type, so it is up to the user to ensure that no other
    /// references to the value are used while this pointer is alive.
    ///
    /// # Safety
    ///
    /// You need to ensure that no other references to the value are used while
    /// this pointer is alive.
    #[inline(always)]
    pub const unsafe fn get_mut(&self) -> *mut T {
        self.0.get()
    }

    /// Accesses the inner value as const pointer. There is no synchronization
    /// provided by this type, so it is up to the user to ensure that no other
    /// references to the value are used while this pointer is alive.
    ///
    /// # Safety
    ///
    /// You need to ensure that no other references to the value are used while
    /// this pointer is alive.
    #[inline(always)]
    pub const unsafe fn get(&self) -> *const T {
        self.0.get()
    }
}