2016-09-22 06:00:43 -05:00
|
|
|
// Check that you can cast between different pointers to trait objects
|
|
|
|
// whose vtable have the same kind (both lengths, or both trait pointers).
|
|
|
|
|
|
|
|
trait Foo<T> {
|
2022-06-20 17:30:34 -05:00
|
|
|
fn foo(&self, _: T) -> u32 {
|
|
|
|
42
|
|
|
|
}
|
2016-09-22 06:00:43 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
trait Bar {
|
2022-06-20 17:30:34 -05:00
|
|
|
fn bar(&self) {
|
|
|
|
println!("Bar!");
|
|
|
|
}
|
2016-09-22 06:00:43 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
impl<T> Foo<T> for () {}
|
2022-06-20 17:30:34 -05:00
|
|
|
impl Foo<u32> for u32 {
|
|
|
|
fn foo(&self, _: u32) -> u32 {
|
|
|
|
self + 43
|
|
|
|
}
|
|
|
|
}
|
2016-09-22 06:00:43 -05:00
|
|
|
impl Bar for () {}
|
|
|
|
|
2022-06-20 17:30:34 -05:00
|
|
|
unsafe fn round_trip_and_call<'a>(t: *const (dyn Foo<u32> + 'a)) -> u32 {
|
|
|
|
let foo_e: *const dyn Foo<u16> = t as *const _;
|
2019-05-30 03:58:30 -05:00
|
|
|
let r_1 = foo_e as *mut dyn Foo<u32>;
|
2016-09-22 06:00:43 -05:00
|
|
|
|
|
|
|
(&*r_1).foo(0)
|
|
|
|
}
|
|
|
|
|
|
|
|
#[repr(C)]
|
2022-06-20 17:30:34 -05:00
|
|
|
struct FooS<T: ?Sized>(T);
|
2016-09-22 06:00:43 -05:00
|
|
|
#[repr(C)]
|
2022-06-20 17:30:34 -05:00
|
|
|
struct BarS<T: ?Sized>(T);
|
2016-09-22 06:00:43 -05:00
|
|
|
|
2022-06-20 17:30:34 -05:00
|
|
|
fn foo_to_bar<T: ?Sized>(u: *const FooS<T>) -> *const BarS<T> {
|
2016-09-22 06:00:43 -05:00
|
|
|
u as *const BarS<T>
|
|
|
|
}
|
|
|
|
|
|
|
|
fn main() {
|
|
|
|
let x = 4u32;
|
2022-06-20 17:30:34 -05:00
|
|
|
let y: &dyn Foo<u32> = &x;
|
2019-05-30 03:58:30 -05:00
|
|
|
let fl = unsafe { round_trip_and_call(y as *const dyn Foo<u32>) };
|
2022-06-20 17:30:34 -05:00
|
|
|
assert_eq!(fl, (43 + 4));
|
2016-09-22 06:00:43 -05:00
|
|
|
|
2022-06-20 17:30:34 -05:00
|
|
|
let s = FooS([0, 1, 2]);
|
2016-09-22 06:00:43 -05:00
|
|
|
let u: &FooS<[u32]> = &s;
|
|
|
|
let u: *const FooS<[u32]> = u;
|
2022-06-20 17:30:34 -05:00
|
|
|
let bar_ref: *const BarS<[u32]> = foo_to_bar(u);
|
|
|
|
let z: &BarS<[u32]> = unsafe { &*bar_ref };
|
|
|
|
assert_eq!(&z.0, &[0, 1, 2]);
|
2017-07-25 00:42:05 -05:00
|
|
|
// If validation fails here, that's likely because an immutable suspension is recovered mutably.
|
2016-09-22 06:00:43 -05:00
|
|
|
}
|