]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/tests/ui/transmute_ptr_to_ptr.rs
Rollup merge of #78769 - est31:remove_lifetimes, r=KodrAus
[rust.git] / src / tools / clippy / tests / ui / transmute_ptr_to_ptr.rs
1 #![warn(clippy::transmute_ptr_to_ptr)]
2
3 // Make sure we can modify lifetimes, which is one of the recommended uses
4 // of transmute
5
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)
9 }
10
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)
14 }
15
16 struct LifetimeParam<'a> {
17     s: &'a str,
18 }
19
20 struct GenericParam<T> {
21     t: T,
22 }
23
24 fn transmute_ptr_to_ptr() {
25     let ptr = &1u32 as *const u32;
26     let mut_ptr = &mut 1u32 as *mut u32;
27     unsafe {
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
35         // the same type
36         let _: &mut f32 = std::mem::transmute(&mut 1u32);
37         let _: &GenericParam<f32> = std::mem::transmute(&GenericParam { t: 1u32 });
38     }
39
40     // these are recommendations for solving the above; if these lint we need to update
41     // those suggestions
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) };
46
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 }) };
52 }
53
54 // dereferencing raw pointers in const contexts, should not lint as it's unstable (issue 5959)
55 const _: &() = {
56     struct ZST;
57     let zst = &ZST;
58
59     unsafe { std::mem::transmute::<&'static ZST, &'static ()>(zst) }
60 };
61
62 fn main() {}