On Wed Sep 2, 2026 at 1:50 AM JST, Gary Guo wrote:
<...>
> +/// Type that is layout-compatible with a primitive representation.
> +///
> +/// # Safety
> +///
> +/// - `Self` must have the same size and alignment as [`Self::Repr`].
> +/// - `Self` can be [transmutable] to [`Self::Repr`].
> +/// - Neither `Self` nor [`Self::Repr`] contains interior mutability.
> +///
> +/// The above basically says that `&Self` can be transmuted to `&Self::Repr`.
> +///
> +/// [transmutable]: core::mem::transmute
> +pub unsafe trait AsRepr: Sized {
> +    /// Primitive representation of this type.
> +    type Repr;
> +
> +    /// Convert from `&Self` to [`&Self::Repr`](AsRepr::Repr).
> +    #[inline(always)]
> +    fn as_repr(this: &Self) -> &Self::Repr {
> +        // SAFETY: Per safety requirement of the trait.
> +        unsafe { core::mem::transmute(this) }
> +    }
> +
> +    /// Convert from `Self` to [`Self::Repr`].
> +    #[inline(always)]
> +    fn into_repr(this: Self) -> Self::Repr {
> +        // SAFETY: Per safety requirement of the trait.
> +        unsafe { transmute(this) }
> +    }
> +
> +    /// Convert from [`Self::Repr`] to `Self`.
> +    ///
> +    /// # Safety
> +    ///
> +    /// `repr` must be a valid bit pattern of `Self` and satisfy 
> type-specific invariants of it.
> +    ///
> +    /// Alternatively, if `repr` is previously obtained using 
> [`Self::into_repr`], and each
> +    /// `from_repr_unchecked` should corresponds to a unique `into_repr` 
> call, then it is safe to

nit: s/corresponds/correspond

> +    /// call as well (this means that we're undoing a `into_repr` call 
> getting the exact bytes
> +    /// back).
> +    ///
> +    /// This method makes no guarantee if a `into_repr` corresponds to 
> multiple
> +    /// `from_repr_unchecked` (i.e. copies are made), to allow for cases 
> where `Repr` is a pointer

This part doesn't parse for me; maybe it is worth rephrasing?

Something like "No guarantee is made if the result of a `into_repr` is
passed to multiple `from_repr_unchecked`" reads a bit better IMHO.

<...>
> +// SAFETY: `*mut T` has the same size and alignment with `*const c_void`, 
> and thus `*mut T` is
> +// transmutable to `*const c_void`. Neither types contain interior 
> mutability.
> +unsafe impl<T> AsRepr for *mut T {
> +    type Repr = *const c_void;
> +}
> +
> +// SAFETY: `*mut T` is transmutable from `*const c_void`.
> +unsafe impl<T> AsReprMut for *mut T {}
> +
> +// SAFETY: `*const T` has the same size and alignment with `*const c_void`, 
> and is transmutable to
> +// `*const c_void`. Neither types contain interior mutability.
> +unsafe impl<T> AsRepr for *const T {
> +    type Repr = *const c_void;
> +}
> +
> +// SAFETY: `*const T` is transmutable from `*const c_void`.
> +unsafe impl<T> AsReprMut for *const T {}

These pointer impls have no user in the series, should we wait until we
have one to add them?

In any case,

Reviewed-by: Alexandre Courbot <[email protected]>

Reply via email to