blob: e8ce9729ad5fe02134ae42bfb06b772eff5271cf (
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
|
/*
* Copyright 2023 jacqueline <me@jacqueline.id.au>
*
* SPDX-License-Identifier: GPL-3.0-only
*/
#pragma once
#include <memory>
#include <utility>
#include "database.hpp"
namespace database {
/*
* Utility to simplify waiting for a std::future to complete without blocking.
* Each instance is good for a single future, and does not directly own anything
* other than the future itself.
*/
template <typename T>
class FutureFetcher {
public:
explicit FutureFetcher(std::future<T>&& fut)
: is_consumed_(false), fut_(std::move(fut)) {}
/*
* Returns whether or not the underlying future is still awaiting async work.
*/
auto Finished() -> bool {
if (!fut_.valid()) {
return true;
}
if (fut_.wait_for(std::chrono::seconds(0)) != std::future_status::ready) {
return false;
}
return true;
}
/*
* Returns the result of the future, and releases ownership of the underling
* resource. Will return an absent value if the future became invalid (e.g.
* the promise associated with it was destroyed.)
*/
auto Result() -> std::optional<T> {
assert(!is_consumed_);
if (is_consumed_) {
return {};
}
is_consumed_ = true;
if (!fut_.valid()) {
return {};
}
return fut_.get();
}
private:
bool is_consumed_;
std::future<T> fut_;
};
} // namespace database
|