1 use core::fmt; 2 3 /// A helper types that is `Send` if `T` is `Sync`. 4 /// 5 /// This structure is a newtype wrapper around the `T` type parameter. What 6 /// makes this a utility is the fact that it contains an `unsafe impl Sync` 7 /// implementation for the type when `T` is `Send`. This is then coupled with 8 /// the fact that there is no ability to access a shared reference, `&T`, from 9 /// this type. Instead all access is done through `&mut T`. 10 /// 11 /// This means that accessing the `T` in this data structure always requires 12 /// exclusive `&mut self` access. This provides the trivial guarantee that this 13 /// type is safe to share across threads because if you do so then you're just 14 /// not able to do anything with it. 15 #[derive(Default /* Do not derive traits with &self here, that's not sound */)] 16 #[repr(transparent)] 17 pub struct AlwaysMut<T>(T); 18 19 // SAFETY: this is the purpose for existence of this type, meaning that if `T` 20 // is `Send` then this type is `Sync` because it statically disallows shared 21 // access to `T`. 22 unsafe impl<T: Send> Sync for AlwaysMut<T> {} 23 24 impl<T> AlwaysMut<T> { 25 /// Creates a new [`AlwaysMut`] with the provided value. 26 pub fn new(value: T) -> AlwaysMut<T> { 27 AlwaysMut(value) 28 } 29 30 /// Return a mutable reference to the underlying data in this [`AlwaysMut`] 31 pub fn get_mut(&mut self) -> &mut T { 32 &mut self.0 33 } 34 35 /// Consume this [`AlwaysMut`], returning the underlying data. 36 #[cfg(feature = "async")] 37 pub fn into_inner(self) -> T { 38 self.0 39 } 40 } 41 42 impl<T> From<T> for AlwaysMut<T> { 43 fn from(val: T) -> AlwaysMut<T> { 44 AlwaysMut::new(val) 45 } 46 } 47 48 impl<T> fmt::Debug for AlwaysMut<T> { 49 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 50 f.debug_struct("AlwaysMut").finish_non_exhaustive() 51 } 52 } 53