1 #![warn(clippy::transmute_ptr_to_ptr)]
3 // Make sure we can modify lifetimes, which is one of the recommended uses
6 // Make sure we can do static lifetime transmutes
7 unsafe fn transmute_lifetime_to_static<'a, T>(t: &'a T) -> &'static T {
8 std::mem::transmute::<&'a T, &'static T>(t)
11 // Make sure we can do non-static lifetime transmutes
12 unsafe fn transmute_lifetime<'a, 'b, T>(t: &'a T, u: &'b T) -> &'b T {
13 std::mem::transmute::<&'a T, &'b T>(t)
16 struct LifetimeParam<'a> {
20 struct GenericParam<T> {
24 fn transmute_ptr_to_ptr() {
25 let ptr = &1u32 as *const u32;
26 let mut_ptr = &mut 1u32 as *mut u32;
28 // pointer-to-pointer transmutes; bad
29 let _: *const f32 = std::mem::transmute(ptr);
30 let _: *mut f32 = std::mem::transmute(mut_ptr);
31 // ref-ref transmutes; bad
32 let _: &f32 = std::mem::transmute(&1u32);
33 let _: &f64 = std::mem::transmute(&1f32);
34 // ^ this test is here because both f32 and f64 are the same TypeVariant, but they are not
36 let _: &mut f32 = std::mem::transmute(&mut 1u32);
37 let _: &GenericParam<f32> = std::mem::transmute(&GenericParam { t: 1u32 });
40 // these are recommendations for solving the above; if these lint we need to update
42 let _ = ptr as *const f32;
43 let _ = mut_ptr as *mut f32;
44 let _ = unsafe { &*(&1u32 as *const u32 as *const f32) };
45 let _ = unsafe { &mut *(&mut 1u32 as *mut u32 as *mut f32) };
47 // transmute internal lifetimes, should not lint
48 let s = "hello world".to_owned();
49 let lp = LifetimeParam { s: &s };
50 let _: &LifetimeParam<'static> = unsafe { std::mem::transmute(&lp) };
51 let _: &GenericParam<&LifetimeParam<'static>> = unsafe { std::mem::transmute(&GenericParam { t: &lp }) };