rust/tests/ui/traits/dyn-drop-principal.rs

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

69 lines
1.4 KiB
Rust
Raw Normal View History

2023-08-08 19:31:26 -05:00
//@ run-pass
//@ check-run-results
2024-07-10 12:00:36 -05:00
use std::{alloc::Layout, any::Any};
2023-08-08 19:31:26 -05:00
const fn yeet_principal(x: Box<dyn Any + Send>) -> Box<dyn Send> {
x
}
trait Bar: Send + Sync {}
impl<T: Send + Sync> Bar for T {}
const fn yeet_principal_2(x: Box<dyn Bar>) -> Box<dyn Send> {
x
}
struct CallMe<F: FnOnce()>(Option<F>);
impl<F: FnOnce()> CallMe<F> {
fn new(f: F) -> Self {
CallMe(Some(f))
}
}
impl<F: FnOnce()> Drop for CallMe<F> {
fn drop(&mut self) {
(self.0.take().unwrap())();
}
}
fn goodbye() {
println!("goodbye");
}
fn main() {
let x = Box::new(CallMe::new(goodbye)) as Box<dyn Any + Send>;
2024-07-10 12:00:36 -05:00
let x_layout = Layout::for_value(&*x);
2023-08-08 19:31:26 -05:00
let y = yeet_principal(x);
2024-07-10 12:00:36 -05:00
let y_layout = Layout::for_value(&*y);
assert_eq!(x_layout, y_layout);
2023-08-08 19:31:26 -05:00
println!("before");
drop(y);
let x = Box::new(CallMe::new(goodbye)) as Box<dyn Bar>;
2024-07-10 12:00:36 -05:00
let x_layout = Layout::for_value(&*x);
2023-08-08 19:31:26 -05:00
let y = yeet_principal_2(x);
2024-07-10 12:00:36 -05:00
let y_layout = Layout::for_value(&*y);
assert_eq!(x_layout, y_layout);
2023-08-08 19:31:26 -05:00
println!("before");
drop(y);
}
// Test that upcast works in `const`
const fn yeet_principal_3(x: &(dyn Any + Send + Sync)) -> &(dyn Send + Sync) {
x
}
#[used]
pub static FOO: &(dyn Send + Sync) = yeet_principal_3(&false);
const fn yeet_principal_4(x: &dyn Bar) -> &(dyn Send + Sync) {
x
}
#[used]
pub static BAR: &(dyn Send + Sync) = yeet_principal_4(&false);