diff options
Diffstat (limited to '3rdparty/asio/src/examples/cpp20/operations')
10 files changed, 2393 insertions, 0 deletions
diff --git a/3rdparty/asio/src/examples/cpp20/operations/c_callback_wrapper.cpp b/3rdparty/asio/src/examples/cpp20/operations/c_callback_wrapper.cpp new file mode 100644 index 00000000000..f4fbe2617ea --- /dev/null +++ b/3rdparty/asio/src/examples/cpp20/operations/c_callback_wrapper.cpp @@ -0,0 +1,232 @@ +// +// c_callback_wrapper.cpp +// ~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#include <asio.hpp> +#include <iostream> +#include <memory> +#include <new> + +//------------------------------------------------------------------------------ + +// This is a mock implementation of a C-based API that uses the function pointer +// plus void* context idiom for exposing a callback. + +void read_input(const char* prompt, void (*cb)(void*, const char*), void* arg) +{ + std::thread( + [prompt = std::string(prompt), cb, arg] + { + std::cout << prompt << ": "; + std::cout.flush(); + std::string line; + std::getline(std::cin, line); + cb(arg, line.c_str()); + }).detach(); +} + +//------------------------------------------------------------------------------ + +// This is an asynchronous operation that wraps the C-based API. + +// To map our completion handler into a function pointer / void* callback, we +// need to allocate some state that will live for the duration of the +// operation. A pointer to this state will be passed to the C-based API. +template <asio::completion_handler_for<void(std::string)> Handler> +class read_input_state +{ +public: + read_input_state(Handler&& handler) + : handler_(std::move(handler)), + work_(asio::make_work_guard(handler_)) + { + } + + // Create the state using the handler's associated allocator. + static read_input_state* create(Handler&& handler) + { + // A unique_ptr deleter that is used to destroy uninitialised objects. + struct deleter + { + // Get the handler's associated allocator type. If the handler does not + // specify an associated allocator, we will use a recycling allocator as + // the default. As the associated allocator is a proto-allocator, we must + // rebind it to the correct type before we can use it to allocate objects. + typename std::allocator_traits< + asio::associated_allocator_t<Handler, + asio::recycling_allocator<void>>>::template + rebind_alloc<read_input_state> alloc; + + void operator()(read_input_state* ptr) + { + std::allocator_traits<decltype(alloc)>::deallocate(alloc, ptr, 1); + } + } d{asio::get_associated_allocator(handler, + asio::recycling_allocator<void>())}; + + // Allocate memory for the state. + std::unique_ptr<read_input_state, deleter> uninit_ptr( + std::allocator_traits<decltype(d.alloc)>::allocate(d.alloc, 1), d); + + // Construct the state into the newly allocated memory. This might throw. + read_input_state* ptr = + new (uninit_ptr.get()) read_input_state(std::move(handler)); + + // Release ownership of the memory and return the newly allocated state. + uninit_ptr.release(); + return ptr; + } + + static void callback(void* arg, const char* result) + { + read_input_state* self = static_cast<read_input_state*>(arg); + + // A unique_ptr deleter that is used to destroy initialised objects. + struct deleter + { + // Get the handler's associated allocator type. If the handler does not + // specify an associated allocator, we will use a recycling allocator as + // the default. As the associated allocator is a proto-allocator, we must + // rebind it to the correct type before we can use it to allocate objects. + typename std::allocator_traits< + asio::associated_allocator_t<Handler, + asio::recycling_allocator<void>>>::template + rebind_alloc<read_input_state> alloc; + + void operator()(read_input_state* ptr) + { + std::allocator_traits<decltype(alloc)>::destroy(alloc, ptr); + std::allocator_traits<decltype(alloc)>::deallocate(alloc, ptr, 1); + } + } d{asio::get_associated_allocator(self->handler_, + asio::recycling_allocator<void>())}; + + // To conform to the rules regarding asynchronous operations and memory + // allocation, we must make a copy of the state and deallocate the memory + // before dispatching the completion handler. + std::unique_ptr<read_input_state, deleter> state_ptr(self, d); + read_input_state state(std::move(*self)); + state_ptr.reset(); + + // Dispatch the completion handler through the handler's associated + // executor, using the handler's associated allocator. + asio::dispatch(state.work_.get_executor(), + asio::bind_allocator(d.alloc, + [ + handler = std::move(state.handler_), + result = std::string(result) + ]() mutable + { + std::move(handler)(result); + })); + } + +private: + Handler handler_; + + // According to the rules for asynchronous operations, we need to track + // outstanding work against the handler's associated executor until the + // asynchronous operation is complete. + asio::executor_work_guard< + asio::associated_executor_t<Handler>> work_; +}; + +// The initiating function for the asynchronous operation. +template <asio::completion_token_for<void(std::string)> CompletionToken> +auto async_read_input(const std::string& prompt, CompletionToken&& token) +{ + // Define a function object that contains the code to launch the asynchronous + // operation. This is passed the concrete completion handler, followed by any + // additional arguments that were passed through the call to async_initiate. + auto init = []( + asio::completion_handler_for<void(std::string)> auto handler, + const std::string& prompt) + { + // The body of the initiation function object creates the long-lived state + // and passes it to the C-based API, along with the function pointer. + using state_type = read_input_state<decltype(handler)>; + read_input(prompt.c_str(), &state_type::callback, + state_type::create(std::move(handler))); + }; + + // The async_initiate function is used to transform the supplied completion + // token to the completion handler. When calling this function we explicitly + // specify the completion signature of the operation. We must also return the + // result of the call since the completion token may produce a return value, + // such as a future. + return asio::async_initiate<CompletionToken, void(std::string)>( + init, // First, pass the function object that launches the operation, + token, // then the completion token that will be transformed to a handler, + prompt); // and, finally, any additional arguments to the function object. +} + +//------------------------------------------------------------------------------ + +void test_callback() +{ + asio::io_context io_context; + + // Test our asynchronous operation using a lambda as a callback. We will use + // an io_context to obtain an associated executor. + async_read_input("Enter your name", + asio::bind_executor(io_context, + [](const std::string& result) + { + std::cout << "Hello " << result << "\n"; + })); + + io_context.run(); +} + +//------------------------------------------------------------------------------ + +void test_deferred() +{ + asio::io_context io_context; + + // Test our asynchronous operation using the deferred completion token. This + // token causes the operation's initiating function to package up the + // operation with its arguments to return a function object, which may then be + // used to launch the asynchronous operation. + auto op = async_read_input("Enter your name", asio::deferred); + + // Launch our asynchronous operation using a lambda as a callback. We will use + // an io_context to obtain an associated executor. + std::move(op)( + asio::bind_executor(io_context, + [](const std::string& result) + { + std::cout << "Hello " << result << "\n"; + })); + + io_context.run(); +} + +//------------------------------------------------------------------------------ + +void test_future() +{ + // Test our asynchronous operation using the use_future completion token. + // This token causes the operation's initiating function to return a future, + // which may be used to synchronously wait for the result of the operation. + std::future<std::string> f = + async_read_input("Enter your name", asio::use_future); + + std::string result = f.get(); + std::cout << "Hello " << result << "\n"; +} + +//------------------------------------------------------------------------------ + +int main() +{ + test_callback(); + test_deferred(); + test_future(); +} diff --git a/3rdparty/asio/src/examples/cpp20/operations/callback_wrapper.cpp b/3rdparty/asio/src/examples/cpp20/operations/callback_wrapper.cpp new file mode 100644 index 00000000000..f8f37b48944 --- /dev/null +++ b/3rdparty/asio/src/examples/cpp20/operations/callback_wrapper.cpp @@ -0,0 +1,154 @@ +// +// callback_wrapper.cpp +// ~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#include <asio.hpp> +#include <iostream> + +//------------------------------------------------------------------------------ + +// This is a mock implementation of an API that uses a move-only function object +// for exposing a callback. The callback has the signature void(std::string). + +template <typename Callback> +void read_input(const std::string& prompt, Callback cb) +{ + std::thread( + [prompt, cb = std::move(cb)]() mutable + { + std::cout << prompt << ": "; + std::cout.flush(); + std::string line; + std::getline(std::cin, line); + std::move(cb)(std::move(line)); + }).detach(); +} + +//------------------------------------------------------------------------------ + +// This is an asynchronous operation that wraps the callback-based API. + +// The initiating function for the asynchronous operation. +template <asio::completion_token_for<void(std::string)> CompletionToken> +auto async_read_input(const std::string& prompt, CompletionToken&& token) +{ + // Define a function object that contains the code to launch the asynchronous + // operation. This is passed the concrete completion handler, followed by any + // additional arguments that were passed through the call to async_initiate. + auto init = []( + asio::completion_handler_for<void(std::string)> auto handler, + const std::string& prompt) + { + // According to the rules for asynchronous operations, we need to track + // outstanding work against the handler's associated executor until the + // asynchronous operation is complete. + auto work = asio::make_work_guard(handler); + + // Launch the operation with a callback that will receive the result and + // pass it through to the asynchronous operation's completion handler. + read_input(prompt, + [ + handler = std::move(handler), + work = std::move(work) + ](std::string result) mutable + { + // Get the handler's associated allocator. If the handler does not + // specify an allocator, use the recycling allocator as the default. + auto alloc = asio::get_associated_allocator( + handler, asio::recycling_allocator<void>()); + + // Dispatch the completion handler through the handler's associated + // executor, using the handler's associated allocator. + asio::dispatch(work.get_executor(), + asio::bind_allocator(alloc, + [ + handler = std::move(handler), + result = std::string(result) + ]() mutable + { + std::move(handler)(result); + })); + }); + }; + + // The async_initiate function is used to transform the supplied completion + // token to the completion handler. When calling this function we explicitly + // specify the completion signature of the operation. We must also return the + // result of the call since the completion token may produce a return value, + // such as a future. + return asio::async_initiate<CompletionToken, void(std::string)>( + init, // First, pass the function object that launches the operation, + token, // then the completion token that will be transformed to a handler, + prompt); // and, finally, any additional arguments to the function object. +} + +//------------------------------------------------------------------------------ + +void test_callback() +{ + asio::io_context io_context; + + // Test our asynchronous operation using a lambda as a callback. We will use + // an io_context to specify an associated executor. + async_read_input("Enter your name", + asio::bind_executor(io_context, + [](const std::string& result) + { + std::cout << "Hello " << result << "\n"; + })); + + io_context.run(); +} + +//------------------------------------------------------------------------------ + +void test_deferred() +{ + asio::io_context io_context; + + // Test our asynchronous operation using the deferred completion token. This + // token causes the operation's initiating function to package up the + // operation with its arguments to return a function object, which may then be + // used to launch the asynchronous operation. + auto op = async_read_input("Enter your name", asio::deferred); + + // Launch our asynchronous operation using a lambda as a callback. We will use + // an io_context to obtain an associated executor. + std::move(op)( + asio::bind_executor(io_context, + [](const std::string& result) + { + std::cout << "Hello " << result << "\n"; + })); + + io_context.run(); +} + +//------------------------------------------------------------------------------ + +void test_future() +{ + // Test our asynchronous operation using the use_future completion token. + // This token causes the operation's initiating function to return a future, + // which may be used to synchronously wait for the result of the operation. + std::future<std::string> f = + async_read_input("Enter your name", asio::use_future); + + std::string result = f.get(); + std::cout << "Hello " << result << "\n"; +} + +//------------------------------------------------------------------------------ + +int main() +{ + test_callback(); + test_deferred(); + test_future(); +} diff --git a/3rdparty/asio/src/examples/cpp20/operations/composed_1.cpp b/3rdparty/asio/src/examples/cpp20/operations/composed_1.cpp new file mode 100644 index 00000000000..e7f795e1756 --- /dev/null +++ b/3rdparty/asio/src/examples/cpp20/operations/composed_1.cpp @@ -0,0 +1,157 @@ +// +// composed_1.cpp +// ~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#include <asio/deferred.hpp> +#include <asio/io_context.hpp> +#include <asio/ip/tcp.hpp> +#include <asio/use_future.hpp> +#include <asio/write.hpp> +#include <cstring> +#include <iostream> +#include <string> +#include <type_traits> +#include <utility> + +using asio::ip::tcp; + +//------------------------------------------------------------------------------ + +// This is the simplest example of a composed asynchronous operation, where we +// simply repackage an existing operation. The asynchronous operation +// requirements are met by delegating responsibility to the underlying +// operation. + +template < + asio::completion_token_for<void(std::error_code, std::size_t)> + CompletionToken> +auto async_write_message(tcp::socket& socket, + const char* message, CompletionToken&& token) + // The return type of the initiating function is deduced from the combination + // of: + // + // - the CompletionToken type, + // - the completion handler signature, and + // - the asynchronous operation's initiation function object. + // + // When the completion token is a simple callback, the return type is void. + // However, when the completion token is asio::yield_context (used for + // stackful coroutines) the return type would be std::size_t, and when the + // completion token is asio::use_future it would be std::future<std::size_t>. + // When the completion token is asio::deferred, the return type differs for + // each asynchronous operation. + // + // In C++20 we can omit the return type as it is automatically deduced from + // the return type of our underlying asynchronous operation. +{ + // When delegating to the underlying operation we must take care to perfectly + // forward the completion token. This ensures that our operation works + // correctly with move-only function objects as callbacks, as well as other + // completion token types. + return asio::async_write(socket, + asio::buffer(message, std::strlen(message)), + std::forward<CompletionToken>(token)); +} + +//------------------------------------------------------------------------------ + +void test_callback() +{ + asio::io_context io_context; + + tcp::acceptor acceptor(io_context, {tcp::v4(), 55555}); + tcp::socket socket = acceptor.accept(); + + // Test our asynchronous operation using a lambda as a callback. + async_write_message(socket, "Testing callback\r\n", + [](const std::error_code& error, std::size_t n) + { + if (!error) + { + std::cout << n << " bytes transferred\n"; + } + else + { + std::cout << "Error: " << error.message() << "\n"; + } + }); + + io_context.run(); +} + +//------------------------------------------------------------------------------ + +void test_deferred() +{ + asio::io_context io_context; + + tcp::acceptor acceptor(io_context, {tcp::v4(), 55555}); + tcp::socket socket = acceptor.accept(); + + // Test our asynchronous operation using the deferred completion token. This + // token causes the operation's initiating function to package up the + // operation with its arguments to return a function object, which may then be + // used to launch the asynchronous operation. + asio::async_operation auto op = async_write_message( + socket, "Testing deferred\r\n", asio::deferred); + + // Launch the operation using a lambda as a callback. + std::move(op)( + [](const std::error_code& error, std::size_t n) + { + if (!error) + { + std::cout << n << " bytes transferred\n"; + } + else + { + std::cout << "Error: " << error.message() << "\n"; + } + }); + + io_context.run(); +} + +//------------------------------------------------------------------------------ + +void test_future() +{ + asio::io_context io_context; + + tcp::acceptor acceptor(io_context, {tcp::v4(), 55555}); + tcp::socket socket = acceptor.accept(); + + // Test our asynchronous operation using the use_future completion token. + // This token causes the operation's initiating function to return a future, + // which may be used to synchronously wait for the result of the operation. + std::future<std::size_t> f = async_write_message( + socket, "Testing future\r\n", asio::use_future); + + io_context.run(); + + try + { + // Get the result of the operation. + std::size_t n = f.get(); + std::cout << n << " bytes transferred\n"; + } + catch (const std::exception& e) + { + std::cout << "Error: " << e.what() << "\n"; + } +} + +//------------------------------------------------------------------------------ + +int main() +{ + test_callback(); + test_deferred(); + test_future(); +} diff --git a/3rdparty/asio/src/examples/cpp20/operations/composed_2.cpp b/3rdparty/asio/src/examples/cpp20/operations/composed_2.cpp new file mode 100644 index 00000000000..ada029d38f0 --- /dev/null +++ b/3rdparty/asio/src/examples/cpp20/operations/composed_2.cpp @@ -0,0 +1,225 @@ +// +// composed_2.cpp +// ~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#include <asio/deferred.hpp> +#include <asio/io_context.hpp> +#include <asio/ip/tcp.hpp> +#include <asio/use_future.hpp> +#include <asio/write.hpp> +#include <cstring> +#include <iostream> +#include <string> +#include <type_traits> +#include <utility> + +using asio::ip::tcp; + +// NOTE: This example requires the new asio::async_initiate function. For +// an example that works with the Networking TS style of completion tokens, +// please see an older version of asio. + +//------------------------------------------------------------------------------ + +// This next simplest example of a composed asynchronous operation involves +// repackaging multiple operations but choosing to invoke just one of them. All +// of these underlying operations have the same completion signature. The +// asynchronous operation requirements are met by delegating responsibility to +// the underlying operations. + +template < + asio::completion_token_for<void(std::error_code, std::size_t)> + CompletionToken> +auto async_write_message(tcp::socket& socket, + const char* message, bool allow_partial_write, + CompletionToken&& token) + // The return type of the initiating function is deduced from the combination + // of: + // + // - the CompletionToken type, + // - the completion handler signature, and + // - the asynchronous operation's initiation function object. + // + // When the completion token is a simple callback, the return type is void. + // However, when the completion token is asio::yield_context (used for + // stackful coroutines) the return type would be std::size_t, and when the + // completion token is asio::use_future it would be std::future<std::size_t>. + // When the completion token is asio::deferred, the return type differs for + // each asynchronous operation. + // + // In C++20 we can omit the return type as it is automatically deduced from + // the return type of asio::async_initiate. +{ + // In addition to determining the mechanism by which an asynchronous + // operation delivers its result, a completion token also determines the time + // when the operation commences. For example, when the completion token is a + // simple callback the operation commences before the initiating function + // returns. However, if the completion token's delivery mechanism uses a + // future, we might instead want to defer initiation of the operation until + // the returned future object is waited upon. + // + // To enable this, when implementing an asynchronous operation we must + // package the initiation step as a function object. The initiation function + // object's call operator is passed the concrete completion handler produced + // by the completion token. This completion handler matches the asynchronous + // operation's completion handler signature, which in this example is: + // + // void(std::error_code error, std::size_t) + // + // The initiation function object also receives any additional arguments + // required to start the operation. (Note: We could have instead passed these + // arguments in the lambda capture set. However, we should prefer to + // propagate them as function call arguments as this allows the completion + // token to optimise how they are passed. For example, a lazy future which + // defers initiation would need to make a decay-copy of the arguments, but + // when using a simple callback the arguments can be trivially forwarded + // straight through.) + auto initiation = []( + asio::completion_handler_for<void(std::error_code, std::size_t)> + auto&& completion_handler, + tcp::socket& socket, + const char* message, + bool allow_partial_write) + { + if (allow_partial_write) + { + // When delegating to an underlying operation we must take care to + // perfectly forward the completion handler. This ensures that our + // operation works correctly with move-only function objects as + // callbacks. + return socket.async_write_some( + asio::buffer(message, std::strlen(message)), + std::forward<decltype(completion_handler)>(completion_handler)); + } + else + { + // As above, we must perfectly forward the completion handler when calling + // the alternate underlying operation. + return asio::async_write(socket, + asio::buffer(message, std::strlen(message)), + std::forward<decltype(completion_handler)>(completion_handler)); + } + }; + + // The asio::async_initiate function takes: + // + // - our initiation function object, + // - the completion token, + // - the completion handler signature, and + // - any additional arguments we need to initiate the operation. + // + // It then asks the completion token to create a completion handler (i.e. a + // callback) with the specified signature, and invoke the initiation function + // object with this completion handler as well as the additional arguments. + // The return value of async_initiate is the result of our operation's + // initiating function. + // + // Note that we wrap non-const reference arguments in std::reference_wrapper + // to prevent incorrect decay-copies of these objects. + return asio::async_initiate< + CompletionToken, void(std::error_code, std::size_t)>( + initiation, token, std::ref(socket), message, allow_partial_write); +} + +//------------------------------------------------------------------------------ + +void test_callback() +{ + asio::io_context io_context; + + tcp::acceptor acceptor(io_context, {tcp::v4(), 55555}); + tcp::socket socket = acceptor.accept(); + + // Test our asynchronous operation using a lambda as a callback. + async_write_message(socket, "Testing callback\r\n", false, + [](const std::error_code& error, std::size_t n) + { + if (!error) + { + std::cout << n << " bytes transferred\n"; + } + else + { + std::cout << "Error: " << error.message() << "\n"; + } + }); + + io_context.run(); +} + +//------------------------------------------------------------------------------ + +void test_deferred() +{ + asio::io_context io_context; + + tcp::acceptor acceptor(io_context, {tcp::v4(), 55555}); + tcp::socket socket = acceptor.accept(); + + // Test our asynchronous operation using the deferred completion token. This + // token causes the operation's initiating function to package up the + // operation with its arguments to return a function object, which may then be + // used to launch the asynchronous operation. + asio::async_operation auto op = async_write_message( + socket, "Testing deferred\r\n", false, asio::deferred); + + // Launch the operation using a lambda as a callback. + std::move(op)( + [](const std::error_code& error, std::size_t n) + { + if (!error) + { + std::cout << n << " bytes transferred\n"; + } + else + { + std::cout << "Error: " << error.message() << "\n"; + } + }); + + io_context.run(); +} + +//------------------------------------------------------------------------------ + +void test_future() +{ + asio::io_context io_context; + + tcp::acceptor acceptor(io_context, {tcp::v4(), 55555}); + tcp::socket socket = acceptor.accept(); + + // Test our asynchronous operation using the use_future completion token. + // This token causes the operation's initiating function to return a future, + // which may be used to synchronously wait for the result of the operation. + std::future<std::size_t> f = async_write_message( + socket, "Testing future\r\n", false, asio::use_future); + + io_context.run(); + + try + { + // Get the result of the operation. + std::size_t n = f.get(); + std::cout << n << " bytes transferred\n"; + } + catch (const std::exception& e) + { + std::cout << "Error: " << e.what() << "\n"; + } +} + +//------------------------------------------------------------------------------ + +int main() +{ + test_callback(); + test_deferred(); + test_future(); +} diff --git a/3rdparty/asio/src/examples/cpp20/operations/composed_3.cpp b/3rdparty/asio/src/examples/cpp20/operations/composed_3.cpp new file mode 100644 index 00000000000..46436a68e28 --- /dev/null +++ b/3rdparty/asio/src/examples/cpp20/operations/composed_3.cpp @@ -0,0 +1,232 @@ +// +// composed_3.cpp +// ~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#include <asio/bind_executor.hpp> +#include <asio/deferred.hpp> +#include <asio/io_context.hpp> +#include <asio/ip/tcp.hpp> +#include <asio/use_future.hpp> +#include <asio/write.hpp> +#include <cstring> +#include <functional> +#include <iostream> +#include <string> +#include <type_traits> +#include <utility> + +using asio::ip::tcp; + +// NOTE: This example requires the new asio::async_initiate function. For +// an example that works with the Networking TS style of completion tokens, +// please see an older version of asio. + +//------------------------------------------------------------------------------ + +// In this composed operation we repackage an existing operation, but with a +// different completion handler signature. The asynchronous operation +// requirements are met by delegating responsibility to the underlying +// operation. + +template < + asio::completion_token_for<void(std::error_code)> CompletionToken> +auto async_write_message(tcp::socket& socket, + const char* message, CompletionToken&& token) + // The return type of the initiating function is deduced from the combination + // of: + // + // - the CompletionToken type, + // - the completion handler signature, and + // - the asynchronous operation's initiation function object. + // + // When the completion token is a simple callback, the return type is always + // void. In this example, when the completion token is asio::yield_context + // (used for stackful coroutines) the return type would also be void, as + // there is no non-error argument to the completion handler. When the + // completion token is asio::use_future it would be std::future<void>. When + // the completion token is asio::deferred, the return type differs for each + // asynchronous operation. + // + // In C++20 we can omit the return type as it is automatically deduced from + // the return type of asio::async_initiate. +{ + // In addition to determining the mechanism by which an asynchronous + // operation delivers its result, a completion token also determines the time + // when the operation commences. For example, when the completion token is a + // simple callback the operation commences before the initiating function + // returns. However, if the completion token's delivery mechanism uses a + // future, we might instead want to defer initiation of the operation until + // the returned future object is waited upon. + // + // To enable this, when implementing an asynchronous operation we must + // package the initiation step as a function object. The initiation function + // object's call operator is passed the concrete completion handler produced + // by the completion token. This completion handler matches the asynchronous + // operation's completion handler signature, which in this example is: + // + // void(std::error_code error) + // + // The initiation function object also receives any additional arguments + // required to start the operation. (Note: We could have instead passed these + // arguments in the lambda capture set. However, we should prefer to + // propagate them as function call arguments as this allows the completion + // token to optimise how they are passed. For example, a lazy future which + // defers initiation would need to make a decay-copy of the arguments, but + // when using a simple callback the arguments can be trivially forwarded + // straight through.) + auto initiation = []( + asio::completion_handler_for<void(std::error_code)> + auto&& completion_handler, + tcp::socket& socket, + const char* message) + { + // The async_write operation has a completion handler signature of: + // + // void(std::error_code error, std::size n) + // + // This differs from our operation's signature in that it is also passed + // the number of bytes transferred as an argument of type std::size_t. We + // will adapt our completion handler to async_write's completion handler + // signature by using std::bind, which drops the additional argument. + // + // However, it is essential to the correctness of our composed operation + // that we preserve the executor of the user-supplied completion handler. + // The std::bind function will not do this for us, so we must do this by + // first obtaining the completion handler's associated executor (defaulting + // to the I/O executor - in this case the executor of the socket - if the + // completion handler does not have its own) ... + auto executor = asio::get_associated_executor( + completion_handler, socket.get_executor()); + + // ... and then binding this executor to our adapted completion handler + // using the asio::bind_executor function. + asio::async_write(socket, + asio::buffer(message, std::strlen(message)), + asio::bind_executor(executor, + std::bind(std::forward<decltype(completion_handler)>( + completion_handler), std::placeholders::_1))); + }; + + // The asio::async_initiate function takes: + // + // - our initiation function object, + // - the completion token, + // - the completion handler signature, and + // - any additional arguments we need to initiate the operation. + // + // It then asks the completion token to create a completion handler (i.e. a + // callback) with the specified signature, and invoke the initiation function + // object with this completion handler as well as the additional arguments. + // The return value of async_initiate is the result of our operation's + // initiating function. + // + // Note that we wrap non-const reference arguments in std::reference_wrapper + // to prevent incorrect decay-copies of these objects. + return asio::async_initiate< + CompletionToken, void(std::error_code)>( + initiation, token, std::ref(socket), message); +} + +//------------------------------------------------------------------------------ + +void test_callback() +{ + asio::io_context io_context; + + tcp::acceptor acceptor(io_context, {tcp::v4(), 55555}); + tcp::socket socket = acceptor.accept(); + + // Test our asynchronous operation using a lambda as a callback. + async_write_message(socket, "Testing callback\r\n", + [](const std::error_code& error) + { + if (!error) + { + std::cout << "Message sent\n"; + } + else + { + std::cout << "Error: " << error.message() << "\n"; + } + }); + + io_context.run(); +} + +//------------------------------------------------------------------------------ + +void test_deferred() +{ + asio::io_context io_context; + + tcp::acceptor acceptor(io_context, {tcp::v4(), 55555}); + tcp::socket socket = acceptor.accept(); + + // Test our asynchronous operation using the deferred completion token. This + // token causes the operation's initiating function to package up the + // operation with its arguments to return a function object, which may then be + // used to launch the asynchronous operation. + asio::async_operation auto op = async_write_message( + socket, "Testing deferred\r\n", asio::deferred); + + // Launch the operation using a lambda as a callback. + std::move(op)( + [](const std::error_code& error) + { + if (!error) + { + std::cout << "Message sent\n"; + } + else + { + std::cout << "Error: " << error.message() << "\n"; + } + }); + + io_context.run(); +} + +//------------------------------------------------------------------------------ + +void test_future() +{ + asio::io_context io_context; + + tcp::acceptor acceptor(io_context, {tcp::v4(), 55555}); + tcp::socket socket = acceptor.accept(); + + // Test our asynchronous operation using the use_future completion token. + // This token causes the operation's initiating function to return a future, + // which may be used to synchronously wait for the result of the operation. + std::future<void> f = async_write_message( + socket, "Testing future\r\n", asio::use_future); + + io_context.run(); + + // Get the result of the operation. + try + { + // Get the result of the operation. + f.get(); + std::cout << "Message sent\n"; + } + catch (const std::exception& e) + { + std::cout << "Error: " << e.what() << "\n"; + } +} + +//------------------------------------------------------------------------------ + +int main() +{ + test_callback(); + test_deferred(); + test_future(); +} diff --git a/3rdparty/asio/src/examples/cpp20/operations/composed_4.cpp b/3rdparty/asio/src/examples/cpp20/operations/composed_4.cpp new file mode 100644 index 00000000000..069f57ce1ac --- /dev/null +++ b/3rdparty/asio/src/examples/cpp20/operations/composed_4.cpp @@ -0,0 +1,247 @@ +// +// composed_4.cpp +// ~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#include <asio/bind_executor.hpp> +#include <asio/deferred.hpp> +#include <asio/io_context.hpp> +#include <asio/ip/tcp.hpp> +#include <asio/use_future.hpp> +#include <asio/write.hpp> +#include <cstring> +#include <functional> +#include <iostream> +#include <string> +#include <type_traits> +#include <utility> + +using asio::ip::tcp; + +// NOTE: This example requires the new asio::async_initiate function. For +// an example that works with the Networking TS style of completion tokens, +// please see an older version of asio. + +//------------------------------------------------------------------------------ + +// In this composed operation we repackage an existing operation, but with a +// different completion handler signature. We will also intercept an empty +// message as an invalid argument, and propagate the corresponding error to the +// user. The asynchronous operation requirements are met by delegating +// responsibility to the underlying operation. + +template < + asio::completion_token_for<void(std::error_code)> CompletionToken> +auto async_write_message(tcp::socket& socket, + const char* message, CompletionToken&& token) + // The return type of the initiating function is deduced from the combination + // of: + // + // - the CompletionToken type, + // - the completion handler signature, and + // - the asynchronous operation's initiation function object. + // + // When the completion token is a simple callback, the return type is always + // void. In this example, when the completion token is asio::yield_context + // (used for stackful coroutines) the return type would also be void, as + // there is no non-error argument to the completion handler. When the + // completion token is asio::use_future it would be std::future<void>. When + // the completion token is asio::deferred, the return type differs for each + // asynchronous operation. + // + // In C++20 we can omit the return type as it is automatically deduced from + // the return type of asio::async_initiate. +{ + // In addition to determining the mechanism by which an asynchronous + // operation delivers its result, a completion token also determines the time + // when the operation commences. For example, when the completion token is a + // simple callback the operation commences before the initiating function + // returns. However, if the completion token's delivery mechanism uses a + // future, we might instead want to defer initiation of the operation until + // the returned future object is waited upon. + // + // To enable this, when implementing an asynchronous operation we must + // package the initiation step as a function object. The initiation function + // object's call operator is passed the concrete completion handler produced + // by the completion token. This completion handler matches the asynchronous + // operation's completion handler signature, which in this example is: + // + // void(std::error_code error) + // + // The initiation function object also receives any additional arguments + // required to start the operation. (Note: We could have instead passed these + // arguments in the lambda capture set. However, we should prefer to + // propagate them as function call arguments as this allows the completion + // token to optimise how they are passed. For example, a lazy future which + // defers initiation would need to make a decay-copy of the arguments, but + // when using a simple callback the arguments can be trivially forwarded + // straight through.) + auto initiation = []( + asio::completion_handler_for<void(std::error_code)> + auto&& completion_handler, + tcp::socket& socket, + const char* message) + { + // The post operation has a completion handler signature of: + // + // void() + // + // and the async_write operation has a completion handler signature of: + // + // void(std::error_code error, std::size n) + // + // Both of these operations' completion handler signatures differ from our + // operation's completion handler signature. We will adapt our completion + // handler to these signatures by using std::bind, which drops the + // additional arguments. + // + // However, it is essential to the correctness of our composed operation + // that we preserve the executor of the user-supplied completion handler. + // The std::bind function will not do this for us, so we must do this by + // first obtaining the completion handler's associated executor (defaulting + // to the I/O executor - in this case the executor of the socket - if the + // completion handler does not have its own) ... + auto executor = asio::get_associated_executor( + completion_handler, socket.get_executor()); + + // ... and then binding this executor to our adapted completion handler + // using the asio::bind_executor function. + std::size_t length = std::strlen(message); + if (length == 0) + { + asio::post( + asio::bind_executor(executor, + std::bind(std::forward<decltype(completion_handler)>( + completion_handler), asio::error::invalid_argument))); + } + else + { + asio::async_write(socket, + asio::buffer(message, length), + asio::bind_executor(executor, + std::bind(std::forward<decltype(completion_handler)>( + completion_handler), std::placeholders::_1))); + } + }; + + // The asio::async_initiate function takes: + // + // - our initiation function object, + // - the completion token, + // - the completion handler signature, and + // - any additional arguments we need to initiate the operation. + // + // It then asks the completion token to create a completion handler (i.e. a + // callback) with the specified signature, and invoke the initiation function + // object with this completion handler as well as the additional arguments. + // The return value of async_initiate is the result of our operation's + // initiating function. + // + // Note that we wrap non-const reference arguments in std::reference_wrapper + // to prevent incorrect decay-copies of these objects. + return asio::async_initiate< + CompletionToken, void(std::error_code)>( + initiation, token, std::ref(socket), message); +} + +//------------------------------------------------------------------------------ + +void test_callback() +{ + asio::io_context io_context; + + tcp::acceptor acceptor(io_context, {tcp::v4(), 55555}); + tcp::socket socket = acceptor.accept(); + + // Test our asynchronous operation using a lambda as a callback. + async_write_message(socket, "", + [](const std::error_code& error) + { + if (!error) + { + std::cout << "Message sent\n"; + } + else + { + std::cout << "Error: " << error.message() << "\n"; + } + }); + + io_context.run(); +} + +//------------------------------------------------------------------------------ + +void test_deferred() +{ + asio::io_context io_context; + + tcp::acceptor acceptor(io_context, {tcp::v4(), 55555}); + tcp::socket socket = acceptor.accept(); + + // Test our asynchronous operation using the deferred completion token. This + // token causes the operation's initiating function to package up the + // operation with its arguments to return a function object, which may then be + // used to launch the asynchronous operation. + asio::async_operation auto op = + async_write_message(socket, "", asio::deferred); + + // Launch the operation using a lambda as a callback. + std::move(op)( + [](const std::error_code& error) + { + if (!error) + { + std::cout << "Message sent\n"; + } + else + { + std::cout << "Error: " << error.message() << "\n"; + } + }); + + io_context.run(); +} + +//------------------------------------------------------------------------------ + +void test_future() +{ + asio::io_context io_context; + + tcp::acceptor acceptor(io_context, {tcp::v4(), 55555}); + tcp::socket socket = acceptor.accept(); + + // Test our asynchronous operation using the use_future completion token. + // This token causes the operation's initiating function to return a future, + // which may be used to synchronously wait for the result of the operation. + std::future<void> f = async_write_message( + socket, "", asio::use_future); + + io_context.run(); + + try + { + // Get the result of the operation. + f.get(); + std::cout << "Message sent\n"; + } + catch (const std::exception& e) + { + std::cout << "Exception: " << e.what() << "\n"; + } +} + +//------------------------------------------------------------------------------ + +int main() +{ + test_callback(); + test_deferred(); + test_future(); +} diff --git a/3rdparty/asio/src/examples/cpp20/operations/composed_5.cpp b/3rdparty/asio/src/examples/cpp20/operations/composed_5.cpp new file mode 100644 index 00000000000..bec83ec3a59 --- /dev/null +++ b/3rdparty/asio/src/examples/cpp20/operations/composed_5.cpp @@ -0,0 +1,284 @@ +// +// composed_5.cpp +// ~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#include <asio/deferred.hpp> +#include <asio/io_context.hpp> +#include <asio/ip/tcp.hpp> +#include <asio/use_future.hpp> +#include <asio/write.hpp> +#include <functional> +#include <iostream> +#include <memory> +#include <sstream> +#include <string> +#include <type_traits> +#include <utility> + +using asio::ip::tcp; + +// NOTE: This example requires the new asio::async_initiate function. For +// an example that works with the Networking TS style of completion tokens, +// please see an older version of asio. + +//------------------------------------------------------------------------------ + +// This composed operation automatically serialises a message, using its I/O +// streams insertion operator, before sending it on the socket. To do this, it +// must allocate a buffer for the encoded message and ensure this buffer's +// validity until the underlying async_write operation completes. + +template <typename T, + asio::completion_token_for<void(std::error_code)> CompletionToken> +auto async_write_message(tcp::socket& socket, + const T& message, CompletionToken&& token) + // The return type of the initiating function is deduced from the combination + // of: + // + // - the CompletionToken type, + // - the completion handler signature, and + // - the asynchronous operation's initiation function object. + // + // When the completion token is a simple callback, the return type is always + // void. In this example, when the completion token is asio::yield_context + // (used for stackful coroutines) the return type would also be void, as + // there is no non-error argument to the completion handler. When the + // completion token is asio::use_future it would be std::future<void>. When + // the completion token is asio::deferred, the return type differs for each + // asynchronous operation. + // + // In C++20 we can omit the return type as it is automatically deduced from + // the return type of asio::async_initiate. +{ + // In addition to determining the mechanism by which an asynchronous + // operation delivers its result, a completion token also determines the time + // when the operation commences. For example, when the completion token is a + // simple callback the operation commences before the initiating function + // returns. However, if the completion token's delivery mechanism uses a + // future, we might instead want to defer initiation of the operation until + // the returned future object is waited upon. + // + // To enable this, when implementing an asynchronous operation we must + // package the initiation step as a function object. The initiation function + // object's call operator is passed the concrete completion handler produced + // by the completion token. This completion handler matches the asynchronous + // operation's completion handler signature, which in this example is: + // + // void(std::error_code error) + // + // The initiation function object also receives any additional arguments + // required to start the operation. (Note: We could have instead passed these + // arguments in the lambda capture set. However, we should prefer to + // propagate them as function call arguments as this allows the completion + // token to optimise how they are passed. For example, a lazy future which + // defers initiation would need to make a decay-copy of the arguments, but + // when using a simple callback the arguments can be trivially forwarded + // straight through.) + auto initiation = []( + asio::completion_handler_for<void(std::error_code)> + auto&& completion_handler, + tcp::socket& socket, + std::unique_ptr<std::string> encoded_message) + { + // In this example, the composed operation's intermediate completion + // handler is implemented as a hand-crafted function object, rather than + // using a lambda or std::bind. + struct intermediate_completion_handler + { + // The intermediate completion handler holds a reference to the socket so + // that it can obtain the I/O executor (see get_executor below). + tcp::socket& socket_; + + // The allocated buffer for the encoded message. The std::unique_ptr + // smart pointer is move-only, and as a consequence our intermediate + // completion handler is also move-only. + std::unique_ptr<std::string> encoded_message_; + + // The user-supplied completion handler. + typename std::decay<decltype(completion_handler)>::type handler_; + + // The function call operator matches the completion signature of the + // async_write operation. + void operator()(const std::error_code& error, std::size_t /*n*/) + { + // Deallocate the encoded message before calling the user-supplied + // completion handler. + encoded_message_.reset(); + + // Call the user-supplied handler with the result of the operation. + // The arguments must match the completion signature of our composed + // operation. + handler_(error); + } + + // It is essential to the correctness of our composed operation that we + // preserve the executor of the user-supplied completion handler. With a + // hand-crafted function object we can do this by defining a nested type + // executor_type and member function get_executor. These obtain the + // completion handler's associated executor, and default to the I/O + // executor - in this case the executor of the socket - if the completion + // handler does not have its own. + using executor_type = asio::associated_executor_t< + typename std::decay<decltype(completion_handler)>::type, + tcp::socket::executor_type>; + + executor_type get_executor() const noexcept + { + return asio::get_associated_executor( + handler_, socket_.get_executor()); + } + + // Although not necessary for correctness, we may also preserve the + // allocator of the user-supplied completion handler. This is achieved by + // defining a nested type allocator_type and member function + // get_allocator. These obtain the completion handler's associated + // allocator, and default to std::allocator<void> if the completion + // handler does not have its own. + using allocator_type = asio::associated_allocator_t< + typename std::decay<decltype(completion_handler)>::type, + std::allocator<void>>; + + allocator_type get_allocator() const noexcept + { + return asio::get_associated_allocator( + handler_, std::allocator<void>{}); + } + }; + + // Initiate the underlying async_write operation using our intermediate + // completion handler. + auto encoded_message_buffer = asio::buffer(*encoded_message); + asio::async_write(socket, encoded_message_buffer, + intermediate_completion_handler{socket, std::move(encoded_message), + std::forward<decltype(completion_handler)>(completion_handler)}); + }; + + // Encode the message and copy it into an allocated buffer. The buffer will + // be maintained for the lifetime of the asynchronous operation. + std::ostringstream os; + os << message; + std::unique_ptr<std::string> encoded_message(new std::string(os.str())); + + // The asio::async_initiate function takes: + // + // - our initiation function object, + // - the completion token, + // - the completion handler signature, and + // - any additional arguments we need to initiate the operation. + // + // It then asks the completion token to create a completion handler (i.e. a + // callback) with the specified signature, and invoke the initiation function + // object with this completion handler as well as the additional arguments. + // The return value of async_initiate is the result of our operation's + // initiating function. + // + // Note that we wrap non-const reference arguments in std::reference_wrapper + // to prevent incorrect decay-copies of these objects. + return asio::async_initiate< + CompletionToken, void(std::error_code)>( + initiation, token, std::ref(socket), + std::move(encoded_message)); +} + +//------------------------------------------------------------------------------ + +void test_callback() +{ + asio::io_context io_context; + + tcp::acceptor acceptor(io_context, {tcp::v4(), 55555}); + tcp::socket socket = acceptor.accept(); + + // Test our asynchronous operation using a lambda as a callback. + async_write_message(socket, 123456, + [](const std::error_code& error) + { + if (!error) + { + std::cout << "Message sent\n"; + } + else + { + std::cout << "Error: " << error.message() << "\n"; + } + }); + + io_context.run(); +} + +//------------------------------------------------------------------------------ + +void test_deferred() +{ + asio::io_context io_context; + + tcp::acceptor acceptor(io_context, {tcp::v4(), 55555}); + tcp::socket socket = acceptor.accept(); + + // Test our asynchronous operation using the deferred completion token. This + // token causes the operation's initiating function to package up the + // operation with its arguments to return a function object, which may then be + // used to launch the asynchronous operation. + asio::async_operation auto op = async_write_message( + socket, std::string("abcdef"), asio::deferred); + + // Launch the operation using a lambda as a callback. + std::move(op)( + [](const std::error_code& error) + { + if (!error) + { + std::cout << "Message sent\n"; + } + else + { + std::cout << "Error: " << error.message() << "\n"; + } + }); + + io_context.run(); +} + +//------------------------------------------------------------------------------ + +void test_future() +{ + asio::io_context io_context; + + tcp::acceptor acceptor(io_context, {tcp::v4(), 55555}); + tcp::socket socket = acceptor.accept(); + + // Test our asynchronous operation using the use_future completion token. + // This token causes the operation's initiating function to return a future, + // which may be used to synchronously wait for the result of the operation. + std::future<void> f = async_write_message( + socket, 654.321, asio::use_future); + + io_context.run(); + + try + { + // Get the result of the operation. + f.get(); + std::cout << "Message sent\n"; + } + catch (const std::exception& e) + { + std::cout << "Exception: " << e.what() << "\n"; + } +} + +//------------------------------------------------------------------------------ + +int main() +{ + test_callback(); + test_deferred(); + test_future(); +} diff --git a/3rdparty/asio/src/examples/cpp20/operations/composed_6.cpp b/3rdparty/asio/src/examples/cpp20/operations/composed_6.cpp new file mode 100644 index 00000000000..77e2f50f93e --- /dev/null +++ b/3rdparty/asio/src/examples/cpp20/operations/composed_6.cpp @@ -0,0 +1,345 @@ +// +// composed_6.cpp +// ~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#include <asio/deferred.hpp> +#include <asio/executor_work_guard.hpp> +#include <asio/io_context.hpp> +#include <asio/ip/tcp.hpp> +#include <asio/steady_timer.hpp> +#include <asio/use_future.hpp> +#include <asio/write.hpp> +#include <functional> +#include <iostream> +#include <memory> +#include <sstream> +#include <string> +#include <type_traits> +#include <utility> + +using asio::ip::tcp; + +// NOTE: This example requires the new asio::async_initiate function. For +// an example that works with the Networking TS style of completion tokens, +// please see an older version of asio. + +//------------------------------------------------------------------------------ + +// This composed operation shows composition of multiple underlying operations. +// It automatically serialises a message, using its I/O streams insertion +// operator, before sending it N times on the socket. To do this, it must +// allocate a buffer for the encoded message and ensure this buffer's validity +// until all underlying async_write operation complete. A one second delay is +// inserted prior to each write operation, using a steady_timer. + +template <typename T, + asio::completion_token_for<void(std::error_code)> CompletionToken> +auto async_write_messages(tcp::socket& socket, + const T& message, std::size_t repeat_count, + CompletionToken&& token) + // The return type of the initiating function is deduced from the combination + // of: + // + // - the CompletionToken type, + // - the completion handler signature, and + // - the asynchronous operation's initiation function object. + // + // When the completion token is a simple callback, the return type is always + // void. In this example, when the completion token is asio::yield_context + // (used for stackful coroutines) the return type would also be void, as + // there is no non-error argument to the completion handler. When the + // completion token is asio::use_future it would be std::future<void>. When + // the completion token is asio::deferred, the return type differs for each + // asynchronous operation. + // + // In C++20 we can omit the return type as it is automatically deduced from + // the return type of asio::async_initiate. +{ + // In addition to determining the mechanism by which an asynchronous + // operation delivers its result, a completion token also determines the time + // when the operation commences. For example, when the completion token is a + // simple callback the operation commences before the initiating function + // returns. However, if the completion token's delivery mechanism uses a + // future, we might instead want to defer initiation of the operation until + // the returned future object is waited upon. + // + // To enable this, when implementing an asynchronous operation we must + // package the initiation step as a function object. The initiation function + // object's call operator is passed the concrete completion handler produced + // by the completion token. This completion handler matches the asynchronous + // operation's completion handler signature, which in this example is: + // + // void(std::error_code error) + // + // The initiation function object also receives any additional arguments + // required to start the operation. (Note: We could have instead passed these + // arguments in the lambda capture set. However, we should prefer to + // propagate them as function call arguments as this allows the completion + // token to optimise how they are passed. For example, a lazy future which + // defers initiation would need to make a decay-copy of the arguments, but + // when using a simple callback the arguments can be trivially forwarded + // straight through.) + auto initiation = []( + asio::completion_handler_for<void(std::error_code)> + auto&& completion_handler, + tcp::socket& socket, + std::unique_ptr<std::string> encoded_message, + std::size_t repeat_count, + std::unique_ptr<asio::steady_timer> delay_timer) + { + // In this example, the composed operation's intermediate completion + // handler is implemented as a hand-crafted function object. + struct intermediate_completion_handler + { + // The intermediate completion handler holds a reference to the socket as + // it is used for multiple async_write operations, as well as for + // obtaining the I/O executor (see get_executor below). + tcp::socket& socket_; + + // The allocated buffer for the encoded message. The std::unique_ptr + // smart pointer is move-only, and as a consequence our intermediate + // completion handler is also move-only. + std::unique_ptr<std::string> encoded_message_; + + // The repeat count remaining. + std::size_t repeat_count_; + + // A steady timer used for introducing a delay. + std::unique_ptr<asio::steady_timer> delay_timer_; + + // To manage the cycle between the multiple underlying asychronous + // operations, our intermediate completion handler is implemented as a + // state machine. + enum { starting, waiting, writing } state_; + + // As our composed operation performs multiple underlying I/O operations, + // we should maintain a work object against the I/O executor. This tells + // the I/O executor that there is still more work to come in the future. + asio::executor_work_guard<tcp::socket::executor_type> io_work_; + + // The user-supplied completion handler, called once only on completion + // of the entire composed operation. + typename std::decay<decltype(completion_handler)>::type handler_; + + // By having a default value for the second argument, this function call + // operator matches the completion signature of both the async_write and + // steady_timer::async_wait operations. + void operator()(const std::error_code& error, std::size_t = 0) + { + if (!error) + { + switch (state_) + { + case starting: + case writing: + if (repeat_count_ > 0) + { + --repeat_count_; + state_ = waiting; + delay_timer_->expires_after(std::chrono::seconds(1)); + delay_timer_->async_wait(std::move(*this)); + return; // Composed operation not yet complete. + } + break; // Composed operation complete, continue below. + case waiting: + state_ = writing; + asio::async_write(socket_, + asio::buffer(*encoded_message_), std::move(*this)); + return; // Composed operation not yet complete. + } + } + + // This point is reached only on completion of the entire composed + // operation. + + // We no longer have any future work coming for the I/O executor. + io_work_.reset(); + + // Deallocate the encoded message before calling the user-supplied + // completion handler. + encoded_message_.reset(); + + // Call the user-supplied handler with the result of the operation. + handler_(error); + } + + // It is essential to the correctness of our composed operation that we + // preserve the executor of the user-supplied completion handler. With a + // hand-crafted function object we can do this by defining a nested type + // executor_type and member function get_executor. These obtain the + // completion handler's associated executor, and default to the I/O + // executor - in this case the executor of the socket - if the completion + // handler does not have its own. + using executor_type = asio::associated_executor_t< + typename std::decay<decltype(completion_handler)>::type, + tcp::socket::executor_type>; + + executor_type get_executor() const noexcept + { + return asio::get_associated_executor( + handler_, socket_.get_executor()); + } + + // Although not necessary for correctness, we may also preserve the + // allocator of the user-supplied completion handler. This is achieved by + // defining a nested type allocator_type and member function + // get_allocator. These obtain the completion handler's associated + // allocator, and default to std::allocator<void> if the completion + // handler does not have its own. + using allocator_type = asio::associated_allocator_t< + typename std::decay<decltype(completion_handler)>::type, + std::allocator<void>>; + + allocator_type get_allocator() const noexcept + { + return asio::get_associated_allocator( + handler_, std::allocator<void>{}); + } + }; + + // Initiate the underlying async_write operation using our intermediate + // completion handler. + auto encoded_message_buffer = asio::buffer(*encoded_message); + asio::async_write(socket, encoded_message_buffer, + intermediate_completion_handler{ + socket, std::move(encoded_message), + repeat_count, std::move(delay_timer), + intermediate_completion_handler::starting, + asio::make_work_guard(socket.get_executor()), + std::forward<decltype(completion_handler)>(completion_handler)}); + }; + + // Encode the message and copy it into an allocated buffer. The buffer will + // be maintained for the lifetime of the composed asynchronous operation. + std::ostringstream os; + os << message; + std::unique_ptr<std::string> encoded_message(new std::string(os.str())); + + // Create a steady_timer to be used for the delay between messages. + std::unique_ptr<asio::steady_timer> delay_timer( + new asio::steady_timer(socket.get_executor())); + + // The asio::async_initiate function takes: + // + // - our initiation function object, + // - the completion token, + // - the completion handler signature, and + // - any additional arguments we need to initiate the operation. + // + // It then asks the completion token to create a completion handler (i.e. a + // callback) with the specified signature, and invoke the initiation function + // object with this completion handler as well as the additional arguments. + // The return value of async_initiate is the result of our operation's + // initiating function. + // + // Note that we wrap non-const reference arguments in std::reference_wrapper + // to prevent incorrect decay-copies of these objects. + return asio::async_initiate< + CompletionToken, void(std::error_code)>( + initiation, token, std::ref(socket), + std::move(encoded_message), repeat_count, + std::move(delay_timer)); +} + +//------------------------------------------------------------------------------ + +void test_callback() +{ + asio::io_context io_context; + + tcp::acceptor acceptor(io_context, {tcp::v4(), 55555}); + tcp::socket socket = acceptor.accept(); + + // Test our asynchronous operation using a lambda as a callback. + async_write_messages(socket, "Testing callback\r\n", 5, + [](const std::error_code& error) + { + if (!error) + { + std::cout << "Messages sent\n"; + } + else + { + std::cout << "Error: " << error.message() << "\n"; + } + }); + + io_context.run(); +} + +//------------------------------------------------------------------------------ + +void test_deferred() +{ + asio::io_context io_context; + + tcp::acceptor acceptor(io_context, {tcp::v4(), 55555}); + tcp::socket socket = acceptor.accept(); + + // Test our asynchronous operation using the deferred completion token. This + // token causes the operation's initiating function to package up the + // operation with its arguments to return a function object, which may then be + // used to launch the asynchronous operation. + asio::async_operation auto op = async_write_messages( + socket, "Testing deferred\r\n", 5, asio::deferred); + + // Launch the operation using a lambda as a callback. + std::move(op)( + [](const std::error_code& error) + { + if (!error) + { + std::cout << "Messages sent\n"; + } + else + { + std::cout << "Error: " << error.message() << "\n"; + } + }); + + io_context.run(); +} + +//------------------------------------------------------------------------------ + +void test_future() +{ + asio::io_context io_context; + + tcp::acceptor acceptor(io_context, {tcp::v4(), 55555}); + tcp::socket socket = acceptor.accept(); + + // Test our asynchronous operation using the use_future completion token. + // This token causes the operation's initiating function to return a future, + // which may be used to synchronously wait for the result of the operation. + std::future<void> f = async_write_messages( + socket, "Testing future\r\n", 5, asio::use_future); + + io_context.run(); + + try + { + // Get the result of the operation. + f.get(); + std::cout << "Messages sent\n"; + } + catch (const std::exception& e) + { + std::cout << "Error: " << e.what() << "\n"; + } +} + +//------------------------------------------------------------------------------ + +int main() +{ + test_callback(); + test_deferred(); + test_future(); +} diff --git a/3rdparty/asio/src/examples/cpp20/operations/composed_7.cpp b/3rdparty/asio/src/examples/cpp20/operations/composed_7.cpp new file mode 100644 index 00000000000..9ae44c797fb --- /dev/null +++ b/3rdparty/asio/src/examples/cpp20/operations/composed_7.cpp @@ -0,0 +1,262 @@ +// +// composed_7.cpp +// ~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#include <asio/compose.hpp> +#include <asio/deferred.hpp> +#include <asio/io_context.hpp> +#include <asio/ip/tcp.hpp> +#include <asio/steady_timer.hpp> +#include <asio/use_future.hpp> +#include <asio/write.hpp> +#include <functional> +#include <iostream> +#include <memory> +#include <sstream> +#include <string> +#include <type_traits> +#include <utility> + +using asio::ip::tcp; + +// NOTE: This example requires the new asio::async_compose function. For +// an example that works with the Networking TS style of completion tokens, +// please see an older version of asio. + +//------------------------------------------------------------------------------ + +// This composed operation shows composition of multiple underlying operations. +// It automatically serialises a message, using its I/O streams insertion +// operator, before sending it N times on the socket. To do this, it must +// allocate a buffer for the encoded message and ensure this buffer's validity +// until all underlying async_write operation complete. A one second delay is +// inserted prior to each write operation, using a steady_timer. + +template <typename T, + asio::completion_token_for<void(std::error_code)> CompletionToken> +auto async_write_messages(tcp::socket& socket, + const T& message, std::size_t repeat_count, + CompletionToken&& token) + // The return type of the initiating function is deduced from the combination + // of: + // + // - the CompletionToken type, + // - the completion handler signature, and + // - the asynchronous operation's initiation function object. + // + // When the completion token is a simple callback, the return type is always + // void. In this example, when the completion token is asio::yield_context + // (used for stackful coroutines) the return type would also be void, as + // there is no non-error argument to the completion handler. When the + // completion token is asio::use_future it would be std::future<void>. When + // the completion token is asio::deferred, the return type differs for each + // asynchronous operation. + // + // In C++20 we can omit the return type as it is automatically deduced from + // the return type of asio::async_compose. +{ + // Encode the message and copy it into an allocated buffer. The buffer will + // be maintained for the lifetime of the composed asynchronous operation. + std::ostringstream os; + os << message; + std::unique_ptr<std::string> encoded_message(new std::string(os.str())); + + // Create a steady_timer to be used for the delay between messages. + std::unique_ptr<asio::steady_timer> delay_timer( + new asio::steady_timer(socket.get_executor())); + + // To manage the cycle between the multiple underlying asychronous + // operations, our implementation is a state machine. + enum { starting, waiting, writing }; + + // The asio::async_compose function takes: + // + // - our asynchronous operation implementation, + // - the completion token, + // - the completion handler signature, and + // - any I/O objects (or executors) used by the operation + // + // It then wraps our implementation, which is implemented here as a state + // machine in a lambda, in an intermediate completion handler that meets the + // requirements of a conforming asynchronous operation. This includes + // tracking outstanding work against the I/O executors associated with the + // operation (in this example, this is the socket's executor). + // + // The first argument to our lambda is a reference to the enclosing + // intermediate completion handler. This intermediate completion handler is + // provided for us by the asio::async_compose function, and takes care + // of all the details required to implement a conforming asynchronous + // operation. When calling an underlying asynchronous operation, we pass it + // this enclosing intermediate completion handler as the completion token. + // + // All arguments to our lambda after the first must be defaulted to allow the + // state machine to be started, as well as to allow the completion handler to + // match the completion signature of both the async_write and + // steady_timer::async_wait operations. + return asio::async_compose< + CompletionToken, void(std::error_code)>( + [ + // The implementation holds a reference to the socket as it is used for + // multiple async_write operations. + &socket, + + // The allocated buffer for the encoded message. The std::unique_ptr + // smart pointer is move-only, and as a consequence our lambda + // implementation is also move-only. + encoded_message = std::move(encoded_message), + + // The repeat count remaining. + repeat_count, + + // A steady timer used for introducing a delay. + delay_timer = std::move(delay_timer), + + // To manage the cycle between the multiple underlying asychronous + // operations, our implementation is a state machine. + state = starting + ] + ( + auto& self, + const std::error_code& error = {}, + std::size_t = 0 + ) mutable + { + if (!error) + { + switch (state) + { + case starting: + case writing: + if (repeat_count > 0) + { + --repeat_count; + state = waiting; + delay_timer->expires_after(std::chrono::seconds(1)); + delay_timer->async_wait(std::move(self)); + return; // Composed operation not yet complete. + } + break; // Composed operation complete, continue below. + case waiting: + state = writing; + asio::async_write(socket, + asio::buffer(*encoded_message), std::move(self)); + return; // Composed operation not yet complete. + } + } + + // This point is reached only on completion of the entire composed + // operation. + + // Deallocate the encoded message and delay timer before calling the + // user-supplied completion handler. + encoded_message.reset(); + delay_timer.reset(); + + // Call the user-supplied handler with the result of the operation. + self.complete(error); + }, + token, socket); +} + +//------------------------------------------------------------------------------ + +void test_callback() +{ + asio::io_context io_context; + + tcp::acceptor acceptor(io_context, {tcp::v4(), 55555}); + tcp::socket socket = acceptor.accept(); + + // Test our asynchronous operation using a lambda as a callback. + async_write_messages(socket, "Testing callback\r\n", 5, + [](const std::error_code& error) + { + if (!error) + { + std::cout << "Messages sent\n"; + } + else + { + std::cout << "Error: " << error.message() << "\n"; + } + }); + + io_context.run(); +} + +//------------------------------------------------------------------------------ + +void test_deferred() +{ + asio::io_context io_context; + + tcp::acceptor acceptor(io_context, {tcp::v4(), 55555}); + tcp::socket socket = acceptor.accept(); + + // Test our asynchronous operation using the deferred completion token. This + // token causes the operation's initiating function to package up the + // operation with its arguments to return a function object, which may then be + // used to launch the asynchronous operation. + asio::async_operation auto op = async_write_messages( + socket, "Testing deferred\r\n", 5, asio::deferred); + + // Launch the operation using a lambda as a callback. + std::move(op)( + [](const std::error_code& error) + { + if (!error) + { + std::cout << "Messages sent\n"; + } + else + { + std::cout << "Error: " << error.message() << "\n"; + } + }); + + io_context.run(); +} + +//------------------------------------------------------------------------------ + +void test_future() +{ + asio::io_context io_context; + + tcp::acceptor acceptor(io_context, {tcp::v4(), 55555}); + tcp::socket socket = acceptor.accept(); + + // Test our asynchronous operation using the use_future completion token. + // This token causes the operation's initiating function to return a future, + // which may be used to synchronously wait for the result of the operation. + std::future<void> f = async_write_messages( + socket, "Testing future\r\n", 5, asio::use_future); + + io_context.run(); + + try + { + // Get the result of the operation. + f.get(); + std::cout << "Messages sent\n"; + } + catch (const std::exception& e) + { + std::cout << "Error: " << e.what() << "\n"; + } +} + +//------------------------------------------------------------------------------ + +int main() +{ + test_callback(); + test_deferred(); + test_future(); +} diff --git a/3rdparty/asio/src/examples/cpp20/operations/composed_8.cpp b/3rdparty/asio/src/examples/cpp20/operations/composed_8.cpp new file mode 100644 index 00000000000..2735d74d047 --- /dev/null +++ b/3rdparty/asio/src/examples/cpp20/operations/composed_8.cpp @@ -0,0 +1,255 @@ +// +// composed_8.cpp +// ~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#include <asio/compose.hpp> +#include <asio/coroutine.hpp> +#include <asio/deferred.hpp> +#include <asio/io_context.hpp> +#include <asio/ip/tcp.hpp> +#include <asio/steady_timer.hpp> +#include <asio/use_future.hpp> +#include <asio/write.hpp> +#include <functional> +#include <iostream> +#include <memory> +#include <sstream> +#include <string> +#include <type_traits> +#include <utility> + +using asio::ip::tcp; + +// NOTE: This example requires the new asio::async_compose function. For +// an example that works with the Networking TS style of completion tokens, +// please see an older version of asio. + +//------------------------------------------------------------------------------ + +// This composed operation shows composition of multiple underlying operations, +// using asio's stackless coroutines support to express the flow of control. It +// automatically serialises a message, using its I/O streams insertion +// operator, before sending it N times on the socket. To do this, it must +// allocate a buffer for the encoded message and ensure this buffer's validity +// until all underlying async_write operation complete. A one second delay is +// inserted prior to each write operation, using a steady_timer. + +#include <asio/yield.hpp> + +template <typename T, + asio::completion_token_for<void(std::error_code)> CompletionToken> +auto async_write_messages(tcp::socket& socket, + const T& message, std::size_t repeat_count, + CompletionToken&& token) + // The return type of the initiating function is deduced from the combination + // of: + // + // - the CompletionToken type, + // - the completion handler signature, and + // - the asynchronous operation's initiation function object. + // + // When the completion token is a simple callback, the return type is always + // void. In this example, when the completion token is asio::yield_context + // (used for stackful coroutines) the return type would also be void, as + // there is no non-error argument to the completion handler. When the + // completion token is asio::use_future it would be std::future<void>. When + // the completion token is asio::deferred, the return type differs for each + // asynchronous operation. + // + // In C++20 we can omit the return type as it is automatically deduced from + // the return type of asio::async_compose. +{ + // Encode the message and copy it into an allocated buffer. The buffer will + // be maintained for the lifetime of the composed asynchronous operation. + std::ostringstream os; + os << message; + std::unique_ptr<std::string> encoded_message(new std::string(os.str())); + + // Create a steady_timer to be used for the delay between messages. + std::unique_ptr<asio::steady_timer> delay_timer( + new asio::steady_timer(socket.get_executor())); + + // The asio::async_compose function takes: + // + // - our asynchronous operation implementation, + // - the completion token, + // - the completion handler signature, and + // - any I/O objects (or executors) used by the operation + // + // It then wraps our implementation, which is implemented here as a stackless + // coroutine in a lambda, in an intermediate completion handler that meets the + // requirements of a conforming asynchronous operation. This includes + // tracking outstanding work against the I/O executors associated with the + // operation (in this example, this is the socket's executor). + // + // The first argument to our lambda is a reference to the enclosing + // intermediate completion handler. This intermediate completion handler is + // provided for us by the asio::async_compose function, and takes care + // of all the details required to implement a conforming asynchronous + // operation. When calling an underlying asynchronous operation, we pass it + // this enclosing intermediate completion handler as the completion token. + // + // All arguments to our lambda after the first must be defaulted to allow the + // state machine to be started, as well as to allow the completion handler to + // match the completion signature of both the async_write and + // steady_timer::async_wait operations. + return asio::async_compose< + CompletionToken, void(std::error_code)>( + [ + // The implementation holds a reference to the socket as it is used for + // multiple async_write operations. + &socket, + + // The allocated buffer for the encoded message. The std::unique_ptr + // smart pointer is move-only, and as a consequence our lambda + // implementation is also move-only. + encoded_message = std::move(encoded_message), + + // The repeat count remaining. + repeat_count, + + // A steady timer used for introducing a delay. + delay_timer = std::move(delay_timer), + + // The coroutine state. + coro = asio::coroutine() + ] + ( + auto& self, + const std::error_code& error = {}, + std::size_t = 0 + ) mutable + { + reenter (coro) + { + while (repeat_count > 0) + { + --repeat_count; + + delay_timer->expires_after(std::chrono::seconds(1)); + yield delay_timer->async_wait(std::move(self)); + if (error) + break; + + yield asio::async_write(socket, + asio::buffer(*encoded_message), std::move(self)); + if (error) + break; + } + + // Deallocate the encoded message and delay timer before calling the + // user-supplied completion handler. + encoded_message.reset(); + delay_timer.reset(); + + // Call the user-supplied handler with the result of the operation. + self.complete(error); + } + }, + token, socket); +} + +#include <asio/unyield.hpp> + +//------------------------------------------------------------------------------ + +void test_callback() +{ + asio::io_context io_context; + + tcp::acceptor acceptor(io_context, {tcp::v4(), 55555}); + tcp::socket socket = acceptor.accept(); + + // Test our asynchronous operation using a lambda as a callback. + async_write_messages(socket, "Testing callback\r\n", 5, + [](const std::error_code& error) + { + if (!error) + { + std::cout << "Messages sent\n"; + } + else + { + std::cout << "Error: " << error.message() << "\n"; + } + }); + + io_context.run(); +} + +//------------------------------------------------------------------------------ + +void test_deferred() +{ + asio::io_context io_context; + + tcp::acceptor acceptor(io_context, {tcp::v4(), 55555}); + tcp::socket socket = acceptor.accept(); + + // Test our asynchronous operation using the deferred completion token. This + // token causes the operation's initiating function to package up the + // operation with its arguments to return a function object, which may then be + // used to launch the asynchronous operation. + asio::async_operation auto op = async_write_messages( + socket, "Testing deferred\r\n", 5, asio::deferred); + + // Launch the operation using a lambda as a callback. + std::move(op)( + [](const std::error_code& error) + { + if (!error) + { + std::cout << "Messages sent\n"; + } + else + { + std::cout << "Error: " << error.message() << "\n"; + } + }); + + io_context.run(); +} + +//------------------------------------------------------------------------------ + +void test_future() +{ + asio::io_context io_context; + + tcp::acceptor acceptor(io_context, {tcp::v4(), 55555}); + tcp::socket socket = acceptor.accept(); + + // Test our asynchronous operation using the use_future completion token. + // This token causes the operation's initiating function to return a future, + // which may be used to synchronously wait for the result of the operation. + std::future<void> f = async_write_messages( + socket, "Testing future\r\n", 5, asio::use_future); + + io_context.run(); + + try + { + // Get the result of the operation. + f.get(); + std::cout << "Messages sent\n"; + } + catch (const std::exception& e) + { + std::cout << "Error: " << e.what() << "\n"; + } +} + +//------------------------------------------------------------------------------ + +int main() +{ + test_callback(); + test_deferred(); + test_future(); +} |