make-send-sync 0.1.0

Unsafely make any type Send and Sync
Documentation
//! [![crates.io](https://img.shields.io/crates/v/make-send-sync.svg)](https://crates.io/crates/make-send-sync)
//! [![docs.rs](https://img.shields.io/docsrs/make-send-sync.svg)](https://docs.rs/make-send-sync)
//! [![license](https://img.shields.io/crates/l/make-send-sync.svg)](https://unlicense.org/)
//! [![repository](https://img.shields.io/badge/repo-codeberg.org-blue.svg)](https://codeberg.org/Aseminaunz/make-send-sync)
//! [![no-std](https://img.shields.io/badge/no--std-compatible-green.svg)](https://docs.rs/make-send-sync)
//!
//! Wrapper types to unsafely make any type [`Send`] and/or [`Sync`].
//!
//! ```rust
//! use ::core::{
//! 	cell::UnsafeCell,
//! 	ptr,
//! };
//! use ::make_send_sync::{
//! 	UnsafeSendSync,
//! 	UnsafeSync,
//! };
//!
//! // A type that is not Send or Sync
//! let not_thread_safe: *const u8 = ptr::dangling();
//!
//! let wrapped: UnsafeSendSync<*const u8> = unsafe { UnsafeSendSync::new(not_thread_safe) };
//!
//! fn assert_send_sync<T: Send + Sync>(_: T) {}
//!
//! // `wrapper` is Send + Sync, even though `not_thread_safe` is not.
//! assert_send_sync(wrapped);
//!
//! // Look! SyncUnsafeCell on stable!
//! static MY_CELL: UnsafeSync<UnsafeCell<u8>> = unsafe { UnsafeSync::new(UnsafeCell::new(0)) };
//! ```
#![no_std]

use ::core::{
	mem::transmute,
	ops::{
		Deref,
		DerefMut,
	},
};
use raw_transmute::raw_transmute;

macro_rules! create_wrapper {
	($name:ident: $($trait:path),+) => {
		#[doc = concat!("A wrapper that unsafely makes `T` " $(, "[`", stringify!($trait), "`]", )" + "+ " without requiring it for `T`.")]
		///
		/// Construction of this type is unsafe, as the caller must ensure that every use of the resulting value is indeed thread-safe. Do not expose instances of this type to safe code!
		///
		/// This is a `#[repr(transparent)]` wrapper around `T`, so it has the same memory layout as `T`.
		#[doc = concat!("Transmuting between this type and `T` is valid, but you must uphold the safety requirements for [`", stringify!($name), "::new`].")]
		#[repr(transparent)]
		#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
		pub struct $name<T: ?Sized>(T);

		$(
			// SAFETY: Construction requires ensuring that every use of the resulting value is thread-safe.
			/// The wrapper forces the unsafe implementation for `T`.
			unsafe impl<T: ?Sized> $trait for $name<T> {}
		)+

		impl<T> $name<T> {
			#[doc = concat!("Creates a new [`", stringify!($name), "<T>`] wrapping the given value.")]
			///
			/// # Safety
			///
			#[doc = concat!("Creating [`", stringify!($name), "<T>`] requires unsafe for construction only.")]
			/// The caller must ensure that every use of the resulting value is thread-safe; later uses are
			/// not marked unsafe. Do not expose instances of this type to safe code!
			#[must_use = "this is a zero-cost wrapper."]
			#[inline(always)]
			pub const unsafe fn new(value: T) -> Self {
				Self(value)
			}

			#[doc = concat!("A safe alternative to construct [`", stringify!($name), "<T>`] when `T` already implements the required traits.")]
			#[must_use = "this is a zero-cost wrapper."]
			#[inline(always)]
			pub const fn safe_new(value: T) -> Self where $(T: $trait),+ {
				// SAFETY: `T` already implements the required traits, so it's safe to wrap it.
				unsafe { Self::new(value) }
			}

			#[doc = concat!("Consumes the [`", stringify!($name), "<T>`] and returns the inner value.")]
			#[must_use = "unwrapping is pure. Did you mean to `drop` the wrapper instead?"]
			#[inline(always)]
			pub const fn into_inner(this: Self) -> T {
				// SAFETY: wrapper is repr(transparent)
				unsafe { raw_transmute::<Self, T>(this) }
			}
		}

		impl<T: ?Sized> $name<T> {
			#[doc = concat!("Returns a reference to the inner value of the [`", stringify!($name), "<T>`].")]
			///
			/// This is a `const` alternative to dereferencing the wrapper.
			#[must_use = "dereferencing is pure."]
			#[inline(always)]
			pub const fn inner_ref(this: &Self) -> &T {
				&this.0
			}

			#[doc = concat!("Returns a mutable reference to the inner value of the [`", stringify!($name), "<T>`].")]
			///
			/// This is a `const` alternative to dereferencing the wrapper.
			#[must_use = "dereferencing is pure."]
			#[inline(always)]
			pub const fn inner_mut(this: &mut Self) -> &mut T {
				&mut this.0
			}

			#[doc = concat!("Maps `&T` to [`&", stringify!($name), "<T>`](", stringify!($name), ").")]
			///
			/// This is useful if you receive a reference to a value that you know will be used in a thread-safe manner.
			///
			/// # Safety
			///
			#[doc = concat!("See [`", stringify!($name), "<T>::new`].")]
			#[must_use = "creating references is pure."]
			#[inline(always)]
			pub const unsafe fn from_ref(value: &T) -> &Self {
				// SAFETY: wrapper is repr(transparent)
				unsafe { transmute::<&T, &Self>(value) }
			}

			#[doc = concat!("A safe alternative to [`", stringify!($name), "<T>::from_ref`] when `T` already implements the required traits.")]
			#[must_use = "creating references is pure."]
			#[inline(always)]
			pub const fn safe_from_ref(value: &T) -> &Self where $(T: $trait),+ {
				// SAFETY: `T` already implements the required traits, so it's safe to wrap it.
				unsafe { Self::from_ref(value) }
			}

			#[doc = concat!("Maps `&mut T` to [`&mut ", stringify!($name), "<T>`](", stringify!($name), ").")]
			///
			/// This is useful if you receive a mutable reference to a value that you know will be used in a thread-safe manner.
			///
			/// # Safety
			///
			#[doc = concat!("See [`", stringify!($name), "<T>::new`].")]
			#[must_use = "creating references is pure."]
			#[inline(always)]
			pub const unsafe fn from_mut(value: &mut T) -> &mut Self {
				// SAFETY: wrapper is repr(transparent)
				unsafe { transmute::<&mut T, &mut Self>(value) }
			}

			#[doc = concat!("A safe alternative to [`", stringify!($name), "<T>::from_mut`] when `T` already implements the required traits.")]
			#[must_use = "creating references is pure."]
			#[inline(always)]
			pub const fn safe_from_mut(value: &mut T) -> &mut Self where $(T: $trait),+ {
				// SAFETY: `T` already implements the required traits, so it's safe to wrap it.
				unsafe { Self::from_mut(value) }
			}
		}

		impl<T: ?Sized> Deref for $name<T> {
			type Target = T;

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

		impl<T: ?Sized> DerefMut for $name<T> {
			#[inline(always)]
			fn deref_mut(&mut self) -> &mut Self::Target {
				Self::inner_mut(self)
			}
		}
	};
}

create_wrapper! { UnsafeSend: Send }
create_wrapper! { UnsafeSync: Sync }
create_wrapper! { UnsafeSendSync: Send, Sync }