1  
//
1  
//
2  
// Copyright (c) 2025 Vinnie Falco (vinnie.falco@gmail.com)
2  
// Copyright (c) 2025 Vinnie Falco (vinnie.falco@gmail.com)
3  
//
3  
//
4  
// Distributed under the Boost Software License, Version 1.0. (See accompanying
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)
5  
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
6  
//
6  
//
7  
// Official repository: https://github.com/cppalliance/capy
7  
// Official repository: https://github.com/cppalliance/capy
8  
//
8  
//
9  

9  

10  
#ifndef BOOST_CAPY_EXECUTION_CONTEXT_HPP
10  
#ifndef BOOST_CAPY_EXECUTION_CONTEXT_HPP
11  
#define BOOST_CAPY_EXECUTION_CONTEXT_HPP
11  
#define BOOST_CAPY_EXECUTION_CONTEXT_HPP
12  

12  

13  
#include <boost/capy/detail/config.hpp>
13  
#include <boost/capy/detail/config.hpp>
14  
#include <boost/capy/detail/frame_memory_resource.hpp>
14  
#include <boost/capy/detail/frame_memory_resource.hpp>
15  
#include <boost/capy/detail/type_id.hpp>
15  
#include <boost/capy/detail/type_id.hpp>
16  
#include <boost/capy/concept/executor.hpp>
16  
#include <boost/capy/concept/executor.hpp>
17  
#include <concepts>
17  
#include <concepts>
18  
#include <memory>
18  
#include <memory>
19  
#include <memory_resource>
19  
#include <memory_resource>
20  
#include <mutex>
20  
#include <mutex>
21  
#include <tuple>
21  
#include <tuple>
22  
#include <type_traits>
22  
#include <type_traits>
23  
#include <utility>
23  
#include <utility>
24  

24  

