summaryrefslogtreecommitdiffstats
path: root/tests/ui/generator/smoke-resume-args.rs
blob: fa9271c538f532ae1c5eced303bebc0313dece83 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
// run-pass

// revisions: default nomiropt
//[nomiropt]compile-flags: -Z mir-opt-level=0

#![feature(generators, generator_trait)]

use std::fmt::Debug;
use std::marker::Unpin;
use std::ops::{
    Generator,
    GeneratorState::{self, *},
};
use std::pin::Pin;
use std::sync::atomic::{AtomicUsize, Ordering};

fn drain<G: Generator<R, Yield = Y> + Unpin, R, Y>(
    gen: &mut G,
    inout: Vec<(R, GeneratorState<Y, G::Return>)>,
) where
    Y: Debug + PartialEq,
    G::Return: Debug + PartialEq,
{
    let mut gen = Pin::new(gen);

    for (input, out) in inout {
        assert_eq!(gen.as_mut().resume(input), out);
    }
}

static DROPS: AtomicUsize = AtomicUsize::new(0);

#[derive(Debug, PartialEq)]
struct DropMe;

impl Drop for DropMe {
    fn drop(&mut self) {
        DROPS.fetch_add(1, Ordering::SeqCst);
    }
}

fn expect_drops<T>(expected_drops: usize, f: impl FnOnce() -> T) -> T {
    DROPS.store(0, Ordering::SeqCst);

    let res = f();

    let actual_drops = DROPS.load(Ordering::SeqCst);
    assert_eq!(actual_drops, expected_drops);
    res
}

fn main() {
    drain(
        &mut |mut b| {
            while b != 0 {
                b = yield (b + 1);
            }
            -1
        },
        vec![(1, Yielded(2)), (-45, Yielded(-44)), (500, Yielded(501)), (0, Complete(-1))],
    );

    expect_drops(2, || drain(&mut |a| yield a, vec![(DropMe, Yielded(DropMe))]));

    expect_drops(6, || {
        drain(
            &mut |a| yield yield a,
            vec![(DropMe, Yielded(DropMe)), (DropMe, Yielded(DropMe)), (DropMe, Complete(DropMe))],
        )
    });

    #[allow(unreachable_code)]
    expect_drops(2, || drain(&mut |a| yield return a, vec![(DropMe, Complete(DropMe))]));

    expect_drops(2, || {
        drain(
            &mut |a: DropMe| {
                if false { yield () } else { a }
            },
            vec![(DropMe, Complete(DropMe))],
        )
    });

    expect_drops(4, || {
        drain(
            #[allow(unused_assignments, unused_variables)]
            &mut |mut a: DropMe| {
                a = yield;
                a = yield;
                a = yield;
            },
            vec![
                (DropMe, Yielded(())),
                (DropMe, Yielded(())),
                (DropMe, Yielded(())),
                (DropMe, Complete(())),
            ],
        )
    });
}