|
| 1 | +// Copyright 2018 The Rust Project Developers. See the COPYRIGHT |
| 2 | +// file at the top-level directory of this distribution and at |
| 3 | +// http://rust-lang.org/COPYRIGHT. |
| 4 | +// |
| 5 | +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or |
| 6 | +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license |
| 7 | +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your |
| 8 | +// option. This file may not be copied, modified, or distributed |
| 9 | +// except according to those terms. |
| 10 | + |
| 11 | +// must-compile-successfully |
| 12 | +// run-pass |
| 13 | + |
| 14 | +union Transmute<T: Copy, U: Copy> { |
| 15 | + t: T, |
| 16 | + u: U, |
| 17 | +} |
| 18 | + |
| 19 | +trait Bar { |
| 20 | + fn bar(&self) -> u32; |
| 21 | +} |
| 22 | + |
| 23 | +struct Foo { |
| 24 | + foo: u32, |
| 25 | + bar: bool, |
| 26 | +} |
| 27 | + |
| 28 | +impl Bar for Foo { |
| 29 | + fn bar(&self) -> u32 { |
| 30 | + self.foo |
| 31 | + } |
| 32 | +} |
| 33 | + |
| 34 | +impl Drop for Foo { |
| 35 | + fn drop(&mut self) { |
| 36 | + assert!(!self.bar); |
| 37 | + self.bar = true; |
| 38 | + println!("dropping Foo"); |
| 39 | + } |
| 40 | +} |
| 41 | + |
| 42 | +#[derive(Copy, Clone)] |
| 43 | +struct Fat<'a>(&'a Foo, &'static VTable); |
| 44 | + |
| 45 | +struct VTable { |
| 46 | + drop: Option<for<'a> fn(&'a mut Foo)>, |
| 47 | + size: usize, |
| 48 | + align: usize, |
| 49 | + bar: for<'a> fn(&'a Foo) -> u32, |
| 50 | +} |
| 51 | + |
| 52 | +const FOO: &Bar = &Foo { foo: 128, bar: false }; |
| 53 | +const G: Fat = unsafe { Transmute { t: FOO }.u }; |
| 54 | +const F: Option<for<'a> fn(&'a mut Foo)> = G.1.drop; |
| 55 | +const H: for<'a> fn(&'a Foo) -> u32 = G.1.bar; |
| 56 | + |
| 57 | +fn main() { |
| 58 | + let mut foo = Foo { foo: 99, bar: false }; |
| 59 | + (F.unwrap())(&mut foo); |
| 60 | + std::mem::forget(foo); // already ran the drop impl |
| 61 | + assert_eq!(H(&Foo { foo: 42, bar: false }), 42); |
| 62 | +} |
0 commit comments