]> git.lizzy.rs Git - rust.git/blob - src/test/ui/cast/cast-rfc0401-vtable-kinds.rs
Rollup merge of #97502 - onlineSoftwareDevOK:rustdocTests, r=GuillaumeGomez
[rust.git] / src / test / ui / cast / cast-rfc0401-vtable-kinds.rs
1 // run-pass
2 // Check that you can cast between different pointers to trait objects
3 // whose vtable have the same kind (both lengths, or both trait pointers).
4
5 #![feature(unsized_tuple_coercion)]
6
7 trait Foo<T> {
8     fn foo(&self, _: T) -> u32 { 42 }
9 }
10
11 trait Bar {
12     fn bar(&self) { println!("Bar!"); }
13 }
14
15 impl<T> Foo<T> for () {}
16 impl Foo<u32> for u32 { fn foo(&self, _: u32) -> u32 { self+43 } }
17 impl Bar for () {}
18
19 unsafe fn round_trip_and_call<'a>(t: *const (dyn Foo<u32>+'a)) -> u32 {
20     let foo_e : *const dyn Foo<u16> = t as *const _;
21     let r_1 = foo_e as *mut dyn Foo<u32>;
22
23     (&*r_1).foo(0)
24 }
25
26 #[repr(C)]
27 struct FooS<T:?Sized>(T);
28 #[repr(C)]
29 struct BarS<T:?Sized>(T);
30
31 fn foo_to_bar<T:?Sized>(u: *const FooS<T>) -> *const BarS<T> {
32     u as *const BarS<T>
33 }
34
35 fn tuple_i32_to_u32<T:?Sized>(u: *const (i32, T)) -> *const (u32, T) {
36     u as *const (u32, T)
37 }
38
39
40 fn main() {
41     let x = 4u32;
42     let y : &dyn Foo<u32> = &x;
43     let fl = unsafe { round_trip_and_call(y as *const dyn Foo<u32>) };
44     assert_eq!(fl, (43+4));
45
46     let s = FooS([0,1,2]);
47     let u: &FooS<[u32]> = &s;
48     let u: *const FooS<[u32]> = u;
49     let bar_ref : *const BarS<[u32]> = foo_to_bar(u);
50     let z : &BarS<[u32]> = unsafe{&*bar_ref};
51     assert_eq!(&z.0, &[0,1,2]);
52
53     // this assumes that tuple reprs for (i32, _) and (u32, _) are
54     // the same.
55     let s = (0i32, [0, 1, 2]);
56     let u: &(i32, [u8]) = &s;
57     let u: *const (i32, [u8]) = u;
58     let u_u32 : *const (u32, [u8]) = tuple_i32_to_u32(u);
59     unsafe {
60         assert_eq!(&(*u_u32).1, &[0, 1, 2]);
61     }
62 }