25  
namespace boost {
25  
namespace boost {
26  
namespace capy {
26  
namespace capy {
27  

27  

28  
/** Base class for I/O object containers providing service management.
28  
/** Base class for I/O object containers providing service management.
29  

29  

30  
    An execution context represents a place where function objects are
30  
    An execution context represents a place where function objects are
31  
    executed. It provides a service registry where polymorphic services
31  
    executed. It provides a service registry where polymorphic services
32  
    can be stored and retrieved by type. Each service type may be stored
32  
    can be stored and retrieved by type. Each service type may be stored
33  
    at most once. Services may specify a nested `key_type` to enable
33  
    at most once. Services may specify a nested `key_type` to enable
34  
    lookup by a base class type.
34  
    lookup by a base class type.
35  

35  

36  
    Derived classes such as `io_context` extend this to provide
36  
    Derived classes such as `io_context` extend this to provide
37  
    execution facilities like event loops and thread pools. Derived
37  
    execution facilities like event loops and thread pools. Derived
38  
    class destructors must call `shutdown()` and `destroy()` to ensure
38  
    class destructors must call `shutdown()` and `destroy()` to ensure
39  
    proper service cleanup before member destruction.
39  
    proper service cleanup before member destruction.
40  

40  

41  
    @par Service Lifecycle
41  
    @par Service Lifecycle
42  
    Services are created on first use via `use_service()` or explicitly
42  
    Services are created on first use via `use_service()` or explicitly
43  
    via `make_service()`. During destruction, `shutdown()` is called on
43  
    via `make_service()`. During destruction, `shutdown()` is called on
44  
    each service in reverse order of creation, then `destroy()` deletes
44  
    each service in reverse order of creation, then `destroy()` deletes
45  
    them. Both functions are idempotent.
45  
    them. Both functions are idempotent.
46  

46  

47  
    @par Thread Safety
47  
    @par Thread Safety
48  
    Service registration and lookup functions are thread-safe.
48  
    Service registration and lookup functions are thread-safe.
49  
    The `shutdown()` and `destroy()` functions are not thread-safe
49  
    The `shutdown()` and `destroy()` functions are not thread-safe
50  
    and must only be called during destruction.
50  
    and must only be called during destruction.
51  

51  

52  
    @par Example
52  
    @par Example
53  
    @code
53  
    @code
54  
    struct file_service : execution_context::service
54  
    struct file_service : execution_context::service
55  
    {
55  
    {
56  
    protected:
56  
    protected:
57  
        void shutdown() override {}
57  
        void shutdown() override {}
58  
    };
58  
    };
59  

59  

60  
    struct posix_file_service : file_service
60  
    struct posix_file_service : file_service
61  
    {
61  
    {
62  
        using key_type = file_service;
62  
        using key_type = file_service;
63  

63  

64  
        explicit posix_file_service(execution_context&) {}
64  
        explicit posix_file_service(execution_context&) {}
65  
    };
65  
    };
66  

66  

67  
    class io_context : public execution_context
67  
    class io_context : public execution_context
68  
    {
68  
    {
69  
    public:
69  
    public:
70  
        ~io_context()
70  
        ~io_context()
71  
        {
71  
        {
72  
            shutdown();
72  
            shutdown();
73  
            destroy();
73  
            destroy();
74  
        }
74  
        }
75  
    };
75  
    };
76  

76  

77  
    io_context ctx;
77  
    io_context ctx;
78  
    ctx.make_service<posix_file_service>();
78  
    ctx.make_service<posix_file_service>();
79  
    ctx.find_service<file_service>();       // returns posix_file_service*
79  
    ctx.find_service<file_service>();       // returns posix_file_service*
80  
    ctx.find_service<posix_file_service>(); // also works
80  
    ctx.find_service<posix_file_service>(); // also works
81  
    @endcode
81  
    @endcode
82  

82  

83  
    @see service, is_execution_context
83  
    @see service, is_execution_context
84  
*/
84  
*/
85  
class BOOST_CAPY_DECL
85  
class BOOST_CAPY_DECL
86  
    execution_context
86  
    execution_context
87  
{
87  
{
 
88 +
    detail::type_info const* ti_ = nullptr;
 
89 +

88  
    template<class T, class = void>
90  
    template<class T, class = void>
89  
    struct get_key : std::false_type
91  
    struct get_key : std::false_type
90  
    {};
92  
    {};
91  

93  

92  
    template<class T>
94  
    template<class T>
93  
    struct get_key<T, std::void_t<typename T::key_type>> : std::true_type
95  
    struct get_key<T, std::void_t<typename T::key_type>> : std::true_type
94  
    {
96  
    {
95  
        using type = typename T::key_type;
97  
        using type = typename T::key_type;
96  
    };
98  
    };
 
99 +
protected:
 
100 +
    template< typename Derived >
 
101 +
    explicit execution_context( Derived* ) noexcept;
97  

102  

98  
public:
103  
public:
99  
    //------------------------------------------------
104  
    //------------------------------------------------
100  

105  

101  
    /** Abstract base class for services owned by an execution context.
106  
    /** Abstract base class for services owned by an execution context.
102  

107  

103  
        Services provide extensible functionality to an execution context.
108  
        Services provide extensible functionality to an execution context.
104  
        Each service type can be registered at most once. Services are
109  
        Each service type can be registered at most once. Services are
105  
        created via `use_service()` or `make_service()` and are owned by
110  
        created via `use_service()` or `make_service()` and are owned by
106  
        the execution context for their lifetime.
111  
        the execution context for their lifetime.
107  

112  

108  
        Derived classes must implement the pure virtual `shutdown()` member
113  
        Derived classes must implement the pure virtual `shutdown()` member
109  
        function, which is called when the owning execution context is
114  
        function, which is called when the owning execution context is
110  
        being destroyed. The `shutdown()` function should release resources
115  
        being destroyed. The `shutdown()` function should release resources
111  
        and cancel outstanding operations without blocking.
116  
        and cancel outstanding operations without blocking.
112  

117  

113  
        @par Deriving from service
118  
        @par Deriving from service
114  
        @li Implement `shutdown()` to perform cleanup.
119  
        @li Implement `shutdown()` to perform cleanup.
115  
        @li Accept `execution_context&` as the first constructor parameter.
120  
        @li Accept `execution_context&` as the first constructor parameter.
116  
        @li Optionally define `key_type` to enable base-class lookup.
121  
        @li Optionally define `key_type` to enable base-class lookup.
117  

122  

118  
        @par Example
123  
        @par Example
119  
        @code
124  
        @code
120  
        struct my_service : execution_context::service
125  
        struct my_service : execution_context::service
121  
        {
126  
        {
122  
            explicit my_service(execution_context&) {}
127  
            explicit my_service(execution_context&) {}
123  

128  

124  
        protected:
129  
        protected:
125  
            void shutdown() override
130  
            void shutdown() override
126  
            {
131  
            {
127  
                // Cancel pending operations, release resources
132  
                // Cancel pending operations, release resources
128  
            }
133  
            }
129  
        };
134  
        };
130  
        @endcode
135  
        @endcode
131  

136  

132  
        @see execution_context
137  
        @see execution_context
133  
    */
138  
    */
134  
    class BOOST_CAPY_DECL
139  
    class BOOST_CAPY_DECL
135  
        service
140  
        service
136  
    {
141  
    {
137  
    public:
142  
    public:
138  
        virtual ~service() = default;
143  
        virtual ~service() = default;
139  

144  

140  
    protected:
145  
    protected:
141  
        service() = default;
146  
        service() = default;
142  

147  

143  
        /** Called when the owning execution context shuts down.
148  
        /** Called when the owning execution context shuts down.
144  

149  

145  
            Implementations should release resources and cancel any
150  
            Implementations should release resources and cancel any
146  
            outstanding asynchronous operations. This function must
151  
            outstanding asynchronous operations. This function must
147  
            not block and must not throw exceptions. Services are
152  
            not block and must not throw exceptions. Services are
148  
            shut down in reverse order of creation.
153  
            shut down in reverse order of creation.
149  

154  

150  
            @par Exception Safety
155  
            @par Exception Safety
151  
            No-throw guarantee.
156  
            No-throw guarantee.
152  
        */
157  
        */
153  
        virtual void shutdown() = 0;
158  
        virtual void shutdown() = 0;
154  

159  

155  
    private:
160  
    private:
156  
        friend class execution_context;
161  
        friend class execution_context;
157  

162  

158  
        service* next_ = nullptr;
163  
        service* next_ = nullptr;
159  

164  

160  
// warning C4251: 'std::type_index' needs to have dll-interface
165  
// warning C4251: 'std::type_index' needs to have dll-interface
161  
#ifdef _MSC_VER
166  
#ifdef _MSC_VER
162  
# pragma warning(push)
167  
# pragma warning(push)
163  
# pragma warning(disable: 4251)
168  
# pragma warning(disable: 4251)
164  
#endif
169  
#endif
165  
        detail::type_index t0_{detail::type_id<void>()};
170  
        detail::type_index t0_{detail::type_id<void>()};
166  
        detail::type_index t1_{detail::type_id<void>()};
171  
        detail::type_index t1_{detail::type_id<void>()};
167  
#ifdef _MSC_VER
172  
#ifdef _MSC_VER
168  
# pragma warning(pop)
173  
# pragma warning(pop)
169  
#endif
174  
#endif
170  
    };
175  
    };
171  

176  

172  
    //------------------------------------------------
177  
    //------------------------------------------------
173  

178  

174  
    execution_context(execution_context const&) = delete;
179  
    execution_context(execution_context const&) = delete;
175  

180  

176  
    execution_context& operator=(execution_context const&) = delete;
181  
    execution_context& operator=(execution_context const&) = delete;
177  

182  

178  
    /** Destructor.
183  
    /** Destructor.
179  

184  

180  
        Calls `shutdown()` then `destroy()` to clean up all services.
185  
        Calls `shutdown()` then `destroy()` to clean up all services.
181  

186  

182  
        @par Effects
187  
        @par Effects
183  
        All services are shut down and deleted in reverse order
188  
        All services are shut down and deleted in reverse order
184  
        of creation.
189  
        of creation.
185  

190  

186  
        @par Exception Safety
191  
        @par Exception Safety
187  
        No-throw guarantee.
192  
        No-throw guarantee.
188  
    */
193  
    */
189  
    ~execution_context();
194  
    ~execution_context();
190  

195  

191  
    /** Default constructor.
196  
    /** Default constructor.
192  

197  

193  
        @par Exception Safety
198  
        @par Exception Safety
194  
        Strong guarantee.
199  
        Strong guarantee.
195  
    */
200  
    */
196  
    execution_context();
201  
    execution_context();
197  

202  

198  
    /** Return true if a service of type T exists.
203  
    /** Return true if a service of type T exists.
199  

204  

200  
        @par Thread Safety
205  
        @par Thread Safety
201  
        Thread-safe.
206  
        Thread-safe.
202  

207  

203  
        @tparam T The type of service to check.
208  
        @tparam T The type of service to check.
204  

209  

205  
        @return `true` if the service exists.
210  
        @return `true` if the service exists.
206  
    */
211  
    */
207  
    template<class T>
212  
    template<class T>
208  
    bool has_service() const noexcept
213  
    bool has_service() const noexcept
209  
    {
214  
    {
210  
        return find_service<T>() != nullptr;
215  
        return find_service<T>() != nullptr;
211  
    }
216  
    }
212  

217  

213  
    /** Return a pointer to the service of type T, or nullptr.
218  
    /** Return a pointer to the service of type T, or nullptr.
214  

219  

215  
        @par Thread Safety
220  
        @par Thread Safety
216  
        Thread-safe.
221  
        Thread-safe.
217  

222  

218  
        @tparam T The type of service to find.
223  
        @tparam T The type of service to find.
219  

224  

220  
        @return A pointer to the service, or `nullptr` if not present.
225  
        @return A pointer to the service, or `nullptr` if not present.
221  
    */
226  
    */
222  
    template<class T>
227  
    template<class T>
223  
    T* find_service() const noexcept
228  
    T* find_service() const noexcept
224  
    {
229  
    {
225  
        std::lock_guard<std::mutex> lock(mutex_);
230  
        std::lock_guard<std::mutex> lock(mutex_);
226  
        return static_cast<T*>(find_impl(detail::type_id<T>()));
231  
        return static_cast<T*>(find_impl(detail::type_id<T>()));
227  
    }
232  
    }
228  

233  

229  
    /** Return a reference to the service of type T, creating it if needed.
234  
    /** Return a reference to the service of type T, creating it if needed.
230  

235  

231  
        If no service of type T exists, one is created by calling
236  
        If no service of type T exists, one is created by calling
232  
        `T(execution_context&)`. If T has a nested `key_type`, the
237  
        `T(execution_context&)`. If T has a nested `key_type`, the
233  
        service is also indexed under that type.
238  
        service is also indexed under that type.
234  

239  

235  
        @par Constraints
240  
        @par Constraints
236  
        @li `T` must derive from `service`.
241  
        @li `T` must derive from `service`.
237  
        @li `T` must be constructible from `execution_context&`.
242  
        @li `T` must be constructible from `execution_context&`.
238  

243  

239  
        @par Exception Safety
244  
        @par Exception Safety
240  
        Strong guarantee. If service creation throws, the container
245  
        Strong guarantee. If service creation throws, the container
241  
        is unchanged.
246  
        is unchanged.
242  

247  

243  
        @par Thread Safety
248  
        @par Thread Safety
244  
        Thread-safe.
249  
        Thread-safe.
245  

250  

246  
        @tparam T The type of service to retrieve or create.
251  
        @tparam T The type of service to retrieve or create.
247  

252  

248  
        @return A reference to the service.
253  
        @return A reference to the service.
249  
    */
254  
    */
250  
    template<class T>
255  
    template<class T>
251  
    T& use_service()
256  
    T& use_service()
252  
    {
257  
    {
253  
        static_assert(std::is_base_of<service, T>::value,
258  
        static_assert(std::is_base_of<service, T>::value,
254  
            "T must derive from service");
259  
            "T must derive from service");
255  
        static_assert(std::is_constructible<T, execution_context&>::value,
260  
        static_assert(std::is_constructible<T, execution_context&>::value,
256  
            "T must be constructible from execution_context&");
261  
            "T must be constructible from execution_context&");
257  

262  

258  
        struct impl : factory
263  
        struct impl : factory
259  
        {
264  
        {
260  
            impl()
265  
            impl()
261  
                : factory(
266  
                : factory(
262  
                    detail::type_id<T>(),
267  
                    detail::type_id<T>(),
263  
                    get_key<T>::value
268  
                    get_key<T>::value
264  
                        ? detail::type_id<typename get_key<T>::type>()
269  
                        ? detail::type_id<typename get_key<T>::type>()
265  
                        : detail::type_id<T>())
270  
                        : detail::type_id<T>())
266  
            {
271  
            {
267  
            }
272  
            }
268  

273  

269  
            service* create(execution_context& ctx) override
274  
            service* create(execution_context& ctx) override
270  
            {
275  
            {
271  
                return new T(ctx);
276  
                return new T(ctx);
272  
            }
277  
            }
273  
        };
278  
        };
274  

279  

275  
        impl f;
280  
        impl f;
276  
        return static_cast<T&>(use_service_impl(f));
281  
        return static_cast<T&>(use_service_impl(f));
277  
    }
282  
    }
278  

283  

279  
    /** Construct and add a service.
284  
    /** Construct and add a service.
280  

285  

281  
        A new service of type T is constructed using the provided
286  
        A new service of type T is constructed using the provided
282  
        arguments and added to the container. If T has a nested
287  
        arguments and added to the container. If T has a nested
283  
        `key_type`, the service is also indexed under that type.
288  
        `key_type`, the service is also indexed under that type.
284  

289  

285  
        @par Constraints
290  
        @par Constraints
286  
        @li `T` must derive from `service`.
291  
        @li `T` must derive from `service`.
287  
        @li `T` must be constructible from `execution_context&, Args...`.
292  
        @li `T` must be constructible from `execution_context&, Args...`.
288  
        @li If `T::key_type` exists, `T&` must be convertible to `key_type&`.
293  
        @li If `T::key_type` exists, `T&` must be convertible to `key_type&`.
289  

294  

290  
        @par Exception Safety
295  
        @par Exception Safety
291  
        Strong guarantee. If service creation throws, the container
296  
        Strong guarantee. If service creation throws, the container
292  
        is unchanged.
297  
        is unchanged.
293  

298  

294  
        @par Thread Safety
299  
        @par Thread Safety
295  
        Thread-safe.
300  
        Thread-safe.
296  

301  

297  
        @throws std::invalid_argument if a service of the same type
302  
        @throws std::invalid_argument if a service of the same type
298  
            or `key_type` already exists.
303  
            or `key_type` already exists.
299  

304  

300  
        @tparam T The type of service to create.
305  
        @tparam T The type of service to create.
301  

306  

302  
        @param args Arguments forwarded to the constructor of T.
307  
        @param args Arguments forwarded to the constructor of T.
303  

308  

304  
        @return A reference to the created service.
309  
        @return A reference to the created service.
305  
    */
310  
    */
306  
    template<class T, class... Args>
311  
    template<class T, class... Args>
307  
    T& make_service(Args&&... args)
312  
    T& make_service(Args&&... args)
308  
    {
313  
    {
309  
        static_assert(std::is_base_of<service, T>::value,
314  
        static_assert(std::is_base_of<service, T>::value,
310  
            "T must derive from service");
315  
            "T must derive from service");
311  
        if constexpr(get_key<T>::value)
316  
        if constexpr(get_key<T>::value)
312  
        {
317  
        {
313  
            static_assert(
318  
            static_assert(
314  
                std::is_convertible<T&, typename get_key<T>::type&>::value,
319  
                std::is_convertible<T&, typename get_key<T>::type&>::value,
315  
                "T& must be convertible to key_type&");
320  
                "T& must be convertible to key_type&");
316  
        }
321  
        }
317  

322  

318  
        struct impl : factory
323  
        struct impl : factory
319  
        {
324  
        {
320  
            std::tuple<Args&&...> args_;
325  
            std::tuple<Args&&...> args_;
321  

326  

322  
            explicit impl(Args&&... a)
327  
            explicit impl(Args&&... a)
323  
                : factory(
328  
                : factory(
324  
                    detail::type_id<T>(),
329  
                    detail::type_id<T>(),
325  
                    get_key<T>::value
330  
                    get_key<T>::value
326  
                        ? detail::type_id<typename get_key<T>::type>()
331  
                        ? detail::type_id<typename get_key<T>::type>()
327  
                        : detail::type_id<T>())
332  
                        : detail::type_id<T>())
328  
                , args_(std::forward<Args>(a)...)
333  
                , args_(std::forward<Args>(a)...)
329  
            {
334  
            {
330  
            }
335  
            }
331  

336  

332  
            service* create(execution_context& ctx) override
337  
            service* create(execution_context& ctx) override
333  
            {
338  
            {
334  
                return std::apply([&ctx](auto&&... a) {
339  
                return std::apply([&ctx](auto&&... a) {
335  
                    return new T(ctx, std::forward<decltype(a)>(a)...);
340  
                    return new T(ctx, std::forward<decltype(a)>(a)...);
336  
                }, std::move(args_));
341  
                }, std::move(args_));
337  
            }
342  
            }
338  
        };
343  
        };
339  

344  

340  
        impl f(std::forward<Args>(args)...);
345  
        impl f(std::forward<Args>(args)...);
341  
        return static_cast<T&>(make_service_impl(f));
346  
        return static_cast<T&>(make_service_impl(f));
342  
    }
347  
    }
343  

348  

344  
    //------------------------------------------------
349  
    //------------------------------------------------
345  

350  

346  
    /** Return the memory resource used for coroutine frame allocation.
351  
    /** Return the memory resource used for coroutine frame allocation.
347  

352  

348  
        The returned pointer is valid for the lifetime of this context.
353  
        The returned pointer is valid for the lifetime of this context.
349  
        By default, this returns a pointer to the recycling memory
354  
        By default, this returns a pointer to the recycling memory
350  
        resource which pools frame allocations for reuse.
355  
        resource which pools frame allocations for reuse.
351  

356  

352  
        @return Pointer to the frame allocator.
357  
        @return Pointer to the frame allocator.
353  

358  

354  
        @see set_frame_allocator
359  
        @see set_frame_allocator
355  
    */
360  
    */
356  
    std::pmr::memory_resource*
361  
    std::pmr::memory_resource*
357  
    get_frame_allocator() const noexcept
362  
    get_frame_allocator() const noexcept
358  
    {
363  
    {
359  
        return frame_alloc_;
364  
        return frame_alloc_;
360  
    }
365  
    }
361  

366  

362  
    /** Set the memory resource used for coroutine frame allocation.
367  
    /** Set the memory resource used for coroutine frame allocation.
363  

368  

364  
        The caller is responsible for ensuring the memory resource
369  
        The caller is responsible for ensuring the memory resource
365  
        remains valid for the lifetime of all coroutines launched
370  
        remains valid for the lifetime of all coroutines launched
366  
        using this context's executor.
371  
        using this context's executor.
367  

372  

368  
        @par Thread Safety
373  
        @par Thread Safety
369  
        Not thread-safe. Must not be called while any thread may
374  
        Not thread-safe. Must not be called while any thread may
370  
        be referencing this execution context or its executor.
375  
        be referencing this execution context or its executor.
371  

376  

372  
        @param mr Pointer to the memory resource.
377  
        @param mr Pointer to the memory resource.
373  

378  

374  
        @see get_frame_allocator
379  
        @see get_frame_allocator
375  
    */
380  
    */
376  
    void
381  
    void
377  
    set_frame_allocator(std::pmr::memory_resource* mr) noexcept
382  
    set_frame_allocator(std::pmr::memory_resource* mr) noexcept
378  
    {
383  
    {
379  
        owned_.reset();
384  
        owned_.reset();
380  
        frame_alloc_ = mr;
385  
        frame_alloc_ = mr;
381  
    }
386  
    }
382  

387  

383  
    /** Set the frame allocator from a standard Allocator.
388  
    /** Set the frame allocator from a standard Allocator.
384  

389  

385  
        The allocator is wrapped in an internal memory resource
390  
        The allocator is wrapped in an internal memory resource
386  
        adapter owned by this context. The wrapper remains valid
391  
        adapter owned by this context. The wrapper remains valid
387  
        for the lifetime of this context or until a subsequent
392  
        for the lifetime of this context or until a subsequent
388  
        call to set_frame_allocator.
393  
        call to set_frame_allocator.
389  

394  

390  
        @par Thread Safety
395  
        @par Thread Safety
391  
        Not thread-safe. Must not be called while any thread may
396  
        Not thread-safe. Must not be called while any thread may
392  
        be referencing this execution context or its executor.
397  
        be referencing this execution context or its executor.
393  

398  

394  
        @tparam Allocator The allocator type satisfying the
399  
        @tparam Allocator The allocator type satisfying the
395  
            standard Allocator requirements.
400  
            standard Allocator requirements.
396  

401  

397  
        @param a The allocator to use.
402  
        @param a The allocator to use.
398  

403  

399  
        @see get_frame_allocator
404  
        @see get_frame_allocator
400  
    */
405  
    */
401  
    template<class Allocator>
406  
    template<class Allocator>
402  
        requires (!std::is_pointer_v<Allocator>)
407  
        requires (!std::is_pointer_v<Allocator>)
403  
    void
408  
    void
404  
    set_frame_allocator(Allocator const& a)
409  
    set_frame_allocator(Allocator const& a)
405  
    {
410  
    {
406  
        static_assert(
411  
        static_assert(
407  
            requires { typename std::allocator_traits<Allocator>::value_type; },
412  
            requires { typename std::allocator_traits<Allocator>::value_type; },
408  
            "Allocator must satisfy allocator requirements");
413  
            "Allocator must satisfy allocator requirements");
409  
        static_assert(
414  
        static_assert(
410  
            std::is_copy_constructible_v<Allocator>,
415  
            std::is_copy_constructible_v<Allocator>,
411  
            "Allocator must be copy constructible");
416  
            "Allocator must be copy constructible");
412  

417  

413  
        auto p = std::make_shared<
418  
        auto p = std::make_shared<
414  
            detail::frame_memory_resource<Allocator>>(a);
419  
            detail::frame_memory_resource<Allocator>>(a);
415  
        frame_alloc_ = p.get();
420  
        frame_alloc_ = p.get();
416  
        owned_ = std::move(p);
421  
        owned_ = std::move(p);
417  
    }
422  
    }
418  

423  

 
424 +
    /** Return a pointer to this context if it matches the
 
425 +
        requested type.
 
426 +

 
427 +
        Performs a type check and downcasts `this` when the
 
428 +
        types match, or returns `nullptr` otherwise. Analogous
 
429 +
        to `std::any_cast< ExecutionContext >( &a )`.
 
430 +

 
431 +
        @tparam ExecutionContext The derived context type to
 
432 +
            retrieve.
 
433 +

 
434 +
        @return A pointer to this context as the requested
 
435 +
            type, or `nullptr` if the type does not match.
 
436 +
    */
 
437 +
    template< typename ExecutionContext >
 
438 +
    const ExecutionContext* target() const
 
439 +
    {
 
440 +
        if ( ti_ && *ti_ == detail::type_id< ExecutionContext >() )
 
441 +
           return static_cast< ExecutionContext const* >( this );
 
442 +
        return nullptr;
 
443 +
    }
 
444 +

 
445 +
    /// @copydoc target() const
 
446 +
    template< typename ExecutionContext >
 
447 +
    ExecutionContext* target()
 
448 +
    {
 
449 +
        if ( ti_ && *ti_ == detail::type_id< ExecutionContext >() )
 
450 +
           return static_cast< ExecutionContext* >( this );
 
451 +
        return nullptr;
 
452 +
    }
 
453 +

419  
protected:
454  
protected:
420  
    /** Shut down all services.
455  
    /** Shut down all services.
421  

456  

422  
        Calls `shutdown()` on each service in reverse order of creation.
457  
        Calls `shutdown()` on each service in reverse order of creation.
423  
        After this call, services remain allocated but are in a stopped
458  
        After this call, services remain allocated but are in a stopped
424  
        state. Derived classes should call this in their destructor
459  
        state. Derived classes should call this in their destructor
425  
        before any members are destroyed. This function is idempotent;
460  
        before any members are destroyed. This function is idempotent;
426  
        subsequent calls have no effect.
461  
        subsequent calls have no effect.
427  

462  

428  
        @par Effects
463  
        @par Effects
429  
        Each service's `shutdown()` member function is invoked once.
464  
        Each service's `shutdown()` member function is invoked once.
430  

465  

431  
        @par Postconditions
466  
        @par Postconditions
432  
        @li All services are in a stopped state.
467  
        @li All services are in a stopped state.
433  

468  

434  
        @par Exception Safety
469  
        @par Exception Safety
435  
        No-throw guarantee.
470  
        No-throw guarantee.
436  

471  

437  
        @par Thread Safety
472  
        @par Thread Safety
438  
        Not thread-safe. Must not be called concurrently with other
473  
        Not thread-safe. Must not be called concurrently with other
439  
        operations on this execution_context.
474  
        operations on this execution_context.
440  
    */
475  
    */
441  
    void shutdown() noexcept;
476  
    void shutdown() noexcept;
442  

477  

443  
    /** Destroy all services.
478  
    /** Destroy all services.
444  

479  

445  
        Deletes all services in reverse order of creation. Derived
480  
        Deletes all services in reverse order of creation. Derived
446  
        classes should call this as the final step of destruction.
481  
        classes should call this as the final step of destruction.
447  
        This function is idempotent; subsequent calls have no effect.
482  
        This function is idempotent; subsequent calls have no effect.
448  

483  

449  
        @par Preconditions
484  
        @par Preconditions
450  
        @li `shutdown()` has been called.
485  
        @li `shutdown()` has been called.
451  

486  

452  
        @par Effects
487  
        @par Effects
453  
        All services are deleted and removed from the container.
488  
        All services are deleted and removed from the container.
454  

489  

455  
        @par Postconditions
490  
        @par Postconditions
456  
        @li The service container is empty.
491  
        @li The service container is empty.
457  

492  

458  
        @par Exception Safety
493  
        @par Exception Safety
459  
        No-throw guarantee.
494  
        No-throw guarantee.
460  

495  

461  
        @par Thread Safety
496  
        @par Thread Safety
462  
        Not thread-safe. Must not be called concurrently with other
497  
        Not thread-safe. Must not be called concurrently with other
463  
        operations on this execution_context.
498  
        operations on this execution_context.
464  
    */
499  
    */
465  
    void destroy() noexcept;
500  
    void destroy() noexcept;
466  

501  

467  
private:
502  
private:
468  
    struct BOOST_CAPY_DECL
503  
    struct BOOST_CAPY_DECL
469  
        factory
504  
        factory
470  
    {
505  
    {
471  
#ifdef _MSC_VER
506  
#ifdef _MSC_VER
472  
# pragma warning(push)
507  
# pragma warning(push)
473  
# pragma warning(disable: 4251)
508  
# pragma warning(disable: 4251)
474  
#endif
509  
#endif
475  
// warning C4251: 'std::type_index' needs to have dll-interface
510  
// warning C4251: 'std::type_index' needs to have dll-interface
476  
        detail::type_index t0;
511  
        detail::type_index t0;
477  
        detail::type_index t1;
512  
        detail::type_index t1;
478  
#ifdef _MSC_VER
513  
#ifdef _MSC_VER
479  
# pragma warning(pop)
514  
# pragma warning(pop)
480  
#endif
515  
#endif
481  

516  

482  
        factory(
517  
        factory(
483  
            detail::type_info const& t0_,
518  
            detail::type_info const& t0_,
484  
            detail::type_info const& t1_)
519  
            detail::type_info const& t1_)
485  
            : t0(t0_), t1(t1_)
520  
            : t0(t0_), t1(t1_)
486  
        {
521  
        {
487  
        }
522  
        }
488  

523  

489  
        virtual service* create(execution_context&) = 0;
524  
        virtual service* create(execution_context&) = 0;
490  

525  

491  
    protected:
526  
    protected:
492  
        ~factory() = default;
527  
        ~factory() = default;
493  
    };
528  
    };
494  

529  

495  
    service* find_impl(detail::type_index ti) const noexcept;
530  
    service* find_impl(detail::type_index ti) const noexcept;
496  
    service& use_service_impl(factory& f);
531  
    service& use_service_impl(factory& f);
497  
    service& make_service_impl(factory& f);
532  
    service& make_service_impl(factory& f);
498  

533  

499  
#ifdef _MSC_VER
534  
#ifdef _MSC_VER
500  
# pragma warning(push)
535  
# pragma warning(push)
501  
# pragma warning(disable: 4251)
536  
# pragma warning(disable: 4251)
502  
#endif
537  
#endif
503  
// warning C4251: 'std::type_index' needs to have dll-interface
538  
// warning C4251: 'std::type_index' needs to have dll-interface
504  
    mutable std::mutex mutex_;
539  
    mutable std::mutex mutex_;
505  
    std::shared_ptr<void> owned_;
540  
    std::shared_ptr<void> owned_;
506  
#ifdef _MSC_VER
541  
#ifdef _MSC_VER
507  
# pragma warning(pop)
542  
# pragma warning(pop)
508  
#endif
543  
#endif
509  
    std::pmr::memory_resource* frame_alloc_ = nullptr;
544  
    std::pmr::memory_resource* frame_alloc_ = nullptr;
510  
    service* head_ = nullptr;
545  
    service* head_ = nullptr;
511  
    bool shutdown_ = false;
546  
    bool shutdown_ = false;
512  
};
547  
};
 
548 +

 
549 +
template< typename Derived >
 
550 +
execution_context::
 
551 +
execution_context( Derived* ) noexcept
 
552 +
    : execution_context()
 
553 +
{
 
554 +
    ti_ = &detail::type_id< Derived >();
 
555 +
}
513  

556  

514  
} // namespace capy
557  
} // namespace capy
515  
} // namespace boost
558  
} // namespace boost
516  

559  

517  
#endif
560  
#endif