blob: 4681793ed814f7dac367e2442ced1fc324023da2 (
plain) (
blame)
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
101
102
103
104
105
106
107
|
// -*- C++ -*-
//===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// UNSUPPORTED: c++98, c++03, c++11
// REQUIRES: fcoroutines-ts
// FIXME: When run under UBSAN this test hits an assertion inside Clang
// XFAIL: ubsan
// RUN: %build -fcoroutines-ts
// RUN: %run
#include <experimental/coroutine>
#include <vector>
#include <cassert>
#include "coroutine_types.h"
using namespace std::experimental;
struct minig {
struct promise_type {
int current_value;
suspend_always yield_value(int value) {
this->current_value = value;
return {};
}
suspend_always initial_suspend() { return {}; }
suspend_always final_suspend() { return {}; }
minig get_return_object() { return minig{this}; };
void return_void() {}
void unhandled_exception() {}
};
bool move_next() {
p.resume();
return !p.done();
}
int current_value() { return p.promise().current_value; }
minig(minig &&rhs) : p(rhs.p) { rhs.p = nullptr; }
~minig() {
if (p)
p.destroy();
}
private:
explicit minig(promise_type *p)
: p(coroutine_handle<promise_type>::from_promise(*p)) {}
coroutine_handle<promise_type> p;
};
minig mini_count(int n) {
for (int i = 0; i < n; i++) {
co_yield i;
}
}
generator<int> count(int n) {
for (int i = 0; i < n; ++i)
co_yield i;
}
generator<int> range(int from, int n) {
for (int i = from; i < n; ++i)
co_yield i;
}
void test_count() {
const std::vector<int> expect = {0, 1, 2, 3, 4};
std::vector<int> got;
for (auto x : count(5))
got.push_back(x);
assert(expect == got);
}
void test_range() {
int sum = 0;
for (auto v: range(1, 20))
sum += v;
assert(sum == 190);
}
void test_mini_generator() {
int sum = 0;
auto g = mini_count(5);
while (g.move_next()) {
sum += g.current_value();
}
assert(sum == 10);
}
int main() {
test_count();
test_range();
test_mini_generator();
}
|