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 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348
//! Functions for safely transmuting types with a [`TransmutableInto`] parameter.
//!
//!
use core::{marker::PhantomData, mem};
use crate::ImplsPod;
#[doc(no_inline)]
pub use crate::TransmutableInto;
pub(crate) mod transmutable_into {
use super::*;
/// Marker type which guarantees that `Fro` is safely transmutable into `To`,
/// both by value and by (mutable) reference.
///
/// Related: [`transmutable`](crate::transmutable) module.
///
/// Functions for transmuting that require `align_of::<Fro>() == align_of::<To>()`
/// (eg: a function that transmutes from `Arc<Fro>` to `Arc<To>`)
/// have to contain that equality check as an assertion,
/// because `TransmutableInto`'s constructors
/// only require `align_of::<Fro>() >= align_of::<To>()`.
///
/// # Example
///
/// ```
/// use constmuck::{
/// transmutable::{TransmutableInto, transmute_into, transmute_slice},
/// infer,
/// };
///
/// use std::num::Wrapping;
///
/// // Transmuting from `&[u8]` to `&[i8]`
/// const POD: &[i8] =
/// transmute_slice(&[5u8, 25, 125, 250], TransmutableInto::pod(infer!()));
/// assert_eq!(*POD, [5, 25, 125, -6]);
///
///
///
/// ```
pub struct TransmutableInto<Fro: ?Sized, To: ?Sized> {
_private: PhantomData<(
// Makes this invariant over the lifetimes in `Fro` and `To`
// so that it's not possible to change lifetime parameters.
fn(PhantomData<Fro>) -> PhantomData<Fro>,
fn(PhantomData<To>) -> PhantomData<To>,
)>,
#[doc(hidden)]
pub _transmutable_into_proof: constmuck_internal::TransmutableProof<Fro, To>,
}
impl<Fro: ?Sized, To: ?Sized> Copy for TransmutableInto<Fro, To> {}
impl<Fro: ?Sized, To: ?Sized> Clone for TransmutableInto<Fro, To> {
fn clone(&self) -> Self {
*self
}
}
impl<Fro: ?Sized, To: ?Sized> TransmutableInto<Fro, To> {
const __NEW_UNCHECKED: Self = unsafe {
Self {
_private: PhantomData,
_transmutable_into_proof: constmuck_internal::TransmutableProof::new_unchecked(),
}
};
/// Constructs a `TransmutableInto`
///
/// # Safety
///
/// `Fro` must be soundly transmutable to `To`.
///
/// References (`&` and `&mut`) to `Fro` must be soundly transmutable to point to `To`.
///
/// `size_of::<Fro>()` must be equal to `size_of::<To>()`.
///
/// `align_of::<Fro>()` must be greater than or equal to `align_of::<To>()`.
///
#[inline(always)]
pub const unsafe fn new_unchecked() -> Self {
Self::__NEW_UNCHECKED
}
}
impl<Fro, To> TransmutableInto<Fro, To> {
/// Constructs a `TransmutableInto`
///
/// # Panics
///
/// Panics if either:
/// - The size of `Fro` isn't the same as `To`.
/// - The alignment of `Fro` is less than `To`
/// (`Foo` is allowed to be more aligned than `To`).
///
/// # Example
///
/// ```rust
/// use constmuck::{
/// transmutable::{TransmutableInto, transmute_into},
/// infer,
/// };
///
/// {
/// // Transmuting from `[u8; 5]` to `[i8; 5]`
/// const POD: [i8; 5] = transmute_into(
/// [0u8, 127, 128, 129, 130],
/// TransmutableInto::pod(infer!()),
/// );
///
/// assert_eq!(POD, [0, 127, -128, -127, -126]);
/// }
/// ```
#[inline(always)]
pub const fn pod(_bounds: (ImplsPod<Fro>, ImplsPod<To>)) -> Self {
if mem::size_of::<Fro>() != mem::size_of::<To>() {
#[allow(non_snake_case)]
let size_of_Fro = mem::size_of::<Fro>();
[/* size of Fro != To */][size_of_Fro]
} else if mem::align_of::<Fro>() < mem::align_of::<To>() {
#[allow(non_snake_case)]
let align_of_Fro = mem::align_of::<Fro>();
[/* alignment of Fro < To */][align_of_Fro]
} else {
Self::__NEW_UNCHECKED
}
}
/// Turns a `TransmutableInto<Fro, To>` into a
/// `TransmutableInto<[Fro; LEN], [To; LEN]>`.
///
/// # Example
///
/// ```rust
/// use constmuck::{
/// transmutable::{TransmutableInto, transmute_ref},
/// infer_tw,
/// };
///
/// #[derive(Debug, PartialEq)]
/// #[repr(transparent)]
/// pub struct Other<T>(pub T);
///
/// unsafe impl<T> constmuck::TransparentWrapper<T> for Other<T> {}
///
/// {
/// // Transmuting from `&[Other<u32>; 5]` to `&[u32; 5]`
/// const ARR: &[u32; 5] = transmute_ref(
/// &[Other(0), Other(127), Other(128), Other(129), Other(130)],
/// // `infer_tw!().into_inner.array()` allows transmuting an arrays of wrappers
/// // into an arraw of the values that are inside those wrappers.
/// infer_tw!().into_inner.array(),
/// );
///
/// assert_eq!(*ARR, [0, 127, 128, 129, 130]);
/// }
/// ```
#[inline(always)]
pub const fn array<const LEN: usize>(self) -> TransmutableInto<[Fro; LEN], [To; LEN]> {
TransmutableInto::__NEW_UNCHECKED
}
}
impl<Fro: ?Sized, To: ?Sized> TransmutableInto<Fro, To> {
/// Combines an `TransmutableInto` with another to allow
/// casting from `Fro` to `To2`.
///
/// Without this you'd have to do `Fro -> To -> To2` casts.
///
/// # Example
///
/// ```rust
/// use constmuck::{TransmutableInto, infer, infer_tw};
/// use constmuck::transmutable::{transmute_ref, transmute_slice};
///
/// use std::num::Wrapping;
///
/// const FOO: TransmutableInto<Wrapping<u8>, i8> = {
/// infer_tw!(Wrapping<u8>, u8)
/// .into_inner
/// .join(TransmutableInto::<_, i8>::pod(infer!()))
/// };
///
/// assert_eq!(transmute_ref(&Wrapping(255u8), FOO), &-1);
///
/// assert_eq!(
/// transmute_slice(&[Wrapping(255u8), Wrapping(0), Wrapping(1)], FOO),
/// &[-1, 0, 1],
/// );
///
/// ```
pub const fn join<To2: ?Sized>(
self,
_other: TransmutableInto<To, To2>,
) -> TransmutableInto<Fro, To2> {
TransmutableInto::__NEW_UNCHECKED
}
}
}
/// Transmutes `T` into `U`, given a [`TransmutableInto`].
///
/// # Example
///
/// ```
/// use constmuck::{
/// transmutable::{TransmutableInto, transmute_into},
/// infer, infer_tw,
/// };
///
/// use std::num::NonZeroU8;
///
/// {
/// // Transmuting from `[Option<NonZeroU8>; 2]` to `[u8; 2]`
/// const POD: [u8; 2] = transmute_into(
/// [None::<NonZeroU8>, NonZeroU8::new(10)],
/// TransmutableInto::pod(infer!()),
/// );
///
/// assert_eq!(POD, [0u8, 10]);
/// }
///
/// #[derive(Debug, PartialEq)]
/// #[repr(transparent)]
/// pub struct That<T>(pub T);
///
/// unsafe impl<T> constmuck::TransparentWrapper<T> for That<T> {}
///
/// {
/// // Transmuting from `[char; 4]` to `That<[char; 4]>`
/// //
/// // `infer_tw!()` constructs an `ImplsTransparentWrapper`,
/// // whose `from_inner` field allows transmuting from a value into a wrapper around it.
/// const THAT_ARRAY: That<[char; 4]> =
/// transmute_into(['A', 'E', 'I', 'O'], infer_tw!().from_inner);
/// assert_eq!(THAT_ARRAY, That(['A', 'E', 'I', 'O']));
/// }
///
/// {
/// // Transmuting from `[That<char>; 4]` to `[char; 4]`
/// //
/// // `infer_tw!().into_inner.array()` allows transmuting an arrays of wrappers
/// // into an arraw of the values that are inside those wrappers.
/// const ARRAY_THAT: [char; 4] = transmute_into(
/// [That('A'), That('E'), That('I'), That('O')],
/// infer_tw!().into_inner.array(),
/// );
/// assert_eq!(ARRAY_THAT, ['A', 'E', 'I', 'O']);
/// }
///
///
/// ```
pub const fn transmute_into<T, U>(value: T, _bounds: TransmutableInto<T, U>) -> U {
unsafe { __priv_transmute!(T, U, value) }
}
/// Transmutes `&T` into `&U`, given a [`TransmutableInto`].
///
/// # Example
///
/// ```
/// use constmuck::{
/// transmutable::{TransmutableInto, transmute_ref},
/// infer,
/// };
///
/// use std::num::NonZeroU8;
///
/// // Transmuting from `[Option<NonZeroU8>; 2]` to `[i8; 2]`
/// const X: &[i8; 2] = transmute_ref(
/// &[None::<NonZeroU8>, NonZeroU8::new(255)],
/// TransmutableInto::pod(infer!()),
/// );
///
/// assert_eq!(*X, [0i8, -1]);
///
/// ```
pub const fn transmute_ref<T, U>(value: &T, _bounds: TransmutableInto<T, U>) -> &U {
unsafe { __priv_transmute_ref!(T, U, value) }
}
/// Transmutes `&T` into `&U`, given a [`TransmutableInto`],
/// allows transmuting between `?Sized` types.
///
/// # Example
///
/// ```
/// use constmuck::{
/// transmutable::transmute_ref,
/// infer_tw,
/// };
///
/// #[derive(Debug, PartialEq)]
/// #[repr(transparent)]
/// pub struct Wrapper<T: ?Sized>(pub T);
///
/// unsafe impl<T: ?Sized> constmuck::TransparentWrapper<T> for Wrapper<T> {}
///
/// // Transmuting from `&[u8]` to `&Wrapper<[u8]>`
/// const BYTES: &Wrapper<[u8]> = transmute_ref!(
/// b"hello" as &[u8],
/// infer_tw!().from_inner,
/// );
///
/// assert_eq!(&BYTES.0, b"hello");
///
/// ```
#[doc(inline)]
pub use constmuck_internal::transmute_ref;
/// Transmutes `&[T]` into `&[U]`, given a [`TransmutableInto`].
///
/// # Example
///
/// ```
/// use constmuck::{
/// transmutable::{TransmutableInto, transmute_slice},
/// infer, infer_tw,
/// };
///
/// use std::num::Wrapping;
///
/// // Transmuting from `&[u8]` to `&[i8]`
/// const SIGNED: &[i8] = transmute_slice(&[5u8, 250u8, 255u8], TransmutableInto::pod(infer!()));
/// assert_eq!(*SIGNED, [5, -6, -1]);
///
/// // Transmuting from `&[Wrapping<u8>]` to `&[i8]`
/// //
/// // `infer_tw!()` constructs an `ImplsTransparentWrapper`,
/// // whose `into_inner` field allows transmuting from a wrapper into the value in it.
/// const UNWRAPPED: &[u8] =
/// transmute_slice(&[Wrapping(5), Wrapping(250)], infer_tw!().into_inner);
/// assert_eq!(*UNWRAPPED, [5, 250]);
///
/// // Transmuting from `&[u8]` to `&[Wrapping<u8>]`
/// //
/// // `infer_tw!()` constructs an `ImplsTransparentWrapper`,
/// // whose `from_inner` field allows transmuting from a value into a wrapper around it.
/// const WRAPPED: &[Wrapping<u8>] = transmute_slice(&[7, 78], infer_tw!().from_inner);
/// assert_eq!(*WRAPPED, [Wrapping(7), Wrapping(78)]);
///
///
/// ```
pub const fn transmute_slice<T, U>(value: &[T], _bounds: TransmutableInto<T, U>) -> &[U] {
unsafe { __priv_transmute_slice!(T, U, value) }
}