]> git.lizzy.rs Git - rust.git/blob - src/test/run-pass/cleanup-rvalue-for-scope.rs
Auto merge of #28816 - petrochenkov:unistruct, r=nrc
[rust.git] / src / test / run-pass / cleanup-rvalue-for-scope.rs
1 // Copyright 2014 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 // Test that the lifetime of rvalues in for loops is extended
12 // to the for loop itself.
13
14 use std::ops::Drop;
15
16 static mut FLAGS: u64 = 0;
17
18 struct Box<T> { f: T }
19 struct AddFlags { bits: u64 }
20
21 fn AddFlags(bits: u64) -> AddFlags {
22     AddFlags { bits: bits }
23 }
24
25 fn arg(exp: u64, _x: &AddFlags) {
26     check_flags(exp);
27 }
28
29 fn pass<T>(v: T) -> T {
30     v
31 }
32
33 fn check_flags(exp: u64) {
34     unsafe {
35         let x = FLAGS;
36         FLAGS = 0;
37         println!("flags {}, expected {}", x, exp);
38         assert_eq!(x, exp);
39     }
40 }
41
42 impl AddFlags {
43     fn check_flags(&self, exp: u64) -> &AddFlags {
44         check_flags(exp);
45         self
46     }
47
48     fn bits(&self) -> u64 {
49         self.bits
50     }
51 }
52
53 impl Drop for AddFlags {
54     fn drop(&mut self) {
55         unsafe {
56             FLAGS = FLAGS + self.bits;
57         }
58     }
59 }
60
61 pub fn main() {
62     // The array containing [AddFlags] should not be dropped until
63     // after the for loop:
64     for x in &[AddFlags(1)] {
65         check_flags(0);
66     }
67     check_flags(1);
68 }