Clio  develop
The XRP Ledger API server.
Loading...
Searching...
No Matches
AnyStopToken.hpp
1#pragma once
2
3#include "util/Assert.hpp"
4#include "util/async/Concepts.hpp"
5
6#include <boost/asio/spawn.hpp>
7
8#include <chrono>
9#include <memory>
10#include <type_traits>
11#include <utility>
12
13namespace util::async {
14
19public:
26 template <SomeStopToken TokenType>
28 /* implicit */ AnyStopToken(TokenType&& token)
29 : pimpl_{std::make_unique<Model<TokenType>>(std::forward<TokenType>(token))}
30 {
31 }
32
34 ~AnyStopToken() = default;
35
36 AnyStopToken(AnyStopToken const& other) : pimpl_{other.pimpl_->clone()}
37 {
38 }
39
41 operator=(AnyStopToken const& rhs)
42 {
43 AnyStopToken copy{rhs};
44 pimpl_.swap(copy.pimpl_);
45 return *this;
46 }
47
48 AnyStopToken(AnyStopToken&&) = default;
49
51 operator=(AnyStopToken&&) = default;
53
59 [[nodiscard]] bool
60 isStopRequested() const noexcept
61 {
62 return pimpl_->isStopRequested();
63 }
64
70 [[nodiscard]]
71 operator bool() const noexcept
72 {
73 return isStopRequested();
74 }
75
82 [[nodiscard]]
83 operator boost::asio::yield_context() const
84 {
85 return pimpl_->yieldContext();
86 }
87
88private:
89 struct Concept {
90 virtual ~Concept() = default;
91
92 [[nodiscard]] virtual bool
93 isStopRequested() const noexcept = 0;
94
95 [[nodiscard]] virtual std::unique_ptr<Concept>
96 clone() const = 0;
97
98 [[nodiscard]] virtual boost::asio::yield_context
99 yieldContext() const = 0;
100 };
101
102 template <SomeStopToken TokenType>
103 struct Model : Concept {
104 TokenType token;
105
106 Model(TokenType&& token) : token{std::move(token)}
107 {
108 }
109
110 [[nodiscard]] bool
111 isStopRequested() const noexcept override
112 {
113 return token.isStopRequested();
114 }
115
116 [[nodiscard]] std::unique_ptr<Concept>
117 clone() const override
118 {
119 return std::make_unique<Model>(*this);
120 }
121
122 [[nodiscard]] boost::asio::yield_context
123 yieldContext() const override
124 {
125 if constexpr (std::is_convertible_v<TokenType, boost::asio::yield_context>) {
126 return token;
127 }
128
129 ASSERT(false, "Token type does not support conversion to boost::asio::yield_context");
130 std::unreachable();
131 }
132 };
133
134private:
135 std::unique_ptr<Concept> pimpl_;
136};
137
138} // namespace util::async
A type-erased stop token.
Definition AnyStopToken.hpp:18
bool isStopRequested() const noexcept
Check if stop is requested.
Definition AnyStopToken.hpp:60
operator boost::asio::yield_context() const
Get the underlying boost::asio::yield_context.
Definition AnyStopToken.hpp:83
AnyStopToken(TokenType &&token)
Construct a new type-erased Stop Token object.
Definition AnyStopToken.hpp:28
Checks that decayed T s not of the same type as Erased.
Definition Concepts.hpp:202
Specifies the interface for a stop token.
Definition Concepts.hpp:113
This namespace implements an async framework built on top of execution contexts.
Definition AnyExecutionContext.hpp:17