Line data Source code
1 : //
2 : // Copyright (c) 2025 Vinnie Falco (vinnie dot falco at gmail dot com)
3 : //
4 : // Distributed under the Boost Software License, Version 1.0. (See accompanying
5 : // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
6 : //
7 : // Official repository: https://github.com/cppalliance/capy
8 : //
9 :
10 : #ifndef BOOST_CAPY_EX_GET_STOP_TOKEN_HPP
11 : #define BOOST_CAPY_EX_GET_STOP_TOKEN_HPP
12 :
13 : #include <boost/capy/detail/config.hpp>
14 :
15 : namespace boost {
16 : namespace capy {
17 :
18 : /** Tag type for coroutine stop token retrieval.
19 :
20 : This tag is returned by @ref get_stop_token and intercepted by a
21 : promise type's `await_transform` to yield the coroutine's current
22 : stop token. The tag itself carries no data; it serves only as a
23 : sentinel for compile-time dispatch.
24 :
25 : @see get_stop_token
26 : @see stop_token_support
27 : */
28 : struct get_stop_token_tag {};
29 :
30 : /** Return a tag that yields the current stop token when awaited.
31 :
32 : Use `co_await get_stop_token()` inside a coroutine whose promise
33 : type supports stop token access (e.g., inherits from
34 : @ref stop_token_support). The returned stop token reflects whatever
35 : token was passed to this coroutine when it was awaited.
36 :
37 : @par Example
38 : @code
39 : task<void> cancellable_work()
40 : {
41 : auto token = co_await get_stop_token();
42 : for (int i = 0; i < 1000; ++i)
43 : {
44 : if (token.stop_requested())
45 : co_return; // Exit gracefully on cancellation
46 : co_await process_chunk(i);
47 : }
48 : }
49 : @endcode
50 :
51 : @par Behavior
52 : @li If no stop token was propagated, returns a default-constructed
53 : `std::stop_token` (where `stop_possible()` returns `false`).
54 : @li The returned token remains valid for the coroutine's lifetime.
55 : @li This operation never suspends; `await_ready()` always returns `true`.
56 :
57 : @return A tag that `await_transform` intercepts to return the stop token.
58 :
59 : @see get_stop_token_tag
60 : @see stop_token_support
61 : */
62 14 : inline get_stop_token_tag get_stop_token() noexcept
63 : {
64 14 : return {};
65 : }
66 :
67 : } // namespace capy
68 : } // namespace boost
69 :
70 : #endif
|