Skip to content

Commit

Permalink
Add transmute_ref! macro
Browse files Browse the repository at this point in the history
This macro is like the existing `transmute!`, but it transmutes
immutable references rather than values.

Issue #159
  • Loading branch information
joshlf committed May 25, 2023
1 parent 27aea67 commit b77b4f7
Show file tree
Hide file tree
Showing 9 changed files with 1,066 additions and 16 deletions.
128 changes: 128 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1463,6 +1463,98 @@ macro_rules! transmute {
}}
}

/// A type whose size is equal to `mem::align_of::<T>()`.
///
/// This type is used internally in `transmute_ref!`, and so needs to be
/// exported. It is not intended for direct use by users of zerocopy, and so is
/// `#[doc(hidden)]`.
#[doc(hidden)]
#[allow(missing_debug_implementations)]
#[repr(C)]
pub struct SizeIsAlign<T> {
// This field ensures that:
// - The size is always at least 1 (the minimum possible alignment).
// - If the alignment is greater than 1, Rust has to round up to the next
// multiple of it in order to make sure that `SizeIsAlign`'s size is a
// multiple of that alignment. Without this field, its size could be 0,
// which is a valid multiple of any alignment.
_u: u8,
_a: [T; 0],
}

impl<T> SizeIsAlign<T> {
#[doc(hidden)]
pub fn new(_t: T) -> SizeIsAlign<T> {
SizeIsAlign { _u: 0, _a: [] }
}

#[doc(hidden)]
pub fn into_t(self) -> T {
unreachable!()
}
}

/// Safely transmutes a reference value of one type to a reference of another
/// type of the same size and alignment.
///
/// The expression `$e` must have a concrete type, `&T`, where `T: Sized +
/// AsBytes`. The `transmute_ref!` expression must also have a concrete type,
/// `&U` (`U` is inferred from the calling context), where `U: Sized +
/// FromBytes`.
///
/// The lifetime of the input type, `&T`, must be the same as or outlive the
/// lifetime of the output type, `&U`.
#[macro_export]
macro_rules! transmute_ref {
($e:expr) => {{
// NOTE: This must be a macro (rather than a function with trait bounds)
// because there's no way, in a generic context, to enforce that two
// types have the same size or alignment. `core::mem::transmute` uses
// compiler magic to enforce size equality so long as the types are
// concrete. We use `SizeIsAlign` to create a type whose size is equal
// to the alignment of another type so that we can use `transmute` to
// check alignment as well.

let e = $e;
#[allow(unused)]
if false {
if false {
// This branch, though never taken, ensures that the type of `e`
// is `&T` where `T: 't + Sized + AsBytes`, that the type of
// this macro expression is `&U` where `U: 'u + Sized +
// FromBytes`, and that `'t` outlives `'u`.
const fn transmute<'u, 't: 'u, T: 't + Sized + $crate::AsBytes, U: 'u + Sized + $crate::FromBytes>(_t: &'t T) -> &'u U {
unreachable!()
}
transmute(e)
} else {
// This branch, though never taken, ensures that the alignment
// of `T` is equal to the alignment of `U`.
let target = unreachable!();
e = &target;

// SAFETY: This code is never executed.
let ret: $crate::SizeIsAlign<_> = unsafe { $crate::__real_transmute($crate::SizeIsAlign::new(target)) };
&ret.into_t()
}
} else {
// SAFETY: `core::mem::transmute` ensures that the type of `e` and
// the type of this macro invocation expression have the same size.
// We know this transmute is safe thanks to the `AsBytes` and
// `FromBytes` bounds enforced by the `false` branch.
//
// We use `$crate::__real_transmute` because we know it will always
// be available for crates which are using the 2015 edition of Rust.
// By contrast, if we were to use `std::mem::transmute`, this macro
// would not work for such crates in `no_std` contexts, and if we
// were to use `core::mem::transmute`, this macro would not work in
// `std` contexts in which `core` was not manually imported. This is
// not a problem for 2018 edition crates.
unsafe { $crate::__real_transmute(e) }
}
}}
}

/// A length- and alignment-checked reference to a byte slice which can safely
/// be reinterpreted as another type.
///
Expand Down Expand Up @@ -3195,6 +3287,42 @@ mod tests {
assert_eq!(X, ARRAY_OF_ARRAYS);
}

#[test]
fn test_size_is_align() {
macro_rules! test {
($ty:ty) => {
assert_eq!(mem::size_of::<SizeIsAlign<$ty>>(), mem::align_of::<$ty>());
};
}

test!(());
test!(u8);
test!(AU64);
test!([AU64; 2]);
}

#[test]
fn test_transmute_ref() {
// Test that memory is transmuted as expected.
let array_of_u8s = [0u8, 1, 2, 3, 4, 5, 6, 7];
let array_of_arrays = [[0, 1], [2, 3], [4, 5], [6, 7]];
let x: &[[u8; 2]; 4] = transmute_ref!(&array_of_u8s);
assert_eq!(*x, array_of_arrays);
let x: &[u8; 8] = transmute_ref!(&array_of_arrays);
assert_eq!(*x, array_of_u8s);

// Test that `transmute_ref!` is legal in a const context.
const ARRAY_OF_U8S: [u8; 8] = [0u8, 1, 2, 3, 4, 5, 6, 7];
const ARRAY_OF_ARRAYS: [[u8; 2]; 4] = [[0, 1], [2, 3], [4, 5], [6, 7]];
const X: &'static [[u8; 2]; 4] = transmute_ref!(&ARRAY_OF_U8S);
assert_eq!(*X, ARRAY_OF_ARRAYS);

// Test that it's legal to transmute a reference while shrinking the
// lifetime (note that `X` has the lifetime `'static`).
let x: &[u8; 8] = transmute_ref!(X);
assert_eq!(*x, ARRAY_OF_U8S);
}

#[test]
fn test_address() {
// Test that the `Deref` and `DerefMut` implementations return a
Expand Down
1 change: 1 addition & 0 deletions tests/ui-msrv/transmute-illegal-lifetime.rs
9 changes: 9 additions & 0 deletions tests/ui-msrv/transmute-illegal-lifetime.stderr
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
error[E0597]: `x` does not live long enough
--> tests/ui-msrv/transmute-illegal-lifetime.rs:12:52
|
12 | let _: &'static u64 = zerocopy::transmute_ref!(&x);
| ------------ ^^ borrowed value does not live long enough
| |
| type annotation requires that `x` is borrowed for `'static`
13 | }
| - `x` dropped here while still borrowed
Loading

0 comments on commit b77b4f7

Please sign in to comment.