TLA Line data Source code
1 : //
2 : // Copyright (c) 2025 Vinnie Falco (vinnie.falco@gmail.com)
3 : // Copyright (c) 2026 Michael Vandeberg
4 : //
5 : // Distributed under the Boost Software License, Version 1.0. (See accompanying
6 : // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
7 : //
8 : // Official repository: https://github.com/cppalliance/capy
9 : //
10 :
11 : #ifndef BOOST_CAPY_ANY_EXECUTOR_HPP
12 : #define BOOST_CAPY_ANY_EXECUTOR_HPP
13 :
14 : #include <boost/capy/detail/config.hpp>
15 : #include <boost/capy/continuation.hpp>
16 : #include <boost/capy/detail/type_id.hpp>
17 : #include <concepts>
18 : #include <coroutine>
19 : #include <memory>
20 : #include <type_traits>
21 :
22 : namespace boost {
23 : namespace capy {
24 :
25 : class execution_context;
26 : template<typename> class strand;
27 :
28 : namespace detail {
29 :
30 : template<typename T>
31 : struct is_strand_type : std::false_type {};
32 :
33 : template<typename E>
34 : struct is_strand_type<strand<E>> : std::true_type {};
35 :
36 : } // detail
37 :
38 : /** Forwards `dispatch`/`post`/`context` calls through a shared, type-erased executor pointer.
39 :
40 : This class provides type erasure for any copyable executor type
41 : other than a @ref strand, enabling runtime polymorphism with
42 : automatic memory management via shared ownership. It stores a
43 : shared pointer to a polymorphic wrapper, allowing executors of
44 : different types to be stored uniformly while satisfying the full
45 : @ref Executor concept. Constructing an `any_executor` from a
46 : `strand<E>` does not compile.
47 :
48 : @par Value Semantics
49 :
50 : This class has value semantics with shared ownership. Copy and
51 : move operations are cheap, copying the internal shared
52 : pointer. Multiple `any_executor` instances may share the same
53 : underlying executor. Move operations do not invalidate the
54 : source; there is no moved-from state.
55 :
56 : @par Default State
57 :
58 : A default-constructed `any_executor` holds no executor.
59 : `operator bool()`, `operator==`, and `target()` report the
60 : empty state. `context()`, `on_work_started()`,
61 : `on_work_finished()`, `dispatch()`, and `post()` are undefined
62 : behavior until an executor is assigned.
63 :
64 : @par Thread Safety
65 :
66 : The `any_executor` itself is thread-safe for concurrent reads.
67 : Concurrent modification requires external synchronization.
68 : Executor operations are safe to call concurrently if the
69 : underlying executor supports it.
70 :
71 : @par Executor Concept
72 :
73 : This class satisfies the @ref Executor concept, making it usable
74 : anywhere a concrete executor is expected.
75 :
76 : @par Example
77 : @par !example example
78 :
79 :
80 : @see @ref executor_ref, @ref Executor
81 : */
82 : class any_executor
83 : {
84 : struct impl_base;
85 :
86 : std::shared_ptr<impl_base> p_;
87 :
88 : struct impl_base
89 : {
90 HIT 32 : virtual ~impl_base() = default;
91 : virtual execution_context& context() const noexcept = 0;
92 : virtual void on_work_started() const noexcept = 0;
93 : virtual void on_work_finished() const noexcept = 0;
94 : virtual std::coroutine_handle<> dispatch(continuation&) const = 0;
95 : virtual void post(continuation&) const = 0;
96 : virtual bool equals(impl_base const*) const noexcept = 0;
97 : virtual detail::type_info const& target_type() const noexcept = 0;
98 : virtual void const* target_ptr() const noexcept = 0;
99 : };
100 :
101 : template<class Ex>
102 : struct impl final : impl_base
103 : {
104 : Ex ex_;
105 :
106 : template<class Ex1>
107 32 : explicit impl(Ex1&& ex)
108 32 : : ex_(std::forward<Ex1>(ex))
109 : {
110 32 : }
111 :
112 8 : execution_context& context() const noexcept override
113 : {
114 8 : return const_cast<Ex&>(ex_).context();
115 : }
116 :
117 6 : void on_work_started() const noexcept override
118 : {
119 6 : ex_.on_work_started();
120 6 : }
121 :
122 6 : void on_work_finished() const noexcept override
123 : {
124 6 : ex_.on_work_finished();
125 6 : }
126 :
127 6 : std::coroutine_handle<> dispatch(continuation& c) const override
128 : {
129 6 : return ex_.dispatch(c);
130 : }
131 :
132 16 : void post(continuation& c) const override
133 : {
134 16 : ex_.post(c);
135 16 : }
136 :
137 12 : bool equals(impl_base const* other) const noexcept override
138 : {
139 12 : if(target_type() != other->target_type())
140 2 : return false;
141 10 : return ex_ == static_cast<impl const*>(other)->ex_;
142 : }
143 :
144 44 : detail::type_info const& target_type() const noexcept override
145 : {
146 44 : return detail::type_id<Ex>();
147 : }
148 :
149 15 : void const* target_ptr() const noexcept override
150 : {
151 15 : return &ex_;
152 : }
153 : };
154 :
155 : public:
156 : /** Construct a default instance.
157 :
158 : Constructs an empty `any_executor`. `operator bool()` reports
159 : the empty state; `context()`, `on_work_started()`,
160 : `on_work_finished()`, `dispatch()`, and `post()` are undefined
161 : behavior until an executor is assigned.
162 :
163 : @par Postconditions
164 : @li `!*this`
165 : */
166 2 : any_executor() = default;
167 :
168 : /** Construct a copy.
169 :
170 : Creates a new `any_executor` sharing ownership of the
171 : underlying executor with `other`.
172 :
173 : @par Postconditions
174 : @li `*this == other`
175 :
176 : @param other The executor to copy.
177 : */
178 41 : any_executor(any_executor const& other) = default;
179 :
180 : /** Share ownership of `other`'s executor.
181 :
182 : @par Postconditions
183 : @li `*this == other`
184 :
185 : @param other The executor to copy.
186 :
187 : @return A reference to `*this`.
188 : */
189 6 : any_executor& operator=(any_executor const& other) = default;
190 :
191 : /** Construct from any copyable executor other than a @ref strand.
192 :
193 : Allocates storage for a copy of the given executor and
194 : stores it internally. The executor must satisfy the
195 : @ref Executor concept. Passing a `strand<E>` does not compile.
196 :
197 : @par Postconditions
198 : @li `static_cast<bool>(*this)` is `true`
199 :
200 : @par Exception Safety
201 : Strong guarantee.
202 :
203 : @throws std::bad_alloc If memory allocation fails.
204 :
205 : @throws Any exception thrown when copying or moving `ex`.
206 :
207 : @param ex The executor to wrap. A copy is stored internally.
208 : */
209 : template<class Ex>
210 : requires (
211 : !std::same_as<std::decay_t<Ex>, any_executor> &&
212 : !detail::is_strand_type<std::decay_t<Ex>>::value &&
213 : std::copy_constructible<std::decay_t<Ex>>)
214 32 : any_executor(Ex&& ex)
215 32 : : p_(std::make_shared<impl<std::decay_t<Ex>>>(std::forward<Ex>(ex)))
216 : {
217 32 : }
218 :
219 : /** Check whether this instance holds a valid executor.
220 :
221 : @return `true` if constructed with an executor, `false` if
222 : default-constructed.
223 : */
224 6 : explicit operator bool() const noexcept
225 : {
226 6 : return p_ != nullptr;
227 : }
228 :
229 : /** Return a reference to the associated execution context.
230 :
231 : @pre This instance holds a valid executor.
232 :
233 : @return A reference to the execution context.
234 : */
235 8 : execution_context& context() const noexcept
236 : {
237 8 : return p_->context();
238 : }
239 :
240 : /** Inform the executor that work is beginning.
241 :
242 : Must be paired with a subsequent call to `on_work_finished()`.
243 :
244 : @pre This instance holds a valid executor.
245 : */
246 6 : void on_work_started() const noexcept
247 : {
248 6 : p_->on_work_started();
249 6 : }
250 :
251 : /** Inform the executor that work has completed.
252 :
253 : @pre A preceding call to `on_work_started()` was made.
254 : @pre This instance holds a valid executor.
255 : */
256 6 : void on_work_finished() const noexcept
257 : {
258 6 : p_->on_work_finished();
259 6 : }
260 :
261 : /** Dispatch a continuation through the wrapped executor.
262 :
263 : Forwards to the wrapped executor's `dispatch`. That executor
264 : returns `c.h` to resume inline, or posts `c` and returns
265 : `std::noop_coroutine()`.
266 :
267 : @pre This instance holds a valid executor.
268 :
269 : @par Exception Safety
270 : Propagates any exception from the wrapped executor.
271 :
272 : @param c The continuation to dispatch for resumption.
273 : Must remain at a stable address until dequeued.
274 :
275 : @return A handle for symmetric transfer or `std::noop_coroutine()`.
276 : */
277 6 : std::coroutine_handle<> dispatch(continuation& c) const
278 : {
279 6 : return p_->dispatch(c);
280 : }
281 :
282 : /** Post a continuation to the wrapped executor.
283 :
284 : Posts the continuation to the executor for later execution
285 : and returns. The caller should transfer to `std::noop_coroutine()`
286 : after calling this.
287 :
288 : @pre This instance holds a valid executor.
289 :
290 : @par Exception Safety
291 : Propagates any exception from the wrapped executor.
292 :
293 : @param c The continuation to post for resumption.
294 : Must remain at a stable address until dequeued.
295 : */
296 16 : void post(continuation& c) const
297 : {
298 16 : p_->post(c);
299 16 : }
300 :
301 : /** Compare two executor wrappers for equality.
302 :
303 : Two `any_executor` instances are equal if they both hold
304 : executors of the same type that compare equal, or if both
305 : are empty.
306 :
307 : @param other The executor to compare against.
308 :
309 : @return `true` if both wrap equal executors of the same type,
310 : or both are empty.
311 : */
312 14 : bool operator==(any_executor const& other) const noexcept
313 : {
314 14 : if(!p_ && !other.p_)
315 1 : return true;
316 13 : if(!p_ || !other.p_)
317 1 : return false;
318 12 : return p_->equals(other.p_.get());
319 : }
320 :
321 : /** Return a pointer to the wrapped executor if it matches
322 : the requested type.
323 :
324 : Analogous to `std::any_cast<Ex>(&a)`. Top-level cv-qualifiers
325 : on `Ex` are ignored when matching.
326 :
327 : Copies of an `any_executor` share one stored executor, so
328 : every copy returns the same address. A modification made
329 : through the non-const overload is visible to all of them.
330 : Such modifications are not synchronized with concurrent use
331 : of any copy.
332 :
333 : @tparam Ex The executor type to retrieve.
334 :
335 : @return A pointer to the stored executor, or `nullptr` if
336 : this instance is empty or holds a different type.
337 : */
338 : template<class Ex>
339 5 : Ex const* target() const noexcept
340 : {
341 5 : if(!p_ || p_->target_type() != detail::type_id<Ex>())
342 3 : return nullptr;
343 : // Casting from void const* avoids naming impl<Ex>, which would
344 : // instantiate its overrides and reject non-executor types
345 2 : return static_cast<Ex const*>(p_->target_ptr());
346 : }
347 :
348 : /// @copydoc target() const
349 : template<class Ex>
350 18 : Ex* target() noexcept
351 : {
352 18 : if(!p_ || p_->target_type() != detail::type_id<Ex>())
353 5 : return nullptr;
354 : return const_cast<Ex*>(
355 13 : static_cast<Ex const*>(p_->target_ptr()));
356 : }
357 : };
358 :
359 : } // capy
360 : } // boost
361 :
362 : #endif
|