]> git.lizzy.rs Git - rust.git/blob - src/tools/miri/tests/pass/cast-rfc0401-vtable-kinds.rs
Auto merge of #104915 - weihanglo:update-cargo, r=ehuss
[rust.git] / src / tools / miri / tests / pass / cast-rfc0401-vtable-kinds.rs
1 // Check that you can cast between different pointers to trait objects
2 // whose vtable have the same kind (both lengths, or both trait pointers).
3
4 trait Foo<T> {
5     fn foo(&self, _: T) -> u32 {
6         42
7     }
8 }
9
10 trait Bar {
11     fn bar(&self) {
12         println!("Bar!");
13     }
14 }
15
16 impl<T> Foo<T> for () {}
17 impl Foo<u32> for u32 {
18     fn foo(&self, _: u32) -> u32 {
19         self + 43
20     }
21 }
22 impl Bar for () {}
23
24 unsafe fn round_trip_and_call<'a>(t: *const (dyn Foo<u32> + 'a)) -> u32 {
25     let foo_e: *const dyn Foo<u16> = t as *const _;
26     let r_1 = foo_e as *mut dyn Foo<u32>;
27
28     (&*r_1).foo(0)
29 }
30
31 #[repr(C)]
32 struct FooS<T: ?Sized>(T);
33 #[repr(C)]
34 struct BarS<T: ?Sized>(T);
35
36 fn foo_to_bar<T: ?Sized>(u: *const FooS<T>) -> *const BarS<T> {
37     u as *const BarS<T>
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     // If validation fails here, that's likely because an immutable suspension is recovered mutably.
53 }