8000 Fix early return in QCoro::waitFor by rgriebl · Pull Request #46 · qcoro/qcoro · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

Fix early return in QCoro::waitFor #46

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jan 26, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
< 8000 svg style="box-sizing: content-box; color: var(--color-icon-primary);" width="32" height="32" viewBox="0 0 16 16" fill="none" aria-hidden="true" data-view-component="true" class="anim-rotate"> Loading
Diff view
Diff view
19 changes: 13 additions & 6 deletions qcoro/task.h
Original file line number Diff line number Diff line change
Expand Up @@ -700,27 +700,34 @@ namespace detail {
* QFunctorSlotObjectWithNoArgs until after the event loop quits.
*/
template<typename Coroutine>
Task<> runCoroutine(QEventLoop &loop, Coroutine &&coroutine) {
Task<> runCoroutine(QEventLoop &loop, bool &startLoop, Coroutine &&coroutine) {
co_await coroutine;
startLoop = false;
loop.quit();
}

template<typename T, typename Coroutine>
Task<> runCoroutine(QEventLoop &loop, T &result, Coroutine &&coroutine) {
Task<> runCoroutine(QEventLoop &loop, bool &startLoop, T &result, Coroutine &&coroutine) {
result = co_await coroutine;
startLoop = false;
loop.quit();
}

template<typename T, typename Coroutine>
T waitFor(Coroutine &&coro) {
QEventLoop loop;
bool startLoop = true; // for early returns: calling quit() before exec() still starts the loop
if constexpr (std::is_void_v<T>) {
runCoroutine(loop, std::forward<Coroutine>(coro));
loop.exec();
runCoroutine(loop, startLoop, std::forward<Coroutine>(coro));
if (startLoop) {
loop.exec();
}
} else {
T result;
runCoroutine(loop, result, std::forward<Coroutine>(coro));
loop.exec();
runCoroutine(loop, startLoop, result, std::forward<Coroutine>(coro));
if (startLoop) {
loop.exec();
}
return result;
}
}
Expand Down
11 changes: 11 additions & 0 deletions tests/task.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -376,6 +376,17 @@ private Q_SLOTS:
QCOMPARE(result, 42);
}

void testEarlyReturnWaitFor() {
QCoro::waitFor([]() -> QCoro::Task<> { co_return; }());
}

void testEarlyReturnWaitForWithValue() {
const auto result = QCoro::waitFor([]() -> QCoro::Task<int> {
co_return 42;
}());
QCOMPARE(result, 42);
}

void testIgnoredVoidTaskResult() {
QEventLoop el;
ignoreCoroutineResult(el, [&el]() -> QCoro::Task<> {
Expand Down
0