diff --git a/tests/ui/transmute.rs b/tests/ui/transmute.rs index ff389ad20a8..17740d50afe 100644 --- a/tests/ui/transmute.rs +++ b/tests/ui/transmute.rs @@ -140,6 +140,21 @@ fn bytes_to_str(b: &[u8], mb: &mut [u8]) { let _: &mut str = unsafe { std::mem::transmute(mb) }; } +// Make sure we can modify lifetimes, which is one of the recommended uses +// of transmute + +// Make sure we can do static lifetime transmutes +#[warn(transmute_ptr_to_ptr)] +unsafe fn transmute_lifetime_to_static<'a, T>(t: &'a T) -> &'static T { + std::mem::transmute::<&'a T, &'static T>(t) +} + +// Make sure we can do non-static lifetime transmutes +#[warn(transmute_ptr_to_ptr)] +unsafe fn transmute_lifetime<'a, 'b, T>(t: &'a T, u: &'b T) -> &'b T { + std::mem::transmute::<&'a T, &'b T>(t) +} + #[warn(transmute_ptr_to_ptr)] fn transmute_ptr_to_ptr() { let ptr = &1u32 as *const u32; @@ -159,10 +174,6 @@ fn transmute_ptr_to_ptr() { let _ = mut_ptr as *mut f32; let _ = unsafe { &*(&1u32 as *const u32 as *const f32) }; let _ = unsafe { &mut *(&mut 1u32 as *mut u32 as *mut f32) }; - // This is just modifying the lifetime, and is one of the recommended uses - // of transmute - let n = 1u32; - let _ = unsafe { std::mem::transmute::<&'_ u32, &'static u32>(&n) }; } fn main() { } diff --git a/tests/ui/transmute.stderr b/tests/ui/transmute.stderr index a343a8a9cb5..3685e3ea2bf 100644 --- a/tests/ui/transmute.stderr +++ b/tests/ui/transmute.stderr @@ -205,29 +205,29 @@ error: transmute from a `&mut [u8]` to a `&mut str` | ^^^^^^^^^^^^^^^^^^^^^^^ help: consider using: `std::str::from_utf8_mut(mb).unwrap()` error: transmute from a pointer to a pointer - --> $DIR/transmute.rs:149:29 + --> $DIR/transmute.rs:164:29 | -149 | let _: *const f32 = std::mem::transmute(ptr); +164 | let _: *const f32 = std::mem::transmute(ptr); | ^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `ptr as *const f32` | = note: `-D transmute-ptr-to-ptr` implied by `-D warnings` error: transmute from a pointer to a pointer - --> $DIR/transmute.rs:150:27 + --> $DIR/transmute.rs:165:27 | -150 | let _: *mut f32 = std::mem::transmute(mut_ptr); +165 | let _: *mut f32 = std::mem::transmute(mut_ptr); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `mut_ptr as *mut f32` error: transmute from a reference to a reference - --> $DIR/transmute.rs:152:23 + --> $DIR/transmute.rs:167:23 | -152 | let _: &f32 = std::mem::transmute(&1u32); +167 | let _: &f32 = std::mem::transmute(&1u32); | ^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `&*(&1u32 as *const u32 as *const f32)` error: transmute from a reference to a reference - --> $DIR/transmute.rs:153:27 + --> $DIR/transmute.rs:168:27 | -153 | let _: &mut f32 = std::mem::transmute(&mut 1u32); +168 | let _: &mut f32 = std::mem::transmute(&mut 1u32); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `&mut *(&mut 1u32 as *mut u32 as *mut f32)` error: aborting due to 36 previous errors