]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/tests/ui/cast_slice_different_sizes.rs
Rollup merge of #102412 - joboet:dont_panic, r=m-ou-se
[rust.git] / src / tools / clippy / tests / ui / cast_slice_different_sizes.rs
1 #![allow(clippy::let_unit_value)]
2
3 fn main() {
4     let x: [i32; 3] = [1_i32, 2, 3];
5     let r_x = &x;
6     // Check casting through multiple bindings
7     // Because it's separate, it does not check the cast back to something of the same size
8     let a = r_x as *const [i32];
9     let b = a as *const [u8];
10     let c = b as *const [u32];
11
12     // loses data
13     let loss = r_x as *const [i32] as *const [u8];
14
15     // Cast back to same size but different type loses no data, just type conversion
16     // This is weird code but there's no reason for this lint specifically to fire *twice* on it
17     let restore = r_x as *const [i32] as *const [u8] as *const [u32];
18
19     // Check casting through blocks is detected
20     let loss_block_1 = { r_x as *const [i32] } as *const [u8];
21     let loss_block_2 = {
22         let _ = ();
23         r_x as *const [i32]
24     } as *const [u8];
25
26     // Check that resores of the same size are detected through blocks
27     let restore_block_1 = { r_x as *const [i32] } as *const [u8] as *const [u32];
28     let restore_block_2 = { ({ r_x as *const [i32] }) as *const [u8] } as *const [u32];
29     let restore_block_3 = {
30         let _ = ();
31         ({
32             let _ = ();
33             r_x as *const [i32]
34         }) as *const [u8]
35     } as *const [u32];
36
37     // Check that the result of a long chain of casts is detected
38     let long_chain_loss = r_x as *const [i32] as *const [u32] as *const [u16] as *const [i8] as *const [u8];
39     let long_chain_restore =
40         r_x as *const [i32] as *const [u32] as *const [u16] as *const [i8] as *const [u8] as *const [u32];
41 }
42
43 // foo and foo2 should not fire, they're the same size
44 fn foo(x: *mut [u8]) -> *mut [u8] {
45     x as *mut [u8]
46 }
47
48 fn foo2(x: *mut [u8]) -> *mut [u8] {
49     x as *mut _
50 }
51
52 // Test that casts as part of function returns work
53 fn bar(x: *mut [u16]) -> *mut [u8] {
54     x as *mut [u8]
55 }
56
57 fn uwu(x: *mut [u16]) -> *mut [u8] {
58     x as *mut _
59 }
60
61 fn bar2(x: *mut [u16]) -> *mut [u8] {
62     x as _
63 }
64
65 // constify
66 fn bar3(x: *mut [u16]) -> *const [u8] {
67     x as _
68 }
69
70 // unconstify
71 fn bar4(x: *const [u16]) -> *mut [u8] {
72     x as _
73 }
74
75 // function returns plus blocks
76 fn blocks(x: *mut [u16]) -> *mut [u8] {
77     ({ x }) as _
78 }
79
80 fn more_blocks(x: *mut [u16]) -> *mut [u8] {
81     { ({ x }) as _ }
82 }