1use super::CriticalSection;
2use core::cell::{Ref, RefCell, RefMut, UnsafeCell};
3
4/// A mutex based on critical sections.
5///
6/// # Example
7///
8/// ```no_run
9/// # use critical_section::Mutex;
10/// # use std::cell::Cell;
11///
12/// static FOO: Mutex<Cell<i32>> = Mutex::new(Cell::new(42));
13///
14/// fn main() {
15/// critical_section::with(|cs| {
16/// FOO.borrow(cs).set(43);
17/// });
18/// }
19///
20/// fn interrupt_handler() {
21/// let _x = critical_section::with(|cs| FOO.borrow(cs).get());
22/// }
23/// ```
24///
25///
26/// # Design
27///
28/// [`std::sync::Mutex`] has two purposes. It converts types that are [`Send`]
29/// but not [`Sync`] into types that are both; and it provides
30/// [interior mutability]. `critical_section::Mutex`, on the other hand, only adds
31/// `Sync`. It does *not* provide interior mutability.
32///
33/// This was a conscious design choice. It is possible to create multiple
34/// [`CriticalSection`] tokens, either by nesting critical sections or `Copy`ing
35/// an existing token. As a result, it would not be sound for [`Mutex::borrow`]
36/// to return `&mut T`, because there would be nothing to prevent calling
37/// `borrow` multiple times to create aliased `&mut T` references.
38///
39/// The solution is to include a runtime check to ensure that each resource is
40/// borrowed only once. This is what `std::sync::Mutex` does. However, this is
41/// a runtime cost that may not be required in all circumstances. For instance,
42/// `Mutex<Cell<T>>` never needs to create `&mut T` or equivalent.
43///
44/// If `&mut T` is needed, the simplest solution is to use `Mutex<RefCell<T>>`,
45/// which is the closest analogy to `std::sync::Mutex`. [`RefCell`] inserts the
46/// exact runtime check necessary to guarantee that the `&mut T` reference is
47/// unique.
48///
49/// To reduce verbosity when using `Mutex<RefCell<T>>`, we reimplement some of
50/// `RefCell`'s methods on it directly.
51///
52/// ```no_run
53/// # use critical_section::Mutex;
54/// # use std::cell::RefCell;
55///
56/// static FOO: Mutex<RefCell<i32>> = Mutex::new(RefCell::new(42));
57///
58/// fn main() {
59/// critical_section::with(|cs| {
60/// // Instead of calling this
61/// let _ = FOO.borrow(cs).take();
62/// // Call this
63/// let _ = FOO.take(cs);
64/// // `RefCell::borrow` and `RefCell::borrow_mut` are renamed to
65/// // `borrow_ref` and `borrow_ref_mut` to avoid name collisions
66/// let _: &mut i32 = &mut *FOO.borrow_ref_mut(cs);
67/// })
68/// }
69/// ```
70///
71/// [`std::sync::Mutex`]: https://doc.rust-lang.org/std/sync/struct.Mutex.html
72/// [interior mutability]: https://doc.rust-lang.org/reference/interior-mutability.html
73#[derive(Debug)]
74pub struct Mutex<T> {
75 inner: UnsafeCell<T>,
76}
77
78impl<T> Mutex<T> {
79 /// Creates a new mutex.
80 #[inline]
81 pub const fn new(value: T) -> Self {
82 Mutex {
83 inner: UnsafeCell::new(value),
84 }
85 }
86
87 /// Gets a mutable reference to the contained value when the mutex is already uniquely borrowed.
88 ///
89 /// This does not require locking or a critical section since it takes `&mut self`, which
90 /// guarantees unique ownership already. Care must be taken when using this method to
91 /// **unsafely** access `static mut` variables, appropriate fences must be used to prevent
92 /// unwanted optimizations.
93 #[inline]
94 pub fn get_mut(&mut self) -> &mut T {
95 unsafe { &mut *self.inner.get() }
96 }
97
98 /// Unwraps the contained value, consuming the mutex.
99 #[inline]
100 pub fn into_inner(self) -> T {
101 self.inner.into_inner()
102 }
103
104 /// Borrows the data for the duration of the critical section.
105 #[inline]
106 pub fn borrow<'cs>(&'cs self, _cs: CriticalSection<'cs>) -> &'cs T {
107 unsafe { &*self.inner.get() }
108 }
109}
110
111impl<T> Mutex<RefCell<T>> {
112 /// Borrow the data and call [`RefCell::replace`]
113 ///
114 /// This is equivalent to `self.borrow(cs).replace(t)`
115 ///
116 /// # Panics
117 ///
118 /// This call could panic. See the documentation for [`RefCell::replace`]
119 /// for more details.
120 #[inline]
121 #[track_caller]
122 pub fn replace<'cs>(&'cs self, cs: CriticalSection<'cs>, t: T) -> T {
123 self.borrow(cs).replace(t)
124 }
125
126 /// Borrow the data and call [`RefCell::replace_with`]
127 ///
128 /// This is equivalent to `self.borrow(cs).replace_with(f)`
129 ///
130 /// # Panics
131 ///
132 /// This call could panic. See the documentation for
133 /// [`RefCell::replace_with`] for more details.
134 #[inline]
135 #[track_caller]
136 pub fn replace_with<'cs, F>(&'cs self, cs: CriticalSection<'cs>, f: F) -> T
137 where
138 F: FnOnce(&mut T) -> T,
139 {
140 self.borrow(cs).replace_with(f)
141 }
142
143 /// Borrow the data and call [`RefCell::borrow`]
144 ///
145 /// This is equivalent to `self.borrow(cs).borrow()`
146 ///
147 /// # Panics
148 ///
149 /// This call could panic. See the documentation for [`RefCell::borrow`]
150 /// for more details.
151 #[inline]
152 #[track_caller]
153 pub fn borrow_ref<'cs>(&'cs self, cs: CriticalSection<'cs>) -> Ref<'cs, T> {
154 self.borrow(cs).borrow()
155 }
156
157 /// Borrow the data and call [`RefCell::borrow_mut`]
158 ///
159 /// This is equivalent to `self.borrow(cs).borrow_mut()`
160 ///
161 /// # Panics
162 ///
163 /// This call could panic. See the documentation for [`RefCell::borrow_mut`]
164 /// for more details.
165 #[inline]
166 #[track_caller]
167 pub fn borrow_ref_mut<'cs>(&'cs self, cs: CriticalSection<'cs>) -> RefMut<'cs, T> {
168 self.borrow(cs).borrow_mut()
169 }
170}
171
172impl<T: Default> Mutex<RefCell<T>> {
173 /// Borrow the data and call [`RefCell::take`]
174 ///
175 /// This is equivalent to `self.borrow(cs).take()`
176 ///
177 /// # Panics
178 ///
179 /// This call could panic. See the documentation for [`RefCell::take`]
180 /// for more details.
181 #[inline]
182 #[track_caller]
183 pub fn take<'cs>(&'cs self, cs: CriticalSection<'cs>) -> T {
184 self.borrow(cs).take()
185 }
186}
187
188// NOTE A `Mutex` can be used as a channel so the protected data must be `Send`
189// to prevent sending non-Sendable stuff (e.g. access tokens) across different
190// threads.
191unsafe impl<T> Sync for Mutex<T> where T: Send {}
192
193/// ``` compile_fail
194/// fn bad(cs: critical_section::CriticalSection) -> &u32 {
195/// let x = critical_section::Mutex::new(42u32);
196/// x.borrow(cs)
197/// }
198/// ```
199#[cfg(doctest)]
200const BorrowMustNotOutliveMutexTest: () = ();
201