Unnamed: 0
int64
0
0
repo_id
stringlengths
5
186
file_path
stringlengths
15
223
content
stringlengths
1
32.8M
0
repos/asio/asio/src/examples/cpp20
repos/asio/asio/src/examples/cpp20/operations/composed_8.cpp
// // 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(); }
0
repos/asio/asio/src/examples/cpp20
repos/asio/asio/src/examples/cpp20/operations/composed_6.cpp
// // 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 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. 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(); }
0
repos/asio/asio/src/examples/cpp20
repos/asio/asio/src/examples/cpp20/operations/composed_2.cpp
// // 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(); }
0
repos/asio/asio/src/examples/cpp20
repos/asio/asio/src/examples/cpp20/operations/composed_4.cpp
// // 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(); }
0
repos/asio/asio/src/examples/cpp20
repos/asio/asio/src/examples/cpp20/operations/composed_7.cpp
// // 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(); }
0
repos/asio/asio/src/examples/cpp20
repos/asio/asio/src/examples/cpp20/operations/c_callback_wrapper.cpp
// // 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(); }
0
repos/asio/asio/src/examples/cpp20
repos/asio/asio/src/examples/cpp20/operations/composed_5.cpp
// // 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(); }
0
repos/asio/asio/src/examples/cpp20
repos/asio/asio/src/examples/cpp20/operations/composed_3.cpp
// // 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(); }
0
repos/asio/asio/src/examples/cpp20
repos/asio/asio/src/examples/cpp20/operations/callback_wrapper.cpp
// // 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(); }
0
repos/asio/asio/src/examples/cpp20
repos/asio/asio/src/examples/cpp20/operations/composed_1.cpp
// // 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(); }
0
repos/asio/asio/src/examples/cpp20
repos/asio/asio/src/examples/cpp20/channels/mutual_exclusion_2.cpp
// // mutual_exclusion_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.hpp> #include <asio/experimental/channel.hpp> #include <iostream> #include <memory> using asio::as_tuple; using asio::awaitable; using asio::dynamic_buffer; using asio::co_spawn; using asio::detached; using asio::experimental::channel; using asio::io_context; using asio::ip::tcp; using asio::steady_timer; using namespace asio::buffer_literals; using namespace std::literals::chrono_literals; // This class implements a simple line-based protocol: // // * For event line that is received from the client, the session sends a // message header followed by the content of the line as the message body. // // * The session generates heartbeat messages once a second. // // This protocol is implemented using two actors, handle_messages() and // send_heartbeats(), each written as a coroutine. class line_based_echo_session : public std::enable_shared_from_this<line_based_echo_session> { // The socket used to read from and write to the client. This socket is a // data member as it is shared between the two actors. tcp::socket socket_; // As both of the actors will write to the socket, we need a lock to prevent // these writes from overlapping. To achieve this, we use a channel with a // buffer size of one. The lock is claimed by sending a message to the // channel, and then released by receiving this message back again. If the // lock is not held then the channel's buffer is empty, and the send will // complete without delay. Otherwise, if the lock is held by the other actor, // then the send operation will not complete until the lock is released. channel<void()> write_lock_{socket_.get_executor(), 1}; public: line_based_echo_session(tcp::socket socket) : socket_{std::move(socket)} { socket_.set_option(tcp::no_delay(true)); } void start() { co_spawn(socket_.get_executor(), [self = shared_from_this()]{ return self->handle_messages(); }, detached); co_spawn(socket_.get_executor(), [self = shared_from_this()]{ return self->send_heartbeats(); }, detached); } private: void stop() { socket_.close(); write_lock_.cancel(); } awaitable<void> handle_messages() { try { constexpr std::size_t max_line_length = 1024; std::string data; for (;;) { // Read an entire line from the client. std::size_t length = co_await async_read_until(socket_, dynamic_buffer(data, max_line_length), '\n'); // Claim the write lock by sending a message to the channel. Since the // channel signature is void(), there are no arguments to send in the // message itself. In this example we optimise for the common case, // where the lock is not held by the other actor, by first trying a // non-blocking send. if (!write_lock_.try_send()) { co_await write_lock_.async_send(); } // Respond to the client with a message, echoing the line they sent. co_await async_write(socket_, "<line>"_buf); co_await async_write(socket_, dynamic_buffer(data, length)); // Release the lock by receiving the message back again. write_lock_.try_receive([](auto...){}); } } catch (const std::exception&) { stop(); } } awaitable<void> send_heartbeats() { steady_timer timer{socket_.get_executor()}; try { for (;;) { // Wait one second before trying to send the next heartbeat. timer.expires_after(1s); co_await timer.async_wait(); // Claim the write lock by sending a message to the channel. Since the // channel signature is void(), there are no arguments to send in the // message itself. In this example we optimise for the common case, // where the lock is not held by the other actor, by first trying a // non-blocking send. if (!write_lock_.try_send()) { co_await write_lock_.async_send(); } // Send a heartbeat to the client. As the content of the heartbeat // message never varies, a buffer literal can be used to specify the // bytes of the message. The memory associated with a buffer literal is // valid for the lifetime of the program, which mean that the buffer // can be safely passed as-is to the asynchronous operation. co_await async_write(socket_, "<heartbeat>\n"_buf); // Release the lock by receiving the message back again. write_lock_.try_receive([](auto...){}); } } catch (const std::exception&) { stop(); } } }; awaitable<void> listen(tcp::acceptor& acceptor) { for (;;) { auto [e, socket] = co_await acceptor.async_accept(as_tuple); if (!e) { std::make_shared<line_based_echo_session>(std::move(socket))->start(); } } } int main(int argc, char* argv[]) { try { if (argc != 3) { std::cerr << "Usage: mutual_exclusion_1"; std::cerr << " <listen_address> <listen_port>\n"; return 1; } io_context ctx; auto listen_endpoint = *tcp::resolver(ctx).resolve(argv[1], argv[2], tcp::resolver::passive).begin(); tcp::acceptor acceptor(ctx, listen_endpoint); co_spawn(ctx, listen(acceptor), detached); ctx.run(); } catch (std::exception& e) { std::cerr << "Exception: " << e.what() << "\n"; } }
0
repos/asio/asio/src/examples/cpp20
repos/asio/asio/src/examples/cpp20/channels/mutual_exclusion_1.cpp
// // mutual_exclusion_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.hpp> #include <asio/experimental/channel.hpp> #include <iostream> #include <memory> using asio::as_tuple; using asio::awaitable; using asio::dynamic_buffer; using asio::co_spawn; using asio::detached; using asio::experimental::channel; using asio::io_context; using asio::ip::tcp; using asio::steady_timer; using namespace asio::buffer_literals; using namespace std::literals::chrono_literals; // This class implements a simple line-based protocol: // // * For event line that is received from the client, the session sends a // message header followed by the content of the line as the message body. // // * The session generates heartbeat messages once a second. // // This protocol is implemented using two actors, handle_messages() and // send_heartbeats(), each written as a coroutine. class line_based_echo_session : public std::enable_shared_from_this<line_based_echo_session> { // The socket used to read from and write to the client. This socket is a // data member as it is shared between the two actors. tcp::socket socket_; // As both of the actors will write to the socket, we need a lock to prevent // these writes from overlapping. To achieve this, we use a channel with a // buffer size of one. The lock is claimed by sending a message to the // channel, and then released by receiving this message back again. If the // lock is not held then the channel's buffer is empty, and the send will // complete without delay. Otherwise, if the lock is held by the other actor, // then the send operation will not complete until the lock is released. channel<void()> write_lock_{socket_.get_executor(), 1}; public: line_based_echo_session(tcp::socket socket) : socket_{std::move(socket)} { socket_.set_option(tcp::no_delay(true)); } void start() { co_spawn(socket_.get_executor(), [self = shared_from_this()]{ return self->handle_messages(); }, detached); co_spawn(socket_.get_executor(), [self = shared_from_this()]{ return self->send_heartbeats(); }, detached); } private: void stop() { socket_.close(); write_lock_.cancel(); } awaitable<void> handle_messages() { try { constexpr std::size_t max_line_length = 1024; std::string data; for (;;) { // Read an entire line from the client. std::size_t length = co_await async_read_until(socket_, dynamic_buffer(data, max_line_length), '\n'); // Claim the write lock by sending a message to the channel. Since the // channel signature is void(), there are no arguments to send in the // message itself. co_await write_lock_.async_send(); // Respond to the client with a message, echoing the line they sent. co_await async_write(socket_, "<line>"_buf); co_await async_write(socket_, dynamic_buffer(data, length)); // Release the lock by receiving the message back again. write_lock_.try_receive([](auto...){}); } } catch (const std::exception&) { stop(); } } awaitable<void> send_heartbeats() { steady_timer timer{socket_.get_executor()}; try { for (;;) { // Wait one second before trying to send the next heartbeat. timer.expires_after(1s); co_await timer.async_wait(); // Claim the write lock by sending a message to the channel. Since the // channel signature is void(), there are no arguments to send in the // message itself. co_await write_lock_.async_send(); // Send a heartbeat to the client. As the content of the heartbeat // message never varies, a buffer literal can be used to specify the // bytes of the message. The memory associated with a buffer literal is // valid for the lifetime of the program, which mean that the buffer // can be safely passed as-is to the asynchronous operation. co_await async_write(socket_, "<heartbeat>\n"_buf); // Release the lock by receiving the message back again. write_lock_.try_receive([](auto...){}); } } catch (const std::exception&) { stop(); } } }; awaitable<void> listen(tcp::acceptor& acceptor) { for (;;) { auto [e, socket] = co_await acceptor.async_accept(as_tuple); if (!e) { std::make_shared<line_based_echo_session>(std::move(socket))->start(); } } } int main(int argc, char* argv[]) { try { if (argc != 3) { std::cerr << "Usage: mutual_exclusion_1"; std::cerr << " <listen_address> <listen_port>\n"; return 1; } io_context ctx; auto listen_endpoint = *tcp::resolver(ctx).resolve(argv[1], argv[2], tcp::resolver::passive).begin(); tcp::acceptor acceptor(ctx, listen_endpoint); co_spawn(ctx, listen(acceptor), detached); ctx.run(); } catch (std::exception& e) { std::cerr << "Exception: " << e.what() << "\n"; } }
0
repos/asio/asio/src/examples/cpp20
repos/asio/asio/src/examples/cpp20/channels/throttling_proxy.cpp
// // throttling_proxy.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 <asio/experimental/awaitable_operators.hpp> #include <asio/experimental/channel.hpp> #include <iostream> using asio::as_tuple; using asio::awaitable; using asio::buffer; using asio::co_spawn; using asio::detached; using asio::experimental::channel; using asio::io_context; using asio::ip::tcp; using asio::steady_timer; namespace this_coro = asio::this_coro; using namespace asio::experimental::awaitable_operators; using namespace std::literals::chrono_literals; using token_channel = channel<void(asio::error_code, std::size_t)>; awaitable<void> produce_tokens(std::size_t bytes_per_token, steady_timer::duration token_interval, token_channel& tokens) { steady_timer timer(co_await this_coro::executor); for (;;) { co_await tokens.async_send(asio::error_code{}, bytes_per_token); timer.expires_after(token_interval); co_await timer.async_wait(); } } awaitable<void> transfer(tcp::socket& from, tcp::socket& to, token_channel& tokens) { std::array<unsigned char, 4096> data; for (;;) { std::size_t bytes_available = co_await tokens.async_receive(); while (bytes_available > 0) { std::size_t n = co_await from.async_read_some( buffer(data, bytes_available)); co_await async_write(to, buffer(data, n)); bytes_available -= n; } } } awaitable<void> proxy(tcp::socket client, tcp::endpoint target) { constexpr std::size_t number_of_tokens = 100; constexpr size_t bytes_per_token = 20 * 1024; constexpr steady_timer::duration token_interval = 100ms; auto ex = client.get_executor(); tcp::socket server(ex); token_channel client_tokens(ex, number_of_tokens); token_channel server_tokens(ex, number_of_tokens); co_await server.async_connect(target); co_await ( produce_tokens(bytes_per_token, token_interval, client_tokens) && transfer(client, server, client_tokens) && produce_tokens(bytes_per_token, token_interval, server_tokens) && transfer(server, client, server_tokens) ); } awaitable<void> listen(tcp::acceptor& acceptor, tcp::endpoint target) { for (;;) { auto [e, client] = co_await acceptor.async_accept(as_tuple); if (!e) { auto ex = client.get_executor(); co_spawn(ex, proxy(std::move(client), target), detached); } else { std::cerr << "Accept failed: " << e.message() << "\n"; steady_timer timer(co_await this_coro::executor); timer.expires_after(100ms); co_await timer.async_wait(); } } } int main(int argc, char* argv[]) { try { if (argc != 5) { std::cerr << "Usage: throttling_proxy"; std::cerr << " <listen_address> <listen_port>"; std::cerr << " <target_address> <target_port>\n"; return 1; } io_context ctx; auto listen_endpoint = *tcp::resolver(ctx).resolve(argv[1], argv[2], tcp::resolver::passive).begin(); auto target_endpoint = *tcp::resolver(ctx).resolve(argv[3], argv[4]).begin(); tcp::acceptor acceptor(ctx, listen_endpoint); co_spawn(ctx, listen(acceptor, target_endpoint), detached); ctx.run(); } catch (std::exception& e) { std::cerr << "Exception: " << e.what() << "\n"; } }
0
repos/asio/asio/src/examples/cpp14
repos/asio/asio/src/examples/cpp14/echo/blocking_udp_echo_client.cpp
// // blocking_udp_echo_client.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 <cstdlib> #include <cstring> #include <iostream> #include <asio/ts/buffer.hpp> #include <asio/ts/internet.hpp> using asio::ip::udp; enum { max_length = 1024 }; int main(int argc, char* argv[]) { try { if (argc != 3) { std::cerr << "Usage: blocking_udp_echo_client <host> <port>\n"; return 1; } asio::io_context io_context; udp::socket s(io_context, udp::endpoint(udp::v4(), 0)); udp::resolver resolver(io_context); udp::endpoint endpoint = *resolver.resolve(udp::v4(), argv[1], argv[2]).begin(); std::cout << "Enter message: "; char request[max_length]; std::cin.getline(request, max_length); size_t request_length = std::strlen(request); s.send_to(asio::buffer(request, request_length), endpoint); char reply[max_length]; udp::endpoint sender_endpoint; size_t reply_length = s.receive_from( asio::buffer(reply, max_length), sender_endpoint); std::cout << "Reply is: "; std::cout.write(reply, reply_length); std::cout << "\n"; } catch (std::exception& e) { std::cerr << "Exception: " << e.what() << "\n"; } return 0; }
0
repos/asio/asio/src/examples/cpp14
repos/asio/asio/src/examples/cpp14/echo/blocking_tcp_echo_server.cpp
// // blocking_tcp_echo_server.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 <cstdlib> #include <iostream> #include <thread> #include <utility> #include <asio/ts/buffer.hpp> #include <asio/ts/internet.hpp> using asio::ip::tcp; const int max_length = 1024; void session(tcp::socket sock) { try { for (;;) { char data[max_length]; std::error_code error; size_t length = sock.read_some(asio::buffer(data), error); if (error == asio::stream_errc::eof) break; // Connection closed cleanly by peer. else if (error) throw std::system_error(error); // Some other error. asio::write(sock, asio::buffer(data, length)); } } catch (std::exception& e) { std::cerr << "Exception in thread: " << e.what() << "\n"; } } void server(asio::io_context& io_context, unsigned short port) { tcp::acceptor a(io_context, tcp::endpoint(tcp::v4(), port)); for (;;) { tcp::socket sock(io_context); a.accept(sock); std::thread(session, std::move(sock)).detach(); } } int main(int argc, char* argv[]) { try { if (argc != 2) { std::cerr << "Usage: blocking_tcp_echo_server <port>\n"; return 1; } asio::io_context io_context; server(io_context, std::atoi(argv[1])); } catch (std::exception& e) { std::cerr << "Exception: " << e.what() << "\n"; } return 0; }
0
repos/asio/asio/src/examples/cpp14
repos/asio/asio/src/examples/cpp14/echo/async_udp_echo_server.cpp
// // async_udp_echo_server.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 <cstdlib> #include <iostream> #include <asio/ts/buffer.hpp> #include <asio/ts/internet.hpp> using asio::ip::udp; class server { public: server(asio::io_context& io_context, short port) : socket_(io_context, udp::endpoint(udp::v4(), port)) { do_receive(); } void do_receive() { socket_.async_receive_from( asio::buffer(data_, max_length), sender_endpoint_, [this](std::error_code ec, std::size_t bytes_recvd) { if (!ec && bytes_recvd > 0) { do_send(bytes_recvd); } else { do_receive(); } }); } void do_send(std::size_t length) { socket_.async_send_to( asio::buffer(data_, length), sender_endpoint_, [this](std::error_code /*ec*/, std::size_t /*bytes_sent*/) { do_receive(); }); } private: udp::socket socket_; udp::endpoint sender_endpoint_; enum { max_length = 1024 }; char data_[max_length]; }; int main(int argc, char* argv[]) { try { if (argc != 2) { std::cerr << "Usage: async_udp_echo_server <port>\n"; return 1; } asio::io_context io_context; server s(io_context, std::atoi(argv[1])); io_context.run(); } catch (std::exception& e) { std::cerr << "Exception: " << e.what() << "\n"; } return 0; }
0
repos/asio/asio/src/examples/cpp14
repos/asio/asio/src/examples/cpp14/echo/blocking_udp_echo_server.cpp
// // blocking_udp_echo_server.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 <cstdlib> #include <iostream> #include <asio/ts/buffer.hpp> #include <asio/ts/internet.hpp> using asio::ip::udp; enum { max_length = 1024 }; void server(asio::io_context& io_context, unsigned short port) { udp::socket sock(io_context, udp::endpoint(udp::v4(), port)); for (;;) { char data[max_length]; udp::endpoint sender_endpoint; size_t length = sock.receive_from( asio::buffer(data, max_length), sender_endpoint); sock.send_to(asio::buffer(data, length), sender_endpoint); } } int main(int argc, char* argv[]) { try { if (argc != 2) { std::cerr << "Usage: blocking_udp_echo_server <port>\n"; return 1; } asio::io_context io_context; server(io_context, std::atoi(argv[1])); } catch (std::exception& e) { std::cerr << "Exception: " << e.what() << "\n"; } return 0; }
0
repos/asio/asio/src/examples/cpp14
repos/asio/asio/src/examples/cpp14/echo/async_tcp_echo_server.cpp
// // async_tcp_echo_server.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 <cstdlib> #include <iostream> #include <memory> #include <utility> #include <asio/ts/buffer.hpp> #include <asio/ts/internet.hpp> using asio::ip::tcp; class session : public std::enable_shared_from_this<session> { public: session(tcp::socket socket) : socket_(std::move(socket)) { } void start() { do_read(); } private: void do_read() { auto self(shared_from_this()); socket_.async_read_some(asio::buffer(data_, max_length), [this, self](std::error_code ec, std::size_t length) { if (!ec) { do_write(length); } }); } void do_write(std::size_t length) { auto self(shared_from_this()); asio::async_write(socket_, asio::buffer(data_, length), [this, self](std::error_code ec, std::size_t /*length*/) { if (!ec) { do_read(); } }); } tcp::socket socket_; enum { max_length = 1024 }; char data_[max_length]; }; class server { public: server(asio::io_context& io_context, short port) : acceptor_(io_context, tcp::endpoint(tcp::v4(), port)), socket_(io_context) { do_accept(); } private: void do_accept() { acceptor_.async_accept(socket_, [this](std::error_code ec) { if (!ec) { std::make_shared<session>(std::move(socket_))->start(); } do_accept(); }); } tcp::acceptor acceptor_; tcp::socket socket_; }; int main(int argc, char* argv[]) { try { if (argc != 2) { std::cerr << "Usage: async_tcp_echo_server <port>\n"; return 1; } asio::io_context io_context; server s(io_context, std::atoi(argv[1])); io_context.run(); } catch (std::exception& e) { std::cerr << "Exception: " << e.what() << "\n"; } return 0; }
0
repos/asio/asio/src/examples/cpp14
repos/asio/asio/src/examples/cpp14/echo/blocking_tcp_echo_client.cpp
// // blocking_tcp_echo_client.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 <cstdlib> #include <cstring> #include <iostream> #include "asio.hpp" using asio::ip::tcp; enum { max_length = 1024 }; int main(int argc, char* argv[]) { try { if (argc != 3) { std::cerr << "Usage: blocking_tcp_echo_client <host> <port>\n"; return 1; } asio::io_context io_context; tcp::socket s(io_context); tcp::resolver resolver(io_context); asio::connect(s, resolver.resolve(argv[1], argv[2])); std::cout << "Enter message: "; char request[max_length]; std::cin.getline(request, max_length); size_t request_length = std::strlen(request); asio::write(s, asio::buffer(request, request_length)); char reply[max_length]; size_t reply_length = asio::read(s, asio::buffer(reply, request_length)); std::cout << "Reply is: "; std::cout.write(reply, reply_length); std::cout << "\n"; } catch (std::exception& e) { std::cerr << "Exception: " << e.what() << "\n"; } return 0; }
0
repos/asio/asio/src/examples/cpp14
repos/asio/asio/src/examples/cpp14/executors/bank_account_2.cpp
#include <asio/execution.hpp> #include <asio/static_thread_pool.hpp> #include <iostream> using asio::static_thread_pool; namespace execution = asio::execution; // Traditional active object pattern. // Member functions block until operation is finished. class bank_account { int balance_ = 0; mutable static_thread_pool pool_{1}; public: void deposit(int amount) { asio::require(pool_.executor(), execution::blocking.always).execute( [this, amount] { balance_ += amount; }); } void withdraw(int amount) { asio::require(pool_.executor(), execution::blocking.always).execute( [this, amount] { if (balance_ >= amount) balance_ -= amount; }); } int balance() const { int result = 0; asio::require(pool_.executor(), execution::blocking.always).execute( [this, &result] { result = balance_; }); return result; } }; int main() { bank_account acct; acct.deposit(20); acct.withdraw(10); std::cout << "balance = " << acct.balance() << "\n"; }
0
repos/asio/asio/src/examples/cpp14
repos/asio/asio/src/examples/cpp14/executors/async_1.cpp
#include <asio/associated_executor.hpp> #include <asio/bind_executor.hpp> #include <asio/execution.hpp> #include <asio/static_thread_pool.hpp> #include <iostream> #include <string> using asio::bind_executor; using asio::get_associated_executor; using asio::static_thread_pool; namespace execution = asio::execution; // A function to asynchronously read a single line from an input stream. template <class IoExecutor, class Handler> void async_getline(IoExecutor io_ex, std::istream& is, Handler handler) { // Track work for the handler's associated executor. auto work_ex = asio::prefer( get_associated_executor(handler, io_ex), execution::outstanding_work.tracked); // Post a function object to do the work asynchronously. asio::require(io_ex, execution::blocking.never).execute( [&is, work_ex, handler=std::move(handler)]() mutable { std::string line; std::getline(is, line); // Pass the result to the handler, via the associated executor. asio::prefer(work_ex, execution::blocking.possibly).execute( [line=std::move(line), handler=std::move(handler)]() mutable { handler(std::move(line)); }); }); } int main() { static_thread_pool io_pool(1); static_thread_pool completion_pool(1); std::cout << "Enter a line: "; async_getline(io_pool.executor(), std::cin, bind_executor(completion_pool.executor(), [](std::string line) { std::cout << "Line: " << line << "\n"; })); io_pool.wait(); completion_pool.wait(); }
0
repos/asio/asio/src/examples/cpp14
repos/asio/asio/src/examples/cpp14/executors/async_2.cpp
#include <asio/associated_executor.hpp> #include <asio/bind_executor.hpp> #include <asio/execution.hpp> #include <asio/static_thread_pool.hpp> #include <iostream> #include <string> using asio::bind_executor; using asio::get_associated_executor; using asio::static_thread_pool; namespace execution = asio::execution; // A function to asynchronously read a single line from an input stream. template <class IoExecutor, class Handler> void async_getline(IoExecutor io_ex, std::istream& is, Handler handler) { // Track work for the handler's associated executor. auto work_ex = asio::prefer( get_associated_executor(handler, io_ex), execution::outstanding_work.tracked); // Post a function object to do the work asynchronously. asio::require(io_ex, execution::blocking.never).execute( [&is, work_ex, handler=std::move(handler)]() mutable { std::string line; std::getline(is, line); // Pass the result to the handler, via the associated executor. asio::prefer(work_ex, execution::blocking.possibly).execute( [line=std::move(line), handler=std::move(handler)]() mutable { handler(std::move(line)); }); }); } // A function to asynchronously read multiple lines from an input stream. template <class IoExecutor, class Handler> void async_getlines(IoExecutor io_ex, std::istream& is, std::string init, Handler handler) { // Track work for the I/O executor. auto io_work_ex = asio::prefer(io_ex, execution::outstanding_work.tracked); // Track work for the handler's associated executor. auto handler_work_ex = asio::prefer( get_associated_executor(handler, io_ex), execution::outstanding_work.tracked); // Use the associated executor for each operation in the composition. async_getline(io_work_ex, is, bind_executor(handler_work_ex, [io_work_ex, &is, lines=std::move(init), handler=std::move(handler)] (std::string line) mutable { if (line.empty()) handler(lines); else async_getlines(io_work_ex, is, lines + line + "\n", std::move(handler)); })); } int main() { static_thread_pool io_pool(1); static_thread_pool completion_pool(1); std::cout << "Enter text, terminating with a blank line:\n"; async_getlines(io_pool.executor(), std::cin, "", bind_executor(completion_pool.executor(), [](std::string lines) { std::cout << "Lines:\n" << lines << "\n"; })); io_pool.wait(); completion_pool.wait(); }
0
repos/asio/asio/src/examples/cpp14
repos/asio/asio/src/examples/cpp14/executors/pipeline.cpp
#include <asio/associated_executor.hpp> #include <asio/bind_executor.hpp> #include <asio/execution.hpp> #include <condition_variable> #include <future> #include <memory> #include <mutex> #include <queue> #include <thread> #include <vector> #include <cctype> using asio::executor_binder; using asio::get_associated_executor; namespace execution = asio::execution; // An executor that launches a new thread for each function submitted to it. // This class satisfies the executor requirements. class thread_executor { private: // Singleton execution context that manages threads launched by the new_thread_executor. class thread_bag { friend class thread_executor; void add_thread(std::thread&& t) { std::unique_lock<std::mutex> lock(mutex_); threads_.push_back(std::move(t)); } thread_bag() = default; ~thread_bag() { for (auto& t : threads_) t.join(); } std::mutex mutex_; std::vector<std::thread> threads_; }; public: static thread_bag& query(execution::context_t) { static thread_bag threads; return threads; } static constexpr auto query(execution::blocking_t) { return execution::blocking.never; } template <class Func> void execute(Func f) const { thread_bag& bag = query(execution::context); bag.add_thread(std::thread(std::move(f))); } friend bool operator==(const thread_executor&, const thread_executor&) noexcept { return true; } friend bool operator!=(const thread_executor&, const thread_executor&) noexcept { return false; } }; // Base class for all thread-safe queue implementations. class queue_impl_base { template <class> friend class queue_front; template <class> friend class queue_back; std::mutex mutex_; std::condition_variable condition_; bool stop_ = false; }; // Underlying implementation of a thread-safe queue, shared between the // queue_front and queue_back classes. template <class T> class queue_impl : public queue_impl_base { template <class> friend class queue_front; template <class> friend class queue_back; std::queue<T> queue_; }; // The front end of a queue between consecutive pipeline stages. template <class T> class queue_front { public: typedef T value_type; explicit queue_front(std::shared_ptr<queue_impl<T>> impl) : impl_(impl) { } void push(T t) { std::unique_lock<std::mutex> lock(impl_->mutex_); impl_->queue_.push(std::move(t)); impl_->condition_.notify_one(); } void stop() { std::unique_lock<std::mutex> lock(impl_->mutex_); impl_->stop_ = true; impl_->condition_.notify_one(); } private: std::shared_ptr<queue_impl<T>> impl_; }; // The back end of a queue between consecutive pipeline stages. template <class T> class queue_back { public: typedef T value_type; explicit queue_back(std::shared_ptr<queue_impl<T>> impl) : impl_(impl) { } bool pop(T& t) { std::unique_lock<std::mutex> lock(impl_->mutex_); while (impl_->queue_.empty() && !impl_->stop_) impl_->condition_.wait(lock); if (!impl_->queue_.empty()) { t = impl_->queue_.front(); impl_->queue_.pop(); return true; } return false; } private: std::shared_ptr<queue_impl<T>> impl_; }; // Launch the last stage in a pipeline. template <class T, class F> std::future<void> pipeline(queue_back<T> in, F f) { // Get the function's associated executor, defaulting to thread_executor. auto ex = get_associated_executor(f, thread_executor()); // Run the function, and as we're the last stage return a future so that the // caller can wait for the pipeline to finish. std::packaged_task<void()> task( [in, f = std::move(f)]() mutable { f(in); }); std::future<void> fut = task.get_future(); asio::require(ex, execution::blocking.never).execute(std::move(task)); return fut; } // Launch an intermediate stage in a pipeline. template <class T, class F, class... Tail> std::future<void> pipeline(queue_back<T> in, F f, Tail... t) { // Determine the output queue type. typedef typename executor_binder<F, thread_executor>::second_argument_type::value_type output_value_type; // Create the output queue and its implementation. auto out_impl = std::make_shared<queue_impl<output_value_type>>(); queue_front<output_value_type> out(out_impl); queue_back<output_value_type> next_in(out_impl); // Get the function's associated executor, defaulting to thread_executor. auto ex = get_associated_executor(f, thread_executor()); // Run the function. asio::require(ex, execution::blocking.never).execute( [in, out, f = std::move(f)]() mutable { f(in, out); out.stop(); }); // Launch the rest of the pipeline. return pipeline(next_in, std::move(t)...); } // Launch the first stage in a pipeline. template <class F, class... Tail> std::future<void> pipeline(F f, Tail... t) { // Determine the output queue type. typedef typename executor_binder<F, thread_executor>::argument_type::value_type output_value_type; // Create the output queue and its implementation. auto out_impl = std::make_shared<queue_impl<output_value_type>>(); queue_front<output_value_type> out(out_impl); queue_back<output_value_type> next_in(out_impl); // Get the function's associated executor, defaulting to thread_executor. auto ex = get_associated_executor(f, thread_executor()); // Run the function. asio::require(ex, execution::blocking.never).execute( [out, f = std::move(f)]() mutable { f(out); out.stop(); }); // Launch the rest of the pipeline. return pipeline(next_in, std::move(t)...); } //------------------------------------------------------------------------------ #include <asio/static_thread_pool.hpp> #include <iostream> #include <string> using asio::bind_executor; using asio::static_thread_pool; void reader(queue_front<std::string> out) { std::string line; while (std::getline(std::cin, line)) out.push(line); } void filter(queue_back<std::string> in, queue_front<std::string> out) { std::string line; while (in.pop(line)) if (line.length() > 5) out.push(line); } void upper(queue_back<std::string> in, queue_front<std::string> out) { std::string line; while (in.pop(line)) { std::string new_line; for (char c : line) new_line.push_back(std::toupper(c)); out.push(new_line); } } void writer(queue_back<std::string> in) { std::size_t count = 0; std::string line; while (in.pop(line)) std::cout << count++ << ": " << line << std::endl; } int main() { static_thread_pool pool(1); auto f = pipeline(reader, filter, bind_executor(pool.executor(), upper), writer); f.wait(); }
0
repos/asio/asio/src/examples/cpp14
repos/asio/asio/src/examples/cpp14/executors/priority_scheduler.cpp
#include <asio/execution.hpp> #include <condition_variable> #include <iostream> #include <memory> #include <mutex> #include <queue> namespace execution = asio::execution; namespace custom_props { struct priority { template <typename T> static constexpr bool is_applicable_property_v = execution::is_executor<T>::value; static constexpr bool is_requirable = true; static constexpr bool is_preferable = true; using polymorphic_query_result_type = int; int value() const { return value_; } int value_ = 1; }; constexpr priority low_priority{0}; constexpr priority normal_priority{1}; constexpr priority high_priority{2}; } // namespace custom_props class priority_scheduler { public: // A class that satisfies the Executor requirements. class executor_type { public: executor_type(priority_scheduler& ctx) noexcept : context_(ctx), priority_(custom_props::normal_priority.value()) { } priority_scheduler& query(execution::context_t) const noexcept { return context_; } int query(custom_props::priority) const noexcept { return priority_; } executor_type require(custom_props::priority pri) const { executor_type new_ex(*this); new_ex.priority_ = pri.value(); return new_ex; } template <class Func> void execute(Func f) const { auto p(std::make_shared<item<Func>>(priority_, std::move(f))); std::lock_guard<std::mutex> lock(context_.mutex_); context_.queue_.push(p); context_.condition_.notify_one(); } friend bool operator==(const executor_type& a, const executor_type& b) noexcept { return &a.context_ == &b.context_; } friend bool operator!=(const executor_type& a, const executor_type& b) noexcept { return &a.context_ != &b.context_; } private: priority_scheduler& context_; int priority_; }; executor_type executor() noexcept { return executor_type(*const_cast<priority_scheduler*>(this)); } void run() { std::unique_lock<std::mutex> lock(mutex_); for (;;) { condition_.wait(lock, [&]{ return stopped_ || !queue_.empty(); }); if (stopped_) return; auto p(queue_.top()); queue_.pop(); lock.unlock(); p->execute_(p); lock.lock(); } } void stop() { std::lock_guard<std::mutex> lock(mutex_); stopped_ = true; condition_.notify_all(); } private: struct item_base { int priority_; void (*execute_)(std::shared_ptr<item_base>&); }; template <class Func> struct item : item_base { item(int pri, Func f) : function_(std::move(f)) { priority_ = pri; execute_ = [](std::shared_ptr<item_base>& p) { Func tmp(std::move(static_cast<item*>(p.get())->function_)); p.reset(); tmp(); }; } Func function_; }; struct item_comp { bool operator()( const std::shared_ptr<item_base>& a, const std::shared_ptr<item_base>& b) { return a->priority_ < b->priority_; } }; std::mutex mutex_; std::condition_variable condition_; std::priority_queue< std::shared_ptr<item_base>, std::vector<std::shared_ptr<item_base>>, item_comp> queue_; bool stopped_ = false; }; int main() { priority_scheduler sched; auto ex = sched.executor(); auto prefer_low = asio::prefer(ex, custom_props::low_priority); auto low = asio::require(ex, custom_props::low_priority); auto med = asio::require(ex, custom_props::normal_priority); auto high = asio::require(ex, custom_props::high_priority); execution::any_executor<custom_props::priority> poly_high(high); prefer_low.execute([]{ std::cout << "1\n"; }); low.execute([]{ std::cout << "11\n"; }); low.execute([]{ std::cout << "111\n"; }); med.execute([]{ std::cout << "2\n"; }); med.execute([]{ std::cout << "22\n"; }); high.execute([]{ std::cout << "3\n"; }); high.execute([]{ std::cout << "33\n"; }); high.execute([]{ std::cout << "333\n"; }); poly_high.execute([]{ std::cout << "3333\n"; }); asio::require(ex, custom_props::priority{-1}).execute([&]{ sched.stop(); }); sched.run(); std::cout << "polymorphic query result = " << asio::query(poly_high, custom_props::priority{}) << "\n"; }
0
repos/asio/asio/src/examples/cpp14
repos/asio/asio/src/examples/cpp14/executors/actor.cpp
#include <asio/any_io_executor.hpp> #include <asio/defer.hpp> #include <asio/post.hpp> #include <asio/strand.hpp> #include <asio/system_executor.hpp> #include <condition_variable> #include <deque> #include <memory> #include <mutex> #include <typeinfo> #include <vector> using asio::any_io_executor; using asio::defer; using asio::post; using asio::strand; using asio::system_executor; //------------------------------------------------------------------------------ // A tiny actor framework // ~~~~~~~~~~~~~~~~~~~~~~ class actor; // Used to identify the sender and recipient of messages. typedef actor* actor_address; // Base class for all registered message handlers. class message_handler_base { public: virtual ~message_handler_base() {} // Used to determine which message handlers receive an incoming message. virtual const std::type_info& message_id() const = 0; }; // Base class for a handler for a specific message type. template <class Message> class message_handler : public message_handler_base { public: // Handle an incoming message. virtual void handle_message(Message msg, actor_address from) = 0; }; // Concrete message handler for a specific message type. template <class Actor, class Message> class mf_message_handler : public message_handler<Message> { public: // Construct a message handler to invoke the specified member function. mf_message_handler(void (Actor::* mf)(Message, actor_address), Actor* a) : function_(mf), actor_(a) { } // Used to determine which message handlers receive an incoming message. virtual const std::type_info& message_id() const { return typeid(Message); } // Handle an incoming message. virtual void handle_message(Message msg, actor_address from) { (actor_->*function_)(std::move(msg), from); } // Determine whether the message handler represents the specified function. bool is_function(void (Actor::* mf)(Message, actor_address)) const { return mf == function_; } private: void (Actor::* function_)(Message, actor_address); Actor* actor_; }; // Base class for all actors. class actor { public: virtual ~actor() { } // Obtain the actor's address for use as a message sender or recipient. actor_address address() { return this; } // Send a message from one actor to another. template <class Message> friend void send(Message msg, actor_address from, actor_address to) { // Execute the message handler in the context of the target's executor. post(to->executor_, [=, msg=std::move(msg)]() mutable { to->call_handler(std::move(msg), from); }); } protected: // Construct the actor to use the specified executor for all message handlers. actor(any_io_executor e) : executor_(std::move(e)) { } // Register a handler for a specific message type. Duplicates are permitted. template <class Actor, class Message> void register_handler(void (Actor::* mf)(Message, actor_address)) { handlers_.push_back( std::make_shared<mf_message_handler<Actor, Message>>( mf, static_cast<Actor*>(this))); } // Deregister a handler. Removes only the first matching handler. template <class Actor, class Message> void deregister_handler(void (Actor::* mf)(Message, actor_address)) { const std::type_info& id = typeid(Message); for (auto iter = handlers_.begin(); iter != handlers_.end(); ++iter) { if ((*iter)->message_id() == id) { auto mh = static_cast<mf_message_handler<Actor, Message>*>(iter->get()); if (mh->is_function(mf)) { handlers_.erase(iter); return; } } } } // Send a message from within a message handler. template <class Message> void tail_send(Message msg, actor_address to) { // Execute the message handler in the context of the target's executor. defer(to->executor_, [=, msg=std::move(msg), from=this] { to->call_handler(std::move(msg), from); }); } private: // Find the matching message handlers, if any, and call them. template <class Message> void call_handler(Message msg, actor_address from) { const std::type_info& message_id = typeid(Message); for (auto& h: handlers_) { if (h->message_id() == message_id) { auto mh = static_cast<message_handler<Message>*>(h.get()); mh->handle_message(msg, from); } } } // All messages associated with a single actor object should be processed // non-concurrently. We use a strand to ensure non-concurrent execution even // if the underlying executor may use multiple threads. strand<any_io_executor> executor_; std::vector<std::shared_ptr<message_handler_base>> handlers_; }; // A concrete actor that allows synchronous message retrieval. template <class Message> class receiver : public actor { public: receiver() : actor(system_executor()) { register_handler(&receiver::message_handler); } // Block until a message has been received. Message wait() { std::unique_lock<std::mutex> lock(mutex_); condition_.wait(lock, [this]{ return !message_queue_.empty(); }); Message msg(std::move(message_queue_.front())); message_queue_.pop_front(); return msg; } private: // Handle a new message by adding it to the queue and waking a waiter. void message_handler(Message msg, actor_address /* from */) { std::lock_guard<std::mutex> lock(mutex_); message_queue_.push_back(std::move(msg)); condition_.notify_one(); } std::mutex mutex_; std::condition_variable condition_; std::deque<Message> message_queue_; }; //------------------------------------------------------------------------------ #include <asio/thread_pool.hpp> #include <iostream> using asio::thread_pool; class member : public actor { public: explicit member(any_io_executor e) : actor(std::move(e)) { register_handler(&member::init_handler); } private: void init_handler(actor_address next, actor_address from) { next_ = next; caller_ = from; register_handler(&member::token_handler); deregister_handler(&member::init_handler); } void token_handler(int token, actor_address /*from*/) { int msg(token); actor_address to(caller_); if (token > 0) { msg = token - 1; to = next_; } tail_send(msg, to); } actor_address next_; actor_address caller_; }; int main() { const std::size_t num_threads = 16; const int num_hops = 50000000; const std::size_t num_actors = 503; const int token_value = (num_hops + num_actors - 1) / num_actors; const std::size_t actors_per_thread = num_actors / num_threads; struct single_thread_pool : thread_pool { single_thread_pool() : thread_pool(1) {} }; single_thread_pool pools[num_threads]; std::vector<std::shared_ptr<member>> members(num_actors); receiver<int> rcvr; // Create the member actors. for (std::size_t i = 0; i < num_actors; ++i) members[i] = std::make_shared<member>(pools[(i / actors_per_thread) % num_threads].get_executor()); // Initialise the actors by passing each one the address of the next actor in the ring. for (std::size_t i = num_actors, next_i = 0; i > 0; next_i = --i) send(members[next_i]->address(), rcvr.address(), members[i - 1]->address()); // Send exactly one token to each actor, all with the same initial value, rounding up if required. for (std::size_t i = 0; i < num_actors; ++i) send(token_value, rcvr.address(), members[i]->address()); // Wait for all signal messages, indicating the tokens have all reached zero. for (std::size_t i = 0; i < num_actors; ++i) rcvr.wait(); }
0
repos/asio/asio/src/examples/cpp14
repos/asio/asio/src/examples/cpp14/executors/bank_account_1.cpp
#include <asio/execution.hpp> #include <asio/static_thread_pool.hpp> #include <iostream> using asio::static_thread_pool; namespace execution = asio::execution; // Traditional active object pattern. // Member functions do not block. class bank_account { int balance_ = 0; mutable static_thread_pool pool_{1}; public: void deposit(int amount) { pool_.executor().execute( [this, amount] { balance_ += amount; }); } void withdraw(int amount) { pool_.executor().execute( [this, amount] { if (balance_ >= amount) balance_ -= amount; }); } void print_balance() const { pool_.executor().execute( [this] { std::cout << "balance = " << balance_ << "\n"; }); } ~bank_account() { pool_.wait(); } }; int main() { bank_account acct; acct.deposit(20); acct.withdraw(10); acct.print_balance(); }
0
repos/asio/asio/src/examples/cpp14
repos/asio/asio/src/examples/cpp14/executors/fork_join.cpp
#include <asio/execution.hpp> #include <asio/static_thread_pool.hpp> #include <algorithm> #include <condition_variable> #include <memory> #include <mutex> #include <queue> #include <thread> #include <numeric> using asio::static_thread_pool; namespace execution = asio::execution; // A fixed-size thread pool used to implement fork/join semantics. Functions // are scheduled using a simple FIFO queue. Implementing work stealing, or // using a queue based on atomic operations, are left as tasks for the reader. class fork_join_pool { public: // The constructor starts a thread pool with the specified number of threads. // Note that the thread_count is not a fixed limit on the pool's concurrency. // Additional threads may temporarily be added to the pool if they join a // fork_executor. explicit fork_join_pool( std::size_t thread_count = std::max(std::thread::hardware_concurrency(), 1u) * 2) : use_count_(1), threads_(thread_count) { try { // Ask each thread in the pool to dequeue and execute functions until // it is time to shut down, i.e. the use count is zero. for (thread_count_ = 0; thread_count_ < thread_count; ++thread_count_) { threads_.executor().execute( [this] { std::unique_lock<std::mutex> lock(mutex_); while (use_count_ > 0) if (!execute_next(lock)) condition_.wait(lock); }); } } catch (...) { stop_threads(); threads_.wait(); throw; } } // The destructor waits for the pool to finish executing functions. ~fork_join_pool() { stop_threads(); threads_.wait(); } private: friend class fork_executor; // The base for all functions that are queued in the pool. struct function_base { std::shared_ptr<std::size_t> work_count_; void (*execute_)(std::shared_ptr<function_base>& p); }; // Execute the next function from the queue, if any. Returns true if a // function was executed, and false if the queue was empty. bool execute_next(std::unique_lock<std::mutex>& lock) { if (queue_.empty()) return false; auto p(queue_.front()); queue_.pop(); lock.unlock(); execute(lock, p); return true; } // Execute a function and decrement the outstanding work. void execute(std::unique_lock<std::mutex>& lock, std::shared_ptr<function_base>& p) { std::shared_ptr<std::size_t> work_count(std::move(p->work_count_)); try { p->execute_(p); lock.lock(); do_work_finished(work_count); } catch (...) { lock.lock(); do_work_finished(work_count); throw; } } // Increment outstanding work. void do_work_started(const std::shared_ptr<std::size_t>& work_count) noexcept { if (++(*work_count) == 1) ++use_count_; } // Decrement outstanding work. Notify waiting threads if we run out. void do_work_finished(const std::shared_ptr<std::size_t>& work_count) noexcept { if (--(*work_count) == 0) { --use_count_; condition_.notify_all(); } } // Dispatch a function, executing it immediately if the queue is already // loaded. Otherwise adds the function to the queue and wakes a thread. void do_execute(std::shared_ptr<function_base> p, const std::shared_ptr<std::size_t>& work_count) { std::unique_lock<std::mutex> lock(mutex_); if (queue_.size() > thread_count_ * 16) { do_work_started(work_count); lock.unlock(); execute(lock, p); } else { queue_.push(p); do_work_started(work_count); condition_.notify_one(); } } // Ask all threads to shut down. void stop_threads() { std::lock_guard<std::mutex> lock(mutex_); --use_count_; condition_.notify_all(); } std::mutex mutex_; std::condition_variable condition_; std::queue<std::shared_ptr<function_base>> queue_; std::size_t use_count_; std::size_t thread_count_; static_thread_pool threads_; }; // A class that satisfies the Executor requirements. Every function or piece of // work associated with a fork_executor is part of a single, joinable group. class fork_executor { public: fork_executor(fork_join_pool& ctx) : context_(ctx), work_count_(std::make_shared<std::size_t>(0)) { } fork_join_pool& query(execution::context_t) const noexcept { return context_; } template <class Func> void execute(Func f) const { auto p(std::make_shared<function<Func>>(std::move(f), work_count_)); context_.do_execute(p, work_count_); } friend bool operator==(const fork_executor& a, const fork_executor& b) noexcept { return a.work_count_ == b.work_count_; } friend bool operator!=(const fork_executor& a, const fork_executor& b) noexcept { return a.work_count_ != b.work_count_; } // Block until all work associated with the executor is complete. While it is // waiting, the thread may be borrowed to execute functions from the queue. void join() const { std::unique_lock<std::mutex> lock(context_.mutex_); while (*work_count_ > 0) if (!context_.execute_next(lock)) context_.condition_.wait(lock); } private: template <class Func> struct function : fork_join_pool::function_base { explicit function(Func f, const std::shared_ptr<std::size_t>& w) : function_(std::move(f)) { work_count_ = w; execute_ = [](std::shared_ptr<fork_join_pool::function_base>& p) { Func tmp(std::move(static_cast<function*>(p.get())->function_)); p.reset(); tmp(); }; } Func function_; }; fork_join_pool& context_; std::shared_ptr<std::size_t> work_count_; }; // Helper class to automatically join a fork_executor when exiting a scope. class join_guard { public: explicit join_guard(const fork_executor& ex) : ex_(ex) {} join_guard(const join_guard&) = delete; join_guard(join_guard&&) = delete; ~join_guard() { ex_.join(); } private: fork_executor ex_; }; //------------------------------------------------------------------------------ #include <algorithm> #include <iostream> #include <random> #include <vector> fork_join_pool pool; template <class Iterator> void fork_join_sort(Iterator begin, Iterator end) { std::size_t n = end - begin; if (n > 32768) { { fork_executor fork(pool); join_guard join(fork); fork.execute([=]{ fork_join_sort(begin, begin + n / 2); }); fork.execute([=]{ fork_join_sort(begin + n / 2, end); }); } std::inplace_merge(begin, begin + n / 2, end); } else { std::sort(begin, end); } } int main(int argc, char* argv[]) { if (argc != 2) { std::cerr << "Usage: fork_join <size>\n"; return 1; } std::vector<double> vec(std::atoll(argv[1])); std::iota(vec.begin(), vec.end(), 0); std::random_device rd; std::mt19937 g(rd()); std::shuffle(vec.begin(), vec.end(), g); std::chrono::steady_clock::time_point start = std::chrono::steady_clock::now(); fork_join_sort(vec.begin(), vec.end()); std::chrono::steady_clock::duration elapsed = std::chrono::steady_clock::now() - start; std::cout << "sort took "; std::cout << std::chrono::duration_cast<std::chrono::microseconds>(elapsed).count(); std::cout << " microseconds" << std::endl; }
0
repos/asio/asio/src/examples/cpp14
repos/asio/asio/src/examples/cpp14/operations/composed_8.cpp
// // 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, typename 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++14 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. 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(); }
0
repos/asio/asio/src/examples/cpp14
repos/asio/asio/src/examples/cpp14/operations/composed_6.cpp
// // 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, typename 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++14 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 = [](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 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. 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. 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(); }
0
repos/asio/asio/src/examples/cpp14
repos/asio/asio/src/examples/cpp14/operations/composed_2.cpp
// // 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 <typename 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++14 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 = [](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. 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(); }
0
repos/asio/asio/src/examples/cpp14
repos/asio/asio/src/examples/cpp14/operations/composed_4.cpp
// // 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 <typename 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++14 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 = [](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. 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(); }
0
repos/asio/asio/src/examples/cpp14
repos/asio/asio/src/examples/cpp14/operations/composed_7.cpp
// // 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, typename 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++14 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. 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(); }
0
repos/asio/asio/src/examples/cpp14
repos/asio/asio/src/examples/cpp14/operations/c_callback_wrapper.cpp
// // 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 <typename 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 <typename 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 = [](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(); }
0
repos/asio/asio/src/examples/cpp14
repos/asio/asio/src/examples/cpp14/operations/composed_5.cpp
// // 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, typename 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++14 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 = [](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. 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(); }
0
repos/asio/asio/src/examples/cpp14
repos/asio/asio/src/examples/cpp14/operations/composed_3.cpp
// // 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 <typename 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++14 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 = [](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. 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(); }
0
repos/asio/asio/src/examples/cpp14
repos/asio/asio/src/examples/cpp14/operations/callback_wrapper.cpp
// // 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 <typename 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 = [](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(); }
0
repos/asio/asio/src/examples/cpp14
repos/asio/asio/src/examples/cpp14/operations/composed_1.cpp
// // 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 <typename 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++14 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. 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(); }
0
repos/asio/asio/src/examples/cpp14
repos/asio/asio/src/examples/cpp14/deferred/deferred_5.cpp
// // deferred_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.hpp> #include <iostream> using asio::deferred; template <typename CompletionToken> auto async_wait_twice(asio::steady_timer& timer, CompletionToken&& token) { return timer.async_wait( deferred( [&](std::error_code ec) { std::cout << "first timer wait finished: " << ec.message() << "\n"; timer.expires_after(std::chrono::seconds(1)); return deferred.when(!ec) .then(timer.async_wait(deferred)) .otherwise(deferred.values(ec)); } ) )( deferred( [&](std::error_code ec) { std::cout << "second timer wait finished: " << ec.message() << "\n"; return deferred.when(!ec) .then(deferred.values(42)) .otherwise(deferred.values(0)); } ) )( std::forward<CompletionToken>(token) ); } int main() { asio::io_context ctx; asio::steady_timer timer(ctx); timer.expires_after(std::chrono::seconds(1)); async_wait_twice( timer, [](int result) { std::cout << "result is " << result << "\n"; } ); // Uncomment the following line to trigger an error in async_wait_twice. //timer.cancel(); ctx.run(); return 0; }
0
repos/asio/asio/src/examples/cpp14
repos/asio/asio/src/examples/cpp14/deferred/deferred_7.cpp
// // deferred_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.hpp> #include <iostream> using asio::append; using asio::deferred; template <typename CompletionToken> auto async_wait_twice(asio::steady_timer& timer, CompletionToken&& token) { return deferred.values(&timer) | deferred( [](asio::steady_timer* timer) { timer->expires_after(std::chrono::seconds(1)); return timer->async_wait(append(deferred, timer)); } ) | deferred( [](std::error_code ec, asio::steady_timer* timer) { std::cout << "first timer wait finished: " << ec.message() << "\n"; timer->expires_after(std::chrono::seconds(1)); return deferred.when(!ec) .then(timer->async_wait(deferred)) .otherwise(deferred.values(ec)); } ) | deferred( [](std::error_code ec) { std::cout << "second timer wait finished: " << ec.message() << "\n"; return deferred.when(!ec) .then(deferred.values(42)) .otherwise(deferred.values(0)); } ) | std::forward<CompletionToken>(token); } int main() { asio::io_context ctx; asio::steady_timer timer(ctx); timer.expires_after(std::chrono::seconds(1)); async_wait_twice( timer, [](int result) { std::cout << "result is " << result << "\n"; } ); // Uncomment the following line to trigger an error in async_wait_twice. //timer.cancel(); ctx.run(); return 0; }
0
repos/asio/asio/src/examples/cpp14
repos/asio/asio/src/examples/cpp14/deferred/deferred_4.cpp
// // deferred_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.hpp> #include <iostream> using asio::deferred; template <typename CompletionToken> auto async_wait_twice(asio::steady_timer& timer, CompletionToken&& token) { return timer.async_wait( deferred( [&](std::error_code ec) { std::cout << "first timer wait finished: " << ec.message() << "\n"; timer.expires_after(std::chrono::seconds(1)); return timer.async_wait(deferred); } ) )( deferred( [&](std::error_code ec) { std::cout << "second timer wait finished: " << ec.message() << "\n"; return deferred.values(42); } ) )( std::forward<CompletionToken>(token) ); } int main() { asio::io_context ctx; asio::steady_timer timer(ctx); timer.expires_after(std::chrono::seconds(1)); async_wait_twice( timer, [](int result) { std::cout << "result is " << result << "\n"; } ); ctx.run(); return 0; }
0
repos/asio/asio/src/examples/cpp14
repos/asio/asio/src/examples/cpp14/deferred/deferred_3.cpp
// // deferred_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.hpp> #include <iostream> using asio::deferred; template <typename CompletionToken> auto async_wait_twice(asio::steady_timer& timer, CompletionToken&& token) { return timer.async_wait( deferred( [&](std::error_code ec) { std::cout << "first timer wait finished: " << ec.message() << "\n"; timer.expires_after(std::chrono::seconds(1)); return timer.async_wait(deferred); } ) )( std::forward<CompletionToken>(token) ); } int main() { asio::io_context ctx; asio::steady_timer timer(ctx); timer.expires_after(std::chrono::seconds(1)); async_wait_twice( timer, [](std::error_code ec) { std::cout << "second timer wait finished: " << ec.message() << "\n"; } ); ctx.run(); return 0; }
0
repos/asio/asio/src/examples/cpp14
repos/asio/asio/src/examples/cpp14/deferred/deferred_1.cpp
// // deferred_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.hpp> #include <iostream> using asio::deferred; int main() { asio::io_context ctx; asio::steady_timer timer(ctx); timer.expires_after(std::chrono::seconds(1)); auto deferred_op = timer.async_wait(deferred); std::move(deferred_op)( [](std::error_code ec) { std::cout << "timer wait finished: " << ec.message() << "\n"; } ); ctx.run(); return 0; }
0
repos/asio/asio/src/examples/cpp14
repos/asio/asio/src/examples/cpp14/deferred/deferred_2.cpp
// // deferred_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.hpp> #include <iostream> using asio::deferred; int main() { asio::io_context ctx; asio::steady_timer timer(ctx); timer.expires_after(std::chrono::seconds(1)); auto deferred_op = timer.async_wait( deferred( [&](std::error_code ec) { std::cout << "first timer wait finished: " << ec.message() << "\n"; timer.expires_after(std::chrono::seconds(1)); return timer.async_wait(deferred); } ) ); std::move(deferred_op)( [](std::error_code ec) { std::cout << "second timer wait finished: " << ec.message() << "\n"; } ); ctx.run(); return 0; }
0
repos/asio/asio/src/examples/cpp14
repos/asio/asio/src/examples/cpp14/deferred/deferred_6.cpp
// // deferred_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.hpp> #include <iostream> using asio::append; using asio::deferred; template <typename CompletionToken> auto async_wait_twice(asio::steady_timer& timer, CompletionToken&& token) { return deferred.values(&timer)( deferred( [](asio::steady_timer* timer) { timer->expires_after(std::chrono::seconds(1)); return timer->async_wait(append(deferred, timer)); } ) )( deferred( [](std::error_code ec, asio::steady_timer* timer) { std::cout << "first timer wait finished: " << ec.message() << "\n"; timer->expires_after(std::chrono::seconds(1)); return deferred.when(!ec) .then(timer->async_wait(deferred)) .otherwise(deferred.values(ec)); } ) )( deferred( [](std::error_code ec) { std::cout << "second timer wait finished: " << ec.message() << "\n"; return deferred.when(!ec) .then(deferred.values(42)) .otherwise(deferred.values(0)); } ) )( std::forward<CompletionToken>(token) ); } int main() { asio::io_context ctx; asio::steady_timer timer(ctx); timer.expires_after(std::chrono::seconds(1)); async_wait_twice( timer, [](int result) { std::cout << "result is " << result << "\n"; } ); // Uncomment the following line to trigger an error in async_wait_twice. //timer.cancel(); ctx.run(); return 0; }
0
repos/asio/asio/src/examples/cpp14
repos/asio/asio/src/examples/cpp14/iostreams/http_client.cpp
// // http_client.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 <iostream> #include <istream> #include <ostream> #include <string> #include <asio/ts/internet.hpp> using asio::ip::tcp; int main(int argc, char* argv[]) { try { if (argc != 3) { std::cout << "Usage: http_client <server> <path>\n"; std::cout << "Example:\n"; std::cout << " http_client www.boost.org /LICENSE_1_0.txt\n"; return 1; } asio::ip::tcp::iostream s; // The entire sequence of I/O operations must complete within 60 seconds. // If an expiry occurs, the socket is automatically closed and the stream // becomes bad. s.expires_after(std::chrono::seconds(60)); // Establish a connection to the server. s.connect(argv[1], "http"); if (!s) { std::cout << "Unable to connect: " << s.error().message() << "\n"; return 1; } // Send the request. We specify the "Connection: close" header so that the // server will close the socket after transmitting the response. This will // allow us to treat all data up until the EOF as the content. s << "GET " << argv[2] << " HTTP/1.0\r\n"; s << "Host: " << argv[1] << "\r\n"; s << "Accept: */*\r\n"; s << "Connection: close\r\n\r\n"; // By default, the stream is tied with itself. This means that the stream // automatically flush the buffered output before attempting a read. It is // not necessary not explicitly flush the stream at this point. // Check that response is OK. std::string http_version; s >> http_version; unsigned int status_code; s >> status_code; std::string status_message; std::getline(s, status_message); if (!s || http_version.substr(0, 5) != "HTTP/") { std::cout << "Invalid response\n"; return 1; } if (status_code != 200) { std::cout << "Response returned with status code " << status_code << "\n"; return 1; } // Process the response headers, which are terminated by a blank line. std::string header; while (std::getline(s, header) && header != "\r") std::cout << header << "\n"; std::cout << "\n"; // Write the remaining data to output. std::cout << s.rdbuf(); } catch (std::exception& e) { std::cout << "Exception: " << e.what() << "\n"; } return 0; }
0
repos/asio/asio/src/examples/cpp14
repos/asio/asio/src/examples/cpp14/parallel_group/wait_for_one_success.cpp
// // wait_for_one_error.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 <asio/experimental/parallel_group.hpp> #include <iostream> #if defined(ASIO_HAS_POSIX_STREAM_DESCRIPTOR) int main() { asio::io_context ctx; asio::posix::stream_descriptor in(ctx, ::dup(STDIN_FILENO)); asio::steady_timer timer(ctx, std::chrono::seconds(5)); char data[1024]; asio::experimental::make_parallel_group( [&](auto token) { return in.async_read_some(asio::buffer(data), token); }, [&](auto token) { return timer.async_wait(token); } ).async_wait( asio::experimental::wait_for_one_success(), []( std::array<std::size_t, 2> completion_order, std::error_code ec1, std::size_t n1, std::error_code ec2 ) { switch (completion_order[0]) { case 0: { std::cout << "descriptor finished: " << ec1 << ", " << n1 << "\n"; } break; case 1: { std::cout << "timer finished: " << ec2 << "\n"; } break; } } ); ctx.run(); } #else // defined(ASIO_HAS_POSIX_STREAM_DESCRIPTOR) int main() {} #endif // defined(ASIO_HAS_POSIX_STREAM_DESCRIPTOR)
0
repos/asio/asio/src/examples/cpp14
repos/asio/asio/src/examples/cpp14/parallel_group/wait_for_one_error.cpp
// // wait_for_one_error.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 <asio/experimental/parallel_group.hpp> #include <iostream> #if defined(ASIO_HAS_POSIX_STREAM_DESCRIPTOR) int main() { asio::io_context ctx; asio::posix::stream_descriptor in(ctx, ::dup(STDIN_FILENO)); asio::steady_timer timer(ctx, std::chrono::seconds(5)); char data[1024]; asio::experimental::make_parallel_group( [&](auto token) { return in.async_read_some(asio::buffer(data), token); }, [&](auto token) { return timer.async_wait(token); } ).async_wait( asio::experimental::wait_for_one_error(), []( std::array<std::size_t, 2> completion_order, std::error_code ec1, std::size_t n1, std::error_code ec2 ) { switch (completion_order[0]) { case 0: { std::cout << "descriptor finished: " << ec1 << ", " << n1 << "\n"; } break; case 1: { std::cout << "timer finished: " << ec2 << "\n"; } break; } } ); ctx.run(); } #else // defined(ASIO_HAS_POSIX_STREAM_DESCRIPTOR) int main() {} #endif // defined(ASIO_HAS_POSIX_STREAM_DESCRIPTOR)
0
repos/asio/asio/src/examples/cpp14
repos/asio/asio/src/examples/cpp14/parallel_group/wait_for_all.cpp
// // wait_for_all.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 <asio/experimental/parallel_group.hpp> #include <iostream> #ifdef ASIO_HAS_POSIX_STREAM_DESCRIPTOR int main() { asio::io_context ctx; asio::posix::stream_descriptor in(ctx, ::dup(STDIN_FILENO)); asio::steady_timer timer(ctx, std::chrono::seconds(5)); char data[1024]; asio::experimental::make_parallel_group( [&](auto token) { return in.async_read_some(asio::buffer(data), token); }, [&](auto token) { return timer.async_wait(token); } ).async_wait( asio::experimental::wait_for_all(), []( std::array<std::size_t, 2> completion_order, std::error_code ec1, std::size_t n1, std::error_code ec2 ) { switch (completion_order[0]) { case 0: { std::cout << "descriptor finished: " << ec1 << ", " << n1 << "\n"; } break; case 1: { std::cout << "timer finished: " << ec2 << "\n"; } break; } } ); ctx.run(); } #else // defined(ASIO_HAS_POSIX_STREAM_DESCRIPTOR) int main() {} #endif // defined(ASIO_HAS_POSIX_STREAM_DESCRIPTOR)
0
repos/asio/asio/src/examples/cpp14
repos/asio/asio/src/examples/cpp14/parallel_group/wait_for_one.cpp
// // wait_for_one.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 <asio/experimental/parallel_group.hpp> #include <iostream> #if defined(ASIO_HAS_POSIX_STREAM_DESCRIPTOR) int main() { asio::io_context ctx; asio::posix::stream_descriptor in(ctx, ::dup(STDIN_FILENO)); asio::steady_timer timer(ctx, std::chrono::seconds(5)); char data[1024]; asio::experimental::make_parallel_group( [&](auto token) { return in.async_read_some(asio::buffer(data), token); }, [&](auto token) { return timer.async_wait(token); } ).async_wait( asio::experimental::wait_for_one(), []( std::array<std::size_t, 2> completion_order, std::error_code ec1, std::size_t n1, std::error_code ec2 ) { switch (completion_order[0]) { case 0: { std::cout << "descriptor finished: " << ec1 << ", " << n1 << "\n"; } break; case 1: { std::cout << "timer finished: " << ec2 << "\n"; } break; } } ); ctx.run(); } #else // defined(ASIO_HAS_POSIX_STREAM_DESCRIPTOR) int main() {} #endif // defined(ASIO_HAS_POSIX_STREAM_DESCRIPTOR)
0
repos/asio/asio/src/examples/cpp14
repos/asio/asio/src/examples/cpp14/parallel_group/ranged_wait_for_all.cpp
// // ranged_wait_for_all.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 <asio/experimental/parallel_group.hpp> #include <iostream> #include <vector> #ifdef ASIO_HAS_POSIX_STREAM_DESCRIPTOR int main() { asio::io_context ctx; asio::posix::stream_descriptor out(ctx, ::dup(STDOUT_FILENO)); asio::posix::stream_descriptor err(ctx, ::dup(STDERR_FILENO)); using op_type = decltype( out.async_write_some(asio::buffer("", 0)) ); std::vector<op_type> ops; ops.push_back( out.async_write_some(asio::buffer("first\r\n", 7)) ); ops.push_back( err.async_write_some(asio::buffer("second\r\n", 8)) ); asio::experimental::make_parallel_group(ops).async_wait( asio::experimental::wait_for_all(), []( std::vector<std::size_t> completion_order, std::vector<std::error_code> ec, std::vector<std::size_t> n ) { for (std::size_t i = 0; i < completion_order.size(); ++i) { std::size_t idx = completion_order[i]; std::cout << "operation " << idx << " finished: "; std::cout << ec[idx] << ", " << n[idx] << "\n"; } } ); ctx.run(); } #else // defined(ASIO_HAS_POSIX_STREAM_DESCRIPTOR) int main() {} #endif // defined(ASIO_HAS_POSIX_STREAM_DESCRIPTOR)
0
repos/asio/asio/src/examples/cpp14
repos/asio/asio/src/examples/cpp14/parallel_group/parallel_sort.cpp
// // parallel_sort.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 <asio/experimental/parallel_group.hpp> #include <algorithm> #include <chrono> #include <functional> #include <iostream> #include <random> template < typename Executor, typename RandomAccessIterator, ASIO_COMPLETION_TOKEN_FOR(void()) CompletionToken> auto parallel_sort( Executor executor, RandomAccessIterator begin, RandomAccessIterator end, CompletionToken&& token); template < typename Executor, typename RandomAccessIterator> void parallel_sort_impl( Executor executor, RandomAccessIterator begin, RandomAccessIterator end, std::function<void()> continuation) { std::size_t n = end - begin; if (n <= 16384) { asio::post(executor, [=] { std::sort(begin, end); continuation(); } ); } else { asio::experimental::make_parallel_group( [=](auto token) { return parallel_sort(executor, begin, begin + n / 2, token); }, [=](auto token) { return parallel_sort(executor, begin + n / 2, end, token); } ).async_wait( asio::experimental::wait_for_all(), [=](std::array<std::size_t, 2>) { std::inplace_merge(begin, begin + n / 2, end); continuation(); } ); } } template < typename Executor, typename RandomAccessIterator, ASIO_COMPLETION_TOKEN_FOR(void()) CompletionToken> auto parallel_sort( Executor executor, RandomAccessIterator begin, RandomAccessIterator end, CompletionToken&& token) { return asio::async_compose<CompletionToken, void()>( [=](auto& self, auto... args) { if (sizeof...(args) == 0) { using self_type = std::decay_t<decltype(self)>; parallel_sort_impl(executor, begin, end, [self = std::make_shared<self_type>(std::move(self))] { asio::dispatch( asio::append( std::move(*self), 0)); } ); } else { self.complete(); } }, token ); } int main() { asio::thread_pool pool(4); std::vector<int> values(100'000'000); std::random_device random_device; std::mt19937 rng(random_device()); std::uniform_int_distribution<int> dist(1, 1'000'000); std::generate(values.begin(), values.end(), [&]{ return dist(rng); }); std::cout << "starting sort\n"; auto begin = std::chrono::high_resolution_clock::now(); parallel_sort( pool.get_executor(), values.begin(), values.end(), asio::use_future ).get(); auto end = std::chrono::high_resolution_clock::now(); auto duration = end - begin; std::cout << "sort took " << std::chrono::duration_cast<std::chrono::microseconds>(duration).count() << " microseconds\n"; }
0
repos/asio/asio/src/examples/cpp17
repos/asio/asio/src/examples/cpp17/coroutines_ts/echo_server_with_as_tuple_default.cpp
// // echo_server_with_as_tuple_default.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/as_tuple.hpp> #include <asio/co_spawn.hpp> #include <asio/detached.hpp> #include <asio/io_context.hpp> #include <asio/ip/tcp.hpp> #include <asio/signal_set.hpp> #include <asio/write.hpp> #include <cstdio> using asio::as_tuple_t; using asio::ip::tcp; using asio::awaitable; using asio::co_spawn; using asio::detached; using asio::use_awaitable_t; using default_token = as_tuple_t<use_awaitable_t<>>; using tcp_acceptor = default_token::as_default_on_t<tcp::acceptor>; using tcp_socket = default_token::as_default_on_t<tcp::socket>; namespace this_coro = asio::this_coro; awaitable<void> echo(tcp_socket socket) { char data[1024]; for (;;) { auto [e1, nread] = co_await socket.async_read_some(asio::buffer(data)); if (nread == 0) break; auto [e2, nwritten] = co_await async_write(socket, asio::buffer(data, nread)); if (nwritten != nread) break; } } awaitable<void> listener() { auto executor = co_await this_coro::executor; tcp_acceptor acceptor(executor, {tcp::v4(), 55555}); for (;;) { if (auto [e, socket] = co_await acceptor.async_accept(); socket.is_open()) co_spawn(executor, echo(std::move(socket)), detached); } } int main() { try { asio::io_context io_context(1); asio::signal_set signals(io_context, SIGINT, SIGTERM); signals.async_wait([&](auto, auto){ io_context.stop(); }); co_spawn(io_context, listener(), detached); io_context.run(); } catch (std::exception& e) { std::printf("Exception: %s\n", e.what()); } }
0
repos/asio/asio/src/examples/cpp17
repos/asio/asio/src/examples/cpp17/coroutines_ts/echo_server_with_as_single_default.cpp
// // echo_server_with_as_single_default.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/experimental/as_single.hpp> #include <asio/co_spawn.hpp> #include <asio/detached.hpp> #include <asio/io_context.hpp> #include <asio/ip/tcp.hpp> #include <asio/signal_set.hpp> #include <asio/write.hpp> #include <cstdio> using asio::experimental::as_single_t; using asio::ip::tcp; using asio::awaitable; using asio::co_spawn; using asio::detached; using asio::use_awaitable_t; using default_token = as_single_t<use_awaitable_t<>>; using tcp_acceptor = default_token::as_default_on_t<tcp::acceptor>; using tcp_socket = default_token::as_default_on_t<tcp::socket>; namespace this_coro = asio::this_coro; awaitable<void> echo(tcp_socket socket) { char data[1024]; for (;;) { auto [e1, nread] = co_await socket.async_read_some(asio::buffer(data)); if (nread == 0) break; auto [e2, nwritten] = co_await async_write(socket, asio::buffer(data, nread)); if (nwritten != nread) break; } } awaitable<void> listener() { auto executor = co_await this_coro::executor; tcp_acceptor acceptor(executor, {tcp::v4(), 55555}); for (;;) { if (auto [e, socket] = co_await acceptor.async_accept(); socket.is_open()) co_spawn(executor, echo(std::move(socket)), detached); } } int main() { try { asio::io_context io_context(1); asio::signal_set signals(io_context, SIGINT, SIGTERM); signals.async_wait([&](auto, auto){ io_context.stop(); }); co_spawn(io_context, listener(), detached); io_context.run(); } catch (std::exception& e) { std::printf("Exception: %s\n", e.what()); } }
0
repos/asio/asio/src/examples/cpp17
repos/asio/asio/src/examples/cpp17/coroutines_ts/range_based_for.cpp
// // range_based_for.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/co_spawn.hpp> #include <asio/detached.hpp> #include <asio/io_context.hpp> #include <asio/ip/tcp.hpp> #include <asio/signal_set.hpp> #include <asio/write.hpp> #include <cstdio> using asio::ip::tcp; using asio::awaitable; using asio::co_spawn; using asio::detached; using asio::use_awaitable; class connection_iter { friend class connections; tcp::acceptor* acceptor_ = nullptr; tcp::socket socket_; connection_iter(tcp::acceptor& a, tcp::socket s) : acceptor_(&a), socket_(std::move(s)) {} public: tcp::socket operator*() { return std::move(socket_); } awaitable<void> operator++() { socket_ = co_await acceptor_->async_accept(use_awaitable); } bool operator==(const connection_iter&) const noexcept { return false; } bool operator!=(const connection_iter&) const noexcept { return true; } }; class connections { tcp::acceptor& acceptor_; public: explicit connections(tcp::acceptor& a) : acceptor_(a) {} awaitable<connection_iter> begin() { tcp::socket s = co_await acceptor_.async_accept(use_awaitable); co_return connection_iter(acceptor_, std::move(s)); } connection_iter end() { return connection_iter(acceptor_, tcp::socket(acceptor_.get_executor())); } }; awaitable<void> listener(tcp::acceptor acceptor) { for co_await (tcp::socket s : connections(acceptor)) { co_await asio::async_write(s, asio::buffer("hello\r\n", 7), use_awaitable); } } int main() { try { asio::io_context io_context(1); asio::signal_set signals(io_context, SIGINT, SIGTERM); signals.async_wait([&](auto, auto){ io_context.stop(); }); tcp::acceptor acceptor(io_context, {tcp::v4(), 55555}); co_spawn(io_context, listener(std::move(acceptor)), detached); io_context.run(); } catch (std::exception& e) { std::printf("Exception: %s\n", e.what()); } }
0
repos/asio/asio/src/examples/cpp17
repos/asio/asio/src/examples/cpp17/coroutines_ts/echo_server.cpp
// // echo_server.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/co_spawn.hpp> #include <asio/detached.hpp> #include <asio/io_context.hpp> #include <asio/ip/tcp.hpp> #include <asio/signal_set.hpp> #include <asio/write.hpp> #include <cstdio> using asio::ip::tcp; using asio::awaitable; using asio::co_spawn; using asio::detached; using asio::use_awaitable; namespace this_coro = asio::this_coro; #if defined(ASIO_ENABLE_HANDLER_TRACKING) # define use_awaitable \ asio::use_awaitable_t(__FILE__, __LINE__, __PRETTY_FUNCTION__) #endif awaitable<void> echo(tcp::socket socket) { try { char data[1024]; for (;;) { std::size_t n = co_await socket.async_read_some(asio::buffer(data), use_awaitable); co_await async_write(socket, asio::buffer(data, n), use_awaitable); } } catch (std::exception& e) { std::printf("echo Exception: %s\n", e.what()); } } awaitable<void> listener() { auto executor = co_await this_coro::executor; tcp::acceptor acceptor(executor, {tcp::v4(), 55555}); for (;;) { tcp::socket socket = co_await acceptor.async_accept(use_awaitable); co_spawn(executor, echo(std::move(socket)), detached); } } int main() { try { asio::io_context io_context(1); asio::signal_set signals(io_context, SIGINT, SIGTERM); signals.async_wait([&](auto, auto){ io_context.stop(); }); co_spawn(io_context, listener(), detached); io_context.run(); } catch (std::exception& e) { std::printf("Exception: %s\n", e.what()); } }
0
repos/asio/asio/src/examples/cpp17
repos/asio/asio/src/examples/cpp17/coroutines_ts/echo_server_with_default.cpp
// // echo_server_with_default.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/co_spawn.hpp> #include <asio/detached.hpp> #include <asio/io_context.hpp> #include <asio/ip/tcp.hpp> #include <asio/signal_set.hpp> #include <asio/write.hpp> #include <cstdio> using asio::ip::tcp; using asio::awaitable; using asio::co_spawn; using asio::detached; using asio::use_awaitable_t; using tcp_acceptor = use_awaitable_t<>::as_default_on_t<tcp::acceptor>; using tcp_socket = use_awaitable_t<>::as_default_on_t<tcp::socket>; namespace this_coro = asio::this_coro; awaitable<void> echo(tcp_socket socket) { try { char data[1024]; for (;;) { std::size_t n = co_await socket.async_read_some(asio::buffer(data)); co_await async_write(socket, asio::buffer(data, n)); } } catch (std::exception& e) { std::printf("echo Exception: %s\n", e.what()); } } awaitable<void> listener() { auto executor = co_await this_coro::executor; tcp_acceptor acceptor(executor, {tcp::v4(), 55555}); for (;;) { auto socket = co_await acceptor.async_accept(); co_spawn(executor, echo(std::move(socket)), detached); } } int main() { try { asio::io_context io_context(1); asio::signal_set signals(io_context, SIGINT, SIGTERM); signals.async_wait([&](auto, auto){ io_context.stop(); }); co_spawn(io_context, listener(), detached); io_context.run(); } catch (std::exception& e) { std::printf("Exception: %s\n", e.what()); } }
0
repos/asio/asio/src/examples/cpp17
repos/asio/asio/src/examples/cpp17/coroutines_ts/refactored_echo_server.cpp
// // refactored_echo_server.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/co_spawn.hpp> #include <asio/detached.hpp> #include <asio/io_context.hpp> #include <asio/ip/tcp.hpp> #include <asio/signal_set.hpp> #include <asio/write.hpp> #include <cstdio> using asio::ip::tcp; using asio::awaitable; using asio::co_spawn; using asio::detached; using asio::use_awaitable; namespace this_coro = asio::this_coro; awaitable<void> echo_once(tcp::socket& socket) { char data[128]; std::size_t n = co_await socket.async_read_some(asio::buffer(data), use_awaitable); co_await async_write(socket, asio::buffer(data, n), use_awaitable); } awaitable<void> echo(tcp::socket socket) { try { for (;;) { // The asynchronous operations to echo a single chunk of data have been // refactored into a separate function. When this function is called, the // operations are still performed in the context of the current // coroutine, and the behaviour is functionally equivalent. co_await echo_once(socket); } } catch (std::exception& e) { std::printf("echo Exception: %s\n", e.what()); } } awaitable<void> listener() { auto executor = co_await this_coro::executor; tcp::acceptor acceptor(executor, {tcp::v4(), 55555}); for (;;) { tcp::socket socket = co_await acceptor.async_accept(use_awaitable); co_spawn(executor, echo(std::move(socket)), detached); } } int main() { try { asio::io_context io_context(1); asio::signal_set signals(io_context, SIGINT, SIGTERM); signals.async_wait([&](auto, auto){ io_context.stop(); }); co_spawn(io_context, listener(), detached); io_context.run(); } catch (std::exception& e) { std::printf("Exception: %s\n", e.what()); } }
0
repos/asio/asio/src/examples/cpp17
repos/asio/asio/src/examples/cpp17/coroutines_ts/chat_server.cpp
// // chat_server.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 <cstdlib> #include <deque> #include <iostream> #include <list> #include <memory> #include <set> #include <string> #include <utility> #include <asio/awaitable.hpp> #include <asio/detached.hpp> #include <asio/co_spawn.hpp> #include <asio/io_context.hpp> #include <asio/ip/tcp.hpp> #include <asio/read_until.hpp> #include <asio/redirect_error.hpp> #include <asio/signal_set.hpp> #include <asio/steady_timer.hpp> #include <asio/use_awaitable.hpp> #include <asio/write.hpp> using asio::ip::tcp; using asio::awaitable; using asio::co_spawn; using asio::detached; using asio::redirect_error; using asio::use_awaitable; //---------------------------------------------------------------------- class chat_participant { public: virtual ~chat_participant() {} virtual void deliver(const std::string& msg) = 0; }; typedef std::shared_ptr<chat_participant> chat_participant_ptr; //---------------------------------------------------------------------- class chat_room { public: void join(chat_participant_ptr participant) { participants_.insert(participant); for (auto msg: recent_msgs_) participant->deliver(msg); } void leave(chat_participant_ptr participant) { participants_.erase(participant); } void deliver(const std::string& msg) { recent_msgs_.push_back(msg); while (recent_msgs_.size() > max_recent_msgs) recent_msgs_.pop_front(); for (auto participant: participants_) participant->deliver(msg); } private: std::set<chat_participant_ptr> participants_; enum { max_recent_msgs = 100 }; std::deque<std::string> recent_msgs_; }; //---------------------------------------------------------------------- class chat_session : public chat_participant, public std::enable_shared_from_this<chat_session> { public: chat_session(tcp::socket socket, chat_room& room) : socket_(std::move(socket)), timer_(socket_.get_executor()), room_(room) { timer_.expires_at(std::chrono::steady_clock::time_point::max()); } void start() { room_.join(shared_from_this()); co_spawn(socket_.get_executor(), [self = shared_from_this()]{ return self->reader(); }, detached); co_spawn(socket_.get_executor(), [self = shared_from_this()]{ return self->writer(); }, detached); } void deliver(const std::string& msg) { write_msgs_.push_back(msg); timer_.cancel_one(); } private: awaitable<void> reader() { try { for (std::string read_msg;;) { std::size_t n = co_await asio::async_read_until(socket_, asio::dynamic_buffer(read_msg, 1024), "\n", use_awaitable); room_.deliver(read_msg.substr(0, n)); read_msg.erase(0, n); } } catch (std::exception&) { stop(); } } awaitable<void> writer() { try { while (socket_.is_open()) { if (write_msgs_.empty()) { asio::error_code ec; co_await timer_.async_wait(redirect_error(use_awaitable, ec)); } else { co_await asio::async_write(socket_, asio::buffer(write_msgs_.front()), use_awaitable); write_msgs_.pop_front(); } } } catch (std::exception&) { stop(); } } void stop() { room_.leave(shared_from_this()); socket_.close(); timer_.cancel(); } tcp::socket socket_; asio::steady_timer timer_; chat_room& room_; std::deque<std::string> write_msgs_; }; //---------------------------------------------------------------------- awaitable<void> listener(tcp::acceptor acceptor) { chat_room room; for (;;) { std::make_shared<chat_session>( co_await acceptor.async_accept(use_awaitable), room )->start(); } } //---------------------------------------------------------------------- int main(int argc, char* argv[]) { try { if (argc < 2) { std::cerr << "Usage: chat_server <port> [<port> ...]\n"; return 1; } asio::io_context io_context(1); for (int i = 1; i < argc; ++i) { unsigned short port = std::atoi(argv[i]); co_spawn(io_context, listener(tcp::acceptor(io_context, {tcp::v4(), port})), detached); } asio::signal_set signals(io_context, SIGINT, SIGTERM); signals.async_wait([&](auto, auto){ io_context.stop(); }); io_context.run(); } catch (std::exception& e) { std::cerr << "Exception: " << e.what() << "\n"; } return 0; }
0
repos/asio/asio/src
repos/asio/asio/src/tools/handlerlive.pl
#!/usr/bin/perl -w # # handlerlive.pl # ~~~~~~~~~~~~~~ # # A tool for post-processing the debug output generated by Asio-based programs # to print a list of "live" handlers. These are handlers that are associated # with operations that have not yet completed, or running handlers that have # not yet finished their execution. Programs write this output to the standard # error stream when compiled with the define `ASIO_ENABLE_HANDLER_TRACKING'. # # 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) # use strict; my %pending_handlers = (); my %running_handlers = (); #------------------------------------------------------------------------------- # Parse the debugging output and update the set of pending handlers. sub parse_debug_output() { while (my $line = <>) { chomp($line); if ($line =~ /\@asio\|([^|]*)\|([^|]*)\|(.*)$/) { my $action = $2; # Handler creation. if ($action =~ /^([0-9]+)\*([0-9]+)$/) { $pending_handlers{$2} = 1; } # Begin handler invocation. elsif ($action =~ /^>([0-9]+)$/) { delete($pending_handlers{$1}); $running_handlers{$1} = 1; } # End handler invocation. elsif ($action =~ /^<([0-9]+)$/) { delete($running_handlers{$1}); } # Handler threw exception. elsif ($action =~ /^!([0-9]+)$/) { delete($running_handlers{$1}); } # Handler was destroyed without being invoked. elsif ($action =~ /^~([0-9]+)$/) { delete($pending_handlers{$1}); } } } } #------------------------------------------------------------------------------- # Print a list of incompleted handers, on a single line delimited by spaces. sub print_handlers($) { my $handlers = shift; my $prefix = ""; foreach my $handler (sort { $a <=> $b } keys %{$handlers}) { print("$prefix$handler"); $prefix = " "; } print("\n") if ($prefix ne ""); } #------------------------------------------------------------------------------- parse_debug_output(); print_handlers(\%running_handlers); print_handlers(\%pending_handlers);
0
repos/asio/asio/src
repos/asio/asio/src/tools/handlertree.pl
#!/usr/bin/perl -w # # handlertree.pl # ~~~~~~~~~~~~~~ # A tool for post-processing the debug output generated by Asio-based programs # to print the tree of handlers that resulted in some specified handler ids. # Programs write this output to the standard error stream when compiled with # the define `ASIO_ENABLE_HANDLER_TRACKING'. # # 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) # use strict; my %target_handlers = (); my @cached_output = (); my %outstanding_handlers = (); my %running_handlers = (); #------------------------------------------------------------------------------- # Build the initial list of target handlers from the command line arguments. sub build_initial_target_handlers() { for my $handler (@ARGV) { $target_handlers{$handler} = 1; } } #------------------------------------------------------------------------------- # Parse the debugging output and cache the handler tracking lines. sub parse_debug_output() { while (my $line = <STDIN>) { chomp($line); if ($line =~ /\@asio\|([^|]*)\|([^|]*)\|(.*)$/) { push(@cached_output, $line); } } } #------------------------------------------------------------------------------- # Iterate over the cached output in revese and build a hash of all target # handlers' ancestors. sub build_target_handler_tree() { my $i = scalar(@cached_output) - 1; while ($i >= 0) { my $line = $cached_output[$i]; if ($line =~ /\@asio\|([^|]*)\|([^|]*)\|(.*)$/) { my $action = $2; # Handler creation. if ($action =~ /^([0-9]+)\*([0-9]+)$/) { if ($1 ne "0" and exists($target_handlers{$2})) { $target_handlers{$1} = 1; } } } --$i; } } #------------------------------------------------------------------------------- # Print out all handler tracking records associated with the target handlers. sub print_target_handler_records() { for my $line (@cached_output) { if ($line =~ /\@asio\|([^|]*)\|([^|]*)\|(.*)$/) { my $action = $2; # Handler location. if ($action =~ /^([0-9]+)\^([0-9]+)$/) { print("$line\n") if ($1 eq "0" or exists($target_handlers{$1})) and exists($target_handlers{$2}); } # Handler creation. if ($action =~ /^([0-9]+)\*([0-9]+)$/) { print("$1, $2, $line\n") if ($1 eq "0" or exists($target_handlers{$1})) and exists($target_handlers{$2}); } # Begin handler invocation. elsif ($action =~ /^>([0-9]+)$/) { print("$line\n") if (exists($target_handlers{$1})); } # End handler invocation. elsif ($action =~ /^<([0-9]+)$/) { print("$line\n") if (exists($target_handlers{$1})); } # Handler threw exception. elsif ($action =~ /^!([0-9]+)$/) { print("$line\n") if (exists($target_handlers{$1})); } # Handler was destroyed without being invoked. elsif ($action =~ /^~([0-9]+)$/) { print("$line\n") if (exists($target_handlers{$1})); } # Operation associated with a handler. elsif ($action =~ /^\.([0-9]+)$/) { print("$line\n") if (exists($target_handlers{$1})); } } } } #------------------------------------------------------------------------------- build_initial_target_handlers(); parse_debug_output(); build_target_handler_tree(); print_target_handler_records();
0
repos/asio/asio/src
repos/asio/asio/src/tools/handlerviz.pl
#!/usr/bin/perl -w # # handlerviz.pl # ~~~~~~~~~~~~~ # # A visualisation tool for post-processing the debug output generated by # Asio-based programs. Programs write this output to the standard error stream # when compiled with the define `ASIO_ENABLE_HANDLER_TRACKING'. # # This tool generates output intended for use with the GraphViz tool `dot'. For # example, to convert output to a PNG image, use: # # perl handlerviz.pl < output.txt | dot -Tpng > output.png # # To convert to a PDF file, use: # # perl handlerviz.pl < output.txt | dot -Tpdf > output.pdf # # 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) # use strict; my %nodes = (); my @edges = (); my %locations = (); my %anon_nodes = (); my $anon_id = 0; my %all_nodes = (); my %pending_nodes = (); #------------------------------------------------------------------------------- # Parse the debugging output and populate the nodes and edges. sub parse_debug_output() { while (my $line = <>) { chomp($line); if ($line =~ /\@asio\|([^|]*)\|([^|]*)\|(.*)$/) { my $timestamp = $1; my $action = $2; my $description = $3; # Handler creation. if ($action =~ /^([0-9]+)\*([0-9]+)$/) { my $begin = $1; my $end = $2; my $label = $description; $label =~ s/\./\\n/g; if ($begin eq "0") { $begin = "a" . $anon_id++; $anon_nodes{$begin} = $timestamp; $all_nodes{"$timestamp-$begin"} = $begin; } my %edge = ( begin=>$begin, end=>$end, label=>$label ); push(@edges, \%edge); $pending_nodes{$end} = 1; } # Handler location. elsif ($action =~ /^([0-9]+)\^([0-9]+)$/) { if ($1 ne "0") { if (not exists($locations{($1,$2)})) { $locations{($1,$2)} = (); } push(@{$locations{($1,$2)}}, $description); } } # Begin handler invocation. elsif ($action =~ /^>([0-9]+)$/) { my %new_node = ( label=>$description, entry=>$timestamp ); $new_node{content} = (); $nodes{$1} = \%new_node; $all_nodes{"$timestamp-$1"} = $1; delete($pending_nodes{$1}); } # End handler invocation. elsif ($action =~ /^<([0-9]+)$/) { $nodes{$1}->{exit} = $timestamp; } # Handler threw exception. elsif ($action =~ /^!([0-9]+)$/) { push(@{$nodes{$1}->{content}}, "exception"); } # Handler was destroyed without being invoked. elsif ($action =~ /^~([0-9]+)$/) { my %new_node = ( label=>"$timestamp destroyed" ); $new_node{content} = (); $nodes{$1} = \%new_node; $all_nodes{"$timestamp-$1"} = $1; delete($pending_nodes{$1}); } # Handler performed some operation. elsif ($action =~ /^([0-9]+)$/) { if ($1 eq "0") { my $id = "a" . $anon_id++; $anon_nodes{$id} = "$timestamp\\l$description"; $all_nodes{"$timestamp-$id"} = $id; } else { push(@{$nodes{$1}->{content}}, "$description"); } } } } } #------------------------------------------------------------------------------- # Helper function to convert a string to escaped HTML text. sub escape($) { my $text = shift; $text =~ s/&/\&amp\;/g; $text =~ s/</\&lt\;/g; $text =~ s/>/\&gt\;/g; $text =~ s/\t/ /g; return $text; } #------------------------------------------------------------------------------- # Templates for dot output. my $graph_header = <<"EOF"; /* Generated by handlerviz.pl */ digraph "handlerviz output" { graph [ nodesep="1" ]; node [ shape="box", fontsize="9" ]; edge [ arrowtail="dot", fontsize="9" ]; EOF my $graph_footer = <<"EOF"; } EOF my $node_header = <<"EOF"; "%name%" [ label=<<table border="0" cellspacing="0"> <tr><td align="left" bgcolor="gray" border="0">%label%</td></tr> EOF my $node_footer = <<"EOF"; </table>> ] EOF my $node_content = <<"EOF"; <tr><td align="left" bgcolor="white" border="0"> <font face="mono" point-size="9">%content%</font> </td></tr> EOF my $anon_nodes_header = <<"EOF"; { node [ shape="record" ]; EOF my $anon_nodes_footer = <<"EOF"; } EOF my $anon_node = <<"EOF"; "%name%" [ label="%label%", color="gray" ]; EOF my $pending_nodes_header = <<"EOF"; { node [ shape="record", color="red" ]; rank = "max"; EOF my $pending_nodes_footer = <<"EOF"; } EOF my $pending_node = <<"EOF"; "%name%"; EOF my $edges_header = <<"EOF"; { edge [ style="dashed", arrowhead="open" ]; EOF my $edges_footer = <<"EOF"; } EOF my $edge = <<"EOF"; "%begin%" -> "%end%" [ label="%label%", labeltooltip="%tooltip%" ] EOF my $node_order_header = <<"EOF"; { node [ style="invisible" ]; edge [ style="invis", weight="100" ]; EOF my $node_order_footer = <<"EOF"; } EOF my $node_order = <<"EOF"; { rank="same" "%begin%"; "o%begin%"; } "o%begin%" -> "o%end%"; EOF #------------------------------------------------------------------------------- # Generate dot output from the nodes and edges. sub print_nodes() { foreach my $name (sort keys %nodes) { my $node = $nodes{$name}; my $entry = $node->{entry}; my $exit = $node->{exit}; my $label = escape($node->{label}); my $header = $node_header; $header =~ s/%name%/$name/g; $header =~ s/%label%/$label/g; print($header); if (defined($exit) and defined($entry)) { my $line = $node_content; my $content = $entry . " + " . sprintf("%.6f", $exit - $entry) . "s"; $line =~ s/%content%/$content/g; print($line); } foreach my $content (@{$node->{content}}) { $content = escape($content); $content = " " if length($content) == 0; my $line = $node_content; $line =~ s/%content%/$content/g; print($line); } print($node_footer); } } sub print_anon_nodes() { print($anon_nodes_header); foreach my $name (sort keys %anon_nodes) { my $label = $anon_nodes{$name}; my $line = $anon_node; $line =~ s/%name%/$name/g; $line =~ s/%label%/$label/g; print($line); } print($anon_nodes_footer); } sub print_pending_nodes() { print($pending_nodes_header); foreach my $name (sort keys %pending_nodes) { my $line = $pending_node; $line =~ s/%name%/$name/g; print($line); } print($pending_nodes_footer); } sub print_edges() { print($edges_header); foreach my $e (@edges) { my $begin = $e->{begin}; my $end = $e->{end}; my $label = $e->{label}; my $tooltip = ""; if (exists($locations{($begin,$end)})) { for my $line (@{$locations{($begin,$end)}}) { $tooltip = $tooltip . escape($line) . "\n"; } } my $line = $edge; $line =~ s/%begin%/$begin/g; $line =~ s/%end%/$end/g; $line =~ s/%label%/$label/g; $line =~ s/%tooltip%/$tooltip/g; print($line); } print($edges_footer); } sub print_node_order() { my $prev = ""; print($node_order_header); foreach my $name (sort keys %all_nodes) { if ($prev ne "") { my $begin = $prev; my $end = $all_nodes{$name}; my $line = $node_order; $line =~ s/%begin%/$begin/g; $line =~ s/%end%/$end/g; print($line); } $prev = $all_nodes{$name}; } foreach my $name (sort keys %pending_nodes) { if ($prev ne "") { my $begin = $prev; my $line = $node_order; $line =~ s/%begin%/$begin/g; $line =~ s/%end%/$name/g; print($line); } last; } print($node_order_footer); } sub generate_dot() { print($graph_header); print_nodes(); print_anon_nodes(); print_pending_nodes(); print_edges(); print_node_order(); print($graph_footer); } #------------------------------------------------------------------------------- parse_debug_output(); generate_dot();
0
repos/asio/asio/src
repos/asio/asio/src/doc/quickref.xml
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE library PUBLIC "-//Boost//DTD BoostBook XML V1.0//EN" "../../../boost/tools/boostbook/dtd/boostbook.dtd"> <!-- 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) --> <informaltable frame="all"> <tgroup cols="4"> <colspec colname="a"/> <colspec colname="b"/> <colspec colname="c"/> <colspec colname="d"/> <thead> <row> <entry valign="center" namest="a" nameend="a"> <bridgehead renderas="sect2">Properties</bridgehead> </entry> <entry valign="center" namest="b" nameend="d"> <bridgehead renderas="sect2">Execution</bridgehead> </entry> </row> </thead> <tbody> <row> <entry valign="top"> <bridgehead renderas="sect3">Customisation Points</bridgehead> <simplelist type="vert" columns="1"> <member><link linkend="asio.reference.prefer">prefer</link></member> <member><link linkend="asio.reference.query">query</link></member> <member><link linkend="asio.reference.require">require</link></member> <member><link linkend="asio.reference.require_concept">require_concept</link></member> </simplelist> <bridgehead renderas="sect3">Traits</bridgehead> <simplelist type="vert" columns="1"> <member><link linkend="asio.reference.can_prefer">can_prefer</link></member> <member><link linkend="asio.reference.can_query">can_query</link></member> <member><link linkend="asio.reference.can_require">can_require</link></member> <member><link linkend="asio.reference.can_require_concept">can_require_concept</link></member> <member><link linkend="asio.reference.is_nothrow_prefer">is_nothrow_prefer</link></member> <member><link linkend="asio.reference.is_nothrow_query">is_nothrow_query</link></member> <member><link linkend="asio.reference.is_nothrow_require">is_nothrow_require</link></member> <member><link linkend="asio.reference.is_nothrow_require_concept">is_nothrow_require_concept</link></member> <member><link linkend="asio.reference.prefer_result">prefer_result</link></member> <member><link linkend="asio.reference.query_result">query_result</link></member> <member><link linkend="asio.reference.require_result">require_result</link></member> <member><link linkend="asio.reference.require_concept_result">require_concept_result</link></member> </simplelist> </entry> <entry valign="top"> <bridgehead renderas="sect3">Class Templates</bridgehead> <simplelist type="vert" columns="1"> <member><link linkend="asio.reference.execution__any_executor">execution::any_executor</link></member> </simplelist> <bridgehead renderas="sect3">Classes</bridgehead> <simplelist type="vert" columns="1"> <member><link linkend="asio.reference.execution__bad_executor">execution::bad_executor</link></member> <member><link linkend="asio.reference.execution__invocable_archetype">execution::invocable_archetype</link></member> </simplelist> <bridgehead renderas="sect3">Type Traits</bridgehead> <simplelist type="vert" columns="1"> <member><link linkend="asio.reference.execution__is_executor">execution::is_executor</link></member> </simplelist> <bridgehead renderas="sect3">Concepts</bridgehead> <simplelist type="vert" columns="1"> <member><link linkend="asio.reference.Executor1.standard_executors">executor</link></member> </simplelist> </entry> <entry valign="top"> <bridgehead renderas="sect3">Properties</bridgehead> <simplelist type="vert" columns="1"> <member><link linkend="asio.reference.execution__allocator_t">execution::allocator_t</link></member> <member><link linkend="asio.reference.execution__blocking_t">execution::blocking_t</link></member> <member><link linkend="asio.reference.execution__blocking_t__possibly_t">execution::blocking_t::possibly_t</link></member> <member><link linkend="asio.reference.execution__blocking_t__always_t">execution::blocking_t::always_t</link></member> <member><link linkend="asio.reference.execution__blocking_t__never_t">execution::blocking_t::never_t</link></member> <member><link linkend="asio.reference.execution__blocking_adaptation_t">execution::blocking_adaptation_t</link></member> <member><link linkend="asio.reference.execution__blocking_adaptation_t__disallowed_t">execution::blocking_adaptation_t::disallowed_t</link></member> <member><link linkend="asio.reference.execution__blocking_adaptation_t__allowed_t">execution::blocking_adaptation_t::allowed_t</link></member> <member><link linkend="asio.reference.execution__context_t">execution::context_t</link></member> <member><link linkend="asio.reference.execution__context_as_t">execution::context_as_t</link></member> <member><link linkend="asio.reference.execution__mapping_t">execution::mapping_t</link></member> <member><link linkend="asio.reference.execution__mapping_t__thread_t">execution::mapping_t::thread_t</link></member> <member><link linkend="asio.reference.execution__mapping_t__new_thread_t">execution::mapping_t::new_thread_t</link></member> <member><link linkend="asio.reference.execution__mapping_t__other_t">execution::mapping_t::other_t</link></member> <member><link linkend="asio.reference.execution__occupancy_t">execution::occupancy_t</link></member> <member><link linkend="asio.reference.execution__outstanding_work_t">execution::outstanding_work_t</link></member> <member><link linkend="asio.reference.execution__outstanding_work_t__untracked_t">execution::outstanding_work_t::untracked_t</link></member> <member><link linkend="asio.reference.execution__outstanding_work_t__tracked_t">execution::outstanding_work_t::tracked_t</link></member> <member><link linkend="asio.reference.execution__prefer_only">execution::prefer_only</link></member> <member><link linkend="asio.reference.execution__relationship_t">execution::relationship_t</link></member> <member><link linkend="asio.reference.execution__relationship_t__fork_t">execution::relationship_t::fork_t</link></member> <member><link linkend="asio.reference.execution__relationship_t__continuation_t">execution::relationship_t::continuation_t</link></member> </simplelist> </entry> <entry valign="top"> <bridgehead renderas="sect3">Property Objects</bridgehead> <simplelist type="vert" columns="1"> <member><link linkend="asio.reference.execution__allocator">execution::allocator</link></member> <member><link linkend="asio.reference.execution__blocking">execution::blocking</link></member> <member><link linkend="asio.reference.execution__blocking_t.possibly">execution::blocking.possibly</link></member> <member><link linkend="asio.reference.execution__blocking_t.always">execution::blocking.always</link></member> <member><link linkend="asio.reference.execution__blocking_t.never">execution::blocking.never</link></member> <member><link linkend="asio.reference.execution__blocking_adaptation">execution::blocking_adaptation</link></member> <member><link linkend="asio.reference.execution__blocking_adaptation_t.disallowed">execution::blocking_adaptation.disallowed</link></member> <member><link linkend="asio.reference.execution__blocking_adaptation_t.allowed">execution::blocking_adaptation.allowed</link></member> <member><link linkend="asio.reference.execution__context">execution::context</link></member> <member><link linkend="asio.reference.execution__context_as">execution::context_as</link></member> <member><link linkend="asio.reference.execution__mapping">execution::mapping</link></member> <member><link linkend="asio.reference.execution__mapping_t.thread">execution::mapping.thread</link></member> <member><link linkend="asio.reference.execution__mapping_t.new_thread">execution::mapping.new_thread</link></member> <member><link linkend="asio.reference.execution__mapping_t.other">execution::mapping.other</link></member> <member><link linkend="asio.reference.execution__occupancy">execution::occupancy</link></member> <member><link linkend="asio.reference.execution__outstanding_work">execution::outstanding_work</link></member> <member><link linkend="asio.reference.execution__outstanding_work_t.untracked">execution::outstanding_work.untracked</link></member> <member><link linkend="asio.reference.execution__outstanding_work_t.tracked">execution::outstanding_work.tracked</link></member> <member><link linkend="asio.reference.execution__relationship">execution::relationship</link></member> <member><link linkend="asio.reference.execution__relationship_t.fork">execution::relationship.fork</link></member> <member><link linkend="asio.reference.execution__relationship_t.continuation">execution::relationship.continuation</link></member> </simplelist> </entry> </row> </tbody> </tgroup> <tgroup cols="4"> <colspec colname="a"/> <colspec colname="b"/> <colspec colname="c"/> <colspec colname="d"/> <thead> <row> <entry valign="center" namest="a" nameend="d"> <bridgehead renderas="sect2">Core</bridgehead> </entry> </row> </thead> <tbody> <row> <entry valign="top"> <bridgehead renderas="sect3">Classes</bridgehead> <simplelist type="vert" columns="1"> <member><link linkend="asio.reference.any_completion_executor">any_completion_executor</link></member> <member><link linkend="asio.reference.any_io_executor">any_io_executor</link></member> <member><link linkend="asio.reference.bad_executor">bad_executor</link></member> <member><link linkend="asio.reference.cancellation_signal">cancellation_signal</link></member> <member><link linkend="asio.reference.cancellation_slot">cancellation_slot</link></member> <member><link linkend="asio.reference.cancellation_state">cancellation_state</link></member> <member><link linkend="asio.reference.cancellation_type">cancellation_type</link></member> <member><link linkend="asio.reference.coroutine">coroutine</link></member> <member><link linkend="asio.reference.detached_t">detached_t</link></member> <member><link linkend="asio.reference.error_code">error_code</link></member> <member><link linkend="asio.reference.execution_context">execution_context</link></member> <member><link linkend="asio.reference.execution_context__id">execution_context::id</link></member> <member><link linkend="asio.reference.execution_context__service">execution_context::service</link></member> <member><link linkend="asio.reference.executor">executor</link></member> <member><link linkend="asio.reference.executor_arg_t">executor_arg_t</link></member> <member><link linkend="asio.reference.invalid_service_owner">invalid_service_owner</link></member> <member><link linkend="asio.reference.io_context">io_context</link></member> <member><link linkend="asio.reference.io_context.executor_type">io_context::executor_type</link></member> <member><link linkend="asio.reference.io_context__service">io_context::service</link></member> <member><link linkend="asio.reference.io_context__strand">io_context::strand</link></member> <member><link linkend="asio.reference.io_context__work">io_context::work</link> (deprecated)</member> <member><link linkend="asio.reference.multiple_exceptions">multiple_exceptions</link></member> <member><link linkend="asio.reference.partial_as_tuple">partial_as_tuple</link></member> <member><link linkend="asio.reference.partial_redirect_error">partial_redirect_error</link></member> <member><link linkend="asio.reference.service_already_exists">service_already_exists</link></member> <member><link linkend="asio.reference.static_thread_pool">static_thread_pool</link></member> <member><link linkend="asio.reference.system_context">system_context</link></member> <member><link linkend="asio.reference.system_error">system_error</link></member> <member><link linkend="asio.reference.system_executor">system_executor</link></member> <member><link linkend="asio.reference.this_coro__cancellation_state_t">this_coro::cancellation_state_t</link></member> <member><link linkend="asio.reference.this_coro__executor_t">this_coro::executor_t</link></member> <member><link linkend="asio.reference.thread">thread</link></member> <member><link linkend="asio.reference.thread_pool">thread_pool</link></member> <member><link linkend="asio.reference.thread_pool.executor_type">thread_pool::executor_type</link></member> <member><link linkend="asio.reference.yield_context">yield_context</link></member> </simplelist> </entry> <entry valign="top"> <bridgehead renderas="sect3">Class Templates</bridgehead> <simplelist type="vert" columns="1"> <member><link linkend="asio.reference.any_completion_handler">any_completion_handler</link></member> <member><link linkend="asio.reference.any_completion_handler_allocator">any_completion_handler_allocator</link></member> <member><link linkend="asio.reference.append_t">append_t</link></member> <member><link linkend="asio.reference.as_tuple_t">as_tuple_t</link></member> <member><link linkend="asio.reference.async_completion">async_completion</link></member> <member><link linkend="asio.reference.awaitable">awaitable</link></member> <member><link linkend="asio.reference.basic_io_object">basic_io_object</link></member> <member><link linkend="asio.reference.basic_system_executor">basic_system_executor</link></member> <member><link linkend="asio.reference.basic_yield_context">basic_yield_context</link></member> <member><link linkend="asio.reference.cancel_after_t">cancel_after_t</link></member> <member><link linkend="asio.reference.cancel_at_t">cancel_at_t</link></member> <member><link linkend="asio.reference.cancellation_filter">cancellation_filter</link></member> <member><link linkend="asio.reference.cancellation_slot_binder">cancellation_slot_binder</link></member> <member><link linkend="asio.reference.consign_t">consign_t</link></member> <member><link linkend="asio.reference.deferred_t">deferred_t</link></member> <member><link linkend="asio.reference.executor_binder">executor_binder</link></member> <member><link linkend="asio.reference.executor_work_guard">executor_work_guard</link></member> <member><link linkend="asio.reference.experimental__as_single_t">experimental::as_single_t</link></member> <member><link linkend="asio.reference.experimental__basic_channel">experimental::basic_channel</link></member> <member><link linkend="asio.reference.experimental__basic_concurrent_channel">experimental::basic_concurrent_channel</link></member> <member><link linkend="asio.reference.experimental__channel_traits">experimental::channel_traits</link></member> <member><link linkend="asio.reference.experimental__coro">experimental::coro</link></member> <member><link linkend="asio.reference.experimental__parallel_group">experimental::parallel_group</link></member> <member><link linkend="asio.reference.experimental__promise">experimental::promise</link></member> <member><link linkend="asio.reference.experimental__ranged_parallel_group">experimental::ranged_parallel_group</link></member> <member><link linkend="asio.reference.experimental__use_coro_t">experimental::use_coro_t</link></member> <member><link linkend="asio.reference.experimental__use_promise_t">experimental::use_promise_t</link></member> <member><link linkend="asio.reference.experimental__wait_for_all">experimental::wait_for_all</link></member> <member><link linkend="asio.reference.experimental__wait_for_one">experimental::wait_for_one</link></member> <member><link linkend="asio.reference.experimental__wait_for_one_error">experimental::wait_for_one_error</link></member> <member><link linkend="asio.reference.experimental__wait_for_one_success">experimental::wait_for_one_success</link></member> <member><link linkend="asio.reference.io_context__basic_executor_type">io_context::basic_executor_type</link></member> <member><link linkend="asio.reference.partial_allocator_binder">partial_allocator_binder</link></member> <member><link linkend="asio.reference.partial_cancel_after">partial_cancel_after</link></member> <member><link linkend="asio.reference.partial_cancel_after_timer">partial_cancel_after_timer</link></member> <member><link linkend="asio.reference.partial_cancel_at">partial_cancel_at</link></member> <member><link linkend="asio.reference.partial_cancel_at_timer">partial_cancel_at_timer</link></member> <member><link linkend="asio.reference.partial_cancellation_slot_binder">partial_cancellation_slot_binder</link></member> <member><link linkend="asio.reference.partial_executor_binder">partial_executor_binder</link></member> <member><link linkend="asio.reference.partial_immediate_executor_binder">partial_immediate_executor_binder</link></member> <member><link linkend="asio.reference.prepend_t">prepend_t</link></member> <member><link linkend="asio.reference.recycling_allocator">recycling_allocator</link></member> <member><link linkend="asio.reference.redirect_error_t">redirect_error_t</link></member> <member><link linkend="asio.reference.strand">strand</link></member> <member><link linkend="asio.reference.thread_pool__basic_executor_type">thread_pool::basic_executor_type</link></member> <member><link linkend="asio.reference.use_awaitable_t">use_awaitable_t</link></member> <member><link linkend="asio.reference.use_future_t">use_future_t</link></member> </simplelist> </entry> <entry valign="top"> <bridgehead renderas="sect3">Free Functions</bridgehead> <simplelist type="vert" columns="1"> <member><link linkend="asio.reference.execution_context.add_service">add_service</link> (deprecated)</member> <member><link linkend="asio.reference.append">append</link></member> <member><link linkend="asio.reference.asio_handler_is_continuation">asio_handler_is_continuation</link></member> <member><link linkend="asio.reference.async_compose">async_compose</link></member> <member><link linkend="asio.reference.async_immediate">async_immediate</link></member> <member><link linkend="asio.reference.async_initiate">async_initiate</link></member> <member><link linkend="asio.reference.bind_allocator">bind_allocator</link></member> <member><link linkend="asio.reference.bind_cancellation_slot">bind_cancellation_slot</link></member> <member><link linkend="asio.reference.bind_executor">bind_executor</link></member> <member><link linkend="asio.reference.bind_immediate_executor">bind_immediate_executor</link></member> <member><link linkend="asio.reference.cancel_after">cancel_after</link></member> <member><link linkend="asio.reference.cancel_at">cancel_at</link></member> <member><link linkend="asio.reference.co_composed">co_composed</link></member> <member><link linkend="asio.reference.co_spawn">co_spawn</link></member> <member><link linkend="asio.reference.composed">composed</link></member> <member><link linkend="asio.reference.consign">consign</link></member> <member><link linkend="asio.reference.defer">defer</link></member> <member><link linkend="asio.reference.dispatch">dispatch</link></member> <member><link linkend="asio.reference.experimental__as_single">experimental::as_single</link></member> <member><link linkend="asio.reference.experimental__make_parallel_group">experimental::make_parallel_group</link></member> <member><link linkend="asio.reference.get_associated_allocator">get_associated_allocator</link></member> <member><link linkend="asio.reference.get_associated_cancellation_slot">get_associated_cancellation_slot</link></member> <member><link linkend="asio.reference.get_associated_executor">get_associated_executor</link></member> <member><link linkend="asio.reference.get_associated_immediate_executor">get_associated_immediate_executor</link></member> <member><link linkend="asio.reference.execution_context.has_service">has_service</link></member> <member><link linkend="asio.reference.execution_context.make_service">make_service</link></member> <member><link linkend="asio.reference.make_strand">make_strand</link></member> <member><link linkend="asio.reference.make_work_guard">make_work_guard</link></member> <member><link linkend="asio.reference.post">post</link></member> <member><link linkend="asio.reference.prepend">prepend</link></member> <member><link linkend="asio.reference.redirect_error">redirect_error</link></member> <member><link linkend="asio.reference.spawn">spawn</link></member> <member><link linkend="asio.reference.this_coro__reset_cancellation_state">this_coro::reset_cancellation_state</link></member> <member><link linkend="asio.reference.this_coro__throw_if_cancelled">this_coro::throw_if_cancelled</link></member> <member><link linkend="asio.reference.execution_context.use_service">use_service</link></member> </simplelist> <bridgehead renderas="sect3">Special Values</bridgehead> <simplelist type="vert" columns="1"> <member><link linkend="asio.reference.as_tuple">as_tuple</link></member> <member><link linkend="asio.reference.deferred">deferred</link></member> <member><link linkend="asio.reference.detached">detached</link></member> <member><link linkend="asio.reference.executor_arg">executor_arg</link></member> <member><link linkend="asio.reference.experimental__use_coro">experimental::use_coro</link></member> <member><link linkend="asio.reference.experimental__use_promise">experimental::use_promise</link></member> <member><link linkend="asio.reference.this_coro__cancellation_state">this_coro::cancellation_state</link></member> <member><link linkend="asio.reference.this_coro__executor">this_coro::executor</link></member> <member><link linkend="asio.reference.use_awaitable">use_awaitable</link></member> <member><link linkend="asio.reference.use_future">use_future</link></member> </simplelist> </entry> <entry valign="top"> <bridgehead renderas="sect3">Error Codes</bridgehead> <simplelist type="vert" columns="1"> <member><link linkend="asio.reference.error__basic_errors">error::basic_errors</link></member> <member><link linkend="asio.reference.error__netdb_errors">error::netdb_errors</link></member> <member><link linkend="asio.reference.error__addrinfo_errors">error::addrinfo_errors</link></member> <member><link linkend="asio.reference.error__misc_errors">error::misc_errors</link></member> </simplelist> <bridgehead renderas="sect3">Bind Placeholders</bridgehead> <simplelist type="vert" columns="1"> <member><link linkend="asio.reference.placeholders__bytes_transferred">placeholders::bytes_transferred</link></member> <member><link linkend="asio.reference.placeholders__endpoint">placeholders::endpoint</link></member> <member><link linkend="asio.reference.placeholders__error">placeholders::error</link></member> <member><link linkend="asio.reference.placeholders__iterator">placeholders::iterator</link></member> <member><link linkend="asio.reference.placeholders__results">placeholders::results</link></member> <member><link linkend="asio.reference.placeholders__signal_number">placeholders::signal_number</link></member> </simplelist> <bridgehead renderas="sect3">Type Traits</bridgehead> <simplelist type="vert" columns="1"> <member><link linkend="asio.reference.associated_allocator">associated_allocator</link></member> <member><link linkend="asio.reference.associated_cancellation_slot">associated_cancellation_slot</link></member> <member><link linkend="asio.reference.associated_executor">associated_executor</link></member> <member><link linkend="asio.reference.associated_immediate_executor">associated_immediate_executor</link></member> <member><link linkend="asio.reference.associator">associator</link></member> <member><link linkend="asio.reference.async_result">async_result</link></member> <member><link linkend="asio.reference.completion_signature_of">completion_signature_of</link></member> <member><link linkend="asio.reference.default_completion_token">default_completion_token</link></member> <member><link linkend="asio.reference.is_async_operation">is_async_operation</link></member> <member><link linkend="asio.reference.is_executor">is_executor</link></member> <member><link linkend="asio.reference.uses_executor">uses_executor</link></member> </simplelist> <bridgehead renderas="sect3">Type Requirements</bridgehead> <simplelist type="vert" columns="1"> <member><link linkend="asio.reference.asynchronous_operations">Asynchronous operations</link></member> <member><link linkend="asio.reference.CancellationHandler">CancellationHandler</link></member> <member><link linkend="asio.reference.CancellationSlot">CancellationSlot</link></member> <member><link linkend="asio.reference.ExecutionContext">ExecutionContext</link></member> <member><link linkend="asio.reference.Executor1">Executor</link></member> <member><link linkend="asio.reference.Handler">Handler</link></member> <member><link linkend="asio.reference.NullaryToken">NullaryToken</link></member> <member><link linkend="asio.reference.Service">Service</link></member> </simplelist> </entry> </row> </tbody> </tgroup> <tgroup cols="4"> <colspec colname="a"/> <colspec colname="b"/> <colspec colname="c"/> <colspec colname="d"/> <thead> <row> <entry valign="center" namest="a" nameend="d"> <bridgehead renderas="sect2">Buffers and Buffer-Oriented Operations</bridgehead> </entry> </row> </thead> <tbody> <row> <entry valign="top"> <bridgehead renderas="sect3">Classes</bridgehead> <simplelist type="vert" columns="1"> <member><link linkend="asio.reference.const_buffer">const_buffer</link></member> <member><link linkend="asio.reference.mutable_buffer">mutable_buffer</link></member> <member><link linkend="asio.reference.const_buffers_1">const_buffers_1 </link> (deprecated)</member> <member><link linkend="asio.reference.mutable_buffers_1">mutable_buffers_1 </link> (deprecated)</member> <member><link linkend="asio.reference.const_registered_buffer">const_registered_buffer</link></member> <member><link linkend="asio.reference.mutable_registered_buffer">mutable_registered_buffer</link></member> <member><link linkend="asio.reference.null_buffers">null_buffers</link> (deprecated)</member> <member><link linkend="asio.reference.streambuf">streambuf</link></member> <member><link linkend="asio.reference.registered_buffer_id">registered_buffer_id</link></member> </simplelist> <bridgehead renderas="sect3">Class Templates</bridgehead> <simplelist type="vert" columns="1"> <member><link linkend="asio.reference.basic_streambuf">basic_streambuf</link></member> <member><link linkend="asio.reference.buffer_registration">buffer_registration</link></member> <member><link linkend="asio.reference.buffered_read_stream">buffered_read_stream</link></member> <member><link linkend="asio.reference.buffered_stream">buffered_stream</link></member> <member><link linkend="asio.reference.buffered_write_stream">buffered_write_stream</link></member> <member><link linkend="asio.reference.buffers_iterator">buffers_iterator</link></member> <member><link linkend="asio.reference.dynamic_string_buffer">dynamic_string_buffer</link></member> <member><link linkend="asio.reference.dynamic_vector_buffer">dynamic_vector_buffer</link></member> </simplelist> </entry> <entry valign="top"> <bridgehead renderas="sect3">Free Functions</bridgehead> <simplelist type="vert" columns="1"> <member><link linkend="asio.reference.async_read">async_read</link></member> <member><link linkend="asio.reference.async_read_at">async_read_at</link></member> <member><link linkend="asio.reference.async_read_until">async_read_until</link></member> <member><link linkend="asio.reference.async_write">async_write</link></member> <member><link linkend="asio.reference.async_write_at">async_write_at</link></member> <member><link linkend="asio.reference.buffer">buffer</link></member> <member><link linkend="asio.reference.buffer_cast">buffer_cast </link> (deprecated)</member> <member><link linkend="asio.reference.buffer_copy">buffer_copy</link></member> <member><link linkend="asio.reference.buffer_size">buffer_size</link></member> <member><link linkend="asio.reference.buffer_sequence_begin">buffer_sequence_begin</link></member> <member><link linkend="asio.reference.buffer_sequence_end">buffer_sequence_end</link></member> <member><link linkend="asio.reference.buffers_begin">buffers_begin</link></member> <member><link linkend="asio.reference.buffers_end">buffers_end</link></member> <member><link linkend="asio.reference.dynamic_buffer">dynamic_buffer</link></member> <member><link linkend="asio.reference.read">read</link></member> <member><link linkend="asio.reference.read_at">read_at</link></member> <member><link linkend="asio.reference.read_until">read_until</link></member> <member><link linkend="asio.reference.register_buffers">register_buffers</link></member> <member><link linkend="asio.reference.transfer_all">transfer_all</link></member> <member><link linkend="asio.reference.transfer_at_least">transfer_at_least</link></member> <member><link linkend="asio.reference.transfer_exactly">transfer_exactly</link></member> <member><link linkend="asio.reference.write">write</link></member> <member><link linkend="asio.reference.write_at">write_at</link></member> </simplelist> </entry> <entry valign="top"> <bridgehead renderas="sect3">Type Traits</bridgehead> <simplelist type="vert" columns="1"> <member><link linkend="asio.reference.is_const_buffer_sequence">is_const_buffer_sequence</link></member> <member><link linkend="asio.reference.is_dynamic_buffer">is_dynamic_buffer</link></member> <member><link linkend="asio.reference.is_dynamic_buffer_v1">is_dynamic_buffer_v1</link></member> <member><link linkend="asio.reference.is_dynamic_buffer_v2">is_dynamic_buffer_v2</link></member> <member><link linkend="asio.reference.is_match_condition">is_match_condition</link></member> <member><link linkend="asio.reference.is_mutable_buffer_sequence">is_mutable_buffer_sequence</link></member> <member><link linkend="asio.reference.is_read_buffered">is_read_buffered</link></member> <member><link linkend="asio.reference.is_write_buffered">is_write_buffered</link></member> </simplelist> </entry> <entry valign="top"> <bridgehead renderas="sect3">Type Requirements</bridgehead> <simplelist type="vert" columns="1"> <member><link linkend="asio.reference.read_write_operations">Read and write operations</link></member> <member><link linkend="asio.reference.AsyncRandomAccessReadDevice">AsyncRandomAccessReadDevice</link></member> <member><link linkend="asio.reference.AsyncRandomAccessWriteDevice">AsyncRandomAccessWriteDevice</link></member> <member><link linkend="asio.reference.AsyncReadStream">AsyncReadStream</link></member> <member><link linkend="asio.reference.AsyncWriteStream">AsyncWriteStream</link></member> <member><link linkend="asio.reference.CompletionCondition">CompletionCondition</link></member> <member><link linkend="asio.reference.ConstBufferSequence">ConstBufferSequence</link></member> <member><link linkend="asio.reference.DynamicBuffer">DynamicBuffer</link></member> <member><link linkend="asio.reference.DynamicBuffer_v1">DynamicBuffer_v1</link></member> <member><link linkend="asio.reference.DynamicBuffer_v2">DynamicBuffer_v2</link></member> <member><link linkend="asio.reference.MutableBufferSequence">MutableBufferSequence</link></member> <member><link linkend="asio.reference.ReadHandler">ReadHandler</link></member> <member><link linkend="asio.reference.ReadToken">ReadToken</link></member> <member><link linkend="asio.reference.SyncRandomAccessReadDevice">SyncRandomAccessReadDevice</link></member> <member><link linkend="asio.reference.SyncRandomAccessWriteDevice">SyncRandomAccessWriteDevice</link></member> <member><link linkend="asio.reference.SyncReadStream">SyncReadStream</link></member> <member><link linkend="asio.reference.SyncWriteStream">SyncWriteStream</link></member> <member><link linkend="asio.reference.WriteHandler">WriteHandler</link></member> <member><link linkend="asio.reference.WriteToken">WriteToken</link></member> </simplelist> </entry> </row> </tbody> </tgroup> <tgroup cols="4"> <colspec colname="a"/> <colspec colname="b"/> <colspec colname="c"/> <colspec colname="d"/> <thead> <row> <entry valign="center" namest="a" nameend="d"> <bridgehead renderas="sect2">Networking</bridgehead> </entry> </row> </thead> <tbody> <row> <entry valign="top"> <bridgehead renderas="sect3">Classes</bridgehead> <simplelist type="vert" columns="1"> <member><link linkend="asio.reference.generic__datagram_protocol">generic::datagram_protocol</link></member> <member><link linkend="asio.reference.generic__datagram_protocol.endpoint">generic::datagram_protocol::endpoint</link></member> <member><link linkend="asio.reference.generic__datagram_protocol.socket">generic::datagram_protocol::socket</link></member> <member><link linkend="asio.reference.generic__raw_protocol">generic::raw_protocol</link></member> <member><link linkend="asio.reference.generic__raw_protocol.endpoint">generic::raw_protocol::endpoint</link></member> <member><link linkend="asio.reference.generic__raw_protocol.socket">generic::raw_protocol::socket</link></member> <member><link linkend="asio.reference.generic__seq_packet_protocol">generic::seq_packet_protocol</link></member> <member><link linkend="asio.reference.generic__seq_packet_protocol.endpoint">generic::seq_packet_protocol::endpoint</link></member> <member><link linkend="asio.reference.generic__seq_packet_protocol.socket">generic::seq_packet_protocol::socket</link></member> <member><link linkend="asio.reference.generic__stream_protocol">generic::stream_protocol</link></member> <member><link linkend="asio.reference.generic__stream_protocol.endpoint">generic::stream_protocol::endpoint</link></member> <member><link linkend="asio.reference.generic__stream_protocol.iostream">generic::stream_protocol::iostream</link></member> <member><link linkend="asio.reference.generic__stream_protocol.socket">generic::stream_protocol::socket</link></member> <member><link linkend="asio.reference.ip__address">ip::address</link></member> <member><link linkend="asio.reference.ip__address_v4">ip::address_v4</link></member> <member><link linkend="asio.reference.ip__address_v4_iterator">ip::address_v4_iterator</link></member> <member><link linkend="asio.reference.ip__address_v4_range">ip::address_v4_range</link></member> <member><link linkend="asio.reference.ip__address_v6">ip::address_v6</link></member> <member><link linkend="asio.reference.ip__address_v6_iterator">ip::address_v6_iterator</link></member> <member><link linkend="asio.reference.ip__address_v6_range">ip::address_v6_range</link></member> <member><link linkend="asio.reference.ip__bad_address_cast">ip::bad_address_cast</link></member> <member><link linkend="asio.reference.ip__icmp">ip::icmp</link></member> <member><link linkend="asio.reference.ip__icmp.endpoint">ip::icmp::endpoint</link></member> <member><link linkend="asio.reference.ip__icmp.resolver">ip::icmp::resolver</link></member> <member><link linkend="asio.reference.ip__icmp.socket">ip::icmp::socket</link></member> <member><link linkend="asio.reference.ip__network_v4">ip::network_v4</link></member> <member><link linkend="asio.reference.ip__network_v6">ip::network_v6</link></member> <member><link linkend="asio.reference.ip__resolver_base">ip::resolver_base</link></member> <member><link linkend="asio.reference.ip__resolver_query_base">ip::resolver_query_base</link></member> <member><link linkend="asio.reference.ip__tcp">ip::tcp</link></member> <member><link linkend="asio.reference.ip__tcp.acceptor">ip::tcp::acceptor</link></member> <member><link linkend="asio.reference.ip__tcp.endpoint">ip::tcp::endpoint</link></member> <member><link linkend="asio.reference.ip__tcp.iostream">ip::tcp::iostream</link></member> <member><link linkend="asio.reference.ip__tcp.resolver">ip::tcp::resolver</link></member> <member><link linkend="asio.reference.ip__tcp.socket">ip::tcp::socket</link></member> <member><link linkend="asio.reference.ip__udp">ip::udp</link></member> <member><link linkend="asio.reference.ip__udp.endpoint">ip::udp::endpoint</link></member> <member><link linkend="asio.reference.ip__udp.resolver">ip::udp::resolver</link></member> <member><link linkend="asio.reference.ip__udp.socket">ip::udp::socket</link></member> <member><link linkend="asio.reference.ip__v4_mapped_t">ip::v4_mapped_t</link></member> <member><link linkend="asio.reference.socket_base">socket_base</link></member> </simplelist> </entry> <entry valign="top"> <bridgehead renderas="sect3">Free Functions</bridgehead> <simplelist type="vert" columns="1"> <member><link linkend="asio.reference.async_connect">async_connect</link></member> <member><link linkend="asio.reference.connect">connect</link></member> <member><link linkend="asio.reference.ip__host_name">ip::host_name</link></member> <member><link linkend="asio.reference.ip__address.make_address">ip::make_address</link></member> <member><link linkend="asio.reference.ip__address_v4.make_address_v4">ip::make_address_v4</link></member> <member><link linkend="asio.reference.ip__address_v6.make_address_v6">ip::make_address_v6</link></member> <member><link linkend="asio.reference.ip__network_v4.make_network_v4">ip::make_network_v4</link></member> <member><link linkend="asio.reference.ip__network_v6.make_network_v6">ip::make_network_v6</link></member> </simplelist> <bridgehead renderas="sect3">Class Templates</bridgehead> <simplelist type="vert" columns="1"> <member><link linkend="asio.reference.basic_datagram_socket">basic_datagram_socket</link></member> <member><link linkend="asio.reference.basic_raw_socket">basic_raw_socket</link></member> <member><link linkend="asio.reference.basic_seq_packet_socket">basic_seq_packet_socket</link></member> <member><link linkend="asio.reference.basic_socket">basic_socket</link></member> <member><link linkend="asio.reference.basic_socket_acceptor">basic_socket_acceptor</link></member> <member><link linkend="asio.reference.basic_socket_iostream">basic_socket_iostream</link></member> <member><link linkend="asio.reference.basic_socket_streambuf">basic_socket_streambuf</link></member> <member><link linkend="asio.reference.basic_stream_socket">basic_stream_socket</link></member> <member><link linkend="asio.reference.generic__basic_endpoint">generic::basic_endpoint</link></member> <member><link linkend="asio.reference.ip__basic_endpoint">ip::basic_endpoint</link></member> <member><link linkend="asio.reference.ip__basic_resolver">ip::basic_resolver</link></member> <member><link linkend="asio.reference.ip__basic_resolver_entry">ip::basic_resolver_entry</link></member> <member><link linkend="asio.reference.ip__basic_resolver_iterator">ip::basic_resolver_iterator</link></member> <member><link linkend="asio.reference.ip__basic_resolver_results">ip::basic_resolver_results</link></member> <member><link linkend="asio.reference.ip__basic_resolver_query">ip::basic_resolver_query</link></member> </simplelist> </entry> <entry valign="top"> <bridgehead renderas="sect3">Socket Options</bridgehead> <simplelist type="vert" columns="1"> <member><link linkend="asio.reference.ip__multicast__enable_loopback">ip::multicast::enable_loopback</link></member> <member><link linkend="asio.reference.ip__multicast__hops">ip::multicast::hops</link></member> <member><link linkend="asio.reference.ip__multicast__join_group">ip::multicast::join_group</link></member> <member><link linkend="asio.reference.ip__multicast__leave_group">ip::multicast::leave_group</link></member> <member><link linkend="asio.reference.ip__multicast__outbound_interface">ip::multicast::outbound_interface</link></member> <member><link linkend="asio.reference.ip__tcp.no_delay">ip::tcp::no_delay</link></member> <member><link linkend="asio.reference.ip__unicast__hops">ip::unicast::hops</link></member> <member><link linkend="asio.reference.ip__v6_only">ip::v6_only</link></member> <member><link linkend="asio.reference.socket_base.broadcast">socket_base::broadcast</link></member> <member><link linkend="asio.reference.socket_base.debug">socket_base::debug</link></member> <member><link linkend="asio.reference.socket_base.do_not_route">socket_base::do_not_route</link></member> <member><link linkend="asio.reference.socket_base.enable_connection_aborted">socket_base::enable_connection_aborted</link></member> <member><link linkend="asio.reference.socket_base.keep_alive">socket_base::keep_alive</link></member> <member><link linkend="asio.reference.socket_base.linger">socket_base::linger</link></member> <member><link linkend="asio.reference.socket_base.receive_buffer_size">socket_base::receive_buffer_size</link></member> <member><link linkend="asio.reference.socket_base.receive_low_watermark">socket_base::receive_low_watermark</link></member> <member><link linkend="asio.reference.socket_base.reuse_address">socket_base::reuse_address</link></member> <member><link linkend="asio.reference.socket_base.send_buffer_size">socket_base::send_buffer_size</link></member> <member><link linkend="asio.reference.socket_base.send_low_watermark">socket_base::send_low_watermark</link></member> </simplelist> </entry> <entry valign="top"> <bridgehead renderas="sect3">I/O Control Commands</bridgehead> <simplelist type="vert" columns="1"> <member><link linkend="asio.reference.socket_base.bytes_readable">socket_base::bytes_readable</link></member> </simplelist> <bridgehead renderas="sect3">Type Requirements</bridgehead> <simplelist type="vert" columns="1"> <member><link linkend="asio.reference.synchronous_socket_operations">Synchronous socket operations</link></member> <member><link linkend="asio.reference.asynchronous_socket_operations">Asynchronous socket operations</link></member> <member><link linkend="asio.reference.AcceptableProtocol">AcceptableProtocol</link></member> <member><link linkend="asio.reference.AcceptHandler">AcceptHandler</link></member> <member><link linkend="asio.reference.AcceptToken">AcceptToken</link></member> <member><link linkend="asio.reference.ConnectCondition">ConnectCondition</link></member> <member><link linkend="asio.reference.ConnectHandler">ConnectHandler</link></member> <member><link linkend="asio.reference.ConnectToken">ConnectToken</link></member> <member><link linkend="asio.reference.Endpoint">Endpoint</link></member> <member><link linkend="asio.reference.EndpointSequence">EndpointSequence</link></member> <member><link linkend="asio.reference.GettableSocketOption">GettableSocketOption</link></member> <member><link linkend="asio.reference.InternetProtocol">InternetProtocol</link></member> <member><link linkend="asio.reference.IoControlCommand">IoControlCommand</link></member> <member><link linkend="asio.reference.IteratorConnectHandler">IteratorConnectHandler</link></member> <member><link linkend="asio.reference.IteratorConnectToken">IteratorConnectToken</link></member> <member><link linkend="asio.reference.MoveAcceptHandler">MoveAcceptHandler</link></member> <member><link linkend="asio.reference.MoveAcceptToken">MoveAcceptToken</link></member> <member><link linkend="asio.reference.Protocol">Protocol</link></member> <member><link linkend="asio.reference.RangeConnectHandler">RangeConnectHandler</link></member> <member><link linkend="asio.reference.RangeConnectToken">RangeConnectToken</link></member> <member><link linkend="asio.reference.ResolveHandler">ResolveHandler</link></member> <member><link linkend="asio.reference.ResolveToken">ResolveToken</link></member> <member><link linkend="asio.reference.SettableSocketOption">SettableSocketOption</link></member> </simplelist> </entry> </row> </tbody> </tgroup> <tgroup cols="4"> <colspec colname="a"/> <colspec colname="b"/> <colspec colname="c"/> <colspec colname="d"/> <thead> <row> <entry valign="center" namest="a" nameend="a"> <bridgehead renderas="sect2">Timers</bridgehead> </entry> <entry valign="center" namest="b" nameend="b"> <bridgehead renderas="sect2">SSL</bridgehead> </entry> <entry valign="center" namest="c" nameend="c"> <bridgehead renderas="sect2">Serial Ports</bridgehead> </entry> <entry valign="center" namest="d" nameend="d"> <bridgehead renderas="sect2">Signal Handling</bridgehead> </entry> </row> </thead> <tbody> <row> <entry valign="top"> <bridgehead renderas="sect3">Classes</bridgehead> <simplelist type="vert" columns="1"> <member><link linkend="asio.reference.deadline_timer">deadline_timer</link></member> <member><link linkend="asio.reference.high_resolution_timer">high_resolution_timer</link></member> <member><link linkend="asio.reference.steady_timer">steady_timer</link></member> <member><link linkend="asio.reference.system_timer">system_timer</link></member> </simplelist> <bridgehead renderas="sect3">Class Templates</bridgehead> <simplelist type="vert" columns="1"> <member><link linkend="asio.reference.basic_deadline_timer">basic_deadline_timer</link></member> <member><link linkend="asio.reference.basic_waitable_timer">basic_waitable_timer</link></member> <member><link linkend="asio.reference.time_traits_lt__ptime__gt_">time_traits</link></member> <member><link linkend="asio.reference.wait_traits">wait_traits</link></member> </simplelist> <bridgehead renderas="sect3">Type Requirements</bridgehead> <simplelist type="vert" columns="1"> <member><link linkend="asio.reference.TimeTraits">TimeTraits</link></member> <member><link linkend="asio.reference.WaitHandler">WaitHandler</link></member> <member><link linkend="asio.reference.WaitToken">WaitToken</link></member> <member><link linkend="asio.reference.WaitTraits">WaitTraits</link></member> </simplelist> </entry> <entry valign="top"> <bridgehead renderas="sect3">Classes</bridgehead> <simplelist type="vert" columns="1"> <member><link linkend="asio.reference.ssl__context">ssl::context</link></member> <member><link linkend="asio.reference.ssl__context_base">ssl::context_base</link></member> <member><link linkend="asio.reference.ssl__host_name_verification">ssl::host_name_verification</link></member> <member><link linkend="asio.reference.ssl__rfc2818_verification">ssl::rfc2818_verification</link> (deprecated)</member> <member><link linkend="asio.reference.ssl__stream_base">ssl::stream_base</link></member> <member><link linkend="asio.reference.ssl__verify_context">ssl::verify_context</link></member> </simplelist> <bridgehead renderas="sect3">Class Templates</bridgehead> <simplelist type="vert" columns="1"> <member><link linkend="asio.reference.ssl__stream">ssl::stream</link></member> </simplelist> <bridgehead renderas="sect3">Error Codes</bridgehead> <simplelist type="vert" columns="1"> <member><link linkend="asio.reference.ssl__error__stream_errors">ssl::error::stream_errors</link></member> </simplelist> <bridgehead renderas="sect3">Type Requirements</bridgehead> <simplelist type="vert" columns="1"> <member><link linkend="asio.reference.BufferedHandshakeHandler">BufferedHandshakeHandler</link></member> <member><link linkend="asio.reference.BufferedHandshakeToken">BufferedHandshakeToken</link></member> <member><link linkend="asio.reference.HandshakeHandler">HandshakeHandler</link></member> <member><link linkend="asio.reference.HandshakeToken">HandshakeToken</link></member> <member><link linkend="asio.reference.ShutdownHandler">ShutdownHandler</link></member> <member><link linkend="asio.reference.ShutdownToken">ShutdownToken</link></member> </simplelist> </entry> <entry valign="top"> <bridgehead renderas="sect3">Classes</bridgehead> <simplelist type="vert" columns="1"> <member><link linkend="asio.reference.serial_port">serial_port</link></member> <member><link linkend="asio.reference.serial_port_base">serial_port_base</link></member> </simplelist> <bridgehead renderas="sect3">Class templates</bridgehead> <simplelist type="vert" columns="1"> <member><link linkend="asio.reference.basic_serial_port">basic_serial_port</link></member> </simplelist> <bridgehead renderas="sect3">Serial Port Options</bridgehead> <simplelist type="vert" columns="1"> <member><link linkend="asio.reference.serial_port_base__baud_rate">serial_port_base::baud_rate</link></member> <member><link linkend="asio.reference.serial_port_base__flow_control">serial_port_base::flow_control</link></member> <member><link linkend="asio.reference.serial_port_base__parity">serial_port_base::parity</link></member> <member><link linkend="asio.reference.serial_port_base__stop_bits">serial_port_base::stop_bits</link></member> <member><link linkend="asio.reference.serial_port_base__character_size">serial_port_base::character_size</link></member> </simplelist> <bridgehead renderas="sect3">Type Requirements</bridgehead> <simplelist type="vert" columns="1"> <member><link linkend="asio.reference.GettableSerialPortOption">GettableSerialPortOption</link></member> <member><link linkend="asio.reference.SettableSerialPortOption">SettableSerialPortOption</link></member> </simplelist> </entry> <entry valign="top"> <bridgehead renderas="sect3">Classes</bridgehead> <simplelist type="vert" columns="1"> <member><link linkend="asio.reference.signal_set">signal_set</link></member> </simplelist> <bridgehead renderas="sect3">Class Templates</bridgehead> <simplelist type="vert" columns="1"> <member><link linkend="asio.reference.basic_signal_set">basic_signal_set</link></member> </simplelist> <bridgehead renderas="sect3">Type Requirements</bridgehead> <simplelist type="vert" columns="1"> <member><link linkend="asio.reference.SignalHandler">SignalHandler</link></member> <member><link linkend="asio.reference.SignalToken">SignalToken</link></member> </simplelist> </entry> </row> </tbody> </tgroup> <tgroup cols="4"> <colspec colname="a"/> <colspec colname="b"/> <colspec colname="c"/> <colspec colname="d"/> <thead> <row> <entry valign="center" namest="a" nameend="a"> <bridgehead renderas="sect2">Files and Pipes</bridgehead> </entry> <entry valign="center" namest="b" nameend="c"> <bridgehead renderas="sect2">POSIX-specific</bridgehead> </entry> <entry valign="center" namest="d" nameend="d"> <bridgehead renderas="sect2">Windows-specific</bridgehead> </entry> </row> </thead> <tbody> <row> <entry valign="top"> <bridgehead renderas="sect3">Class Templates</bridgehead> <simplelist type="vert" columns="1"> <member><link linkend="asio.reference.basic_file">basic_file</link></member> <member><link linkend="asio.reference.basic_random_access_file">basic_random_access_file</link></member> <member><link linkend="asio.reference.basic_readable_pipe">basic_readable_pipe</link></member> <member><link linkend="asio.reference.basic_stream_file">basic_stream_file</link></member> <member><link linkend="asio.reference.basic_writable_pipe">basic_writable_pipe</link></member> </simplelist> <bridgehead renderas="sect3">Classes</bridgehead> <simplelist type="vert" columns="1"> <member><link linkend="asio.reference.file_base">file_base</link></member> <member><link linkend="asio.reference.random_access_file">random_access_file</link></member> <member><link linkend="asio.reference.readable_pipe">readable_pipe</link></member> <member><link linkend="asio.reference.stream_file">stream_file</link></member> <member><link linkend="asio.reference.writable_pipe">writable_pipe</link></member> </simplelist> <bridgehead renderas="sect3">Free Functions</bridgehead> <simplelist type="vert" columns="1"> <member><link linkend="asio.reference.connect_pipe">connect_pipe</link></member> </simplelist> </entry> <entry valign="top"> <bridgehead renderas="sect3">Classes</bridgehead> <simplelist type="vert" columns="1"> <member><link linkend="asio.reference.local__seq_packet_protocol">local::seq_packet_protocol</link></member> <member><link linkend="asio.reference.local__seq_packet_protocol.acceptor">local::seq_packet_protocol::acceptor</link></member> <member><link linkend="asio.reference.local__seq_packet_protocol.endpoint">local::seq_packet_protocol::endpoint</link></member> <member><link linkend="asio.reference.local__seq_packet_protocol.socket">local::seq_packet_protocol::socket</link></member> <member><link linkend="asio.reference.local__stream_protocol">local::stream_protocol</link></member> <member><link linkend="asio.reference.local__stream_protocol.acceptor">local::stream_protocol::acceptor</link></member> <member><link linkend="asio.reference.local__stream_protocol.endpoint">local::stream_protocol::endpoint</link></member> <member><link linkend="asio.reference.local__stream_protocol.iostream">local::stream_protocol::iostream</link></member> <member><link linkend="asio.reference.local__stream_protocol.socket">local::stream_protocol::socket</link></member> <member><link linkend="asio.reference.local__datagram_protocol">local::datagram_protocol</link></member> <member><link linkend="asio.reference.local__datagram_protocol.endpoint">local::datagram_protocol::endpoint</link></member> <member><link linkend="asio.reference.local__datagram_protocol.socket">local::datagram_protocol::socket</link></member> <member><link linkend="asio.reference.posix__descriptor">posix::descriptor</link></member> <member><link linkend="asio.reference.posix__descriptor_base">posix::descriptor_base</link></member> <member><link linkend="asio.reference.posix__stream_descriptor">posix::stream_descriptor</link></member> </simplelist> </entry> <entry valign="top"> <bridgehead renderas="sect3">Free Functions</bridgehead> <simplelist type="vert" columns="1"> <member><link linkend="asio.reference.local__connect_pair">local::connect_pair</link></member> </simplelist> <bridgehead renderas="sect3">Class Templates</bridgehead> <simplelist type="vert" columns="1"> <member><link linkend="asio.reference.local__basic_endpoint">local::basic_endpoint</link></member> <member><link linkend="asio.reference.posix__basic_descriptor">posix::basic_descriptor</link></member> <member><link linkend="asio.reference.posix__basic_stream_descriptor">posix::basic_stream_descriptor</link></member> </simplelist> </entry> <entry valign="top"> <bridgehead renderas="sect3">Classes</bridgehead> <simplelist type="vert" columns="1"> <member><link linkend="asio.reference.windows__object_handle">windows::object_handle</link></member> <member><link linkend="asio.reference.windows__overlapped_handle">windows::overlapped_handle</link></member> <member><link linkend="asio.reference.windows__overlapped_ptr">windows::overlapped_ptr</link></member> <member><link linkend="asio.reference.windows__random_access_handle">windows::random_access_handle</link></member> <member><link linkend="asio.reference.windows__stream_handle">windows::stream_handle</link></member> </simplelist> <bridgehead renderas="sect3">Class Templates</bridgehead> <simplelist type="vert" columns="1"> <member><link linkend="asio.reference.windows__basic_object_handle">windows::basic_object_handle</link></member> <member><link linkend="asio.reference.windows__basic_overlapped_handle">windows::basic_overlapped_handle</link></member> <member><link linkend="asio.reference.windows__basic_random_access_handle">windows::basic_random_access_handle</link></member> <member><link linkend="asio.reference.windows__basic_stream_handle">windows::basic_stream_handle</link></member> </simplelist> </entry> </row> </tbody> </tgroup> </informaltable>
0
repos/asio/asio/src
repos/asio/asio/src/doc/index.xml
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE library PUBLIC "-//Boost//DTD BoostBook XML V1.0//EN" "../../../boost/tools/boostbook/dtd/boostbook.dtd"> <!-- 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) --> <section id="asio.index"> <index id="asio.index.index"/> </section>
0
repos/asio/asio/src
repos/asio/asio/src/doc/noncopyable_dox.txt
/** \class noncopyable */
0
repos/asio/asio/src
repos/asio/asio/src/doc/platform_macros.pl
#!/usr/bin/perl -w # 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) use strict; open(my $fh, "<../../include/asio/detail/config.hpp") or die("can't open config.hpp"); my $current_comment = ""; my %has_macros = (); my %disable_macros = (); while (my $line = <$fh>) { chomp($line); if ($line =~ /^$/) { $current_comment = ""; } elsif ($line =~ /^\/\/ (.*)$/) { if (!($line =~ /boostify/)) { $current_comment = $current_comment . $1 . "\n"; } } elsif ($line =~ /^# *define *ASIO_HAS_([A-Z-0-9_]*) 1/) { if (not defined($has_macros{$1})) { $has_macros{$1} = $current_comment; } } elsif ($line =~ /ASIO_DISABLE_([A-Z-0-9_]*)/) { $disable_macros{$1} = 1; } } my $intro = <<EOF; [/ / 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) /] [heading Compiler/platform feature detection macros] Asio automatically defines preprocessor macros corresponding to the detected available features on a particular compiler and target platform. These macros are named with the prefix `ASIO_HAS_`, and are listed in the table below. Many of these macros also have a corresponding `ASIO_DISABLE_` macro that may be used to explicitly disable the feature. In general, `ASIO_HAS_` macros should not be explicitly defined by the user, except when absolutely required as a workaround for the latest version of a compiler or platform. For older compiler/platform combinations where a specific `ASIO_HAS_` macro is not automatically defined, testing may have shown that a claimed feature isn't sufficiently conformant to be compatible with Asio's needs. EOF print("$intro\n"); print("[table\n"); print(" [[Macro][Description][Macro to disable feature]]\n"); for my $macro (sort keys %has_macros) { print(" [\n"); print(" [`ASIO_HAS_$macro`]\n"); print(" [\n"); my $description = $has_macros{$macro}; chomp($description); $description =~ s/\n/\n /g; print(" $description\n"); print(" ]\n"); if (defined $disable_macros{$macro}) { print(" [`ASIO_DISABLE_$macro`]\n"); } else { print(" []\n"); } print(" ]\n"); } print("]\n");
0
repos/asio/asio/src
repos/asio/asio/src/doc/std_exception_dox.txt
/** \namespace std */ /** \class std::exception */
0
repos/asio/asio/src
repos/asio/asio/src/doc/boost_bind_dox.txt
/** \page boost_bind boost::bind See the <a href="http://www.boost.org/libs/bind/bind.html">Boost: bind.hpp documentation</a> for more information on how to use <tt>boost::bind</tt>. */
0
repos/asio/asio/src
repos/asio/asio/src/doc/doxy2qbk.pl
#!/usr/bin/perl -w # 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) use strict; system("doxygen reference.dox"); chdir("xml"); system("xsltproc combine.xslt index.xml > all.xml"); chdir(".."); system("xsltproc reference.xsl xml/all.xml > reference.qbk"); system("rm -rf xml"); system("doxygen tutorial.dox"); chdir("xml"); system("xsltproc combine.xslt index.xml > all.xml"); chdir(".."); system("xsltproc tutorial.xsl xml/all.xml > tutorial.qbk"); system("rm -rf xml reference.tags");
0
repos/asio/asio/src
repos/asio/asio/src/doc/model_dox.txt
// // 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) // /** \page asynchronous_operation asynchronous operation */ /** \page completion_token completion token */
0
repos/asio/asio/src
repos/asio/asio/src/doc/makepdf.pl
#!/usr/bin/perl -w # 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) use strict; # Determine version number my $version = "X.Y.Z"; open(VERSION, "../../include/asio/version.hpp") or die("Can't open version.hpp"); while (my $line = <VERSION>) { if ($line =~ /^#define ASIO_VERSION .* \/\/ (.*)$/) { $version = $1; } } close(VERSION); # Generate PDF output system("bjam asioref"); system("xsltproc --stringparam asio.version $version asioref.xsl asio.docbook > asioref.docbook"); system("dblatex -I overview -s asioref.sty -P table.in.float=0 -o asioref-$version.pdf asioref.docbook"); system("rm asioref.docbook");
0
repos/asio/asio/src/doc
repos/asio/asio/src/doc/overview/async_op1.dot
digraph g { graph [ nodesep="0.2" ]; edge [ fontname="Helvetica", fontsize=10, labelfontname="Helvetica", labelfontsize=10 ]; node [ fontname="Helvetica", fontsize=10, shape=box ]; edge [ arrowhead="open" ] // Program elements. { operating_system [ label="Operating System", shape=ellipse ]; io_context [ label="I/O Execution Context\ne.g. io_context" ]; io_object [ label="I/O Object\ne.g. socket" ]; your_program [ label="Your Program" ]; your_completion_handler [ label="Your Completion Handler" ]; } // Owning relationships. { edge [ arrowtail="diamond" ]; your_program:e -> your_completion_handler:n; your_program:w -> io_object:nw; your_program:se -> io_context:ne; } // Non-owning relationships; { io_object:sw -> io_context:w; } // Visible actions. { edge [ style="dashed", color="#808080" ]; // Forward actions. { your_program:sw -> io_object:n [ label="1" ]; io_object:s -> io_context:nw [ label="2" ]; io_context:s -> operating_system:n [ label="3" ]; } } // Invisible actions. { edge [ style="invis" ]; // Forward actions. { your_program:s -> io_context:n [ label="5" ]; } // Reverse actions. { edge [ arrowhead="none", arrowtail="open" ]; //io_context:s -> operating_system:n [ label="4" ]; your_completion_handler:s -> io_context:e [ label="6" ]; } } }
0
repos/asio/asio/src/doc
repos/asio/asio/src/doc/overview/sync_op.dot
digraph g { graph [ nodesep="0.6" ]; edge [ fontname="Helvetica", fontsize=10, labelfontname="Helvetica", labelfontsize=10 ]; node [ fontname="Helvetica", fontsize=10, shape=box ]; edge [ arrowhead="open" ] // Program elements. { operating_system [ label="Operating System", shape=ellipse ]; io_context [ label="I/O Execution Context\ne.g. io_context" ]; io_object [ label="I/O Object\ne.g. socket" ]; your_program [ label="Your Program" ]; } // Owning relationships. { edge [ arrowtail="diamond" ]; your_program:w -> io_object:nw; your_program:se -> io_context:ne; } // Non-owning relationships; { io_object:sw -> io_context:w; } // Actions. { edge [ style="dashed", color="#808080" ]; // Forward actions. { your_program:sw -> io_object:n [ label="1" ]; io_object:s -> io_context:nw [ label="2" ]; io_context:sw -> operating_system:nw [ label="3" ]; } // Reverse actions. { edge [ arrowhead="none", arrowtail="open" ]; io_context:se -> operating_system:ne [ label="4" ]; io_object:se -> io_context:n [ label="5" ]; your_program:s -> io_object:ne [ label="6" ]; } } }
0
repos/asio/asio/src/doc
repos/asio/asio/src/doc/overview/proactor.dot
digraph g { edge [ fontname="Helvetica", fontsize=10, labelfontname="Helvetica", labelfontsize=10 ]; node [ fontname="Helvetica", fontsize=10, shape=record ]; initiator [ label="Initiator" ]; async_processor [ label="Asynchronous\nOperation Processor" ]; async_op [ label="Asynchronous\nOperation" ]; completion_queue [ label="Completion\nEvent Queue" ]; async_event_demuxer [ label="Asynchronous\nEvent Demultiplexer" ]; proactor [ label="Proactor" ]; handler [ label="Completion\nHandler" ]; initiator -> async_processor [ label="uses", style="dashed" ]; initiator -> async_op [ label="starts", style="dashed" ]; initiator -> handler [ label="creates", style="dashed" ]; async_processor -> async_op [ label="executes", style="dashed" ]; async_processor -> completion_queue [ label="enqueues", style="dashed" ]; async_op -> handler; async_event_demuxer -> completion_queue [ label="dequeues", style="dashed" ]; proactor -> async_event_demuxer [ ]; proactor -> handler [ label="demultiplexes\n& dispatches" style="dashed" ]; }
0
repos/asio/asio/src/doc
repos/asio/asio/src/doc/overview/async_op2.dot
digraph g { graph [ nodesep="0.2" ]; edge [ fontname="Helvetica", fontsize=10, labelfontname="Helvetica", labelfontsize=10 ]; node [ fontname="Helvetica", fontsize=10, shape=box ]; edge [ arrowhead="open" ] // Program elements. { operating_system [ label="Operating System", shape=ellipse ]; io_context [ label="I/O Execution Context\ne.g. io_context" ]; io_object [ label="I/O Object\ne.g. socket" ]; your_program [ label="Your Program" ]; your_completion_handler [ label="Your Completion Handler" ]; } // Owning relationships. { edge [ arrowtail="diamond" ]; your_program:e -> your_completion_handler:n; your_program:w -> io_object:nw; your_program:se -> io_context:ne; } // Non-owning relationships; { io_object:sw -> io_context:w; } // Visible actions. { edge [ style="dashed", color="#808080" ]; // Forward actions. { your_program:s -> io_context:n [ label="5" ]; } // Reverse actions. { edge [ arrowhead="none", arrowtail="open" ]; io_context:s -> operating_system:n [ label="4" ]; your_completion_handler:s -> io_context:e [ label="6" ]; } } // Invisible actions. { edge [ style="invis" ]; // Forward actions. { your_program:sw -> io_object:n [ label="1" ]; io_object:s -> io_context:nw [ label="2" ]; //io_context:s -> operating_system:n [ label="3" ]; } } }
0
repos
repos/zbox/zbox.zig
pub const wires = @import("zbox/wires.zig"); pub const values = @import("zbox/values.zig"); pub const Drawing = @import("zbox/Drawing.zig"); pub const X_Ref = @import("zbox/X_Ref.zig"); pub const Y_Ref = @import("zbox/Y_Ref.zig"); pub const Point_Ref = @import("zbox/Point_Ref.zig"); pub const X_Ref_Cluster = @import("zbox/X_Ref_Cluster.zig"); pub const Y_Ref_Cluster = @import("zbox/Y_Ref_Cluster.zig"); pub const Box = @import("zbox/Box.zig"); pub const Label = @import("zbox/Label.zig"); pub const Wire_H = @import("zbox/Wire_H.zig"); pub const Wire_V = @import("zbox/Wire_V.zig"); pub const Separator_H = @import("zbox/Separator_H.zig"); pub const Separator_V = @import("zbox/Separator_V.zig"); test "example" { var d = Drawing.init(std.testing.allocator); defer d.deinit(); d.title = "Test"; d.desc = "some descriptive words"; const b = d.box(.{ .label = "Hello\nWorld" }) .top_label(.left, "ASDF") .bottom_label(.right, "123abc") ; _ = b.size(300, 400); _ = b.right_side("CLK"); _ = b.right_side("D0"); _ = b.right_side("D3"); _ = b.right_side(""); const asdf = b.left_side("asdf").wire_h(.{}).length(-50); _ = asdf.turn() .turn_at_offset(b.top(), -50) .turn_at_offset(b.right(), 50) .turn_and_end_at(b.right_side("asdf")) ; _ = asdf.turn().turn().y() .wire(.{ .dir = .junction_begin }) .end_at_point(b.top_side("asdf")) ; const small = d.box(.{ .shape = .small, .label = "^1" }); _ = small.top_left().attach_to_offset(b.top_right(), 300, 0); const mux = d.box(.{ .shape = .mux }); _ = mux.top_center().attach_to_offset(small.bottom_center(), 0, 50); const demux = d.box(.{ .shape = .demux }); _ = demux.middle_left().attach_to_offset(mux.middle_right(), 50, 0); _ = b.top_side("asd"); _ = b.top_side("asd2"); _ = b.top_side("asd3"); _ = b.bottom_side("Hello World!"); _ = b.bottom_side("Hellorld!"); const b2 = d.box(.{}); _ = b2.left().attach_to_offset(b.right(), 150); _ = b2.bottom().attach_to(b.bottom()); const halfway = d.some_x().attach_between(b.right(), b2.left(), 0.5); const sep = d.separator_v(); _ = sep.x().attach_to(halfway); _ = sep.label(d.y(0), "asdf1", .{}); _ = sep.label(d.y(0), "asdf2", .{ .baseline = .hanging }); const cols = d.columns(); _ = cols.center().attach_between(b.right(), b2.left(), 0.5); _ = b.right_side("D4") .wire_h(.{ .bits = 32, .dir = .reverse }) .bit_mark() .turn_at(cols.push()) .bit_mark() .label("D4", .{ .baseline = .hanging, .alignment = .right }) .turn_and_end_at(b2.left_side("IN")); _ = b.right_side("D5") .wire_h(.{ .dir = .junction_both }) .turn_at(cols.push()) .bit_mark_at(0.2) .label("D5", .{}) .turn_and_end_at(b2.left_side("IN2")); _ = b2.left_side("aaa") .wire_h(.{}) .bit_mark() .end_at_mutable_point(b.right_side("qqq")); cols.interface.flip(); const b3 = d.box(.{}); _ = b2.bottom_right().attach(b3.bottom_left()); const bus = d.point() .attach_to_offset(b.bottom_left(), 0, 100) .wire_h(.{ .bits = 16 }) .bit_mark() ; const bus2 = bus.continue_at(b.right()).end_at(b3.right()); _ = bus.endpoint() .wire_v(.{ .bits = 16, .dir = .junction_begin }) .turn() .end_at_point(bus2.endpoint().offset(0, 100)); _ = bus.label("Hellorld", .{ .baseline = .middle, .alignment = .right }); _ = bus2.label("Hello", .{}); _ = bus2.label("fasdf", .{ .baseline = .middle, .alignment = .left }); _ = bus.y().wire(.{ .dir = .forward }).end_at_point(b2.bottom_side("ABC")); _ = bus.y().wire(.{ .dir = .reverse }).end_at_point(b2.bottom_side("DEF")); _ = b3.bottom_side("XYZ").wire_v(.{ .dir = .forward }).end_at(bus.y()); _ = b3.bottom_side("123").wire_v(.{ .dir = .reverse }).end_at(bus.y()); var f = try std.fs.cwd().createFile("test.svg", .{}); defer f.close(); try d.render_svg(f.writer()); //try d.state.debug(std.io.getStdErr().writer()); } const std = @import("std");
0
repos
repos/zbox/build.zig.zon
.{ .name = "ZBox", .version = "1.1.0", .minimum_zig_version = "0.12.0-dev.1849+bb0f7d55e", .dependencies = .{ .@"Zig-DeepHashMap" = .{ .url = "https://github.com/bcrist/Zig-DeepHashMap/archive/7f5cc0cc3d36545a6f9bcf34c1b5cc4f06a3cd56.tar.gz", .hash = "122081984f52f7ca15d7ced6e11266e79e7db5f162048c3e272e838585393d63cdb9", }, }, .paths = .{ "build.zig", "build.zig.zon", "zbox.zig", "zbox", }, }
0
repos
repos/zbox/build.zig
const std = @import("std"); pub fn build(b: *std.Build) void { const deep_hash_map = b.dependency("Zig-DeepHashMap", .{}).module("deep_hash_map"); const zbox = b.addModule("zbox", .{ .root_source_file = .{ .path = "zbox.zig" }, }); zbox.addImport("deep_hash_map", deep_hash_map); const tests = b.addTest(.{ .root_source_file = .{ .path = "zbox.zig"}, .target = b.standardTargetOptions(.{}), .optimize = b.standardOptimizeOption(.{}), }); tests.root_module.addImport("deep_hash_map", deep_hash_map); const run_tests = b.addRunArtifact(tests); const test_step = b.step("test", "Run all tests"); test_step.dependOn(&run_tests.step); }
0
repos
repos/zbox/readme.md
# ZBox ZBox is a tool for programmatically creating SVG block diagrams in Zig.
0
repos/zbox
repos/zbox/zbox/Point_Ref.zig
state: *Drawing_State, _x: *f64, _y: *f64, mut_x: bool = true, mut_y: bool = true, pub fn anchor_at(self: Point_Ref, abs_x: f64, abs_y: f64) Point_Ref { if (!self.mut_x or !self.mut_y) { @panic("This point is not mutable"); } self.state.remove_constraint(self._x); self.state.remove_constraint(self._y); self._x.* = abs_x; self._y.* = abs_y; return self; } pub fn attach(self: Point_Ref, other: Point_Ref) Point_Ref { _ = other.attach_to(self); return self; } pub fn attach_to(self: Point_Ref, target: Point_Ref) Point_Ref { if (!self.mut_x or !self.mut_y) { @panic("This point is not mutable"); } self.state.constrain_eql(self._x, target._x, "Point_Ref attach_to x"); self.state.constrain_eql(self._y, target._y, "Point_Ref attach_to y"); return self; } pub fn attach_to_offset(self: Point_Ref, target: Point_Ref, offset_x: f64, offset_y: f64) Point_Ref { if (!self.mut_x or !self.mut_y) { @panic("This point is not mutable"); } self.state.constrain_offset(self._x, target._x, offset_x, "Point_Ref attach_to_offset x"); self.state.constrain_offset(self._y, target._y, offset_y, "Point_Ref attach_to_offset y"); return self; } pub fn attach_between(self: Point_Ref, a: Point_Ref, b: Point_Ref, f: f64) Point_Ref { if (!self.mut_x or !self.mut_y) { @panic("This point is not mutable"); } self.state.constrain_lerp(self._x, a._x, b._x, f, "Point_Ref x attach_between"); self.state.constrain_lerp(self._y, a._y, b._y, f, "Point_Ref y attach_between"); return self; } pub fn x(self: Point_Ref) X_Ref { return .{ .state = self.state, ._x = self._x, .mut = self.mut_x, }; } pub fn y(self: Point_Ref) Y_Ref { return .{ .state = self.state, ._y = self._y, .mut = self.mut_y, }; } pub fn offset(self: Point_Ref, x_offset: f64, y_offset: f64) Point_Ref { const xv = self.state.create_value(values.uninitialized); const yv = self.state.create_value(values.uninitialized); self.state.constrain_offset(xv, self._x, x_offset, "Point_Ref x offset"); self.state.constrain_offset(yv, self._y, y_offset, "Point_Ref y offset"); return .{ .state = self.state, ._x = xv, ._y = yv, }; } pub fn label(self: Point_Ref, class: []const u8, alignment: Label.Alignment, baseline: Label.Baseline, text: []const u8) *Label { const item = self.state.create_label(text, class, alignment, baseline, 0); self.state.constrain_eql(&item._x, self._x, "label x"); self.state.constrain_eql(&item._y, self._y, "label y"); return item; } pub fn label_v(self: Point_Ref, class: []const u8, alignment: Label.Alignment, baseline: Label.Baseline, text: []const u8) *Label { const item = self.state.create_label(text, class, alignment, baseline, -90); self.state.constrain_eql(&item._x, self._x, "label x"); self.state.constrain_eql(&item._y, self._y, "label y"); return item; } pub fn wire_h(self: Point_Ref, options: wires.Options) *Wire_H { const item = self.state.create_wire_h(options, null); self.state.constrain_eql(&item._x.begin, self._x, "wire begin x"); self.state.constrain_eql(&item._y, self._y, "wire y"); return item; } pub fn wire_v(self: Point_Ref, options: wires.Options) *Wire_V { const item = self.state.create_wire_v(options, null); self.state.constrain_eql(&item._x, self._x, "wire x"); self.state.constrain_eql(&item._y.begin, self._y, "wire begin y"); return item; } const Point_Ref = @This(); const X_Ref = @import("X_Ref.zig"); const Y_Ref = @import("Y_Ref.zig"); const Label = @import("Label.zig"); const Wire_H = @import("Wire_H.zig"); const Wire_V = @import("Wire_V.zig"); const wires = @import("wires.zig"); const values = @import("values.zig"); const Drawing_State = @import("Drawing_State.zig"); const std = @import("std");
0
repos/zbox
repos/zbox/zbox/Y_Ref.zig
state: *Drawing_State, _y: *f64, mut: bool = true, pub fn anchor_at(self: Y_Ref, abs_y: f64) Y_Ref { if (!self.mut) { @panic("This y coordinate is not mutable"); } self.state.remove_constraint(self._y); self._y.* = abs_y; return self; } pub fn attach(self: Y_Ref, other: Y_Ref) Y_Ref { _ = other.attach_to(self); return self; } pub fn attach_to(self: Y_Ref, target: Y_Ref) Y_Ref { if (!self.mut) { @panic("This y coordinate is not mutable"); } self.state.constrain_eql(self._y, target._y, "Y_Ref attach_to"); return self; } pub fn attach_to_offset(self: Y_Ref, target: Y_Ref, offset_y: f64) Y_Ref { if (!self.mut) { @panic("This y coordinate is not mutable"); } self.state.constrain_offset(self._y, target._y, offset_y, "Y_Ref attach_to_offset"); return self; } pub fn attach_between(self: Y_Ref, a: Y_Ref, b: Y_Ref, f: f64) Y_Ref { if (!self.mut) { @panic("This y coordinate is not mutable"); } self.state.constrain_lerp(self._y, a._y, b._y, f, "Y_Ref attach_between"); return self; } pub fn intersection_with(self: Y_Ref, x: X_Ref) Point_Ref { std.debug.assert(self.state == x.state); return .{ .state = self.state, ._x = x._x, ._y = self._y, .mut_x = x.mut, .mut_y = self.mut, }; } // Note that this creates a new loose value representing the offset location pub fn offset(self: Y_Ref, amount: f64) Y_Ref { const y = self.state.create_value(values.uninitialized); self.state.constrain_offset(y, self._y, amount, "Y_Ref offset"); return .{ .state = self.state, ._y = y, }; } pub fn wire(self: Y_Ref, options: wires.Options) *Wire_V { const item = self.state.create_wire_v(options, null); self.state.constrain_eql(&item._y.begin, self._y, "wire begin y"); return item; } const Y_Ref = @This(); const X_Ref = @import("X_Ref.zig"); const Point_Ref = @import("Point_Ref.zig"); const Wire_V = @import("Wire_V.zig"); const wires = @import("wires.zig"); const values = @import("values.zig"); const Drawing_State = @import("Drawing_State.zig"); const std = @import("std");
0
repos/zbox
repos/zbox/zbox/values.zig
pub const uninitialized: f64 = @bitCast(@as(u64, 0x7FF8_0000_0000_0001)); pub const constrained: f64 = @bitCast(@as(u64, 0x7FF8_0000_0000_0002)); pub fn is_uninitialized(value: f64) bool { const uvalue: u64 = @bitCast(value); const ucheck: u64 = @bitCast(uninitialized); return uvalue == ucheck; } pub fn is_constrained(value: f64) bool { const uvalue: u64 = @bitCast(value); const ucheck: u64 = @bitCast(constrained); return uvalue == ucheck; } pub fn ptr_to_slice(val: *const *const f64) []const *const f64 { // This can be removed when https://github.com/ziglang/zig/issues/16075 is implemented var slice: []const *const f64 = undefined; slice.ptr = @ptrCast(val); slice.len = 1; return slice; } const std = @import("std");
0
repos/zbox
repos/zbox/zbox/kahn.zig
/// A standard topological sort pub fn sort(arena: std.mem.Allocator, constraints: []Constraint) !void { var open_nodes = Open_Node_List.initCapacity(arena, constraints.len) catch @panic("OOM"); const nodes = init_nodes(arena, constraints, &open_nodes); _ = nodes; var out_index: usize = 0; while (open_nodes.items.len > 0) { var node = open_nodes.pop(); std.debug.assert(node.antecedents.len == 0); constraints[out_index] = node.constraint; out_index += 1; for (node.successors) |successor| { successor.remove_antecedent(node); if (successor.antecedents.len == 0) { open_nodes.appendAssumeCapacity(successor); } } node.successors.len = 0; } if (out_index != constraints.len) { return error.CyclicDependency; } } fn init_nodes(arena: std.mem.Allocator, constraints: []Constraint, open_nodes: *Open_Node_List) []Node { const nodes = arena.alloc(Node, constraints.len) catch @panic("OOM"); var ptr_to_node = ShallowAutoHashMap(*const f64, *Node).init(arena); for (constraints, nodes) |constraint, *node| { node.constraint = constraint; node.antecedents = arena.alloc(*Node, constraint.op.deps().len) catch @panic("OOM"); node.antecedents.len = 0; node.successors = &.{}; ptr_to_node.put(constraint.dest, node) catch @panic("OOM"); } for (constraints) |constraint| { for (constraint.op.deps()) |ptr| { if (ptr_to_node.get(ptr)) |antecedent| { antecedent.successors.len += 1; } } } for (nodes) |*node| { const successors = node.successors.len; if (successors > 0) { node.successors = arena.alloc(*Node, successors) catch @panic("OOM"); node.successors.len = 0; } } for (constraints, nodes) |constraint, *node| { for (constraint.op.deps()) |ptr| { if (ptr_to_node.get(ptr)) |antecedent| { node.add_antecedent(antecedent); antecedent.add_successor(node); } } if (node.antecedents.len == 0) { open_nodes.appendAssumeCapacity(node); } } return nodes; } const Node = struct { constraint: Constraint, antecedents: []*Node, successors: []*Node, pub fn add_antecedent(self: *Node, antecedent: *Node) void { self.antecedents.len += 1; self.antecedents[self.antecedents.len - 1] = antecedent; } pub fn remove_antecedent(self: *Node, antecedent: *Node) void { for (0.., self.antecedents) |i, node| { if (node == antecedent) { self.antecedents[i] = self.antecedents[self.antecedents.len - 1]; self.antecedents.len -= 1; return; } } std.debug.assert(false); // antecedent not found } pub fn add_successor(self: *Node, successor: *Node) void { self.successors.len += 1; self.successors[self.successors.len - 1] = successor; } }; const Open_Node_List = std.ArrayListUnmanaged(*Node); const Constraint = @import("Constraint.zig"); const ShallowAutoHashMap = @import("deep_hash_map").ShallowAutoHashMap; const std = @import("std");
0
repos/zbox
repos/zbox/zbox/Viewport.zig
left: ?f64 = null, right: ?f64 = null, top: ?f64 = null, bottom: ?f64 = null, pub fn width(self: Viewport) f64 { if (self.left) |left| { if (self.right) |right| { return right - left; } } return 0; } pub fn height(self: Viewport) f64 { if (self.top) |top| { if (self.bottom) |bottom| { return bottom - top; } } return 0; } pub fn include_point(self: *Viewport, x: f64, y: f64) void { self.left = if (self.left) |left| @min(left, x) else x; self.right = if (self.right) |right| @max(right, x) else x; self.top = if (self.top) |top| @min(top, y) else y; self.bottom = if (self.bottom) |bottom| @max(bottom, y) else y; } const Viewport = @This();
0
repos/zbox
repos/zbox/zbox/Style.zig
base_css: []const u8 = @embedFile("default.css"), extra_css: []const u8 = "", drawing_padding_x: f64 = 25, drawing_padding_y: f64 = 25, box_padding_x: f64 = 8, box_padding_y: f64 = 10, box_label_line_height: f64 = 25, default_interface_spacing: f64 = 20, separator_label_padding_x: f64 = 8, separator_label_padding_y: f64 = 4, wire_style: Wire_Style = .{ .label_padding_x = 8, .label_padding_y = 3, .label_padding_cap = 5, .default_length = 100, .default_corner_radius = 5, .arrow_length = 10, .arrow_width = 5, .junction_radius = 4, .bit_mark_length = 6, .bit_mark_label_offset_x = 5, .bit_mark_label_offset_xy = 1, .bit_mark_label_offset_y = 5, }, bus_style: Wire_Style = .{ .label_padding_x = 8, .label_padding_y = 4, .label_padding_cap = 5, .default_length = 100, .default_corner_radius = 5, .arrow_length = 12, .arrow_width = 8, .junction_radius = 6, .bit_mark_length = 10, .bit_mark_label_offset_x = 6, .bit_mark_label_offset_xy = 1.5, .bit_mark_label_offset_y = 7, }, pub const Wire_Style = struct { label_padding_x: f64, label_padding_y: f64, label_padding_cap: f64, default_length: f64, default_corner_radius: f64, // TODO rounded corners on wires arrow_length: f64, arrow_width: f64, junction_radius: f64, bit_mark_length: f64, bit_mark_label_offset_x: f64, bit_mark_label_offset_xy: f64, bit_mark_label_offset_y: f64, };
0
repos/zbox
repos/zbox/zbox/Separator_V.zig
state: *Drawing_State, class: []const u8 = "", _x: f64 = values.uninitialized, pub fn x(self: *Separator_V) X_Ref { return .{ .state = self.state, ._x = &self._x, }; } pub fn label(self: *Separator_V, y: Y_Ref, text: []const u8, options: Label.Options) *Separator_V { var options_mut = options; options_mut.angle = -90; options_mut._class1 = self.class; options_mut._class2 = "sep-label"; const style = &self.state.drawing.style; const item = self.state.create_label(text, options_mut); switch (options_mut.baseline) { .normal => self.state.constrain_offset(&item._x, &self._x, -style.separator_label_padding_y, "separator label x"), .middle => self.state.constrain_eql(&item._x, &self._x, "separator label x"), .hanging => self.state.constrain_offset(&item._x, &self._x, style.separator_label_padding_y, "separator label x"), } switch (options_mut.alignment) { .left => self.state.constrain_offset(&item._y, y._y, style.separator_label_padding_x, "separator label y"), .center => self.state.constrain_eql(&item._y, y._y, "separator label y"), .right => self.state.constrain_offset(&item._y, y._y, -style.separator_label_padding_x, "separator label y"), } return self; } const Separator_V = @This(); const X_Ref = @import("X_Ref.zig"); const Y_Ref = @import("Y_Ref.zig"); const Label = @import("Label.zig"); const Drawing_State = @import("Drawing_State.zig"); const values = @import("values.zig"); const std = @import("std");
0
repos/zbox
repos/zbox/zbox/Box.zig
state: *Drawing_State, options: Options, _x: Span = .{}, _y: Span = .{}, _l: ?*Interface = null, _r: ?*Interface = null, _t: ?*Interface = null, _b: ?*Interface = null, pub const Options = struct { shape: Shape = .block, class: []const u8 = "", label: []const u8 = "", label_class: []const u8 = "", }; pub const Shape = enum { block, small, mux, demux, }; pub fn left(self: *Box) X_Ref { return .{ .state = self.state, ._x = &self._x.begin, }; } pub fn right(self: *Box) X_Ref { return .{ .state = self.state, ._x = &self._x.end, }; } pub fn top(self: *Box) Y_Ref { return .{ .state = self.state, ._y = &self._y.begin, }; } pub fn bottom(self: *Box) Y_Ref { return .{ .state = self.state, ._y = &self._y.end, }; } pub fn x(self: *Box) X_Ref { return .{ .state = self.state, ._x = &self._x.mid, }; } pub fn y(self: *Box) Y_Ref { return .{ .state = self.state, ._y = &self._y.mid, }; } pub fn top_left(self: *Box) Point_Ref { return .{ .state = self.state, ._x = &self._x.begin, ._y = &self._y.begin, }; } pub fn top_center(self: *Box) Point_Ref { return .{ .state = self.state, ._x = &self._x.mid, ._y = &self._y.begin, }; } pub fn top_right(self: *Box) Point_Ref { return .{ .state = self.state, ._x = &self._x.end, ._y = &self._y.begin, }; } pub fn middle_left(self: *Box) Point_Ref { return .{ .state = self.state, ._x = &self._x.begin, ._y = &self._y.mid, }; } pub fn middle_center(self: *Box) Point_Ref { return .{ .state = self.state, ._x = &self._x.mid, ._y = &self._y.mid, }; } pub fn middle_right(self: *Box) Point_Ref { return .{ .state = self.state, ._x = &self._x.end, ._y = &self._y.mid, }; } pub fn bottom_left(self: *Box) Point_Ref { return .{ .state = self.state, ._x = &self._x.begin, ._y = &self._y.end, }; } pub fn bottom_center(self: *Box) Point_Ref { return .{ .state = self.state, ._x = &self._x.mid, ._y = &self._y.end, }; } pub fn bottom_right(self: *Box) Point_Ref { return .{ .state = self.state, ._x = &self._x.end, ._y = &self._y.end, }; } pub fn width(self: *Box, w: f64) *Box { self.state.remove_constraint(&self._x.delta); self._x.delta = w; return self; } pub fn match_width_of(self: *Box, other: *const Box) *Box { self.state.constrain_eql(&self._x.delta, &other._x.delta, "box width"); return self; } pub fn height(self: *Box, h: f64) *Box { self.state.remove_constraint(&self._y.delta); self._y.delta = h; return self; } pub fn match_height_of(self: *Box, other: *const Box) *Box { self.state.constrain_eql(&self._y.delta, &other._y.delta, "box height"); return self; } pub fn size(self: *Box, w: f64, h: f64) *Box { self.state.remove_constraint(&self._x.delta); self.state.remove_constraint(&self._y.delta); self._x.delta = w; self._y.delta = h; return self; } pub fn match_size_of(self: *Box, other: *const Box) *Box { self.state.constrain_eql(&self._x.delta, &other._x.delta, "box width"); self.state.constrain_eql(&self._y.delta, &other._y.delta, "box height"); return self; } pub fn top_label(self: *Box, alignment: Label.Alignment, text: []const u8) *Box { return self.top_label_with_class("", alignment, text); } pub fn top_label_with_class(self: *Box, extra_class: []const u8, alignment: Label.Alignment, text: []const u8) *Box { const item = self.state.create_label(text, .{ .class = extra_class, ._class1 = @tagName(self.options.shape), ._class2 = "box-label top", .alignment = alignment, .baseline = .hanging, }); self.constrain_label_x(alignment, &item._x); self.state.constrain_offset(&item._y, &self._y.begin, self.state.drawing.style.box_padding_y, "box label y from span begin"); return self; } pub fn bottom_label(self: *Box, alignment: Label.Alignment, text: []const u8) *Box { return self.bottom_label_with_class("", alignment, text); } pub fn bottom_label_with_class(self: *Box, extra_class: []const u8, alignment: Label.Alignment, text: []const u8) *Box { const item = self.state.create_label(text, .{ .class = extra_class, ._class1 = @tagName(self.options.shape), ._class2 = "box-label bottom", .alignment = alignment, .baseline = .normal, }); self.constrain_label_x(alignment, &item._x); self.state.constrain_offset(&item._y, &self._y.end, -self.state.drawing.style.box_padding_y, "box label y from span end"); return self; } fn constrain_label_x(self: *Box, alignment: Label.Alignment, label_x: *f64) void { switch (alignment) { .left => self.state.constrain_offset(label_x, &self._x.begin, self.state.drawing.style.box_padding_x, "box label x from span begin"), .center => self.state.constrain_eql(label_x, &self._x.mid, "box label x from span mid"), .right => self.state.constrain_offset(label_x, &self._x.end, -self.state.drawing.style.box_padding_x, "box label x from span end"), } } pub fn left_side(self: *Box, text: []const u8) Point_Ref { return self.left_side_with_class("", text); } pub fn left_side_with_class(self: *Box, extra_class: []const u8, text: []const u8) Point_Ref { const iy = self.get_left_interface().push(); if (text.len > 0) { const item = self.state.create_label(text, .{ .class = extra_class, ._class1 = @tagName(self.options.shape), ._class2 = "box-label interface left", .alignment = .left, .baseline = .middle, }); self.constrain_label_x(.left, &item._x); self.state.constrain_eql(&item._y, iy, "interface label y from interface y"); } return .{ .state = self.state, ._x = &self._x.begin, ._y = iy, }; } pub fn get_left_side(self: *Box, index: usize) Point_Ref { return .{ .state = self.state, ._x = &self._x.begin, ._y = self.get_left_interface().contents.items[index], }; } pub fn right_side(self: *Box, text: []const u8) Point_Ref { return self.right_side_with_class("", text); } pub fn right_side_with_class(self: *Box, extra_class: []const u8, text: []const u8) Point_Ref { const iy = self.get_right_interface().push(); if (text.len > 0) { const item = self.state.create_label(text, .{ .class = extra_class, ._class1 = @tagName(self.options.shape), ._class2 = "box-label interface right", .alignment = .right, .baseline = .middle, }); self.constrain_label_x(.right, &item._x); self.state.constrain_eql(&item._y, iy, "interface label y from interface y"); } return .{ .state = self.state, ._x = &self._x.end, ._y = iy, }; } pub fn get_right_side(self: *Box, index: usize) Point_Ref { return .{ .state = self.state, ._x = &self._x.end, ._y = self.get_right_interface().contents.items[index], }; } pub fn top_side(self: *Box, text: []const u8) Point_Ref { return self.top_side_with_class("", text); } pub fn top_side_with_class(self: *Box, extra_class: []const u8, text: []const u8) Point_Ref { const ix = self.get_top_interface().push(); if (text.len > 0) { const item = self.state.create_label(text, .{ .class = extra_class, ._class1 = @tagName(self.options.shape), ._class2 = "box-label interface top", .alignment = .right, .baseline = .middle, .angle = -90, }); self.state.constrain_eql(&item._x, ix, "interface label x from interface x"); // since we're rotated we use the x padding in the y direction: self.state.constrain_offset(&item._y, &self._y.begin, self.state.drawing.style.box_padding_x, "interface label y from box y span begin"); } return .{ .state = self.state, ._x = ix, ._y = &self._y.begin, }; } pub fn get_top_side(self: *Box, index: usize) Point_Ref { return .{ .state = self.state, ._x = self.get_top_interface().contents.items[index], ._y = &self._y.begin, }; } pub fn bottom_side(self: *Box, text: []const u8) Point_Ref { return self.bottom_side_with_class("", text); } pub fn bottom_side_with_class(self: *Box, extra_class: []const u8, text: []const u8) Point_Ref { const ix = self.get_bottom_interface().push(); if (text.len > 0) { const item = self.state.create_label(text, .{ .class = extra_class, ._class1 = @tagName(self.options.shape), ._class2 = "box-label interface bottom", .alignment = .left, .baseline = .middle, .angle = -90, }); self.state.constrain_eql(&item._x, ix, "interface label x from interface x"); // since we're rotated we use the x padding in the y direction: self.state.constrain_offset(&item._y, &self._y.end, -self.state.drawing.style.box_padding_x, "interface label y from box y span end"); } return .{ .state = self.state, ._x = ix, ._y = &self._y.end, }; } pub fn get_bottom_side(self: *Box, index: usize) Point_Ref { return .{ .state = self.state, ._x = self.get_bottom_interface().contents.items[index], ._y = &self._y.begin, }; } pub fn get_left_interface(self: *Box) *Interface { if (self._l) |interface| return interface; const interface = self.state.create_interface(); self._l = interface; return interface; } pub fn get_right_interface(self: *Box) *Interface { if (self._r) |interface| return interface; const interface = self.state.create_interface(); self._r = interface; return interface; } pub fn get_top_interface(self: *Box) *Interface { if (self._t) |interface| return interface; const interface = self.state.create_interface(); self._t = interface; return interface; } pub fn get_bottom_interface(self: *Box) *Interface { if (self._b) |interface| return interface; const interface = self.state.create_interface(); self._b = interface; return interface; } pub fn add_missing_constraints(self: *Box) void { if (self._l) |interface| self.add_missing_interface_constraints(interface, &self._y.mid); if (self._r) |interface| self.add_missing_interface_constraints(interface, &self._y.mid); if (self._t) |interface| self.add_missing_interface_constraints(interface, &self._x.mid); if (self._b) |interface| self.add_missing_interface_constraints(interface, &self._x.mid); if (self.options.shape == .mux or self.options.shape == .demux) { if (!self._x.is_delta_constrained()) { self.state.constrain_scale(&self._x.delta, &self._y.delta, 0.5, "mux/demux default width"); } } self._x.add_missing_constraints(self.state, 0, switch (self.options.shape) { .block, .mux, .demux => 240, .small => 25, }); self._y.add_missing_constraints(self.state, 0, switch (self.options.shape) { .block, .mux, .demux => 120, .small => 25, }); } fn add_missing_interface_constraints(self: *Box, interface: *Interface, default_mid: *const f64) void { if (!interface.span.is_position_constrained()) { self.state.constrain_eql(&interface.span.mid, default_mid, "interface span mid matching box mid"); } interface.add_missing_constraints(); } pub fn debug(self: *Box, writer: anytype) !void { try writer.print("Box: {s}\n", .{ self.class }); try writer.writeAll(" x: "); try self._x.debug(writer); try writer.writeAll(" y: "); try self._y.debug(writer); if (self._l) |interface| { try writer.writeAll(" l: "); try interface.debug(writer); } if (self._r) |interface| { try writer.writeAll(" r: "); try interface.debug(writer); } if (self._t) |interface| { try writer.writeAll(" t: "); try interface.debug(writer); } if (self._b) |interface| { try writer.writeAll(" b: "); try interface.debug(writer); } } const Box = @This(); const X_Ref = @import("X_Ref.zig"); const Y_Ref = @import("Y_Ref.zig"); const Point_Ref = @import("Point_Ref.zig"); const Label = @import("Label.zig"); const Interface = @import("Interface.zig"); const Span = @import("Span.zig"); const Drawing_State = @import("Drawing_State.zig"); const values = @import("values.zig"); const std = @import("std");
0
repos/zbox
repos/zbox/zbox/X_Ref_Cluster.zig
interface: Interface, pub fn left(self: *X_Ref_Cluster) X_Ref { return .{ .state = self.interface.state, ._x = &self.interface.span.begin, }; } pub fn center(self: *X_Ref_Cluster) X_Ref { return .{ .state = self.interface.state, ._x = &self.interface.span.mid, }; } pub fn right(self: *X_Ref_Cluster) X_Ref { return .{ .state = self.interface.state, ._x = &self.interface.span.end, }; } pub fn get(self: *X_Ref_Cluster, index: usize) X_Ref { return .{ .state = self.interface.state, ._x = self.interface.contents.items[index], }; } pub fn push(self: *X_Ref_Cluster) X_Ref { return .{ .state = self.interface.state, ._x = self.interface.push(), }; } pub fn debug(self: *X_Ref_Cluster, writer: anytype) !void { try writer.writeAll("X_Ref_Cluster: "); try self.interface.debug(writer); } const X_Ref_Cluster = @This(); const X_Ref = @import("X_Ref.zig"); const Interface = @import("Interface.zig"); const Drawing_State = @import("Drawing_State.zig"); const std = @import("std");
0
repos/zbox
repos/zbox/zbox/Separator_H.zig
state: *Drawing_State, class: []const u8 = "", _y: f64 = values.uninitialized, pub fn y(self: *Separator_H) Y_Ref { return .{ .state = self.state, ._y = &self._y, }; } pub fn label(self: *Separator_H, x: X_Ref, text: []const u8, options: Label.Options) *Separator_H { const style = &self.state.drawing.style; const options_mut = options; options_mut.angle = 0; options_mut._class1 = self.class; options_mut._class2 = "sep-label"; const item = self.state.create_label(text, options_mut); switch (options_mut.baseline) { .normal => self.state.constrain_offset(&item._y, &self._y, -style.separator_label_padding_y, "separator label y"), .middle => self.state.constrain_eql(&item._y, &self._y, "separator label y"), .hanging => self.state.constrain_offset(&item._y, &self._y, style.separator_label_padding_y, "separator label y"), } switch (options_mut.alignment) { .left => self.state.constrain_offset(&item._x, x._x, style.separator_label_padding_x, "separator label x"), .center => self.state.constrain_eql(&item._x, x._x, "separator label x"), .right => self.state.constrain_offset(&item._x, x._x, -style.separator_label_padding_x, "separator label x"), } return self; } const Separator_H = @This(); const X_Ref = @import("X_Ref.zig"); const Y_Ref = @import("Y_Ref.zig"); const Label = @import("Label.zig"); const Drawing_State = @import("Drawing_State.zig"); const values = @import("values.zig"); const std = @import("std");
0
repos/zbox
repos/zbox/zbox/Y_Ref_Cluster.zig
interface: Interface, pub fn top(self: *Y_Ref_Cluster) Y_Ref { return .{ .state = self.interface.state, ._y = &self.interface.span.begin, }; } pub fn middle(self: *Y_Ref_Cluster) Y_Ref { return .{ .state = self.interface.state, ._y = &self.interface.span.mid, }; } pub fn bottom(self: *Y_Ref_Cluster) Y_Ref { return .{ .state = self.interface.state, ._y = &self.interface.span.end, }; } pub fn get(self: *Y_Ref_Cluster, index: usize) Y_Ref { return .{ .state = self.interface.state, ._y = self.interface.contents.items[index], }; } pub fn push(self: *Y_Ref_Cluster) Y_Ref { return .{ .state = self.interface.state, ._y = self.interface.push(), }; } pub fn debug(self: *Y_Ref_Cluster, writer: anytype) !void { try writer.writeAll("Y_Ref_Cluster: "); try self.interface.debug(writer); } const Y_Ref_Cluster = @This(); const Y_Ref = @import("Y_Ref.zig"); const Interface = @import("Interface.zig"); const Drawing_State = @import("Drawing_State.zig"); const std = @import("std");
0
repos/zbox
repos/zbox/zbox/Label.zig
state: *Drawing_State, text: []const u8, options: Options, _x: f64 = values.uninitialized, _y: f64 = values.uninitialized, pub const Options = struct { class: []const u8 = "", _class1: []const u8 = "", // reserved _class2: []const u8 = "", // reserved alignment: Alignment = .left, baseline: Baseline = .normal, angle: f64 = 0, }; pub const Alignment = enum { left, center, right, }; pub const Baseline = enum { normal, middle, hanging, }; pub fn anchor_point(self: *Label) Point_Ref { return .{ .state = self.state, ._x = &self._x, ._y = &self._y, }; } pub fn add_missing_constraints(self: *Label) void { if (values.is_uninitialized(self._x)) { self._x = 0; } if (values.is_uninitialized(self._y)) { self._y = 0; } } pub fn debug(self: *Label, writer: anytype) !void { try writer.print("Label: {s} {s} {s} {s}\n", .{ self.class, @tagName(self.alignment), @tagName(self.baseline), self.text, }); try writer.print(" x: {d}\n", .{ self._x }); try writer.print(" y: {d}\n", .{ self._y }); } const Label = @This(); const Point_Ref = @import("Point_Ref.zig"); const Drawing_State = @import("Drawing_State.zig"); const values = @import("values.zig"); const std = @import("std");
0
repos/zbox
repos/zbox/zbox/X_Ref.zig
state: *Drawing_State, _x: *f64, mut: bool = true, pub fn anchor_at(self: X_Ref, abs_x: f64) X_Ref { if (!self.mut) { @panic("This x coordinate is not mutable"); } self.state.remove_constraint(self._x); self._x.* = abs_x; return self; } pub fn attach(self: X_Ref, other: X_Ref) X_Ref { _ = other.attach_to(self); return self; } pub fn attach_to(self: X_Ref, target: X_Ref) X_Ref { if (!self.mut) { @panic("This x coordinate is not mutable"); } self.state.constrain_eql(self._x, target._x, "X_Ref attach_to"); return self; } pub fn attach_to_offset(self: X_Ref, target: X_Ref, offset_x: f64) X_Ref { if (!self.mut) { @panic("This x coordinate is not mutable"); } self.state.constrain_offset(self._x, target._x, offset_x, "X_Ref attach_to_offset"); return self; } pub fn attach_between(self: X_Ref, a: X_Ref, b: X_Ref, f: f64) X_Ref { if (!self.mut) { @panic("This x coordinate is not mutable"); } self.state.constrain_lerp(self._x, a._x, b._x, f, "X_Ref attach_between"); return self; } pub fn intersection_with(self: X_Ref, y: Y_Ref) Point_Ref { std.debug.assert(self.state == y.state); return .{ .state = self.state, ._x = self._x, ._y = y._y, .mut_x = self.mut, .mut_y = y.mut, }; } // Note that this creates a new loose value representing the offset location pub fn offset(self: X_Ref, amount: f64) X_Ref { const x = self.state.create_value(values.uninitialized); self.state.constrain_offset(x, self._x, amount, "X_Ref offset"); return .{ .state = self.state, ._x = x, }; } pub fn wire(self: X_Ref, options: wires.Options) *Wire_H { const item = self.state.create_wire_h(options, null); self.state.constrain_eql(&item._x.begin, self._x, "wire begin x"); return item; } const X_Ref = @This(); const Y_Ref = @import("Y_Ref.zig"); const Point_Ref = @import("Point_Ref.zig"); const Wire_H = @import("Wire_H.zig"); const wires = @import("wires.zig"); const values = @import("values.zig"); const Drawing_State = @import("Drawing_State.zig"); const std = @import("std");
0
repos/zbox
repos/zbox/zbox/Wire_V.zig
state: *Drawing_State, options: wires.Options, next: ?*Wire_H = null, bit_mark_location: ?f64 = null, _x: f64 = values.uninitialized, _y: Span = .{}, pub fn x(self: *Wire_V) X_Ref { return .{ .state = self.state, ._x = &self._x, }; } pub fn origin(self: *Wire_V) Point_Ref { return .{ .state = self.state, ._x = &self._x, ._y = &self._y.begin, }; } pub fn midpoint(self: *Wire_V) Point_Ref { return .{ .state = self.state, ._x = &self._x, ._y = &self._y.mid, }; } pub fn endpoint(self: *Wire_V) Point_Ref { return .{ .state = self.state, ._x = &self._x, ._y = &self._y.end, }; } pub fn length(self: *Wire_V, len: f64) *Wire_V { self.state.remove_constraint(&self._y.delta); self._y.delta = len; return self; } pub fn match_length_of(self: *Wire_V, other: *const Wire_V) *Wire_V { self.state.constrain_eql(&self._y.delta, &other._y.delta, "wire match_length_of"); return self; } pub fn bit_mark(self: *Wire_V) *Wire_V { self.bit_mark_location = 0.5; return self; } pub fn bit_mark_at(self: *Wire_V, f: f64) *Wire_V { self.bit_mark_location = f; return self; } pub fn label(self: *Wire_V, text: []const u8, options: Label.Options) *Wire_V { const style = if (self.options.bits > 1) self.state.drawing.style.bus_style else self.state.drawing.style.wire_style; var options_mut = options; options_mut.angle = -90; options_mut._class1 = self.options.class; options_mut._class2 = if (self.options.bits > 1) "wire-label bus" else "wire-label"; const item = self.state.create_label(text, options_mut); if (options_mut.baseline == .middle) { self.state.constrain_eql(&item._x, &self._x, "wire label x"); switch (options_mut.alignment) { .left, .center => self.state.constrain_offset(&item._y, &self._y.min, style.label_padding_cap, "wire label y from min"), .right => self.state.constrain_offset(&item._y, &self._y.max, -style.label_padding_cap, "wire label y from max"), } } else { switch (options_mut.baseline) { .normal => self.state.constrain_offset(&item._x, &self._x, -style.label_padding_y, "wire label x"), .hanging => self.state.constrain_offset(&item._x, &self._x, style.label_padding_y, "wire label x"), .middle => unreachable, } switch (options_mut.alignment) { .left => self.state.constrain_offset(&item._y, &self._y.max, -style.label_padding_x, "wire label y from max"), .center => self.state.constrain_eql(&item._y, &self._y.mid, "wire label y from mid"), .right => self.state.constrain_offset(&item._y, &self._y.min, style.label_padding_x, "wire label y from min"), } } return self; } pub fn turn(self: *Wire_V) *Wire_H { if (self.next) |next| return next; return self.state.create_wire_h(self.options, self); } pub fn turn_at(self: *Wire_V, y: Y_Ref) *Wire_H { return self.end_at(y).turn(); } pub fn turn_at_offset(self: *Wire_V, y: Y_Ref, offset: f64) *Wire_H { return self.end_at_offset(y, offset).turn(); } pub fn turn_between(self: *Wire_V, y0: Y_Ref, y1: Y_Ref, f: f64) *Wire_H { self.state.constrain_lerp(&self._y.end, y0._y, y1._y, f, "wire turn_between"); return self.turn(); } pub fn turn_and_end_at(self: *Wire_V, end: Point_Ref) *Wire_H { return self.turn_at(end.y()).end_at(end.x()); } pub fn segment(self: *Wire_V) *Wire_V { const h_wire = self.turn(); self.state.constrain_eql(&h_wire._x.end, &self._x, "segment x"); return h_wire.turn(); } pub fn continue_at(self: *Wire_V, y: Y_Ref) *Wire_V { const h_wire = self.turn_at(y); self.state.constrain_eql(&h_wire._x.end, &self._x, "continue_at x"); return h_wire.turn(); } pub fn end_at(self: *Wire_V, y: Y_Ref) *Wire_V { self.state.constrain_eql(&self._y.end, y._y, "wire end_at"); return self; } pub fn end_at_offset(self: *Wire_V, y: Y_Ref, offset: f64) *Wire_V { self.state.constrain_offset(&self._y.end, y._y, offset, "wire end_at_offset"); return self; } pub fn end_at_point(self: *Wire_V, end: Point_Ref) *Wire_V { if (values.is_uninitialized(self._x)) { _ = self.end_at(end.y()); self.state.constrain_eql(&self._x, end._x, "wire end_at_point"); return self; } else { if (!self._y.is_end_constrained()) { self.state.constrain_midpoint(&self._y.end, &self._y.begin, end._y, "wire end_at_point midpoint"); } return self.turn().turn_and_end_at(end); } } pub fn end_at_mutable_point(self: *Wire_V, end: Point_Ref) *Wire_V { _ = self.end_at(end.y()); self.state.constrain_eql(end._x, &self._x, "wire end_at_mutable_point"); return self; } pub fn add_missing_constraints(self: *Wire_V) void { if (self.next) |next| { if (self._y.is_end_constrained()) { self.state.constrain_eql(&next._y, &self._y.end, "wire segment connection"); } else if (!values.is_uninitialized(next._y)) { self.state.constrain_eql(&self._y.end, &next._y, "wire segment connection"); } else { self.state.constrain_eql(&next._y, &self._y.end, "wire segment connection"); } if (values.is_uninitialized(self._x) and next._x.is_begin_constrained()) { self.state.constrain_eql(&self._x, &next._x.begin, "wire segment connection"); } else { self.state.constrain_eql(&next._x.begin, &self._x, "wire segment connection"); } next.add_missing_constraints(); } if (values.is_uninitialized(self._x)) { self._x = 0; } const style = if (self.options.bits > 1) self.state.drawing.style.bus_style else self.state.drawing.style.wire_style; self._y.add_missing_constraints(self.state, 0, style.default_length); } pub fn debug(self: *Wire_V, writer: anytype) @TypeOf(writer).Error!void { try writer.print("Wire_V: {?s}\n x: {d}\n y: ", .{ self.options.class, self._x, }); try self._y.debug(writer); if (self.next) |next| { try writer.writeAll(" -> "); try next.debug(writer); } } const Wire_V = @This(); const Wire_H = @import("Wire_H.zig"); const Point_Ref = @import("Point_Ref.zig"); const X_Ref = @import("X_Ref.zig"); const Y_Ref = @import("Y_Ref.zig"); const Span = @import("Span.zig"); const Label = @import("Label.zig"); const Drawing_State = @import("Drawing_State.zig"); const wires = @import("wires.zig"); const values = @import("values.zig"); const std = @import("std");
0
repos/zbox
repos/zbox/zbox/Span.zig
// Exactly two of the following should be initialized to fully constrain the span: begin: f64 = values.uninitialized, end: f64 = values.uninitialized, mid: f64 = values.uninitialized, delta: f64 = values.uninitialized, // usable as dependencies only! min: f64 = values.uninitialized, max: f64 = values.uninitialized, len: f64 = values.uninitialized, fn count_uninitialized(self: Span, include_delta: bool) u8 { const begin: u8 = @intFromBool(values.is_uninitialized(self.begin)); const end: u8 = @intFromBool(values.is_uninitialized(self.end)); const mid: u8 = @intFromBool(values.is_uninitialized(self.mid)); const delta: u8 = @intFromBool(include_delta and values.is_uninitialized(self.delta)); return begin + end + mid + delta; } pub fn is_position_constrained(self: Span) bool { return self.count_uninitialized(false) <= 2; } pub fn is_fully_constrained(self: Span) bool { return self.count_uninitialized(true) <= 2; } pub fn is_begin_constrained(self: Span) bool { return !values.is_uninitialized(self.begin) or self.is_fully_constrained(); } pub fn is_mid_constrained(self: Span) bool { return !values.is_uninitialized(self.mid) or self.is_fully_constrained(); } pub fn is_end_constrained(self: Span) bool { return !values.is_uninitialized(self.end) or self.is_fully_constrained(); } pub fn is_delta_constrained(self: Span) bool { return !values.is_uninitialized(self.delta) or self.is_fully_constrained(); } pub fn add_missing_constraints(self: *Span, state: *Drawing_State, mid: f64, delta: f64) void { if (!values.is_uninitialized(self.begin)) { if (!values.is_uninitialized(self.end)) { self.default_mid(state); self.default_delta(state); } else if (!values.is_uninitialized(self.mid)) { state.constrain_lerp(&self.end, &self.begin, &self.mid, 2, "span end from begin/mid"); self.default_delta(state); } else { if (values.is_uninitialized(self.delta)) self.delta = delta; state.constrain(&self.end, .{ .sum2 = .{ &self.begin, &self.delta }}, "span end from begin/delta"); self.default_mid(state); } } else if (!values.is_uninitialized(self.end)) { if (!values.is_uninitialized(self.mid)) { state.constrain_lerp(&self.begin, &self.end, &self.mid, 2, "span begin from end/mid"); self.default_delta(state); } else { if (values.is_uninitialized(self.delta)) self.delta = delta; state.constrain(&self.begin, .{ .difference = .{ &self.end, &self.delta }}, "span begin from end/delta"); self.default_mid(state); } } else { if (values.is_uninitialized(self.mid)) self.mid = mid; if (values.is_uninitialized(self.delta)) self.delta = delta; state.constrain_scaled_offset(&self.begin, &self.mid, &self.delta, -0.5, "span begin from mid/delta"); state.constrain_scaled_offset(&self.end, &self.mid, &self.delta, 0.5, "span end from mid/delta"); } state.constrain(&self.min, .{ .min2 = .{ &self.begin, &self.end }}, "span min from begin/end"); state.constrain(&self.max, .{ .max2 = .{ &self.begin, &self.end }}, "span max from begin/end"); state.constrain(&self.len, .{ .difference = .{ &self.max, &self.min }}, "span len from max/min"); } fn default_delta(self: *Span, state: *Drawing_State) void { state.constrain(&self.delta, .{ .difference = .{ &self.end, &self.begin }}, "default span delta"); } fn default_mid(self: *Span, state: *Drawing_State) void { state.constrain_midpoint(&self.mid, &self.begin, &self.end, "default span mid"); } pub fn debug(self: *Span, writer: anytype) !void { try writer.print("begin: {d} mid: {d} end: {d} delta: {d} min: {d} max: {d} len: {d}\n", .{ self.begin, self.mid, self.end, self.delta, self.min, self.max, self.len, }); } const Span = @This(); const Drawing_State = @import("Drawing_State.zig"); const values = @import("values.zig"); const std = @import("std");
0
repos/zbox
repos/zbox/zbox/wires.zig
pub const Arrow_Style = enum { none, forward, reverse, bidirectional, junction_begin, junction_end, junction_both, }; pub const Options = struct { bits: usize = 1, dir: Arrow_Style = .none, class: []const u8 = "", corner_radius: ?f64 = null, }; pub const Wire_Ref = union(enum) { H: *Wire_H, V: *Wire_V, pub fn initH(wire: *Wire_H) Wire_Ref { return .{ .H = wire }; } pub fn initV(wire: *Wire_V) Wire_Ref { return .{ .V = wire }; } pub fn options(self: Wire_Ref) Options { return switch (self) { .H => |w| w.options, .V => |w| w.options, }; } pub fn begin(self: Wire_Ref) Point_Ref { return switch (self) { .H => |w| .{ .state = w.state, ._x = &w._x.begin, ._y = &w._y, }, .V => |w| .{ .state = w.state, ._x = &w._x, ._y = &w._y.begin, }, }; } pub fn end(self: Wire_Ref) Point_Ref { return switch (self) { .H => |w| .{ .state = w.state, ._x = &w._x.end, ._y = &w._y, }, .V => |w| .{ .state = w.state, ._x = &w._x, ._y = &w._y.end, }, }; } pub fn bit_mark(self: Wire_Ref) ?f64 { return switch (self) { .H => |w| w.bit_mark_location, .V => |w| w.bit_mark_location, }; } }; pub const Iterator = struct { wire: ?Wire_Ref, pub fn next(self: *Iterator) ?Wire_Ref { if (self.wire) |wire| { self.wire = switch (wire) { .H => |w| if (w.next) |n| Wire_Ref.initV(n) else null, .V => |w| if (w.next) |n| Wire_Ref.initH(n) else null, }; return wire; } return null; } }; const Wire_H = @import("Wire_H.zig"); const Wire_V = @import("Wire_V.zig"); const Point_Ref = @import("Point_Ref.zig");
0
repos/zbox
repos/zbox/zbox/Drawing.zig
state: Drawing_State, style: Style = .{}, title: []const u8 = "", desc: []const u8 = "", view: Viewport = .{}, pub fn init(gpa: std.mem.Allocator) *Drawing { const self = gpa.create(Drawing) catch @panic("OOM"); self.* = .{ .state = .{ .drawing = self, .gpa = gpa, }}; return self; } pub fn deinit(self: *Drawing) void { const gpa = self.state.gpa; self.state.deinit(); gpa.destroy(self); } pub fn label(self: *Drawing, class: []const u8, alignment: Label.Alignment, baseline: Label.Baseline, text: []const u8) *Label { return self.state.create_label(text, class, alignment, baseline, 0); } pub fn label_v(self: *Drawing, class: []const u8, alignment: Label.Alignment, baseline: Label.Baseline, text: []const u8) *Label { return self.state.create_label(text, class, alignment, baseline, -90); } pub fn box(self: *Drawing, options: Box.Options) *Box { return self.state.create_box(options); } // TODO cubic beziers - "swoopWest/East/North/South" // ends with "endWestAt/EastAt/NorthAt/SouthAt(Point_Ref) // TODO Grouping rectangles // TODO Circles (for state diagrams) // TODO and gates // TODO or gates // TODO xor gates // TODO buffers/inverters // TODO transmission gates // TODO muxes & demuxes // TODO ALU blocks // TODO bus line driver blocks // TODO bus/wire swap block // TODO flowchart shapes // TODO memory layout/protocol diagrams // TODO simple tables // TODO railroad diagrams? pub fn separator_h(self: *Drawing) *Separator_H { return self.state.create_separator_h(); } pub fn separator_v(self: *Drawing) *Separator_V { return self.state.create_separator_v(); } pub fn columns(self: *Drawing) *X_Ref_Cluster { return self.state.create_x_ref_cluster(); } pub fn rows(self: *Drawing) *Y_Ref_Cluster { return self.state.create_y_ref_cluster(); } pub fn wire_h(self: *Drawing, options: wires.Options) *Wire_H { return self.state.create_wire_h(options, null); } pub fn wire_v(self: *Drawing, options: wires.Options) *Wire_V { return self.state.create_wire_v(options, null); } pub fn at(self: *Drawing, abs_x: f64, abs_y: f64) Point_Ref { return .{ .state = &self.state, ._x = self.state.create_value(abs_x), ._y = self.state.create_value(abs_y), .mut_x = false, .mut_y = false, }; } pub fn point(self: *Drawing) Point_Ref { return .{ .state = &self.state, ._x = self.state.create_value(values.uninitialized), ._y = self.state.create_value(values.uninitialized), }; } pub fn x(self: *Drawing, abs_x: f64) X_Ref { return .{ .state = &self.state, ._x = self.state.create_value(abs_x), .mut = false, }; } pub fn some_x(self: *Drawing) X_Ref { return .{ .state = &self.state, ._x = self.state.create_value(values.uninitialized), }; } pub fn between_x(self: *Drawing, a: X_Ref, b: X_Ref, f: f64) X_Ref { const item = self.state.create_value(values.uninitialized); self.state.constrain_lerp(item, a._x, b._x, f, "between_x"); return .{ .state = &self.state, ._x = item, .mut = false, }; } pub fn y(self: *Drawing, abs_y: f64) Y_Ref { return .{ .state = &self.state, ._y = self.state.create_value(abs_y), .mut = false, }; } pub fn some_y(self: *Drawing) Y_Ref { return .{ .state = &self.state, ._y = self.state.create_value(values.uninitialized), }; } pub fn between_y(self: *Drawing, a: Y_Ref, b: Y_Ref, f: f64) Y_Ref { const item = self.state.create_value(values.uninitialized); self.state.constrain_lerp(item, a._y, b._y, f, "between_y"); return .{ .state = &self.state, ._y = item, .mut = false, }; } pub fn render_svg(self: *Drawing, writer: anytype) !void { self.state.add_missing_constraints(); try self.state.resolve_constraints(); const computed_view = self.compute_viewport(); const view: Viewport = .{ .left = self.view.left orelse computed_view.left, .right = self.view.right orelse computed_view.right, .top = self.view.top orelse computed_view.top, .bottom = self.view.bottom orelse computed_view.bottom, }; try writer.print( \\<svg viewBox="{d} {d} {d} {d}" xmlns="http://www.w3.org/2000/svg"> \\ , .{ view.left orelse 0, view.top orelse 0, view.width(), view.height(), }); if (self.title.len > 0) { try writer.print( \\<title>{s}</title> \\ , .{ self.title }); } if (self.desc.len > 0) { try writer.print( \\<desc>{s}</desc> \\ , .{ self.desc }); } try writer.print( \\<style> \\{s} \\{s} \\</style> \\ , .{ self.style.base_css, self.style.extra_css }); for (self.state.separators_h.items) |s| { try writer.print( \\<line x1="{d}" y1="{d}" x2="{d}" y2="{d}" class="{s} sep"/> \\ , .{ view.left.?, s._y, view.right.?, s._y, s.class, }); } for (self.state.separators_v.items) |s| { try writer.print( \\<line x1="{d}" y1="{d}" x2="{d}" y2="{d}" class="{s} sep"/> \\ , .{ s._x, view.top.?, s._x, view.bottom.?, s.class, }); } for (self.state.wires_h.items) |w| { try self.render_svg_wire(wires.Wire_Ref.initH(w), writer); } for (self.state.wires_v.items) |w| { try self.render_svg_wire(wires.Wire_Ref.initV(w), writer); } for (self.state.boxes.items) |b| { try self.render_svg_box(b, writer); } for (self.state.labels.items) |l| { try render_svg_label(l._x, l._y, l.text, l.options, writer); } try writer.writeAll("</svg>"); } fn render_svg_box(self: *Drawing, b: *Box, writer: anytype) @TypeOf(writer).Error!void { switch (b.options.shape) { .mux => { const dy = b._x.len / 4; try writer.print( \\<path d="M {d} {d} V {d} L {d} {d} V {d} Z" class="box {s} {s}"/> \\ , .{ b._x.begin, // top left x b._y.begin - dy, // top left y b._y.end + dy, // bottom left y b._x.end, // bottom right x b._y.end - dy, // bottom right y b._y.begin + dy, // top right y @tagName(b.options.shape), b.options.class, }); }, .demux => { const dy = b._x.len / 4; try writer.print( \\<path d="M {d} {d} V {d} L {d} {d} V {d} Z" class="box {s} {s}"/> \\ , .{ b._x.begin, // top left x b._y.begin + dy, // top left y b._y.end - dy, // bottom left y b._x.end, // bottom right x b._y.end + dy, // bottom right y b._y.begin - dy, // top right y @tagName(b.options.shape), b.options.class, }); }, .block, .small => { try writer.print( \\<rect x="{d}" y="{d}" width="{d}" height="{d}" class="box {s} {s}"/> \\ , .{ b._x.min, b._y.min, b._x.len, b._y.len, @tagName(b.options.shape), b.options.class, }); }, } if (b.options.label.len > 0) { const n: f64 = @floatFromInt(std.mem.count(u8, b.options.label, "\n")); const tx = b._x.mid; var ty = b._y.mid - n * self.style.box_label_line_height / 2; var iter = std.mem.splitScalar(u8, b.options.label, '\n'); while (iter.next()) |line| { try render_svg_label(tx, ty, line, .{ .class = b.options.label_class, ._class1 = @tagName(b.options.shape), ._class2 = "box-label main", .alignment = .center, .baseline = .middle, }, writer); ty += self.style.box_label_line_height; } } } fn render_svg_label(lx: f64, ly: f64, text: []const u8, options: Label.Options, writer: anytype) @TypeOf(writer).Error!void { try writer.print( \\<text x="{d}" y="{d}" class="label _{s}{s} , .{ lx, ly, @tagName(options.baseline)[0..1], @tagName(options.alignment)[0..1], }); if (options.class.len > 0) try writer.print(" {s}", .{ options.class }); if (options._class1.len > 0) try writer.print(" {s}", .{ options._class1 }); if (options._class2.len > 0) try writer.print(" {s}", .{ options._class2 }); if (options.angle != 0) { try writer.print( \\" transform-origin="{d} {d}" transform="rotate({d})" , .{ lx, ly, options.angle, }); } else { try writer.writeByte('"'); } try writer.print( \\>{s}</text> \\ , .{ text }); } fn render_svg_wire(self: *Drawing, wire: wires.Wire_Ref, writer: anytype) @TypeOf(writer).Error!void { const options = wire.options(); const style = if (options.bits > 1) self.style.bus_style else self.style.wire_style; var draw_start_arrow = false; var draw_end_arrow = false; var draw_start_junction = false; var draw_end_junction = false; switch (options.dir) { .none => {}, .forward => draw_end_arrow = true, .junction_end => draw_end_junction = true, .reverse => draw_start_arrow = true, .junction_begin => draw_start_junction = true, .bidirectional => { draw_start_arrow = true; draw_end_arrow = true; }, .junction_both => { draw_start_junction = true; draw_end_junction = true; }, } switch (wire) { .H => |w| try writer.print("<path d=\"M {d} {d} H {d}", .{ w._x.begin, w._y, w._x.end }), .V => |w| try writer.print("<path d=\"M {d} {d} V {d}", .{ w._x, w._y.begin, w._y.end }), } var iter: wires.Iterator = .{ .wire = wire }; _ = iter.next(); // we already processed ourself var final_segment = wire; while (iter.next()) |segment| { final_segment = segment; switch (segment) { .H => |w| try writer.print(" H {d}", .{ w._x.end }), .V => |w| try writer.print(" V {d}", .{ w._y.end }), } } if (draw_end_arrow) { const begin = final_segment.begin(); const end = final_segment.end(); const dx = end._x.* - begin._x.*; const dy = end._y.* - begin._y.*; try render_svg_arrowhead_path(dx, dy, style, writer); } if (draw_start_arrow) { const begin = wire.begin(); const end = wire.end(); const dx = begin._x.* - end._x.*; const dy = begin._y.* - end._y.*; try writer.print(" M {d} {d}", .{ begin._x.*, begin._y.* }); try render_svg_arrowhead_path(dx, dy, style, writer); } try writer.writeAll("\" class=\"wire"); if (options.bits > 1) try writer.writeAll(" bus"); if (options.class.len > 0) try writer.print(" {s}", .{ options.class }); try writer.writeAll("\"/>\n"); iter = .{ .wire = wire }; while (iter.next()) |segment| { if (segment.bit_mark()) |f| { const begin = segment.begin(); const end = segment.end(); const cx = (1-f)*begin._x.* + f*end._x.*; const cy = (1-f)*begin._y.* + f*end._y.*; const x0 = cx - style.bit_mark_length / 2; const x1 = cx + style.bit_mark_length / 2; const y0 = cy + style.bit_mark_length / 2; const y1 = cy - style.bit_mark_length / 2; try writer.print( \\<line x1="{d}" y1="{d}" x2="{d}" y2="{d}" class="wire bitmark , .{ x0, y0, x1, y1 }); if (options.bits > 1) try writer.writeAll(" bus"); if (options.class.len > 0) try writer.print(" {s}", .{ options.class }); try writer.writeAll("\"/>\n"); var buf: [64]u8 = undefined; const text = try std.fmt.bufPrint(&buf, "{}", .{ options.bits }); switch (segment) { .H => try render_svg_label(cx, cy + style.bit_mark_label_offset_y, text, .{ .alignment = .center, .baseline = .hanging, .class = "bitmark-label", }, writer), .V => try render_svg_label(cx + style.bit_mark_label_offset_x, cy + style.bit_mark_label_offset_xy, text, .{ .alignment = .left, .baseline = .middle, .class = "bitmark-label", }, writer), } } } if (draw_start_junction) { const begin = wire.begin(); try writer.print( \\<circle cx="{d}" cy="{d}" r="{d}" class="wire junction , .{ begin._x.*, begin._y.*, style.junction_radius }); if (options.bits > 1) try writer.writeAll(" bus"); if (options.class.len > 0) try writer.print(" {s}", .{ options.class }); try writer.writeAll("\"/>\n"); } if (draw_end_junction) { const end = final_segment.end(); try writer.print( \\<circle cx="{d}" cy="{d}" r="{d}" class="wire junction , .{ end._x.*, end._y.*, style.junction_radius }); if (options.bits > 1) try writer.writeAll(" bus"); if (options.class.len > 0) try writer.print(" {s}", .{ options.class }); try writer.writeAll("\"/>\n"); } } fn render_svg_arrowhead_path(dx: f64, dy: f64, wire_style: Style.Wire_Style, writer: anytype) @TypeOf(writer).Error!void { var tangent_x: f64 = if (dx > 0) 1 else if (dx < 0) -1 else 0; var tangent_y: f64 = if (dy > 0) 1 else if (dy < 0) -1 else 0; var normal_x = tangent_y; var normal_y = -tangent_x; tangent_x *= wire_style.arrow_length; tangent_y *= wire_style.arrow_length; normal_x *= wire_style.arrow_width; normal_y *= wire_style.arrow_width; try writer.print( \\ m {d} {d} l {d} {d} l {d} {d} , .{ -tangent_x - normal_x, -tangent_y - normal_y, tangent_x + normal_x, tangent_y + normal_y, -tangent_x + normal_x, -tangent_y + normal_y, }); } fn compute_viewport(self: *Drawing) Viewport { var view: Viewport = .{}; for (self.state.wires_h.items) |h_wire| { var maybe_wire: ?*Wire_H = h_wire; while (maybe_wire) |w| { view.include_point(w._x.begin, w._y); view.include_point(w._x.end, w._y); if (w.next) |vw| { view.include_point(vw._x, vw._y.begin); view.include_point(vw._x, vw._y.end); maybe_wire = vw.next; } else { maybe_wire = null; } } } for (self.state.wires_v.items) |v_wire| { var maybe_wire: ?*Wire_V = v_wire; while (maybe_wire) |w| { view.include_point(w._x, w._y.begin); view.include_point(w._x, w._y.end); if (w.next) |hw| { view.include_point(hw._x.begin, hw._y); view.include_point(hw._x.end, hw._y); maybe_wire = hw.next; } else { maybe_wire = null; } } } for (self.state.boxes.items) |b| { view.include_point(b._x.begin, b._y.begin); view.include_point(b._x.end, b._y.end); } for (self.state.labels.items) |l| { view.include_point(l._x, l._y); } view.left = (view.left orelse 0) - self.style.drawing_padding_x; view.right = (view.right orelse 0) + self.style.drawing_padding_x; view.top = (view.top orelse 0) - self.style.drawing_padding_y; view.bottom = (view.bottom orelse 0) + self.style.drawing_padding_y; return view; } const Drawing = @This(); const Drawing_State = @import("Drawing_State.zig"); const Point_Ref = @import("Point_Ref.zig"); const X_Ref = @import("X_Ref.zig"); const Y_Ref = @import("Y_Ref.zig"); const X_Ref_Cluster = @import("X_Ref_Cluster.zig"); const Y_Ref_Cluster = @import("Y_Ref_Cluster.zig"); const Box = @import("Box.zig"); const Separator_H = @import("Separator_H.zig"); const Separator_V = @import("Separator_V.zig"); const wires = @import("wires.zig"); const Wire_H = @import("Wire_H.zig"); const Wire_V = @import("Wire_V.zig"); const Interface = @import("Interface.zig"); const Label = @import("Label.zig"); const Constraint = @import("Constraint.zig"); const Style = @import("Style.zig"); const Viewport = @import("Viewport.zig"); const values = @import("values.zig"); const std = @import("std");
0
repos/zbox
repos/zbox/zbox/default.css
svg { background: #394150; } text { display: block; white-space-collapse: preserve; text-wrap: nowrap; font-size: 14px; font-family: Iosevka Custom, Iosevka, Inconsolata, Consolas, monospace; fill: #E5E9F0; } text._nl { dominant-baseline: auto; text-anchor: start; } text._nc { dominant-baseline: auto; text-anchor: middle; } text._nr { dominant-baseline: auto; text-anchor: end; } text._ml { dominant-baseline: middle; text-anchor: start; } text._mc { dominant-baseline: middle; text-anchor: middle; } text._mr { dominant-baseline: middle; text-anchor: end; } text._hl { dominant-baseline: hanging; text-anchor: start; } text._hc { dominant-baseline: hanging; text-anchor: middle; } text._hr { dominant-baseline: hanging; text-anchor: end; } .box-label.main, .box-label.top, .box-label.bottom { font-size: 25px; } .box-label.interface.interface, text.small.small.small { font-size: 14px; } text.bitmark-label { stroke: none; fill: #E5E9F0; font-size: 9px; } .sep { stroke-width: 3; stroke: #262c38; } .sep-label { fill: #12161d; font-size: 18px; } .box { stroke-width: 2; stroke: #ECEFF4; fill: #4C566A; rx: 5; ry: 5; } .wire { stroke-width: 2; stroke: #A3BE8C; stroke-linecap: round; stroke-linejoin: round; fill: none; } .wire.junction { fill: #A3BE8C; stroke: none; } .wire.bus { stroke-width: 4; stroke: #5E81AC; stroke-linecap: round; stroke-linejoin: round; fill: none; } .wire.bus.junction { fill: #5E81AC; stroke: none; } .wire.wire.wire.bitmark { stroke-width: 1; }
0
repos/zbox
repos/zbox/zbox/Interface.zig
// TODO consider alternative names for this struct that are more descriptive state: *Drawing_State, contents: std.ArrayListUnmanaged(*f64) = .{}, spacing: f64 = values.uninitialized, span: Span = .{}, pub fn push(self: *Interface) *f64 { const item = self.state.create_value(values.uninitialized); self.contents.append(self.state.gpa, item) catch @panic("OOM"); return item; } pub fn flip(self: *Interface) void { const items = self.contents.items; for (0..items.len/2) |i| { const j = items.len - i - 1; const temp = items[i]; items[i] = items[j]; items[j] = temp; } } pub fn add_missing_constraints(self: *Interface) void { var spaces: usize = 0; for (self.contents.items) |item| { if (values.is_uninitialized(item.*)) { spaces += 1; } } if (spaces > 0) spaces -= 1; const spaces_f64: f64 = @floatFromInt(spaces); if (values.is_uninitialized(self.spacing)) { const divisor: f64 = if (spaces == 0) 1 else spaces_f64; self.state.constrain_scale(&self.spacing, &self.span.delta, 1 / divisor, "interface spacing from span delta"); } else { self.state.constrain_scale(&self.span.delta, &self.spacing, spaces_f64, "interface span delta from spacing"); // Ensure that delta won't be clobbered by add_missing_constraints below. if (!values.is_uninitialized(self.span.mid)) { self.span.begin = values.uninitialized; self.span.end = values.uninitialized; } else if (!values.is_uninitialized(self.span.begin)) { self.span.mid = values.uninitialized; self.span.end = values.uninitialized; } else if (!values.is_uninitialized(self.span.end)) { self.span.begin = values.uninitialized; self.span.mid = values.uninitialized; } } var i: f64 = 0; for (self.contents.items) |ptr| { if (values.is_uninitialized(ptr.*)) { self.state.constrain_scaled_offset(ptr, &self.span.begin, &self.spacing, i, "interface item from span begin/spacing"); i += 1; } } self.span.add_missing_constraints(self.state, 0, self.state.drawing.style.default_interface_spacing * spaces_f64); } pub fn debug(self: *Interface, writer: anytype) !void { try writer.print("n: {} spacing: {d}\n", .{ self.contents.items.len, self.spacing }); try writer.writeAll(" span: "); try self.span.debug(writer); } const Interface = @This(); const Span = @import("Span.zig"); const Drawing_State = @import("Drawing_State.zig"); const values = @import("values.zig"); const std = @import("std");
0
repos/zbox
repos/zbox/zbox/Wire_H.zig
state: *Drawing_State, options: wires.Options, bit_mark_location: ?f64 = null, next: ?*Wire_V = null, _y: f64 = values.uninitialized, _x: Span = .{}, pub fn y(self: *Wire_H) Y_Ref { return .{ .state = self.state, ._y = &self._y, }; } pub fn origin(self: *Wire_H) Point_Ref { return .{ .state = self.state, ._x = &self._x.begin, ._y = &self._y, }; } pub fn midpoint(self: *Wire_H) Point_Ref { return .{ .state = self.state, ._x = &self._x.mid, ._y = &self._y, }; } pub fn endpoint(self: *Wire_H) Point_Ref { return .{ .state = self.state, ._x = &self._x.end, ._y = &self._y, }; } pub fn length(self: *Wire_H, len: f64) *Wire_H { self.state.remove_constraint(&self._x.delta); self._x.delta = len; return self; } pub fn match_length_of(self: *Wire_H, other: *const Wire_H) *Wire_H { self.state.constrain_eql(&self._x.delta, &other._x.delta, "wire match_length_of"); return self; } pub fn bit_mark(self: *Wire_H) *Wire_H { self.bit_mark_location = 0.5; return self; } pub fn bit_mark_at(self: *Wire_H, f: f64) *Wire_H { self.bit_mark_location = f; return self; } pub fn label(self: *Wire_H, text: []const u8, options: Label.Options) *Wire_H { const style = if (self.options.bits > 1) self.state.drawing.style.bus_style else self.state.drawing.style.wire_style; var options_mut = options; options_mut.angle = 0; options_mut._class1 = self.options.class; options_mut._class2 = if (self.options.bits > 1) "wire-label bus" else "wire-label"; const item = self.state.create_label(text, options_mut); if (options_mut.baseline == .middle) { self.state.constrain_eql(&item._y, &self._y, "wire label y"); switch (options_mut.alignment) { .left, .center => self.state.constrain_offset(&item._x, &self._x.max, style.label_padding_cap, "wire label x from max"), .right => self.state.constrain_offset(&item._x, &self._x.min, -style.label_padding_cap, "wire label x from min"), } } else { switch (options_mut.baseline) { .normal => self.state.constrain_offset(&item._y, &self._y, -style.label_padding_y, "wire label y"), .hanging => self.state.constrain_offset(&item._y, &self._y, style.label_padding_y, "wire label y"), .middle => unreachable, } switch (options_mut.alignment) { .left => self.state.constrain_offset(&item._x, &self._x.min, style.label_padding_x, "wire label x from min"), .center => self.state.constrain_eql(&item._x, &self._x.mid, "wire label x from mid"), .right => self.state.constrain_offset(&item._x, &self._x.max, -style.label_padding_x, "wire label x from max"), } } return self; } pub fn turn(self: *Wire_H) *Wire_V { if (self.next) |next| return next; return self.state.create_wire_v(self.options, self); } pub fn turn_at(self: *Wire_H, x: X_Ref) *Wire_V { return self.end_at(x).turn(); } pub fn turn_at_offset(self: *Wire_H, x: X_Ref, offset: f64) *Wire_V { return self.end_at_offset(x, offset).turn(); } pub fn turn_between(self: *Wire_H, x0: X_Ref, x1: X_Ref, f: f64) *Wire_V { self.state.constrain_lerp(&self._x.end, x0._x, x1._x, f, "wire turn_between"); return self.turn(); } pub fn turn_and_end_at(self: *Wire_H, end: Point_Ref) *Wire_V { return self.turn_at(end.x()).end_at(end.y()); } pub fn segment(self: *Wire_H) *Wire_H { const v_wire = self.turn(); self.state.constrain_eql(&v_wire._y.end, &self._y, "segment y"); return v_wire.turn(); } pub fn continue_at(self: *Wire_H, x: X_Ref) *Wire_H { const v_wire = self.turn_at(x); self.state.constrain_eql(&v_wire._y.end, &self._y, "continue_at y"); return v_wire.turn(); } pub fn end_at(self: *Wire_H, x: X_Ref) *Wire_H { self.state.constrain_eql(&self._x.end, x._x, "wire end_at"); return self; } pub fn end_at_offset(self: *Wire_H, x: X_Ref, offset: f64) *Wire_H { self.state.constrain_offset(&self._x.end, x._x, offset, "wire end_at_offset"); return self; } pub fn end_at_point(self: *Wire_H, end: Point_Ref) *Wire_H { if (values.is_uninitialized(self._y)) { _ = self.end_at(end.x()); self.state.constrain_eql(&self._y, end._y, "wire end_at_point"); return self; } else { if (!self._x.is_end_constrained()) { self.state.constrain_midpoint(&self._x.end, &self._x.begin, end._x, "wire end_at_point midpoint"); } return self.turn().turn_and_end_at(end); } } pub fn end_at_mutable_point(self: *Wire_H, end: Point_Ref) *Wire_H { _ = self.end_at(end.x()); self.state.constrain_eql(end._y, &self._y, "wire end_at_mutable_point"); return self; } pub fn add_missing_constraints(self: *Wire_H) void { if (self.next) |next| { if (self._x.is_end_constrained()) { self.state.constrain_eql(&next._x, &self._x.end, "wire segment connection"); } else if (!values.is_uninitialized(next._x)) { self.state.constrain_eql(&self._x.end, &next._x, "wire segment connection"); } else { self.state.constrain_eql(&next._x, &self._x.end, "wire segment connection"); } if (values.is_uninitialized(self._y) and next._y.is_begin_constrained()) { self.state.constrain_eql(&self._y, &next._y.begin, "wire segment connection"); } else { self.state.constrain_eql(&next._y.begin, &self._y, "wire segment connection"); } next.add_missing_constraints(); } if (values.is_uninitialized(self._y)) { self._y = 0; } const style = if (self.options.bits > 1) self.state.drawing.style.bus_style else self.state.drawing.style.wire_style; self._x.add_missing_constraints(self.state, 0, style.default_length); } pub fn debug(self: *Wire_H, writer: anytype) @TypeOf(writer).Error!void { try writer.print("Wire_H: {?s}\n x: ", .{ self.options.class, }); try self._x.debug(writer); try writer.print(" y: {d}\n", .{ self._y, }); if (self.next) |next| { try writer.writeAll(" -> "); try next.debug(writer); } } const Wire_H = @This(); const Wire_V = @import("Wire_V.zig"); const Point_Ref = @import("Point_Ref.zig"); const X_Ref = @import("X_Ref.zig"); const Y_Ref = @import("Y_Ref.zig"); const Span = @import("Span.zig"); const Label = @import("Label.zig"); const Drawing_State = @import("Drawing_State.zig"); const wires = @import("wires.zig"); const values = @import("values.zig"); const std = @import("std");
0
repos/zbox
repos/zbox/zbox/Drawing_State.zig
drawing: *Drawing, gpa: std.mem.Allocator, arena: std.heap.ArenaAllocator = std.heap.ArenaAllocator.init(std.heap.page_allocator), constraints: ShallowAutoHashMapUnmanaged(*const f64, Constraint) = .{}, labels: std.ArrayListUnmanaged(*Label) = .{}, boxes: std.ArrayListUnmanaged(*Box) = .{}, // Note only the first segment of each wire is stored here; // iterate through the .next chains to find the other segments wires_h: std.ArrayListUnmanaged(*Wire_H) = .{}, wires_v: std.ArrayListUnmanaged(*Wire_V) = .{}, x_ref_clusters: std.ArrayListUnmanaged(*X_Ref_Cluster) = .{}, y_ref_clusters: std.ArrayListUnmanaged(*Y_Ref_Cluster) = .{}, separators_h: std.ArrayListUnmanaged(*Separator_H) = .{}, separators_v: std.ArrayListUnmanaged(*Separator_V) = .{}, loose_values: std.ArrayListUnmanaged(*f64) = .{}, // note this includes the interfaces inside X/Y_Ref_Clusters as well interfaces: std.ArrayListUnmanaged(*Interface) = .{}, pub fn deinit(self: *Drawing_State) void { for (self.interfaces.items) |interface| { interface.contents.deinit(self.gpa); } self.interfaces.deinit(self.gpa); self.loose_values.deinit(self.gpa); self.separators_h.deinit(self.gpa); self.separators_v.deinit(self.gpa); self.y_ref_clusters.deinit(self.gpa); self.x_ref_clusters.deinit(self.gpa); self.wires_v.deinit(self.gpa); self.wires_h.deinit(self.gpa); self.boxes.deinit(self.gpa); self.labels.deinit(self.gpa); self.constraints.deinit(self.gpa); self.arena.deinit(); } pub fn print(self: *Drawing_State, comptime fmt: []const u8, args: anytype) []const u8 { return std.fmt.allocPrint(self.arena.allocator(), fmt, args) catch @panic("OOM"); } pub fn create_value(self: *Drawing_State, initial_value: f64) *f64 { const arena = self.arena.allocator(); const item = arena.create(f64) catch @panic("OOM"); item.* = initial_value; self.loose_values.append(self.gpa, item) catch @panic("OOM"); return item; } pub fn create_label(self: *Drawing_State, text: []const u8, options: Label.Options) *Label { const arena = self.arena.allocator(); const item = arena.create(Label) catch @panic("OOM"); item.* = .{ .state = self, .text = text, .options = options, }; self.labels.append(self.gpa, item) catch @panic("OOM"); return item; } pub fn create_wire_h(self: *Drawing_State, options: wires.Options, previous: ?*Wire_V) *Wire_H { const arena = self.arena.allocator(); const item = arena.create(Wire_H) catch @panic("OOM"); item.* = .{ .state = self, .options = options, }; if (previous) |w| { w.next = item; } else { self.wires_h.append(self.gpa, item) catch @panic("OOM"); } return item; } pub fn create_wire_v(self: *Drawing_State, options: wires.Options, previous: ?*Wire_H) *Wire_V { const arena = self.arena.allocator(); const item = arena.create(Wire_V) catch @panic("OOM"); item.* = .{ .state = self, .options = options, }; if (previous) |w| { w.next = item; } else { self.wires_v.append(self.gpa, item) catch @panic("OOM"); } return item; } pub fn create_separator_h(self: *Drawing_State) *Separator_H { const arena = self.arena.allocator(); const item = arena.create(Separator_H) catch @panic("OOM"); item.* = .{ .state = self, }; self.separators_h.append(self.gpa, item) catch @panic("OOM"); return item; } pub fn create_separator_v(self: *Drawing_State) *Separator_V { const arena = self.arena.allocator(); const item = arena.create(Separator_V) catch @panic("OOM"); item.* = .{ .state = self, }; self.separators_v.append(self.gpa, item) catch @panic("OOM"); return item; } pub fn create_box(self: *Drawing_State, options: Box.Options) *Box { const arena = self.arena.allocator(); const item = arena.create(Box) catch @panic("OOM"); item.* = .{ .state = self, .options = options, }; self.boxes.append(self.gpa, item) catch @panic("OOM"); return item; } pub fn create_interface(self: *Drawing_State) *Interface { const arena = self.arena.allocator(); const item = arena.create(Interface) catch @panic("OOM"); item.* = .{ .state = self, }; self.interfaces.append(self.gpa, item) catch @panic("OOM"); return item; } pub fn create_x_ref_cluster(self: *Drawing_State) *X_Ref_Cluster { const arena = self.arena.allocator(); const item = arena.create(X_Ref_Cluster) catch @panic("OOM"); item.* = .{ .interface = .{ .state = self, }}; self.x_ref_clusters.append(self.gpa, item) catch @panic("OOM"); self.interfaces.append(self.gpa, &item.interface) catch @panic("OOM"); return item; } pub fn create_y_ref_cluster(self: *Drawing_State) *Y_Ref_Cluster { const arena = self.arena.allocator(); const item = arena.create(Y_Ref_Cluster) catch @panic("OOM"); item.* = .{ .interface = .{ .state = self, }}; self.y_ref_clusters.append(self.gpa, item) catch @panic("OOM"); self.interfaces.append(self.gpa, &item.interface) catch @panic("OOM"); return item; } pub fn add_missing_constraints(self: *Drawing_State) void { for (self.wires_h.items) |w| { w.add_missing_constraints(); } for (self.wires_v.items) |w| { w.add_missing_constraints(); } for (self.boxes.items) |b| { b.add_missing_constraints(); } for (self.labels.items) |l| { l.add_missing_constraints(); } for (self.x_ref_clusters.items) |c| { c.interface.add_missing_constraints(); } for (self.y_ref_clusters.items) |c| { c.interface.add_missing_constraints(); } for (self.separators_h.items) |sep| { if (values.is_uninitialized(sep._y)) { sep._y = 0; } } for (self.separators_v.items) |sep| { if (values.is_uninitialized(sep._x)) { sep._x = 0; } } for (self.loose_values.items) |v| { if (values.is_uninitialized(v.*)) { v.* = 0; } } } pub fn resolve_constraints(self: *Drawing_State) !void { var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); var a = arena.allocator(); var constraints = a.alloc(Constraint, self.constraints.size) catch @panic("OOM"); var i: usize = 0; var iter = self.constraints.valueIterator(); while (iter.next()) |ptr| { constraints[i] = ptr.*; i += 1; } std.debug.assert(i == constraints.len); try kahn.sort(a, constraints); for (constraints) |constraint| { std.debug.assert(values.is_constrained(constraint.dest.*)); constraint.dest.* = constraint.op.compute(); } } pub fn constrain(self: *Drawing_State, val: *f64, op: Constraint.Op, debug_text: []const u8) void { const new_op = op.clone(self.arena.allocator()); self.constraints.put(self.gpa, val, .{ .dest = val, .op = new_op, .debug = debug_text, }) catch @panic("OOM"); val.* = values.constrained; } pub fn constrain_eql(self: *Drawing_State, dest: *f64, src: *const f64, debug_text: []const u8) void { self.constrain(dest, .{ .copy = src }, debug_text); } pub fn constrain_offset(self: *Drawing_State, dest: *f64, src: *const f64, offset: f64, debug_text: []const u8) void { self.constrain(dest, .{ .offset_and_scale = .{ .src = src, .offset = offset, .scale = 1, }}, debug_text); } pub fn constrain_scaled_offset(self: *Drawing_State, dest: *f64, src: *const f64, offset: *const f64, offset_scale: f64, debug_text: []const u8) void { self.constrain(dest, .{ .scaled_offset = .{ .operands = .{ src, offset }, .k = offset_scale, }}, debug_text); } pub fn constrain_scale(self: *Drawing_State, dest: *f64, src: *const f64, scale: f64, debug_text: []const u8) void { self.constrain(dest, .{ .offset_and_scale = .{ .src = src, .offset = 0, .scale = scale, }}, debug_text); } pub fn constrain_midpoint(self: *Drawing_State, dest: *f64, v0: *const f64, v1: *const f64, debug_text: []const u8) void { self.constrain(dest, .{ .midpoint = .{ v0, v1 }}, debug_text); } pub fn constrain_lerp(self: *Drawing_State, dest: *f64, v0: *const f64, v1: *const f64, f: f64, debug_text: []const u8) void { self.constrain(dest, .{ .lerp = .{ .operands = .{ v0, v1 }, .k = f, }}, debug_text); } pub fn remove_constraint(self: *Drawing_State, val: *f64) void { _ = self.constraints.remove(val); } pub fn debug(self: *Drawing_State, writer: anytype) !void { for (self.x_ref_clusters.items) |c| { try c.debug(writer); } for (self.y_ref_clusters.items) |c| { try c.debug(writer); } for (self.wires_h.items) |w| { try w.debug(writer); } for (self.wires_v.items) |w| { try w.debug(writer); } for (self.boxes.items) |b| { try b.debug(writer); } for (self.labels.items) |l| { try l.debug(writer); } } const Drawing_State = @This(); const Drawing = @import("Drawing.zig"); const Point_Ref = @import("Point_Ref.zig"); const X_Ref = @import("X_Ref.zig"); const Y_Ref = @import("Y_Ref.zig"); const X_Ref_Cluster = @import("X_Ref_Cluster.zig"); const Y_Ref_Cluster = @import("Y_Ref_Cluster.zig"); const Box = @import("Box.zig"); const Separator_H = @import("Separator_H.zig"); const Separator_V = @import("Separator_V.zig"); const wires = @import("wires.zig"); const Wire_H = @import("Wire_H.zig"); const Wire_V = @import("Wire_V.zig"); const Interface = @import("Interface.zig"); const Label = @import("Label.zig"); const Constraint = @import("Constraint.zig"); const ShallowAutoHashMapUnmanaged = @import("deep_hash_map").ShallowAutoHashMapUnmanaged; const kahn = @import("kahn.zig"); const values = @import("values.zig"); const std = @import("std");
0
repos/zbox
repos/zbox/zbox/Constraint.zig
dest: *f64, op: Op, debug: []const u8, pub const Op = union(enum) { copy: *const f64, offset_and_scale: One_Operand_Scale_Offset, scale_and_offset: One_Operand_Scale_Offset, scaled_difference: Two_Operand_Coefficient, scaled_offset: Two_Operand_Coefficient, lerp: Two_Operand_Coefficient, difference: [2]*const f64, midpoint: [2]*const f64, sum2: [2]*const f64, min2: [2]*const f64, max2: [2]*const f64, sum: []*const f64, product: []*const f64, mean: []*const f64, min: []*const f64, max: []*const f64, pub fn clone(self: Op, allocator: std.mem.Allocator) Op { switch (self) { .copy, .offset_and_scale, .scale_and_offset, .scaled_difference, .scaled_offset, .lerp, .difference, .midpoint, .sum2, .min2, .max2 => return self, .sum => |ptrs| return .{ .sum = allocator.dupe(*const f64, ptrs) catch @panic("OOM") }, .product => |ptrs| return .{ .product = allocator.dupe(*const f64, ptrs) catch @panic("OOM") }, .mean => |ptrs| return .{ .mean = allocator.dupe(*const f64, ptrs) catch @panic("OOM") }, .min => |ptrs| return .{ .min = allocator.dupe(*const f64, ptrs) catch @panic("OOM") }, .max => |ptrs| return .{ .max = allocator.dupe(*const f64, ptrs) catch @panic("OOM") }, } } pub fn deps(self: *const Op) []const *const f64 { return switch (self.*) { .copy => |*ptr| values.ptr_to_slice(ptr), .offset_and_scale, .scale_and_offset => |*info| values.ptr_to_slice(&info.src), .scaled_difference, .scaled_offset, .lerp => |*info| &info.operands, .difference, .midpoint, .sum2, .min2, .max2 => |*operands| operands, .sum, .product, .mean, .min, .max => |ptrs| ptrs, }; } pub fn compute(self: Op) f64 { switch (self) { .copy => |ptr| { const v: f64 = ptr.*; std.debug.assert(!std.math.isNan(v)); return v; }, .offset_and_scale => |info| { const src = info.src.*; std.debug.assert(!std.math.isNan(src)); return (src + info.offset) * info.scale; }, .scale_and_offset => |info| { const src = info.src.*; std.debug.assert(!std.math.isNan(src)); return src * info.scale + info.offset; }, .scaled_difference => |info| { const minuend = info.operands[0].*; const subtrahend = info.operands[1].*; std.debug.assert(!std.math.isNan(minuend)); std.debug.assert(!std.math.isNan(subtrahend)); return (minuend - subtrahend) * info.k; }, .scaled_offset => |info| { const base = info.operands[0].*; const offset = info.operands[1].*; std.debug.assert(!std.math.isNan(base)); std.debug.assert(!std.math.isNan(offset)); return base + offset * info.k; }, .lerp => |info| { const a = info.operands[0].*; const b = info.operands[1].*; std.debug.assert(!std.math.isNan(a)); std.debug.assert(!std.math.isNan(b)); const fb = info.k; const fa = 1 - fb; return a * fa + b * fb; }, .difference => |operands| { const a: f64 = operands[0].*; const b: f64 = operands[1].*; std.debug.assert(!std.math.isNan(a)); std.debug.assert(!std.math.isNan(b)); return a - b; }, .midpoint => |operands| { const a: f64 = operands[0].*; const b: f64 = operands[1].*; std.debug.assert(!std.math.isNan(a)); std.debug.assert(!std.math.isNan(b)); return (a + b) / 2; }, .sum2 => |operands| { const a: f64 = operands[0].*; const b: f64 = operands[1].*; std.debug.assert(!std.math.isNan(a)); std.debug.assert(!std.math.isNan(b)); return a + b; }, .min2 => |operands| { const a: f64 = operands[0].*; const b: f64 = operands[1].*; std.debug.assert(!std.math.isNan(a)); std.debug.assert(!std.math.isNan(b)); return @min(a, b); }, .max2 => |operands| { const a: f64 = operands[0].*; const b: f64 = operands[1].*; std.debug.assert(!std.math.isNan(a)); std.debug.assert(!std.math.isNan(b)); return @max(a, b); }, .sum => |ptrs| { var a: f64 = 0; for (ptrs) |ptr| { const src = ptr.*; std.debug.assert(!std.math.isNan(src)); a += src; } return a; }, .product => |ptrs| { var a: f64 = 0; for (ptrs) |ptr| { const src = ptr.*; std.debug.assert(!std.math.isNan(src)); a *= src; } return a; }, .mean => |ptrs| { var a: f64 = 0; for (ptrs) |ptr| { const src = ptr.*; std.debug.assert(!std.math.isNan(src)); a += src; } a /= @floatFromInt(ptrs.len); return a; }, .min => |ptrs| { var m: f64 = ptrs[0].*; for (ptrs[1..]) |ptr| { const src = ptr.*; std.debug.assert(!std.math.isNan(src)); if (src < m) { m = src; } } return m; }, .max => |ptrs| { var m: f64 = ptrs[0].*; for (ptrs[1..]) |ptr| { const src = ptr.*; std.debug.assert(!std.math.isNan(src)); if (src > m) { m = src; } } return m; }, } } }; pub const One_Operand_Scale_Offset = struct { src: *const f64, offset: f64, scale: f64, }; pub const Two_Operand_Coefficient = struct { operands: [2]*const f64, k: f64, }; const values = @import("values.zig"); const std = @import("std");