1 /* 2 * Copyright 2020 Actyx AG 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 //! A mutual exclusion primitive that relies on static type information only 17 //! 18 //! This library is inspired by [this discussion](https://internals.rust-lang.org/t/what-shall-sync-mean-across-an-await/12020/2). 19 #![doc(html_logo_url = "https://developer.actyx.com/img/logo.svg")] 20 #![doc(html_favicon_url = "https://developer.actyx.com/img/favicon.ico")] 21 #![no_std] 22 23 // ANDROID: Use std to allow building as a dylib. 24 #[cfg(android_dylib)] 25 extern crate std; 26 27 use core::{ 28 fmt::{self, Debug, Formatter}, 29 pin::Pin, 30 future::Future, 31 task::{Context, Poll}, 32 }; 33 34 /// A mutual exclusion primitive that relies on static type information only 35 /// 36 /// In some cases synchronization can be proven statically: whenever you hold an exclusive `&mut` 37 /// reference, the Rust type system ensures that no other part of the program can hold another 38 /// reference to the data. Therefore it is safe to access it even if the current thread obtained 39 /// this reference via a channel. Whenever this is the case, the overhead of allocating and locking 40 /// a [`Mutex`] can be avoided by using this static version. 41 /// 42 /// One example where this is often applicable is [`Future`], which requires an exclusive reference 43 /// for its [`poll`] method: While a given `Future` implementation may not be safe to access by 44 /// multiple threads concurrently, the executor can only run the `Future` on one thread at any 45 /// given time, making it [`Sync`] in practice as long as the implementation is `Send`. You can 46 /// therefore use the static mutex to prove that your data structure is `Sync` even though it 47 /// contains such a `Future`. 48 /// 49 /// # Example 50 /// 51 /// ``` 52 /// use sync_wrapper::SyncWrapper; 53 /// use std::future::Future; 54 /// 55 /// struct MyThing { 56 /// future: SyncWrapper<Box<dyn Future<Output = String> + Send>>, 57 /// } 58 /// 59 /// impl MyThing { 60 /// // all accesses to `self.future` now require an exclusive reference or ownership 61 /// } 62 /// 63 /// fn assert_sync<T: Sync>() {} 64 /// 65 /// assert_sync::<MyThing>(); 66 /// ``` 67 /// 68 /// [`Mutex`]: https://doc.rust-lang.org/std/sync/struct.Mutex.html 69 /// [`Future`]: https://doc.rust-lang.org/std/future/trait.Future.html 70 /// [`poll`]: https://doc.rust-lang.org/std/future/trait.Future.html#method.poll 71 /// [`Sync`]: https://doc.rust-lang.org/std/marker/trait.Sync.html 72 #[repr(transparent)] 73 pub struct SyncWrapper<T>(T); 74 75 impl<T> SyncWrapper<T> { 76 /// Creates a new static mutex containing the given value. 77 /// 78 /// # Examples 79 /// 80 /// ``` 81 /// use sync_wrapper::SyncWrapper; 82 /// 83 /// let mutex = SyncWrapper::new(42); 84 /// ``` new(value: T) -> Self85 pub const fn new(value: T) -> Self { 86 Self(value) 87 } 88 89 /// Acquires a reference to the protected value. 90 /// 91 /// This is safe because it requires an exclusive reference to the mutex. Therefore this method 92 /// neither panics nor does it return an error. This is in contrast to [`Mutex::get_mut`] which 93 /// returns an error if another thread panicked while holding the lock. It is not recommended 94 /// to send an exclusive reference to a potentially damaged value to another thread for further 95 /// processing. 96 /// 97 /// [`Mutex::get_mut`]: https://doc.rust-lang.org/std/sync/struct.Mutex.html#method.get_mut 98 /// 99 /// # Examples 100 /// 101 /// ``` 102 /// use sync_wrapper::SyncWrapper; 103 /// 104 /// let mut mutex = SyncWrapper::new(42); 105 /// let value = mutex.get_mut(); 106 /// *value = 0; 107 /// assert_eq!(*mutex.get_mut(), 0); 108 /// ``` get_mut(&mut self) -> &mut T109 pub fn get_mut(&mut self) -> &mut T { 110 &mut self.0 111 } 112 113 /// Acquires a pinned reference to the protected value. 114 /// 115 /// See [`Self::get_mut`] for why this method is safe. 116 /// 117 /// # Examples 118 /// 119 /// ``` 120 /// use std::future::Future; 121 /// use std::pin::Pin; 122 /// use std::task::{Context, Poll}; 123 /// 124 /// use pin_project_lite::pin_project; 125 /// use sync_wrapper::SyncWrapper; 126 /// 127 /// pin_project! { 128 /// struct FutureWrapper<F> { 129 /// #[pin] 130 /// inner: SyncWrapper<F>, 131 /// } 132 /// } 133 /// 134 /// impl<F: Future> Future for FutureWrapper<F> { 135 /// type Output = F::Output; 136 /// 137 /// fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { 138 /// self.project().inner.get_pin_mut().poll(cx) 139 /// } 140 /// } 141 /// ``` get_pin_mut(self: Pin<&mut Self>) -> Pin<&mut T>142 pub fn get_pin_mut(self: Pin<&mut Self>) -> Pin<&mut T> { 143 unsafe { Pin::map_unchecked_mut(self, |this| &mut this.0) } 144 } 145 146 /// Consumes this mutex, returning the underlying data. 147 /// 148 /// This is safe because it requires ownership of the mutex, therefore this method will neither 149 /// panic nor does it return an error. This is in contrast to [`Mutex::into_inner`] which 150 /// returns an error if another thread panicked while holding the lock. It is not recommended 151 /// to send an exclusive reference to a potentially damaged value to another thread for further 152 /// processing. 153 /// 154 /// [`Mutex::into_inner`]: https://doc.rust-lang.org/std/sync/struct.Mutex.html#method.into_inner 155 /// 156 /// # Examples 157 /// 158 /// ``` 159 /// use sync_wrapper::SyncWrapper; 160 /// 161 /// let mut mutex = SyncWrapper::new(42); 162 /// assert_eq!(mutex.into_inner(), 42); 163 /// ``` into_inner(self) -> T164 pub fn into_inner(self) -> T { 165 self.0 166 } 167 } 168 169 // this is safe because the only operations permitted on this data structure require exclusive 170 // access or ownership 171 unsafe impl<T> Sync for SyncWrapper<T> {} 172 173 impl<T> Debug for SyncWrapper<T> { fmt(&self, f: &mut Formatter<'_>) -> fmt::Result174 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { 175 f.pad("SyncWrapper") 176 } 177 } 178 179 impl<T: Default> Default for SyncWrapper<T> { default() -> Self180 fn default() -> Self { 181 Self::new(T::default()) 182 } 183 } 184 185 impl<T> From<T> for SyncWrapper<T> { from(value: T) -> Self186 fn from(value: T) -> Self { 187 Self::new(value) 188 } 189 } 190 191 /// `Future` which is `Sync`. 192 /// 193 /// # Examples 194 /// 195 /// ``` 196 /// use sync_wrapper::{SyncWrapper, SyncFuture}; 197 /// 198 /// let fut = async { 1 }; 199 /// let fut = SyncFuture::new(fut); 200 /// ``` 201 pub struct SyncFuture<F> { 202 inner: SyncWrapper<F> 203 } 204 impl <F: Future> SyncFuture<F> { new(inner: F) -> Self205 pub fn new(inner: F) -> Self { 206 Self { inner: SyncWrapper::new(inner) } 207 } into_inner(self) -> F208 pub fn into_inner(self) -> F { 209 self.inner.into_inner() 210 } 211 } 212 impl <F: Future> Future for SyncFuture<F> { 213 type Output = F::Output; poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output>214 fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { 215 let inner = unsafe { self.map_unchecked_mut(|x| x.inner.get_mut()) }; 216 inner.poll(cx) 217 } 218 } 219 220 /// `Stream` which is `Sync`. 221 /// 222 /// # Examples 223 /// 224 /// ``` 225 /// use sync_wrapper::SyncStream; 226 /// use futures::stream; 227 /// 228 /// let st = stream::iter(vec![1]); 229 /// let st = SyncStream::new(st); 230 /// ``` 231 #[cfg(feature = "futures")] 232 pub struct SyncStream<S> { 233 inner: SyncWrapper<S> 234 } 235 #[cfg(feature = "futures")] 236 impl <S: futures_core::Stream> SyncStream<S> { new(inner: S) -> Self237 pub fn new(inner: S) -> Self { 238 Self { inner: SyncWrapper::new(inner) } 239 } into_inner(self) -> S240 pub fn into_inner(self) -> S { 241 self.inner.into_inner() 242 } 243 } 244 #[cfg(feature = "futures")] 245 impl <S: futures_core::Stream> futures_core::Stream for SyncStream<S> { 246 type Item = S::Item; poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>>247 fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> { 248 let inner = unsafe { self.map_unchecked_mut(|x| x.inner.get_mut()) }; 249 inner.poll_next(cx) 250 } 251 } 252 253