Unnamed: 0
int64
0
0
repo_id
stringlengths
5
186
file_path
stringlengths
15
223
content
stringlengths
1
32.8M
0
repos/asio
repos/asio/asio/boostify.pl
#!/usr/bin/perl -w use strict; use File::Path; our $boost_dir = "boostified"; our $bad_lines = 0; sub print_line { my ($output, $line, $from, $lineno) = @_; # Warn if the resulting line is >80 characters wide. if (length($line) > 80) { if ($from =~ /\.[chi]pp$/) { ++$bad_lines; print("Warning: $from:$lineno: output >80 characters wide.\n"); } } # Write the output. print($output $line . "\n"); } sub source_contains_asio_thread_usage { my ($from) = @_; # Open the input file. open(my $input, "<$from") or die("Can't open $from for reading"); # Check file for use of asio::thread. while (my $line = <$input>) { chomp($line); if ($line =~ /asio::thread/) { close($input); return 1; } elsif ($line =~ /^ *thread /) { close($input); return 1; } } close($input); return 0; } sub source_contains_asio_include { my ($from) = @_; # Open the input file. open(my $input, "<$from") or die("Can't open $from for reading"); # Check file for inclusion of asio.hpp. while (my $line = <$input>) { chomp($line); if ($line =~ /# *include [<"]asio\.hpp[>"]/) { close($input); return 1; } } close($input); return 0; } sub copy_source_file { my ($from, $to) = @_; # Ensure the output directory exists. my $dir = $to; $dir =~ s/[^\/]*$//; mkpath($dir); # First determine whether the file makes any use of asio::thread. my $uses_asio_thread = source_contains_asio_thread_usage($from); my $includes_asio = source_contains_asio_include($from); my $is_asio_hpp = 0; $is_asio_hpp = 1 if ($from =~ /asio\.hpp/); my $needs_doc_link = 0; $needs_doc_link = 1 if ($is_asio_hpp); my $is_error_hpp = 0; $is_error_hpp = 1 if ($from =~ /asio\/error\.hpp/); my $is_qbk = 0; $is_qbk = 1 if ($from =~ /.qbk$/); my $is_xsl = 0; $is_xsl = 1 if ($from =~ /.xsl$/); my $is_quickref = 0; $is_quickref = 1 if ($from =~ /quickref.xml$/); my $is_test = 0; $is_test = 1 if ($from =~ /tests\/unit/); my $is_coroutine_related = 0; $is_coroutine_related = 1 if ($from =~ /await/ || $from =~ /partial_promise/ || $from =~ /co_composed/); my $is_hash_related = 0; $is_hash_related = 1 if ($from =~ /ip\/address/ || $from =~ /ip\/basic_endpoint/); # Open the files. open(my $input, "<$from") or die("Can't open $from for reading"); open(my $output, ">$to") or die("Can't open $to for writing"); # Copy the content. my $lineno = 1; while (my $line = <$input>) { chomp($line); # Unconditional replacements. $line =~ s/[\\@]ref boost_bind/boost::bind()/g; if ($from =~ /.*\.txt$/) { $line =~ s/[\\@]ref async_read/boost::asio::async_read()/g; $line =~ s/[\\@]ref async_write/boost::asio::async_write()/g; } if ($line =~ /asio_detail_posix_thread_function/) { $line =~ s/asio_detail_posix_thread_function/boost_asio_detail_posix_thread_function/g; } if ($line =~ /asio_signal_handler/) { $line =~ s/asio_signal_handler/boost_asio_signal_handler/g; } if ($line =~ /ASIO_/ && !($line =~ /BOOST_ASIO_/)) { $line =~ s/ASIO_/BOOST_ASIO_/g; } # Extra replacements for quickbook, XSL and quickref.xml source only. if ($is_qbk || $is_xsl || $is_quickref) { $line =~ s/asio\.examples/boost_asio.examples/g; $line =~ s/asio\.history/boost_asio.history/g; $line =~ s/asio\.index/boost_asio.index/g; $line =~ s/asio\.net_ts/boost_asio.net_ts/g; $line =~ s/asio\.std_executors/boost_asio.std_executors/g; $line =~ s/asio\.overview/boost_asio.overview/g; $line =~ s/asio\.reference/boost_asio.reference/g; $line =~ s/asio\.tutorial/boost_asio.tutorial/g; $line =~ s/asio\.using/boost_asio.using/g; $line =~ s/Asio/Boost.Asio/g; $line =~ s/changes made in each release/changes made in each Boost release/g; $line =~ s/\[\$/[\$boost_asio\//g; $line =~ s/\[@\.\.\/src\/examples/[\@boost_asio\/example/g; $line =~ s/asio\//boost\/asio\//g if $is_xsl; $line =~ s/include\/asio/boost\/asio/g; $line =~ s/\^asio/^boost\/asio/g; $line =~ s/namespaceasio/namespaceboost_1_1asio/g; $line =~ s/ \(\[\@examples\/diffs.*$//; $line =~ s/boost\/tools\/boostbook/tools\/boostbook/g; } # Conditional replacements. if ($line =~ /^( *)namespace asio \{/) { if ($is_qbk) { print_line($output, $1 . "namespace boost { namespace asio {", $from, $lineno); } else { print_line($output, $1 . "namespace boost {", $from, $lineno); print_line($output, $line, $from, $lineno); } } elsif ($line =~ /^( *)} \/\/ namespace asio$/) { if ($is_qbk) { print_line($output, $1 . "} } // namespace boost::asio", $from, $lineno); } else { print_line($output, $line, $from, $lineno); print_line($output, $1 . "} // namespace boost", $from, $lineno); } } elsif ($line =~ /^(# *include )[<"](asio\.hpp)[>"]$/) { print_line($output, $1 . "<boost/" . $2 . ">", $from, $lineno); if ($uses_asio_thread) { print_line($output, $1 . "<boost/thread/thread.hpp>", $from, $lineno) if (!$is_test); $uses_asio_thread = 0; } } elsif ($line =~ /^(# *include )[<"]boost\/.*[>"].*$/) { if (!$includes_asio && $uses_asio_thread) { print_line($output, $1 . "<boost/thread/thread.hpp>", $from, $lineno) if (!$is_test); $uses_asio_thread = 0; } print_line($output, $line, $from, $lineno); } elsif ($line =~ /^(# *include )[<"]asio\/thread\.hpp[>"]/) { if ($is_test) { print_line($output, $1 . "<boost/asio/detail/thread.hpp>", $from, $lineno); } else { # Line is removed. } } elsif ($line =~ /(# *include )[<"]asio\/error_code\.hpp[>"]/) { if ($is_asio_hpp) { # Line is removed. } else { print_line($output, $1 . "<boost/cerrno.hpp>", $from, $lineno) if ($is_error_hpp); print_line($output, $1 . "<boost/system/error_code.hpp>", $from, $lineno); } } elsif ($line =~ /# *include [<"]asio\/impl\/error_code\.[hi]pp[>"]/) { # Line is removed. } elsif ($line =~ /(# *include )[<"]asio\/system_error\.hpp[>"]/) { if ($is_asio_hpp) { # Line is removed. } else { print_line($output, $1 . "<boost/system/system_error.hpp>", $from, $lineno); } } elsif ($line =~ /(^.*# *include )[<"](asio\/[^>"]*)[>"](.*)$/) { print_line($output, $1 . "<boost/" . $2 . ">" . $3, $from, $lineno); } elsif ($line =~ /#.*defined\(.*ASIO_HAS_STD_SYSTEM_ERROR\)$/) { # Line is removed. } elsif ($line =~ /asio::thread\b/) { if ($is_test) { $line =~ s/asio::thread/asio::detail::thread/g; } else { $line =~ s/asio::thread/boost::thread/g; } if (!($line =~ /boost::asio::/)) { $line =~ s/asio::/boost::asio::/g; } print_line($output, $line, $from, $lineno); } elsif ($line =~ /^( *)thread( .*)$/ && !$is_qbk) { if ($is_test) { print_line($output, $1 . "boost::asio::detail::thread" . $2, $from, $lineno); } else { print_line($output, $1 . "boost::thread" . $2, $from, $lineno); } } elsif ($line =~ /namespace std \{ *$/ && !$is_coroutine_related && !$is_hash_related) { print_line($output, "namespace boost {", $from, $lineno); print_line($output, "namespace system {", $from, $lineno); } elsif ($line =~ /std::error_code/) { $line =~ s/std::error_code/boost::system::error_code/g; $line =~ s/asio::/boost::asio::/g if !$is_xsl; print_line($output, $line, $from, $lineno); } elsif ($line =~ /std::system_error/) { $line =~ s/std::system_error/boost::system::system_error/g; $line =~ s/asio::/boost::asio::/g if !$is_xsl; print_line($output, $line, $from, $lineno); } elsif ($line =~ /ec\.assign\(0, ec\.category\(\)\)/) { $line =~ s/ec\.assign\(0, ec\.category\(\)\)/ec = boost::system::error_code()/g; print_line($output, $line, $from, $lineno); } elsif ($line =~ /^} \/\/ namespace std/ && !$is_coroutine_related && !$is_hash_related) { print_line($output, "} // namespace system", $from, $lineno); print_line($output, "} // namespace boost", $from, $lineno); } elsif ($line =~ /asio::/ && !($line =~ /boost::asio::/)) { $line =~ s/asio::error_code/boost::system::error_code/g; $line =~ s/asio::error_category/boost::system::error_category/g; $line =~ s/asio::system_category/boost::system::system_category/g; $line =~ s/asio::system_error/boost::system::system_error/g; $line =~ s/asio::/boost::asio::/g if !$is_xsl; print_line($output, $line, $from, $lineno); } elsif ($line =~ /using namespace asio/) { $line =~ s/using namespace asio/using namespace boost::asio/g; print_line($output, $line, $from, $lineno); } elsif ($line =~ /asio_handler_alloc_helpers/) { $line =~ s/asio_handler_alloc_helpers/boost_asio_handler_alloc_helpers/g; print_line($output, $line, $from, $lineno); } elsif ($line =~ /asio_handler_cont_helpers/) { $line =~ s/asio_handler_cont_helpers/boost_asio_handler_cont_helpers/g; print_line($output, $line, $from, $lineno); } elsif ($line =~ /asio_handler_invoke_helpers/) { $line =~ s/asio_handler_invoke_helpers/boost_asio_handler_invoke_helpers/g; print_line($output, $line, $from, $lineno); } elsif ($line =~ /asio_(prefer|query|require|require_concept)_fn/) { $line =~ s/asio_(prefer|query|require|require_concept)_fn/boost_asio_$1_fn/g; print_line($output, $line, $from, $lineno); } elsif ($line =~ /asio_execution_/ && !($line =~ /_is_unspecialised/)) { $line =~ s/asio_execution_/boost_asio_execution_/g; print_line($output, $line, $from, $lineno); } elsif ($line =~ /[\\@]ref boost_bind/) { $line =~ s/[\\@]ref boost_bind/boost::bind()/g; print_line($output, $line, $from, $lineno); } elsif ($line =~ /( *)\[category template\]/) { print_line($output, $1 . "[authors [Kohlhoff, Christopher]]", $from, $lineno); print_line($output, $line, $from, $lineno); } elsif ($line =~ /boostify: non-boost docs start here/) { while ($line = <$input>) { last if $line =~ /boostify: non-boost docs end here/; } } elsif ($line =~ /boostify: non-boost code starts here/) { while ($line = <$input>) { last if $line =~ /boostify: non-boost code ends here/; } } elsif ($line =~ /^$/ && $needs_doc_link) { $needs_doc_link = 0; print_line($output, "// See www.boost.org/libs/asio for documentation.", $from, $lineno); print_line($output, "//", $from, $lineno); print_line($output, $line, $from, $lineno); } elsif ($is_quickref) { if ($line =~ /asio\.reference\.error_code">/) { # Line is removed. } elsif ($line =~ /asio\.reference\.system_error">/) { # Line is removed. } elsif ($line =~ /asio\.reference\.thread">/) { # Line is removed. } else { print_line($output, $line, $from, $lineno); } } else { print_line($output, $line, $from, $lineno); } ++$lineno; } # Ok, we're done. close($input); close($output); } sub copy_include_files { my @dirs = ( "include", "include/asio", "include/asio/detail", "include/asio/detail/impl", "include/asio/execution", "include/asio/execution/detail", "include/asio/execution/impl", "include/asio/experimental", "include/asio/experimental/detail", "include/asio/experimental/detail/impl", "include/asio/experimental/impl", "include/asio/generic", "include/asio/generic/detail", "include/asio/generic/detail/impl", "include/asio/impl", "include/asio/ip", "include/asio/ip/impl", "include/asio/ip/detail", "include/asio/ip/detail/impl", "include/asio/local", "include/asio/local/detail", "include/asio/local/detail/impl", "include/asio/posix", "include/asio/ssl", "include/asio/ssl/detail", "include/asio/ssl/detail/impl", "include/asio/ssl/impl", "include/asio/ssl/old", "include/asio/ssl/old/detail", "include/asio/traits", "include/asio/ts", "include/asio/windows"); foreach my $dir (@dirs) { our $boost_dir; my @files = ( glob("$dir/*.hpp"), glob("$dir/*.ipp") ); foreach my $file (@files) { if ($file ne "include/asio/thread.hpp" and $file ne "include/asio/error_code.hpp" and $file ne "include/asio/system_error.hpp" and $file ne "include/asio/impl/error_code.hpp" and $file ne "include/asio/impl/error_code.ipp") { my $from = $file; my $to = $file; $to =~ s/^include\//$boost_dir\/libs\/asio\/include\/boost\//; copy_source_file($from, $to); } } } } sub create_lib_directory { my @dirs = ( "doc", "example", "test"); our $boost_dir; foreach my $dir (@dirs) { mkpath("$boost_dir/libs/asio/$dir"); } } sub copy_unit_tests { my @dirs = ( "src/tests/unit", "src/tests/unit/archetypes", "src/tests/unit/execution", "src/tests/unit/experimental", "src/tests/unit/experimental/coro", "src/tests/unit/generic", "src/tests/unit/ip", "src/tests/unit/local", "src/tests/unit/posix", "src/tests/unit/ssl", "src/tests/unit/ts", "src/tests/unit/windows"); our $boost_dir; foreach my $dir (@dirs) { my @files = ( glob("$dir/*.*pp"), glob("$dir/Jamfile*") ); foreach my $file (@files) { if ($file ne "src/tests/unit/thread.cpp" and $file ne "src/tests/unit/error_handler.cpp" and $file ne "src/tests/unit/unit_test.cpp") { my $from = $file; my $to = $file; $to =~ s/^src\/tests\/unit\//$boost_dir\/libs\/asio\/test\//; copy_source_file($from, $to); } } } } sub copy_latency_tests { my @dirs = ( "src/tests/latency"); our $boost_dir; foreach my $dir (@dirs) { my @files = ( glob("$dir/*.*pp"), glob("$dir/Jamfile*") ); foreach my $file (@files) { my $from = $file; my $to = $file; $to =~ s/^src\/tests\/latency\//$boost_dir\/libs\/asio\/test\/latency\//; copy_source_file($from, $to); } } } sub copy_properties_tests { my @dirs = ( "src/tests/properties/cpp03", "src/tests/properties/cpp11", "src/tests/properties/cpp14"); our $boost_dir; foreach my $dir (@dirs) { my @files = ( glob("$dir/*.*pp"), glob("$dir/Jamfile*") ); foreach my $file (@files) { my $from = $file; my $to = $file; $to =~ s/^src\/tests\/properties\//$boost_dir\/libs\/asio\/test\/properties\//; copy_source_file($from, $to); } } } sub copy_examples { my @dirs = ( "src/examples/cpp11/allocation", "src/examples/cpp11/buffers", "src/examples/cpp11/chat", "src/examples/cpp11/deferred", "src/examples/cpp11/echo", "src/examples/cpp11/executors", "src/examples/cpp11/files", "src/examples/cpp11/fork", "src/examples/cpp11/futures", "src/examples/cpp11/handler_tracking", "src/examples/cpp11/http/client", "src/examples/cpp11/http/doc_root", "src/examples/cpp11/http/server", "src/examples/cpp11/http/server2", "src/examples/cpp11/http/server3", "src/examples/cpp11/http/server4", "src/examples/cpp11/icmp", "src/examples/cpp11/invocation", "src/examples/cpp11/iostreams", "src/examples/cpp11/local", "src/examples/cpp11/multicast", "src/examples/cpp11/nonblocking", "src/examples/cpp11/operations", "src/examples/cpp11/parallel_group", "src/examples/cpp11/porthopper", "src/examples/cpp11/serialization", "src/examples/cpp11/services", "src/examples/cpp11/socks4", "src/examples/cpp11/spawn", "src/examples/cpp11/ssl", "src/examples/cpp11/timeouts", "src/examples/cpp11/timers", "src/examples/cpp11/tutorial", "src/examples/cpp11/tutorial/daytime1", "src/examples/cpp11/tutorial/daytime2", "src/examples/cpp11/tutorial/daytime3", "src/examples/cpp11/tutorial/daytime4", "src/examples/cpp11/tutorial/daytime5", "src/examples/cpp11/tutorial/daytime6", "src/examples/cpp11/tutorial/daytime7", "src/examples/cpp11/tutorial/timer1", "src/examples/cpp11/tutorial/timer2", "src/examples/cpp11/tutorial/timer3", "src/examples/cpp11/tutorial/timer4", "src/examples/cpp11/tutorial/timer5", "src/examples/cpp11/type_erasure", "src/examples/cpp11/windows", "src/examples/cpp14/deferred", "src/examples/cpp14/echo", "src/examples/cpp14/executors", "src/examples/cpp14/iostreams", "src/examples/cpp14/operations", "src/examples/cpp14/parallel_group", "src/examples/cpp17/coroutines_ts", "src/examples/cpp20/channels", "src/examples/cpp20/coroutines", "src/examples/cpp20/invocation", "src/examples/cpp20/operations", "src/examples/cpp20/type_erasure"); our $boost_dir; foreach my $dir (@dirs) { my @files = ( glob("$dir/*.*pp"), glob("$dir/*.html"), glob("$dir/Jamfile*"), glob("$dir/*.pem"), glob("$dir/README*"), glob("$dir/*.txt")); foreach my $file (@files) { my $from = $file; my $to = $file; $to =~ s/^src\/examples\//$boost_dir\/libs\/asio\/example\//; copy_source_file($from, $to); } } } sub copy_doc { our $boost_dir; my @files = ( "src/doc/asio.qbk", "src/doc/examples.qbk", "src/doc/net_ts.qbk", "src/doc/overview.qbk", "src/doc/quickref.xml", "src/doc/reference.xsl", "src/doc/std_executors.qbk", "src/doc/tutorial.xsl", glob("src/doc/overview/*.qbk"), glob("src/doc/overview/model/*.qbk"), glob("src/doc/requirements/*.qbk")); foreach my $file (@files) { my $from = $file; my $to = $file; $to =~ s/^src\/doc\//$boost_dir\/libs\/asio\/doc\//; copy_source_file($from, $to); } } sub copy_tools { our $boost_dir; my @files = ( glob("src/tools/*.pl")); foreach my $file (@files) { my $from = $file; my $to = $file; $to =~ s/^src\/tools\//$boost_dir\/libs\/asio\/tools\//; copy_source_file($from, $to); } } my $includes_only = 0; if (scalar(@ARGV) == 1 && $ARGV[0] eq "--includes-only") { $includes_only = 1; } copy_include_files(); if (not $includes_only) { create_lib_directory(); copy_unit_tests(); copy_latency_tests(); copy_properties_tests(); copy_examples(); copy_doc(); copy_tools(); } exit($bad_lines > 0 ? 1 : 0);
0
repos/asio/asio
repos/asio/asio/include/asio.hpp
// // asio.hpp // ~~~~~~~~ // // 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) // #ifndef ASIO_HPP #define ASIO_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/any_completion_executor.hpp" #include "asio/any_completion_handler.hpp" #include "asio/any_io_executor.hpp" #include "asio/append.hpp" #include "asio/as_tuple.hpp" #include "asio/associated_allocator.hpp" #include "asio/associated_cancellation_slot.hpp" #include "asio/associated_executor.hpp" #include "asio/associated_immediate_executor.hpp" #include "asio/associator.hpp" #include "asio/async_result.hpp" #include "asio/awaitable.hpp" #include "asio/basic_datagram_socket.hpp" #include "asio/basic_deadline_timer.hpp" #include "asio/basic_file.hpp" #include "asio/basic_io_object.hpp" #include "asio/basic_random_access_file.hpp" #include "asio/basic_raw_socket.hpp" #include "asio/basic_readable_pipe.hpp" #include "asio/basic_seq_packet_socket.hpp" #include "asio/basic_serial_port.hpp" #include "asio/basic_signal_set.hpp" #include "asio/basic_socket.hpp" #include "asio/basic_socket_acceptor.hpp" #include "asio/basic_socket_iostream.hpp" #include "asio/basic_socket_streambuf.hpp" #include "asio/basic_stream_file.hpp" #include "asio/basic_stream_socket.hpp" #include "asio/basic_streambuf.hpp" #include "asio/basic_waitable_timer.hpp" #include "asio/basic_writable_pipe.hpp" #include "asio/bind_allocator.hpp" #include "asio/bind_cancellation_slot.hpp" #include "asio/bind_executor.hpp" #include "asio/bind_immediate_executor.hpp" #include "asio/buffer.hpp" #include "asio/buffer_registration.hpp" #include "asio/buffered_read_stream_fwd.hpp" #include "asio/buffered_read_stream.hpp" #include "asio/buffered_stream_fwd.hpp" #include "asio/buffered_stream.hpp" #include "asio/buffered_write_stream_fwd.hpp" #include "asio/buffered_write_stream.hpp" #include "asio/buffers_iterator.hpp" #include "asio/cancel_after.hpp" #include "asio/cancel_at.hpp" #include "asio/cancellation_signal.hpp" #include "asio/cancellation_state.hpp" #include "asio/cancellation_type.hpp" #include "asio/co_composed.hpp" #include "asio/co_spawn.hpp" #include "asio/completion_condition.hpp" #include "asio/compose.hpp" #include "asio/composed.hpp" #include "asio/connect.hpp" #include "asio/connect_pipe.hpp" #include "asio/consign.hpp" #include "asio/coroutine.hpp" #include "asio/deadline_timer.hpp" #include "asio/defer.hpp" #include "asio/deferred.hpp" #include "asio/default_completion_token.hpp" #include "asio/detached.hpp" #include "asio/dispatch.hpp" #include "asio/error.hpp" #include "asio/error_code.hpp" #include "asio/execution.hpp" #include "asio/execution/allocator.hpp" #include "asio/execution/any_executor.hpp" #include "asio/execution/blocking.hpp" #include "asio/execution/blocking_adaptation.hpp" #include "asio/execution/context.hpp" #include "asio/execution/context_as.hpp" #include "asio/execution/executor.hpp" #include "asio/execution/invocable_archetype.hpp" #include "asio/execution/mapping.hpp" #include "asio/execution/occupancy.hpp" #include "asio/execution/outstanding_work.hpp" #include "asio/execution/prefer_only.hpp" #include "asio/execution/relationship.hpp" #include "asio/executor.hpp" #include "asio/executor_work_guard.hpp" #include "asio/file_base.hpp" #include "asio/generic/basic_endpoint.hpp" #include "asio/generic/datagram_protocol.hpp" #include "asio/generic/raw_protocol.hpp" #include "asio/generic/seq_packet_protocol.hpp" #include "asio/generic/stream_protocol.hpp" #include "asio/handler_continuation_hook.hpp" #include "asio/high_resolution_timer.hpp" #include "asio/immediate.hpp" #include "asio/io_context.hpp" #include "asio/io_context_strand.hpp" #include "asio/io_service.hpp" #include "asio/io_service_strand.hpp" #include "asio/ip/address.hpp" #include "asio/ip/address_v4.hpp" #include "asio/ip/address_v4_iterator.hpp" #include "asio/ip/address_v4_range.hpp" #include "asio/ip/address_v6.hpp" #include "asio/ip/address_v6_iterator.hpp" #include "asio/ip/address_v6_range.hpp" #include "asio/ip/network_v4.hpp" #include "asio/ip/network_v6.hpp" #include "asio/ip/bad_address_cast.hpp" #include "asio/ip/basic_endpoint.hpp" #include "asio/ip/basic_resolver.hpp" #include "asio/ip/basic_resolver_entry.hpp" #include "asio/ip/basic_resolver_iterator.hpp" #include "asio/ip/basic_resolver_query.hpp" #include "asio/ip/host_name.hpp" #include "asio/ip/icmp.hpp" #include "asio/ip/multicast.hpp" #include "asio/ip/resolver_base.hpp" #include "asio/ip/resolver_query_base.hpp" #include "asio/ip/tcp.hpp" #include "asio/ip/udp.hpp" #include "asio/ip/unicast.hpp" #include "asio/ip/v6_only.hpp" #include "asio/is_applicable_property.hpp" #include "asio/is_contiguous_iterator.hpp" #include "asio/is_executor.hpp" #include "asio/is_read_buffered.hpp" #include "asio/is_write_buffered.hpp" #include "asio/local/basic_endpoint.hpp" #include "asio/local/connect_pair.hpp" #include "asio/local/datagram_protocol.hpp" #include "asio/local/seq_packet_protocol.hpp" #include "asio/local/stream_protocol.hpp" #include "asio/multiple_exceptions.hpp" #include "asio/packaged_task.hpp" #include "asio/placeholders.hpp" #include "asio/posix/basic_descriptor.hpp" #include "asio/posix/basic_stream_descriptor.hpp" #include "asio/posix/descriptor.hpp" #include "asio/posix/descriptor_base.hpp" #include "asio/posix/stream_descriptor.hpp" #include "asio/post.hpp" #include "asio/prefer.hpp" #include "asio/prepend.hpp" #include "asio/query.hpp" #include "asio/random_access_file.hpp" #include "asio/read.hpp" #include "asio/read_at.hpp" #include "asio/read_until.hpp" #include "asio/readable_pipe.hpp" #include "asio/recycling_allocator.hpp" #include "asio/redirect_error.hpp" #include "asio/registered_buffer.hpp" #include "asio/require.hpp" #include "asio/require_concept.hpp" #include "asio/serial_port.hpp" #include "asio/serial_port_base.hpp" #include "asio/signal_set.hpp" #include "asio/signal_set_base.hpp" #include "asio/socket_base.hpp" #include "asio/static_thread_pool.hpp" #include "asio/steady_timer.hpp" #include "asio/strand.hpp" #include "asio/stream_file.hpp" #include "asio/streambuf.hpp" #include "asio/system_context.hpp" #include "asio/system_error.hpp" #include "asio/system_executor.hpp" #include "asio/system_timer.hpp" #include "asio/this_coro.hpp" #include "asio/thread.hpp" #include "asio/thread_pool.hpp" #include "asio/time_traits.hpp" #include "asio/use_awaitable.hpp" #include "asio/use_future.hpp" #include "asio/uses_executor.hpp" #include "asio/version.hpp" #include "asio/wait_traits.hpp" #include "asio/windows/basic_object_handle.hpp" #include "asio/windows/basic_overlapped_handle.hpp" #include "asio/windows/basic_random_access_handle.hpp" #include "asio/windows/basic_stream_handle.hpp" #include "asio/windows/object_handle.hpp" #include "asio/windows/overlapped_handle.hpp" #include "asio/windows/overlapped_ptr.hpp" #include "asio/windows/random_access_handle.hpp" #include "asio/windows/stream_handle.hpp" #include "asio/writable_pipe.hpp" #include "asio/write.hpp" #include "asio/write_at.hpp" #endif // ASIO_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/buffered_read_stream.hpp
// // buffered_read_stream.hpp // ~~~~~~~~~~~~~~~~~~~~~~~~ // // 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) // #ifndef ASIO_BUFFERED_READ_STREAM_HPP #define ASIO_BUFFERED_READ_STREAM_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include <cstddef> #include "asio/async_result.hpp" #include "asio/buffered_read_stream_fwd.hpp" #include "asio/buffer.hpp" #include "asio/detail/bind_handler.hpp" #include "asio/detail/buffer_resize_guard.hpp" #include "asio/detail/buffered_stream_storage.hpp" #include "asio/detail/noncopyable.hpp" #include "asio/detail/type_traits.hpp" #include "asio/error.hpp" #include "asio/detail/push_options.hpp" namespace asio { namespace detail { template <typename> class initiate_async_buffered_fill; template <typename> class initiate_async_buffered_read_some; } // namespace detail /// Adds buffering to the read-related operations of a stream. /** * The buffered_read_stream class template can be used to add buffering to the * synchronous and asynchronous read operations of a stream. * * @par Thread Safety * @e Distinct @e objects: Safe.@n * @e Shared @e objects: Unsafe. * * @par Concepts: * AsyncReadStream, AsyncWriteStream, Stream, SyncReadStream, SyncWriteStream. */ template <typename Stream> class buffered_read_stream : private noncopyable { public: /// The type of the next layer. typedef remove_reference_t<Stream> next_layer_type; /// The type of the lowest layer. typedef typename next_layer_type::lowest_layer_type lowest_layer_type; /// The type of the executor associated with the object. typedef typename lowest_layer_type::executor_type executor_type; #if defined(GENERATING_DOCUMENTATION) /// The default buffer size. static const std::size_t default_buffer_size = implementation_defined; #else ASIO_STATIC_CONSTANT(std::size_t, default_buffer_size = 1024); #endif /// Construct, passing the specified argument to initialise the next layer. template <typename Arg> explicit buffered_read_stream(Arg&& a) : next_layer_(static_cast<Arg&&>(a)), storage_(default_buffer_size) { } /// Construct, passing the specified argument to initialise the next layer. template <typename Arg> buffered_read_stream(Arg&& a, std::size_t buffer_size) : next_layer_(static_cast<Arg&&>(a)), storage_(buffer_size) { } /// Get a reference to the next layer. next_layer_type& next_layer() { return next_layer_; } /// Get a reference to the lowest layer. lowest_layer_type& lowest_layer() { return next_layer_.lowest_layer(); } /// Get a const reference to the lowest layer. const lowest_layer_type& lowest_layer() const { return next_layer_.lowest_layer(); } /// Get the executor associated with the object. executor_type get_executor() noexcept { return next_layer_.lowest_layer().get_executor(); } /// Close the stream. void close() { next_layer_.close(); } /// Close the stream. ASIO_SYNC_OP_VOID close(asio::error_code& ec) { next_layer_.close(ec); ASIO_SYNC_OP_VOID_RETURN(ec); } /// Write the given data to the stream. Returns the number of bytes written. /// Throws an exception on failure. template <typename ConstBufferSequence> std::size_t write_some(const ConstBufferSequence& buffers) { return next_layer_.write_some(buffers); } /// Write the given data to the stream. Returns the number of bytes written, /// or 0 if an error occurred. template <typename ConstBufferSequence> std::size_t write_some(const ConstBufferSequence& buffers, asio::error_code& ec) { return next_layer_.write_some(buffers, ec); } /// Start an asynchronous write. The data being written must be valid for the /// lifetime of the asynchronous operation. /** * @par Completion Signature * @code void(asio::error_code, std::size_t) @endcode */ template <typename ConstBufferSequence, ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code, std::size_t)) WriteHandler = default_completion_token_t<executor_type>> auto async_write_some(const ConstBufferSequence& buffers, WriteHandler&& handler = default_completion_token_t<executor_type>()) -> decltype( declval<conditional_t<true, Stream&, WriteHandler>>().async_write_some( buffers, static_cast<WriteHandler&&>(handler))) { return next_layer_.async_write_some(buffers, static_cast<WriteHandler&&>(handler)); } /// Fill the buffer with some data. Returns the number of bytes placed in the /// buffer as a result of the operation. Throws an exception on failure. std::size_t fill(); /// Fill the buffer with some data. Returns the number of bytes placed in the /// buffer as a result of the operation, or 0 if an error occurred. std::size_t fill(asio::error_code& ec); /// Start an asynchronous fill. /** * @par Completion Signature * @code void(asio::error_code, std::size_t) @endcode */ template < ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code, std::size_t)) ReadHandler = default_completion_token_t<executor_type>> auto async_fill( ReadHandler&& handler = default_completion_token_t<executor_type>()) -> decltype( async_initiate<ReadHandler, void (asio::error_code, std::size_t)>( declval<detail::initiate_async_buffered_fill<Stream>>(), handler, declval<detail::buffered_stream_storage*>())); /// Read some data from the stream. Returns the number of bytes read. Throws /// an exception on failure. template <typename MutableBufferSequence> std::size_t read_some(const MutableBufferSequence& buffers); /// Read some data from the stream. Returns the number of bytes read or 0 if /// an error occurred. template <typename MutableBufferSequence> std::size_t read_some(const MutableBufferSequence& buffers, asio::error_code& ec); /// Start an asynchronous read. The buffer into which the data will be read /// must be valid for the lifetime of the asynchronous operation. /** * @par Completion Signature * @code void(asio::error_code, std::size_t) @endcode */ template <typename MutableBufferSequence, ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code, std::size_t)) ReadHandler = default_completion_token_t<executor_type>> auto async_read_some(const MutableBufferSequence& buffers, ReadHandler&& handler = default_completion_token_t<executor_type>()) -> decltype( async_initiate<ReadHandler, void (asio::error_code, std::size_t)>( declval<detail::initiate_async_buffered_read_some<Stream>>(), handler, declval<detail::buffered_stream_storage*>(), buffers)); /// Peek at the incoming data on the stream. Returns the number of bytes read. /// Throws an exception on failure. template <typename MutableBufferSequence> std::size_t peek(const MutableBufferSequence& buffers); /// Peek at the incoming data on the stream. Returns the number of bytes read, /// or 0 if an error occurred. template <typename MutableBufferSequence> std::size_t peek(const MutableBufferSequence& buffers, asio::error_code& ec); /// Determine the amount of data that may be read without blocking. std::size_t in_avail() { return storage_.size(); } /// Determine the amount of data that may be read without blocking. std::size_t in_avail(asio::error_code& ec) { ec = asio::error_code(); return storage_.size(); } private: /// Copy data out of the internal buffer to the specified target buffer. /// Returns the number of bytes copied. template <typename MutableBufferSequence> std::size_t copy(const MutableBufferSequence& buffers) { std::size_t bytes_copied = asio::buffer_copy( buffers, storage_.data(), storage_.size()); storage_.consume(bytes_copied); return bytes_copied; } /// Copy data from the internal buffer to the specified target buffer, without /// removing the data from the internal buffer. Returns the number of bytes /// copied. template <typename MutableBufferSequence> std::size_t peek_copy(const MutableBufferSequence& buffers) { return asio::buffer_copy(buffers, storage_.data(), storage_.size()); } /// The next layer. Stream next_layer_; // The data in the buffer. detail::buffered_stream_storage storage_; }; } // namespace asio #include "asio/detail/pop_options.hpp" #include "asio/impl/buffered_read_stream.hpp" #endif // ASIO_BUFFERED_READ_STREAM_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/connect.hpp
// // connect.hpp // ~~~~~~~~~~~ // // 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) // #ifndef ASIO_CONNECT_HPP #define ASIO_CONNECT_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include "asio/async_result.hpp" #include "asio/basic_socket.hpp" #include "asio/detail/type_traits.hpp" #include "asio/error.hpp" #include "asio/detail/push_options.hpp" namespace asio { namespace detail { struct default_connect_condition; template <typename, typename> class initiate_async_range_connect; template <typename, typename> class initiate_async_iterator_connect; template <typename T, typename = void, typename = void> struct is_endpoint_sequence_helper : false_type { }; template <typename T> struct is_endpoint_sequence_helper<T, void_t< decltype(declval<T>().begin()) >, void_t< decltype(declval<T>().end()) > > : true_type { }; template <typename T, typename Iterator, typename = void> struct is_connect_condition_helper : false_type { }; template <typename T, typename Iterator> struct is_connect_condition_helper<T, Iterator, enable_if_t< is_same< result_of_t<T(asio::error_code, Iterator)>, Iterator >::value > > : true_type { }; template <typename T, typename Iterator> struct is_connect_condition_helper<T, Iterator, enable_if_t< is_same< result_of_t<T(asio::error_code, decltype(*declval<Iterator>()))>, bool >::value > > : true_type { }; struct default_connect_condition { template <typename Endpoint> bool operator()(const asio::error_code&, const Endpoint&) { return true; } }; } // namespace detail #if defined(GENERATING_DOCUMENTATION) /// Type trait used to determine whether a type is an endpoint sequence that can /// be used with with @c connect and @c async_connect. template <typename T> struct is_endpoint_sequence { /// The value member is true if the type may be used as an endpoint sequence. static const bool value = automatically_determined; }; /// Trait for determining whether a function object is a connect condition that /// can be used with @c connect and @c async_connect. template <typename T, typename Iterator> struct is_connect_condition { /// The value member is true if the type may be used as a connect condition. static constexpr bool value = automatically_determined; }; #else // defined(GENERATING_DOCUMENTATION) template <typename T> struct is_endpoint_sequence : detail::is_endpoint_sequence_helper<T> { }; template <typename T, typename Iterator> struct is_connect_condition : detail::is_connect_condition_helper<T, Iterator> { }; #endif // defined(GENERATING_DOCUMENTATION) /** * @defgroup connect asio::connect * * @brief The @c connect function is a composed operation that establishes a * socket connection by trying each endpoint in a sequence. */ /*@{*/ /// Establishes a socket connection by trying each endpoint in a sequence. /** * This function attempts to connect a socket to one of a sequence of * endpoints. It does this by repeated calls to the socket's @c connect member * function, once for each endpoint in the sequence, until a connection is * successfully established. * * @param s The socket to be connected. If the socket is already open, it will * be closed. * * @param endpoints A sequence of endpoints. * * @returns The successfully connected endpoint. * * @throws asio::system_error Thrown on failure. If the sequence is * empty, the associated @c error_code is asio::error::not_found. * Otherwise, contains the error from the last connection attempt. * * @par Example * @code tcp::resolver r(my_context); * tcp::resolver::query q("host", "service"); * tcp::socket s(my_context); * asio::connect(s, r.resolve(q)); @endcode */ template <typename Protocol, typename Executor, typename EndpointSequence> typename Protocol::endpoint connect(basic_socket<Protocol, Executor>& s, const EndpointSequence& endpoints, constraint_t< is_endpoint_sequence<EndpointSequence>::value > = 0); /// Establishes a socket connection by trying each endpoint in a sequence. /** * This function attempts to connect a socket to one of a sequence of * endpoints. It does this by repeated calls to the socket's @c connect member * function, once for each endpoint in the sequence, until a connection is * successfully established. * * @param s The socket to be connected. If the socket is already open, it will * be closed. * * @param endpoints A sequence of endpoints. * * @param ec Set to indicate what error occurred, if any. If the sequence is * empty, set to asio::error::not_found. Otherwise, contains the error * from the last connection attempt. * * @returns On success, the successfully connected endpoint. Otherwise, a * default-constructed endpoint. * * @par Example * @code tcp::resolver r(my_context); * tcp::resolver::query q("host", "service"); * tcp::socket s(my_context); * asio::error_code ec; * asio::connect(s, r.resolve(q), ec); * if (ec) * { * // An error occurred. * } @endcode */ template <typename Protocol, typename Executor, typename EndpointSequence> typename Protocol::endpoint connect(basic_socket<Protocol, Executor>& s, const EndpointSequence& endpoints, asio::error_code& ec, constraint_t< is_endpoint_sequence<EndpointSequence>::value > = 0); #if !defined(ASIO_NO_DEPRECATED) /// (Deprecated: Use range overload.) Establishes a socket connection by trying /// each endpoint in a sequence. /** * This function attempts to connect a socket to one of a sequence of * endpoints. It does this by repeated calls to the socket's @c connect member * function, once for each endpoint in the sequence, until a connection is * successfully established. * * @param s The socket to be connected. If the socket is already open, it will * be closed. * * @param begin An iterator pointing to the start of a sequence of endpoints. * * @returns On success, an iterator denoting the successfully connected * endpoint. Otherwise, the end iterator. * * @throws asio::system_error Thrown on failure. If the sequence is * empty, the associated @c error_code is asio::error::not_found. * Otherwise, contains the error from the last connection attempt. * * @note This overload assumes that a default constructed object of type @c * Iterator represents the end of the sequence. This is a valid assumption for * iterator types such as @c asio::ip::tcp::resolver::iterator. */ template <typename Protocol, typename Executor, typename Iterator> Iterator connect(basic_socket<Protocol, Executor>& s, Iterator begin, constraint_t< !is_endpoint_sequence<Iterator>::value > = 0); /// (Deprecated: Use range overload.) Establishes a socket connection by trying /// each endpoint in a sequence. /** * This function attempts to connect a socket to one of a sequence of * endpoints. It does this by repeated calls to the socket's @c connect member * function, once for each endpoint in the sequence, until a connection is * successfully established. * * @param s The socket to be connected. If the socket is already open, it will * be closed. * * @param begin An iterator pointing to the start of a sequence of endpoints. * * @param ec Set to indicate what error occurred, if any. If the sequence is * empty, set to asio::error::not_found. Otherwise, contains the error * from the last connection attempt. * * @returns On success, an iterator denoting the successfully connected * endpoint. Otherwise, the end iterator. * * @note This overload assumes that a default constructed object of type @c * Iterator represents the end of the sequence. This is a valid assumption for * iterator types such as @c asio::ip::tcp::resolver::iterator. */ template <typename Protocol, typename Executor, typename Iterator> Iterator connect(basic_socket<Protocol, Executor>& s, Iterator begin, asio::error_code& ec, constraint_t< !is_endpoint_sequence<Iterator>::value > = 0); #endif // !defined(ASIO_NO_DEPRECATED) /// Establishes a socket connection by trying each endpoint in a sequence. /** * This function attempts to connect a socket to one of a sequence of * endpoints. It does this by repeated calls to the socket's @c connect member * function, once for each endpoint in the sequence, until a connection is * successfully established. * * @param s The socket to be connected. If the socket is already open, it will * be closed. * * @param begin An iterator pointing to the start of a sequence of endpoints. * * @param end An iterator pointing to the end of a sequence of endpoints. * * @returns An iterator denoting the successfully connected endpoint. * * @throws asio::system_error Thrown on failure. If the sequence is * empty, the associated @c error_code is asio::error::not_found. * Otherwise, contains the error from the last connection attempt. * * @par Example * @code tcp::resolver r(my_context); * tcp::resolver::query q("host", "service"); * tcp::resolver::results_type e = r.resolve(q); * tcp::socket s(my_context); * asio::connect(s, e.begin(), e.end()); @endcode */ template <typename Protocol, typename Executor, typename Iterator> Iterator connect(basic_socket<Protocol, Executor>& s, Iterator begin, Iterator end); /// Establishes a socket connection by trying each endpoint in a sequence. /** * This function attempts to connect a socket to one of a sequence of * endpoints. It does this by repeated calls to the socket's @c connect member * function, once for each endpoint in the sequence, until a connection is * successfully established. * * @param s The socket to be connected. If the socket is already open, it will * be closed. * * @param begin An iterator pointing to the start of a sequence of endpoints. * * @param end An iterator pointing to the end of a sequence of endpoints. * * @param ec Set to indicate what error occurred, if any. If the sequence is * empty, set to asio::error::not_found. Otherwise, contains the error * from the last connection attempt. * * @returns On success, an iterator denoting the successfully connected * endpoint. Otherwise, the end iterator. * * @par Example * @code tcp::resolver r(my_context); * tcp::resolver::query q("host", "service"); * tcp::resolver::results_type e = r.resolve(q); * tcp::socket s(my_context); * asio::error_code ec; * asio::connect(s, e.begin(), e.end(), ec); * if (ec) * { * // An error occurred. * } @endcode */ template <typename Protocol, typename Executor, typename Iterator> Iterator connect(basic_socket<Protocol, Executor>& s, Iterator begin, Iterator end, asio::error_code& ec); /// Establishes a socket connection by trying each endpoint in a sequence. /** * This function attempts to connect a socket to one of a sequence of * endpoints. It does this by repeated calls to the socket's @c connect member * function, once for each endpoint in the sequence, until a connection is * successfully established. * * @param s The socket to be connected. If the socket is already open, it will * be closed. * * @param endpoints A sequence of endpoints. * * @param connect_condition A function object that is called prior to each * connection attempt. The signature of the function object must be: * @code bool connect_condition( * const asio::error_code& ec, * const typename Protocol::endpoint& next); @endcode * The @c ec parameter contains the result from the most recent connect * operation. Before the first connection attempt, @c ec is always set to * indicate success. The @c next parameter is the next endpoint to be tried. * The function object should return true if the next endpoint should be tried, * and false if it should be skipped. * * @returns The successfully connected endpoint. * * @throws asio::system_error Thrown on failure. If the sequence is * empty, the associated @c error_code is asio::error::not_found. * Otherwise, contains the error from the last connection attempt. * * @par Example * The following connect condition function object can be used to output * information about the individual connection attempts: * @code struct my_connect_condition * { * bool operator()( * const asio::error_code& ec, * const::tcp::endpoint& next) * { * if (ec) std::cout << "Error: " << ec.message() << std::endl; * std::cout << "Trying: " << next << std::endl; * return true; * } * }; @endcode * It would be used with the asio::connect function as follows: * @code tcp::resolver r(my_context); * tcp::resolver::query q("host", "service"); * tcp::socket s(my_context); * tcp::endpoint e = asio::connect(s, * r.resolve(q), my_connect_condition()); * std::cout << "Connected to: " << e << std::endl; @endcode */ template <typename Protocol, typename Executor, typename EndpointSequence, typename ConnectCondition> typename Protocol::endpoint connect(basic_socket<Protocol, Executor>& s, const EndpointSequence& endpoints, ConnectCondition connect_condition, constraint_t< is_endpoint_sequence<EndpointSequence>::value > = 0, constraint_t< is_connect_condition<ConnectCondition, decltype(declval<const EndpointSequence&>().begin())>::value > = 0); /// Establishes a socket connection by trying each endpoint in a sequence. /** * This function attempts to connect a socket to one of a sequence of * endpoints. It does this by repeated calls to the socket's @c connect member * function, once for each endpoint in the sequence, until a connection is * successfully established. * * @param s The socket to be connected. If the socket is already open, it will * be closed. * * @param endpoints A sequence of endpoints. * * @param connect_condition A function object that is called prior to each * connection attempt. The signature of the function object must be: * @code bool connect_condition( * const asio::error_code& ec, * const typename Protocol::endpoint& next); @endcode * The @c ec parameter contains the result from the most recent connect * operation. Before the first connection attempt, @c ec is always set to * indicate success. The @c next parameter is the next endpoint to be tried. * The function object should return true if the next endpoint should be tried, * and false if it should be skipped. * * @param ec Set to indicate what error occurred, if any. If the sequence is * empty, set to asio::error::not_found. Otherwise, contains the error * from the last connection attempt. * * @returns On success, the successfully connected endpoint. Otherwise, a * default-constructed endpoint. * * @par Example * The following connect condition function object can be used to output * information about the individual connection attempts: * @code struct my_connect_condition * { * bool operator()( * const asio::error_code& ec, * const::tcp::endpoint& next) * { * if (ec) std::cout << "Error: " << ec.message() << std::endl; * std::cout << "Trying: " << next << std::endl; * return true; * } * }; @endcode * It would be used with the asio::connect function as follows: * @code tcp::resolver r(my_context); * tcp::resolver::query q("host", "service"); * tcp::socket s(my_context); * asio::error_code ec; * tcp::endpoint e = asio::connect(s, * r.resolve(q), my_connect_condition(), ec); * if (ec) * { * // An error occurred. * } * else * { * std::cout << "Connected to: " << e << std::endl; * } @endcode */ template <typename Protocol, typename Executor, typename EndpointSequence, typename ConnectCondition> typename Protocol::endpoint connect(basic_socket<Protocol, Executor>& s, const EndpointSequence& endpoints, ConnectCondition connect_condition, asio::error_code& ec, constraint_t< is_endpoint_sequence<EndpointSequence>::value > = 0, constraint_t< is_connect_condition<ConnectCondition, decltype(declval<const EndpointSequence&>().begin())>::value > = 0); #if !defined(ASIO_NO_DEPRECATED) /// (Deprecated: Use range overload.) Establishes a socket connection by trying /// each endpoint in a sequence. /** * This function attempts to connect a socket to one of a sequence of * endpoints. It does this by repeated calls to the socket's @c connect member * function, once for each endpoint in the sequence, until a connection is * successfully established. * * @param s The socket to be connected. If the socket is already open, it will * be closed. * * @param begin An iterator pointing to the start of a sequence of endpoints. * * @param connect_condition A function object that is called prior to each * connection attempt. The signature of the function object must be: * @code bool connect_condition( * const asio::error_code& ec, * const typename Protocol::endpoint& next); @endcode * The @c ec parameter contains the result from the most recent connect * operation. Before the first connection attempt, @c ec is always set to * indicate success. The @c next parameter is the next endpoint to be tried. * The function object should return true if the next endpoint should be tried, * and false if it should be skipped. * * @returns On success, an iterator denoting the successfully connected * endpoint. Otherwise, the end iterator. * * @throws asio::system_error Thrown on failure. If the sequence is * empty, the associated @c error_code is asio::error::not_found. * Otherwise, contains the error from the last connection attempt. * * @note This overload assumes that a default constructed object of type @c * Iterator represents the end of the sequence. This is a valid assumption for * iterator types such as @c asio::ip::tcp::resolver::iterator. */ template <typename Protocol, typename Executor, typename Iterator, typename ConnectCondition> Iterator connect(basic_socket<Protocol, Executor>& s, Iterator begin, ConnectCondition connect_condition, constraint_t< !is_endpoint_sequence<Iterator>::value > = 0, constraint_t< is_connect_condition<ConnectCondition, Iterator>::value > = 0); /// (Deprecated: Use range overload.) Establishes a socket connection by trying /// each endpoint in a sequence. /** * This function attempts to connect a socket to one of a sequence of * endpoints. It does this by repeated calls to the socket's @c connect member * function, once for each endpoint in the sequence, until a connection is * successfully established. * * @param s The socket to be connected. If the socket is already open, it will * be closed. * * @param begin An iterator pointing to the start of a sequence of endpoints. * * @param connect_condition A function object that is called prior to each * connection attempt. The signature of the function object must be: * @code bool connect_condition( * const asio::error_code& ec, * const typename Protocol::endpoint& next); @endcode * The @c ec parameter contains the result from the most recent connect * operation. Before the first connection attempt, @c ec is always set to * indicate success. The @c next parameter is the next endpoint to be tried. * The function object should return true if the next endpoint should be tried, * and false if it should be skipped. * * @param ec Set to indicate what error occurred, if any. If the sequence is * empty, set to asio::error::not_found. Otherwise, contains the error * from the last connection attempt. * * @returns On success, an iterator denoting the successfully connected * endpoint. Otherwise, the end iterator. * * @note This overload assumes that a default constructed object of type @c * Iterator represents the end of the sequence. This is a valid assumption for * iterator types such as @c asio::ip::tcp::resolver::iterator. */ template <typename Protocol, typename Executor, typename Iterator, typename ConnectCondition> Iterator connect(basic_socket<Protocol, Executor>& s, Iterator begin, ConnectCondition connect_condition, asio::error_code& ec, constraint_t< !is_endpoint_sequence<Iterator>::value > = 0, constraint_t< is_connect_condition<ConnectCondition, Iterator>::value > = 0); #endif // !defined(ASIO_NO_DEPRECATED) /// Establishes a socket connection by trying each endpoint in a sequence. /** * This function attempts to connect a socket to one of a sequence of * endpoints. It does this by repeated calls to the socket's @c connect member * function, once for each endpoint in the sequence, until a connection is * successfully established. * * @param s The socket to be connected. If the socket is already open, it will * be closed. * * @param begin An iterator pointing to the start of a sequence of endpoints. * * @param end An iterator pointing to the end of a sequence of endpoints. * * @param connect_condition A function object that is called prior to each * connection attempt. The signature of the function object must be: * @code bool connect_condition( * const asio::error_code& ec, * const typename Protocol::endpoint& next); @endcode * The @c ec parameter contains the result from the most recent connect * operation. Before the first connection attempt, @c ec is always set to * indicate success. The @c next parameter is the next endpoint to be tried. * The function object should return true if the next endpoint should be tried, * and false if it should be skipped. * * @returns An iterator denoting the successfully connected endpoint. * * @throws asio::system_error Thrown on failure. If the sequence is * empty, the associated @c error_code is asio::error::not_found. * Otherwise, contains the error from the last connection attempt. * * @par Example * The following connect condition function object can be used to output * information about the individual connection attempts: * @code struct my_connect_condition * { * bool operator()( * const asio::error_code& ec, * const::tcp::endpoint& next) * { * if (ec) std::cout << "Error: " << ec.message() << std::endl; * std::cout << "Trying: " << next << std::endl; * return true; * } * }; @endcode * It would be used with the asio::connect function as follows: * @code tcp::resolver r(my_context); * tcp::resolver::query q("host", "service"); * tcp::resolver::results_type e = r.resolve(q); * tcp::socket s(my_context); * tcp::resolver::results_type::iterator i = asio::connect( * s, e.begin(), e.end(), my_connect_condition()); * std::cout << "Connected to: " << i->endpoint() << std::endl; @endcode */ template <typename Protocol, typename Executor, typename Iterator, typename ConnectCondition> Iterator connect(basic_socket<Protocol, Executor>& s, Iterator begin, Iterator end, ConnectCondition connect_condition, constraint_t< is_connect_condition<ConnectCondition, Iterator>::value > = 0); /// Establishes a socket connection by trying each endpoint in a sequence. /** * This function attempts to connect a socket to one of a sequence of * endpoints. It does this by repeated calls to the socket's @c connect member * function, once for each endpoint in the sequence, until a connection is * successfully established. * * @param s The socket to be connected. If the socket is already open, it will * be closed. * * @param begin An iterator pointing to the start of a sequence of endpoints. * * @param end An iterator pointing to the end of a sequence of endpoints. * * @param connect_condition A function object that is called prior to each * connection attempt. The signature of the function object must be: * @code bool connect_condition( * const asio::error_code& ec, * const typename Protocol::endpoint& next); @endcode * The @c ec parameter contains the result from the most recent connect * operation. Before the first connection attempt, @c ec is always set to * indicate success. The @c next parameter is the next endpoint to be tried. * The function object should return true if the next endpoint should be tried, * and false if it should be skipped. * * @param ec Set to indicate what error occurred, if any. If the sequence is * empty, set to asio::error::not_found. Otherwise, contains the error * from the last connection attempt. * * @returns On success, an iterator denoting the successfully connected * endpoint. Otherwise, the end iterator. * * @par Example * The following connect condition function object can be used to output * information about the individual connection attempts: * @code struct my_connect_condition * { * bool operator()( * const asio::error_code& ec, * const::tcp::endpoint& next) * { * if (ec) std::cout << "Error: " << ec.message() << std::endl; * std::cout << "Trying: " << next << std::endl; * return true; * } * }; @endcode * It would be used with the asio::connect function as follows: * @code tcp::resolver r(my_context); * tcp::resolver::query q("host", "service"); * tcp::resolver::results_type e = r.resolve(q); * tcp::socket s(my_context); * asio::error_code ec; * tcp::resolver::results_type::iterator i = asio::connect( * s, e.begin(), e.end(), my_connect_condition()); * if (ec) * { * // An error occurred. * } * else * { * std::cout << "Connected to: " << i->endpoint() << std::endl; * } @endcode */ template <typename Protocol, typename Executor, typename Iterator, typename ConnectCondition> Iterator connect(basic_socket<Protocol, Executor>& s, Iterator begin, Iterator end, ConnectCondition connect_condition, asio::error_code& ec, constraint_t< is_connect_condition<ConnectCondition, Iterator>::value > = 0); /*@}*/ /** * @defgroup async_connect asio::async_connect * * @brief The @c async_connect function is a composed asynchronous operation * that establishes a socket connection by trying each endpoint in a sequence. */ /*@{*/ /// Asynchronously establishes a socket connection by trying each endpoint in a /// sequence. /** * This function attempts to connect a socket to one of a sequence of * endpoints. It does this by repeated calls to the socket's @c async_connect * member function, once for each endpoint in the sequence, until a connection * is successfully established. It is an initiating function for an @ref * asynchronous_operation, and always returns immediately. * * @param s The socket to be connected. If the socket is already open, it will * be closed. * * @param endpoints A sequence of endpoints. * * @param token The @ref completion_token that will be used to produce a * completion handler, which will be called when the connect completes. * Potential completion tokens include @ref use_future, @ref use_awaitable, * @ref yield_context, or a function object with the correct completion * signature. The function signature of the completion handler must be: * @code void handler( * // Result of operation. if the sequence is empty, set to * // asio::error::not_found. Otherwise, contains the * // error from the last connection attempt. * const asio::error_code& error, * * // On success, the successfully connected endpoint. * // Otherwise, a default-constructed endpoint. * const typename Protocol::endpoint& endpoint * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the completion handler will not be invoked from within this function. * On immediate completion, invocation of the handler will be performed in a * manner equivalent to using asio::async_immediate(). * * @par Completion Signature * @code void(asio::error_code, typename Protocol::endpoint) @endcode * * @par Example * @code tcp::resolver r(my_context); * tcp::resolver::query q("host", "service"); * tcp::socket s(my_context); * * // ... * * r.async_resolve(q, resolve_handler); * * // ... * * void resolve_handler( * const asio::error_code& ec, * tcp::resolver::results_type results) * { * if (!ec) * { * asio::async_connect(s, results, connect_handler); * } * } * * // ... * * void connect_handler( * const asio::error_code& ec, * const tcp::endpoint& endpoint) * { * // ... * } @endcode * * @par Per-Operation Cancellation * This asynchronous operation supports cancellation for the following * asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * if they are also supported by the socket's @c async_connect operation. */ template <typename Protocol, typename Executor, typename EndpointSequence, ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code, typename Protocol::endpoint)) RangeConnectToken = default_completion_token_t<Executor>> inline auto async_connect(basic_socket<Protocol, Executor>& s, const EndpointSequence& endpoints, RangeConnectToken&& token = default_completion_token_t<Executor>(), constraint_t< is_endpoint_sequence<EndpointSequence>::value > = 0, constraint_t< !is_connect_condition<RangeConnectToken, decltype(declval<const EndpointSequence&>().begin())>::value > = 0) -> decltype( async_initiate<RangeConnectToken, void (asio::error_code, typename Protocol::endpoint)>( declval<detail::initiate_async_range_connect<Protocol, Executor>>(), token, endpoints, declval<detail::default_connect_condition>())) { return async_initiate<RangeConnectToken, void (asio::error_code, typename Protocol::endpoint)>( detail::initiate_async_range_connect<Protocol, Executor>(s), token, endpoints, detail::default_connect_condition()); } #if !defined(ASIO_NO_DEPRECATED) /// (Deprecated: Use range overload.) Asynchronously establishes a socket /// connection by trying each endpoint in a sequence. /** * This function attempts to connect a socket to one of a sequence of * endpoints. It does this by repeated calls to the socket's @c async_connect * member function, once for each endpoint in the sequence, until a connection * is successfully established. It is an initiating function for an @ref * asynchronous_operation, and always returns immediately. * * @param s The socket to be connected. If the socket is already open, it will * be closed. * * @param begin An iterator pointing to the start of a sequence of endpoints. * * @param token The @ref completion_token that will be used to produce a * completion handler, which will be called when the connect completes. * Potential completion tokens include @ref use_future, @ref use_awaitable, * @ref yield_context, or a function object with the correct completion * signature. The function signature of the completion handler must be: * @code void handler( * // Result of operation. if the sequence is empty, set to * // asio::error::not_found. Otherwise, contains the * // error from the last connection attempt. * const asio::error_code& error, * * // On success, an iterator denoting the successfully * // connected endpoint. Otherwise, the end iterator. * Iterator iterator * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the completion handler will not be invoked from within this function. * On immediate completion, invocation of the handler will be performed in a * manner equivalent to using asio::async_immediate(). * * @par Completion Signature * @code void(asio::error_code, Iterator) @endcode * * @note This overload assumes that a default constructed object of type @c * Iterator represents the end of the sequence. This is a valid assumption for * iterator types such as @c asio::ip::tcp::resolver::iterator. * * @par Per-Operation Cancellation * This asynchronous operation supports cancellation for the following * asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * if they are also supported by the socket's @c async_connect operation. */ template <typename Protocol, typename Executor, typename Iterator, ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code, Iterator)) IteratorConnectToken = default_completion_token_t<Executor>> inline auto async_connect(basic_socket<Protocol, Executor>& s, Iterator begin, IteratorConnectToken&& token = default_completion_token_t<Executor>(), constraint_t< !is_endpoint_sequence<Iterator>::value > = 0, constraint_t< !is_same<Iterator, decay_t<IteratorConnectToken>>::value > = 0, constraint_t< !is_connect_condition<IteratorConnectToken, Iterator>::value > = 0) -> decltype( async_initiate<IteratorConnectToken, void (asio::error_code, Iterator)>( declval<detail::initiate_async_iterator_connect<Protocol, Executor>>(), token, begin, Iterator(), declval<detail::default_connect_condition>())) { return async_initiate<IteratorConnectToken, void (asio::error_code, Iterator)>( detail::initiate_async_iterator_connect<Protocol, Executor>(s), token, begin, Iterator(), detail::default_connect_condition()); } #endif // !defined(ASIO_NO_DEPRECATED) /// Asynchronously establishes a socket connection by trying each endpoint in a /// sequence. /** * This function attempts to connect a socket to one of a sequence of * endpoints. It does this by repeated calls to the socket's @c async_connect * member function, once for each endpoint in the sequence, until a connection * is successfully established. It is an initiating function for an @ref * asynchronous_operation, and always returns immediately. * * @param s The socket to be connected. If the socket is already open, it will * be closed. * * @param begin An iterator pointing to the start of a sequence of endpoints. * * @param end An iterator pointing to the end of a sequence of endpoints. * * @param token The @ref completion_token that will be used to produce a * completion handler, which will be called when the connect completes. * Potential completion tokens include @ref use_future, @ref use_awaitable, * @ref yield_context, or a function object with the correct completion * signature. The function signature of the completion handler must be: * @code void handler( * // Result of operation. if the sequence is empty, set to * // asio::error::not_found. Otherwise, contains the * // error from the last connection attempt. * const asio::error_code& error, * * // On success, an iterator denoting the successfully * // connected endpoint. Otherwise, the end iterator. * Iterator iterator * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the completion handler will not be invoked from within this function. * On immediate completion, invocation of the handler will be performed in a * manner equivalent to using asio::async_immediate(). * * @par Completion Signature * @code void(asio::error_code, Iterator) @endcode * * @par Example * @code std::vector<tcp::endpoint> endpoints = ...; * tcp::socket s(my_context); * asio::async_connect(s, * endpoints.begin(), endpoints.end(), * connect_handler); * * // ... * * void connect_handler( * const asio::error_code& ec, * std::vector<tcp::endpoint>::iterator i) * { * // ... * } @endcode * * @par Per-Operation Cancellation * This asynchronous operation supports cancellation for the following * asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * if they are also supported by the socket's @c async_connect operation. */ template <typename Protocol, typename Executor, typename Iterator, ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code, Iterator)) IteratorConnectToken = default_completion_token_t<Executor>> inline auto async_connect( basic_socket<Protocol, Executor>& s, Iterator begin, Iterator end, IteratorConnectToken&& token = default_completion_token_t<Executor>(), constraint_t< !is_connect_condition<IteratorConnectToken, Iterator>::value > = 0) -> decltype( async_initiate<IteratorConnectToken, void (asio::error_code, Iterator)>( declval<detail::initiate_async_iterator_connect<Protocol, Executor>>(), token, begin, end, declval<detail::default_connect_condition>())) { return async_initiate<IteratorConnectToken, void (asio::error_code, Iterator)>( detail::initiate_async_iterator_connect<Protocol, Executor>(s), token, begin, end, detail::default_connect_condition()); } /// Asynchronously establishes a socket connection by trying each endpoint in a /// sequence. /** * This function attempts to connect a socket to one of a sequence of * endpoints. It does this by repeated calls to the socket's @c async_connect * member function, once for each endpoint in the sequence, until a connection * is successfully established. It is an initiating function for an @ref * asynchronous_operation, and always returns immediately. * * @param s The socket to be connected. If the socket is already open, it will * be closed. * * @param endpoints A sequence of endpoints. * * @param connect_condition A function object that is called prior to each * connection attempt. The signature of the function object must be: * @code bool connect_condition( * const asio::error_code& ec, * const typename Protocol::endpoint& next); @endcode * The @c ec parameter contains the result from the most recent connect * operation. Before the first connection attempt, @c ec is always set to * indicate success. The @c next parameter is the next endpoint to be tried. * The function object should return true if the next endpoint should be tried, * and false if it should be skipped. * * @param token The @ref completion_token that will be used to produce a * completion handler, which will be called when the connect completes. * Potential completion tokens include @ref use_future, @ref use_awaitable, * @ref yield_context, or a function object with the correct completion * signature. The function signature of the completion handler must be: * @code void handler( * // Result of operation. if the sequence is empty, set to * // asio::error::not_found. Otherwise, contains the * // error from the last connection attempt. * const asio::error_code& error, * * // On success, an iterator denoting the successfully * // connected endpoint. Otherwise, the end iterator. * Iterator iterator * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the completion handler will not be invoked from within this function. * On immediate completion, invocation of the handler will be performed in a * manner equivalent to using asio::async_immediate(). * * @par Completion Signature * @code void(asio::error_code, typename Protocol::endpoint) @endcode * * @par Example * The following connect condition function object can be used to output * information about the individual connection attempts: * @code struct my_connect_condition * { * bool operator()( * const asio::error_code& ec, * const::tcp::endpoint& next) * { * if (ec) std::cout << "Error: " << ec.message() << std::endl; * std::cout << "Trying: " << next << std::endl; * return true; * } * }; @endcode * It would be used with the asio::connect function as follows: * @code tcp::resolver r(my_context); * tcp::resolver::query q("host", "service"); * tcp::socket s(my_context); * * // ... * * r.async_resolve(q, resolve_handler); * * // ... * * void resolve_handler( * const asio::error_code& ec, * tcp::resolver::results_type results) * { * if (!ec) * { * asio::async_connect(s, results, * my_connect_condition(), * connect_handler); * } * } * * // ... * * void connect_handler( * const asio::error_code& ec, * const tcp::endpoint& endpoint) * { * if (ec) * { * // An error occurred. * } * else * { * std::cout << "Connected to: " << endpoint << std::endl; * } * } @endcode * * @par Per-Operation Cancellation * This asynchronous operation supports cancellation for the following * asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * if they are also supported by the socket's @c async_connect operation. */ template <typename Protocol, typename Executor, typename EndpointSequence, typename ConnectCondition, ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code, typename Protocol::endpoint)) RangeConnectToken = default_completion_token_t<Executor>> inline auto async_connect(basic_socket<Protocol, Executor>& s, const EndpointSequence& endpoints, ConnectCondition connect_condition, RangeConnectToken&& token = default_completion_token_t<Executor>(), constraint_t< is_endpoint_sequence<EndpointSequence>::value > = 0, constraint_t< is_connect_condition<ConnectCondition, decltype(declval<const EndpointSequence&>().begin())>::value > = 0) -> decltype( async_initiate<RangeConnectToken, void (asio::error_code, typename Protocol::endpoint)>( declval<detail::initiate_async_range_connect<Protocol, Executor>>(), token, endpoints, connect_condition)) { return async_initiate<RangeConnectToken, void (asio::error_code, typename Protocol::endpoint)>( detail::initiate_async_range_connect<Protocol, Executor>(s), token, endpoints, connect_condition); } #if !defined(ASIO_NO_DEPRECATED) /// (Deprecated: Use range overload.) Asynchronously establishes a socket /// connection by trying each endpoint in a sequence. /** * This function attempts to connect a socket to one of a sequence of * endpoints. It does this by repeated calls to the socket's @c async_connect * member function, once for each endpoint in the sequence, until a connection * is successfully established. It is an initiating function for an @ref * asynchronous_operation, and always returns immediately. * * @param s The socket to be connected. If the socket is already open, it will * be closed. * * @param begin An iterator pointing to the start of a sequence of endpoints. * * @param connect_condition A function object that is called prior to each * connection attempt. The signature of the function object must be: * @code bool connect_condition( * const asio::error_code& ec, * const typename Protocol::endpoint& next); @endcode * The @c ec parameter contains the result from the most recent connect * operation. Before the first connection attempt, @c ec is always set to * indicate success. The @c next parameter is the next endpoint to be tried. * The function object should return true if the next endpoint should be tried, * and false if it should be skipped. * * @param token The @ref completion_token that will be used to produce a * completion handler, which will be called when the connect completes. * Potential completion tokens include @ref use_future, @ref use_awaitable, * @ref yield_context, or a function object with the correct completion * signature. The function signature of the completion handler must be: * @code void handler( * // Result of operation. if the sequence is empty, set to * // asio::error::not_found. Otherwise, contains the * // error from the last connection attempt. * const asio::error_code& error, * * // On success, an iterator denoting the successfully * // connected endpoint. Otherwise, the end iterator. * Iterator iterator * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the completion handler will not be invoked from within this function. * On immediate completion, invocation of the handler will be performed in a * manner equivalent to using asio::async_immediate(). * * @par Completion Signature * @code void(asio::error_code, Iterator) @endcode * * @note This overload assumes that a default constructed object of type @c * Iterator represents the end of the sequence. This is a valid assumption for * iterator types such as @c asio::ip::tcp::resolver::iterator. * * @par Per-Operation Cancellation * This asynchronous operation supports cancellation for the following * asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * if they are also supported by the socket's @c async_connect operation. */ template <typename Protocol, typename Executor, typename Iterator, typename ConnectCondition, ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code, Iterator)) IteratorConnectToken = default_completion_token_t<Executor>> inline auto async_connect(basic_socket<Protocol, Executor>& s, Iterator begin, ConnectCondition connect_condition, IteratorConnectToken&& token = default_completion_token_t<Executor>(), constraint_t< !is_endpoint_sequence<Iterator>::value > = 0, constraint_t< is_connect_condition<ConnectCondition, Iterator>::value > = 0) -> decltype( async_initiate<IteratorConnectToken, void (asio::error_code, Iterator)>( declval<detail::initiate_async_iterator_connect<Protocol, Executor>>(), token, begin, Iterator(), connect_condition)) { return async_initiate<IteratorConnectToken, void (asio::error_code, Iterator)>( detail::initiate_async_iterator_connect<Protocol, Executor>(s), token, begin, Iterator(), connect_condition); } #endif // !defined(ASIO_NO_DEPRECATED) /// Asynchronously establishes a socket connection by trying each endpoint in a /// sequence. /** * This function attempts to connect a socket to one of a sequence of * endpoints. It does this by repeated calls to the socket's @c async_connect * member function, once for each endpoint in the sequence, until a connection * is successfully established. It is an initiating function for an @ref * asynchronous_operation, and always returns immediately. * * @param s The socket to be connected. If the socket is already open, it will * be closed. * * @param begin An iterator pointing to the start of a sequence of endpoints. * * @param end An iterator pointing to the end of a sequence of endpoints. * * @param connect_condition A function object that is called prior to each * connection attempt. The signature of the function object must be: * @code bool connect_condition( * const asio::error_code& ec, * const typename Protocol::endpoint& next); @endcode * The @c ec parameter contains the result from the most recent connect * operation. Before the first connection attempt, @c ec is always set to * indicate success. The @c next parameter is the next endpoint to be tried. * The function object should return true if the next endpoint should be tried, * and false if it should be skipped. * * @param token The @ref completion_token that will be used to produce a * completion handler, which will be called when the connect completes. * Potential completion tokens include @ref use_future, @ref use_awaitable, * @ref yield_context, or a function object with the correct completion * signature. The function signature of the completion handler must be: * @code void handler( * // Result of operation. if the sequence is empty, set to * // asio::error::not_found. Otherwise, contains the * // error from the last connection attempt. * const asio::error_code& error, * * // On success, an iterator denoting the successfully * // connected endpoint. Otherwise, the end iterator. * Iterator iterator * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the completion handler will not be invoked from within this function. * On immediate completion, invocation of the handler will be performed in a * manner equivalent to using asio::async_immediate(). * * @par Completion Signature * @code void(asio::error_code, Iterator) @endcode * * @par Example * The following connect condition function object can be used to output * information about the individual connection attempts: * @code struct my_connect_condition * { * bool operator()( * const asio::error_code& ec, * const::tcp::endpoint& next) * { * if (ec) std::cout << "Error: " << ec.message() << std::endl; * std::cout << "Trying: " << next << std::endl; * return true; * } * }; @endcode * It would be used with the asio::connect function as follows: * @code tcp::resolver r(my_context); * tcp::resolver::query q("host", "service"); * tcp::socket s(my_context); * * // ... * * r.async_resolve(q, resolve_handler); * * // ... * * void resolve_handler( * const asio::error_code& ec, * tcp::resolver::iterator i) * { * if (!ec) * { * tcp::resolver::iterator end; * asio::async_connect(s, i, end, * my_connect_condition(), * connect_handler); * } * } * * // ... * * void connect_handler( * const asio::error_code& ec, * tcp::resolver::iterator i) * { * if (ec) * { * // An error occurred. * } * else * { * std::cout << "Connected to: " << i->endpoint() << std::endl; * } * } @endcode * * @par Per-Operation Cancellation * This asynchronous operation supports cancellation for the following * asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * if they are also supported by the socket's @c async_connect operation. */ template <typename Protocol, typename Executor, typename Iterator, typename ConnectCondition, ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code, Iterator)) IteratorConnectToken = default_completion_token_t<Executor>> inline auto async_connect(basic_socket<Protocol, Executor>& s, Iterator begin, Iterator end, ConnectCondition connect_condition, IteratorConnectToken&& token = default_completion_token_t<Executor>(), constraint_t< is_connect_condition<ConnectCondition, Iterator>::value > = 0) -> decltype( async_initiate<IteratorConnectToken, void (asio::error_code, Iterator)>( declval<detail::initiate_async_iterator_connect<Protocol, Executor>>(), token, begin, end, connect_condition)) { return async_initiate<IteratorConnectToken, void (asio::error_code, Iterator)>( detail::initiate_async_iterator_connect<Protocol, Executor>(s), token, begin, end, connect_condition); } /*@}*/ } // namespace asio #include "asio/detail/pop_options.hpp" #include "asio/impl/connect.hpp" #endif // ASIO_CONNECT_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/buffered_write_stream.hpp
// // buffered_write_stream.hpp // ~~~~~~~~~~~~~~~~~~~~~~~~~ // // 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) // #ifndef ASIO_BUFFERED_WRITE_STREAM_HPP #define ASIO_BUFFERED_WRITE_STREAM_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include <cstddef> #include "asio/buffered_write_stream_fwd.hpp" #include "asio/buffer.hpp" #include "asio/completion_condition.hpp" #include "asio/detail/bind_handler.hpp" #include "asio/detail/buffered_stream_storage.hpp" #include "asio/detail/noncopyable.hpp" #include "asio/detail/type_traits.hpp" #include "asio/error.hpp" #include "asio/write.hpp" #include "asio/detail/push_options.hpp" namespace asio { namespace detail { template <typename> class initiate_async_buffered_flush; template <typename> class initiate_async_buffered_write_some; } // namespace detail /// Adds buffering to the write-related operations of a stream. /** * The buffered_write_stream class template can be used to add buffering to the * synchronous and asynchronous write operations of a stream. * * @par Thread Safety * @e Distinct @e objects: Safe.@n * @e Shared @e objects: Unsafe. * * @par Concepts: * AsyncReadStream, AsyncWriteStream, Stream, SyncReadStream, SyncWriteStream. */ template <typename Stream> class buffered_write_stream : private noncopyable { public: /// The type of the next layer. typedef remove_reference_t<Stream> next_layer_type; /// The type of the lowest layer. typedef typename next_layer_type::lowest_layer_type lowest_layer_type; /// The type of the executor associated with the object. typedef typename lowest_layer_type::executor_type executor_type; #if defined(GENERATING_DOCUMENTATION) /// The default buffer size. static const std::size_t default_buffer_size = implementation_defined; #else ASIO_STATIC_CONSTANT(std::size_t, default_buffer_size = 1024); #endif /// Construct, passing the specified argument to initialise the next layer. template <typename Arg> explicit buffered_write_stream(Arg&& a) : next_layer_(static_cast<Arg&&>(a)), storage_(default_buffer_size) { } /// Construct, passing the specified argument to initialise the next layer. template <typename Arg> buffered_write_stream(Arg&& a, std::size_t buffer_size) : next_layer_(static_cast<Arg&&>(a)), storage_(buffer_size) { } /// Get a reference to the next layer. next_layer_type& next_layer() { return next_layer_; } /// Get a reference to the lowest layer. lowest_layer_type& lowest_layer() { return next_layer_.lowest_layer(); } /// Get a const reference to the lowest layer. const lowest_layer_type& lowest_layer() const { return next_layer_.lowest_layer(); } /// Get the executor associated with the object. executor_type get_executor() noexcept { return next_layer_.lowest_layer().get_executor(); } /// Close the stream. void close() { next_layer_.close(); } /// Close the stream. ASIO_SYNC_OP_VOID close(asio::error_code& ec) { next_layer_.close(ec); ASIO_SYNC_OP_VOID_RETURN(ec); } /// Flush all data from the buffer to the next layer. Returns the number of /// bytes written to the next layer on the last write operation. Throws an /// exception on failure. std::size_t flush(); /// Flush all data from the buffer to the next layer. Returns the number of /// bytes written to the next layer on the last write operation, or 0 if an /// error occurred. std::size_t flush(asio::error_code& ec); /// Start an asynchronous flush. /** * @par Completion Signature * @code void(asio::error_code, std::size_t) @endcode */ template < ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code, std::size_t)) WriteHandler = default_completion_token_t<executor_type>> auto async_flush( WriteHandler&& handler = default_completion_token_t<executor_type>()) -> decltype( async_initiate<WriteHandler, void (asio::error_code, std::size_t)>( declval<detail::initiate_async_buffered_flush<Stream>>(), handler, declval<detail::buffered_stream_storage*>())); /// Write the given data to the stream. Returns the number of bytes written. /// Throws an exception on failure. template <typename ConstBufferSequence> std::size_t write_some(const ConstBufferSequence& buffers); /// Write the given data to the stream. Returns the number of bytes written, /// or 0 if an error occurred and the error handler did not throw. template <typename ConstBufferSequence> std::size_t write_some(const ConstBufferSequence& buffers, asio::error_code& ec); /// Start an asynchronous write. The data being written must be valid for the /// lifetime of the asynchronous operation. /** * @par Completion Signature * @code void(asio::error_code, std::size_t) @endcode */ template <typename ConstBufferSequence, ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code, std::size_t)) WriteHandler = default_completion_token_t<executor_type>> auto async_write_some(const ConstBufferSequence& buffers, WriteHandler&& handler = default_completion_token_t<executor_type>()) -> decltype( async_initiate<WriteHandler, void (asio::error_code, std::size_t)>( declval<detail::initiate_async_buffered_write_some<Stream>>(), handler, declval<detail::buffered_stream_storage*>(), buffers)); /// Read some data from the stream. Returns the number of bytes read. Throws /// an exception on failure. template <typename MutableBufferSequence> std::size_t read_some(const MutableBufferSequence& buffers) { return next_layer_.read_some(buffers); } /// Read some data from the stream. Returns the number of bytes read or 0 if /// an error occurred. template <typename MutableBufferSequence> std::size_t read_some(const MutableBufferSequence& buffers, asio::error_code& ec) { return next_layer_.read_some(buffers, ec); } /// Start an asynchronous read. The buffer into which the data will be read /// must be valid for the lifetime of the asynchronous operation. /** * @par Completion Signature * @code void(asio::error_code, std::size_t) @endcode */ template <typename MutableBufferSequence, ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code, std::size_t)) ReadHandler = default_completion_token_t<executor_type>> auto async_read_some(const MutableBufferSequence& buffers, ReadHandler&& handler = default_completion_token_t<executor_type>()) -> decltype( declval<conditional_t<true, Stream&, ReadHandler>>().async_read_some( buffers, static_cast<ReadHandler&&>(handler))) { return next_layer_.async_read_some(buffers, static_cast<ReadHandler&&>(handler)); } /// Peek at the incoming data on the stream. Returns the number of bytes read. /// Throws an exception on failure. template <typename MutableBufferSequence> std::size_t peek(const MutableBufferSequence& buffers) { return next_layer_.peek(buffers); } /// Peek at the incoming data on the stream. Returns the number of bytes read, /// or 0 if an error occurred. template <typename MutableBufferSequence> std::size_t peek(const MutableBufferSequence& buffers, asio::error_code& ec) { return next_layer_.peek(buffers, ec); } /// Determine the amount of data that may be read without blocking. std::size_t in_avail() { return next_layer_.in_avail(); } /// Determine the amount of data that may be read without blocking. std::size_t in_avail(asio::error_code& ec) { return next_layer_.in_avail(ec); } private: /// Copy data into the internal buffer from the specified source buffer. /// Returns the number of bytes copied. template <typename ConstBufferSequence> std::size_t copy(const ConstBufferSequence& buffers); /// The next layer. Stream next_layer_; // The data in the buffer. detail::buffered_stream_storage storage_; }; } // namespace asio #include "asio/detail/pop_options.hpp" #include "asio/impl/buffered_write_stream.hpp" #endif // ASIO_BUFFERED_WRITE_STREAM_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/immediate.hpp
// // immediate.hpp // ~~~~~~~~~~~~~ // // 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) // #ifndef ASIO_IMMEDIATE_HPP #define ASIO_IMMEDIATE_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include "asio/associated_immediate_executor.hpp" #include "asio/async_result.hpp" #include "asio/dispatch.hpp" #include "asio/detail/push_options.hpp" namespace asio { namespace detail { template <typename Executor> class initiate_immediate { public: typedef Executor executor_type; explicit initiate_immediate(const Executor& ex) : ex_(ex) { } executor_type get_executor() const noexcept { return ex_; } template <typename CompletionHandler> void operator()(CompletionHandler&& handler) const { typename associated_immediate_executor< CompletionHandler, executor_type>::type ex = (get_associated_immediate_executor)(handler, ex_); (dispatch)(ex, static_cast<CompletionHandler&&>(handler)); } private: Executor ex_; }; } // namespace detail /// Launch a trivial asynchronous operation that completes immediately. /** * The async_immediate function is intended for use by composed operations, * which can delegate to this operation in order to implement the correct * semantics for immediate completion. * * @param ex The asynchronous operation's I/O executor. * * @param token The completion token. * * The completion handler is immediately submitted for execution by calling * asio::dispatch() on the handler's associated immediate executor. * * If the completion handler does not have a customised associated immediate * executor, then the handler is submitted as if by calling asio::post() * on the supplied I/O executor. * * @par Completion Signature * @code void() @endcode */ template <typename Executor, ASIO_COMPLETION_TOKEN_FOR(void()) NullaryToken = default_completion_token_t<Executor>> inline auto async_immediate(const Executor& ex, NullaryToken&& token = default_completion_token_t<Executor>(), constraint_t< (execution::is_executor<Executor>::value && can_require<Executor, execution::blocking_t::never_t>::value) || is_executor<Executor>::value > = 0) -> decltype( async_initiate<NullaryToken, void()>( declval<detail::initiate_immediate<Executor>>(), token)) { return async_initiate<NullaryToken, void()>( detail::initiate_immediate<Executor>(ex), token); } /// Launch a trivial asynchronous operation that completes immediately. /** * The async_immediate function is intended for use by composed operations, * which can delegate to this operation in order to implement the correct * semantics for immediate completion. * * @param ex The execution context used to obtain the asynchronous operation's * I/O executor. * * @param token The completion token. * * The completion handler is immediately submitted for execution by calling * asio::dispatch() on the handler's associated immediate executor. * * If the completion handler does not have a customised associated immediate * executor, then the handler is submitted as if by calling asio::post() * on the I/O executor obtained from the supplied execution context. * * @par Completion Signature * @code void() @endcode */ template <typename ExecutionContext, ASIO_COMPLETION_TOKEN_FOR(void()) NullaryToken = default_completion_token_t<typename ExecutionContext::executor_type>> inline auto async_immediate(ExecutionContext& ctx, NullaryToken&& token = default_completion_token_t< typename ExecutionContext::executor_type>(), constraint_t< is_convertible<ExecutionContext&, execution_context&>::value > = 0) -> decltype( async_initiate<NullaryToken, void()>( declval<detail::initiate_immediate< typename ExecutionContext::executor_type>>(), token)) { return async_initiate<NullaryToken, void()>( detail::initiate_immediate< typename ExecutionContext::executor_type>( ctx.get_executor()), token); } } // namespace asio #include "asio/detail/pop_options.hpp" #endif // ASIO_IMMEDIATE_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/write_at.hpp
// // write_at.hpp // ~~~~~~~~~~~~ // // 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) // #ifndef ASIO_WRITE_AT_HPP #define ASIO_WRITE_AT_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include <cstddef> #include "asio/async_result.hpp" #include "asio/completion_condition.hpp" #include "asio/detail/cstdint.hpp" #include "asio/error.hpp" #if !defined(ASIO_NO_EXTENSIONS) # include "asio/basic_streambuf_fwd.hpp" #endif // !defined(ASIO_NO_EXTENSIONS) #include "asio/detail/push_options.hpp" namespace asio { namespace detail { template <typename> class initiate_async_write_at; #if !defined(ASIO_NO_IOSTREAM) template <typename> class initiate_async_write_at_streambuf; #endif // !defined(ASIO_NO_IOSTREAM) } // namespace detail /** * @defgroup write_at asio::write_at * * @brief The @c write_at function is a composed operation that writes a * certain amount of data at a specified offset before returning. */ /*@{*/ /// Write all of the supplied data at the specified offset before returning. /** * This function is used to write a certain number of bytes of data to a random * access device at a specified offset. The call will block until one of the * following conditions is true: * * @li All of the data in the supplied buffers has been written. That is, the * bytes transferred is equal to the sum of the buffer sizes. * * @li An error occurred. * * This operation is implemented in terms of zero or more calls to the device's * write_some_at function. * * @param d The device to which the data is to be written. The type must support * the SyncRandomAccessWriteDevice concept. * * @param offset The offset at which the data will be written. * * @param buffers One or more buffers containing the data to be written. The sum * of the buffer sizes indicates the maximum number of bytes to write to the * device. * * @returns The number of bytes transferred. * * @throws asio::system_error Thrown on failure. * * @par Example * To write a single data buffer use the @ref buffer function as follows: * @code asio::write_at(d, 42, asio::buffer(data, size)); @endcode * See the @ref buffer documentation for information on writing multiple * buffers in one go, and how to use it with arrays, boost::array or * std::vector. * * @note This overload is equivalent to calling: * @code asio::write_at( * d, offset, buffers, * asio::transfer_all()); @endcode */ template <typename SyncRandomAccessWriteDevice, typename ConstBufferSequence> std::size_t write_at(SyncRandomAccessWriteDevice& d, uint64_t offset, const ConstBufferSequence& buffers); /// Write all of the supplied data at the specified offset before returning. /** * This function is used to write a certain number of bytes of data to a random * access device at a specified offset. The call will block until one of the * following conditions is true: * * @li All of the data in the supplied buffers has been written. That is, the * bytes transferred is equal to the sum of the buffer sizes. * * @li An error occurred. * * This operation is implemented in terms of zero or more calls to the device's * write_some_at function. * * @param d The device to which the data is to be written. The type must support * the SyncRandomAccessWriteDevice concept. * * @param offset The offset at which the data will be written. * * @param buffers One or more buffers containing the data to be written. The sum * of the buffer sizes indicates the maximum number of bytes to write to the * device. * * @param ec Set to indicate what error occurred, if any. * * @returns The number of bytes transferred. * * @par Example * To write a single data buffer use the @ref buffer function as follows: * @code asio::write_at(d, 42, * asio::buffer(data, size), ec); @endcode * See the @ref buffer documentation for information on writing multiple * buffers in one go, and how to use it with arrays, boost::array or * std::vector. * * @note This overload is equivalent to calling: * @code asio::write_at( * d, offset, buffers, * asio::transfer_all(), ec); @endcode */ template <typename SyncRandomAccessWriteDevice, typename ConstBufferSequence> std::size_t write_at(SyncRandomAccessWriteDevice& d, uint64_t offset, const ConstBufferSequence& buffers, asio::error_code& ec); /// Write a certain amount of data at a specified offset before returning. /** * This function is used to write a certain number of bytes of data to a random * access device at a specified offset. The call will block until one of the * following conditions is true: * * @li All of the data in the supplied buffers has been written. That is, the * bytes transferred is equal to the sum of the buffer sizes. * * @li The completion_condition function object returns 0. * * This operation is implemented in terms of zero or more calls to the device's * write_some_at function. * * @param d The device to which the data is to be written. The type must support * the SyncRandomAccessWriteDevice concept. * * @param offset The offset at which the data will be written. * * @param buffers One or more buffers containing the data to be written. The sum * of the buffer sizes indicates the maximum number of bytes to write to the * device. * * @param completion_condition The function object to be called to determine * whether the write operation is complete. The signature of the function object * must be: * @code std::size_t completion_condition( * // Result of latest write_some_at operation. * const asio::error_code& error, * * // Number of bytes transferred so far. * std::size_t bytes_transferred * ); @endcode * A return value of 0 indicates that the write operation is complete. A * non-zero return value indicates the maximum number of bytes to be written on * the next call to the device's write_some_at function. * * @returns The number of bytes transferred. * * @throws asio::system_error Thrown on failure. * * @par Example * To write a single data buffer use the @ref buffer function as follows: * @code asio::write_at(d, 42, asio::buffer(data, size), * asio::transfer_at_least(32)); @endcode * See the @ref buffer documentation for information on writing multiple * buffers in one go, and how to use it with arrays, boost::array or * std::vector. */ template <typename SyncRandomAccessWriteDevice, typename ConstBufferSequence, typename CompletionCondition> std::size_t write_at(SyncRandomAccessWriteDevice& d, uint64_t offset, const ConstBufferSequence& buffers, CompletionCondition completion_condition, constraint_t< is_completion_condition<CompletionCondition>::value > = 0); /// Write a certain amount of data at a specified offset before returning. /** * This function is used to write a certain number of bytes of data to a random * access device at a specified offset. The call will block until one of the * following conditions is true: * * @li All of the data in the supplied buffers has been written. That is, the * bytes transferred is equal to the sum of the buffer sizes. * * @li The completion_condition function object returns 0. * * This operation is implemented in terms of zero or more calls to the device's * write_some_at function. * * @param d The device to which the data is to be written. The type must support * the SyncRandomAccessWriteDevice concept. * * @param offset The offset at which the data will be written. * * @param buffers One or more buffers containing the data to be written. The sum * of the buffer sizes indicates the maximum number of bytes to write to the * device. * * @param completion_condition The function object to be called to determine * whether the write operation is complete. The signature of the function object * must be: * @code std::size_t completion_condition( * // Result of latest write_some_at operation. * const asio::error_code& error, * * // Number of bytes transferred so far. * std::size_t bytes_transferred * ); @endcode * A return value of 0 indicates that the write operation is complete. A * non-zero return value indicates the maximum number of bytes to be written on * the next call to the device's write_some_at function. * * @param ec Set to indicate what error occurred, if any. * * @returns The number of bytes written. If an error occurs, returns the total * number of bytes successfully transferred prior to the error. */ template <typename SyncRandomAccessWriteDevice, typename ConstBufferSequence, typename CompletionCondition> std::size_t write_at(SyncRandomAccessWriteDevice& d, uint64_t offset, const ConstBufferSequence& buffers, CompletionCondition completion_condition, asio::error_code& ec, constraint_t< is_completion_condition<CompletionCondition>::value > = 0); #if !defined(ASIO_NO_EXTENSIONS) #if !defined(ASIO_NO_IOSTREAM) /// Write all of the supplied data at the specified offset before returning. /** * This function is used to write a certain number of bytes of data to a random * access device at a specified offset. The call will block until one of the * following conditions is true: * * @li All of the data in the supplied basic_streambuf has been written. * * @li An error occurred. * * This operation is implemented in terms of zero or more calls to the device's * write_some_at function. * * @param d The device to which the data is to be written. The type must support * the SyncRandomAccessWriteDevice concept. * * @param offset The offset at which the data will be written. * * @param b The basic_streambuf object from which data will be written. * * @returns The number of bytes transferred. * * @throws asio::system_error Thrown on failure. * * @note This overload is equivalent to calling: * @code asio::write_at( * d, 42, b, * asio::transfer_all()); @endcode */ template <typename SyncRandomAccessWriteDevice, typename Allocator> std::size_t write_at(SyncRandomAccessWriteDevice& d, uint64_t offset, basic_streambuf<Allocator>& b); /// Write all of the supplied data at the specified offset before returning. /** * This function is used to write a certain number of bytes of data to a random * access device at a specified offset. The call will block until one of the * following conditions is true: * * @li All of the data in the supplied basic_streambuf has been written. * * @li An error occurred. * * This operation is implemented in terms of zero or more calls to the device's * write_some_at function. * * @param d The device to which the data is to be written. The type must support * the SyncRandomAccessWriteDevice concept. * * @param offset The offset at which the data will be written. * * @param b The basic_streambuf object from which data will be written. * * @param ec Set to indicate what error occurred, if any. * * @returns The number of bytes transferred. * * @note This overload is equivalent to calling: * @code asio::write_at( * d, 42, b, * asio::transfer_all(), ec); @endcode */ template <typename SyncRandomAccessWriteDevice, typename Allocator> std::size_t write_at(SyncRandomAccessWriteDevice& d, uint64_t offset, basic_streambuf<Allocator>& b, asio::error_code& ec); /// Write a certain amount of data at a specified offset before returning. /** * This function is used to write a certain number of bytes of data to a random * access device at a specified offset. The call will block until one of the * following conditions is true: * * @li All of the data in the supplied basic_streambuf has been written. * * @li The completion_condition function object returns 0. * * This operation is implemented in terms of zero or more calls to the device's * write_some_at function. * * @param d The device to which the data is to be written. The type must support * the SyncRandomAccessWriteDevice concept. * * @param offset The offset at which the data will be written. * * @param b The basic_streambuf object from which data will be written. * * @param completion_condition The function object to be called to determine * whether the write operation is complete. The signature of the function object * must be: * @code std::size_t completion_condition( * // Result of latest write_some_at operation. * const asio::error_code& error, * * // Number of bytes transferred so far. * std::size_t bytes_transferred * ); @endcode * A return value of 0 indicates that the write operation is complete. A * non-zero return value indicates the maximum number of bytes to be written on * the next call to the device's write_some_at function. * * @returns The number of bytes transferred. * * @throws asio::system_error Thrown on failure. */ template <typename SyncRandomAccessWriteDevice, typename Allocator, typename CompletionCondition> std::size_t write_at(SyncRandomAccessWriteDevice& d, uint64_t offset, basic_streambuf<Allocator>& b, CompletionCondition completion_condition, constraint_t< is_completion_condition<CompletionCondition>::value > = 0); /// Write a certain amount of data at a specified offset before returning. /** * This function is used to write a certain number of bytes of data to a random * access device at a specified offset. The call will block until one of the * following conditions is true: * * @li All of the data in the supplied basic_streambuf has been written. * * @li The completion_condition function object returns 0. * * This operation is implemented in terms of zero or more calls to the device's * write_some_at function. * * @param d The device to which the data is to be written. The type must support * the SyncRandomAccessWriteDevice concept. * * @param offset The offset at which the data will be written. * * @param b The basic_streambuf object from which data will be written. * * @param completion_condition The function object to be called to determine * whether the write operation is complete. The signature of the function object * must be: * @code std::size_t completion_condition( * // Result of latest write_some_at operation. * const asio::error_code& error, * * // Number of bytes transferred so far. * std::size_t bytes_transferred * ); @endcode * A return value of 0 indicates that the write operation is complete. A * non-zero return value indicates the maximum number of bytes to be written on * the next call to the device's write_some_at function. * * @param ec Set to indicate what error occurred, if any. * * @returns The number of bytes written. If an error occurs, returns the total * number of bytes successfully transferred prior to the error. */ template <typename SyncRandomAccessWriteDevice, typename Allocator, typename CompletionCondition> std::size_t write_at(SyncRandomAccessWriteDevice& d, uint64_t offset, basic_streambuf<Allocator>& b, CompletionCondition completion_condition, asio::error_code& ec, constraint_t< is_completion_condition<CompletionCondition>::value > = 0); #endif // !defined(ASIO_NO_IOSTREAM) #endif // !defined(ASIO_NO_EXTENSIONS) /*@}*/ /** * @defgroup async_write_at asio::async_write_at * * @brief The @c async_write_at function is a composed asynchronous operation * that writes a certain amount of data at the specified offset before * completion. */ /*@{*/ /// Start an asynchronous operation to write all of the supplied data at the /// specified offset. /** * This function is used to asynchronously write a certain number of bytes of * data to a random access device at a specified offset. It is an initiating * function for an @ref asynchronous_operation, and always returns immediately. * The asynchronous operation will continue until one of the following * conditions is true: * * @li All of the data in the supplied buffers has been written. That is, the * bytes transferred is equal to the sum of the buffer sizes. * * @li An error occurred. * * This operation is implemented in terms of zero or more calls to the device's * async_write_some_at function, and is known as a <em>composed operation</em>. * The program must ensure that the device performs no <em>overlapping</em> * write operations (such as async_write_at, the device's async_write_some_at * function, or any other composed operations that perform writes) until this * operation completes. Operations are overlapping if the regions defined by * their offsets, and the numbers of bytes to write, intersect. * * @param d The device to which the data is to be written. The type must support * the AsyncRandomAccessWriteDevice concept. * * @param offset The offset at which the data will be written. * * @param buffers One or more buffers containing the data to be written. * Although the buffers object may be copied as necessary, ownership of the * underlying memory blocks is retained by the caller, which must guarantee * that they remain valid until the completion handler is called. * * @param token The @ref completion_token that will be used to produce a * completion handler, which will be called when the write completes. * Potential completion tokens include @ref use_future, @ref use_awaitable, * @ref yield_context, or a function object with the correct completion * signature. The function signature of the completion handler must be: * @code void handler( * // Result of operation. * const asio::error_code& error, * * // Number of bytes written from the buffers. If an error * // occurred, this will be less than the sum of the buffer sizes. * std::size_t bytes_transferred * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the completion handler will not be invoked from within this function. * On immediate completion, invocation of the handler will be performed in a * manner equivalent to using asio::async_immediate(). * * @par Completion Signature * @code void(asio::error_code, std::size_t) @endcode * * @par Example * To write a single data buffer use the @ref buffer function as follows: * @code * asio::async_write_at(d, 42, asio::buffer(data, size), handler); * @endcode * See the @ref buffer documentation for information on writing multiple * buffers in one go, and how to use it with arrays, boost::array or * std::vector. * * @par Per-Operation Cancellation * This asynchronous operation supports cancellation for the following * asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * if they are also supported by the @c AsyncRandomAccessWriteDevice type's * async_write_some_at operation. */ template <typename AsyncRandomAccessWriteDevice, typename ConstBufferSequence, ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code, std::size_t)) WriteToken = default_completion_token_t< typename AsyncRandomAccessWriteDevice::executor_type>> inline auto async_write_at(AsyncRandomAccessWriteDevice& d, uint64_t offset, const ConstBufferSequence& buffers, WriteToken&& token = default_completion_token_t< typename AsyncRandomAccessWriteDevice::executor_type>(), constraint_t< !is_completion_condition<WriteToken>::value > = 0) -> decltype( async_initiate<WriteToken, void (asio::error_code, std::size_t)>( declval<detail::initiate_async_write_at< AsyncRandomAccessWriteDevice>>(), token, offset, buffers, transfer_all())) { return async_initiate<WriteToken, void (asio::error_code, std::size_t)>( detail::initiate_async_write_at<AsyncRandomAccessWriteDevice>(d), token, offset, buffers, transfer_all()); } /// Start an asynchronous operation to write a certain amount of data at the /// specified offset. /** * This function is used to asynchronously write a certain number of bytes of * data to a random access device at a specified offset. It is an initiating * function for an @ref asynchronous_operation, and always returns immediately. * The asynchronous operation will continue until one of the following * conditions is true: * * @li All of the data in the supplied buffers has been written. That is, the * bytes transferred is equal to the sum of the buffer sizes. * * @li The completion_condition function object returns 0. * * This operation is implemented in terms of zero or more calls to the device's * async_write_some_at function, and is known as a <em>composed operation</em>. * The program must ensure that the device performs no <em>overlapping</em> * write operations (such as async_write_at, the device's async_write_some_at * function, or any other composed operations that perform writes) until this * operation completes. Operations are overlapping if the regions defined by * their offsets, and the numbers of bytes to write, intersect. * * @param d The device to which the data is to be written. The type must support * the AsyncRandomAccessWriteDevice concept. * * @param offset The offset at which the data will be written. * * @param buffers One or more buffers containing the data to be written. * Although the buffers object may be copied as necessary, ownership of the * underlying memory blocks is retained by the caller, which must guarantee * that they remain valid until the completion handler is called. * * @param completion_condition The function object to be called to determine * whether the write operation is complete. The signature of the function object * must be: * @code std::size_t completion_condition( * // Result of latest async_write_some_at operation. * const asio::error_code& error, * * // Number of bytes transferred so far. * std::size_t bytes_transferred * ); @endcode * A return value of 0 indicates that the write operation is complete. A * non-zero return value indicates the maximum number of bytes to be written on * the next call to the device's async_write_some_at function. * * @param token The @ref completion_token that will be used to produce a * completion handler, which will be called when the write completes. * Potential completion tokens include @ref use_future, @ref use_awaitable, * @ref yield_context, or a function object with the correct completion * signature. The function signature of the completion handler must be: * @code void handler( * // Result of operation. * const asio::error_code& error, * * // Number of bytes written from the buffers. If an error * // occurred, this will be less than the sum of the buffer sizes. * std::size_t bytes_transferred * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the completion handler will not be invoked from within this function. * On immediate completion, invocation of the handler will be performed in a * manner equivalent to using asio::async_immediate(). * * @par Completion Signature * @code void(asio::error_code, std::size_t) @endcode * * @par Example * To write a single data buffer use the @ref buffer function as follows: * @code asio::async_write_at(d, 42, * asio::buffer(data, size), * asio::transfer_at_least(32), * handler); @endcode * See the @ref buffer documentation for information on writing multiple * buffers in one go, and how to use it with arrays, boost::array or * std::vector. * * @par Per-Operation Cancellation * This asynchronous operation supports cancellation for the following * asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * if they are also supported by the @c AsyncRandomAccessWriteDevice type's * async_write_some_at operation. */ template <typename AsyncRandomAccessWriteDevice, typename ConstBufferSequence, typename CompletionCondition, ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code, std::size_t)) WriteToken = default_completion_token_t< typename AsyncRandomAccessWriteDevice::executor_type>> inline auto async_write_at(AsyncRandomAccessWriteDevice& d, uint64_t offset, const ConstBufferSequence& buffers, CompletionCondition completion_condition, WriteToken&& token = default_completion_token_t< typename AsyncRandomAccessWriteDevice::executor_type>(), constraint_t< is_completion_condition<CompletionCondition>::value > = 0) -> decltype( async_initiate<WriteToken, void (asio::error_code, std::size_t)>( declval<detail::initiate_async_write_at< AsyncRandomAccessWriteDevice>>(), token, offset, buffers, static_cast<CompletionCondition&&>(completion_condition))) { return async_initiate<WriteToken, void (asio::error_code, std::size_t)>( detail::initiate_async_write_at<AsyncRandomAccessWriteDevice>(d), token, offset, buffers, static_cast<CompletionCondition&&>(completion_condition)); } #if !defined(ASIO_NO_EXTENSIONS) #if !defined(ASIO_NO_IOSTREAM) /// Start an asynchronous operation to write all of the supplied data at the /// specified offset. /** * This function is used to asynchronously write a certain number of bytes of * data to a random access device at a specified offset. It is an initiating * function for an @ref asynchronous_operation, and always returns immediately. * The asynchronous operation will continue until one of the following * conditions is true: * * @li All of the data in the supplied basic_streambuf has been written. * * @li An error occurred. * * This operation is implemented in terms of zero or more calls to the device's * async_write_some_at function, and is known as a <em>composed operation</em>. * The program must ensure that the device performs no <em>overlapping</em> * write operations (such as async_write_at, the device's async_write_some_at * function, or any other composed operations that perform writes) until this * operation completes. Operations are overlapping if the regions defined by * their offsets, and the numbers of bytes to write, intersect. * * @param d The device to which the data is to be written. The type must support * the AsyncRandomAccessWriteDevice concept. * * @param offset The offset at which the data will be written. * * @param b A basic_streambuf object from which data will be written. Ownership * of the streambuf is retained by the caller, which must guarantee that it * remains valid until the completion handler is called. * * @param token The @ref completion_token that will be used to produce a * completion handler, which will be called when the write completes. * Potential completion tokens include @ref use_future, @ref use_awaitable, * @ref yield_context, or a function object with the correct completion * signature. The function signature of the completion handler must be: * @code void handler( * // Result of operation. * const asio::error_code& error, * * // Number of bytes written from the buffers. If an error * // occurred, this will be less than the sum of the buffer sizes. * std::size_t bytes_transferred * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the completion handler will not be invoked from within this function. * On immediate completion, invocation of the handler will be performed in a * manner equivalent to using asio::async_immediate(). * * @par Completion Signature * @code void(asio::error_code, std::size_t) @endcode * * @par Per-Operation Cancellation * This asynchronous operation supports cancellation for the following * asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * if they are also supported by the @c AsyncRandomAccessWriteDevice type's * async_write_some_at operation. */ template <typename AsyncRandomAccessWriteDevice, typename Allocator, ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code, std::size_t)) WriteToken = default_completion_token_t< typename AsyncRandomAccessWriteDevice::executor_type>> inline auto async_write_at(AsyncRandomAccessWriteDevice& d, uint64_t offset, basic_streambuf<Allocator>& b, WriteToken&& token = default_completion_token_t< typename AsyncRandomAccessWriteDevice::executor_type>(), constraint_t< !is_completion_condition<WriteToken>::value > = 0) -> decltype( async_initiate<WriteToken, void (asio::error_code, std::size_t)>( declval<detail::initiate_async_write_at_streambuf< AsyncRandomAccessWriteDevice>>(), token, offset, &b, transfer_all())) { return async_initiate<WriteToken, void (asio::error_code, std::size_t)>( detail::initiate_async_write_at_streambuf< AsyncRandomAccessWriteDevice>(d), token, offset, &b, transfer_all()); } /// Start an asynchronous operation to write a certain amount of data at the /// specified offset. /** * This function is used to asynchronously write a certain number of bytes of * data to a random access device at a specified offset. It is an initiating * function for an @ref asynchronous_operation, and always returns immediately. * The asynchronous operation will continue until one of the following * conditions is true: * * @li All of the data in the supplied basic_streambuf has been written. * * @li The completion_condition function object returns 0. * * This operation is implemented in terms of zero or more calls to the device's * async_write_some_at function, and is known as a <em>composed operation</em>. * The program must ensure that the device performs no <em>overlapping</em> * write operations (such as async_write_at, the device's async_write_some_at * function, or any other composed operations that perform writes) until this * operation completes. Operations are overlapping if the regions defined by * their offsets, and the numbers of bytes to write, intersect. * * @param d The device to which the data is to be written. The type must support * the AsyncRandomAccessWriteDevice concept. * * @param offset The offset at which the data will be written. * * @param b A basic_streambuf object from which data will be written. Ownership * of the streambuf is retained by the caller, which must guarantee that it * remains valid until the completion handler is called. * * @param completion_condition The function object to be called to determine * whether the write operation is complete. The signature of the function object * must be: * @code std::size_t completion_condition( * // Result of latest async_write_some_at operation. * const asio::error_code& error, * * // Number of bytes transferred so far. * std::size_t bytes_transferred * ); @endcode * A return value of 0 indicates that the write operation is complete. A * non-zero return value indicates the maximum number of bytes to be written on * the next call to the device's async_write_some_at function. * * @param token The @ref completion_token that will be used to produce a * completion handler, which will be called when the write completes. * Potential completion tokens include @ref use_future, @ref use_awaitable, * @ref yield_context, or a function object with the correct completion * signature. The function signature of the completion handler must be: * @code void handler( * // Result of operation. * const asio::error_code& error, * * // Number of bytes written from the buffers. If an error * // occurred, this will be less than the sum of the buffer sizes. * std::size_t bytes_transferred * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the completion handler will not be invoked from within this function. * On immediate completion, invocation of the handler will be performed in a * manner equivalent to using asio::async_immediate(). * * @par Completion Signature * @code void(asio::error_code, std::size_t) @endcode * * @par Per-Operation Cancellation * This asynchronous operation supports cancellation for the following * asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * if they are also supported by the @c AsyncRandomAccessWriteDevice type's * async_write_some_at operation. */ template <typename AsyncRandomAccessWriteDevice, typename Allocator, typename CompletionCondition, ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code, std::size_t)) WriteToken = default_completion_token_t< typename AsyncRandomAccessWriteDevice::executor_type>> inline auto async_write_at(AsyncRandomAccessWriteDevice& d, uint64_t offset, basic_streambuf<Allocator>& b, CompletionCondition completion_condition, WriteToken&& token = default_completion_token_t< typename AsyncRandomAccessWriteDevice::executor_type>(), constraint_t< is_completion_condition<CompletionCondition>::value > = 0) -> decltype( async_initiate<WriteToken, void (asio::error_code, std::size_t)>( declval<detail::initiate_async_write_at_streambuf< AsyncRandomAccessWriteDevice>>(), token, offset, &b, static_cast<CompletionCondition&&>(completion_condition))) { return async_initiate<WriteToken, void (asio::error_code, std::size_t)>( detail::initiate_async_write_at_streambuf< AsyncRandomAccessWriteDevice>(d), token, offset, &b, static_cast<CompletionCondition&&>(completion_condition)); } #endif // !defined(ASIO_NO_IOSTREAM) #endif // !defined(ASIO_NO_EXTENSIONS) /*@}*/ } // namespace asio #include "asio/detail/pop_options.hpp" #include "asio/impl/write_at.hpp" #endif // ASIO_WRITE_AT_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/use_future.hpp
// // use_future.hpp // ~~~~~~~~~~~~~~ // // 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) // #ifndef ASIO_USE_FUTURE_HPP #define ASIO_USE_FUTURE_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include "asio/detail/future.hpp" #if defined(ASIO_HAS_STD_FUTURE_CLASS) \ || defined(GENERATING_DOCUMENTATION) #include <memory> #include "asio/detail/type_traits.hpp" #include "asio/detail/push_options.hpp" namespace asio { namespace detail { template <typename Function, typename Allocator> class packaged_token; template <typename Function, typename Allocator, typename Result> class packaged_handler; } // namespace detail /// A @ref completion_token type that causes an asynchronous operation to return /// a future. /** * The use_future_t class is a completion token type that is used to indicate * that an asynchronous operation should return a std::future object. A * use_future_t object may be passed as a completion token to an asynchronous * operation, typically using the special value @c asio::use_future. For * example: * * @code std::future<std::size_t> my_future * = my_socket.async_read_some(my_buffer, asio::use_future); @endcode * * The initiating function (async_read_some in the above example) returns a * future that will receive the result of the operation. If the operation * completes with an error_code indicating failure, it is converted into a * system_error and passed back to the caller via the future. */ template <typename Allocator = std::allocator<void>> class use_future_t { public: /// The allocator type. The allocator is used when constructing the /// @c std::promise object for a given asynchronous operation. typedef Allocator allocator_type; /// Construct using default-constructed allocator. constexpr use_future_t() { } /// Construct using specified allocator. explicit use_future_t(const Allocator& allocator) : allocator_(allocator) { } #if !defined(ASIO_NO_DEPRECATED) /// (Deprecated: Use rebind().) Specify an alternate allocator. template <typename OtherAllocator> use_future_t<OtherAllocator> operator[](const OtherAllocator& allocator) const { return use_future_t<OtherAllocator>(allocator); } #endif // !defined(ASIO_NO_DEPRECATED) /// Specify an alternate allocator. template <typename OtherAllocator> use_future_t<OtherAllocator> rebind(const OtherAllocator& allocator) const { return use_future_t<OtherAllocator>(allocator); } /// Obtain allocator. allocator_type get_allocator() const { return allocator_; } /// Wrap a function object in a packaged task. /** * The @c package function is used to adapt a function object as a packaged * task. When this adapter is passed as a completion token to an asynchronous * operation, the result of the function object is retuned via a std::future. * * @par Example * * @code std::future<std::size_t> fut = * my_socket.async_read_some(buffer, * use_future([](asio::error_code ec, std::size_t n) * { * return ec ? 0 : n; * })); * ... * std::size_t n = fut.get(); @endcode */ template <typename Function> #if defined(GENERATING_DOCUMENTATION) unspecified #else // defined(GENERATING_DOCUMENTATION) detail::packaged_token<decay_t<Function>, Allocator> #endif // defined(GENERATING_DOCUMENTATION) operator()(Function&& f) const; private: // Helper type to ensure that use_future can be constexpr default-constructed // even when std::allocator<void> can't be. struct std_allocator_void { constexpr std_allocator_void() { } operator std::allocator<void>() const { return std::allocator<void>(); } }; conditional_t< is_same<std::allocator<void>, Allocator>::value, std_allocator_void, Allocator> allocator_; }; /// A @ref completion_token object that causes an asynchronous operation to /// return a future. /** * See the documentation for asio::use_future_t for a usage example. */ ASIO_INLINE_VARIABLE constexpr use_future_t<> use_future; } // namespace asio #include "asio/detail/pop_options.hpp" #include "asio/impl/use_future.hpp" #endif // defined(ASIO_HAS_STD_FUTURE_CLASS) // || defined(GENERATING_DOCUMENTATION) #endif // ASIO_USE_FUTURE_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/serial_port_base.hpp
// // serial_port_base.hpp // ~~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // Copyright (c) 2008 Rep Invariant Systems, Inc. ([email protected]) // // 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) // #ifndef ASIO_SERIAL_PORT_BASE_HPP #define ASIO_SERIAL_PORT_BASE_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #if defined(ASIO_HAS_SERIAL_PORT) \ || defined(GENERATING_DOCUMENTATION) #if !defined(ASIO_WINDOWS) && !defined(__CYGWIN__) # include <termios.h> #endif // !defined(ASIO_WINDOWS) && !defined(__CYGWIN__) #include "asio/detail/socket_types.hpp" #include "asio/error_code.hpp" #if defined(GENERATING_DOCUMENTATION) # define ASIO_OPTION_STORAGE implementation_defined #elif defined(ASIO_WINDOWS) || defined(__CYGWIN__) # define ASIO_OPTION_STORAGE DCB #else # define ASIO_OPTION_STORAGE termios #endif #include "asio/detail/push_options.hpp" namespace asio { /// The serial_port_base class is used as a base for the basic_serial_port class /// template so that we have a common place to define the serial port options. class serial_port_base { public: /// Serial port option to permit changing the baud rate. /** * Implements changing the baud rate for a given serial port. */ class baud_rate { public: explicit baud_rate(unsigned int rate = 0); unsigned int value() const; ASIO_DECL ASIO_SYNC_OP_VOID store( ASIO_OPTION_STORAGE& storage, asio::error_code& ec) const; ASIO_DECL ASIO_SYNC_OP_VOID load( const ASIO_OPTION_STORAGE& storage, asio::error_code& ec); private: unsigned int value_; }; /// Serial port option to permit changing the flow control. /** * Implements changing the flow control for a given serial port. */ class flow_control { public: enum type { none, software, hardware }; ASIO_DECL explicit flow_control(type t = none); type value() const; ASIO_DECL ASIO_SYNC_OP_VOID store( ASIO_OPTION_STORAGE& storage, asio::error_code& ec) const; ASIO_DECL ASIO_SYNC_OP_VOID load( const ASIO_OPTION_STORAGE& storage, asio::error_code& ec); private: type value_; }; /// Serial port option to permit changing the parity. /** * Implements changing the parity for a given serial port. */ class parity { public: enum type { none, odd, even }; ASIO_DECL explicit parity(type t = none); type value() const; ASIO_DECL ASIO_SYNC_OP_VOID store( ASIO_OPTION_STORAGE& storage, asio::error_code& ec) const; ASIO_DECL ASIO_SYNC_OP_VOID load( const ASIO_OPTION_STORAGE& storage, asio::error_code& ec); private: type value_; }; /// Serial port option to permit changing the number of stop bits. /** * Implements changing the number of stop bits for a given serial port. */ class stop_bits { public: enum type { one, onepointfive, two }; ASIO_DECL explicit stop_bits(type t = one); type value() const; ASIO_DECL ASIO_SYNC_OP_VOID store( ASIO_OPTION_STORAGE& storage, asio::error_code& ec) const; ASIO_DECL ASIO_SYNC_OP_VOID load( const ASIO_OPTION_STORAGE& storage, asio::error_code& ec); private: type value_; }; /// Serial port option to permit changing the character size. /** * Implements changing the character size for a given serial port. */ class character_size { public: ASIO_DECL explicit character_size(unsigned int t = 8); unsigned int value() const; ASIO_DECL ASIO_SYNC_OP_VOID store( ASIO_OPTION_STORAGE& storage, asio::error_code& ec) const; ASIO_DECL ASIO_SYNC_OP_VOID load( const ASIO_OPTION_STORAGE& storage, asio::error_code& ec); private: unsigned int value_; }; protected: /// Protected destructor to prevent deletion through this type. ~serial_port_base() { } }; } // namespace asio #include "asio/detail/pop_options.hpp" #undef ASIO_OPTION_STORAGE #include "asio/impl/serial_port_base.hpp" #if defined(ASIO_HEADER_ONLY) # include "asio/impl/serial_port_base.ipp" #endif // defined(ASIO_HEADER_ONLY) #endif // defined(ASIO_HAS_SERIAL_PORT) // || defined(GENERATING_DOCUMENTATION) #endif // ASIO_SERIAL_PORT_BASE_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/require_concept.hpp
// // require_concept.hpp // ~~~~~~~~~~~~~~~~~~~ // // 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) // #ifndef ASIO_REQUIRE_CONCEPT_HPP #define ASIO_REQUIRE_CONCEPT_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include "asio/detail/type_traits.hpp" #include "asio/is_applicable_property.hpp" #include "asio/traits/require_concept_member.hpp" #include "asio/traits/require_concept_free.hpp" #include "asio/traits/static_require_concept.hpp" #include "asio/detail/push_options.hpp" #if defined(GENERATING_DOCUMENTATION) namespace asio { /// A customisation point that applies a concept-enforcing property to an /// object. /** * The name <tt>require_concept</tt> denotes a customization point object. The * expression <tt>asio::require_concept(E, P)</tt> for some * subexpressions <tt>E</tt> and <tt>P</tt> (with types <tt>T = * decay_t<decltype(E)></tt> and <tt>Prop = decay_t<decltype(P)></tt>) is * expression-equivalent to: * * @li If <tt>is_applicable_property_v<T, Prop> && * Prop::is_requirable_concept</tt> is not a well-formed constant expression * with value <tt>true</tt>, <tt>asio::require_concept(E, P)</tt> is * ill-formed. * * @li Otherwise, <tt>E</tt> if the expression <tt>Prop::template * static_query_v<T> == Prop::value()</tt> is a well-formed constant * expression with value <tt>true</tt>. * * @li Otherwise, <tt>(E).require_concept(P)</tt> if the expression * <tt>(E).require_concept(P)</tt> is well-formed. * * @li Otherwise, <tt>require_concept(E, P)</tt> if the expression * <tt>require_concept(E, P)</tt> is a valid expression with overload * resolution performed in a context that does not include the declaration * of the <tt>require_concept</tt> customization point object. * * @li Otherwise, <tt>asio::require_concept(E, P)</tt> is ill-formed. */ inline constexpr unspecified require_concept = unspecified; /// A type trait that determines whether a @c require_concept expression is /// well-formed. /** * Class template @c can_require_concept is a trait that is derived from * @c true_type if the expression * <tt>asio::require_concept(std::declval<T>(), * std::declval<Property>())</tt> is well formed; otherwise @c false_type. */ template <typename T, typename Property> struct can_require_concept : integral_constant<bool, automatically_determined> { }; /// A type trait that determines whether a @c require_concept expression will /// not throw. /** * Class template @c is_nothrow_require_concept is a trait that is derived from * @c true_type if the expression * <tt>asio::require_concept(std::declval<T>(), * std::declval<Property>())</tt> is @c noexcept; otherwise @c false_type. */ template <typename T, typename Property> struct is_nothrow_require_concept : integral_constant<bool, automatically_determined> { }; /// A type trait that determines the result type of a @c require_concept /// expression. /** * Class template @c require_concept_result is a trait that determines the * result type of the expression * <tt>asio::require_concept(std::declval<T>(), * std::declval<Property>())</tt>. */ template <typename T, typename Property> struct require_concept_result { /// The result of the @c require_concept expression. typedef automatically_determined type; }; } // namespace asio #else // defined(GENERATING_DOCUMENTATION) namespace asio_require_concept_fn { using asio::conditional_t; using asio::decay_t; using asio::declval; using asio::enable_if_t; using asio::is_applicable_property; using asio::traits::require_concept_free; using asio::traits::require_concept_member; using asio::traits::static_require_concept; void require_concept(); enum overload_type { identity, call_member, call_free, ill_formed }; template <typename Impl, typename T, typename Properties, typename = void, typename = void, typename = void, typename = void, typename = void> struct call_traits { static constexpr overload_type overload = ill_formed; static constexpr bool is_noexcept = false; typedef void result_type; }; template <typename Impl, typename T, typename Property> struct call_traits<Impl, T, void(Property), enable_if_t< is_applicable_property< decay_t<T>, decay_t<Property> >::value >, enable_if_t< decay_t<Property>::is_requirable_concept >, enable_if_t< static_require_concept<T, Property>::is_valid >> { static constexpr overload_type overload = identity; static constexpr bool is_noexcept = true; typedef T&& result_type; }; template <typename Impl, typename T, typename Property> struct call_traits<Impl, T, void(Property), enable_if_t< is_applicable_property< decay_t<T>, decay_t<Property> >::value >, enable_if_t< decay_t<Property>::is_requirable_concept >, enable_if_t< !static_require_concept<T, Property>::is_valid >, enable_if_t< require_concept_member< typename Impl::template proxy<T>::type, Property >::is_valid >> : require_concept_member< typename Impl::template proxy<T>::type, Property > { static constexpr overload_type overload = call_member; }; template <typename Impl, typename T, typename Property> struct call_traits<Impl, T, void(Property), enable_if_t< is_applicable_property< decay_t<T>, decay_t<Property> >::value >, enable_if_t< decay_t<Property>::is_requirable_concept >, enable_if_t< !static_require_concept<T, Property>::is_valid >, enable_if_t< !require_concept_member< typename Impl::template proxy<T>::type, Property >::is_valid >, enable_if_t< require_concept_free<T, Property>::is_valid >> : require_concept_free<T, Property> { static constexpr overload_type overload = call_free; }; struct impl { template <typename T> struct proxy { #if defined(ASIO_HAS_DEDUCED_REQUIRE_CONCEPT_MEMBER_TRAIT) struct type { template <typename P> auto require_concept(P&& p) noexcept( noexcept( declval<conditional_t<true, T, P>>().require_concept( static_cast<P&&>(p)) ) ) -> decltype( declval<conditional_t<true, T, P>>().require_concept( static_cast<P&&>(p)) ); }; #else // defined(ASIO_HAS_DEDUCED_REQUIRE_CONCEPT_MEMBER_TRAIT) typedef T type; #endif // defined(ASIO_HAS_DEDUCED_REQUIRE_CONCEPT_MEMBER_TRAIT) }; template <typename T, typename Property> ASIO_NODISCARD constexpr enable_if_t< call_traits<impl, T, void(Property)>::overload == identity, typename call_traits<impl, T, void(Property)>::result_type > operator()(T&& t, Property&&) const noexcept(call_traits<impl, T, void(Property)>::is_noexcept) { return static_cast<T&&>(t); } template <typename T, typename Property> ASIO_NODISCARD constexpr enable_if_t< call_traits<impl, T, void(Property)>::overload == call_member, typename call_traits<impl, T, void(Property)>::result_type > operator()(T&& t, Property&& p) const noexcept(call_traits<impl, T, void(Property)>::is_noexcept) { return static_cast<T&&>(t).require_concept(static_cast<Property&&>(p)); } template <typename T, typename Property> ASIO_NODISCARD constexpr enable_if_t< call_traits<impl, T, void(Property)>::overload == call_free, typename call_traits<impl, T, void(Property)>::result_type > operator()(T&& t, Property&& p) const noexcept(call_traits<impl, T, void(Property)>::is_noexcept) { return require_concept(static_cast<T&&>(t), static_cast<Property&&>(p)); } }; template <typename T = impl> struct static_instance { static const T instance; }; template <typename T> const T static_instance<T>::instance = {}; } // namespace asio_require_concept_fn namespace asio { namespace { static constexpr const asio_require_concept_fn::impl& require_concept = asio_require_concept_fn::static_instance<>::instance; } // namespace typedef asio_require_concept_fn::impl require_concept_t; template <typename T, typename Property> struct can_require_concept : integral_constant<bool, asio_require_concept_fn::call_traits< require_concept_t, T, void(Property)>::overload != asio_require_concept_fn::ill_formed> { }; #if defined(ASIO_HAS_VARIABLE_TEMPLATES) template <typename T, typename Property> constexpr bool can_require_concept_v = can_require_concept<T, Property>::value; #endif // defined(ASIO_HAS_VARIABLE_TEMPLATES) template <typename T, typename Property> struct is_nothrow_require_concept : integral_constant<bool, asio_require_concept_fn::call_traits< require_concept_t, T, void(Property)>::is_noexcept> { }; #if defined(ASIO_HAS_VARIABLE_TEMPLATES) template <typename T, typename Property> constexpr bool is_nothrow_require_concept_v = is_nothrow_require_concept<T, Property>::value; #endif // defined(ASIO_HAS_VARIABLE_TEMPLATES) template <typename T, typename Property> struct require_concept_result { typedef typename asio_require_concept_fn::call_traits< require_concept_t, T, void(Property)>::result_type type; }; template <typename T, typename Property> using require_concept_result_t = typename require_concept_result<T, Property>::type; } // namespace asio #endif // defined(GENERATING_DOCUMENTATION) #include "asio/detail/pop_options.hpp" #endif // ASIO_REQUIRE_CONCEPT_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/error.hpp
// // error.hpp // ~~~~~~~~~ // // 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) // #ifndef ASIO_ERROR_HPP #define ASIO_ERROR_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include "asio/error_code.hpp" #include "asio/system_error.hpp" #if defined(ASIO_WINDOWS) \ || defined(__CYGWIN__) \ || defined(ASIO_WINDOWS_RUNTIME) # include <winerror.h> #else # include <cerrno> # include <netdb.h> #endif #if defined(GENERATING_DOCUMENTATION) /// INTERNAL ONLY. # define ASIO_NATIVE_ERROR(e) implementation_defined /// INTERNAL ONLY. # define ASIO_SOCKET_ERROR(e) implementation_defined /// INTERNAL ONLY. # define ASIO_NETDB_ERROR(e) implementation_defined /// INTERNAL ONLY. # define ASIO_GETADDRINFO_ERROR(e) implementation_defined /// INTERNAL ONLY. # define ASIO_WIN_OR_POSIX(e_win, e_posix) implementation_defined #elif defined(ASIO_WINDOWS_RUNTIME) # define ASIO_NATIVE_ERROR(e) __HRESULT_FROM_WIN32(e) # define ASIO_SOCKET_ERROR(e) __HRESULT_FROM_WIN32(WSA ## e) # define ASIO_NETDB_ERROR(e) __HRESULT_FROM_WIN32(WSA ## e) # define ASIO_GETADDRINFO_ERROR(e) __HRESULT_FROM_WIN32(WSA ## e) # define ASIO_WIN_OR_POSIX(e_win, e_posix) e_win #elif defined(ASIO_WINDOWS) || defined(__CYGWIN__) # define ASIO_NATIVE_ERROR(e) e # define ASIO_SOCKET_ERROR(e) WSA ## e # define ASIO_NETDB_ERROR(e) WSA ## e # define ASIO_GETADDRINFO_ERROR(e) WSA ## e # define ASIO_WIN_OR_POSIX(e_win, e_posix) e_win #else # define ASIO_NATIVE_ERROR(e) e # define ASIO_SOCKET_ERROR(e) e # define ASIO_NETDB_ERROR(e) e # define ASIO_GETADDRINFO_ERROR(e) e # define ASIO_WIN_OR_POSIX(e_win, e_posix) e_posix #endif #include "asio/detail/push_options.hpp" namespace asio { namespace error { enum basic_errors { /// Permission denied. access_denied = ASIO_SOCKET_ERROR(EACCES), /// Address family not supported by protocol. address_family_not_supported = ASIO_SOCKET_ERROR(EAFNOSUPPORT), /// Address already in use. address_in_use = ASIO_SOCKET_ERROR(EADDRINUSE), /// Transport endpoint is already connected. already_connected = ASIO_SOCKET_ERROR(EISCONN), /// Operation already in progress. already_started = ASIO_SOCKET_ERROR(EALREADY), /// Broken pipe. broken_pipe = ASIO_WIN_OR_POSIX( ASIO_NATIVE_ERROR(ERROR_BROKEN_PIPE), ASIO_NATIVE_ERROR(EPIPE)), /// A connection has been aborted. connection_aborted = ASIO_SOCKET_ERROR(ECONNABORTED), /// Connection refused. connection_refused = ASIO_SOCKET_ERROR(ECONNREFUSED), /// Connection reset by peer. connection_reset = ASIO_SOCKET_ERROR(ECONNRESET), /// Bad file descriptor. bad_descriptor = ASIO_SOCKET_ERROR(EBADF), /// Bad address. fault = ASIO_SOCKET_ERROR(EFAULT), /// No route to host. host_unreachable = ASIO_SOCKET_ERROR(EHOSTUNREACH), /// Operation now in progress. in_progress = ASIO_SOCKET_ERROR(EINPROGRESS), /// Interrupted system call. interrupted = ASIO_SOCKET_ERROR(EINTR), /// Invalid argument. invalid_argument = ASIO_SOCKET_ERROR(EINVAL), /// Message too long. message_size = ASIO_SOCKET_ERROR(EMSGSIZE), /// The name was too long. name_too_long = ASIO_SOCKET_ERROR(ENAMETOOLONG), /// Network is down. network_down = ASIO_SOCKET_ERROR(ENETDOWN), /// Network dropped connection on reset. network_reset = ASIO_SOCKET_ERROR(ENETRESET), /// Network is unreachable. network_unreachable = ASIO_SOCKET_ERROR(ENETUNREACH), /// Too many open files. no_descriptors = ASIO_SOCKET_ERROR(EMFILE), /// No buffer space available. no_buffer_space = ASIO_SOCKET_ERROR(ENOBUFS), /// Cannot allocate memory. no_memory = ASIO_WIN_OR_POSIX( ASIO_NATIVE_ERROR(ERROR_OUTOFMEMORY), ASIO_NATIVE_ERROR(ENOMEM)), /// Operation not permitted. no_permission = ASIO_WIN_OR_POSIX( ASIO_NATIVE_ERROR(ERROR_ACCESS_DENIED), ASIO_NATIVE_ERROR(EPERM)), /// Protocol not available. no_protocol_option = ASIO_SOCKET_ERROR(ENOPROTOOPT), /// No such device. no_such_device = ASIO_WIN_OR_POSIX( ASIO_NATIVE_ERROR(ERROR_BAD_UNIT), ASIO_NATIVE_ERROR(ENODEV)), /// Transport endpoint is not connected. not_connected = ASIO_SOCKET_ERROR(ENOTCONN), /// Socket operation on non-socket. not_socket = ASIO_SOCKET_ERROR(ENOTSOCK), /// Operation cancelled. operation_aborted = ASIO_WIN_OR_POSIX( ASIO_NATIVE_ERROR(ERROR_OPERATION_ABORTED), ASIO_NATIVE_ERROR(ECANCELED)), /// Operation not supported. operation_not_supported = ASIO_SOCKET_ERROR(EOPNOTSUPP), /// Cannot send after transport endpoint shutdown. shut_down = ASIO_SOCKET_ERROR(ESHUTDOWN), /// Connection timed out. timed_out = ASIO_SOCKET_ERROR(ETIMEDOUT), /// Resource temporarily unavailable. try_again = ASIO_WIN_OR_POSIX( ASIO_NATIVE_ERROR(ERROR_RETRY), ASIO_NATIVE_ERROR(EAGAIN)), /// The socket is marked non-blocking and the requested operation would block. would_block = ASIO_SOCKET_ERROR(EWOULDBLOCK) }; enum netdb_errors { /// Host not found (authoritative). host_not_found = ASIO_NETDB_ERROR(HOST_NOT_FOUND), /// Host not found (non-authoritative). host_not_found_try_again = ASIO_NETDB_ERROR(TRY_AGAIN), /// The query is valid but does not have associated address data. no_data = ASIO_NETDB_ERROR(NO_DATA), /// A non-recoverable error occurred. no_recovery = ASIO_NETDB_ERROR(NO_RECOVERY) }; enum addrinfo_errors { /// The service is not supported for the given socket type. service_not_found = ASIO_WIN_OR_POSIX( ASIO_NATIVE_ERROR(WSATYPE_NOT_FOUND), ASIO_GETADDRINFO_ERROR(EAI_SERVICE)), /// The socket type is not supported. socket_type_not_supported = ASIO_WIN_OR_POSIX( ASIO_NATIVE_ERROR(WSAESOCKTNOSUPPORT), ASIO_GETADDRINFO_ERROR(EAI_SOCKTYPE)) }; enum misc_errors { /// Already open. already_open = 1, /// End of file or stream. eof, /// Element not found. not_found, /// The descriptor cannot fit into the select system call's fd_set. fd_set_failure }; // boostify: non-boost code starts here #if !defined(ASIO_ERROR_LOCATION) # define ASIO_ERROR_LOCATION(e) (void)0 #endif // !defined(ASIO_ERROR_LOCATION) // boostify: non-boost code ends here #if !defined(ASIO_ERROR_LOCATION) \ && !defined(ASIO_DISABLE_ERROR_LOCATION) \ && defined(ASIO_HAS_BOOST_CONFIG) \ && (BOOST_VERSION >= 107900) # define ASIO_ERROR_LOCATION(e) \ do { \ BOOST_STATIC_CONSTEXPR boost::source_location loc \ = BOOST_CURRENT_LOCATION; \ (e).assign((e), &loc); \ } while (false) #else // !defined(ASIO_ERROR_LOCATION) // && !defined(ASIO_DISABLE_ERROR_LOCATION) // && defined(ASIO_HAS_BOOST_CONFIG) // && (BOOST_VERSION >= 107900) # define ASIO_ERROR_LOCATION(e) (void)0 #endif // !defined(ASIO_ERROR_LOCATION) // && !defined(ASIO_DISABLE_ERROR_LOCATION) // && defined(ASIO_HAS_BOOST_CONFIG) // && (BOOST_VERSION >= 107900) inline void clear(asio::error_code& ec) { ec.assign(0, ec.category()); } inline const asio::error_category& get_system_category() { return asio::system_category(); } #if !defined(ASIO_WINDOWS) && !defined(__CYGWIN__) extern ASIO_DECL const asio::error_category& get_netdb_category(); extern ASIO_DECL const asio::error_category& get_addrinfo_category(); #else // !defined(ASIO_WINDOWS) && !defined(__CYGWIN__) inline const asio::error_category& get_netdb_category() { return get_system_category(); } inline const asio::error_category& get_addrinfo_category() { return get_system_category(); } #endif // !defined(ASIO_WINDOWS) && !defined(__CYGWIN__) extern ASIO_DECL const asio::error_category& get_misc_category(); static const asio::error_category& system_category ASIO_UNUSED_VARIABLE = asio::error::get_system_category(); static const asio::error_category& netdb_category ASIO_UNUSED_VARIABLE = asio::error::get_netdb_category(); static const asio::error_category& addrinfo_category ASIO_UNUSED_VARIABLE = asio::error::get_addrinfo_category(); static const asio::error_category& misc_category ASIO_UNUSED_VARIABLE = asio::error::get_misc_category(); } // namespace error } // namespace asio namespace std { template<> struct is_error_code_enum<asio::error::basic_errors> { static const bool value = true; }; template<> struct is_error_code_enum<asio::error::netdb_errors> { static const bool value = true; }; template<> struct is_error_code_enum<asio::error::addrinfo_errors> { static const bool value = true; }; template<> struct is_error_code_enum<asio::error::misc_errors> { static const bool value = true; }; } // namespace std namespace asio { namespace error { inline asio::error_code make_error_code(basic_errors e) { return asio::error_code( static_cast<int>(e), get_system_category()); } inline asio::error_code make_error_code(netdb_errors e) { return asio::error_code( static_cast<int>(e), get_netdb_category()); } inline asio::error_code make_error_code(addrinfo_errors e) { return asio::error_code( static_cast<int>(e), get_addrinfo_category()); } inline asio::error_code make_error_code(misc_errors e) { return asio::error_code( static_cast<int>(e), get_misc_category()); } } // namespace error namespace stream_errc { // Simulates the proposed stream_errc scoped enum. using error::eof; using error::not_found; } // namespace stream_errc namespace socket_errc { // Simulates the proposed socket_errc scoped enum. using error::already_open; using error::not_found; } // namespace socket_errc namespace resolver_errc { // Simulates the proposed resolver_errc scoped enum. using error::host_not_found; const error::netdb_errors try_again = error::host_not_found_try_again; using error::service_not_found; } // namespace resolver_errc } // namespace asio #include "asio/detail/pop_options.hpp" #undef ASIO_NATIVE_ERROR #undef ASIO_SOCKET_ERROR #undef ASIO_NETDB_ERROR #undef ASIO_GETADDRINFO_ERROR #undef ASIO_WIN_OR_POSIX #if defined(ASIO_HEADER_ONLY) # include "asio/impl/error.ipp" #endif // defined(ASIO_HEADER_ONLY) #endif // ASIO_ERROR_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/basic_deadline_timer.hpp
// // basic_deadline_timer.hpp // ~~~~~~~~~~~~~~~~~~~~~~~~ // // 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) // #ifndef ASIO_BASIC_DEADLINE_TIMER_HPP #define ASIO_BASIC_DEADLINE_TIMER_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #if defined(ASIO_HAS_BOOST_DATE_TIME) \ || defined(GENERATING_DOCUMENTATION) #include <cstddef> #include "asio/any_io_executor.hpp" #include "asio/detail/deadline_timer_service.hpp" #include "asio/detail/handler_type_requirements.hpp" #include "asio/detail/io_object_impl.hpp" #include "asio/detail/non_const_lvalue.hpp" #include "asio/detail/throw_error.hpp" #include "asio/error.hpp" #include "asio/execution_context.hpp" #include "asio/time_traits.hpp" #include "asio/detail/push_options.hpp" namespace asio { /// Provides waitable timer functionality. /** * The basic_deadline_timer class template provides the ability to perform a * blocking or asynchronous wait for a timer to expire. * * A deadline timer is always in one of two states: "expired" or "not expired". * If the wait() or async_wait() function is called on an expired timer, the * wait operation will complete immediately. * * Most applications will use the asio::deadline_timer typedef. * * @par Thread Safety * @e Distinct @e objects: Safe.@n * @e Shared @e objects: Unsafe. * * @par Examples * Performing a blocking wait: * @code * // Construct a timer without setting an expiry time. * asio::deadline_timer timer(my_context); * * // Set an expiry time relative to now. * timer.expires_from_now(boost::posix_time::seconds(5)); * * // Wait for the timer to expire. * timer.wait(); * @endcode * * @par * Performing an asynchronous wait: * @code * void handler(const asio::error_code& error) * { * if (!error) * { * // Timer expired. * } * } * * ... * * // Construct a timer with an absolute expiry time. * asio::deadline_timer timer(my_context, * boost::posix_time::time_from_string("2005-12-07 23:59:59.000")); * * // Start an asynchronous wait. * timer.async_wait(handler); * @endcode * * @par Changing an active deadline_timer's expiry time * * Changing the expiry time of a timer while there are pending asynchronous * waits causes those wait operations to be cancelled. To ensure that the action * associated with the timer is performed only once, use something like this: * used: * * @code * void on_some_event() * { * if (my_timer.expires_from_now(seconds(5)) > 0) * { * // We managed to cancel the timer. Start new asynchronous wait. * my_timer.async_wait(on_timeout); * } * else * { * // Too late, timer has already expired! * } * } * * void on_timeout(const asio::error_code& e) * { * if (e != asio::error::operation_aborted) * { * // Timer was not cancelled, take necessary action. * } * } * @endcode * * @li The asio::basic_deadline_timer::expires_from_now() function * cancels any pending asynchronous waits, and returns the number of * asynchronous waits that were cancelled. If it returns 0 then you were too * late and the wait handler has already been executed, or will soon be * executed. If it returns 1 then the wait handler was successfully cancelled. * * @li If a wait handler is cancelled, the asio::error_code passed to * it contains the value asio::error::operation_aborted. */ template <typename Time, typename TimeTraits = asio::time_traits<Time>, typename Executor = any_io_executor> class basic_deadline_timer { private: class initiate_async_wait; public: /// The type of the executor associated with the object. typedef Executor executor_type; /// Rebinds the timer type to another executor. template <typename Executor1> struct rebind_executor { /// The timer type when rebound to the specified executor. typedef basic_deadline_timer<Time, TimeTraits, Executor1> other; }; /// The time traits type. typedef TimeTraits traits_type; /// The time type. typedef typename traits_type::time_type time_type; /// The duration type. typedef typename traits_type::duration_type duration_type; /// Constructor. /** * This constructor creates a timer without setting an expiry time. The * expires_at() or expires_from_now() functions must be called to set an * expiry time before the timer can be waited on. * * @param ex The I/O executor that the timer will use, by default, to * dispatch handlers for any asynchronous operations performed on the timer. */ explicit basic_deadline_timer(const executor_type& ex) : impl_(0, ex) { } /// Constructor. /** * This constructor creates a timer without setting an expiry time. The * expires_at() or expires_from_now() functions must be called to set an * expiry time before the timer can be waited on. * * @param context An execution context which provides the I/O executor that * the timer will use, by default, to dispatch handlers for any asynchronous * operations performed on the timer. */ template <typename ExecutionContext> explicit basic_deadline_timer(ExecutionContext& context, constraint_t< is_convertible<ExecutionContext&, execution_context&>::value > = 0) : impl_(0, 0, context) { } /// Constructor to set a particular expiry time as an absolute time. /** * This constructor creates a timer and sets the expiry time. * * @param ex The I/O executor that the timer will use, by default, to * dispatch handlers for any asynchronous operations performed on the timer. * * @param expiry_time The expiry time to be used for the timer, expressed * as an absolute time. */ basic_deadline_timer(const executor_type& ex, const time_type& expiry_time) : impl_(0, ex) { asio::error_code ec; impl_.get_service().expires_at(impl_.get_implementation(), expiry_time, ec); asio::detail::throw_error(ec, "expires_at"); } /// Constructor to set a particular expiry time as an absolute time. /** * This constructor creates a timer and sets the expiry time. * * @param context An execution context which provides the I/O executor that * the timer will use, by default, to dispatch handlers for any asynchronous * operations performed on the timer. * * @param expiry_time The expiry time to be used for the timer, expressed * as an absolute time. */ template <typename ExecutionContext> basic_deadline_timer(ExecutionContext& context, const time_type& expiry_time, constraint_t< is_convertible<ExecutionContext&, execution_context&>::value > = 0) : impl_(0, 0, context) { asio::error_code ec; impl_.get_service().expires_at(impl_.get_implementation(), expiry_time, ec); asio::detail::throw_error(ec, "expires_at"); } /// Constructor to set a particular expiry time relative to now. /** * This constructor creates a timer and sets the expiry time. * * @param ex The I/O executor that the timer will use, by default, to * dispatch handlers for any asynchronous operations performed on the timer. * * @param expiry_time The expiry time to be used for the timer, relative to * now. */ basic_deadline_timer(const executor_type& ex, const duration_type& expiry_time) : impl_(0, ex) { asio::error_code ec; impl_.get_service().expires_from_now( impl_.get_implementation(), expiry_time, ec); asio::detail::throw_error(ec, "expires_from_now"); } /// Constructor to set a particular expiry time relative to now. /** * This constructor creates a timer and sets the expiry time. * * @param context An execution context which provides the I/O executor that * the timer will use, by default, to dispatch handlers for any asynchronous * operations performed on the timer. * * @param expiry_time The expiry time to be used for the timer, relative to * now. */ template <typename ExecutionContext> basic_deadline_timer(ExecutionContext& context, const duration_type& expiry_time, constraint_t< is_convertible<ExecutionContext&, execution_context&>::value > = 0) : impl_(0, 0, context) { asio::error_code ec; impl_.get_service().expires_from_now( impl_.get_implementation(), expiry_time, ec); asio::detail::throw_error(ec, "expires_from_now"); } /// Move-construct a basic_deadline_timer from another. /** * This constructor moves a timer from one object to another. * * @param other The other basic_deadline_timer object from which the move will * occur. * * @note Following the move, the moved-from object is in the same state as if * constructed using the @c basic_deadline_timer(const executor_type&) * constructor. */ basic_deadline_timer(basic_deadline_timer&& other) : impl_(std::move(other.impl_)) { } /// Move-assign a basic_deadline_timer from another. /** * This assignment operator moves a timer from one object to another. Cancels * any outstanding asynchronous operations associated with the target object. * * @param other The other basic_deadline_timer object from which the move will * occur. * * @note Following the move, the moved-from object is in the same state as if * constructed using the @c basic_deadline_timer(const executor_type&) * constructor. */ basic_deadline_timer& operator=(basic_deadline_timer&& other) { impl_ = std::move(other.impl_); return *this; } /// Destroys the timer. /** * This function destroys the timer, cancelling any outstanding asynchronous * wait operations associated with the timer as if by calling @c cancel. */ ~basic_deadline_timer() { } /// Get the executor associated with the object. const executor_type& get_executor() noexcept { return impl_.get_executor(); } /// Cancel any asynchronous operations that are waiting on the timer. /** * This function forces the completion of any pending asynchronous wait * operations against the timer. The handler for each cancelled operation will * be invoked with the asio::error::operation_aborted error code. * * Cancelling the timer does not change the expiry time. * * @return The number of asynchronous operations that were cancelled. * * @throws asio::system_error Thrown on failure. * * @note If the timer has already expired when cancel() is called, then the * handlers for asynchronous wait operations will: * * @li have already been invoked; or * * @li have been queued for invocation in the near future. * * These handlers can no longer be cancelled, and therefore are passed an * error code that indicates the successful completion of the wait operation. */ std::size_t cancel() { asio::error_code ec; std::size_t s = impl_.get_service().cancel(impl_.get_implementation(), ec); asio::detail::throw_error(ec, "cancel"); return s; } /// Cancel any asynchronous operations that are waiting on the timer. /** * This function forces the completion of any pending asynchronous wait * operations against the timer. The handler for each cancelled operation will * be invoked with the asio::error::operation_aborted error code. * * Cancelling the timer does not change the expiry time. * * @param ec Set to indicate what error occurred, if any. * * @return The number of asynchronous operations that were cancelled. * * @note If the timer has already expired when cancel() is called, then the * handlers for asynchronous wait operations will: * * @li have already been invoked; or * * @li have been queued for invocation in the near future. * * These handlers can no longer be cancelled, and therefore are passed an * error code that indicates the successful completion of the wait operation. */ std::size_t cancel(asio::error_code& ec) { return impl_.get_service().cancel(impl_.get_implementation(), ec); } /// Cancels one asynchronous operation that is waiting on the timer. /** * This function forces the completion of one pending asynchronous wait * operation against the timer. Handlers are cancelled in FIFO order. The * handler for the cancelled operation will be invoked with the * asio::error::operation_aborted error code. * * Cancelling the timer does not change the expiry time. * * @return The number of asynchronous operations that were cancelled. That is, * either 0 or 1. * * @throws asio::system_error Thrown on failure. * * @note If the timer has already expired when cancel_one() is called, then * the handlers for asynchronous wait operations will: * * @li have already been invoked; or * * @li have been queued for invocation in the near future. * * These handlers can no longer be cancelled, and therefore are passed an * error code that indicates the successful completion of the wait operation. */ std::size_t cancel_one() { asio::error_code ec; std::size_t s = impl_.get_service().cancel_one( impl_.get_implementation(), ec); asio::detail::throw_error(ec, "cancel_one"); return s; } /// Cancels one asynchronous operation that is waiting on the timer. /** * This function forces the completion of one pending asynchronous wait * operation against the timer. Handlers are cancelled in FIFO order. The * handler for the cancelled operation will be invoked with the * asio::error::operation_aborted error code. * * Cancelling the timer does not change the expiry time. * * @param ec Set to indicate what error occurred, if any. * * @return The number of asynchronous operations that were cancelled. That is, * either 0 or 1. * * @note If the timer has already expired when cancel_one() is called, then * the handlers for asynchronous wait operations will: * * @li have already been invoked; or * * @li have been queued for invocation in the near future. * * These handlers can no longer be cancelled, and therefore are passed an * error code that indicates the successful completion of the wait operation. */ std::size_t cancel_one(asio::error_code& ec) { return impl_.get_service().cancel_one(impl_.get_implementation(), ec); } /// Get the timer's expiry time as an absolute time. /** * This function may be used to obtain the timer's current expiry time. * Whether the timer has expired or not does not affect this value. */ time_type expires_at() const { return impl_.get_service().expires_at(impl_.get_implementation()); } /// Set the timer's expiry time as an absolute time. /** * This function sets the expiry time. Any pending asynchronous wait * operations will be cancelled. The handler for each cancelled operation will * be invoked with the asio::error::operation_aborted error code. * * @param expiry_time The expiry time to be used for the timer. * * @return The number of asynchronous operations that were cancelled. * * @throws asio::system_error Thrown on failure. * * @note If the timer has already expired when expires_at() is called, then * the handlers for asynchronous wait operations will: * * @li have already been invoked; or * * @li have been queued for invocation in the near future. * * These handlers can no longer be cancelled, and therefore are passed an * error code that indicates the successful completion of the wait operation. */ std::size_t expires_at(const time_type& expiry_time) { asio::error_code ec; std::size_t s = impl_.get_service().expires_at( impl_.get_implementation(), expiry_time, ec); asio::detail::throw_error(ec, "expires_at"); return s; } /// Set the timer's expiry time as an absolute time. /** * This function sets the expiry time. Any pending asynchronous wait * operations will be cancelled. The handler for each cancelled operation will * be invoked with the asio::error::operation_aborted error code. * * @param expiry_time The expiry time to be used for the timer. * * @param ec Set to indicate what error occurred, if any. * * @return The number of asynchronous operations that were cancelled. * * @note If the timer has already expired when expires_at() is called, then * the handlers for asynchronous wait operations will: * * @li have already been invoked; or * * @li have been queued for invocation in the near future. * * These handlers can no longer be cancelled, and therefore are passed an * error code that indicates the successful completion of the wait operation. */ std::size_t expires_at(const time_type& expiry_time, asio::error_code& ec) { return impl_.get_service().expires_at( impl_.get_implementation(), expiry_time, ec); } /// Get the timer's expiry time relative to now. /** * This function may be used to obtain the timer's current expiry time. * Whether the timer has expired or not does not affect this value. */ duration_type expires_from_now() const { return impl_.get_service().expires_from_now(impl_.get_implementation()); } /// Set the timer's expiry time relative to now. /** * This function sets the expiry time. Any pending asynchronous wait * operations will be cancelled. The handler for each cancelled operation will * be invoked with the asio::error::operation_aborted error code. * * @param expiry_time The expiry time to be used for the timer. * * @return The number of asynchronous operations that were cancelled. * * @throws asio::system_error Thrown on failure. * * @note If the timer has already expired when expires_from_now() is called, * then the handlers for asynchronous wait operations will: * * @li have already been invoked; or * * @li have been queued for invocation in the near future. * * These handlers can no longer be cancelled, and therefore are passed an * error code that indicates the successful completion of the wait operation. */ std::size_t expires_from_now(const duration_type& expiry_time) { asio::error_code ec; std::size_t s = impl_.get_service().expires_from_now( impl_.get_implementation(), expiry_time, ec); asio::detail::throw_error(ec, "expires_from_now"); return s; } /// Set the timer's expiry time relative to now. /** * This function sets the expiry time. Any pending asynchronous wait * operations will be cancelled. The handler for each cancelled operation will * be invoked with the asio::error::operation_aborted error code. * * @param expiry_time The expiry time to be used for the timer. * * @param ec Set to indicate what error occurred, if any. * * @return The number of asynchronous operations that were cancelled. * * @note If the timer has already expired when expires_from_now() is called, * then the handlers for asynchronous wait operations will: * * @li have already been invoked; or * * @li have been queued for invocation in the near future. * * These handlers can no longer be cancelled, and therefore are passed an * error code that indicates the successful completion of the wait operation. */ std::size_t expires_from_now(const duration_type& expiry_time, asio::error_code& ec) { return impl_.get_service().expires_from_now( impl_.get_implementation(), expiry_time, ec); } /// Perform a blocking wait on the timer. /** * This function is used to wait for the timer to expire. This function * blocks and does not return until the timer has expired. * * @throws asio::system_error Thrown on failure. */ void wait() { asio::error_code ec; impl_.get_service().wait(impl_.get_implementation(), ec); asio::detail::throw_error(ec, "wait"); } /// Perform a blocking wait on the timer. /** * This function is used to wait for the timer to expire. This function * blocks and does not return until the timer has expired. * * @param ec Set to indicate what error occurred, if any. */ void wait(asio::error_code& ec) { impl_.get_service().wait(impl_.get_implementation(), ec); } /// Start an asynchronous wait on the timer. /** * This function may be used to initiate an asynchronous wait against the * timer. It is an initiating function for an @ref asynchronous_operation, * and always returns immediately. * * For each call to async_wait(), the completion handler will be called * exactly once. The completion handler will be called when: * * @li The timer has expired. * * @li The timer was cancelled, in which case the handler is passed the error * code asio::error::operation_aborted. * * @param token The @ref completion_token that will be used to produce a * completion handler, which will be called when the timer expires. Potential * completion tokens include @ref use_future, @ref use_awaitable, @ref * yield_context, or a function object with the correct completion signature. * The function signature of the completion handler must be: * @code void handler( * const asio::error_code& error // Result of operation. * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the completion handler will not be invoked from within this function. * On immediate completion, invocation of the handler will be performed in a * manner equivalent to using asio::async_immediate(). * * @par Completion Signature * @code void(asio::error_code) @endcode * * @par Per-Operation Cancellation * This asynchronous operation supports cancellation for the following * asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * @li @c cancellation_type::total */ template < ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code)) WaitToken = default_completion_token_t<executor_type>> auto async_wait( WaitToken&& token = default_completion_token_t<executor_type>()) -> decltype( async_initiate<WaitToken, void (asio::error_code)>( declval<initiate_async_wait>(), token)) { return async_initiate<WaitToken, void (asio::error_code)>( initiate_async_wait(this), token); } private: // Disallow copying and assignment. basic_deadline_timer(const basic_deadline_timer&) = delete; basic_deadline_timer& operator=( const basic_deadline_timer&) = delete; class initiate_async_wait { public: typedef Executor executor_type; explicit initiate_async_wait(basic_deadline_timer* self) : self_(self) { } const executor_type& get_executor() const noexcept { return self_->get_executor(); } template <typename WaitHandler> void operator()(WaitHandler&& handler) const { // If you get an error on the following line it means that your handler // does not meet the documented type requirements for a WaitHandler. ASIO_WAIT_HANDLER_CHECK(WaitHandler, handler) type_check; detail::non_const_lvalue<WaitHandler> handler2(handler); self_->impl_.get_service().async_wait( self_->impl_.get_implementation(), handler2.value, self_->impl_.get_executor()); } private: basic_deadline_timer* self_; }; detail::io_object_impl< detail::deadline_timer_service<TimeTraits>, Executor> impl_; }; } // namespace asio #include "asio/detail/pop_options.hpp" #endif // defined(ASIO_HAS_BOOST_DATE_TIME) // || defined(GENERATING_DOCUMENTATION) #endif // ASIO_BASIC_DEADLINE_TIMER_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/error_code.hpp
// // error_code.hpp // ~~~~~~~~~~~~~~ // // 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) // #ifndef ASIO_ERROR_CODE_HPP #define ASIO_ERROR_CODE_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include <system_error> #include "asio/detail/push_options.hpp" namespace asio { typedef std::error_category error_category; typedef std::error_code error_code; /// Returns the error category used for the system errors produced by asio. extern ASIO_DECL const error_category& system_category(); } // namespace asio #include "asio/detail/pop_options.hpp" #if defined(ASIO_HEADER_ONLY) # include "asio/impl/error_code.ipp" #endif // defined(ASIO_HEADER_ONLY) #endif // ASIO_ERROR_CODE_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/execution.hpp
// // execution.hpp // ~~~~~~~~~~~~~ // // 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) // #ifndef ASIO_EXECUTION_HPP #define ASIO_EXECUTION_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/execution/allocator.hpp" #include "asio/execution/any_executor.hpp" #include "asio/execution/bad_executor.hpp" #include "asio/execution/blocking.hpp" #include "asio/execution/blocking_adaptation.hpp" #include "asio/execution/context.hpp" #include "asio/execution/context_as.hpp" #include "asio/execution/executor.hpp" #include "asio/execution/invocable_archetype.hpp" #include "asio/execution/mapping.hpp" #include "asio/execution/occupancy.hpp" #include "asio/execution/outstanding_work.hpp" #include "asio/execution/prefer_only.hpp" #include "asio/execution/relationship.hpp" #endif // ASIO_EXECUTION_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/defer.hpp
// // defer.hpp // ~~~~~~~~~ // // 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) // #ifndef ASIO_DEFER_HPP #define ASIO_DEFER_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include "asio/async_result.hpp" #include "asio/detail/initiate_defer.hpp" #include "asio/detail/type_traits.hpp" #include "asio/execution_context.hpp" #include "asio/execution/blocking.hpp" #include "asio/execution/executor.hpp" #include "asio/is_executor.hpp" #include "asio/require.hpp" #include "asio/detail/push_options.hpp" namespace asio { /// Submits a completion token or function object for execution. /** * This function submits an object for execution using the object's associated * executor. The function object is queued for execution, and is never called * from the current thread prior to returning from <tt>defer()</tt>. * * The use of @c defer(), rather than @ref post(), indicates the caller's * preference that the executor defer the queueing of the function object. This * may allow the executor to optimise queueing for cases when the function * object represents a continuation of the current call context. * * @param token The @ref completion_token that will be used to produce a * completion handler. The function signature of the completion handler must be: * @code void handler(); @endcode * * @returns This function returns <tt>async_initiate<NullaryToken, * void()>(Init{}, token)</tt>, where @c Init is a function object type defined * as: * * @code class Init * { * public: * template <typename CompletionHandler> * void operator()(CompletionHandler&& completion_handler) const; * }; @endcode * * The function call operator of @c Init: * * @li Obtains the handler's associated executor object @c ex of type @c Ex by * performing @code auto ex = get_associated_executor(handler); @endcode * * @li Obtains the handler's associated allocator object @c alloc by performing * @code auto alloc = get_associated_allocator(handler); @endcode * * @li If <tt>execution::is_executor<Ex>::value</tt> is true, performs * @code prefer( * require(ex, execution::blocking.never), * execution::relationship.continuation, * execution::allocator(alloc) * ).execute(std::forward<CompletionHandler>(completion_handler)); @endcode * * @li If <tt>execution::is_executor<Ex>::value</tt> is false, performs * @code ex.defer( * std::forward<CompletionHandler>(completion_handler), * alloc); @endcode * * @par Completion Signature * @code void() @endcode */ template <ASIO_COMPLETION_TOKEN_FOR(void()) NullaryToken> auto defer(NullaryToken&& token) -> decltype( async_initiate<NullaryToken, void()>( declval<detail::initiate_defer>(), token)) { return async_initiate<NullaryToken, void()>( detail::initiate_defer(), token); } /// Submits a completion token or function object for execution. /** * This function submits an object for execution using the specified executor. * The function object is queued for execution, and is never called from the * current thread prior to returning from <tt>defer()</tt>. * * The use of @c defer(), rather than @ref post(), indicates the caller's * preference that the executor defer the queueing of the function object. This * may allow the executor to optimise queueing for cases when the function * object represents a continuation of the current call context. * * @param ex The target executor. * * @param token The @ref completion_token that will be used to produce a * completion handler. The function signature of the completion handler must be: * @code void handler(); @endcode * * @returns This function returns <tt>async_initiate<NullaryToken, * void()>(Init{ex}, token)</tt>, where @c Init is a function object type * defined as: * * @code class Init * { * public: * using executor_type = Executor; * explicit Init(const Executor& ex) : ex_(ex) {} * executor_type get_executor() const noexcept { return ex_; } * template <typename CompletionHandler> * void operator()(CompletionHandler&& completion_handler) const; * private: * Executor ex_; // exposition only * }; @endcode * * The function call operator of @c Init: * * @li Obtains the handler's associated executor object @c ex1 of type @c Ex1 by * performing @code auto ex1 = get_associated_executor(handler, ex); @endcode * * @li Obtains the handler's associated allocator object @c alloc by performing * @code auto alloc = get_associated_allocator(handler); @endcode * * @li If <tt>execution::is_executor<Ex1>::value</tt> is true, constructs a * function object @c f with a member @c executor_ that is initialised with * <tt>prefer(ex1, execution::outstanding_work.tracked)</tt>, a member @c * handler_ that is a decay-copy of @c completion_handler, and a function call * operator that performs: * @code auto a = get_associated_allocator(handler_); * prefer(executor_, execution::allocator(a)).execute(std::move(handler_)); * @endcode * * @li If <tt>execution::is_executor<Ex1>::value</tt> is false, constructs a * function object @c f with a member @c work_ that is initialised with * <tt>make_work_guard(ex1)</tt>, a member @c handler_ that is a decay-copy of * @c completion_handler, and a function call operator that performs: * @code auto a = get_associated_allocator(handler_); * work_.get_executor().dispatch(std::move(handler_), a); * work_.reset(); @endcode * * @li If <tt>execution::is_executor<Ex>::value</tt> is true, performs * @code prefer( * require(ex, execution::blocking.never), * execution::relationship.continuation, * execution::allocator(alloc) * ).execute(std::move(f)); @endcode * * @li If <tt>execution::is_executor<Ex>::value</tt> is false, performs * @code ex.defer(std::move(f), alloc); @endcode * * @par Completion Signature * @code void() @endcode */ template <typename Executor, ASIO_COMPLETION_TOKEN_FOR(void()) NullaryToken = default_completion_token_t<Executor>> auto defer(const Executor& ex, NullaryToken&& token = default_completion_token_t<Executor>(), constraint_t< (execution::is_executor<Executor>::value && can_require<Executor, execution::blocking_t::never_t>::value) || is_executor<Executor>::value > = 0) -> decltype( async_initiate<NullaryToken, void()>( declval<detail::initiate_defer_with_executor<Executor>>(), token)) { return async_initiate<NullaryToken, void()>( detail::initiate_defer_with_executor<Executor>(ex), token); } /// Submits a completion token or function object for execution. /** * @param ctx An execution context, from which the target executor is obtained. * * @param token The @ref completion_token that will be used to produce a * completion handler. The function signature of the completion handler must be: * @code void handler(); @endcode * * @returns <tt>defer(ctx.get_executor(), forward<NullaryToken>(token))</tt>. * * @par Completion Signature * @code void() @endcode */ template <typename ExecutionContext, ASIO_COMPLETION_TOKEN_FOR(void()) NullaryToken = default_completion_token_t<typename ExecutionContext::executor_type>> auto defer(ExecutionContext& ctx, NullaryToken&& token = default_completion_token_t<typename ExecutionContext::executor_type>(), constraint_t< is_convertible<ExecutionContext&, execution_context&>::value > = 0) -> decltype( async_initiate<NullaryToken, void()>( declval<detail::initiate_defer_with_executor< typename ExecutionContext::executor_type>>(), token)) { return async_initiate<NullaryToken, void()>( detail::initiate_defer_with_executor< typename ExecutionContext::executor_type>( ctx.get_executor()), token); } } // namespace asio #include "asio/detail/pop_options.hpp" #endif // ASIO_DEFER_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/buffer.hpp
// // buffer.hpp // ~~~~~~~~~~ // // 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) // #ifndef ASIO_BUFFER_HPP #define ASIO_BUFFER_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include <cstddef> #include <cstring> #include <limits> #include <stdexcept> #include <string> #include <vector> #include "asio/detail/array_fwd.hpp" #include "asio/detail/memory.hpp" #include "asio/detail/string_view.hpp" #include "asio/detail/throw_exception.hpp" #include "asio/detail/type_traits.hpp" #include "asio/is_contiguous_iterator.hpp" #if defined(ASIO_MSVC) && (ASIO_MSVC >= 1700) # if defined(_HAS_ITERATOR_DEBUGGING) && (_HAS_ITERATOR_DEBUGGING != 0) # if !defined(ASIO_DISABLE_BUFFER_DEBUGGING) # define ASIO_ENABLE_BUFFER_DEBUGGING # endif // !defined(ASIO_DISABLE_BUFFER_DEBUGGING) # endif // defined(_HAS_ITERATOR_DEBUGGING) #endif // defined(ASIO_MSVC) && (ASIO_MSVC >= 1700) #if defined(__GNUC__) # if defined(_GLIBCXX_DEBUG) # if !defined(ASIO_DISABLE_BUFFER_DEBUGGING) # define ASIO_ENABLE_BUFFER_DEBUGGING # endif // !defined(ASIO_DISABLE_BUFFER_DEBUGGING) # endif // defined(_GLIBCXX_DEBUG) #endif // defined(__GNUC__) #if defined(ASIO_ENABLE_BUFFER_DEBUGGING) # include "asio/detail/functional.hpp" #endif // ASIO_ENABLE_BUFFER_DEBUGGING #include "asio/detail/push_options.hpp" namespace asio { class mutable_buffer; class const_buffer; /// Holds a buffer that can be modified. /** * The mutable_buffer class provides a safe representation of a buffer that can * be modified. It does not own the underlying data, and so is cheap to copy or * assign. * * @par Accessing Buffer Contents * * The contents of a buffer may be accessed using the @c data() and @c size() * member functions: * * @code asio::mutable_buffer b1 = ...; * std::size_t s1 = b1.size(); * unsigned char* p1 = static_cast<unsigned char*>(b1.data()); * @endcode * * The @c data() member function permits violations of type safety, so uses of * it in application code should be carefully considered. */ class mutable_buffer { public: /// Construct an empty buffer. mutable_buffer() noexcept : data_(0), size_(0) { } /// Construct a buffer to represent a given memory range. mutable_buffer(void* data, std::size_t size) noexcept : data_(data), size_(size) { } #if defined(ASIO_ENABLE_BUFFER_DEBUGGING) mutable_buffer(void* data, std::size_t size, asio::detail::function<void()> debug_check) : data_(data), size_(size), debug_check_(debug_check) { } const asio::detail::function<void()>& get_debug_check() const { return debug_check_; } #endif // ASIO_ENABLE_BUFFER_DEBUGGING /// Get a pointer to the beginning of the memory range. void* data() const noexcept { #if defined(ASIO_ENABLE_BUFFER_DEBUGGING) if (size_ && debug_check_) debug_check_(); #endif // ASIO_ENABLE_BUFFER_DEBUGGING return data_; } /// Get the size of the memory range. std::size_t size() const noexcept { return size_; } /// Move the start of the buffer by the specified number of bytes. mutable_buffer& operator+=(std::size_t n) noexcept { std::size_t offset = n < size_ ? n : size_; data_ = static_cast<char*>(data_) + offset; size_ -= offset; return *this; } private: void* data_; std::size_t size_; #if defined(ASIO_ENABLE_BUFFER_DEBUGGING) asio::detail::function<void()> debug_check_; #endif // ASIO_ENABLE_BUFFER_DEBUGGING }; #if !defined(ASIO_NO_DEPRECATED) /// (Deprecated: Use mutable_buffer.) Adapts a single modifiable buffer so that /// it meets the requirements of the MutableBufferSequence concept. class mutable_buffers_1 : public mutable_buffer { public: /// The type for each element in the list of buffers. typedef mutable_buffer value_type; /// A random-access iterator type that may be used to read elements. typedef const mutable_buffer* const_iterator; /// Construct to represent a given memory range. mutable_buffers_1(void* data, std::size_t size) noexcept : mutable_buffer(data, size) { } #if defined(ASIO_ENABLE_BUFFER_DEBUGGING) mutable_buffers_1(void* data, std::size_t size, asio::detail::function<void()> debug_check) : mutable_buffer(data, size, debug_check) { } #endif // ASIO_ENABLE_BUFFER_DEBUGGING /// Construct to represent a single modifiable buffer. explicit mutable_buffers_1(const mutable_buffer& b) noexcept : mutable_buffer(b) { } /// Get a random-access iterator to the first element. const_iterator begin() const noexcept { return this; } /// Get a random-access iterator for one past the last element. const_iterator end() const noexcept { return begin() + 1; } }; #endif // !defined(ASIO_NO_DEPRECATED) /// Holds a buffer that cannot be modified. /** * The const_buffer class provides a safe representation of a buffer that cannot * be modified. It does not own the underlying data, and so is cheap to copy or * assign. * * @par Accessing Buffer Contents * * The contents of a buffer may be accessed using the @c data() and @c size() * member functions: * * @code asio::const_buffer b1 = ...; * std::size_t s1 = b1.size(); * const unsigned char* p1 = static_cast<const unsigned char*>(b1.data()); * @endcode * * The @c data() member function permits violations of type safety, so uses of * it in application code should be carefully considered. */ class const_buffer { public: /// Construct an empty buffer. const_buffer() noexcept : data_(0), size_(0) { } /// Construct a buffer to represent a given memory range. const_buffer(const void* data, std::size_t size) noexcept : data_(data), size_(size) { } /// Construct a non-modifiable buffer from a modifiable one. const_buffer(const mutable_buffer& b) noexcept : data_(b.data()), size_(b.size()) #if defined(ASIO_ENABLE_BUFFER_DEBUGGING) , debug_check_(b.get_debug_check()) #endif // ASIO_ENABLE_BUFFER_DEBUGGING { } #if defined(ASIO_ENABLE_BUFFER_DEBUGGING) const_buffer(const void* data, std::size_t size, asio::detail::function<void()> debug_check) : data_(data), size_(size), debug_check_(debug_check) { } const asio::detail::function<void()>& get_debug_check() const { return debug_check_; } #endif // ASIO_ENABLE_BUFFER_DEBUGGING /// Get a pointer to the beginning of the memory range. const void* data() const noexcept { #if defined(ASIO_ENABLE_BUFFER_DEBUGGING) if (size_ && debug_check_) debug_check_(); #endif // ASIO_ENABLE_BUFFER_DEBUGGING return data_; } /// Get the size of the memory range. std::size_t size() const noexcept { return size_; } /// Move the start of the buffer by the specified number of bytes. const_buffer& operator+=(std::size_t n) noexcept { std::size_t offset = n < size_ ? n : size_; data_ = static_cast<const char*>(data_) + offset; size_ -= offset; return *this; } private: const void* data_; std::size_t size_; #if defined(ASIO_ENABLE_BUFFER_DEBUGGING) asio::detail::function<void()> debug_check_; #endif // ASIO_ENABLE_BUFFER_DEBUGGING }; #if !defined(ASIO_NO_DEPRECATED) /// (Deprecated: Use const_buffer.) Adapts a single non-modifiable buffer so /// that it meets the requirements of the ConstBufferSequence concept. class const_buffers_1 : public const_buffer { public: /// The type for each element in the list of buffers. typedef const_buffer value_type; /// A random-access iterator type that may be used to read elements. typedef const const_buffer* const_iterator; /// Construct to represent a given memory range. const_buffers_1(const void* data, std::size_t size) noexcept : const_buffer(data, size) { } #if defined(ASIO_ENABLE_BUFFER_DEBUGGING) const_buffers_1(const void* data, std::size_t size, asio::detail::function<void()> debug_check) : const_buffer(data, size, debug_check) { } #endif // ASIO_ENABLE_BUFFER_DEBUGGING /// Construct to represent a single non-modifiable buffer. explicit const_buffers_1(const const_buffer& b) noexcept : const_buffer(b) { } /// Get a random-access iterator to the first element. const_iterator begin() const noexcept { return this; } /// Get a random-access iterator for one past the last element. const_iterator end() const noexcept { return begin() + 1; } }; #endif // !defined(ASIO_NO_DEPRECATED) /// (Deprecated: Use the socket/descriptor wait() and async_wait() member /// functions.) An implementation of both the ConstBufferSequence and /// MutableBufferSequence concepts to represent a null buffer sequence. class null_buffers { public: /// The type for each element in the list of buffers. typedef mutable_buffer value_type; /// A random-access iterator type that may be used to read elements. typedef const mutable_buffer* const_iterator; /// Get a random-access iterator to the first element. const_iterator begin() const noexcept { return &buf_; } /// Get a random-access iterator for one past the last element. const_iterator end() const noexcept { return &buf_; } private: mutable_buffer buf_; }; /** @defgroup buffer_sequence_begin asio::buffer_sequence_begin * * @brief The asio::buffer_sequence_begin function returns an iterator * pointing to the first element in a buffer sequence. */ /*@{*/ /// Get an iterator to the first element in a buffer sequence. template <typename MutableBuffer> inline const mutable_buffer* buffer_sequence_begin(const MutableBuffer& b, constraint_t< is_convertible<const MutableBuffer*, const mutable_buffer*>::value > = 0) noexcept { return static_cast<const mutable_buffer*>(detail::addressof(b)); } /// Get an iterator to the first element in a buffer sequence. template <typename ConstBuffer> inline const const_buffer* buffer_sequence_begin(const ConstBuffer& b, constraint_t< is_convertible<const ConstBuffer*, const const_buffer*>::value > = 0) noexcept { return static_cast<const const_buffer*>(detail::addressof(b)); } /// Get an iterator to the first element in a buffer sequence. template <typename C> inline auto buffer_sequence_begin(C& c, constraint_t< !is_convertible<const C*, const mutable_buffer*>::value && !is_convertible<const C*, const const_buffer*>::value > = 0) noexcept -> decltype(c.begin()) { return c.begin(); } /// Get an iterator to the first element in a buffer sequence. template <typename C> inline auto buffer_sequence_begin(const C& c, constraint_t< !is_convertible<const C*, const mutable_buffer*>::value && !is_convertible<const C*, const const_buffer*>::value > = 0) noexcept -> decltype(c.begin()) { return c.begin(); } /*@}*/ /** @defgroup buffer_sequence_end asio::buffer_sequence_end * * @brief The asio::buffer_sequence_end function returns an iterator * pointing to one past the end element in a buffer sequence. */ /*@{*/ /// Get an iterator to one past the end element in a buffer sequence. template <typename MutableBuffer> inline const mutable_buffer* buffer_sequence_end(const MutableBuffer& b, constraint_t< is_convertible<const MutableBuffer*, const mutable_buffer*>::value > = 0) noexcept { return static_cast<const mutable_buffer*>(detail::addressof(b)) + 1; } /// Get an iterator to one past the end element in a buffer sequence. template <typename ConstBuffer> inline const const_buffer* buffer_sequence_end(const ConstBuffer& b, constraint_t< is_convertible<const ConstBuffer*, const const_buffer*>::value > = 0) noexcept { return static_cast<const const_buffer*>(detail::addressof(b)) + 1; } /// Get an iterator to one past the end element in a buffer sequence. template <typename C> inline auto buffer_sequence_end(C& c, constraint_t< !is_convertible<const C*, const mutable_buffer*>::value && !is_convertible<const C*, const const_buffer*>::value > = 0) noexcept -> decltype(c.end()) { return c.end(); } /// Get an iterator to one past the end element in a buffer sequence. template <typename C> inline auto buffer_sequence_end(const C& c, constraint_t< !is_convertible<const C*, const mutable_buffer*>::value && !is_convertible<const C*, const const_buffer*>::value > = 0) noexcept -> decltype(c.end()) { return c.end(); } /*@}*/ namespace detail { // Tag types used to select appropriately optimised overloads. struct one_buffer {}; struct multiple_buffers {}; // Helper trait to detect single buffers. template <typename BufferSequence> struct buffer_sequence_cardinality : conditional_t< is_same<BufferSequence, mutable_buffer>::value #if !defined(ASIO_NO_DEPRECATED) || is_same<BufferSequence, mutable_buffers_1>::value || is_same<BufferSequence, const_buffers_1>::value #endif // !defined(ASIO_NO_DEPRECATED) || is_same<BufferSequence, const_buffer>::value, one_buffer, multiple_buffers> {}; template <typename Iterator> inline std::size_t buffer_size(one_buffer, Iterator begin, Iterator) noexcept { return const_buffer(*begin).size(); } template <typename Iterator> inline std::size_t buffer_size(multiple_buffers, Iterator begin, Iterator end) noexcept { std::size_t total_buffer_size = 0; Iterator iter = begin; for (; iter != end; ++iter) { const_buffer b(*iter); total_buffer_size += b.size(); } return total_buffer_size; } } // namespace detail /// Get the total number of bytes in a buffer sequence. /** * The @c buffer_size function determines the total size of all buffers in the * buffer sequence, as if computed as follows: * * @code size_t total_size = 0; * auto i = asio::buffer_sequence_begin(buffers); * auto end = asio::buffer_sequence_end(buffers); * for (; i != end; ++i) * { * const_buffer b(*i); * total_size += b.size(); * } * return total_size; @endcode * * The @c BufferSequence template parameter may meet either of the @c * ConstBufferSequence or @c MutableBufferSequence type requirements. */ template <typename BufferSequence> inline std::size_t buffer_size(const BufferSequence& b) noexcept { return detail::buffer_size( detail::buffer_sequence_cardinality<BufferSequence>(), asio::buffer_sequence_begin(b), asio::buffer_sequence_end(b)); } #if !defined(ASIO_NO_DEPRECATED) /** @defgroup buffer_cast asio::buffer_cast * * @brief (Deprecated: Use the @c data() member function.) The * asio::buffer_cast function is used to obtain a pointer to the * underlying memory region associated with a buffer. * * @par Examples: * * To access the memory of a non-modifiable buffer, use: * @code asio::const_buffer b1 = ...; * const unsigned char* p1 = asio::buffer_cast<const unsigned char*>(b1); * @endcode * * To access the memory of a modifiable buffer, use: * @code asio::mutable_buffer b2 = ...; * unsigned char* p2 = asio::buffer_cast<unsigned char*>(b2); * @endcode * * The asio::buffer_cast function permits violations of type safety, so * uses of it in application code should be carefully considered. */ /*@{*/ /// Cast a non-modifiable buffer to a specified pointer to POD type. template <typename PointerToPodType> inline PointerToPodType buffer_cast(const mutable_buffer& b) noexcept { return static_cast<PointerToPodType>(b.data()); } /// Cast a non-modifiable buffer to a specified pointer to POD type. template <typename PointerToPodType> inline PointerToPodType buffer_cast(const const_buffer& b) noexcept { return static_cast<PointerToPodType>(b.data()); } /*@}*/ #endif // !defined(ASIO_NO_DEPRECATED) /// Create a new modifiable buffer that is offset from the start of another. /** * @relates mutable_buffer */ inline mutable_buffer operator+(const mutable_buffer& b, std::size_t n) noexcept { std::size_t offset = n < b.size() ? n : b.size(); char* new_data = static_cast<char*>(b.data()) + offset; std::size_t new_size = b.size() - offset; return mutable_buffer(new_data, new_size #if defined(ASIO_ENABLE_BUFFER_DEBUGGING) , b.get_debug_check() #endif // ASIO_ENABLE_BUFFER_DEBUGGING ); } /// Create a new modifiable buffer that is offset from the start of another. /** * @relates mutable_buffer */ inline mutable_buffer operator+(std::size_t n, const mutable_buffer& b) noexcept { return b + n; } /// Create a new non-modifiable buffer that is offset from the start of another. /** * @relates const_buffer */ inline const_buffer operator+(const const_buffer& b, std::size_t n) noexcept { std::size_t offset = n < b.size() ? n : b.size(); const char* new_data = static_cast<const char*>(b.data()) + offset; std::size_t new_size = b.size() - offset; return const_buffer(new_data, new_size #if defined(ASIO_ENABLE_BUFFER_DEBUGGING) , b.get_debug_check() #endif // ASIO_ENABLE_BUFFER_DEBUGGING ); } /// Create a new non-modifiable buffer that is offset from the start of another. /** * @relates const_buffer */ inline const_buffer operator+(std::size_t n, const const_buffer& b) noexcept { return b + n; } #if defined(ASIO_ENABLE_BUFFER_DEBUGGING) namespace detail { template <typename Iterator> class buffer_debug_check { public: buffer_debug_check(Iterator iter) : iter_(iter) { } ~buffer_debug_check() { #if defined(ASIO_MSVC) && (ASIO_MSVC == 1400) // MSVC 8's string iterator checking may crash in a std::string::iterator // object's destructor when the iterator points to an already-destroyed // std::string object, unless the iterator is cleared first. iter_ = Iterator(); #endif // defined(ASIO_MSVC) && (ASIO_MSVC == 1400) } void operator()() { (void)*iter_; } private: Iterator iter_; }; } // namespace detail #endif // ASIO_ENABLE_BUFFER_DEBUGGING /** @defgroup buffer asio::buffer * * @brief The asio::buffer function is used to create a buffer object to * represent raw memory, an array of POD elements, a vector of POD elements, * or a std::string. * * A buffer object represents a contiguous region of memory as a 2-tuple * consisting of a pointer and size in bytes. A tuple of the form <tt>{void*, * size_t}</tt> specifies a mutable (modifiable) region of memory. Similarly, a * tuple of the form <tt>{const void*, size_t}</tt> specifies a const * (non-modifiable) region of memory. These two forms correspond to the classes * mutable_buffer and const_buffer, respectively. To mirror C++'s conversion * rules, a mutable_buffer is implicitly convertible to a const_buffer, and the * opposite conversion is not permitted. * * The simplest use case involves reading or writing a single buffer of a * specified size: * * @code sock.send(asio::buffer(data, size)); @endcode * * In the above example, the return value of asio::buffer meets the * requirements of the ConstBufferSequence concept so that it may be directly * passed to the socket's write function. A buffer created for modifiable * memory also meets the requirements of the MutableBufferSequence concept. * * An individual buffer may be created from a builtin array, std::vector, * std::array or boost::array of POD elements. This helps prevent buffer * overruns by automatically determining the size of the buffer: * * @code char d1[128]; * size_t bytes_transferred = sock.receive(asio::buffer(d1)); * * std::vector<char> d2(128); * bytes_transferred = sock.receive(asio::buffer(d2)); * * std::array<char, 128> d3; * bytes_transferred = sock.receive(asio::buffer(d3)); * * boost::array<char, 128> d4; * bytes_transferred = sock.receive(asio::buffer(d4)); @endcode * * In all three cases above, the buffers created are exactly 128 bytes long. * Note that a vector is @e never automatically resized when creating or using * a buffer. The buffer size is determined using the vector's <tt>size()</tt> * member function, and not its capacity. * * @par Accessing Buffer Contents * * The contents of a buffer may be accessed using the @c data() and @c size() * member functions: * * @code asio::mutable_buffer b1 = ...; * std::size_t s1 = b1.size(); * unsigned char* p1 = static_cast<unsigned char*>(b1.data()); * * asio::const_buffer b2 = ...; * std::size_t s2 = b2.size(); * const void* p2 = b2.data(); @endcode * * The @c data() member function permits violations of type safety, so * uses of it in application code should be carefully considered. * * For convenience, a @ref buffer_size function is provided that works with * both buffers and buffer sequences (that is, types meeting the * ConstBufferSequence or MutableBufferSequence type requirements). In this * case, the function returns the total size of all buffers in the sequence. * * @par Buffer Copying * * The @ref buffer_copy function may be used to copy raw bytes between * individual buffers and buffer sequences. * * In particular, when used with the @ref buffer_size function, the @ref * buffer_copy function can be used to linearise a sequence of buffers. For * example: * * @code vector<const_buffer> buffers = ...; * * vector<unsigned char> data(asio::buffer_size(buffers)); * asio::buffer_copy(asio::buffer(data), buffers); @endcode * * Note that @ref buffer_copy is implemented in terms of @c memcpy, and * consequently it cannot be used to copy between overlapping memory regions. * * @par Buffer Invalidation * * A buffer object does not have any ownership of the memory it refers to. It * is the responsibility of the application to ensure the memory region remains * valid until it is no longer required for an I/O operation. When the memory * is no longer available, the buffer is said to have been invalidated. * * For the asio::buffer overloads that accept an argument of type * std::vector, the buffer objects returned are invalidated by any vector * operation that also invalidates all references, pointers and iterators * referring to the elements in the sequence (C++ Std, 23.2.4) * * For the asio::buffer overloads that accept an argument of type * std::basic_string, the buffer objects returned are invalidated according to * the rules defined for invalidation of references, pointers and iterators * referring to elements of the sequence (C++ Std, 21.3). * * @par Buffer Arithmetic * * Buffer objects may be manipulated using simple arithmetic in a safe way * which helps prevent buffer overruns. Consider an array initialised as * follows: * * @code boost::array<char, 6> a = { 'a', 'b', 'c', 'd', 'e' }; @endcode * * A buffer object @c b1 created using: * * @code b1 = asio::buffer(a); @endcode * * represents the entire array, <tt>{ 'a', 'b', 'c', 'd', 'e' }</tt>. An * optional second argument to the asio::buffer function may be used to * limit the size, in bytes, of the buffer: * * @code b2 = asio::buffer(a, 3); @endcode * * such that @c b2 represents the data <tt>{ 'a', 'b', 'c' }</tt>. Even if the * size argument exceeds the actual size of the array, the size of the buffer * object created will be limited to the array size. * * An offset may be applied to an existing buffer to create a new one: * * @code b3 = b1 + 2; @endcode * * where @c b3 will set to represent <tt>{ 'c', 'd', 'e' }</tt>. If the offset * exceeds the size of the existing buffer, the newly created buffer will be * empty. * * Both an offset and size may be specified to create a buffer that corresponds * to a specific range of bytes within an existing buffer: * * @code b4 = asio::buffer(b1 + 1, 3); @endcode * * so that @c b4 will refer to the bytes <tt>{ 'b', 'c', 'd' }</tt>. * * @par Buffers and Scatter-Gather I/O * * To read or write using multiple buffers (i.e. scatter-gather I/O), multiple * buffer objects may be assigned into a container that supports the * MutableBufferSequence (for read) or ConstBufferSequence (for write) concepts: * * @code * char d1[128]; * std::vector<char> d2(128); * boost::array<char, 128> d3; * * boost::array<mutable_buffer, 3> bufs1 = { * asio::buffer(d1), * asio::buffer(d2), * asio::buffer(d3) }; * bytes_transferred = sock.receive(bufs1); * * std::vector<const_buffer> bufs2; * bufs2.push_back(asio::buffer(d1)); * bufs2.push_back(asio::buffer(d2)); * bufs2.push_back(asio::buffer(d3)); * bytes_transferred = sock.send(bufs2); @endcode * * @par Buffer Literals * * The `_buf` literal suffix, defined in namespace * <tt>asio::buffer_literals</tt>, may be used to create @c const_buffer * objects from string, binary integer, and hexadecimal integer literals. * For example: * * @code * using namespace asio::buffer_literals; * * asio::const_buffer b1 = "hello"_buf; * asio::const_buffer b2 = 0xdeadbeef_buf; * asio::const_buffer b3 = 0x0123456789abcdef0123456789abcdef_buf; * asio::const_buffer b4 = 0b1010101011001100_buf; @endcode * * Note that the memory associated with a buffer literal is valid for the * lifetime of the program. This means that the buffer can be safely used with * asynchronous operations. */ /*@{*/ #if defined(ASIO_NO_DEPRECATED) || defined(GENERATING_DOCUMENTATION) # define ASIO_MUTABLE_BUFFER mutable_buffer # define ASIO_CONST_BUFFER const_buffer #else // defined(ASIO_NO_DEPRECATED) || defined(GENERATING_DOCUMENTATION) # define ASIO_MUTABLE_BUFFER mutable_buffers_1 # define ASIO_CONST_BUFFER const_buffers_1 #endif // defined(ASIO_NO_DEPRECATED) || defined(GENERATING_DOCUMENTATION) /// Create a new modifiable buffer from an existing buffer. /** * @returns <tt>mutable_buffer(b)</tt>. */ ASIO_NODISCARD inline ASIO_MUTABLE_BUFFER buffer( const mutable_buffer& b) noexcept { return ASIO_MUTABLE_BUFFER(b); } /// Create a new modifiable buffer from an existing buffer. /** * @returns A mutable_buffer value equivalent to: * @code mutable_buffer( * b.data(), * min(b.size(), max_size_in_bytes)); @endcode */ ASIO_NODISCARD inline ASIO_MUTABLE_BUFFER buffer( const mutable_buffer& b, std::size_t max_size_in_bytes) noexcept { return ASIO_MUTABLE_BUFFER( mutable_buffer(b.data(), b.size() < max_size_in_bytes ? b.size() : max_size_in_bytes #if defined(ASIO_ENABLE_BUFFER_DEBUGGING) , b.get_debug_check() #endif // ASIO_ENABLE_BUFFER_DEBUGGING )); } /// Create a new non-modifiable buffer from an existing buffer. /** * @returns <tt>const_buffer(b)</tt>. */ ASIO_NODISCARD inline ASIO_CONST_BUFFER buffer( const const_buffer& b) noexcept { return ASIO_CONST_BUFFER(b); } /// Create a new non-modifiable buffer from an existing buffer. /** * @returns A const_buffer value equivalent to: * @code const_buffer( * b.data(), * min(b.size(), max_size_in_bytes)); @endcode */ ASIO_NODISCARD inline ASIO_CONST_BUFFER buffer( const const_buffer& b, std::size_t max_size_in_bytes) noexcept { return ASIO_CONST_BUFFER(b.data(), b.size() < max_size_in_bytes ? b.size() : max_size_in_bytes #if defined(ASIO_ENABLE_BUFFER_DEBUGGING) , b.get_debug_check() #endif // ASIO_ENABLE_BUFFER_DEBUGGING ); } /// Create a new modifiable buffer that represents the given memory range. /** * @returns <tt>mutable_buffer(data, size_in_bytes)</tt>. */ ASIO_NODISCARD inline ASIO_MUTABLE_BUFFER buffer( void* data, std::size_t size_in_bytes) noexcept { return ASIO_MUTABLE_BUFFER(data, size_in_bytes); } /// Create a new non-modifiable buffer that represents the given memory range. /** * @returns <tt>const_buffer(data, size_in_bytes)</tt>. */ ASIO_NODISCARD inline ASIO_CONST_BUFFER buffer( const void* data, std::size_t size_in_bytes) noexcept { return ASIO_CONST_BUFFER(data, size_in_bytes); } /// Create a new modifiable buffer that represents the given POD array. /** * @returns A mutable_buffer value equivalent to: * @code mutable_buffer( * static_cast<void*>(data), * N * sizeof(PodType)); @endcode */ template <typename PodType, std::size_t N> ASIO_NODISCARD inline ASIO_MUTABLE_BUFFER buffer( PodType (&data)[N]) noexcept { return ASIO_MUTABLE_BUFFER(data, N * sizeof(PodType)); } /// Create a new modifiable buffer that represents the given POD array. /** * @returns A mutable_buffer value equivalent to: * @code mutable_buffer( * static_cast<void*>(data), * min(N * sizeof(PodType), max_size_in_bytes)); @endcode */ template <typename PodType, std::size_t N> ASIO_NODISCARD inline ASIO_MUTABLE_BUFFER buffer( PodType (&data)[N], std::size_t max_size_in_bytes) noexcept { return ASIO_MUTABLE_BUFFER(data, N * sizeof(PodType) < max_size_in_bytes ? N * sizeof(PodType) : max_size_in_bytes); } /// Create a new non-modifiable buffer that represents the given POD array. /** * @returns A const_buffer value equivalent to: * @code const_buffer( * static_cast<const void*>(data), * N * sizeof(PodType)); @endcode */ template <typename PodType, std::size_t N> ASIO_NODISCARD inline ASIO_CONST_BUFFER buffer( const PodType (&data)[N]) noexcept { return ASIO_CONST_BUFFER(data, N * sizeof(PodType)); } /// Create a new non-modifiable buffer that represents the given POD array. /** * @returns A const_buffer value equivalent to: * @code const_buffer( * static_cast<const void*>(data), * min(N * sizeof(PodType), max_size_in_bytes)); @endcode */ template <typename PodType, std::size_t N> ASIO_NODISCARD inline ASIO_CONST_BUFFER buffer( const PodType (&data)[N], std::size_t max_size_in_bytes) noexcept { return ASIO_CONST_BUFFER(data, N * sizeof(PodType) < max_size_in_bytes ? N * sizeof(PodType) : max_size_in_bytes); } /// Create a new modifiable buffer that represents the given POD array. /** * @returns A mutable_buffer value equivalent to: * @code mutable_buffer( * data.data(), * data.size() * sizeof(PodType)); @endcode */ template <typename PodType, std::size_t N> ASIO_NODISCARD inline ASIO_MUTABLE_BUFFER buffer( boost::array<PodType, N>& data) noexcept { return ASIO_MUTABLE_BUFFER( data.c_array(), data.size() * sizeof(PodType)); } /// Create a new modifiable buffer that represents the given POD array. /** * @returns A mutable_buffer value equivalent to: * @code mutable_buffer( * data.data(), * min(data.size() * sizeof(PodType), max_size_in_bytes)); @endcode */ template <typename PodType, std::size_t N> ASIO_NODISCARD inline ASIO_MUTABLE_BUFFER buffer( boost::array<PodType, N>& data, std::size_t max_size_in_bytes) noexcept { return ASIO_MUTABLE_BUFFER(data.c_array(), data.size() * sizeof(PodType) < max_size_in_bytes ? data.size() * sizeof(PodType) : max_size_in_bytes); } /// Create a new non-modifiable buffer that represents the given POD array. /** * @returns A const_buffer value equivalent to: * @code const_buffer( * data.data(), * data.size() * sizeof(PodType)); @endcode */ template <typename PodType, std::size_t N> ASIO_NODISCARD inline ASIO_CONST_BUFFER buffer( boost::array<const PodType, N>& data) noexcept { return ASIO_CONST_BUFFER(data.data(), data.size() * sizeof(PodType)); } /// Create a new non-modifiable buffer that represents the given POD array. /** * @returns A const_buffer value equivalent to: * @code const_buffer( * data.data(), * min(data.size() * sizeof(PodType), max_size_in_bytes)); @endcode */ template <typename PodType, std::size_t N> ASIO_NODISCARD inline ASIO_CONST_BUFFER buffer( boost::array<const PodType, N>& data, std::size_t max_size_in_bytes) noexcept { return ASIO_CONST_BUFFER(data.data(), data.size() * sizeof(PodType) < max_size_in_bytes ? data.size() * sizeof(PodType) : max_size_in_bytes); } /// Create a new non-modifiable buffer that represents the given POD array. /** * @returns A const_buffer value equivalent to: * @code const_buffer( * data.data(), * data.size() * sizeof(PodType)); @endcode */ template <typename PodType, std::size_t N> ASIO_NODISCARD inline ASIO_CONST_BUFFER buffer( const boost::array<PodType, N>& data) noexcept { return ASIO_CONST_BUFFER(data.data(), data.size() * sizeof(PodType)); } /// Create a new non-modifiable buffer that represents the given POD array. /** * @returns A const_buffer value equivalent to: * @code const_buffer( * data.data(), * min(data.size() * sizeof(PodType), max_size_in_bytes)); @endcode */ template <typename PodType, std::size_t N> ASIO_NODISCARD inline ASIO_CONST_BUFFER buffer( const boost::array<PodType, N>& data, std::size_t max_size_in_bytes) noexcept { return ASIO_CONST_BUFFER(data.data(), data.size() * sizeof(PodType) < max_size_in_bytes ? data.size() * sizeof(PodType) : max_size_in_bytes); } /// Create a new modifiable buffer that represents the given POD array. /** * @returns A mutable_buffer value equivalent to: * @code mutable_buffer( * data.data(), * data.size() * sizeof(PodType)); @endcode */ template <typename PodType, std::size_t N> ASIO_NODISCARD inline ASIO_MUTABLE_BUFFER buffer( std::array<PodType, N>& data) noexcept { return ASIO_MUTABLE_BUFFER(data.data(), data.size() * sizeof(PodType)); } /// Create a new modifiable buffer that represents the given POD array. /** * @returns A mutable_buffer value equivalent to: * @code mutable_buffer( * data.data(), * min(data.size() * sizeof(PodType), max_size_in_bytes)); @endcode */ template <typename PodType, std::size_t N> ASIO_NODISCARD inline ASIO_MUTABLE_BUFFER buffer( std::array<PodType, N>& data, std::size_t max_size_in_bytes) noexcept { return ASIO_MUTABLE_BUFFER(data.data(), data.size() * sizeof(PodType) < max_size_in_bytes ? data.size() * sizeof(PodType) : max_size_in_bytes); } /// Create a new non-modifiable buffer that represents the given POD array. /** * @returns A const_buffer value equivalent to: * @code const_buffer( * data.data(), * data.size() * sizeof(PodType)); @endcode */ template <typename PodType, std::size_t N> ASIO_NODISCARD inline ASIO_CONST_BUFFER buffer( std::array<const PodType, N>& data) noexcept { return ASIO_CONST_BUFFER(data.data(), data.size() * sizeof(PodType)); } /// Create a new non-modifiable buffer that represents the given POD array. /** * @returns A const_buffer value equivalent to: * @code const_buffer( * data.data(), * min(data.size() * sizeof(PodType), max_size_in_bytes)); @endcode */ template <typename PodType, std::size_t N> ASIO_NODISCARD inline ASIO_CONST_BUFFER buffer( std::array<const PodType, N>& data, std::size_t max_size_in_bytes) noexcept { return ASIO_CONST_BUFFER(data.data(), data.size() * sizeof(PodType) < max_size_in_bytes ? data.size() * sizeof(PodType) : max_size_in_bytes); } /// Create a new non-modifiable buffer that represents the given POD array. /** * @returns A const_buffer value equivalent to: * @code const_buffer( * data.data(), * data.size() * sizeof(PodType)); @endcode */ template <typename PodType, std::size_t N> ASIO_NODISCARD inline ASIO_CONST_BUFFER buffer( const std::array<PodType, N>& data) noexcept { return ASIO_CONST_BUFFER(data.data(), data.size() * sizeof(PodType)); } /// Create a new non-modifiable buffer that represents the given POD array. /** * @returns A const_buffer value equivalent to: * @code const_buffer( * data.data(), * min(data.size() * sizeof(PodType), max_size_in_bytes)); @endcode */ template <typename PodType, std::size_t N> ASIO_NODISCARD inline ASIO_CONST_BUFFER buffer( const std::array<PodType, N>& data, std::size_t max_size_in_bytes) noexcept { return ASIO_CONST_BUFFER(data.data(), data.size() * sizeof(PodType) < max_size_in_bytes ? data.size() * sizeof(PodType) : max_size_in_bytes); } /// Create a new modifiable buffer that represents the given POD vector. /** * @returns A mutable_buffer value equivalent to: * @code mutable_buffer( * data.size() ? &data[0] : 0, * data.size() * sizeof(PodType)); @endcode * * @note The buffer is invalidated by any vector operation that would also * invalidate iterators. */ template <typename PodType, typename Allocator> ASIO_NODISCARD inline ASIO_MUTABLE_BUFFER buffer( std::vector<PodType, Allocator>& data) noexcept { return ASIO_MUTABLE_BUFFER( data.size() ? &data[0] : 0, data.size() * sizeof(PodType) #if defined(ASIO_ENABLE_BUFFER_DEBUGGING) , detail::buffer_debug_check< typename std::vector<PodType, Allocator>::iterator >(data.begin()) #endif // ASIO_ENABLE_BUFFER_DEBUGGING ); } /// Create a new modifiable buffer that represents the given POD vector. /** * @returns A mutable_buffer value equivalent to: * @code mutable_buffer( * data.size() ? &data[0] : 0, * min(data.size() * sizeof(PodType), max_size_in_bytes)); @endcode * * @note The buffer is invalidated by any vector operation that would also * invalidate iterators. */ template <typename PodType, typename Allocator> ASIO_NODISCARD inline ASIO_MUTABLE_BUFFER buffer( std::vector<PodType, Allocator>& data, std::size_t max_size_in_bytes) noexcept { return ASIO_MUTABLE_BUFFER(data.size() ? &data[0] : 0, data.size() * sizeof(PodType) < max_size_in_bytes ? data.size() * sizeof(PodType) : max_size_in_bytes #if defined(ASIO_ENABLE_BUFFER_DEBUGGING) , detail::buffer_debug_check< typename std::vector<PodType, Allocator>::iterator >(data.begin()) #endif // ASIO_ENABLE_BUFFER_DEBUGGING ); } /// Create a new non-modifiable buffer that represents the given POD vector. /** * @returns A const_buffer value equivalent to: * @code const_buffer( * data.size() ? &data[0] : 0, * data.size() * sizeof(PodType)); @endcode * * @note The buffer is invalidated by any vector operation that would also * invalidate iterators. */ template <typename PodType, typename Allocator> ASIO_NODISCARD inline ASIO_CONST_BUFFER buffer( const std::vector<PodType, Allocator>& data) noexcept { return ASIO_CONST_BUFFER( data.size() ? &data[0] : 0, data.size() * sizeof(PodType) #if defined(ASIO_ENABLE_BUFFER_DEBUGGING) , detail::buffer_debug_check< typename std::vector<PodType, Allocator>::const_iterator >(data.begin()) #endif // ASIO_ENABLE_BUFFER_DEBUGGING ); } /// Create a new non-modifiable buffer that represents the given POD vector. /** * @returns A const_buffer value equivalent to: * @code const_buffer( * data.size() ? &data[0] : 0, * min(data.size() * sizeof(PodType), max_size_in_bytes)); @endcode * * @note The buffer is invalidated by any vector operation that would also * invalidate iterators. */ template <typename PodType, typename Allocator> ASIO_NODISCARD inline ASIO_CONST_BUFFER buffer( const std::vector<PodType, Allocator>& data, std::size_t max_size_in_bytes) noexcept { return ASIO_CONST_BUFFER(data.size() ? &data[0] : 0, data.size() * sizeof(PodType) < max_size_in_bytes ? data.size() * sizeof(PodType) : max_size_in_bytes #if defined(ASIO_ENABLE_BUFFER_DEBUGGING) , detail::buffer_debug_check< typename std::vector<PodType, Allocator>::const_iterator >(data.begin()) #endif // ASIO_ENABLE_BUFFER_DEBUGGING ); } /// Create a new modifiable buffer that represents the given string. /** * @returns <tt>mutable_buffer(data.size() ? &data[0] : 0, * data.size() * sizeof(Elem))</tt>. * * @note The buffer is invalidated by any non-const operation called on the * given string object. */ template <typename Elem, typename Traits, typename Allocator> ASIO_NODISCARD inline ASIO_MUTABLE_BUFFER buffer( std::basic_string<Elem, Traits, Allocator>& data) noexcept { return ASIO_MUTABLE_BUFFER(data.size() ? &data[0] : 0, data.size() * sizeof(Elem) #if defined(ASIO_ENABLE_BUFFER_DEBUGGING) , detail::buffer_debug_check< typename std::basic_string<Elem, Traits, Allocator>::iterator >(data.begin()) #endif // ASIO_ENABLE_BUFFER_DEBUGGING ); } /// Create a new modifiable buffer that represents the given string. /** * @returns A mutable_buffer value equivalent to: * @code mutable_buffer( * data.size() ? &data[0] : 0, * min(data.size() * sizeof(Elem), max_size_in_bytes)); @endcode * * @note The buffer is invalidated by any non-const operation called on the * given string object. */ template <typename Elem, typename Traits, typename Allocator> ASIO_NODISCARD inline ASIO_MUTABLE_BUFFER buffer( std::basic_string<Elem, Traits, Allocator>& data, std::size_t max_size_in_bytes) noexcept { return ASIO_MUTABLE_BUFFER(data.size() ? &data[0] : 0, data.size() * sizeof(Elem) < max_size_in_bytes ? data.size() * sizeof(Elem) : max_size_in_bytes #if defined(ASIO_ENABLE_BUFFER_DEBUGGING) , detail::buffer_debug_check< typename std::basic_string<Elem, Traits, Allocator>::iterator >(data.begin()) #endif // ASIO_ENABLE_BUFFER_DEBUGGING ); } /// Create a new non-modifiable buffer that represents the given string. /** * @returns <tt>const_buffer(data.data(), data.size() * sizeof(Elem))</tt>. * * @note The buffer is invalidated by any non-const operation called on the * given string object. */ template <typename Elem, typename Traits, typename Allocator> ASIO_NODISCARD inline ASIO_CONST_BUFFER buffer( const std::basic_string<Elem, Traits, Allocator>& data) noexcept { return ASIO_CONST_BUFFER(data.data(), data.size() * sizeof(Elem) #if defined(ASIO_ENABLE_BUFFER_DEBUGGING) , detail::buffer_debug_check< typename std::basic_string<Elem, Traits, Allocator>::const_iterator >(data.begin()) #endif // ASIO_ENABLE_BUFFER_DEBUGGING ); } /// Create a new non-modifiable buffer that represents the given string. /** * @returns A const_buffer value equivalent to: * @code const_buffer( * data.data(), * min(data.size() * sizeof(Elem), max_size_in_bytes)); @endcode * * @note The buffer is invalidated by any non-const operation called on the * given string object. */ template <typename Elem, typename Traits, typename Allocator> ASIO_NODISCARD inline ASIO_CONST_BUFFER buffer( const std::basic_string<Elem, Traits, Allocator>& data, std::size_t max_size_in_bytes) noexcept { return ASIO_CONST_BUFFER(data.data(), data.size() * sizeof(Elem) < max_size_in_bytes ? data.size() * sizeof(Elem) : max_size_in_bytes #if defined(ASIO_ENABLE_BUFFER_DEBUGGING) , detail::buffer_debug_check< typename std::basic_string<Elem, Traits, Allocator>::const_iterator >(data.begin()) #endif // ASIO_ENABLE_BUFFER_DEBUGGING ); } #if defined(ASIO_HAS_STRING_VIEW) \ || defined(GENERATING_DOCUMENTATION) /// Create a new non-modifiable buffer that represents the given string_view. /** * @returns <tt>mutable_buffer(data.size() ? &data[0] : 0, * data.size() * sizeof(Elem))</tt>. */ template <typename Elem, typename Traits> ASIO_NODISCARD inline ASIO_CONST_BUFFER buffer( basic_string_view<Elem, Traits> data) noexcept { return ASIO_CONST_BUFFER(data.size() ? &data[0] : 0, data.size() * sizeof(Elem) #if defined(ASIO_ENABLE_BUFFER_DEBUGGING) , detail::buffer_debug_check< typename basic_string_view<Elem, Traits>::iterator >(data.begin()) #endif // ASIO_ENABLE_BUFFER_DEBUGGING ); } /// Create a new non-modifiable buffer that represents the given string. /** * @returns A mutable_buffer value equivalent to: * @code mutable_buffer( * data.size() ? &data[0] : 0, * min(data.size() * sizeof(Elem), max_size_in_bytes)); @endcode */ template <typename Elem, typename Traits> ASIO_NODISCARD inline ASIO_CONST_BUFFER buffer( basic_string_view<Elem, Traits> data, std::size_t max_size_in_bytes) noexcept { return ASIO_CONST_BUFFER(data.size() ? &data[0] : 0, data.size() * sizeof(Elem) < max_size_in_bytes ? data.size() * sizeof(Elem) : max_size_in_bytes #if defined(ASIO_ENABLE_BUFFER_DEBUGGING) , detail::buffer_debug_check< typename basic_string_view<Elem, Traits>::iterator >(data.begin()) #endif // ASIO_ENABLE_BUFFER_DEBUGGING ); } #endif // defined(ASIO_HAS_STRING_VIEW) // || defined(GENERATING_DOCUMENTATION) /// Create a new modifiable buffer from a contiguous container. /** * @returns A mutable_buffer value equivalent to: * @code mutable_buffer( * data.size() ? &data[0] : 0, * data.size() * sizeof(typename T::value_type)); @endcode */ template <typename T> ASIO_NODISCARD inline ASIO_MUTABLE_BUFFER buffer( T& data, constraint_t< is_contiguous_iterator<typename T::iterator>::value, defaulted_constraint > = defaulted_constraint(), constraint_t< !is_convertible<T, const_buffer>::value, defaulted_constraint > = defaulted_constraint(), constraint_t< !is_convertible<T, mutable_buffer>::value, defaulted_constraint > = defaulted_constraint(), constraint_t< !is_const< remove_reference_t< typename std::iterator_traits<typename T::iterator>::reference > >::value, defaulted_constraint > = defaulted_constraint()) noexcept { return ASIO_MUTABLE_BUFFER( data.size() ? detail::to_address(data.begin()) : 0, data.size() * sizeof(typename T::value_type)); } /// Create a new modifiable buffer from a contiguous container. /** * @returns A mutable_buffer value equivalent to: * @code mutable_buffer( * data.size() ? &data[0] : 0, * min( * data.size() * sizeof(typename T::value_type), * max_size_in_bytes)); @endcode */ template <typename T> ASIO_NODISCARD inline ASIO_MUTABLE_BUFFER buffer( T& data, std::size_t max_size_in_bytes, constraint_t< is_contiguous_iterator<typename T::iterator>::value, defaulted_constraint > = defaulted_constraint(), constraint_t< !is_convertible<T, const_buffer>::value, defaulted_constraint > = defaulted_constraint(), constraint_t< !is_convertible<T, mutable_buffer>::value, defaulted_constraint > = defaulted_constraint(), constraint_t< !is_const< remove_reference_t< typename std::iterator_traits<typename T::iterator>::reference > >::value, defaulted_constraint > = defaulted_constraint()) noexcept { return ASIO_MUTABLE_BUFFER( data.size() ? detail::to_address(data.begin()) : 0, data.size() * sizeof(typename T::value_type) < max_size_in_bytes ? data.size() * sizeof(typename T::value_type) : max_size_in_bytes); } /// Create a new non-modifiable buffer from a contiguous container. /** * @returns A const_buffer value equivalent to: * @code const_buffer( * data.size() ? &data[0] : 0, * data.size() * sizeof(typename T::value_type)); @endcode */ template <typename T> ASIO_NODISCARD inline ASIO_CONST_BUFFER buffer( T& data, constraint_t< is_contiguous_iterator<typename T::iterator>::value, defaulted_constraint > = defaulted_constraint(), constraint_t< !is_convertible<T, const_buffer>::value, defaulted_constraint > = defaulted_constraint(), constraint_t< !is_convertible<T, mutable_buffer>::value, defaulted_constraint > = defaulted_constraint(), constraint_t< is_const< remove_reference_t< typename std::iterator_traits<typename T::iterator>::reference > >::value, defaulted_constraint > = defaulted_constraint()) noexcept { return ASIO_CONST_BUFFER( data.size() ? detail::to_address(data.begin()) : 0, data.size() * sizeof(typename T::value_type)); } /// Create a new non-modifiable buffer from a contiguous container. /** * @returns A const_buffer value equivalent to: * @code const_buffer( * data.size() ? &data[0] : 0, * min( * data.size() * sizeof(typename T::value_type), * max_size_in_bytes)); @endcode */ template <typename T> ASIO_NODISCARD inline ASIO_CONST_BUFFER buffer( T& data, std::size_t max_size_in_bytes, constraint_t< is_contiguous_iterator<typename T::iterator>::value, defaulted_constraint > = defaulted_constraint(), constraint_t< !is_convertible<T, const_buffer>::value, defaulted_constraint > = defaulted_constraint(), constraint_t< !is_convertible<T, mutable_buffer>::value, defaulted_constraint > = defaulted_constraint(), constraint_t< is_const< remove_reference_t< typename std::iterator_traits<typename T::iterator>::reference > >::value, defaulted_constraint > = defaulted_constraint()) noexcept { return ASIO_CONST_BUFFER( data.size() ? detail::to_address(data.begin()) : 0, data.size() * sizeof(typename T::value_type) < max_size_in_bytes ? data.size() * sizeof(typename T::value_type) : max_size_in_bytes); } /// Create a new non-modifiable buffer from a contiguous container. /** * @returns A const_buffer value equivalent to: * @code const_buffer( * data.size() ? &data[0] : 0, * data.size() * sizeof(typename T::value_type)); @endcode */ template <typename T> ASIO_NODISCARD inline ASIO_CONST_BUFFER buffer( const T& data, constraint_t< is_contiguous_iterator<typename T::const_iterator>::value, defaulted_constraint > = defaulted_constraint(), constraint_t< !is_convertible<T, const_buffer>::value, defaulted_constraint > = defaulted_constraint(), constraint_t< !is_convertible<T, mutable_buffer>::value, defaulted_constraint > = defaulted_constraint()) noexcept { return ASIO_CONST_BUFFER( data.size() ? detail::to_address(data.begin()) : 0, data.size() * sizeof(typename T::value_type)); } /// Create a new non-modifiable buffer from a contiguous container. /** * @returns A const_buffer value equivalent to: * @code const_buffer( * data.size() ? &data[0] : 0, * min( * data.size() * sizeof(typename T::value_type), * max_size_in_bytes)); @endcode */ template <typename T> ASIO_NODISCARD inline ASIO_CONST_BUFFER buffer( const T& data, std::size_t max_size_in_bytes, constraint_t< is_contiguous_iterator<typename T::const_iterator>::value, defaulted_constraint > = defaulted_constraint(), constraint_t< !is_convertible<T, const_buffer>::value, defaulted_constraint > = defaulted_constraint(), constraint_t< !is_convertible<T, mutable_buffer>::value, defaulted_constraint > = defaulted_constraint()) noexcept { return ASIO_CONST_BUFFER( data.size() ? detail::to_address(data.begin()) : 0, data.size() * sizeof(typename T::value_type) < max_size_in_bytes ? data.size() * sizeof(typename T::value_type) : max_size_in_bytes); } /*@}*/ /// Adapt a basic_string to the DynamicBuffer requirements. /** * Requires that <tt>sizeof(Elem) == 1</tt>. */ template <typename Elem, typename Traits, typename Allocator> class dynamic_string_buffer { public: /// The type used to represent a sequence of constant buffers that refers to /// the underlying memory. typedef ASIO_CONST_BUFFER const_buffers_type; /// The type used to represent a sequence of mutable buffers that refers to /// the underlying memory. typedef ASIO_MUTABLE_BUFFER mutable_buffers_type; /// Construct a dynamic buffer from a string. /** * @param s The string to be used as backing storage for the dynamic buffer. * The object stores a reference to the string and the user is responsible * for ensuring that the string object remains valid while the * dynamic_string_buffer object, and copies of the object, are in use. * * @b DynamicBuffer_v1: Any existing data in the string is treated as the * dynamic buffer's input sequence. * * @param maximum_size Specifies a maximum size for the buffer, in bytes. */ explicit dynamic_string_buffer(std::basic_string<Elem, Traits, Allocator>& s, std::size_t maximum_size = (std::numeric_limits<std::size_t>::max)()) noexcept : string_(s), #if !defined(ASIO_NO_DYNAMIC_BUFFER_V1) size_((std::numeric_limits<std::size_t>::max)()), #endif // !defined(ASIO_NO_DYNAMIC_BUFFER_V1) max_size_(maximum_size) { } /// @b DynamicBuffer_v2: Copy construct a dynamic buffer. dynamic_string_buffer(const dynamic_string_buffer& other) noexcept : string_(other.string_), #if !defined(ASIO_NO_DYNAMIC_BUFFER_V1) size_(other.size_), #endif // !defined(ASIO_NO_DYNAMIC_BUFFER_V1) max_size_(other.max_size_) { } /// Move construct a dynamic buffer. dynamic_string_buffer(dynamic_string_buffer&& other) noexcept : string_(other.string_), #if !defined(ASIO_NO_DYNAMIC_BUFFER_V1) size_(other.size_), #endif // !defined(ASIO_NO_DYNAMIC_BUFFER_V1) max_size_(other.max_size_) { } /// @b DynamicBuffer_v1: Get the size of the input sequence. /// @b DynamicBuffer_v2: Get the current size of the underlying memory. /** * @returns @b DynamicBuffer_v1 The current size of the input sequence. * @b DynamicBuffer_v2: The current size of the underlying string if less than * max_size(). Otherwise returns max_size(). */ std::size_t size() const noexcept { #if !defined(ASIO_NO_DYNAMIC_BUFFER_V1) if (size_ != (std::numeric_limits<std::size_t>::max)()) return size_; #endif // !defined(ASIO_NO_DYNAMIC_BUFFER_V1) return (std::min)(string_.size(), max_size()); } /// Get the maximum size of the dynamic buffer. /** * @returns The allowed maximum size of the underlying memory. */ std::size_t max_size() const noexcept { return max_size_; } /// Get the maximum size that the buffer may grow to without triggering /// reallocation. /** * @returns The current capacity of the underlying string if less than * max_size(). Otherwise returns max_size(). */ std::size_t capacity() const noexcept { return (std::min)(string_.capacity(), max_size()); } #if !defined(ASIO_NO_DYNAMIC_BUFFER_V1) /// @b DynamicBuffer_v1: Get a list of buffers that represents the input /// sequence. /** * @returns An object of type @c const_buffers_type that satisfies * ConstBufferSequence requirements, representing the basic_string memory in * the input sequence. * * @note The returned object is invalidated by any @c dynamic_string_buffer * or @c basic_string member function that resizes or erases the string. */ const_buffers_type data() const noexcept { return const_buffers_type(asio::buffer(string_, size_)); } #endif // !defined(ASIO_NO_DYNAMIC_BUFFER_V1) /// @b DynamicBuffer_v2: Get a sequence of buffers that represents the /// underlying memory. /** * @param pos Position of the first byte to represent in the buffer sequence * * @param n The number of bytes to return in the buffer sequence. If the * underlying memory is shorter, the buffer sequence represents as many bytes * as are available. * * @returns An object of type @c mutable_buffers_type that satisfies * MutableBufferSequence requirements, representing the basic_string memory. * * @note The returned object is invalidated by any @c dynamic_string_buffer * or @c basic_string member function that resizes or erases the string. */ mutable_buffers_type data(std::size_t pos, std::size_t n) noexcept { return mutable_buffers_type(asio::buffer( asio::buffer(string_, max_size_) + pos, n)); } /// @b DynamicBuffer_v2: Get a sequence of buffers that represents the /// underlying memory. /** * @param pos Position of the first byte to represent in the buffer sequence * * @param n The number of bytes to return in the buffer sequence. If the * underlying memory is shorter, the buffer sequence represents as many bytes * as are available. * * @note The returned object is invalidated by any @c dynamic_string_buffer * or @c basic_string member function that resizes or erases the string. */ const_buffers_type data(std::size_t pos, std::size_t n) const noexcept { return const_buffers_type(asio::buffer( asio::buffer(string_, max_size_) + pos, n)); } #if !defined(ASIO_NO_DYNAMIC_BUFFER_V1) /// @b DynamicBuffer_v1: Get a list of buffers that represents the output /// sequence, with the given size. /** * Ensures that the output sequence can accommodate @c n bytes, resizing the * basic_string object as necessary. * * @returns An object of type @c mutable_buffers_type that satisfies * MutableBufferSequence requirements, representing basic_string memory * at the start of the output sequence of size @c n. * * @throws std::length_error If <tt>size() + n > max_size()</tt>. * * @note The returned object is invalidated by any @c dynamic_string_buffer * or @c basic_string member function that modifies the input sequence or * output sequence. */ mutable_buffers_type prepare(std::size_t n) { if (size() > max_size() || max_size() - size() < n) { std::length_error ex("dynamic_string_buffer too long"); asio::detail::throw_exception(ex); } if (size_ == (std::numeric_limits<std::size_t>::max)()) size_ = string_.size(); // Enable v1 behaviour. string_.resize(size_ + n); return asio::buffer(asio::buffer(string_) + size_, n); } /// @b DynamicBuffer_v1: Move bytes from the output sequence to the input /// sequence. /** * @param n The number of bytes to append from the start of the output * sequence to the end of the input sequence. The remainder of the output * sequence is discarded. * * Requires a preceding call <tt>prepare(x)</tt> where <tt>x >= n</tt>, and * no intervening operations that modify the input or output sequence. * * @note If @c n is greater than the size of the output sequence, the entire * output sequence is moved to the input sequence and no error is issued. */ void commit(std::size_t n) { size_ += (std::min)(n, string_.size() - size_); string_.resize(size_); } #endif // !defined(ASIO_NO_DYNAMIC_BUFFER_V1) /// @b DynamicBuffer_v2: Grow the underlying memory by the specified number of /// bytes. /** * Resizes the string to accommodate an additional @c n bytes at the end. * * @throws std::length_error If <tt>size() + n > max_size()</tt>. */ void grow(std::size_t n) { if (size() > max_size() || max_size() - size() < n) { std::length_error ex("dynamic_string_buffer too long"); asio::detail::throw_exception(ex); } string_.resize(size() + n); } /// @b DynamicBuffer_v2: Shrink the underlying memory by the specified number /// of bytes. /** * Erases @c n bytes from the end of the string by resizing the basic_string * object. If @c n is greater than the current size of the string, the string * is emptied. */ void shrink(std::size_t n) { string_.resize(n > size() ? 0 : size() - n); } /// @b DynamicBuffer_v1: Remove characters from the input sequence. /// @b DynamicBuffer_v2: Consume the specified number of bytes from the /// beginning of the underlying memory. /** * @b DynamicBuffer_v1: Removes @c n characters from the beginning of the * input sequence. @note If @c n is greater than the size of the input * sequence, the entire input sequence is consumed and no error is issued. * * @b DynamicBuffer_v2: Erases @c n bytes from the beginning of the string. * If @c n is greater than the current size of the string, the string is * emptied. */ void consume(std::size_t n) { #if !defined(ASIO_NO_DYNAMIC_BUFFER_V1) if (size_ != (std::numeric_limits<std::size_t>::max)()) { std::size_t consume_length = (std::min)(n, size_); string_.erase(0, consume_length); size_ -= consume_length; return; } #endif // !defined(ASIO_NO_DYNAMIC_BUFFER_V1) string_.erase(0, n); } private: std::basic_string<Elem, Traits, Allocator>& string_; #if !defined(ASIO_NO_DYNAMIC_BUFFER_V1) std::size_t size_; #endif // !defined(ASIO_NO_DYNAMIC_BUFFER_V1) const std::size_t max_size_; }; /// Adapt a vector to the DynamicBuffer requirements. /** * Requires that <tt>sizeof(Elem) == 1</tt>. */ template <typename Elem, typename Allocator> class dynamic_vector_buffer { public: /// The type used to represent a sequence of constant buffers that refers to /// the underlying memory. typedef ASIO_CONST_BUFFER const_buffers_type; /// The type used to represent a sequence of mutable buffers that refers to /// the underlying memory. typedef ASIO_MUTABLE_BUFFER mutable_buffers_type; /// Construct a dynamic buffer from a vector. /** * @param v The vector to be used as backing storage for the dynamic buffer. * The object stores a reference to the vector and the user is responsible * for ensuring that the vector object remains valid while the * dynamic_vector_buffer object, and copies of the object, are in use. * * @param maximum_size Specifies a maximum size for the buffer, in bytes. */ explicit dynamic_vector_buffer(std::vector<Elem, Allocator>& v, std::size_t maximum_size = (std::numeric_limits<std::size_t>::max)()) noexcept : vector_(v), #if !defined(ASIO_NO_DYNAMIC_BUFFER_V1) size_((std::numeric_limits<std::size_t>::max)()), #endif // !defined(ASIO_NO_DYNAMIC_BUFFER_V1) max_size_(maximum_size) { } /// @b DynamicBuffer_v2: Copy construct a dynamic buffer. dynamic_vector_buffer(const dynamic_vector_buffer& other) noexcept : vector_(other.vector_), #if !defined(ASIO_NO_DYNAMIC_BUFFER_V1) size_(other.size_), #endif // !defined(ASIO_NO_DYNAMIC_BUFFER_V1) max_size_(other.max_size_) { } /// Move construct a dynamic buffer. dynamic_vector_buffer(dynamic_vector_buffer&& other) noexcept : vector_(other.vector_), #if !defined(ASIO_NO_DYNAMIC_BUFFER_V1) size_(other.size_), #endif // !defined(ASIO_NO_DYNAMIC_BUFFER_V1) max_size_(other.max_size_) { } /// @b DynamicBuffer_v1: Get the size of the input sequence. /// @b DynamicBuffer_v2: Get the current size of the underlying memory. /** * @returns @b DynamicBuffer_v1 The current size of the input sequence. * @b DynamicBuffer_v2: The current size of the underlying vector if less than * max_size(). Otherwise returns max_size(). */ std::size_t size() const noexcept { #if !defined(ASIO_NO_DYNAMIC_BUFFER_V1) if (size_ != (std::numeric_limits<std::size_t>::max)()) return size_; #endif // !defined(ASIO_NO_DYNAMIC_BUFFER_V1) return (std::min)(vector_.size(), max_size()); } /// Get the maximum size of the dynamic buffer. /** * @returns @b DynamicBuffer_v1: The allowed maximum of the sum of the sizes * of the input sequence and output sequence. @b DynamicBuffer_v2: The allowed * maximum size of the underlying memory. */ std::size_t max_size() const noexcept { return max_size_; } /// Get the maximum size that the buffer may grow to without triggering /// reallocation. /** * @returns @b DynamicBuffer_v1: The current total capacity of the buffer, * i.e. for both the input sequence and output sequence. @b DynamicBuffer_v2: * The current capacity of the underlying vector if less than max_size(). * Otherwise returns max_size(). */ std::size_t capacity() const noexcept { return (std::min)(vector_.capacity(), max_size()); } #if !defined(ASIO_NO_DYNAMIC_BUFFER_V1) /// @b DynamicBuffer_v1: Get a list of buffers that represents the input /// sequence. /** * @returns An object of type @c const_buffers_type that satisfies * ConstBufferSequence requirements, representing the vector memory in the * input sequence. * * @note The returned object is invalidated by any @c dynamic_vector_buffer * or @c vector member function that modifies the input sequence or output * sequence. */ const_buffers_type data() const noexcept { return const_buffers_type(asio::buffer(vector_, size_)); } #endif // !defined(ASIO_NO_DYNAMIC_BUFFER_V1) /// @b DynamicBuffer_v2: Get a sequence of buffers that represents the /// underlying memory. /** * @param pos Position of the first byte to represent in the buffer sequence * * @param n The number of bytes to return in the buffer sequence. If the * underlying memory is shorter, the buffer sequence represents as many bytes * as are available. * * @returns An object of type @c mutable_buffers_type that satisfies * MutableBufferSequence requirements, representing the vector memory. * * @note The returned object is invalidated by any @c dynamic_vector_buffer * or @c vector member function that resizes or erases the vector. */ mutable_buffers_type data(std::size_t pos, std::size_t n) noexcept { return mutable_buffers_type(asio::buffer( asio::buffer(vector_, max_size_) + pos, n)); } /// @b DynamicBuffer_v2: Get a sequence of buffers that represents the /// underlying memory. /** * @param pos Position of the first byte to represent in the buffer sequence * * @param n The number of bytes to return in the buffer sequence. If the * underlying memory is shorter, the buffer sequence represents as many bytes * as are available. * * @note The returned object is invalidated by any @c dynamic_vector_buffer * or @c vector member function that resizes or erases the vector. */ const_buffers_type data(std::size_t pos, std::size_t n) const noexcept { return const_buffers_type(asio::buffer( asio::buffer(vector_, max_size_) + pos, n)); } #if !defined(ASIO_NO_DYNAMIC_BUFFER_V1) /// @b DynamicBuffer_v1: Get a list of buffers that represents the output /// sequence, with the given size. /** * Ensures that the output sequence can accommodate @c n bytes, resizing the * vector object as necessary. * * @returns An object of type @c mutable_buffers_type that satisfies * MutableBufferSequence requirements, representing vector memory at the * start of the output sequence of size @c n. * * @throws std::length_error If <tt>size() + n > max_size()</tt>. * * @note The returned object is invalidated by any @c dynamic_vector_buffer * or @c vector member function that modifies the input sequence or output * sequence. */ mutable_buffers_type prepare(std::size_t n) { if (size () > max_size() || max_size() - size() < n) { std::length_error ex("dynamic_vector_buffer too long"); asio::detail::throw_exception(ex); } if (size_ == (std::numeric_limits<std::size_t>::max)()) size_ = vector_.size(); // Enable v1 behaviour. vector_.resize(size_ + n); return asio::buffer(asio::buffer(vector_) + size_, n); } /// @b DynamicBuffer_v1: Move bytes from the output sequence to the input /// sequence. /** * @param n The number of bytes to append from the start of the output * sequence to the end of the input sequence. The remainder of the output * sequence is discarded. * * Requires a preceding call <tt>prepare(x)</tt> where <tt>x >= n</tt>, and * no intervening operations that modify the input or output sequence. * * @note If @c n is greater than the size of the output sequence, the entire * output sequence is moved to the input sequence and no error is issued. */ void commit(std::size_t n) { size_ += (std::min)(n, vector_.size() - size_); vector_.resize(size_); } #endif // !defined(ASIO_NO_DYNAMIC_BUFFER_V1) /// @b DynamicBuffer_v2: Grow the underlying memory by the specified number of /// bytes. /** * Resizes the vector to accommodate an additional @c n bytes at the end. * * @throws std::length_error If <tt>size() + n > max_size()</tt>. */ void grow(std::size_t n) { if (size() > max_size() || max_size() - size() < n) { std::length_error ex("dynamic_vector_buffer too long"); asio::detail::throw_exception(ex); } vector_.resize(size() + n); } /// @b DynamicBuffer_v2: Shrink the underlying memory by the specified number /// of bytes. /** * Erases @c n bytes from the end of the vector by resizing the vector * object. If @c n is greater than the current size of the vector, the vector * is emptied. */ void shrink(std::size_t n) { vector_.resize(n > size() ? 0 : size() - n); } /// @b DynamicBuffer_v1: Remove characters from the input sequence. /// @b DynamicBuffer_v2: Consume the specified number of bytes from the /// beginning of the underlying memory. /** * @b DynamicBuffer_v1: Removes @c n characters from the beginning of the * input sequence. @note If @c n is greater than the size of the input * sequence, the entire input sequence is consumed and no error is issued. * * @b DynamicBuffer_v2: Erases @c n bytes from the beginning of the vector. * If @c n is greater than the current size of the vector, the vector is * emptied. */ void consume(std::size_t n) { #if !defined(ASIO_NO_DYNAMIC_BUFFER_V1) if (size_ != (std::numeric_limits<std::size_t>::max)()) { std::size_t consume_length = (std::min)(n, size_); vector_.erase(vector_.begin(), vector_.begin() + consume_length); size_ -= consume_length; return; } #endif // !defined(ASIO_NO_DYNAMIC_BUFFER_V1) vector_.erase(vector_.begin(), vector_.begin() + (std::min)(size(), n)); } private: std::vector<Elem, Allocator>& vector_; #if !defined(ASIO_NO_DYNAMIC_BUFFER_V1) std::size_t size_; #endif // !defined(ASIO_NO_DYNAMIC_BUFFER_V1) const std::size_t max_size_; }; /** @defgroup dynamic_buffer asio::dynamic_buffer * * @brief The asio::dynamic_buffer function is used to create a * dynamically resized buffer from a @c std::basic_string or @c std::vector. */ /*@{*/ /// Create a new dynamic buffer that represents the given string. /** * @returns <tt>dynamic_string_buffer<Elem, Traits, Allocator>(data)</tt>. */ template <typename Elem, typename Traits, typename Allocator> ASIO_NODISCARD inline dynamic_string_buffer<Elem, Traits, Allocator> dynamic_buffer( std::basic_string<Elem, Traits, Allocator>& data) noexcept { return dynamic_string_buffer<Elem, Traits, Allocator>(data); } /// Create a new dynamic buffer that represents the given string. /** * @returns <tt>dynamic_string_buffer<Elem, Traits, Allocator>(data, * max_size)</tt>. */ template <typename Elem, typename Traits, typename Allocator> ASIO_NODISCARD inline dynamic_string_buffer<Elem, Traits, Allocator> dynamic_buffer( std::basic_string<Elem, Traits, Allocator>& data, std::size_t max_size) noexcept { return dynamic_string_buffer<Elem, Traits, Allocator>(data, max_size); } /// Create a new dynamic buffer that represents the given vector. /** * @returns <tt>dynamic_vector_buffer<Elem, Allocator>(data)</tt>. */ template <typename Elem, typename Allocator> ASIO_NODISCARD inline dynamic_vector_buffer<Elem, Allocator> dynamic_buffer( std::vector<Elem, Allocator>& data) noexcept { return dynamic_vector_buffer<Elem, Allocator>(data); } /// Create a new dynamic buffer that represents the given vector. /** * @returns <tt>dynamic_vector_buffer<Elem, Allocator>(data, max_size)</tt>. */ template <typename Elem, typename Allocator> ASIO_NODISCARD inline dynamic_vector_buffer<Elem, Allocator> dynamic_buffer( std::vector<Elem, Allocator>& data, std::size_t max_size) noexcept { return dynamic_vector_buffer<Elem, Allocator>(data, max_size); } /*@}*/ /** @defgroup buffer_copy asio::buffer_copy * * @brief The asio::buffer_copy function is used to copy bytes from a * source buffer (or buffer sequence) to a target buffer (or buffer sequence). * * The @c buffer_copy function is available in two forms: * * @li A 2-argument form: @c buffer_copy(target, source) * * @li A 3-argument form: @c buffer_copy(target, source, max_bytes_to_copy) * * Both forms return the number of bytes actually copied. The number of bytes * copied is the lesser of: * * @li @c buffer_size(target) * * @li @c buffer_size(source) * * @li @c If specified, @c max_bytes_to_copy. * * This prevents buffer overflow, regardless of the buffer sizes used in the * copy operation. * * Note that @ref buffer_copy is implemented in terms of @c memcpy, and * consequently it cannot be used to copy between overlapping memory regions. */ /*@{*/ namespace detail { inline std::size_t buffer_copy_1(const mutable_buffer& target, const const_buffer& source) { using namespace std; // For memcpy. std::size_t target_size = target.size(); std::size_t source_size = source.size(); std::size_t n = target_size < source_size ? target_size : source_size; if (n > 0) memcpy(target.data(), source.data(), n); return n; } template <typename TargetIterator, typename SourceIterator> inline std::size_t buffer_copy(one_buffer, one_buffer, TargetIterator target_begin, TargetIterator, SourceIterator source_begin, SourceIterator) noexcept { return (buffer_copy_1)(*target_begin, *source_begin); } template <typename TargetIterator, typename SourceIterator> inline std::size_t buffer_copy(one_buffer, one_buffer, TargetIterator target_begin, TargetIterator, SourceIterator source_begin, SourceIterator, std::size_t max_bytes_to_copy) noexcept { return (buffer_copy_1)(*target_begin, asio::buffer(*source_begin, max_bytes_to_copy)); } template <typename TargetIterator, typename SourceIterator> std::size_t buffer_copy(one_buffer, multiple_buffers, TargetIterator target_begin, TargetIterator, SourceIterator source_begin, SourceIterator source_end, std::size_t max_bytes_to_copy = (std::numeric_limits<std::size_t>::max)()) noexcept { std::size_t total_bytes_copied = 0; SourceIterator source_iter = source_begin; for (mutable_buffer target_buffer( asio::buffer(*target_begin, max_bytes_to_copy)); target_buffer.size() && source_iter != source_end; ++source_iter) { const_buffer source_buffer(*source_iter); std::size_t bytes_copied = (buffer_copy_1)(target_buffer, source_buffer); total_bytes_copied += bytes_copied; target_buffer += bytes_copied; } return total_bytes_copied; } template <typename TargetIterator, typename SourceIterator> std::size_t buffer_copy(multiple_buffers, one_buffer, TargetIterator target_begin, TargetIterator target_end, SourceIterator source_begin, SourceIterator, std::size_t max_bytes_to_copy = (std::numeric_limits<std::size_t>::max)()) noexcept { std::size_t total_bytes_copied = 0; TargetIterator target_iter = target_begin; for (const_buffer source_buffer( asio::buffer(*source_begin, max_bytes_to_copy)); source_buffer.size() && target_iter != target_end; ++target_iter) { mutable_buffer target_buffer(*target_iter); std::size_t bytes_copied = (buffer_copy_1)(target_buffer, source_buffer); total_bytes_copied += bytes_copied; source_buffer += bytes_copied; } return total_bytes_copied; } template <typename TargetIterator, typename SourceIterator> std::size_t buffer_copy(multiple_buffers, multiple_buffers, TargetIterator target_begin, TargetIterator target_end, SourceIterator source_begin, SourceIterator source_end) noexcept { std::size_t total_bytes_copied = 0; TargetIterator target_iter = target_begin; std::size_t target_buffer_offset = 0; SourceIterator source_iter = source_begin; std::size_t source_buffer_offset = 0; while (target_iter != target_end && source_iter != source_end) { mutable_buffer target_buffer = mutable_buffer(*target_iter) + target_buffer_offset; const_buffer source_buffer = const_buffer(*source_iter) + source_buffer_offset; std::size_t bytes_copied = (buffer_copy_1)(target_buffer, source_buffer); total_bytes_copied += bytes_copied; if (bytes_copied == target_buffer.size()) { ++target_iter; target_buffer_offset = 0; } else target_buffer_offset += bytes_copied; if (bytes_copied == source_buffer.size()) { ++source_iter; source_buffer_offset = 0; } else source_buffer_offset += bytes_copied; } return total_bytes_copied; } template <typename TargetIterator, typename SourceIterator> std::size_t buffer_copy(multiple_buffers, multiple_buffers, TargetIterator target_begin, TargetIterator target_end, SourceIterator source_begin, SourceIterator source_end, std::size_t max_bytes_to_copy) noexcept { std::size_t total_bytes_copied = 0; TargetIterator target_iter = target_begin; std::size_t target_buffer_offset = 0; SourceIterator source_iter = source_begin; std::size_t source_buffer_offset = 0; while (total_bytes_copied != max_bytes_to_copy && target_iter != target_end && source_iter != source_end) { mutable_buffer target_buffer = mutable_buffer(*target_iter) + target_buffer_offset; const_buffer source_buffer = const_buffer(*source_iter) + source_buffer_offset; std::size_t bytes_copied = (buffer_copy_1)( target_buffer, asio::buffer(source_buffer, max_bytes_to_copy - total_bytes_copied)); total_bytes_copied += bytes_copied; if (bytes_copied == target_buffer.size()) { ++target_iter; target_buffer_offset = 0; } else target_buffer_offset += bytes_copied; if (bytes_copied == source_buffer.size()) { ++source_iter; source_buffer_offset = 0; } else source_buffer_offset += bytes_copied; } return total_bytes_copied; } } // namespace detail /// Copies bytes from a source buffer sequence to a target buffer sequence. /** * @param target A modifiable buffer sequence representing the memory regions to * which the bytes will be copied. * * @param source A non-modifiable buffer sequence representing the memory * regions from which the bytes will be copied. * * @returns The number of bytes copied. * * @note The number of bytes copied is the lesser of: * * @li @c buffer_size(target) * * @li @c buffer_size(source) * * This function is implemented in terms of @c memcpy, and consequently it * cannot be used to copy between overlapping memory regions. */ template <typename MutableBufferSequence, typename ConstBufferSequence> inline std::size_t buffer_copy(const MutableBufferSequence& target, const ConstBufferSequence& source) noexcept { return detail::buffer_copy( detail::buffer_sequence_cardinality<MutableBufferSequence>(), detail::buffer_sequence_cardinality<ConstBufferSequence>(), asio::buffer_sequence_begin(target), asio::buffer_sequence_end(target), asio::buffer_sequence_begin(source), asio::buffer_sequence_end(source)); } /// Copies a limited number of bytes from a source buffer sequence to a target /// buffer sequence. /** * @param target A modifiable buffer sequence representing the memory regions to * which the bytes will be copied. * * @param source A non-modifiable buffer sequence representing the memory * regions from which the bytes will be copied. * * @param max_bytes_to_copy The maximum number of bytes to be copied. * * @returns The number of bytes copied. * * @note The number of bytes copied is the lesser of: * * @li @c buffer_size(target) * * @li @c buffer_size(source) * * @li @c max_bytes_to_copy * * This function is implemented in terms of @c memcpy, and consequently it * cannot be used to copy between overlapping memory regions. */ template <typename MutableBufferSequence, typename ConstBufferSequence> inline std::size_t buffer_copy(const MutableBufferSequence& target, const ConstBufferSequence& source, std::size_t max_bytes_to_copy) noexcept { return detail::buffer_copy( detail::buffer_sequence_cardinality<MutableBufferSequence>(), detail::buffer_sequence_cardinality<ConstBufferSequence>(), asio::buffer_sequence_begin(target), asio::buffer_sequence_end(target), asio::buffer_sequence_begin(source), asio::buffer_sequence_end(source), max_bytes_to_copy); } /*@}*/ } // namespace asio #include "asio/detail/pop_options.hpp" #include "asio/detail/is_buffer_sequence.hpp" #include "asio/detail/push_options.hpp" namespace asio { /// Trait to determine whether a type satisfies the MutableBufferSequence /// requirements. template <typename T> struct is_mutable_buffer_sequence #if defined(GENERATING_DOCUMENTATION) : integral_constant<bool, automatically_determined> #else // defined(GENERATING_DOCUMENTATION) : asio::detail::is_buffer_sequence<T, mutable_buffer> #endif // defined(GENERATING_DOCUMENTATION) { }; /// Trait to determine whether a type satisfies the ConstBufferSequence /// requirements. template <typename T> struct is_const_buffer_sequence #if defined(GENERATING_DOCUMENTATION) : integral_constant<bool, automatically_determined> #else // defined(GENERATING_DOCUMENTATION) : asio::detail::is_buffer_sequence<T, const_buffer> #endif // defined(GENERATING_DOCUMENTATION) { }; #if !defined(ASIO_NO_DYNAMIC_BUFFER_V1) /// Trait to determine whether a type satisfies the DynamicBuffer_v1 /// requirements. template <typename T> struct is_dynamic_buffer_v1 #if defined(GENERATING_DOCUMENTATION) : integral_constant<bool, automatically_determined> #else // defined(GENERATING_DOCUMENTATION) : asio::detail::is_dynamic_buffer_v1<T> #endif // defined(GENERATING_DOCUMENTATION) { }; #endif // !defined(ASIO_NO_DYNAMIC_BUFFER_V1) /// Trait to determine whether a type satisfies the DynamicBuffer_v2 /// requirements. template <typename T> struct is_dynamic_buffer_v2 #if defined(GENERATING_DOCUMENTATION) : integral_constant<bool, automatically_determined> #else // defined(GENERATING_DOCUMENTATION) : asio::detail::is_dynamic_buffer_v2<T> #endif // defined(GENERATING_DOCUMENTATION) { }; /// Trait to determine whether a type satisfies the DynamicBuffer requirements. /** * If @c ASIO_NO_DYNAMIC_BUFFER_V1 is not defined, determines whether the * type satisfies the DynamicBuffer_v1 requirements. Otherwise, if @c * ASIO_NO_DYNAMIC_BUFFER_V1 is defined, determines whether the type * satisfies the DynamicBuffer_v2 requirements. */ template <typename T> struct is_dynamic_buffer #if defined(GENERATING_DOCUMENTATION) : integral_constant<bool, automatically_determined> #elif defined(ASIO_NO_DYNAMIC_BUFFER_V1) : asio::is_dynamic_buffer_v2<T> #else // defined(ASIO_NO_DYNAMIC_BUFFER_V1) : asio::is_dynamic_buffer_v1<T> #endif // defined(ASIO_NO_DYNAMIC_BUFFER_V1) { }; namespace buffer_literals { namespace detail { template <char... Chars> struct chars {}; template <unsigned char... Bytes> struct bytes {}; // Literal processor that converts binary literals to an array of bytes. template <typename Bytes, char... Chars> struct bin_literal; template <unsigned char... Bytes> struct bin_literal<bytes<Bytes...>> { static const std::size_t size = sizeof...(Bytes); static const unsigned char data[sizeof...(Bytes)]; }; template <unsigned char... Bytes> const unsigned char bin_literal<bytes<Bytes...>>::data[sizeof...(Bytes)] = { Bytes... }; template <unsigned char... Bytes, char Bit7, char Bit6, char Bit5, char Bit4, char Bit3, char Bit2, char Bit1, char Bit0, char... Chars> struct bin_literal<bytes<Bytes...>, Bit7, Bit6, Bit5, Bit4, Bit3, Bit2, Bit1, Bit0, Chars...> : bin_literal< bytes<Bytes..., static_cast<unsigned char>( (Bit7 == '1' ? 0x80 : 0) | (Bit6 == '1' ? 0x40 : 0) | (Bit5 == '1' ? 0x20 : 0) | (Bit4 == '1' ? 0x10 : 0) | (Bit3 == '1' ? 0x08 : 0) | (Bit2 == '1' ? 0x04 : 0) | (Bit1 == '1' ? 0x02 : 0) | (Bit0 == '1' ? 0x01 : 0)) >, Chars...> {}; template <unsigned char... Bytes, char... Chars> struct bin_literal<bytes<Bytes...>, Chars...> { static_assert(sizeof...(Chars) == 0, "number of digits in a binary buffer literal must be a multiple of 8"); static const std::size_t size = 0; static const unsigned char data[1]; }; template <unsigned char... Bytes, char... Chars> const unsigned char bin_literal<bytes<Bytes...>, Chars...>::data[1] = {}; // Literal processor that converts hexadecimal literals to an array of bytes. template <typename Bytes, char... Chars> struct hex_literal; template <unsigned char... Bytes> struct hex_literal<bytes<Bytes...>> { static const std::size_t size = sizeof...(Bytes); static const unsigned char data[sizeof...(Bytes)]; }; template <unsigned char... Bytes> const unsigned char hex_literal<bytes<Bytes...>>::data[sizeof...(Bytes)] = { Bytes... }; template <unsigned char... Bytes, char Hi, char Lo, char... Chars> struct hex_literal<bytes<Bytes...>, Hi, Lo, Chars...> : hex_literal< bytes<Bytes..., static_cast<unsigned char>( Lo >= 'A' && Lo <= 'F' ? Lo - 'A' + 10 : (Lo >= 'a' && Lo <= 'f' ? Lo - 'a' + 10 : Lo - '0')) | ((static_cast<unsigned char>( Hi >= 'A' && Hi <= 'F' ? Hi - 'A' + 10 : (Hi >= 'a' && Hi <= 'f' ? Hi - 'a' + 10 : Hi - '0'))) << 4) >, Chars...> {}; template <unsigned char... Bytes, char Char> struct hex_literal<bytes<Bytes...>, Char> { static_assert(!Char, "a hexadecimal buffer literal must have an even number of digits"); static const std::size_t size = 0; static const unsigned char data[1]; }; template <unsigned char... Bytes, char Char> const unsigned char hex_literal<bytes<Bytes...>, Char>::data[1] = {}; // Helper template that removes digit separators and then passes the cleaned // variadic pack of characters to the literal processor. template <template <typename, char...> class Literal, typename Clean, char... Raw> struct remove_separators; template <template <typename, char...> class Literal, char... Clean, char... Raw> struct remove_separators<Literal, chars<Clean...>, '\'', Raw...> : remove_separators<Literal, chars<Clean...>, Raw...> {}; template <template <typename, char...> class Literal, char... Clean, char C, char... Raw> struct remove_separators<Literal, chars<Clean...>, C, Raw...> : remove_separators<Literal, chars<Clean..., C>, Raw...> {}; template <template <typename, char...> class Literal, char... Clean> struct remove_separators<Literal, chars<Clean...>> : Literal<bytes<>, Clean...> {}; // Helper template to determine the literal type based on the prefix. template <char... Chars> struct literal; template <char... Chars> struct literal<'0', 'b', Chars...> : remove_separators<bin_literal, chars<>, Chars...>{}; template <char... Chars> struct literal<'0', 'B', Chars...> : remove_separators<bin_literal, chars<>, Chars...>{}; template <char... Chars> struct literal<'0', 'x', Chars...> : remove_separators<hex_literal, chars<>, Chars...>{}; template <char... Chars> struct literal<'0', 'X', Chars...> : remove_separators<hex_literal, chars<>, Chars...>{}; } // namespace detail /// Literal operator for creating const_buffer objects from string literals. inline ASIO_CONST_BUFFER operator ""_buf(const char* data, std::size_t n) { return ASIO_CONST_BUFFER(data, n); } /// Literal operator for creating const_buffer objects from unbounded binary or /// hexadecimal integer literals. template <char... Chars> inline ASIO_CONST_BUFFER operator ""_buf() { return ASIO_CONST_BUFFER( +detail::literal<Chars...>::data, detail::literal<Chars...>::size); } } // namespace buffer_literals } // namespace asio #include "asio/detail/pop_options.hpp" #endif // ASIO_BUFFER_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/wait_traits.hpp
// // wait_traits.hpp // ~~~~~~~~~~~~~~~ // // 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) // #ifndef ASIO_WAIT_TRAITS_HPP #define ASIO_WAIT_TRAITS_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/push_options.hpp" namespace asio { /// Wait traits suitable for use with the basic_waitable_timer class template. template <typename Clock> struct wait_traits { /// Convert a clock duration into a duration used for waiting. /** * @returns @c d. */ static typename Clock::duration to_wait_duration( const typename Clock::duration& d) { return d; } /// Convert a clock duration into a duration used for waiting. /** * @returns @c d. */ static typename Clock::duration to_wait_duration( const typename Clock::time_point& t) { typename Clock::time_point now = Clock::now(); if (now + (Clock::duration::max)() < t) return (Clock::duration::max)(); if (now + (Clock::duration::min)() > t) return (Clock::duration::min)(); return t - now; } }; } // namespace asio #include "asio/detail/pop_options.hpp" #endif // ASIO_WAIT_TRAITS_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/buffered_stream_fwd.hpp
// // buffered_stream_fwd.hpp // ~~~~~~~~~~~~~~~~~~~~~~~ // // 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) // #ifndef ASIO_BUFFERED_STREAM_FWD_HPP #define ASIO_BUFFERED_STREAM_FWD_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) namespace asio { template <typename Stream> class buffered_stream; } // namespace asio #endif // ASIO_BUFFERED_STREAM_FWD_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/system_executor.hpp
// // system_executor.hpp // ~~~~~~~~~~~~~~~~~~~ // // 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) // #ifndef ASIO_SYSTEM_EXECUTOR_HPP #define ASIO_SYSTEM_EXECUTOR_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include "asio/detail/memory.hpp" #include "asio/execution.hpp" #include "asio/detail/push_options.hpp" namespace asio { class system_context; /// An executor that uses arbitrary threads. /** * The system executor represents an execution context where functions are * permitted to run on arbitrary threads. When the blocking.never property is * established, the system executor will schedule the function to run on an * unspecified system thread pool. When either blocking.possibly or * blocking.always is established, the executor invokes the function * immediately. */ template <typename Blocking, typename Relationship, typename Allocator> class basic_system_executor { public: /// Default constructor. basic_system_executor() noexcept : allocator_(Allocator()) { } #if !defined(GENERATING_DOCUMENTATION) private: friend struct asio_require_fn::impl; friend struct asio_prefer_fn::impl; #endif // !defined(GENERATING_DOCUMENTATION) /// Obtain an executor with the @c blocking.possibly property. /** * Do not call this function directly. It is intended for use with the * asio::require customisation point. * * For example: * @code asio::system_executor ex1; * auto ex2 = asio::require(ex1, * asio::execution::blocking.possibly); @endcode */ basic_system_executor<execution::blocking_t::possibly_t, Relationship, Allocator> require(execution::blocking_t::possibly_t) const { return basic_system_executor<execution::blocking_t::possibly_t, Relationship, Allocator>(allocator_); } /// Obtain an executor with the @c blocking.always property. /** * Do not call this function directly. It is intended for use with the * asio::require customisation point. * * For example: * @code asio::system_executor ex1; * auto ex2 = asio::require(ex1, * asio::execution::blocking.always); @endcode */ basic_system_executor<execution::blocking_t::always_t, Relationship, Allocator> require(execution::blocking_t::always_t) const { return basic_system_executor<execution::blocking_t::always_t, Relationship, Allocator>(allocator_); } /// Obtain an executor with the @c blocking.never property. /** * Do not call this function directly. It is intended for use with the * asio::require customisation point. * * For example: * @code asio::system_executor ex1; * auto ex2 = asio::require(ex1, * asio::execution::blocking.never); @endcode */ basic_system_executor<execution::blocking_t::never_t, Relationship, Allocator> require(execution::blocking_t::never_t) const { return basic_system_executor<execution::blocking_t::never_t, Relationship, Allocator>(allocator_); } /// Obtain an executor with the @c relationship.continuation property. /** * Do not call this function directly. It is intended for use with the * asio::require customisation point. * * For example: * @code asio::system_executor ex1; * auto ex2 = asio::require(ex1, * asio::execution::relationship.continuation); @endcode */ basic_system_executor<Blocking, execution::relationship_t::continuation_t, Allocator> require(execution::relationship_t::continuation_t) const { return basic_system_executor<Blocking, execution::relationship_t::continuation_t, Allocator>(allocator_); } /// Obtain an executor with the @c relationship.fork property. /** * Do not call this function directly. It is intended for use with the * asio::require customisation point. * * For example: * @code asio::system_executor ex1; * auto ex2 = asio::require(ex1, * asio::execution::relationship.fork); @endcode */ basic_system_executor<Blocking, execution::relationship_t::fork_t, Allocator> require(execution::relationship_t::fork_t) const { return basic_system_executor<Blocking, execution::relationship_t::fork_t, Allocator>(allocator_); } /// Obtain an executor with the specified @c allocator property. /** * Do not call this function directly. It is intended for use with the * asio::require customisation point. * * For example: * @code asio::system_executor ex1; * auto ex2 = asio::require(ex1, * asio::execution::allocator(my_allocator)); @endcode */ template <typename OtherAllocator> basic_system_executor<Blocking, Relationship, OtherAllocator> require(execution::allocator_t<OtherAllocator> a) const { return basic_system_executor<Blocking, Relationship, OtherAllocator>(a.value()); } /// Obtain an executor with the default @c allocator property. /** * Do not call this function directly. It is intended for use with the * asio::require customisation point. * * For example: * @code asio::system_executor ex1; * auto ex2 = asio::require(ex1, * asio::execution::allocator); @endcode */ basic_system_executor<Blocking, Relationship, std::allocator<void>> require(execution::allocator_t<void>) const { return basic_system_executor<Blocking, Relationship, std::allocator<void>>(); } #if !defined(GENERATING_DOCUMENTATION) private: friend struct asio_query_fn::impl; friend struct asio::execution::detail::blocking_t<0>; friend struct asio::execution::detail::mapping_t<0>; friend struct asio::execution::detail::outstanding_work_t<0>; friend struct asio::execution::detail::relationship_t<0>; #endif // !defined(GENERATING_DOCUMENTATION) /// Query the current value of the @c mapping property. /** * Do not call this function directly. It is intended for use with the * asio::query customisation point. * * For example: * @code asio::system_executor ex; * if (asio::query(ex, asio::execution::mapping) * == asio::execution::mapping.thread) * ... @endcode */ static constexpr execution::mapping_t query( execution::mapping_t) noexcept { return execution::mapping.thread; } /// Query the current value of the @c context property. /** * Do not call this function directly. It is intended for use with the * asio::query customisation point. * * For example: * @code asio::system_executor ex; * asio::system_context& pool = asio::query( * ex, asio::execution::context); @endcode */ static system_context& query(execution::context_t) noexcept; /// Query the current value of the @c blocking property. /** * Do not call this function directly. It is intended for use with the * asio::query customisation point. * * For example: * @code asio::system_executor ex; * if (asio::query(ex, asio::execution::blocking) * == asio::execution::blocking.always) * ... @endcode */ static constexpr execution::blocking_t query( execution::blocking_t) noexcept { return Blocking(); } /// Query the current value of the @c relationship property. /** * Do not call this function directly. It is intended for use with the * asio::query customisation point. * * For example: * @code asio::system_executor ex; * if (asio::query(ex, asio::execution::relationship) * == asio::execution::relationship.continuation) * ... @endcode */ static constexpr execution::relationship_t query( execution::relationship_t) noexcept { return Relationship(); } /// Query the current value of the @c allocator property. /** * Do not call this function directly. It is intended for use with the * asio::query customisation point. * * For example: * @code asio::system_executor ex; * auto alloc = asio::query(ex, * asio::execution::allocator); @endcode */ template <typename OtherAllocator> constexpr Allocator query( execution::allocator_t<OtherAllocator>) const noexcept { return allocator_; } /// Query the current value of the @c allocator property. /** * Do not call this function directly. It is intended for use with the * asio::query customisation point. * * For example: * @code asio::system_executor ex; * auto alloc = asio::query(ex, * asio::execution::allocator); @endcode */ constexpr Allocator query( execution::allocator_t<void>) const noexcept { return allocator_; } /// Query the occupancy (recommended number of work items) for the system /// context. /** * Do not call this function directly. It is intended for use with the * asio::query customisation point. * * For example: * @code asio::system_executor ex; * std::size_t occupancy = asio::query( * ex, asio::execution::occupancy); @endcode */ std::size_t query(execution::occupancy_t) const noexcept; public: /// Compare two executors for equality. /** * Two executors are equal if they refer to the same underlying io_context. */ friend bool operator==(const basic_system_executor&, const basic_system_executor&) noexcept { return true; } /// Compare two executors for inequality. /** * Two executors are equal if they refer to the same underlying io_context. */ friend bool operator!=(const basic_system_executor&, const basic_system_executor&) noexcept { return false; } /// Execution function. template <typename Function> void execute(Function&& f) const { this->do_execute(static_cast<Function&&>(f), Blocking()); } #if !defined(ASIO_NO_TS_EXECUTORS) public: /// Obtain the underlying execution context. system_context& context() const noexcept; /// Inform the executor that it has some outstanding work to do. /** * For the system executor, this is a no-op. */ void on_work_started() const noexcept { } /// Inform the executor that some work is no longer outstanding. /** * For the system executor, this is a no-op. */ void on_work_finished() const noexcept { } /// Request the system executor to invoke the given function object. /** * This function is used to ask the executor to execute the given function * object. The function object will always be executed inside this function. * * @param f The function object to be called. The executor will make * a copy of the handler object as required. The function signature of the * function object must be: @code void function(); @endcode * * @param a An allocator that may be used by the executor to allocate the * internal storage needed for function invocation. */ template <typename Function, typename OtherAllocator> void dispatch(Function&& f, const OtherAllocator& a) const; /// Request the system executor to invoke the given function object. /** * This function is used to ask the executor to execute the given function * object. The function object will never be executed inside this function. * Instead, it will be scheduled to run on an unspecified system thread pool. * * @param f The function object to be called. The executor will make * a copy of the handler object as required. The function signature of the * function object must be: @code void function(); @endcode * * @param a An allocator that may be used by the executor to allocate the * internal storage needed for function invocation. */ template <typename Function, typename OtherAllocator> void post(Function&& f, const OtherAllocator& a) const; /// Request the system executor to invoke the given function object. /** * This function is used to ask the executor to execute the given function * object. The function object will never be executed inside this function. * Instead, it will be scheduled to run on an unspecified system thread pool. * * @param f The function object to be called. The executor will make * a copy of the handler object as required. The function signature of the * function object must be: @code void function(); @endcode * * @param a An allocator that may be used by the executor to allocate the * internal storage needed for function invocation. */ template <typename Function, typename OtherAllocator> void defer(Function&& f, const OtherAllocator& a) const; #endif // !defined(ASIO_NO_TS_EXECUTORS) private: template <typename, typename, typename> friend class basic_system_executor; // Constructor used by require(). basic_system_executor(const Allocator& a) : allocator_(a) { } /// Execution helper implementation for the possibly blocking property. template <typename Function> void do_execute(Function&& f, execution::blocking_t::possibly_t) const; /// Execution helper implementation for the always blocking property. template <typename Function> void do_execute(Function&& f, execution::blocking_t::always_t) const; /// Execution helper implementation for the never blocking property. template <typename Function> void do_execute(Function&& f, execution::blocking_t::never_t) const; // The allocator used for execution functions. Allocator allocator_; }; /// An executor that uses arbitrary threads. /** * The system executor represents an execution context where functions are * permitted to run on arbitrary threads. When the blocking.never property is * established, the system executor will schedule the function to run on an * unspecified system thread pool. When either blocking.possibly or * blocking.always is established, the executor invokes the function * immediately. */ typedef basic_system_executor<execution::blocking_t::possibly_t, execution::relationship_t::fork_t, std::allocator<void>> system_executor; #if !defined(GENERATING_DOCUMENTATION) namespace traits { #if !defined(ASIO_HAS_DEDUCED_EQUALITY_COMPARABLE_TRAIT) template <typename Blocking, typename Relationship, typename Allocator> struct equality_comparable< asio::basic_system_executor<Blocking, Relationship, Allocator> > { static constexpr bool is_valid = true; static constexpr bool is_noexcept = true; }; #endif // !defined(ASIO_HAS_DEDUCED_EQUALITY_COMPARABLE_TRAIT) #if !defined(ASIO_HAS_DEDUCED_EXECUTE_MEMBER_TRAIT) template <typename Blocking, typename Relationship, typename Allocator, typename Function> struct execute_member< asio::basic_system_executor<Blocking, Relationship, Allocator>, Function > { static constexpr bool is_valid = true; static constexpr bool is_noexcept = false; typedef void result_type; }; #endif // !defined(ASIO_HAS_DEDUCED_EXECUTE_MEMBER_TRAIT) #if !defined(ASIO_HAS_DEDUCED_REQUIRE_MEMBER_TRAIT) template <typename Blocking, typename Relationship, typename Allocator> struct require_member< asio::basic_system_executor<Blocking, Relationship, Allocator>, asio::execution::blocking_t::possibly_t > { static constexpr bool is_valid = true; static constexpr bool is_noexcept = false; typedef asio::basic_system_executor< asio::execution::blocking_t::possibly_t, Relationship, Allocator> result_type; }; template <typename Blocking, typename Relationship, typename Allocator> struct require_member< asio::basic_system_executor<Blocking, Relationship, Allocator>, asio::execution::blocking_t::always_t > { static constexpr bool is_valid = true; static constexpr bool is_noexcept = false; typedef asio::basic_system_executor< asio::execution::blocking_t::always_t, Relationship, Allocator> result_type; }; template <typename Blocking, typename Relationship, typename Allocator> struct require_member< asio::basic_system_executor<Blocking, Relationship, Allocator>, asio::execution::blocking_t::never_t > { static constexpr bool is_valid = true; static constexpr bool is_noexcept = false; typedef asio::basic_system_executor< asio::execution::blocking_t::never_t, Relationship, Allocator> result_type; }; template <typename Blocking, typename Relationship, typename Allocator> struct require_member< asio::basic_system_executor<Blocking, Relationship, Allocator>, asio::execution::relationship_t::fork_t > { static constexpr bool is_valid = true; static constexpr bool is_noexcept = false; typedef asio::basic_system_executor<Blocking, asio::execution::relationship_t::fork_t, Allocator> result_type; }; template <typename Blocking, typename Relationship, typename Allocator> struct require_member< asio::basic_system_executor<Blocking, Relationship, Allocator>, asio::execution::relationship_t::continuation_t > { static constexpr bool is_valid = true; static constexpr bool is_noexcept = false; typedef asio::basic_system_executor<Blocking, asio::execution::relationship_t::continuation_t, Allocator> result_type; }; template <typename Blocking, typename Relationship, typename Allocator> struct require_member< asio::basic_system_executor<Blocking, Relationship, Allocator>, asio::execution::allocator_t<void> > { static constexpr bool is_valid = true; static constexpr bool is_noexcept = false; typedef asio::basic_system_executor<Blocking, Relationship, std::allocator<void>> result_type; }; template <typename Blocking, typename Relationship, typename Allocator, typename OtherAllocator> struct require_member< asio::basic_system_executor<Blocking, Relationship, Allocator>, asio::execution::allocator_t<OtherAllocator> > { static constexpr bool is_valid = true; static constexpr bool is_noexcept = false; typedef asio::basic_system_executor<Blocking, Relationship, OtherAllocator> result_type; }; #endif // !defined(ASIO_HAS_DEDUCED_REQUIRE_MEMBER_TRAIT) #if !defined(ASIO_HAS_DEDUCED_QUERY_STATIC_CONSTEXPR_MEMBER_TRAIT) template <typename Blocking, typename Relationship, typename Allocator, typename Property> struct query_static_constexpr_member< asio::basic_system_executor<Blocking, Relationship, Allocator>, Property, typename asio::enable_if< asio::is_convertible< Property, asio::execution::mapping_t >::value >::type > { static constexpr bool is_valid = true; static constexpr bool is_noexcept = true; typedef asio::execution::mapping_t::thread_t result_type; static constexpr result_type value() noexcept { return result_type(); } }; #endif // !defined(ASIO_HAS_DEDUCED_QUERY_STATIC_CONSTEXPR_MEMBER_TRAIT) #if !defined(ASIO_HAS_DEDUCED_QUERY_MEMBER_TRAIT) template <typename Blocking, typename Relationship, typename Allocator, typename Property> struct query_member< asio::basic_system_executor<Blocking, Relationship, Allocator>, Property, typename asio::enable_if< asio::is_convertible< Property, asio::execution::blocking_t >::value >::type > { static constexpr bool is_valid = true; static constexpr bool is_noexcept = true; typedef asio::execution::blocking_t result_type; }; template <typename Blocking, typename Relationship, typename Allocator, typename Property> struct query_member< asio::basic_system_executor<Blocking, Relationship, Allocator>, Property, typename asio::enable_if< asio::is_convertible< Property, asio::execution::relationship_t >::value >::type > { static constexpr bool is_valid = true; static constexpr bool is_noexcept = true; typedef asio::execution::relationship_t result_type; }; template <typename Blocking, typename Relationship, typename Allocator> struct query_member< asio::basic_system_executor<Blocking, Relationship, Allocator>, asio::execution::context_t > { static constexpr bool is_valid = true; static constexpr bool is_noexcept = true; typedef asio::system_context& result_type; }; template <typename Blocking, typename Relationship, typename Allocator> struct query_member< asio::basic_system_executor<Blocking, Relationship, Allocator>, asio::execution::allocator_t<void> > { static constexpr bool is_valid = true; static constexpr bool is_noexcept = true; typedef Allocator result_type; }; template <typename Blocking, typename Relationship, typename Allocator> struct query_member< asio::basic_system_executor<Blocking, Relationship, Allocator>, asio::execution::allocator_t<Allocator> > { static constexpr bool is_valid = true; static constexpr bool is_noexcept = true; typedef Allocator result_type; }; #endif // !defined(ASIO_HAS_DEDUCED_QUERY_MEMBER_TRAIT) } // namespace traits #endif // !defined(GENERATING_DOCUMENTATION) } // namespace asio #include "asio/detail/pop_options.hpp" #include "asio/impl/system_executor.hpp" #endif // ASIO_SYSTEM_EXECUTOR_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/basic_datagram_socket.hpp
// // basic_datagram_socket.hpp // ~~~~~~~~~~~~~~~~~~~~~~~~~ // // 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) // #ifndef ASIO_BASIC_DATAGRAM_SOCKET_HPP #define ASIO_BASIC_DATAGRAM_SOCKET_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include <cstddef> #include "asio/basic_socket.hpp" #include "asio/detail/handler_type_requirements.hpp" #include "asio/detail/non_const_lvalue.hpp" #include "asio/detail/throw_error.hpp" #include "asio/detail/type_traits.hpp" #include "asio/error.hpp" #include "asio/detail/push_options.hpp" namespace asio { #if !defined(ASIO_BASIC_DATAGRAM_SOCKET_FWD_DECL) #define ASIO_BASIC_DATAGRAM_SOCKET_FWD_DECL // Forward declaration with defaulted arguments. template <typename Protocol, typename Executor = any_io_executor> class basic_datagram_socket; #endif // !defined(ASIO_BASIC_DATAGRAM_SOCKET_FWD_DECL) /// Provides datagram-oriented socket functionality. /** * The basic_datagram_socket class template provides asynchronous and blocking * datagram-oriented socket functionality. * * @par Thread Safety * @e Distinct @e objects: Safe.@n * @e Shared @e objects: Unsafe. * * Synchronous @c send, @c send_to, @c receive, @c receive_from, @c connect, * and @c shutdown operations are thread safe with respect to each other, if * the underlying operating system calls are also thread safe. This means that * it is permitted to perform concurrent calls to these synchronous operations * on a single socket object. Other synchronous operations, such as @c open or * @c close, are not thread safe. */ template <typename Protocol, typename Executor> class basic_datagram_socket : public basic_socket<Protocol, Executor> { private: class initiate_async_send; class initiate_async_send_to; class initiate_async_receive; class initiate_async_receive_from; public: /// The type of the executor associated with the object. typedef Executor executor_type; /// Rebinds the socket type to another executor. template <typename Executor1> struct rebind_executor { /// The socket type when rebound to the specified executor. typedef basic_datagram_socket<Protocol, Executor1> other; }; /// The native representation of a socket. #if defined(GENERATING_DOCUMENTATION) typedef implementation_defined native_handle_type; #else typedef typename basic_socket<Protocol, Executor>::native_handle_type native_handle_type; #endif /// The protocol type. typedef Protocol protocol_type; /// The endpoint type. typedef typename Protocol::endpoint endpoint_type; /// Construct a basic_datagram_socket without opening it. /** * This constructor creates a datagram socket without opening it. The open() * function must be called before data can be sent or received on the socket. * * @param ex The I/O executor that the socket will use, by default, to * dispatch handlers for any asynchronous operations performed on the socket. */ explicit basic_datagram_socket(const executor_type& ex) : basic_socket<Protocol, Executor>(ex) { } /// Construct a basic_datagram_socket without opening it. /** * This constructor creates a datagram socket without opening it. The open() * function must be called before data can be sent or received on the socket. * * @param context An execution context which provides the I/O executor that * the socket will use, by default, to dispatch handlers for any asynchronous * operations performed on the socket. */ template <typename ExecutionContext> explicit basic_datagram_socket(ExecutionContext& context, constraint_t< is_convertible<ExecutionContext&, execution_context&>::value > = 0) : basic_socket<Protocol, Executor>(context) { } /// Construct and open a basic_datagram_socket. /** * This constructor creates and opens a datagram socket. * * @param ex The I/O executor that the socket will use, by default, to * dispatch handlers for any asynchronous operations performed on the socket. * * @param protocol An object specifying protocol parameters to be used. * * @throws asio::system_error Thrown on failure. */ basic_datagram_socket(const executor_type& ex, const protocol_type& protocol) : basic_socket<Protocol, Executor>(ex, protocol) { } /// Construct and open a basic_datagram_socket. /** * This constructor creates and opens a datagram socket. * * @param context An execution context which provides the I/O executor that * the socket will use, by default, to dispatch handlers for any asynchronous * operations performed on the socket. * * @param protocol An object specifying protocol parameters to be used. * * @throws asio::system_error Thrown on failure. */ template <typename ExecutionContext> basic_datagram_socket(ExecutionContext& context, const protocol_type& protocol, constraint_t< is_convertible<ExecutionContext&, execution_context&>::value, defaulted_constraint > = defaulted_constraint()) : basic_socket<Protocol, Executor>(context, protocol) { } /// Construct a basic_datagram_socket, opening it and binding it to the given /// local endpoint. /** * This constructor creates a datagram socket and automatically opens it bound * to the specified endpoint on the local machine. The protocol used is the * protocol associated with the given endpoint. * * @param ex The I/O executor that the socket will use, by default, to * dispatch handlers for any asynchronous operations performed on the socket. * * @param endpoint An endpoint on the local machine to which the datagram * socket will be bound. * * @throws asio::system_error Thrown on failure. */ basic_datagram_socket(const executor_type& ex, const endpoint_type& endpoint) : basic_socket<Protocol, Executor>(ex, endpoint) { } /// Construct a basic_datagram_socket, opening it and binding it to the given /// local endpoint. /** * This constructor creates a datagram socket and automatically opens it bound * to the specified endpoint on the local machine. The protocol used is the * protocol associated with the given endpoint. * * @param context An execution context which provides the I/O executor that * the socket will use, by default, to dispatch handlers for any asynchronous * operations performed on the socket. * * @param endpoint An endpoint on the local machine to which the datagram * socket will be bound. * * @throws asio::system_error Thrown on failure. */ template <typename ExecutionContext> basic_datagram_socket(ExecutionContext& context, const endpoint_type& endpoint, constraint_t< is_convertible<ExecutionContext&, execution_context&>::value > = 0) : basic_socket<Protocol, Executor>(context, endpoint) { } /// Construct a basic_datagram_socket on an existing native socket. /** * This constructor creates a datagram socket object to hold an existing * native socket. * * @param ex The I/O executor that the socket will use, by default, to * dispatch handlers for any asynchronous operations performed on the socket. * * @param protocol An object specifying protocol parameters to be used. * * @param native_socket The new underlying socket implementation. * * @throws asio::system_error Thrown on failure. */ basic_datagram_socket(const executor_type& ex, const protocol_type& protocol, const native_handle_type& native_socket) : basic_socket<Protocol, Executor>(ex, protocol, native_socket) { } /// Construct a basic_datagram_socket on an existing native socket. /** * This constructor creates a datagram socket object to hold an existing * native socket. * * @param context An execution context which provides the I/O executor that * the socket will use, by default, to dispatch handlers for any asynchronous * operations performed on the socket. * * @param protocol An object specifying protocol parameters to be used. * * @param native_socket The new underlying socket implementation. * * @throws asio::system_error Thrown on failure. */ template <typename ExecutionContext> basic_datagram_socket(ExecutionContext& context, const protocol_type& protocol, const native_handle_type& native_socket, constraint_t< is_convertible<ExecutionContext&, execution_context&>::value > = 0) : basic_socket<Protocol, Executor>(context, protocol, native_socket) { } /// Move-construct a basic_datagram_socket from another. /** * This constructor moves a datagram socket from one object to another. * * @param other The other basic_datagram_socket object from which the move * will occur. * * @note Following the move, the moved-from object is in the same state as if * constructed using the @c basic_datagram_socket(const executor_type&) * constructor. */ basic_datagram_socket(basic_datagram_socket&& other) noexcept : basic_socket<Protocol, Executor>(std::move(other)) { } /// Move-assign a basic_datagram_socket from another. /** * This assignment operator moves a datagram socket from one object to * another. * * @param other The other basic_datagram_socket object from which the move * will occur. * * @note Following the move, the moved-from object is in the same state as if * constructed using the @c basic_datagram_socket(const executor_type&) * constructor. */ basic_datagram_socket& operator=(basic_datagram_socket&& other) { basic_socket<Protocol, Executor>::operator=(std::move(other)); return *this; } /// Move-construct a basic_datagram_socket from a socket of another protocol /// type. /** * This constructor moves a datagram socket from one object to another. * * @param other The other basic_datagram_socket object from which the move * will occur. * * @note Following the move, the moved-from object is in the same state as if * constructed using the @c basic_datagram_socket(const executor_type&) * constructor. */ template <typename Protocol1, typename Executor1> basic_datagram_socket(basic_datagram_socket<Protocol1, Executor1>&& other, constraint_t< is_convertible<Protocol1, Protocol>::value && is_convertible<Executor1, Executor>::value > = 0) : basic_socket<Protocol, Executor>(std::move(other)) { } /// Move-assign a basic_datagram_socket from a socket of another protocol /// type. /** * This assignment operator moves a datagram socket from one object to * another. * * @param other The other basic_datagram_socket object from which the move * will occur. * * @note Following the move, the moved-from object is in the same state as if * constructed using the @c basic_datagram_socket(const executor_type&) * constructor. */ template <typename Protocol1, typename Executor1> constraint_t< is_convertible<Protocol1, Protocol>::value && is_convertible<Executor1, Executor>::value, basic_datagram_socket& > operator=(basic_datagram_socket<Protocol1, Executor1>&& other) { basic_socket<Protocol, Executor>::operator=(std::move(other)); return *this; } /// Destroys the socket. /** * This function destroys the socket, cancelling any outstanding asynchronous * operations associated with the socket as if by calling @c cancel. */ ~basic_datagram_socket() { } /// Send some data on a connected socket. /** * This function is used to send data on the datagram socket. The function * call will block until the data has been sent successfully or an error * occurs. * * @param buffers One ore more data buffers to be sent on the socket. * * @returns The number of bytes sent. * * @throws asio::system_error Thrown on failure. * * @note The send operation can only be used with a connected socket. Use * the send_to function to send data on an unconnected datagram socket. * * @par Example * To send a single data buffer use the @ref buffer function as follows: * @code socket.send(asio::buffer(data, size)); @endcode * See the @ref buffer documentation for information on sending multiple * buffers in one go, and how to use it with arrays, boost::array or * std::vector. */ template <typename ConstBufferSequence> std::size_t send(const ConstBufferSequence& buffers) { asio::error_code ec; std::size_t s = this->impl_.get_service().send( this->impl_.get_implementation(), buffers, 0, ec); asio::detail::throw_error(ec, "send"); return s; } /// Send some data on a connected socket. /** * This function is used to send data on the datagram socket. The function * call will block until the data has been sent successfully or an error * occurs. * * @param buffers One ore more data buffers to be sent on the socket. * * @param flags Flags specifying how the send call is to be made. * * @returns The number of bytes sent. * * @throws asio::system_error Thrown on failure. * * @note The send operation can only be used with a connected socket. Use * the send_to function to send data on an unconnected datagram socket. */ template <typename ConstBufferSequence> std::size_t send(const ConstBufferSequence& buffers, socket_base::message_flags flags) { asio::error_code ec; std::size_t s = this->impl_.get_service().send( this->impl_.get_implementation(), buffers, flags, ec); asio::detail::throw_error(ec, "send"); return s; } /// Send some data on a connected socket. /** * This function is used to send data on the datagram socket. The function * call will block until the data has been sent successfully or an error * occurs. * * @param buffers One or more data buffers to be sent on the socket. * * @param flags Flags specifying how the send call is to be made. * * @param ec Set to indicate what error occurred, if any. * * @returns The number of bytes sent. * * @note The send operation can only be used with a connected socket. Use * the send_to function to send data on an unconnected datagram socket. */ template <typename ConstBufferSequence> std::size_t send(const ConstBufferSequence& buffers, socket_base::message_flags flags, asio::error_code& ec) { return this->impl_.get_service().send( this->impl_.get_implementation(), buffers, flags, ec); } /// Start an asynchronous send on a connected socket. /** * This function is used to asynchronously send data on the datagram socket. * It is an initiating function for an @ref asynchronous_operation, and always * returns immediately. * * @param buffers One or more data buffers to be sent on the socket. Although * the buffers object may be copied as necessary, ownership of the underlying * memory blocks is retained by the caller, which must guarantee that they * remain valid until the completion handler is called. * * @param token The @ref completion_token that will be used to produce a * completion handler, which will be called when the send completes. Potential * completion tokens include @ref use_future, @ref use_awaitable, @ref * yield_context, or a function object with the correct completion signature. * The function signature of the completion handler must be: * @code void handler( * const asio::error_code& error, // Result of operation. * std::size_t bytes_transferred // Number of bytes sent. * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the completion handler will not be invoked from within this function. * On immediate completion, invocation of the handler will be performed in a * manner equivalent to using asio::async_immediate(). * * @par Completion Signature * @code void(asio::error_code, std::size_t) @endcode * * @note The async_send operation can only be used with a connected socket. * Use the async_send_to function to send data on an unconnected datagram * socket. * * @par Example * To send a single data buffer use the @ref buffer function as follows: * @code * socket.async_send(asio::buffer(data, size), handler); * @endcode * See the @ref buffer documentation for information on sending multiple * buffers in one go, and how to use it with arrays, boost::array or * std::vector. * * @par Per-Operation Cancellation * On POSIX or Windows operating systems, this asynchronous operation supports * cancellation for the following asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * @li @c cancellation_type::total */ template <typename ConstBufferSequence, ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code, std::size_t)) WriteToken = default_completion_token_t<executor_type>> auto async_send(const ConstBufferSequence& buffers, WriteToken&& token = default_completion_token_t<executor_type>()) -> decltype( async_initiate<WriteToken, void (asio::error_code, std::size_t)>( declval<initiate_async_send>(), token, buffers, socket_base::message_flags(0))) { return async_initiate<WriteToken, void (asio::error_code, std::size_t)>( initiate_async_send(this), token, buffers, socket_base::message_flags(0)); } /// Start an asynchronous send on a connected socket. /** * This function is used to asynchronously send data on the datagram socket. * It is an initiating function for an @ref asynchronous_operation, and always * returns immediately. * * @param buffers One or more data buffers to be sent on the socket. Although * the buffers object may be copied as necessary, ownership of the underlying * memory blocks is retained by the caller, which must guarantee that they * remain valid until the completion handler is called. * * @param flags Flags specifying how the send call is to be made. * * @param token The @ref completion_token that will be used to produce a * completion handler, which will be called when the send completes. Potential * completion tokens include @ref use_future, @ref use_awaitable, @ref * yield_context, or a function object with the correct completion signature. * The function signature of the completion handler must be: * @code void handler( * const asio::error_code& error, // Result of operation. * std::size_t bytes_transferred // Number of bytes sent. * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the completion handler will not be invoked from within this function. * On immediate completion, invocation of the handler will be performed in a * manner equivalent to using asio::async_immediate(). * * @par Completion Signature * @code void(asio::error_code, std::size_t) @endcode * * @note The async_send operation can only be used with a connected socket. * Use the async_send_to function to send data on an unconnected datagram * socket. * * @par Per-Operation Cancellation * On POSIX or Windows operating systems, this asynchronous operation supports * cancellation for the following asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * @li @c cancellation_type::total */ template <typename ConstBufferSequence, ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code, std::size_t)) WriteToken = default_completion_token_t<executor_type>> auto async_send(const ConstBufferSequence& buffers, socket_base::message_flags flags, WriteToken&& token = default_completion_token_t<executor_type>()) -> decltype( async_initiate<WriteToken, void (asio::error_code, std::size_t)>( declval<initiate_async_send>(), token, buffers, flags)) { return async_initiate<WriteToken, void (asio::error_code, std::size_t)>( initiate_async_send(this), token, buffers, flags); } /// Send a datagram to the specified endpoint. /** * This function is used to send a datagram to the specified remote endpoint. * The function call will block until the data has been sent successfully or * an error occurs. * * @param buffers One or more data buffers to be sent to the remote endpoint. * * @param destination The remote endpoint to which the data will be sent. * * @returns The number of bytes sent. * * @throws asio::system_error Thrown on failure. * * @par Example * To send a single data buffer use the @ref buffer function as follows: * @code * asio::ip::udp::endpoint destination( * asio::ip::address::from_string("1.2.3.4"), 12345); * socket.send_to(asio::buffer(data, size), destination); * @endcode * See the @ref buffer documentation for information on sending multiple * buffers in one go, and how to use it with arrays, boost::array or * std::vector. */ template <typename ConstBufferSequence> std::size_t send_to(const ConstBufferSequence& buffers, const endpoint_type& destination) { asio::error_code ec; std::size_t s = this->impl_.get_service().send_to( this->impl_.get_implementation(), buffers, destination, 0, ec); asio::detail::throw_error(ec, "send_to"); return s; } /// Send a datagram to the specified endpoint. /** * This function is used to send a datagram to the specified remote endpoint. * The function call will block until the data has been sent successfully or * an error occurs. * * @param buffers One or more data buffers to be sent to the remote endpoint. * * @param destination The remote endpoint to which the data will be sent. * * @param flags Flags specifying how the send call is to be made. * * @returns The number of bytes sent. * * @throws asio::system_error Thrown on failure. */ template <typename ConstBufferSequence> std::size_t send_to(const ConstBufferSequence& buffers, const endpoint_type& destination, socket_base::message_flags flags) { asio::error_code ec; std::size_t s = this->impl_.get_service().send_to( this->impl_.get_implementation(), buffers, destination, flags, ec); asio::detail::throw_error(ec, "send_to"); return s; } /// Send a datagram to the specified endpoint. /** * This function is used to send a datagram to the specified remote endpoint. * The function call will block until the data has been sent successfully or * an error occurs. * * @param buffers One or more data buffers to be sent to the remote endpoint. * * @param destination The remote endpoint to which the data will be sent. * * @param flags Flags specifying how the send call is to be made. * * @param ec Set to indicate what error occurred, if any. * * @returns The number of bytes sent. */ template <typename ConstBufferSequence> std::size_t send_to(const ConstBufferSequence& buffers, const endpoint_type& destination, socket_base::message_flags flags, asio::error_code& ec) { return this->impl_.get_service().send_to(this->impl_.get_implementation(), buffers, destination, flags, ec); } /// Start an asynchronous send. /** * This function is used to asynchronously send a datagram to the specified * remote endpoint. It is an initiating function for an @ref * asynchronous_operation, and always returns immediately. * * @param buffers One or more data buffers to be sent to the remote endpoint. * Although the buffers object may be copied as necessary, ownership of the * underlying memory blocks is retained by the caller, which must guarantee * that they remain valid until the completion handler is called. * * @param destination The remote endpoint to which the data will be sent. * Copies will be made of the endpoint as required. * * @param token The @ref completion_token that will be used to produce a * completion handler, which will be called when the send completes. Potential * completion tokens include @ref use_future, @ref use_awaitable, @ref * yield_context, or a function object with the correct completion signature. * The function signature of the completion handler must be: * @code void handler( * const asio::error_code& error, // Result of operation. * std::size_t bytes_transferred // Number of bytes sent. * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the completion handler will not be invoked from within this function. * On immediate completion, invocation of the handler will be performed in a * manner equivalent to using asio::async_immediate(). * * @par Completion Signature * @code void(asio::error_code, std::size_t) @endcode * * @par Example * To send a single data buffer use the @ref buffer function as follows: * @code * asio::ip::udp::endpoint destination( * asio::ip::address::from_string("1.2.3.4"), 12345); * socket.async_send_to( * asio::buffer(data, size), destination, handler); * @endcode * See the @ref buffer documentation for information on sending multiple * buffers in one go, and how to use it with arrays, boost::array or * std::vector. * * @par Per-Operation Cancellation * On POSIX or Windows operating systems, this asynchronous operation supports * cancellation for the following asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * @li @c cancellation_type::total */ template <typename ConstBufferSequence, ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code, std::size_t)) WriteToken = default_completion_token_t<executor_type>> auto async_send_to(const ConstBufferSequence& buffers, const endpoint_type& destination, WriteToken&& token = default_completion_token_t<executor_type>()) -> decltype( async_initiate<WriteToken, void (asio::error_code, std::size_t)>( declval<initiate_async_send_to>(), token, buffers, destination, socket_base::message_flags(0))) { return async_initiate<WriteToken, void (asio::error_code, std::size_t)>( initiate_async_send_to(this), token, buffers, destination, socket_base::message_flags(0)); } /// Start an asynchronous send. /** * This function is used to asynchronously send a datagram to the specified * remote endpoint. It is an initiating function for an @ref * asynchronous_operation, and always returns immediately. * * @param buffers One or more data buffers to be sent to the remote endpoint. * Although the buffers object may be copied as necessary, ownership of the * underlying memory blocks is retained by the caller, which must guarantee * that they remain valid until the completion handler is called. * * @param flags Flags specifying how the send call is to be made. * * @param destination The remote endpoint to which the data will be sent. * Copies will be made of the endpoint as required. * * @param token The @ref completion_token that will be used to produce a * completion handler, which will be called when the send completes. Potential * completion tokens include @ref use_future, @ref use_awaitable, @ref * yield_context, or a function object with the correct completion signature. * The function signature of the completion handler must be: * @code void handler( * const asio::error_code& error, // Result of operation. * std::size_t bytes_transferred // Number of bytes sent. * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the completion handler will not be invoked from within this function. * On immediate completion, invocation of the handler will be performed in a * manner equivalent to using asio::async_immediate(). * * @par Completion Signature * @code void(asio::error_code, std::size_t) @endcode * * @par Per-Operation Cancellation * On POSIX or Windows operating systems, this asynchronous operation supports * cancellation for the following asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * @li @c cancellation_type::total */ template <typename ConstBufferSequence, ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code, std::size_t)) WriteToken = default_completion_token_t<executor_type>> auto async_send_to(const ConstBufferSequence& buffers, const endpoint_type& destination, socket_base::message_flags flags, WriteToken&& token = default_completion_token_t<executor_type>()) -> decltype( async_initiate<WriteToken, void (asio::error_code, std::size_t)>( declval<initiate_async_send_to>(), token, buffers, destination, flags)) { return async_initiate<WriteToken, void (asio::error_code, std::size_t)>( initiate_async_send_to(this), token, buffers, destination, flags); } /// Receive some data on a connected socket. /** * This function is used to receive data on the datagram socket. The function * call will block until data has been received successfully or an error * occurs. * * @param buffers One or more buffers into which the data will be received. * * @returns The number of bytes received. * * @throws asio::system_error Thrown on failure. * * @note The receive operation can only be used with a connected socket. Use * the receive_from function to receive data on an unconnected datagram * socket. * * @par Example * To receive into a single data buffer use the @ref buffer function as * follows: * @code socket.receive(asio::buffer(data, size)); @endcode * See the @ref buffer documentation for information on receiving into * multiple buffers in one go, and how to use it with arrays, boost::array or * std::vector. */ template <typename MutableBufferSequence> std::size_t receive(const MutableBufferSequence& buffers) { asio::error_code ec; std::size_t s = this->impl_.get_service().receive( this->impl_.get_implementation(), buffers, 0, ec); asio::detail::throw_error(ec, "receive"); return s; } /// Receive some data on a connected socket. /** * This function is used to receive data on the datagram socket. The function * call will block until data has been received successfully or an error * occurs. * * @param buffers One or more buffers into which the data will be received. * * @param flags Flags specifying how the receive call is to be made. * * @returns The number of bytes received. * * @throws asio::system_error Thrown on failure. * * @note The receive operation can only be used with a connected socket. Use * the receive_from function to receive data on an unconnected datagram * socket. */ template <typename MutableBufferSequence> std::size_t receive(const MutableBufferSequence& buffers, socket_base::message_flags flags) { asio::error_code ec; std::size_t s = this->impl_.get_service().receive( this->impl_.get_implementation(), buffers, flags, ec); asio::detail::throw_error(ec, "receive"); return s; } /// Receive some data on a connected socket. /** * This function is used to receive data on the datagram socket. The function * call will block until data has been received successfully or an error * occurs. * * @param buffers One or more buffers into which the data will be received. * * @param flags Flags specifying how the receive call is to be made. * * @param ec Set to indicate what error occurred, if any. * * @returns The number of bytes received. * * @note The receive operation can only be used with a connected socket. Use * the receive_from function to receive data on an unconnected datagram * socket. */ template <typename MutableBufferSequence> std::size_t receive(const MutableBufferSequence& buffers, socket_base::message_flags flags, asio::error_code& ec) { return this->impl_.get_service().receive( this->impl_.get_implementation(), buffers, flags, ec); } /// Start an asynchronous receive on a connected socket. /** * This function is used to asynchronously receive data from the datagram * socket. It is an initiating function for an @ref asynchronous_operation, * and always returns immediately. * * @param buffers One or more buffers into which the data will be received. * Although the buffers object may be copied as necessary, ownership of the * underlying memory blocks is retained by the caller, which must guarantee * that they remain valid until the completion handler is called. * * @param token The @ref completion_token that will be used to produce a * completion handler, which will be called when the receive completes. * Potential completion tokens include @ref use_future, @ref use_awaitable, * @ref yield_context, or a function object with the correct completion * signature. The function signature of the completion handler must be: * @code void handler( * const asio::error_code& error, // Result of operation. * std::size_t bytes_transferred // Number of bytes received. * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the completion handler will not be invoked from within this function. * On immediate completion, invocation of the handler will be performed in a * manner equivalent to using asio::async_immediate(). * * @par Completion Signature * @code void(asio::error_code, std::size_t) @endcode * * @note The async_receive operation can only be used with a connected socket. * Use the async_receive_from function to receive data on an unconnected * datagram socket. * * @par Example * To receive into a single data buffer use the @ref buffer function as * follows: * @code * socket.async_receive(asio::buffer(data, size), handler); * @endcode * See the @ref buffer documentation for information on receiving into * multiple buffers in one go, and how to use it with arrays, boost::array or * std::vector. * * @par Per-Operation Cancellation * On POSIX or Windows operating systems, this asynchronous operation supports * cancellation for the following asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * @li @c cancellation_type::total */ template <typename MutableBufferSequence, ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code, std::size_t)) ReadToken = default_completion_token_t<executor_type>> auto async_receive(const MutableBufferSequence& buffers, ReadToken&& token = default_completion_token_t<executor_type>()) -> decltype( async_initiate<ReadToken, void (asio::error_code, std::size_t)>( declval<initiate_async_receive>(), token, buffers, socket_base::message_flags(0))) { return async_initiate<ReadToken, void (asio::error_code, std::size_t)>( initiate_async_receive(this), token, buffers, socket_base::message_flags(0)); } /// Start an asynchronous receive on a connected socket. /** * This function is used to asynchronously receive data from the datagram * socket. It is an initiating function for an @ref asynchronous_operation, * and always returns immediately. * * @param buffers One or more buffers into which the data will be received. * Although the buffers object may be copied as necessary, ownership of the * underlying memory blocks is retained by the caller, which must guarantee * that they remain valid until the completion handler is called. * * @param flags Flags specifying how the receive call is to be made. * * @param token The @ref completion_token that will be used to produce a * completion handler, which will be called when the receive completes. * Potential completion tokens include @ref use_future, @ref use_awaitable, * @ref yield_context, or a function object with the correct completion * signature. The function signature of the completion handler must be: * @code void handler( * const asio::error_code& error, // Result of operation. * std::size_t bytes_transferred // Number of bytes received. * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the completion handler will not be invoked from within this function. * On immediate completion, invocation of the handler will be performed in a * manner equivalent to using asio::async_immediate(). * * @par Completion Signature * @code void(asio::error_code, std::size_t) @endcode * * @note The async_receive operation can only be used with a connected socket. * Use the async_receive_from function to receive data on an unconnected * datagram socket. * * @par Per-Operation Cancellation * On POSIX or Windows operating systems, this asynchronous operation supports * cancellation for the following asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * @li @c cancellation_type::total */ template <typename MutableBufferSequence, ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code, std::size_t)) ReadToken = default_completion_token_t<executor_type>> auto async_receive(const MutableBufferSequence& buffers, socket_base::message_flags flags, ReadToken&& token = default_completion_token_t<executor_type>()) -> decltype( async_initiate<ReadToken, void (asio::error_code, std::size_t)>( declval<initiate_async_receive>(), token, buffers, flags)) { return async_initiate<ReadToken, void (asio::error_code, std::size_t)>( initiate_async_receive(this), token, buffers, flags); } /// Receive a datagram with the endpoint of the sender. /** * This function is used to receive a datagram. The function call will block * until data has been received successfully or an error occurs. * * @param buffers One or more buffers into which the data will be received. * * @param sender_endpoint An endpoint object that receives the endpoint of * the remote sender of the datagram. * * @returns The number of bytes received. * * @throws asio::system_error Thrown on failure. * * @par Example * To receive into a single data buffer use the @ref buffer function as * follows: * @code * asio::ip::udp::endpoint sender_endpoint; * socket.receive_from( * asio::buffer(data, size), sender_endpoint); * @endcode * See the @ref buffer documentation for information on receiving into * multiple buffers in one go, and how to use it with arrays, boost::array or * std::vector. */ template <typename MutableBufferSequence> std::size_t receive_from(const MutableBufferSequence& buffers, endpoint_type& sender_endpoint) { asio::error_code ec; std::size_t s = this->impl_.get_service().receive_from( this->impl_.get_implementation(), buffers, sender_endpoint, 0, ec); asio::detail::throw_error(ec, "receive_from"); return s; } /// Receive a datagram with the endpoint of the sender. /** * This function is used to receive a datagram. The function call will block * until data has been received successfully or an error occurs. * * @param buffers One or more buffers into which the data will be received. * * @param sender_endpoint An endpoint object that receives the endpoint of * the remote sender of the datagram. * * @param flags Flags specifying how the receive call is to be made. * * @returns The number of bytes received. * * @throws asio::system_error Thrown on failure. */ template <typename MutableBufferSequence> std::size_t receive_from(const MutableBufferSequence& buffers, endpoint_type& sender_endpoint, socket_base::message_flags flags) { asio::error_code ec; std::size_t s = this->impl_.get_service().receive_from( this->impl_.get_implementation(), buffers, sender_endpoint, flags, ec); asio::detail::throw_error(ec, "receive_from"); return s; } /// Receive a datagram with the endpoint of the sender. /** * This function is used to receive a datagram. The function call will block * until data has been received successfully or an error occurs. * * @param buffers One or more buffers into which the data will be received. * * @param sender_endpoint An endpoint object that receives the endpoint of * the remote sender of the datagram. * * @param flags Flags specifying how the receive call is to be made. * * @param ec Set to indicate what error occurred, if any. * * @returns The number of bytes received. */ template <typename MutableBufferSequence> std::size_t receive_from(const MutableBufferSequence& buffers, endpoint_type& sender_endpoint, socket_base::message_flags flags, asio::error_code& ec) { return this->impl_.get_service().receive_from( this->impl_.get_implementation(), buffers, sender_endpoint, flags, ec); } /// Start an asynchronous receive. /** * This function is used to asynchronously receive a datagram. It is an * initiating function for an @ref asynchronous_operation, and always returns * immediately. * * @param buffers One or more buffers into which the data will be received. * Although the buffers object may be copied as necessary, ownership of the * underlying memory blocks is retained by the caller, which must guarantee * that they remain valid until the completion handler is called. * * @param sender_endpoint An endpoint object that receives the endpoint of * the remote sender of the datagram. Ownership of the sender_endpoint object * is retained by the caller, which must guarantee that it is valid until the * completion handler is called. * * @param token The @ref completion_token that will be used to produce a * completion handler, which will be called when the receive completes. * Potential completion tokens include @ref use_future, @ref use_awaitable, * @ref yield_context, or a function object with the correct completion * signature. The function signature of the completion handler must be: * @code void handler( * const asio::error_code& error, // Result of operation. * std::size_t bytes_transferred // Number of bytes received. * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the completion handler will not be invoked from within this function. * On immediate completion, invocation of the handler will be performed in a * manner equivalent to using asio::async_immediate(). * * @par Completion Signature * @code void(asio::error_code, std::size_t) @endcode * * @par Example * To receive into a single data buffer use the @ref buffer function as * follows: * @code socket.async_receive_from( * asio::buffer(data, size), sender_endpoint, handler); @endcode * See the @ref buffer documentation for information on receiving into * multiple buffers in one go, and how to use it with arrays, boost::array or * std::vector. * * @par Per-Operation Cancellation * On POSIX or Windows operating systems, this asynchronous operation supports * cancellation for the following asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * @li @c cancellation_type::total */ template <typename MutableBufferSequence, ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code, std::size_t)) ReadToken = default_completion_token_t<executor_type>> auto async_receive_from(const MutableBufferSequence& buffers, endpoint_type& sender_endpoint, ReadToken&& token = default_completion_token_t<executor_type>()) -> decltype( async_initiate<ReadToken, void (asio::error_code, std::size_t)>( declval<initiate_async_receive_from>(), token, buffers, &sender_endpoint, socket_base::message_flags(0))) { return async_initiate<ReadToken, void (asio::error_code, std::size_t)>( initiate_async_receive_from(this), token, buffers, &sender_endpoint, socket_base::message_flags(0)); } /// Start an asynchronous receive. /** * This function is used to asynchronously receive a datagram. It is an * initiating function for an @ref asynchronous_operation, and always returns * immediately. * * @param buffers One or more buffers into which the data will be received. * Although the buffers object may be copied as necessary, ownership of the * underlying memory blocks is retained by the caller, which must guarantee * that they remain valid until the completion handler is called. * * @param sender_endpoint An endpoint object that receives the endpoint of * the remote sender of the datagram. Ownership of the sender_endpoint object * is retained by the caller, which must guarantee that it is valid until the * completion handler is called. * * @param flags Flags specifying how the receive call is to be made. * * @param token The @ref completion_token that will be used to produce a * completion handler, which will be called when the receive completes. * Potential completion tokens include @ref use_future, @ref use_awaitable, * @ref yield_context, or a function object with the correct completion * signature. The function signature of the completion handler must be: * @code void handler( * const asio::error_code& error, // Result of operation. * std::size_t bytes_transferred // Number of bytes received. * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the completion handler will not be invoked from within this function. * On immediate completion, invocation of the handler will be performed in a * manner equivalent to using asio::async_immediate(). * * @par Completion Signature * @code void(asio::error_code, std::size_t) @endcode * * @par Per-Operation Cancellation * On POSIX or Windows operating systems, this asynchronous operation supports * cancellation for the following asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * @li @c cancellation_type::total */ template <typename MutableBufferSequence, ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code, std::size_t)) ReadToken = default_completion_token_t<executor_type>> auto async_receive_from(const MutableBufferSequence& buffers, endpoint_type& sender_endpoint, socket_base::message_flags flags, ReadToken&& token = default_completion_token_t<executor_type>()) -> decltype( async_initiate<ReadToken, void (asio::error_code, std::size_t)>( declval<initiate_async_receive_from>(), token, buffers, &sender_endpoint, flags)) { return async_initiate<ReadToken, void (asio::error_code, std::size_t)>( initiate_async_receive_from(this), token, buffers, &sender_endpoint, flags); } private: // Disallow copying and assignment. basic_datagram_socket(const basic_datagram_socket&) = delete; basic_datagram_socket& operator=( const basic_datagram_socket&) = delete; class initiate_async_send { public: typedef Executor executor_type; explicit initiate_async_send(basic_datagram_socket* self) : self_(self) { } const executor_type& get_executor() const noexcept { return self_->get_executor(); } template <typename WriteHandler, typename ConstBufferSequence> void operator()(WriteHandler&& handler, const ConstBufferSequence& buffers, socket_base::message_flags flags) const { // If you get an error on the following line it means that your handler // does not meet the documented type requirements for a WriteHandler. ASIO_WRITE_HANDLER_CHECK(WriteHandler, handler) type_check; detail::non_const_lvalue<WriteHandler> handler2(handler); self_->impl_.get_service().async_send( self_->impl_.get_implementation(), buffers, flags, handler2.value, self_->impl_.get_executor()); } private: basic_datagram_socket* self_; }; class initiate_async_send_to { public: typedef Executor executor_type; explicit initiate_async_send_to(basic_datagram_socket* self) : self_(self) { } const executor_type& get_executor() const noexcept { return self_->get_executor(); } template <typename WriteHandler, typename ConstBufferSequence> void operator()(WriteHandler&& handler, const ConstBufferSequence& buffers, const endpoint_type& destination, socket_base::message_flags flags) const { // If you get an error on the following line it means that your handler // does not meet the documented type requirements for a WriteHandler. ASIO_WRITE_HANDLER_CHECK(WriteHandler, handler) type_check; detail::non_const_lvalue<WriteHandler> handler2(handler); self_->impl_.get_service().async_send_to( self_->impl_.get_implementation(), buffers, destination, flags, handler2.value, self_->impl_.get_executor()); } private: basic_datagram_socket* self_; }; class initiate_async_receive { public: typedef Executor executor_type; explicit initiate_async_receive(basic_datagram_socket* self) : self_(self) { } const executor_type& get_executor() const noexcept { return self_->get_executor(); } template <typename ReadHandler, typename MutableBufferSequence> void operator()(ReadHandler&& handler, const MutableBufferSequence& buffers, socket_base::message_flags flags) const { // If you get an error on the following line it means that your handler // does not meet the documented type requirements for a ReadHandler. ASIO_READ_HANDLER_CHECK(ReadHandler, handler) type_check; detail::non_const_lvalue<ReadHandler> handler2(handler); self_->impl_.get_service().async_receive( self_->impl_.get_implementation(), buffers, flags, handler2.value, self_->impl_.get_executor()); } private: basic_datagram_socket* self_; }; class initiate_async_receive_from { public: typedef Executor executor_type; explicit initiate_async_receive_from(basic_datagram_socket* self) : self_(self) { } const executor_type& get_executor() const noexcept { return self_->get_executor(); } template <typename ReadHandler, typename MutableBufferSequence> void operator()(ReadHandler&& handler, const MutableBufferSequence& buffers, endpoint_type* sender_endpoint, socket_base::message_flags flags) const { // If you get an error on the following line it means that your handler // does not meet the documented type requirements for a ReadHandler. ASIO_READ_HANDLER_CHECK(ReadHandler, handler) type_check; detail::non_const_lvalue<ReadHandler> handler2(handler); self_->impl_.get_service().async_receive_from( self_->impl_.get_implementation(), buffers, *sender_endpoint, flags, handler2.value, self_->impl_.get_executor()); } private: basic_datagram_socket* self_; }; }; } // namespace asio #include "asio/detail/pop_options.hpp" #endif // ASIO_BASIC_DATAGRAM_SOCKET_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/thread_pool.hpp
// // thread_pool.hpp // ~~~~~~~~~~~~~~~ // // 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) // #ifndef ASIO_THREAD_POOL_HPP #define ASIO_THREAD_POOL_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include "asio/detail/atomic_count.hpp" #include "asio/detail/scheduler.hpp" #include "asio/detail/thread_group.hpp" #include "asio/execution.hpp" #include "asio/execution_context.hpp" #include "asio/detail/push_options.hpp" namespace asio { namespace detail { struct thread_pool_bits { static constexpr unsigned int blocking_never = 1; static constexpr unsigned int blocking_always = 2; static constexpr unsigned int blocking_mask = 3; static constexpr unsigned int relationship_continuation = 4; static constexpr unsigned int outstanding_work_tracked = 8; }; } // namespace detail /// A simple fixed-size thread pool. /** * The thread pool class is an execution context where functions are permitted * to run on one of a fixed number of threads. * * @par Submitting tasks to the pool * * To submit functions to the thread pool, use the @ref asio::dispatch, * @ref asio::post or @ref asio::defer free functions. * * For example: * * @code void my_task() * { * ... * } * * ... * * // Launch the pool with four threads. * asio::thread_pool pool(4); * * // Submit a function to the pool. * asio::post(pool, my_task); * * // Submit a lambda object to the pool. * asio::post(pool, * []() * { * ... * }); * * // Wait for all tasks in the pool to complete. * pool.join(); @endcode */ class thread_pool : public execution_context { public: template <typename Allocator, unsigned int Bits> class basic_executor_type; template <typename Allocator, unsigned int Bits> friend class basic_executor_type; /// Executor used to submit functions to a thread pool. typedef basic_executor_type<std::allocator<void>, 0> executor_type; #if !defined(ASIO_NO_TS_EXECUTORS) /// Constructs a pool with an automatically determined number of threads. ASIO_DECL thread_pool(); #endif // !defined(ASIO_NO_TS_EXECUTORS) /// Constructs a pool with a specified number of threads. ASIO_DECL thread_pool(std::size_t num_threads); /// Destructor. /** * Automatically stops and joins the pool, if not explicitly done beforehand. */ ASIO_DECL ~thread_pool(); /// Obtains the executor associated with the pool. executor_type get_executor() noexcept; /// Obtains the executor associated with the pool. executor_type executor() noexcept; /// Stops the threads. /** * This function stops the threads as soon as possible. As a result of calling * @c stop(), pending function objects may be never be invoked. */ ASIO_DECL void stop(); /// Attaches the current thread to the pool. /** * This function attaches the current thread to the pool so that it may be * used for executing submitted function objects. Blocks the calling thread * until the pool is stopped or joined and has no outstanding work. */ ASIO_DECL void attach(); /// Joins the threads. /** * This function blocks until the threads in the pool have completed. If @c * stop() is not called prior to @c join(), the @c join() call will wait * until the pool has no more outstanding work. */ ASIO_DECL void join(); /// Waits for threads to complete. /** * This function blocks until the threads in the pool have completed. If @c * stop() is not called prior to @c wait(), the @c wait() call will wait * until the pool has no more outstanding work. */ ASIO_DECL void wait(); private: thread_pool(const thread_pool&) = delete; thread_pool& operator=(const thread_pool&) = delete; struct thread_function; // Helper function to create the underlying scheduler. ASIO_DECL detail::scheduler& add_scheduler(detail::scheduler* s); // The underlying scheduler. detail::scheduler& scheduler_; // The threads in the pool. detail::thread_group threads_; // The current number of threads in the pool. detail::atomic_count num_threads_; }; /// Executor implementation type used to submit functions to a thread pool. template <typename Allocator, unsigned int Bits> class thread_pool::basic_executor_type : detail::thread_pool_bits { public: /// Copy constructor. basic_executor_type(const basic_executor_type& other) noexcept : pool_(other.pool_), allocator_(other.allocator_), bits_(other.bits_) { if (Bits & outstanding_work_tracked) if (pool_) pool_->scheduler_.work_started(); } /// Move constructor. basic_executor_type(basic_executor_type&& other) noexcept : pool_(other.pool_), allocator_(static_cast<Allocator&&>(other.allocator_)), bits_(other.bits_) { if (Bits & outstanding_work_tracked) other.pool_ = 0; } /// Destructor. ~basic_executor_type() noexcept { if (Bits & outstanding_work_tracked) if (pool_) pool_->scheduler_.work_finished(); } /// Assignment operator. basic_executor_type& operator=(const basic_executor_type& other) noexcept; /// Move assignment operator. basic_executor_type& operator=(basic_executor_type&& other) noexcept; #if !defined(GENERATING_DOCUMENTATION) private: friend struct asio_require_fn::impl; friend struct asio_prefer_fn::impl; #endif // !defined(GENERATING_DOCUMENTATION) /// Obtain an executor with the @c blocking.possibly property. /** * Do not call this function directly. It is intended for use with the * asio::require customisation point. * * For example: * @code auto ex1 = my_thread_pool.executor(); * auto ex2 = asio::require(ex1, * asio::execution::blocking.possibly); @endcode */ constexpr basic_executor_type<Allocator, ASIO_UNSPECIFIED(Bits & ~blocking_mask)> require(execution::blocking_t::possibly_t) const { return basic_executor_type<Allocator, Bits & ~blocking_mask>( pool_, allocator_, bits_ & ~blocking_mask); } /// Obtain an executor with the @c blocking.always property. /** * Do not call this function directly. It is intended for use with the * asio::require customisation point. * * For example: * @code auto ex1 = my_thread_pool.executor(); * auto ex2 = asio::require(ex1, * asio::execution::blocking.always); @endcode */ constexpr basic_executor_type<Allocator, ASIO_UNSPECIFIED((Bits & ~blocking_mask) | blocking_always)> require(execution::blocking_t::always_t) const { return basic_executor_type<Allocator, ASIO_UNSPECIFIED((Bits & ~blocking_mask) | blocking_always)>( pool_, allocator_, bits_ & ~blocking_mask); } /// Obtain an executor with the @c blocking.never property. /** * Do not call this function directly. It is intended for use with the * asio::require customisation point. * * For example: * @code auto ex1 = my_thread_pool.executor(); * auto ex2 = asio::require(ex1, * asio::execution::blocking.never); @endcode */ constexpr basic_executor_type<Allocator, ASIO_UNSPECIFIED(Bits & ~blocking_mask)> require(execution::blocking_t::never_t) const { return basic_executor_type<Allocator, Bits & ~blocking_mask>( pool_, allocator_, (bits_ & ~blocking_mask) | blocking_never); } /// Obtain an executor with the @c relationship.fork property. /** * Do not call this function directly. It is intended for use with the * asio::require customisation point. * * For example: * @code auto ex1 = my_thread_pool.executor(); * auto ex2 = asio::require(ex1, * asio::execution::relationship.fork); @endcode */ constexpr basic_executor_type require(execution::relationship_t::fork_t) const { return basic_executor_type(pool_, allocator_, bits_ & ~relationship_continuation); } /// Obtain an executor with the @c relationship.continuation property. /** * Do not call this function directly. It is intended for use with the * asio::require customisation point. * * For example: * @code auto ex1 = my_thread_pool.executor(); * auto ex2 = asio::require(ex1, * asio::execution::relationship.continuation); @endcode */ constexpr basic_executor_type require( execution::relationship_t::continuation_t) const { return basic_executor_type(pool_, allocator_, bits_ | relationship_continuation); } /// Obtain an executor with the @c outstanding_work.tracked property. /** * Do not call this function directly. It is intended for use with the * asio::require customisation point. * * For example: * @code auto ex1 = my_thread_pool.executor(); * auto ex2 = asio::require(ex1, * asio::execution::outstanding_work.tracked); @endcode */ constexpr basic_executor_type<Allocator, ASIO_UNSPECIFIED(Bits | outstanding_work_tracked)> require(execution::outstanding_work_t::tracked_t) const { return basic_executor_type<Allocator, Bits | outstanding_work_tracked>( pool_, allocator_, bits_); } /// Obtain an executor with the @c outstanding_work.untracked property. /** * Do not call this function directly. It is intended for use with the * asio::require customisation point. * * For example: * @code auto ex1 = my_thread_pool.executor(); * auto ex2 = asio::require(ex1, * asio::execution::outstanding_work.untracked); @endcode */ constexpr basic_executor_type<Allocator, ASIO_UNSPECIFIED(Bits & ~outstanding_work_tracked)> require(execution::outstanding_work_t::untracked_t) const { return basic_executor_type<Allocator, Bits & ~outstanding_work_tracked>( pool_, allocator_, bits_); } /// Obtain an executor with the specified @c allocator property. /** * Do not call this function directly. It is intended for use with the * asio::require customisation point. * * For example: * @code auto ex1 = my_thread_pool.executor(); * auto ex2 = asio::require(ex1, * asio::execution::allocator(my_allocator)); @endcode */ template <typename OtherAllocator> constexpr basic_executor_type<OtherAllocator, Bits> require(execution::allocator_t<OtherAllocator> a) const { return basic_executor_type<OtherAllocator, Bits>( pool_, a.value(), bits_); } /// Obtain an executor with the default @c allocator property. /** * Do not call this function directly. It is intended for use with the * asio::require customisation point. * * For example: * @code auto ex1 = my_thread_pool.executor(); * auto ex2 = asio::require(ex1, * asio::execution::allocator); @endcode */ constexpr basic_executor_type<std::allocator<void>, Bits> require(execution::allocator_t<void>) const { return basic_executor_type<std::allocator<void>, Bits>( pool_, std::allocator<void>(), bits_); } #if !defined(GENERATING_DOCUMENTATION) private: friend struct asio_query_fn::impl; friend struct asio::execution::detail::mapping_t<0>; friend struct asio::execution::detail::outstanding_work_t<0>; #endif // !defined(GENERATING_DOCUMENTATION) /// Query the current value of the @c mapping property. /** * Do not call this function directly. It is intended for use with the * asio::query customisation point. * * For example: * @code auto ex = my_thread_pool.executor(); * if (asio::query(ex, asio::execution::mapping) * == asio::execution::mapping.thread) * ... @endcode */ static constexpr execution::mapping_t query(execution::mapping_t) noexcept { return execution::mapping.thread; } /// Query the current value of the @c context property. /** * Do not call this function directly. It is intended for use with the * asio::query customisation point. * * For example: * @code auto ex = my_thread_pool.executor(); * asio::thread_pool& pool = asio::query( * ex, asio::execution::context); @endcode */ thread_pool& query(execution::context_t) const noexcept { return *pool_; } /// Query the current value of the @c blocking property. /** * Do not call this function directly. It is intended for use with the * asio::query customisation point. * * For example: * @code auto ex = my_thread_pool.executor(); * if (asio::query(ex, asio::execution::blocking) * == asio::execution::blocking.always) * ... @endcode */ constexpr execution::blocking_t query(execution::blocking_t) const noexcept { return (bits_ & blocking_never) ? execution::blocking_t(execution::blocking.never) : ((Bits & blocking_always) ? execution::blocking_t(execution::blocking.always) : execution::blocking_t(execution::blocking.possibly)); } /// Query the current value of the @c relationship property. /** * Do not call this function directly. It is intended for use with the * asio::query customisation point. * * For example: * @code auto ex = my_thread_pool.executor(); * if (asio::query(ex, asio::execution::relationship) * == asio::execution::relationship.continuation) * ... @endcode */ constexpr execution::relationship_t query( execution::relationship_t) const noexcept { return (bits_ & relationship_continuation) ? execution::relationship_t(execution::relationship.continuation) : execution::relationship_t(execution::relationship.fork); } /// Query the current value of the @c outstanding_work property. /** * Do not call this function directly. It is intended for use with the * asio::query customisation point. * * For example: * @code auto ex = my_thread_pool.executor(); * if (asio::query(ex, asio::execution::outstanding_work) * == asio::execution::outstanding_work.tracked) * ... @endcode */ static constexpr execution::outstanding_work_t query( execution::outstanding_work_t) noexcept { return (Bits & outstanding_work_tracked) ? execution::outstanding_work_t(execution::outstanding_work.tracked) : execution::outstanding_work_t(execution::outstanding_work.untracked); } /// Query the current value of the @c allocator property. /** * Do not call this function directly. It is intended for use with the * asio::query customisation point. * * For example: * @code auto ex = my_thread_pool.executor(); * auto alloc = asio::query(ex, * asio::execution::allocator); @endcode */ template <typename OtherAllocator> constexpr Allocator query( execution::allocator_t<OtherAllocator>) const noexcept { return allocator_; } /// Query the current value of the @c allocator property. /** * Do not call this function directly. It is intended for use with the * asio::query customisation point. * * For example: * @code auto ex = my_thread_pool.executor(); * auto alloc = asio::query(ex, * asio::execution::allocator); @endcode */ constexpr Allocator query(execution::allocator_t<void>) const noexcept { return allocator_; } /// Query the occupancy (recommended number of work items) for the pool. /** * Do not call this function directly. It is intended for use with the * asio::query customisation point. * * For example: * @code auto ex = my_thread_pool.executor(); * std::size_t occupancy = asio::query( * ex, asio::execution::occupancy); @endcode */ std::size_t query(execution::occupancy_t) const noexcept { return static_cast<std::size_t>(pool_->num_threads_); } public: /// Determine whether the thread pool is running in the current thread. /** * @return @c true if the current thread is running the thread pool. Otherwise * returns @c false. */ bool running_in_this_thread() const noexcept; /// Compare two executors for equality. /** * Two executors are equal if they refer to the same underlying thread pool. */ friend bool operator==(const basic_executor_type& a, const basic_executor_type& b) noexcept { return a.pool_ == b.pool_ && a.allocator_ == b.allocator_ && a.bits_ == b.bits_; } /// Compare two executors for inequality. /** * Two executors are equal if they refer to the same underlying thread pool. */ friend bool operator!=(const basic_executor_type& a, const basic_executor_type& b) noexcept { return a.pool_ != b.pool_ || a.allocator_ != b.allocator_ || a.bits_ != b.bits_; } /// Execution function. template <typename Function> void execute(Function&& f) const { this->do_execute(static_cast<Function&&>(f), integral_constant<bool, (Bits & blocking_always) != 0>()); } public: #if !defined(ASIO_NO_TS_EXECUTORS) /// Obtain the underlying execution context. thread_pool& context() const noexcept; /// Inform the thread pool that it has some outstanding work to do. /** * This function is used to inform the thread pool that some work has begun. * This ensures that the thread pool's join() function will not return while * the work is underway. */ void on_work_started() const noexcept; /// Inform the thread pool that some work is no longer outstanding. /** * This function is used to inform the thread pool that some work has * finished. Once the count of unfinished work reaches zero, the thread * pool's join() function is permitted to exit. */ void on_work_finished() const noexcept; /// Request the thread pool to invoke the given function object. /** * This function is used to ask the thread pool to execute the given function * object. If the current thread belongs to the pool, @c dispatch() executes * the function before returning. Otherwise, the function will be scheduled * to run on the thread pool. * * @param f The function object to be called. The executor will make * a copy of the handler object as required. The function signature of the * function object must be: @code void function(); @endcode * * @param a An allocator that may be used by the executor to allocate the * internal storage needed for function invocation. */ template <typename Function, typename OtherAllocator> void dispatch(Function&& f, const OtherAllocator& a) const; /// Request the thread pool to invoke the given function object. /** * This function is used to ask the thread pool to execute the given function * object. The function object will never be executed inside @c post(). * Instead, it will be scheduled to run on the thread pool. * * @param f The function object to be called. The executor will make * a copy of the handler object as required. The function signature of the * function object must be: @code void function(); @endcode * * @param a An allocator that may be used by the executor to allocate the * internal storage needed for function invocation. */ template <typename Function, typename OtherAllocator> void post(Function&& f, const OtherAllocator& a) const; /// Request the thread pool to invoke the given function object. /** * This function is used to ask the thread pool to execute the given function * object. The function object will never be executed inside @c defer(). * Instead, it will be scheduled to run on the thread pool. * * If the current thread belongs to the thread pool, @c defer() will delay * scheduling the function object until the current thread returns control to * the pool. * * @param f The function object to be called. The executor will make * a copy of the handler object as required. The function signature of the * function object must be: @code void function(); @endcode * * @param a An allocator that may be used by the executor to allocate the * internal storage needed for function invocation. */ template <typename Function, typename OtherAllocator> void defer(Function&& f, const OtherAllocator& a) const; #endif // !defined(ASIO_NO_TS_EXECUTORS) private: friend class thread_pool; template <typename, unsigned int> friend class basic_executor_type; // Constructor used by thread_pool::get_executor(). explicit basic_executor_type(thread_pool& p) noexcept : pool_(&p), allocator_(), bits_(0) { if (Bits & outstanding_work_tracked) pool_->scheduler_.work_started(); } // Constructor used by require(). basic_executor_type(thread_pool* p, const Allocator& a, unsigned int bits) noexcept : pool_(p), allocator_(a), bits_(bits) { if (Bits & outstanding_work_tracked) if (pool_) pool_->scheduler_.work_started(); } /// Execution helper implementation for possibly and never blocking. template <typename Function> void do_execute(Function&& f, false_type) const; /// Execution helper implementation for always blocking. template <typename Function> void do_execute(Function&& f, true_type) const; // The underlying thread pool. thread_pool* pool_; // The allocator used for execution functions. Allocator allocator_; // The runtime-switched properties of the thread pool executor. unsigned int bits_; }; #if !defined(GENERATING_DOCUMENTATION) namespace traits { #if !defined(ASIO_HAS_DEDUCED_EQUALITY_COMPARABLE_TRAIT) template <typename Allocator, unsigned int Bits> struct equality_comparable< asio::thread_pool::basic_executor_type<Allocator, Bits> > { static constexpr bool is_valid = true; static constexpr bool is_noexcept = true; }; #endif // !defined(ASIO_HAS_DEDUCED_EQUALITY_COMPARABLE_TRAIT) #if !defined(ASIO_HAS_DEDUCED_EXECUTE_MEMBER_TRAIT) template <typename Allocator, unsigned int Bits, typename Function> struct execute_member< asio::thread_pool::basic_executor_type<Allocator, Bits>, Function > { static constexpr bool is_valid = true; static constexpr bool is_noexcept = false; typedef void result_type; }; #endif // !defined(ASIO_HAS_DEDUCED_EXECUTE_MEMBER_TRAIT) #if !defined(ASIO_HAS_DEDUCED_REQUIRE_MEMBER_TRAIT) template <typename Allocator, unsigned int Bits> struct require_member< asio::thread_pool::basic_executor_type<Allocator, Bits>, asio::execution::blocking_t::possibly_t > : asio::detail::thread_pool_bits { static constexpr bool is_valid = true; static constexpr bool is_noexcept = true; typedef asio::thread_pool::basic_executor_type< Allocator, Bits & ~blocking_mask> result_type; }; template <typename Allocator, unsigned int Bits> struct require_member< asio::thread_pool::basic_executor_type<Allocator, Bits>, asio::execution::blocking_t::always_t > : asio::detail::thread_pool_bits { static constexpr bool is_valid = true; static constexpr bool is_noexcept = false; typedef asio::thread_pool::basic_executor_type<Allocator, (Bits & ~blocking_mask) | blocking_always> result_type; }; template <typename Allocator, unsigned int Bits> struct require_member< asio::thread_pool::basic_executor_type<Allocator, Bits>, asio::execution::blocking_t::never_t > : asio::detail::thread_pool_bits { static constexpr bool is_valid = true; static constexpr bool is_noexcept = false; typedef asio::thread_pool::basic_executor_type< Allocator, Bits & ~blocking_mask> result_type; }; template <typename Allocator, unsigned int Bits> struct require_member< asio::thread_pool::basic_executor_type<Allocator, Bits>, asio::execution::relationship_t::fork_t > { static constexpr bool is_valid = true; static constexpr bool is_noexcept = false; typedef asio::thread_pool::basic_executor_type< Allocator, Bits> result_type; }; template <typename Allocator, unsigned int Bits> struct require_member< asio::thread_pool::basic_executor_type<Allocator, Bits>, asio::execution::relationship_t::continuation_t > { static constexpr bool is_valid = true; static constexpr bool is_noexcept = false; typedef asio::thread_pool::basic_executor_type< Allocator, Bits> result_type; }; template <typename Allocator, unsigned int Bits> struct require_member< asio::thread_pool::basic_executor_type<Allocator, Bits>, asio::execution::outstanding_work_t::tracked_t > : asio::detail::thread_pool_bits { static constexpr bool is_valid = true; static constexpr bool is_noexcept = false; typedef asio::thread_pool::basic_executor_type< Allocator, Bits | outstanding_work_tracked> result_type; }; template <typename Allocator, unsigned int Bits> struct require_member< asio::thread_pool::basic_executor_type<Allocator, Bits>, asio::execution::outstanding_work_t::untracked_t > : asio::detail::thread_pool_bits { static constexpr bool is_valid = true; static constexpr bool is_noexcept = false; typedef asio::thread_pool::basic_executor_type< Allocator, Bits & ~outstanding_work_tracked> result_type; }; template <typename Allocator, unsigned int Bits> struct require_member< asio::thread_pool::basic_executor_type<Allocator, Bits>, asio::execution::allocator_t<void> > { static constexpr bool is_valid = true; static constexpr bool is_noexcept = false; typedef asio::thread_pool::basic_executor_type< std::allocator<void>, Bits> result_type; }; template <unsigned int Bits, typename Allocator, typename OtherAllocator> struct require_member< asio::thread_pool::basic_executor_type<Allocator, Bits>, asio::execution::allocator_t<OtherAllocator> > { static constexpr bool is_valid = true; static constexpr bool is_noexcept = false; typedef asio::thread_pool::basic_executor_type< OtherAllocator, Bits> result_type; }; #endif // !defined(ASIO_HAS_DEDUCED_REQUIRE_MEMBER_TRAIT) #if !defined(ASIO_HAS_DEDUCED_QUERY_STATIC_CONSTEXPR_MEMBER_TRAIT) template <typename Allocator, unsigned int Bits, typename Property> struct query_static_constexpr_member< asio::thread_pool::basic_executor_type<Allocator, Bits>, Property, typename asio::enable_if< asio::is_convertible< Property, asio::execution::outstanding_work_t >::value >::type > : asio::detail::thread_pool_bits { static constexpr bool is_valid = true; static constexpr bool is_noexcept = true; typedef asio::execution::outstanding_work_t result_type; static constexpr result_type value() noexcept { return (Bits & outstanding_work_tracked) ? execution::outstanding_work_t(execution::outstanding_work.tracked) : execution::outstanding_work_t(execution::outstanding_work.untracked); } }; template <typename Allocator, unsigned int Bits, typename Property> struct query_static_constexpr_member< asio::thread_pool::basic_executor_type<Allocator, Bits>, Property, typename asio::enable_if< asio::is_convertible< Property, asio::execution::mapping_t >::value >::type > { static constexpr bool is_valid = true; static constexpr bool is_noexcept = true; typedef asio::execution::mapping_t::thread_t result_type; static constexpr result_type value() noexcept { return result_type(); } }; #endif // !defined(ASIO_HAS_DEDUCED_QUERY_STATIC_CONSTEXPR_MEMBER_TRAIT) #if !defined(ASIO_HAS_DEDUCED_QUERY_MEMBER_TRAIT) template <typename Allocator, unsigned int Bits, typename Property> struct query_member< asio::thread_pool::basic_executor_type<Allocator, Bits>, Property, typename asio::enable_if< asio::is_convertible< Property, asio::execution::blocking_t >::value >::type > { static constexpr bool is_valid = true; static constexpr bool is_noexcept = true; typedef asio::execution::blocking_t result_type; }; template <typename Allocator, unsigned int Bits, typename Property> struct query_member< asio::thread_pool::basic_executor_type<Allocator, Bits>, Property, typename asio::enable_if< asio::is_convertible< Property, asio::execution::relationship_t >::value >::type > { static constexpr bool is_valid = true; static constexpr bool is_noexcept = true; typedef asio::execution::relationship_t result_type; }; template <typename Allocator, unsigned int Bits> struct query_member< asio::thread_pool::basic_executor_type<Allocator, Bits>, asio::execution::occupancy_t > { static constexpr bool is_valid = true; static constexpr bool is_noexcept = true; typedef std::size_t result_type; }; template <typename Allocator, unsigned int Bits> struct query_member< asio::thread_pool::basic_executor_type<Allocator, Bits>, asio::execution::context_t > { static constexpr bool is_valid = true; static constexpr bool is_noexcept = true; typedef asio::thread_pool& result_type; }; template <typename Allocator, unsigned int Bits> struct query_member< asio::thread_pool::basic_executor_type<Allocator, Bits>, asio::execution::allocator_t<void> > { static constexpr bool is_valid = true; static constexpr bool is_noexcept = true; typedef Allocator result_type; }; template <typename Allocator, unsigned int Bits, typename OtherAllocator> struct query_member< asio::thread_pool::basic_executor_type<Allocator, Bits>, asio::execution::allocator_t<OtherAllocator> > { static constexpr bool is_valid = true; static constexpr bool is_noexcept = true; typedef Allocator result_type; }; #endif // !defined(ASIO_HAS_DEDUCED_QUERY_MEMBER_TRAIT) } // namespace traits namespace execution { template <> struct is_executor<thread_pool> : false_type { }; } // namespace execution #endif // !defined(GENERATING_DOCUMENTATION) } // namespace asio #include "asio/detail/pop_options.hpp" #include "asio/impl/thread_pool.hpp" #if defined(ASIO_HEADER_ONLY) # include "asio/impl/thread_pool.ipp" #endif // defined(ASIO_HEADER_ONLY) #endif // ASIO_THREAD_POOL_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/ssl.hpp
// // ssl.hpp // ~~~~~~~ // // 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) // #ifndef ASIO_SSL_HPP #define ASIO_SSL_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/ssl/context.hpp" #include "asio/ssl/context_base.hpp" #include "asio/ssl/error.hpp" #include "asio/ssl/rfc2818_verification.hpp" #include "asio/ssl/host_name_verification.hpp" #include "asio/ssl/stream.hpp" #include "asio/ssl/stream_base.hpp" #include "asio/ssl/verify_context.hpp" #include "asio/ssl/verify_mode.hpp" #endif // ASIO_SSL_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/any_completion_handler.hpp
// // any_completion_handler.hpp // ~~~~~~~~~~~~~~~~~~~~~~~~~~ // // 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) // #ifndef ASIO_ANY_COMPLETION_HANDLER_HPP #define ASIO_ANY_COMPLETION_HANDLER_HPP #include "asio/detail/config.hpp" #include <cstring> #include <functional> #include <memory> #include <utility> #include "asio/any_completion_executor.hpp" #include "asio/any_io_executor.hpp" #include "asio/associated_allocator.hpp" #include "asio/associated_cancellation_slot.hpp" #include "asio/associated_executor.hpp" #include "asio/associated_immediate_executor.hpp" #include "asio/cancellation_state.hpp" #include "asio/recycling_allocator.hpp" #include "asio/detail/push_options.hpp" namespace asio { namespace detail { class any_completion_handler_impl_base { public: template <typename S> explicit any_completion_handler_impl_base(S&& slot) : cancel_state_(static_cast<S&&>(slot), enable_total_cancellation()) { } cancellation_slot get_cancellation_slot() const noexcept { return cancel_state_.slot(); } private: cancellation_state cancel_state_; }; template <typename Handler> class any_completion_handler_impl : public any_completion_handler_impl_base { public: template <typename S, typename H> any_completion_handler_impl(S&& slot, H&& h) : any_completion_handler_impl_base(static_cast<S&&>(slot)), handler_(static_cast<H&&>(h)) { } struct uninit_deleter { typename std::allocator_traits< associated_allocator_t<Handler, asio::recycling_allocator<void>>>::template rebind_alloc<any_completion_handler_impl> alloc; void operator()(any_completion_handler_impl* ptr) { std::allocator_traits<decltype(alloc)>::deallocate(alloc, ptr, 1); } }; struct deleter { typename std::allocator_traits< associated_allocator_t<Handler, asio::recycling_allocator<void>>>::template rebind_alloc<any_completion_handler_impl> alloc; void operator()(any_completion_handler_impl* ptr) { std::allocator_traits<decltype(alloc)>::destroy(alloc, ptr); std::allocator_traits<decltype(alloc)>::deallocate(alloc, ptr, 1); } }; template <typename S, typename H> static any_completion_handler_impl* create(S&& slot, H&& h) { uninit_deleter d{ (get_associated_allocator)(h, asio::recycling_allocator<void>())}; std::unique_ptr<any_completion_handler_impl, uninit_deleter> uninit_ptr( std::allocator_traits<decltype(d.alloc)>::allocate(d.alloc, 1), d); any_completion_handler_impl* ptr = new (uninit_ptr.get()) any_completion_handler_impl( static_cast<S&&>(slot), static_cast<H&&>(h)); uninit_ptr.release(); return ptr; } void destroy() { deleter d{ (get_associated_allocator)(handler_, asio::recycling_allocator<void>())}; d(this); } any_completion_executor executor( const any_completion_executor& candidate) const noexcept { return any_completion_executor(std::nothrow, (get_associated_executor)(handler_, candidate)); } any_completion_executor immediate_executor( const any_io_executor& candidate) const noexcept { return any_completion_executor(std::nothrow, (get_associated_immediate_executor)(handler_, candidate)); } void* allocate(std::size_t size, std::size_t align) const { typename std::allocator_traits< associated_allocator_t<Handler, asio::recycling_allocator<void>>>::template rebind_alloc<unsigned char> alloc( (get_associated_allocator)(handler_, asio::recycling_allocator<void>())); std::size_t space = size + align - 1; unsigned char* base = std::allocator_traits<decltype(alloc)>::allocate( alloc, space + sizeof(std::ptrdiff_t)); void* p = base; if (detail::align(align, size, p, space)) { std::ptrdiff_t off = static_cast<unsigned char*>(p) - base; std::memcpy(static_cast<unsigned char*>(p) + size, &off, sizeof(off)); return p; } std::bad_alloc ex; asio::detail::throw_exception(ex); return nullptr; } void deallocate(void* p, std::size_t size, std::size_t align) const { if (p) { typename std::allocator_traits< associated_allocator_t<Handler, asio::recycling_allocator<void>>>::template rebind_alloc<unsigned char> alloc( (get_associated_allocator)(handler_, asio::recycling_allocator<void>())); std::ptrdiff_t off; std::memcpy(&off, static_cast<unsigned char*>(p) + size, sizeof(off)); unsigned char* base = static_cast<unsigned char*>(p) - off; std::allocator_traits<decltype(alloc)>::deallocate( alloc, base, size + align -1 + sizeof(std::ptrdiff_t)); } } template <typename... Args> void call(Args&&... args) { deleter d{ (get_associated_allocator)(handler_, asio::recycling_allocator<void>())}; std::unique_ptr<any_completion_handler_impl, deleter> ptr(this, d); Handler handler(static_cast<Handler&&>(handler_)); ptr.reset(); static_cast<Handler&&>(handler)( static_cast<Args&&>(args)...); } private: Handler handler_; }; template <typename Signature> class any_completion_handler_call_fn; template <typename R, typename... Args> class any_completion_handler_call_fn<R(Args...)> { public: using type = void(*)(any_completion_handler_impl_base*, Args...); constexpr any_completion_handler_call_fn(type fn) : call_fn_(fn) { } void call(any_completion_handler_impl_base* impl, Args... args) const { call_fn_(impl, static_cast<Args&&>(args)...); } template <typename Handler> static void impl(any_completion_handler_impl_base* impl, Args... args) { static_cast<any_completion_handler_impl<Handler>*>(impl)->call( static_cast<Args&&>(args)...); } private: type call_fn_; }; template <typename... Signatures> class any_completion_handler_call_fns; template <typename Signature> class any_completion_handler_call_fns<Signature> : public any_completion_handler_call_fn<Signature> { public: using any_completion_handler_call_fn< Signature>::any_completion_handler_call_fn; using any_completion_handler_call_fn<Signature>::call; }; template <typename Signature, typename... Signatures> class any_completion_handler_call_fns<Signature, Signatures...> : public any_completion_handler_call_fn<Signature>, public any_completion_handler_call_fns<Signatures...> { public: template <typename CallFn, typename... CallFns> constexpr any_completion_handler_call_fns(CallFn fn, CallFns... fns) : any_completion_handler_call_fn<Signature>(fn), any_completion_handler_call_fns<Signatures...>(fns...) { } using any_completion_handler_call_fn<Signature>::call; using any_completion_handler_call_fns<Signatures...>::call; }; class any_completion_handler_destroy_fn { public: using type = void(*)(any_completion_handler_impl_base*); constexpr any_completion_handler_destroy_fn(type fn) : destroy_fn_(fn) { } void destroy(any_completion_handler_impl_base* impl) const { destroy_fn_(impl); } template <typename Handler> static void impl(any_completion_handler_impl_base* impl) { static_cast<any_completion_handler_impl<Handler>*>(impl)->destroy(); } private: type destroy_fn_; }; class any_completion_handler_executor_fn { public: using type = any_completion_executor(*)( any_completion_handler_impl_base*, const any_completion_executor&); constexpr any_completion_handler_executor_fn(type fn) : executor_fn_(fn) { } any_completion_executor executor(any_completion_handler_impl_base* impl, const any_completion_executor& candidate) const { return executor_fn_(impl, candidate); } template <typename Handler> static any_completion_executor impl(any_completion_handler_impl_base* impl, const any_completion_executor& candidate) { return static_cast<any_completion_handler_impl<Handler>*>(impl)->executor( candidate); } private: type executor_fn_; }; class any_completion_handler_immediate_executor_fn { public: using type = any_completion_executor(*)( any_completion_handler_impl_base*, const any_io_executor&); constexpr any_completion_handler_immediate_executor_fn(type fn) : immediate_executor_fn_(fn) { } any_completion_executor immediate_executor( any_completion_handler_impl_base* impl, const any_io_executor& candidate) const { return immediate_executor_fn_(impl, candidate); } template <typename Handler> static any_completion_executor impl(any_completion_handler_impl_base* impl, const any_io_executor& candidate) { return static_cast<any_completion_handler_impl<Handler>*>( impl)->immediate_executor(candidate); } private: type immediate_executor_fn_; }; class any_completion_handler_allocate_fn { public: using type = void*(*)(any_completion_handler_impl_base*, std::size_t, std::size_t); constexpr any_completion_handler_allocate_fn(type fn) : allocate_fn_(fn) { } void* allocate(any_completion_handler_impl_base* impl, std::size_t size, std::size_t align) const { return allocate_fn_(impl, size, align); } template <typename Handler> static void* impl(any_completion_handler_impl_base* impl, std::size_t size, std::size_t align) { return static_cast<any_completion_handler_impl<Handler>*>(impl)->allocate( size, align); } private: type allocate_fn_; }; class any_completion_handler_deallocate_fn { public: using type = void(*)(any_completion_handler_impl_base*, void*, std::size_t, std::size_t); constexpr any_completion_handler_deallocate_fn(type fn) : deallocate_fn_(fn) { } void deallocate(any_completion_handler_impl_base* impl, void* p, std::size_t size, std::size_t align) const { deallocate_fn_(impl, p, size, align); } template <typename Handler> static void impl(any_completion_handler_impl_base* impl, void* p, std::size_t size, std::size_t align) { static_cast<any_completion_handler_impl<Handler>*>(impl)->deallocate( p, size, align); } private: type deallocate_fn_; }; template <typename... Signatures> class any_completion_handler_fn_table : private any_completion_handler_destroy_fn, private any_completion_handler_executor_fn, private any_completion_handler_immediate_executor_fn, private any_completion_handler_allocate_fn, private any_completion_handler_deallocate_fn, private any_completion_handler_call_fns<Signatures...> { public: template <typename... CallFns> constexpr any_completion_handler_fn_table( any_completion_handler_destroy_fn::type destroy_fn, any_completion_handler_executor_fn::type executor_fn, any_completion_handler_immediate_executor_fn::type immediate_executor_fn, any_completion_handler_allocate_fn::type allocate_fn, any_completion_handler_deallocate_fn::type deallocate_fn, CallFns... call_fns) : any_completion_handler_destroy_fn(destroy_fn), any_completion_handler_executor_fn(executor_fn), any_completion_handler_immediate_executor_fn(immediate_executor_fn), any_completion_handler_allocate_fn(allocate_fn), any_completion_handler_deallocate_fn(deallocate_fn), any_completion_handler_call_fns<Signatures...>(call_fns...) { } using any_completion_handler_destroy_fn::destroy; using any_completion_handler_executor_fn::executor; using any_completion_handler_immediate_executor_fn::immediate_executor; using any_completion_handler_allocate_fn::allocate; using any_completion_handler_deallocate_fn::deallocate; using any_completion_handler_call_fns<Signatures...>::call; }; template <typename Handler, typename... Signatures> struct any_completion_handler_fn_table_instance { static constexpr any_completion_handler_fn_table<Signatures...> value = any_completion_handler_fn_table<Signatures...>( &any_completion_handler_destroy_fn::impl<Handler>, &any_completion_handler_executor_fn::impl<Handler>, &any_completion_handler_immediate_executor_fn::impl<Handler>, &any_completion_handler_allocate_fn::impl<Handler>, &any_completion_handler_deallocate_fn::impl<Handler>, &any_completion_handler_call_fn<Signatures>::template impl<Handler>...); }; template <typename Handler, typename... Signatures> constexpr any_completion_handler_fn_table<Signatures...> any_completion_handler_fn_table_instance<Handler, Signatures...>::value; } // namespace detail template <typename... Signatures> class any_completion_handler; /// An allocator type that forwards memory allocation operations through an /// instance of @c any_completion_handler. template <typename T, typename... Signatures> class any_completion_handler_allocator { private: template <typename...> friend class any_completion_handler; template <typename, typename...> friend class any_completion_handler_allocator; const detail::any_completion_handler_fn_table<Signatures...>* fn_table_; detail::any_completion_handler_impl_base* impl_; constexpr any_completion_handler_allocator(int, const any_completion_handler<Signatures...>& h) noexcept : fn_table_(h.fn_table_), impl_(h.impl_) { } public: /// The type of objects that may be allocated by the allocator. typedef T value_type; /// Rebinds an allocator to another value type. template <typename U> struct rebind { /// Specifies the type of the rebound allocator. typedef any_completion_handler_allocator<U, Signatures...> other; }; /// Construct from another @c any_completion_handler_allocator. template <typename U> constexpr any_completion_handler_allocator( const any_completion_handler_allocator<U, Signatures...>& a) noexcept : fn_table_(a.fn_table_), impl_(a.impl_) { } /// Equality operator. constexpr bool operator==( const any_completion_handler_allocator& other) const noexcept { return fn_table_ == other.fn_table_ && impl_ == other.impl_; } /// Inequality operator. constexpr bool operator!=( const any_completion_handler_allocator& other) const noexcept { return fn_table_ != other.fn_table_ || impl_ != other.impl_; } /// Allocate space for @c n objects of the allocator's value type. T* allocate(std::size_t n) const { if (fn_table_) { return static_cast<T*>( fn_table_->allocate( impl_, sizeof(T) * n, alignof(T))); } std::bad_alloc ex; asio::detail::throw_exception(ex); return nullptr; } /// Deallocate space for @c n objects of the allocator's value type. void deallocate(T* p, std::size_t n) const { fn_table_->deallocate(impl_, p, sizeof(T) * n, alignof(T)); } }; /// A protoco-allocator type that may be rebound to obtain an allocator that /// forwards memory allocation operations through an instance of /// @c any_completion_handler. template <typename... Signatures> class any_completion_handler_allocator<void, Signatures...> { private: template <typename...> friend class any_completion_handler; template <typename, typename...> friend class any_completion_handler_allocator; const detail::any_completion_handler_fn_table<Signatures...>* fn_table_; detail::any_completion_handler_impl_base* impl_; constexpr any_completion_handler_allocator(int, const any_completion_handler<Signatures...>& h) noexcept : fn_table_(h.fn_table_), impl_(h.impl_) { } public: /// @c void as no objects can be allocated through a proto-allocator. typedef void value_type; /// Rebinds an allocator to another value type. template <typename U> struct rebind { /// Specifies the type of the rebound allocator. typedef any_completion_handler_allocator<U, Signatures...> other; }; /// Construct from another @c any_completion_handler_allocator. template <typename U> constexpr any_completion_handler_allocator( const any_completion_handler_allocator<U, Signatures...>& a) noexcept : fn_table_(a.fn_table_), impl_(a.impl_) { } /// Equality operator. constexpr bool operator==( const any_completion_handler_allocator& other) const noexcept { return fn_table_ == other.fn_table_ && impl_ == other.impl_; } /// Inequality operator. constexpr bool operator!=( const any_completion_handler_allocator& other) const noexcept { return fn_table_ != other.fn_table_ || impl_ != other.impl_; } }; /// Polymorphic wrapper for completion handlers. /** * The @c any_completion_handler class template is a polymorphic wrapper for * completion handlers that propagates the associated executor, associated * allocator, and associated cancellation slot through a type-erasing interface. * * When using @c any_completion_handler, specify one or more completion * signatures as template parameters. These will dictate the arguments that may * be passed to the handler through the polymorphic interface. * * Typical uses for @c any_completion_handler include: * * @li Separate compilation of asynchronous operation implementations. * * @li Enabling interoperability between asynchronous operations and virtual * functions. */ template <typename... Signatures> class any_completion_handler { #if !defined(GENERATING_DOCUMENTATION) private: template <typename, typename...> friend class any_completion_handler_allocator; template <typename, typename> friend struct associated_executor; template <typename, typename> friend struct associated_immediate_executor; const detail::any_completion_handler_fn_table<Signatures...>* fn_table_; detail::any_completion_handler_impl_base* impl_; #endif // !defined(GENERATING_DOCUMENTATION) public: /// The associated allocator type. using allocator_type = any_completion_handler_allocator<void, Signatures...>; /// The associated cancellation slot type. using cancellation_slot_type = cancellation_slot; /// Construct an @c any_completion_handler in an empty state, without a target /// object. constexpr any_completion_handler() : fn_table_(nullptr), impl_(nullptr) { } /// Construct an @c any_completion_handler in an empty state, without a target /// object. constexpr any_completion_handler(nullptr_t) : fn_table_(nullptr), impl_(nullptr) { } /// Construct an @c any_completion_handler to contain the specified target. template <typename H, typename Handler = decay_t<H>> any_completion_handler(H&& h, constraint_t< !is_same<decay_t<H>, any_completion_handler>::value > = 0) : fn_table_( &detail::any_completion_handler_fn_table_instance< Handler, Signatures...>::value), impl_(detail::any_completion_handler_impl<Handler>::create( (get_associated_cancellation_slot)(h), static_cast<H&&>(h))) { } /// Move-construct an @c any_completion_handler from another. /** * After the operation, the moved-from object @c other has no target. */ any_completion_handler(any_completion_handler&& other) noexcept : fn_table_(other.fn_table_), impl_(other.impl_) { other.fn_table_ = nullptr; other.impl_ = nullptr; } /// Move-assign an @c any_completion_handler from another. /** * After the operation, the moved-from object @c other has no target. */ any_completion_handler& operator=( any_completion_handler&& other) noexcept { any_completion_handler( static_cast<any_completion_handler&&>(other)).swap(*this); return *this; } /// Assignment operator that sets the polymorphic wrapper to the empty state. any_completion_handler& operator=(nullptr_t) noexcept { any_completion_handler().swap(*this); return *this; } /// Destructor. ~any_completion_handler() { if (impl_) fn_table_->destroy(impl_); } /// Test if the polymorphic wrapper is empty. constexpr explicit operator bool() const noexcept { return impl_ != nullptr; } /// Test if the polymorphic wrapper is non-empty. constexpr bool operator!() const noexcept { return impl_ == nullptr; } /// Swap the content of an @c any_completion_handler with another. void swap(any_completion_handler& other) noexcept { std::swap(fn_table_, other.fn_table_); std::swap(impl_, other.impl_); } /// Get the associated allocator. allocator_type get_allocator() const noexcept { return allocator_type(0, *this); } /// Get the associated cancellation slot. cancellation_slot_type get_cancellation_slot() const noexcept { return impl_ ? impl_->get_cancellation_slot() : cancellation_slot_type(); } /// Function call operator. /** * Invokes target completion handler with the supplied arguments. * * This function may only be called once, as the target handler is moved from. * The polymorphic wrapper is left in an empty state. * * Throws @c std::bad_function_call if the polymorphic wrapper is empty. */ template <typename... Args> auto operator()(Args&&... args) -> decltype(fn_table_->call(impl_, static_cast<Args&&>(args)...)) { if (detail::any_completion_handler_impl_base* impl = impl_) { impl_ = nullptr; return fn_table_->call(impl, static_cast<Args&&>(args)...); } std::bad_function_call ex; asio::detail::throw_exception(ex); } /// Equality operator. friend constexpr bool operator==( const any_completion_handler& a, nullptr_t) noexcept { return a.impl_ == nullptr; } /// Equality operator. friend constexpr bool operator==( nullptr_t, const any_completion_handler& b) noexcept { return nullptr == b.impl_; } /// Inequality operator. friend constexpr bool operator!=( const any_completion_handler& a, nullptr_t) noexcept { return a.impl_ != nullptr; } /// Inequality operator. friend constexpr bool operator!=( nullptr_t, const any_completion_handler& b) noexcept { return nullptr != b.impl_; } }; template <typename... Signatures, typename Candidate> struct associated_executor<any_completion_handler<Signatures...>, Candidate> { using type = any_completion_executor; static type get(const any_completion_handler<Signatures...>& handler, const Candidate& candidate = Candidate()) noexcept { any_completion_executor any_candidate(std::nothrow, candidate); return handler.fn_table_ ? handler.fn_table_->executor(handler.impl_, any_candidate) : any_candidate; } }; template <typename... Signatures, typename Candidate> struct associated_immediate_executor< any_completion_handler<Signatures...>, Candidate> { using type = any_completion_executor; static type get(const any_completion_handler<Signatures...>& handler, const Candidate& candidate = Candidate()) noexcept { any_io_executor any_candidate(std::nothrow, candidate); return handler.fn_table_ ? handler.fn_table_->immediate_executor(handler.impl_, any_candidate) : any_candidate; } }; } // namespace asio #include "asio/detail/pop_options.hpp" #endif // ASIO_ANY_COMPLETION_HANDLER_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/signal_set_base.hpp
// // signal_set_base.hpp // ~~~~~~~~~~~~~~~~~~~ // // 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) // #ifndef ASIO_SIGNAL_SET_BASE_HPP #define ASIO_SIGNAL_SET_BASE_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include "asio/detail/socket_types.hpp" #include "asio/detail/push_options.hpp" namespace asio { /// The signal_set_base class is used as a base for the basic_signal_set class /// templates so that we have a common place to define the flags enum. class signal_set_base { public: # if defined(GENERATING_DOCUMENTATION) /// Enumeration representing the different types of flags that may specified /// when adding a signal to a set. enum flags { /// Bitmask representing no flags. none = 0, /// Affects the behaviour of interruptible functions such that, if the /// function would have failed with error::interrupted when interrupted by /// the specified signal, the function shall instead be restarted and not /// fail with error::interrupted. restart = implementation_defined, /// Do not generate SIGCHLD when child processes stop or stopped child /// processes continue. no_child_stop = implementation_defined, /// Do not transform child processes into zombies when they terminate. no_child_wait = implementation_defined, /// Special value to indicate that the signal registration does not care /// which flags are set, and so will not conflict with any prior /// registrations of the same signal. dont_care = -1 }; /// Portability typedef. typedef flags flags_t; #else // defined(GENERATING_DOCUMENTATION) enum class flags : int { none = 0, restart = ASIO_OS_DEF(SA_RESTART), no_child_stop = ASIO_OS_DEF(SA_NOCLDSTOP), no_child_wait = ASIO_OS_DEF(SA_NOCLDWAIT), dont_care = -1 }; typedef flags flags_t; #endif // defined(GENERATING_DOCUMENTATION) protected: /// Protected destructor to prevent deletion through this type. ~signal_set_base() { } }; /// Negation operator. /** * @relates signal_set_base::flags */ inline constexpr bool operator!(signal_set_base::flags_t x) { return static_cast<int>(x) == 0; } /// Bitwise and operator. /** * @relates signal_set_base::flags */ inline constexpr signal_set_base::flags_t operator&( signal_set_base::flags_t x, signal_set_base::flags_t y) { return static_cast<signal_set_base::flags_t>( static_cast<int>(x) & static_cast<int>(y)); } /// Bitwise or operator. /** * @relates signal_set_base::flags */ inline constexpr signal_set_base::flags_t operator|( signal_set_base::flags_t x, signal_set_base::flags_t y) { return static_cast<signal_set_base::flags_t>( static_cast<int>(x) | static_cast<int>(y)); } /// Bitwise xor operator. /** * @relates signal_set_base::flags */ inline constexpr signal_set_base::flags_t operator^( signal_set_base::flags_t x, signal_set_base::flags_t y) { return static_cast<signal_set_base::flags_t>( static_cast<int>(x) ^ static_cast<int>(y)); } /// Bitwise negation operator. /** * @relates signal_set_base::flags */ inline constexpr signal_set_base::flags_t operator~( signal_set_base::flags_t x) { return static_cast<signal_set_base::flags_t>(~static_cast<int>(x)); } /// Bitwise and-assignment operator. /** * @relates signal_set_base::flags */ inline signal_set_base::flags_t& operator&=( signal_set_base::flags_t& x, signal_set_base::flags_t y) { x = x & y; return x; } /// Bitwise or-assignment operator. /** * @relates signal_set_base::flags */ inline signal_set_base::flags_t& operator|=( signal_set_base::flags_t& x, signal_set_base::flags_t y) { x = x | y; return x; } /// Bitwise xor-assignment operator. /** * @relates signal_set_base::flags */ inline signal_set_base::flags_t& operator^=( signal_set_base::flags_t& x, signal_set_base::flags_t y) { x = x ^ y; return x; } } // namespace asio #include "asio/detail/pop_options.hpp" #endif // ASIO_SIGNAL_SET_BASE_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/system_error.hpp
// // system_error.hpp // ~~~~~~~~~~~~~~~~ // // 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) // #ifndef ASIO_SYSTEM_ERROR_HPP #define ASIO_SYSTEM_ERROR_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include <system_error> #include "asio/detail/push_options.hpp" namespace asio { typedef std::system_error system_error; } // namespace asio #include "asio/detail/pop_options.hpp" #endif // ASIO_SYSTEM_ERROR_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/any_io_executor.hpp
// // any_io_executor.hpp // ~~~~~~~~~~~~~~~~~~~ // // 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) // #ifndef ASIO_ANY_IO_EXECUTOR_HPP #define ASIO_ANY_IO_EXECUTOR_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #if defined(ASIO_USE_TS_EXECUTOR_AS_DEFAULT) # include "asio/executor.hpp" #else // defined(ASIO_USE_TS_EXECUTOR_AS_DEFAULT) # include "asio/execution.hpp" # include "asio/execution_context.hpp" #endif // defined(ASIO_USE_TS_EXECUTOR_AS_DEFAULT) #include "asio/detail/push_options.hpp" namespace asio { #if defined(ASIO_USE_TS_EXECUTOR_AS_DEFAULT) typedef executor any_io_executor; #else // defined(ASIO_USE_TS_EXECUTOR_AS_DEFAULT) /// Polymorphic executor type for use with I/O objects. /** * The @c any_io_executor type is a polymorphic executor that supports the set * of properties required by I/O objects. It is defined as the * execution::any_executor class template parameterised as follows: * @code execution::any_executor< * execution::context_as_t<execution_context&>, * execution::blocking_t::never_t, * execution::prefer_only<execution::blocking_t::possibly_t>, * execution::prefer_only<execution::outstanding_work_t::tracked_t>, * execution::prefer_only<execution::outstanding_work_t::untracked_t>, * execution::prefer_only<execution::relationship_t::fork_t>, * execution::prefer_only<execution::relationship_t::continuation_t> * > @endcode */ class any_io_executor : #if defined(GENERATING_DOCUMENTATION) public execution::any_executor<...> #else // defined(GENERATING_DOCUMENTATION) public execution::any_executor< execution::context_as_t<execution_context&>, execution::blocking_t::never_t, execution::prefer_only<execution::blocking_t::possibly_t>, execution::prefer_only<execution::outstanding_work_t::tracked_t>, execution::prefer_only<execution::outstanding_work_t::untracked_t>, execution::prefer_only<execution::relationship_t::fork_t>, execution::prefer_only<execution::relationship_t::continuation_t> > #endif // defined(GENERATING_DOCUMENTATION) { public: #if !defined(GENERATING_DOCUMENTATION) typedef execution::any_executor< execution::context_as_t<execution_context&>, execution::blocking_t::never_t, execution::prefer_only<execution::blocking_t::possibly_t>, execution::prefer_only<execution::outstanding_work_t::tracked_t>, execution::prefer_only<execution::outstanding_work_t::untracked_t>, execution::prefer_only<execution::relationship_t::fork_t>, execution::prefer_only<execution::relationship_t::continuation_t> > base_type; typedef void supportable_properties_type( execution::context_as_t<execution_context&>, execution::blocking_t::never_t, execution::prefer_only<execution::blocking_t::possibly_t>, execution::prefer_only<execution::outstanding_work_t::tracked_t>, execution::prefer_only<execution::outstanding_work_t::untracked_t>, execution::prefer_only<execution::relationship_t::fork_t>, execution::prefer_only<execution::relationship_t::continuation_t> ); #endif // !defined(GENERATING_DOCUMENTATION) /// Default constructor. ASIO_DECL any_io_executor() noexcept; /// Construct in an empty state. Equivalent effects to default constructor. ASIO_DECL any_io_executor(nullptr_t) noexcept; /// Copy constructor. ASIO_DECL any_io_executor(const any_io_executor& e) noexcept; /// Move constructor. ASIO_DECL any_io_executor(any_io_executor&& e) noexcept; /// Construct to point to the same target as another any_executor. #if defined(GENERATING_DOCUMENTATION) template <class... OtherSupportableProperties> any_io_executor(execution::any_executor<OtherSupportableProperties...> e); #else // defined(GENERATING_DOCUMENTATION) template <typename OtherAnyExecutor> any_io_executor(OtherAnyExecutor e, constraint_t< conditional_t< !is_same<OtherAnyExecutor, any_io_executor>::value && is_base_of<execution::detail::any_executor_base, OtherAnyExecutor>::value, typename execution::detail::supportable_properties< 0, supportable_properties_type>::template is_valid_target<OtherAnyExecutor>, false_type >::value > = 0) : base_type(static_cast<OtherAnyExecutor&&>(e)) { } #endif // defined(GENERATING_DOCUMENTATION) /// Construct to point to the same target as another any_executor. #if defined(GENERATING_DOCUMENTATION) template <class... OtherSupportableProperties> any_io_executor(std::nothrow_t, execution::any_executor<OtherSupportableProperties...> e); #else // defined(GENERATING_DOCUMENTATION) template <typename OtherAnyExecutor> any_io_executor(std::nothrow_t, OtherAnyExecutor e, constraint_t< conditional_t< !is_same<OtherAnyExecutor, any_io_executor>::value && is_base_of<execution::detail::any_executor_base, OtherAnyExecutor>::value, typename execution::detail::supportable_properties< 0, supportable_properties_type>::template is_valid_target<OtherAnyExecutor>, false_type >::value > = 0) noexcept : base_type(std::nothrow, static_cast<OtherAnyExecutor&&>(e)) { } #endif // defined(GENERATING_DOCUMENTATION) /// Construct to point to the same target as another any_executor. ASIO_DECL any_io_executor(std::nothrow_t, const any_io_executor& e) noexcept; /// Construct to point to the same target as another any_executor. ASIO_DECL any_io_executor(std::nothrow_t, any_io_executor&& e) noexcept; /// Construct a polymorphic wrapper for the specified executor. #if defined(GENERATING_DOCUMENTATION) template <ASIO_EXECUTION_EXECUTOR Executor> any_io_executor(Executor e); #else // defined(GENERATING_DOCUMENTATION) template <ASIO_EXECUTION_EXECUTOR Executor> any_io_executor(Executor e, constraint_t< conditional_t< !is_same<Executor, any_io_executor>::value && !is_base_of<execution::detail::any_executor_base, Executor>::value, execution::detail::is_valid_target_executor< Executor, supportable_properties_type>, false_type >::value > = 0) : base_type(static_cast<Executor&&>(e)) { } #endif // defined(GENERATING_DOCUMENTATION) /// Construct a polymorphic wrapper for the specified executor. #if defined(GENERATING_DOCUMENTATION) template <ASIO_EXECUTION_EXECUTOR Executor> any_io_executor(std::nothrow_t, Executor e); #else // defined(GENERATING_DOCUMENTATION) template <ASIO_EXECUTION_EXECUTOR Executor> any_io_executor(std::nothrow_t, Executor e, constraint_t< conditional_t< !is_same<Executor, any_io_executor>::value && !is_base_of<execution::detail::any_executor_base, Executor>::value, execution::detail::is_valid_target_executor< Executor, supportable_properties_type>, false_type >::value > = 0) noexcept : base_type(std::nothrow, static_cast<Executor&&>(e)) { } #endif // defined(GENERATING_DOCUMENTATION) /// Assignment operator. ASIO_DECL any_io_executor& operator=( const any_io_executor& e) noexcept; /// Move assignment operator. ASIO_DECL any_io_executor& operator=(any_io_executor&& e) noexcept; /// Assignment operator that sets the polymorphic wrapper to the empty state. ASIO_DECL any_io_executor& operator=(nullptr_t); /// Destructor. ASIO_DECL ~any_io_executor(); /// Swap targets with another polymorphic wrapper. ASIO_DECL void swap(any_io_executor& other) noexcept; /// Obtain a polymorphic wrapper with the specified property. /** * Do not call this function directly. It is intended for use with the * asio::require and asio::prefer customisation points. * * For example: * @code any_io_executor ex = ...; * auto ex2 = asio::require(ex, execution::blocking.possibly); @endcode */ template <typename Property> any_io_executor require(const Property& p, constraint_t< traits::require_member<const base_type&, const Property&>::is_valid > = 0) const { return static_cast<const base_type&>(*this).require(p); } /// Obtain a polymorphic wrapper with the specified property. /** * Do not call this function directly. It is intended for use with the * asio::prefer customisation point. * * For example: * @code any_io_executor ex = ...; * auto ex2 = asio::prefer(ex, execution::blocking.possibly); @endcode */ template <typename Property> any_io_executor prefer(const Property& p, constraint_t< traits::prefer_member<const base_type&, const Property&>::is_valid > = 0) const { return static_cast<const base_type&>(*this).prefer(p); } }; #if !defined(GENERATING_DOCUMENTATION) template <> ASIO_DECL any_io_executor any_io_executor::require( const execution::blocking_t::never_t&, int) const; template <> ASIO_DECL any_io_executor any_io_executor::prefer( const execution::blocking_t::possibly_t&, int) const; template <> ASIO_DECL any_io_executor any_io_executor::prefer( const execution::outstanding_work_t::tracked_t&, int) const; template <> ASIO_DECL any_io_executor any_io_executor::prefer( const execution::outstanding_work_t::untracked_t&, int) const; template <> ASIO_DECL any_io_executor any_io_executor::prefer( const execution::relationship_t::fork_t&, int) const; template <> ASIO_DECL any_io_executor any_io_executor::prefer( const execution::relationship_t::continuation_t&, int) const; namespace traits { #if !defined(ASIO_HAS_DEDUCED_EQUALITY_COMPARABLE_TRAIT) template <> struct equality_comparable<any_io_executor> { static const bool is_valid = true; static const bool is_noexcept = true; }; #endif // !defined(ASIO_HAS_DEDUCED_EQUALITY_COMPARABLE_TRAIT) #if !defined(ASIO_HAS_DEDUCED_EXECUTE_MEMBER_TRAIT) template <typename F> struct execute_member<any_io_executor, F> { static const bool is_valid = true; static const bool is_noexcept = false; typedef void result_type; }; #endif // !defined(ASIO_HAS_DEDUCED_EXECUTE_MEMBER_TRAIT) #if !defined(ASIO_HAS_DEDUCED_QUERY_MEMBER_TRAIT) template <typename Prop> struct query_member<any_io_executor, Prop> : query_member<any_io_executor::base_type, Prop> { }; #endif // !defined(ASIO_HAS_DEDUCED_QUERY_MEMBER_TRAIT) #if !defined(ASIO_HAS_DEDUCED_REQUIRE_MEMBER_TRAIT) template <typename Prop> struct require_member<any_io_executor, Prop> : require_member<any_io_executor::base_type, Prop> { typedef any_io_executor result_type; }; #endif // !defined(ASIO_HAS_DEDUCED_REQUIRE_MEMBER_TRAIT) #if !defined(ASIO_HAS_DEDUCED_PREFER_MEMBER_TRAIT) template <typename Prop> struct prefer_member<any_io_executor, Prop> : prefer_member<any_io_executor::base_type, Prop> { typedef any_io_executor result_type; }; #endif // !defined(ASIO_HAS_DEDUCED_PREFER_MEMBER_TRAIT) } // namespace traits #endif // !defined(GENERATING_DOCUMENTATION) #endif // defined(ASIO_USE_TS_EXECUTOR_AS_DEFAULT) } // namespace asio #include "asio/detail/pop_options.hpp" #if defined(ASIO_HEADER_ONLY) \ && !defined(ASIO_USE_TS_EXECUTOR_AS_DEFAULT) # include "asio/impl/any_io_executor.ipp" #endif // defined(ASIO_HEADER_ONLY) // && !defined(ASIO_USE_TS_EXECUTOR_AS_DEFAULT) #endif // ASIO_ANY_IO_EXECUTOR_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/buffered_write_stream_fwd.hpp
// // buffered_write_stream_fwd.hpp // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // // 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) // #ifndef ASIO_BUFFERED_WRITE_STREAM_FWD_HPP #define ASIO_BUFFERED_WRITE_STREAM_FWD_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) namespace asio { template <typename Stream> class buffered_write_stream; } // namespace asio #endif // ASIO_BUFFERED_WRITE_STREAM_FWD_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/consign.hpp
// // consign.hpp // ~~~~~~~~~~~ // // 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) // #ifndef ASIO_CONSIGN_HPP #define ASIO_CONSIGN_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include <tuple> #include "asio/detail/type_traits.hpp" #include "asio/detail/push_options.hpp" namespace asio { /// Completion token type used to specify that the completion handler should /// carry additional values along with it. /** * This completion token adapter is typically used to keep at least one copy of * an object, such as a smart pointer, alive until the completion handler is * called. */ template <typename CompletionToken, typename... Values> class consign_t { public: /// Constructor. template <typename T, typename... V> constexpr explicit consign_t(T&& completion_token, V&&... values) : token_(static_cast<T&&>(completion_token)), values_(static_cast<V&&>(values)...) { } #if defined(GENERATING_DOCUMENTATION) private: #endif // defined(GENERATING_DOCUMENTATION) CompletionToken token_; std::tuple<Values...> values_; }; /// Completion token adapter used to specify that the completion handler should /// carry additional values along with it. /** * This completion token adapter is typically used to keep at least one copy of * an object, such as a smart pointer, alive until the completion handler is * called. */ template <typename CompletionToken, typename... Values> ASIO_NODISCARD inline constexpr consign_t<decay_t<CompletionToken>, decay_t<Values>...> consign(CompletionToken&& completion_token, Values&&... values) { return consign_t<decay_t<CompletionToken>, decay_t<Values>...>( static_cast<CompletionToken&&>(completion_token), static_cast<Values&&>(values)...); } } // namespace asio #include "asio/detail/pop_options.hpp" #include "asio/impl/consign.hpp" #endif // ASIO_CONSIGN_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/coroutine.hpp
// // coroutine.hpp // ~~~~~~~~~~~~~ // // 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) // #ifndef ASIO_COROUTINE_HPP #define ASIO_COROUTINE_HPP namespace asio { namespace detail { class coroutine_ref; } // namespace detail /// Provides support for implementing stackless coroutines. /** * The @c coroutine class may be used to implement stackless coroutines. The * class itself is used to store the current state of the coroutine. * * Coroutines are copy-constructible and assignable, and the space overhead is * a single int. They can be used as a base class: * * @code class session : coroutine * { * ... * }; @endcode * * or as a data member: * * @code class session * { * ... * coroutine coro_; * }; @endcode * * or even bound in as a function argument using lambdas or @c bind(). The * important thing is that as the application maintains a copy of the object * for as long as the coroutine must be kept alive. * * @par Pseudo-keywords * * A coroutine is used in conjunction with certain "pseudo-keywords", which * are implemented as macros. These macros are defined by a header file: * * @code #include <asio/yield.hpp>@endcode * * and may conversely be undefined as follows: * * @code #include <asio/unyield.hpp>@endcode * * <b>reenter</b> * * The @c reenter macro is used to define the body of a coroutine. It takes a * single argument: a pointer or reference to a coroutine object. For example, * if the base class is a coroutine object you may write: * * @code reenter (this) * { * ... coroutine body ... * } @endcode * * and if a data member or other variable you can write: * * @code reenter (coro_) * { * ... coroutine body ... * } @endcode * * When @c reenter is executed at runtime, control jumps to the location of the * last @c yield or @c fork. * * The coroutine body may also be a single statement, such as: * * @code reenter (this) for (;;) * { * ... * } @endcode * * @b Limitation: The @c reenter macro is implemented using a switch. This * means that you must take care when using local variables within the * coroutine body. The local variable is not allowed in a position where * reentering the coroutine could bypass the variable definition. * * <b>yield <em>statement</em></b> * * This form of the @c yield keyword is often used with asynchronous operations: * * @code yield socket_->async_read_some(buffer(*buffer_), *this); @endcode * * This divides into four logical steps: * * @li @c yield saves the current state of the coroutine. * @li The statement initiates the asynchronous operation. * @li The resume point is defined immediately following the statement. * @li Control is transferred to the end of the coroutine body. * * When the asynchronous operation completes, the function object is invoked * and @c reenter causes control to transfer to the resume point. It is * important to remember to carry the coroutine state forward with the * asynchronous operation. In the above snippet, the current class is a * function object object with a coroutine object as base class or data member. * * The statement may also be a compound statement, and this permits us to * define local variables with limited scope: * * @code yield * { * mutable_buffers_1 b = buffer(*buffer_); * socket_->async_read_some(b, *this); * } @endcode * * <b>yield return <em>expression</em> ;</b> * * This form of @c yield is often used in generators or coroutine-based parsers. * For example, the function object: * * @code struct interleave : coroutine * { * istream& is1; * istream& is2; * char operator()(char c) * { * reenter (this) for (;;) * { * yield return is1.get(); * yield return is2.get(); * } * } * }; @endcode * * defines a trivial coroutine that interleaves the characters from two input * streams. * * This type of @c yield divides into three logical steps: * * @li @c yield saves the current state of the coroutine. * @li The resume point is defined immediately following the semicolon. * @li The value of the expression is returned from the function. * * <b>yield ;</b> * * This form of @c yield is equivalent to the following steps: * * @li @c yield saves the current state of the coroutine. * @li The resume point is defined immediately following the semicolon. * @li Control is transferred to the end of the coroutine body. * * This form might be applied when coroutines are used for cooperative * threading and scheduling is explicitly managed. For example: * * @code struct task : coroutine * { * ... * void operator()() * { * reenter (this) * { * while (... not finished ...) * { * ... do something ... * yield; * ... do some more ... * yield; * } * } * } * ... * }; * ... * task t1, t2; * for (;;) * { * t1(); * t2(); * } @endcode * * <b>yield break ;</b> * * The final form of @c yield is used to explicitly terminate the coroutine. * This form is comprised of two steps: * * @li @c yield sets the coroutine state to indicate termination. * @li Control is transferred to the end of the coroutine body. * * Once terminated, calls to is_complete() return true and the coroutine cannot * be reentered. * * Note that a coroutine may also be implicitly terminated if the coroutine * body is exited without a yield, e.g. by return, throw or by running to the * end of the body. * * <b>fork <em>statement</em></b> * * The @c fork pseudo-keyword is used when "forking" a coroutine, i.e. splitting * it into two (or more) copies. One use of @c fork is in a server, where a new * coroutine is created to handle each client connection: * * @code reenter (this) * { * do * { * socket_.reset(new tcp::socket(my_context_)); * yield acceptor->async_accept(*socket_, *this); * fork server(*this)(); * } while (is_parent()); * ... client-specific handling follows ... * } @endcode * * The logical steps involved in a @c fork are: * * @li @c fork saves the current state of the coroutine. * @li The statement creates a copy of the coroutine and either executes it * immediately or schedules it for later execution. * @li The resume point is defined immediately following the semicolon. * @li For the "parent", control immediately continues from the next line. * * The functions is_parent() and is_child() can be used to differentiate * between parent and child. You would use these functions to alter subsequent * control flow. * * Note that @c fork doesn't do the actual forking by itself. It is the * application's responsibility to create a clone of the coroutine and call it. * The clone can be called immediately, as above, or scheduled for delayed * execution using something like asio::post(). * * @par Alternate macro names * * If preferred, an application can use macro names that follow a more typical * naming convention, rather than the pseudo-keywords. These are: * * @li @c ASIO_CORO_REENTER instead of @c reenter * @li @c ASIO_CORO_YIELD instead of @c yield * @li @c ASIO_CORO_FORK instead of @c fork */ class coroutine { public: /// Constructs a coroutine in its initial state. coroutine() : value_(0) {} /// Returns true if the coroutine is the child of a fork. bool is_child() const { return value_ < 0; } /// Returns true if the coroutine is the parent of a fork. bool is_parent() const { return !is_child(); } /// Returns true if the coroutine has reached its terminal state. bool is_complete() const { return value_ == -1; } private: friend class detail::coroutine_ref; int value_; }; namespace detail { class coroutine_ref { public: coroutine_ref(coroutine& c) : value_(c.value_), modified_(false) {} coroutine_ref(coroutine* c) : value_(c->value_), modified_(false) {} coroutine_ref(const coroutine_ref&) = default; ~coroutine_ref() { if (!modified_) value_ = -1; } operator int() const { return value_; } int& operator=(int v) { modified_ = true; return value_ = v; } private: void operator=(const coroutine_ref&); int& value_; bool modified_; }; } // namespace detail } // namespace asio #define ASIO_CORO_REENTER(c) \ switch (::asio::detail::coroutine_ref _coro_value = c) \ case -1: if (_coro_value) \ { \ goto terminate_coroutine; \ terminate_coroutine: \ _coro_value = -1; \ goto bail_out_of_coroutine; \ bail_out_of_coroutine: \ break; \ } \ else /* fall-through */ case 0: #define ASIO_CORO_YIELD_IMPL(n) \ for (_coro_value = (n);;) \ if (_coro_value == 0) \ { \ case (n): ; \ break; \ } \ else \ switch (_coro_value ? 0 : 1) \ for (;;) \ /* fall-through */ case -1: if (_coro_value) \ goto terminate_coroutine; \ else for (;;) \ /* fall-through */ case 1: if (_coro_value) \ goto bail_out_of_coroutine; \ else /* fall-through */ case 0: #define ASIO_CORO_FORK_IMPL(n) \ for (_coro_value = -(n);; _coro_value = (n)) \ if (_coro_value == (n)) \ { \ case -(n): ; \ break; \ } \ else #if defined(_MSC_VER) # define ASIO_CORO_YIELD ASIO_CORO_YIELD_IMPL(__COUNTER__ + 1) # define ASIO_CORO_FORK ASIO_CORO_FORK_IMPL(__COUNTER__ + 1) #else // defined(_MSC_VER) # define ASIO_CORO_YIELD ASIO_CORO_YIELD_IMPL(__LINE__) # define ASIO_CORO_FORK ASIO_CORO_FORK_IMPL(__LINE__) #endif // defined(_MSC_VER) #endif // ASIO_COROUTINE_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/basic_signal_set.hpp
// // basic_signal_set.hpp // ~~~~~~~~~~~~~~~~~~~~ // // 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) // #ifndef ASIO_BASIC_SIGNAL_SET_HPP #define ASIO_BASIC_SIGNAL_SET_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include "asio/any_io_executor.hpp" #include "asio/async_result.hpp" #include "asio/detail/handler_type_requirements.hpp" #include "asio/detail/io_object_impl.hpp" #include "asio/detail/non_const_lvalue.hpp" #include "asio/detail/signal_set_service.hpp" #include "asio/detail/throw_error.hpp" #include "asio/detail/type_traits.hpp" #include "asio/error.hpp" #include "asio/execution_context.hpp" #include "asio/signal_set_base.hpp" #include "asio/detail/push_options.hpp" namespace asio { /// Provides signal functionality. /** * The basic_signal_set class provides the ability to perform an asynchronous * wait for one or more signals to occur. * * @par Thread Safety * @e Distinct @e objects: Safe.@n * @e Shared @e objects: Unsafe. * * @par Example * Performing an asynchronous wait: * @code * void handler( * const asio::error_code& error, * int signal_number) * { * if (!error) * { * // A signal occurred. * } * } * * ... * * // Construct a signal set registered for process termination. * asio::signal_set signals(my_context, SIGINT, SIGTERM); * * // Start an asynchronous wait for one of the signals to occur. * signals.async_wait(handler); * @endcode * * @par Queueing of signal notifications * * If a signal is registered with a signal_set, and the signal occurs when * there are no waiting handlers, then the signal notification is queued. The * next async_wait operation on that signal_set will dequeue the notification. * If multiple notifications are queued, subsequent async_wait operations * dequeue them one at a time. Signal notifications are dequeued in order of * ascending signal number. * * If a signal number is removed from a signal_set (using the @c remove or @c * erase member functions) then any queued notifications for that signal are * discarded. * * @par Multiple registration of signals * * The same signal number may be registered with different signal_set objects. * When the signal occurs, one handler is called for each signal_set object. * * Note that multiple registration only works for signals that are registered * using Asio. The application must not also register a signal handler using * functions such as @c signal() or @c sigaction(). * * @par Signal masking on POSIX platforms * * POSIX allows signals to be blocked using functions such as @c sigprocmask() * and @c pthread_sigmask(). For signals to be delivered, programs must ensure * that any signals registered using signal_set objects are unblocked in at * least one thread. */ template <typename Executor = any_io_executor> class basic_signal_set : public signal_set_base { private: class initiate_async_wait; public: /// The type of the executor associated with the object. typedef Executor executor_type; /// Rebinds the signal set type to another executor. template <typename Executor1> struct rebind_executor { /// The signal set type when rebound to the specified executor. typedef basic_signal_set<Executor1> other; }; /// Construct a signal set without adding any signals. /** * This constructor creates a signal set without registering for any signals. * * @param ex The I/O executor that the signal set will use, by default, to * dispatch handlers for any asynchronous operations performed on the * signal set. */ explicit basic_signal_set(const executor_type& ex) : impl_(0, ex) { } /// Construct a signal set without adding any signals. /** * This constructor creates a signal set without registering for any signals. * * @param context An execution context which provides the I/O executor that * the signal set will use, by default, to dispatch handlers for any * asynchronous operations performed on the signal set. */ template <typename ExecutionContext> explicit basic_signal_set(ExecutionContext& context, constraint_t< is_convertible<ExecutionContext&, execution_context&>::value, defaulted_constraint > = defaulted_constraint()) : impl_(0, 0, context) { } /// Construct a signal set and add one signal. /** * This constructor creates a signal set and registers for one signal. * * @param ex The I/O executor that the signal set will use, by default, to * dispatch handlers for any asynchronous operations performed on the * signal set. * * @param signal_number_1 The signal number to be added. * * @note This constructor is equivalent to performing: * @code asio::signal_set signals(ex); * signals.add(signal_number_1); @endcode */ basic_signal_set(const executor_type& ex, int signal_number_1) : impl_(0, ex) { asio::error_code ec; impl_.get_service().add(impl_.get_implementation(), signal_number_1, ec); asio::detail::throw_error(ec, "add"); } /// Construct a signal set and add one signal. /** * This constructor creates a signal set and registers for one signal. * * @param context An execution context which provides the I/O executor that * the signal set will use, by default, to dispatch handlers for any * asynchronous operations performed on the signal set. * * @param signal_number_1 The signal number to be added. * * @note This constructor is equivalent to performing: * @code asio::signal_set signals(context); * signals.add(signal_number_1); @endcode */ template <typename ExecutionContext> basic_signal_set(ExecutionContext& context, int signal_number_1, constraint_t< is_convertible<ExecutionContext&, execution_context&>::value, defaulted_constraint > = defaulted_constraint()) : impl_(0, 0, context) { asio::error_code ec; impl_.get_service().add(impl_.get_implementation(), signal_number_1, ec); asio::detail::throw_error(ec, "add"); } /// Construct a signal set and add two signals. /** * This constructor creates a signal set and registers for two signals. * * @param ex The I/O executor that the signal set will use, by default, to * dispatch handlers for any asynchronous operations performed on the * signal set. * * @param signal_number_1 The first signal number to be added. * * @param signal_number_2 The second signal number to be added. * * @note This constructor is equivalent to performing: * @code asio::signal_set signals(ex); * signals.add(signal_number_1); * signals.add(signal_number_2); @endcode */ basic_signal_set(const executor_type& ex, int signal_number_1, int signal_number_2) : impl_(0, ex) { asio::error_code ec; impl_.get_service().add(impl_.get_implementation(), signal_number_1, ec); asio::detail::throw_error(ec, "add"); impl_.get_service().add(impl_.get_implementation(), signal_number_2, ec); asio::detail::throw_error(ec, "add"); } /// Construct a signal set and add two signals. /** * This constructor creates a signal set and registers for two signals. * * @param context An execution context which provides the I/O executor that * the signal set will use, by default, to dispatch handlers for any * asynchronous operations performed on the signal set. * * @param signal_number_1 The first signal number to be added. * * @param signal_number_2 The second signal number to be added. * * @note This constructor is equivalent to performing: * @code asio::signal_set signals(context); * signals.add(signal_number_1); * signals.add(signal_number_2); @endcode */ template <typename ExecutionContext> basic_signal_set(ExecutionContext& context, int signal_number_1, int signal_number_2, constraint_t< is_convertible<ExecutionContext&, execution_context&>::value, defaulted_constraint > = defaulted_constraint()) : impl_(0, 0, context) { asio::error_code ec; impl_.get_service().add(impl_.get_implementation(), signal_number_1, ec); asio::detail::throw_error(ec, "add"); impl_.get_service().add(impl_.get_implementation(), signal_number_2, ec); asio::detail::throw_error(ec, "add"); } /// Construct a signal set and add three signals. /** * This constructor creates a signal set and registers for three signals. * * @param ex The I/O executor that the signal set will use, by default, to * dispatch handlers for any asynchronous operations performed on the * signal set. * * @param signal_number_1 The first signal number to be added. * * @param signal_number_2 The second signal number to be added. * * @param signal_number_3 The third signal number to be added. * * @note This constructor is equivalent to performing: * @code asio::signal_set signals(ex); * signals.add(signal_number_1); * signals.add(signal_number_2); * signals.add(signal_number_3); @endcode */ basic_signal_set(const executor_type& ex, int signal_number_1, int signal_number_2, int signal_number_3) : impl_(0, ex) { asio::error_code ec; impl_.get_service().add(impl_.get_implementation(), signal_number_1, ec); asio::detail::throw_error(ec, "add"); impl_.get_service().add(impl_.get_implementation(), signal_number_2, ec); asio::detail::throw_error(ec, "add"); impl_.get_service().add(impl_.get_implementation(), signal_number_3, ec); asio::detail::throw_error(ec, "add"); } /// Construct a signal set and add three signals. /** * This constructor creates a signal set and registers for three signals. * * @param context An execution context which provides the I/O executor that * the signal set will use, by default, to dispatch handlers for any * asynchronous operations performed on the signal set. * * @param signal_number_1 The first signal number to be added. * * @param signal_number_2 The second signal number to be added. * * @param signal_number_3 The third signal number to be added. * * @note This constructor is equivalent to performing: * @code asio::signal_set signals(context); * signals.add(signal_number_1); * signals.add(signal_number_2); * signals.add(signal_number_3); @endcode */ template <typename ExecutionContext> basic_signal_set(ExecutionContext& context, int signal_number_1, int signal_number_2, int signal_number_3, constraint_t< is_convertible<ExecutionContext&, execution_context&>::value, defaulted_constraint > = defaulted_constraint()) : impl_(0, 0, context) { asio::error_code ec; impl_.get_service().add(impl_.get_implementation(), signal_number_1, ec); asio::detail::throw_error(ec, "add"); impl_.get_service().add(impl_.get_implementation(), signal_number_2, ec); asio::detail::throw_error(ec, "add"); impl_.get_service().add(impl_.get_implementation(), signal_number_3, ec); asio::detail::throw_error(ec, "add"); } /// Destroys the signal set. /** * This function destroys the signal set, cancelling any outstanding * asynchronous wait operations associated with the signal set as if by * calling @c cancel. */ ~basic_signal_set() { } /// Get the executor associated with the object. const executor_type& get_executor() noexcept { return impl_.get_executor(); } /// Add a signal to a signal_set. /** * This function adds the specified signal to the set. It has no effect if the * signal is already in the set. * * @param signal_number The signal to be added to the set. * * @throws asio::system_error Thrown on failure. */ void add(int signal_number) { asio::error_code ec; impl_.get_service().add(impl_.get_implementation(), signal_number, ec); asio::detail::throw_error(ec, "add"); } /// Add a signal to a signal_set. /** * This function adds the specified signal to the set. It has no effect if the * signal is already in the set. * * @param signal_number The signal to be added to the set. * * @param ec Set to indicate what error occurred, if any. */ ASIO_SYNC_OP_VOID add(int signal_number, asio::error_code& ec) { impl_.get_service().add(impl_.get_implementation(), signal_number, ec); ASIO_SYNC_OP_VOID_RETURN(ec); } /// Add a signal to a signal_set with the specified flags. /** * This function adds the specified signal to the set. It has no effect if the * signal is already in the set. * * Flags other than flags::dont_care require OS support for the @c sigaction * call, and this function will fail with @c error::operation_not_supported if * this is unavailable. * * The specified flags will conflict with a prior, active registration of the * same signal, if either specified a flags value other than flags::dont_care. * In this case, the @c add will fail with @c error::invalid_argument. * * @param signal_number The signal to be added to the set. * * @param f Flags to modify the behaviour of the specified signal. * * @throws asio::system_error Thrown on failure. */ void add(int signal_number, flags_t f) { asio::error_code ec; impl_.get_service().add(impl_.get_implementation(), signal_number, f, ec); asio::detail::throw_error(ec, "add"); } /// Add a signal to a signal_set with the specified flags. /** * This function adds the specified signal to the set. It has no effect if the * signal is already in the set. * * Flags other than flags::dont_care require OS support for the @c sigaction * call, and this function will fail with @c error::operation_not_supported if * this is unavailable. * * The specified flags will conflict with a prior, active registration of the * same signal, if either specified a flags value other than flags::dont_care. * In this case, the @c add will fail with @c error::invalid_argument. * * @param signal_number The signal to be added to the set. * * @param f Flags to modify the behaviour of the specified signal. * * @param ec Set to indicate what error occurred, if any. */ ASIO_SYNC_OP_VOID add(int signal_number, flags_t f, asio::error_code& ec) { impl_.get_service().add(impl_.get_implementation(), signal_number, f, ec); ASIO_SYNC_OP_VOID_RETURN(ec); } /// Remove a signal from a signal_set. /** * This function removes the specified signal from the set. It has no effect * if the signal is not in the set. * * @param signal_number The signal to be removed from the set. * * @throws asio::system_error Thrown on failure. * * @note Removes any notifications that have been queued for the specified * signal number. */ void remove(int signal_number) { asio::error_code ec; impl_.get_service().remove(impl_.get_implementation(), signal_number, ec); asio::detail::throw_error(ec, "remove"); } /// Remove a signal from a signal_set. /** * This function removes the specified signal from the set. It has no effect * if the signal is not in the set. * * @param signal_number The signal to be removed from the set. * * @param ec Set to indicate what error occurred, if any. * * @note Removes any notifications that have been queued for the specified * signal number. */ ASIO_SYNC_OP_VOID remove(int signal_number, asio::error_code& ec) { impl_.get_service().remove(impl_.get_implementation(), signal_number, ec); ASIO_SYNC_OP_VOID_RETURN(ec); } /// Remove all signals from a signal_set. /** * This function removes all signals from the set. It has no effect if the set * is already empty. * * @throws asio::system_error Thrown on failure. * * @note Removes all queued notifications. */ void clear() { asio::error_code ec; impl_.get_service().clear(impl_.get_implementation(), ec); asio::detail::throw_error(ec, "clear"); } /// Remove all signals from a signal_set. /** * This function removes all signals from the set. It has no effect if the set * is already empty. * * @param ec Set to indicate what error occurred, if any. * * @note Removes all queued notifications. */ ASIO_SYNC_OP_VOID clear(asio::error_code& ec) { impl_.get_service().clear(impl_.get_implementation(), ec); ASIO_SYNC_OP_VOID_RETURN(ec); } /// Cancel all operations associated with the signal set. /** * This function forces the completion of any pending asynchronous wait * operations against the signal set. The handler for each cancelled * operation will be invoked with the asio::error::operation_aborted * error code. * * Cancellation does not alter the set of registered signals. * * @throws asio::system_error Thrown on failure. * * @note If a registered signal occurred before cancel() is called, then the * handlers for asynchronous wait operations will: * * @li have already been invoked; or * * @li have been queued for invocation in the near future. * * These handlers can no longer be cancelled, and therefore are passed an * error code that indicates the successful completion of the wait operation. */ void cancel() { asio::error_code ec; impl_.get_service().cancel(impl_.get_implementation(), ec); asio::detail::throw_error(ec, "cancel"); } /// Cancel all operations associated with the signal set. /** * This function forces the completion of any pending asynchronous wait * operations against the signal set. The handler for each cancelled * operation will be invoked with the asio::error::operation_aborted * error code. * * Cancellation does not alter the set of registered signals. * * @param ec Set to indicate what error occurred, if any. * * @note If a registered signal occurred before cancel() is called, then the * handlers for asynchronous wait operations will: * * @li have already been invoked; or * * @li have been queued for invocation in the near future. * * These handlers can no longer be cancelled, and therefore are passed an * error code that indicates the successful completion of the wait operation. */ ASIO_SYNC_OP_VOID cancel(asio::error_code& ec) { impl_.get_service().cancel(impl_.get_implementation(), ec); ASIO_SYNC_OP_VOID_RETURN(ec); } /// Start an asynchronous operation to wait for a signal to be delivered. /** * This function may be used to initiate an asynchronous wait against the * signal set. It is an initiating function for an @ref * asynchronous_operation, and always returns immediately. * * For each call to async_wait(), the completion handler will be called * exactly once. The completion handler will be called when: * * @li One of the registered signals in the signal set occurs; or * * @li The signal set was cancelled, in which case the handler is passed the * error code asio::error::operation_aborted. * * @param token The @ref completion_token that will be used to produce a * completion handler, which will be called when the wait completes. * Potential completion tokens include @ref use_future, @ref use_awaitable, * @ref yield_context, or a function object with the correct completion * signature. The function signature of the completion handler must be: * @code void handler( * const asio::error_code& error, // Result of operation. * int signal_number // Indicates which signal occurred. * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the completion handler will not be invoked from within this function. * On immediate completion, invocation of the handler will be performed in a * manner equivalent to using asio::async_immediate(). * * @par Completion Signature * @code void(asio::error_code, int) @endcode * * @par Per-Operation Cancellation * This asynchronous operation supports cancellation for the following * asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * @li @c cancellation_type::total */ template < ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code, int)) SignalToken = default_completion_token_t<executor_type>> auto async_wait( SignalToken&& token = default_completion_token_t<executor_type>()) -> decltype( async_initiate<SignalToken, void (asio::error_code, int)>( declval<initiate_async_wait>(), token)) { return async_initiate<SignalToken, void (asio::error_code, int)>( initiate_async_wait(this), token); } private: // Disallow copying and assignment. basic_signal_set(const basic_signal_set&) = delete; basic_signal_set& operator=(const basic_signal_set&) = delete; class initiate_async_wait { public: typedef Executor executor_type; explicit initiate_async_wait(basic_signal_set* self) : self_(self) { } const executor_type& get_executor() const noexcept { return self_->get_executor(); } template <typename SignalHandler> void operator()(SignalHandler&& handler) const { // If you get an error on the following line it means that your handler // does not meet the documented type requirements for a SignalHandler. ASIO_SIGNAL_HANDLER_CHECK(SignalHandler, handler) type_check; detail::non_const_lvalue<SignalHandler> handler2(handler); self_->impl_.get_service().async_wait( self_->impl_.get_implementation(), handler2.value, self_->impl_.get_executor()); } private: basic_signal_set* self_; }; detail::io_object_impl<detail::signal_set_service, Executor> impl_; }; } // namespace asio #include "asio/detail/pop_options.hpp" #endif // ASIO_BASIC_SIGNAL_SET_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/high_resolution_timer.hpp
// // high_resolution_timer.hpp // ~~~~~~~~~~~~~~~~~~~~~~~~~ // // 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) // #ifndef ASIO_HIGH_RESOLUTION_TIMER_HPP #define ASIO_HIGH_RESOLUTION_TIMER_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include "asio/basic_waitable_timer.hpp" #include "asio/detail/chrono.hpp" namespace asio { /// Typedef for a timer based on the high resolution clock. /** * This typedef uses the C++11 @c &lt;chrono&gt; standard library facility, if * available. Otherwise, it may use the Boost.Chrono library. To explicitly * utilise Boost.Chrono, use the basic_waitable_timer template directly: * @code * typedef basic_waitable_timer<boost::chrono::high_resolution_clock> timer; * @endcode */ typedef basic_waitable_timer< chrono::high_resolution_clock> high_resolution_timer; } // namespace asio #endif // ASIO_HIGH_RESOLUTION_TIMER_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/cancel_after.hpp
// // cancel_after.hpp // ~~~~~~~~~~~~~~~~ // // 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) // #ifndef ASIO_CANCEL_AFTER_HPP #define ASIO_CANCEL_AFTER_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include "asio/basic_waitable_timer.hpp" #include "asio/cancellation_type.hpp" #include "asio/detail/chrono.hpp" #include "asio/detail/type_traits.hpp" #include "asio/wait_traits.hpp" #include "asio/detail/push_options.hpp" namespace asio { /// A @ref completion_token adapter that cancels an operation after a timeout. /** * The cancel_after_t class is used to indicate that an asynchronous operation * should be cancelled if not complete before the specified duration has * elapsed. */ template <typename CompletionToken, typename Clock, typename WaitTraits = asio::wait_traits<Clock>> class cancel_after_t { public: /// Constructor. template <typename T> cancel_after_t(T&& completion_token, const typename Clock::duration& timeout, cancellation_type_t cancel_type = cancellation_type::terminal) : token_(static_cast<T&&>(completion_token)), timeout_(timeout), cancel_type_(cancel_type) { } //private: CompletionToken token_; typename Clock::duration timeout_; cancellation_type_t cancel_type_; }; /// A @ref completion_token adapter that cancels an operation after a timeout. /** * The cancel_after_timer class is used to indicate that an asynchronous * operation should be cancelled if not complete before the specified duration * has elapsed. */ template <typename CompletionToken, typename Clock, typename WaitTraits = asio::wait_traits<Clock>, typename Executor = any_io_executor> class cancel_after_timer { public: /// Constructor. template <typename T> cancel_after_timer(T&& completion_token, basic_waitable_timer<Clock, WaitTraits, Executor>& timer, const typename Clock::duration& timeout, cancellation_type_t cancel_type = cancellation_type::terminal) : token_(static_cast<T&&>(completion_token)), timer_(timer), timeout_(timeout), cancel_type_(cancel_type) { } //private: CompletionToken token_; basic_waitable_timer<Clock, WaitTraits, Executor>& timer_; typename Clock::duration timeout_; cancellation_type_t cancel_type_; }; /// A function object type that adapts a @ref completion_token to cancel an /// operation after a timeout. /** * May also be used directly as a completion token, in which case it adapts the * asynchronous operation's default completion token (or asio::deferred * if no default is available). */ template <typename Clock, typename WaitTraits = asio::wait_traits<Clock>> class partial_cancel_after { public: /// Constructor that specifies the timeout duration and cancellation type. explicit partial_cancel_after(const typename Clock::duration& timeout, cancellation_type_t cancel_type = cancellation_type::terminal) : timeout_(timeout), cancel_type_(cancel_type) { } /// Adapt a @ref completion_token to specify that the completion handler /// arguments should be combined into a single tuple argument. template <typename CompletionToken> ASIO_NODISCARD inline cancel_after_t<decay_t<CompletionToken>, Clock, WaitTraits> operator()(CompletionToken&& completion_token) const { return cancel_after_t<decay_t<CompletionToken>, Clock, WaitTraits>( static_cast<CompletionToken&&>(completion_token), timeout_, cancel_type_); } //private: typename Clock::duration timeout_; cancellation_type_t cancel_type_; }; /// A function object type that adapts a @ref completion_token to cancel an /// operation after a timeout. /** * May also be used directly as a completion token, in which case it adapts the * asynchronous operation's default completion token (or asio::deferred * if no default is available). */ template <typename Clock, typename WaitTraits = asio::wait_traits<Clock>, typename Executor = any_io_executor> class partial_cancel_after_timer { public: /// Constructor that specifies the timeout duration and cancellation type. explicit partial_cancel_after_timer( basic_waitable_timer<Clock, WaitTraits, Executor>& timer, const typename Clock::duration& timeout, cancellation_type_t cancel_type = cancellation_type::terminal) : timer_(timer), timeout_(timeout), cancel_type_(cancel_type) { } /// Adapt a @ref completion_token to specify that the completion handler /// arguments should be combined into a single tuple argument. template <typename CompletionToken> ASIO_NODISCARD inline cancel_after_timer<decay_t<CompletionToken>, Clock, WaitTraits, Executor> operator()(CompletionToken&& completion_token) const { return cancel_after_timer<decay_t<CompletionToken>, Clock, WaitTraits, Executor>( static_cast<CompletionToken&&>(completion_token), timeout_, cancel_type_); } //private: basic_waitable_timer<Clock, WaitTraits, Executor>& timer_; typename Clock::duration timeout_; cancellation_type_t cancel_type_; }; /// Create a partial completion token adapter that cancels an operation if not /// complete before the specified relative timeout has elapsed. /** * @par Thread Safety * When an asynchronous operation is used with cancel_after, a timer async_wait * operation is performed in parallel to the main operation. If this parallel * async_wait completes first, a cancellation request is emitted to cancel the * main operation. Consequently, the application must ensure that the * asynchronous operation is performed within an implicit or explicit strand. */ template <typename Rep, typename Period> ASIO_NODISCARD inline partial_cancel_after<chrono::steady_clock> cancel_after(const chrono::duration<Rep, Period>& timeout, cancellation_type_t cancel_type = cancellation_type::terminal) { return partial_cancel_after<chrono::steady_clock>(timeout, cancel_type); } /// Create a partial completion token adapter that cancels an operation if not /// complete before the specified relative timeout has elapsed. /** * @par Thread Safety * When an asynchronous operation is used with cancel_after, a timer async_wait * operation is performed in parallel to the main operation. If this parallel * async_wait completes first, a cancellation request is emitted to cancel the * main operation. Consequently, the application must ensure that the * asynchronous operation is performed within an implicit or explicit strand. */ template <typename Clock, typename WaitTraits, typename Executor, typename Rep, typename Period> ASIO_NODISCARD inline partial_cancel_after_timer<Clock, WaitTraits, Executor> cancel_after(basic_waitable_timer<Clock, WaitTraits, Executor>& timer, const chrono::duration<Rep, Period>& timeout, cancellation_type_t cancel_type = cancellation_type::terminal) { return partial_cancel_after_timer<Clock, WaitTraits, Executor>( timer, timeout, cancel_type); } /// Adapt a @ref completion_token to cancel an operation if not complete before /// the specified relative timeout has elapsed. /** * @par Thread Safety * When an asynchronous operation is used with cancel_after, a timer async_wait * operation is performed in parallel to the main operation. If this parallel * async_wait completes first, a cancellation request is emitted to cancel the * main operation. Consequently, the application must ensure that the * asynchronous operation is performed within an implicit or explicit strand. */ template <typename Rep, typename Period, typename CompletionToken> ASIO_NODISCARD inline cancel_after_t<decay_t<CompletionToken>, chrono::steady_clock> cancel_after(const chrono::duration<Rep, Period>& timeout, CompletionToken&& completion_token) { return cancel_after_t<decay_t<CompletionToken>, chrono::steady_clock>( static_cast<CompletionToken&&>(completion_token), timeout, cancellation_type::terminal); } /// Adapt a @ref completion_token to cancel an operation if not complete before /// the specified relative timeout has elapsed. /** * @par Thread Safety * When an asynchronous operation is used with cancel_after, a timer async_wait * operation is performed in parallel to the main operation. If this parallel * async_wait completes first, a cancellation request is emitted to cancel the * main operation. Consequently, the application must ensure that the * asynchronous operation is performed within an implicit or explicit strand. */ template <typename Rep, typename Period, typename CompletionToken> ASIO_NODISCARD inline cancel_after_t<decay_t<CompletionToken>, chrono::steady_clock> cancel_after(const chrono::duration<Rep, Period>& timeout, cancellation_type_t cancel_type, CompletionToken&& completion_token) { return cancel_after_t<decay_t<CompletionToken>, chrono::steady_clock>( static_cast<CompletionToken&&>(completion_token), timeout, cancel_type); } /// Adapt a @ref completion_token to cancel an operation if not complete before /// the specified relative timeout has elapsed. /** * @par Thread Safety * When an asynchronous operation is used with cancel_after, a timer async_wait * operation is performed in parallel to the main operation. If this parallel * async_wait completes first, a cancellation request is emitted to cancel the * main operation. Consequently, the application must ensure that the * asynchronous operation is performed within an implicit or explicit strand. */ template <typename Clock, typename WaitTraits, typename Executor, typename Rep, typename Period, typename CompletionToken> ASIO_NODISCARD inline cancel_after_timer<decay_t<CompletionToken>, Clock, WaitTraits, Executor> cancel_after(basic_waitable_timer<Clock, WaitTraits, Executor>& timer, const chrono::duration<Rep, Period>& timeout, CompletionToken&& completion_token) { return cancel_after_timer<decay_t<CompletionToken>, Clock, WaitTraits, Executor>( static_cast<CompletionToken&&>(completion_token), timer, timeout, cancellation_type::terminal); } /// Adapt a @ref completion_token to cancel an operation if not complete before /// the specified relative timeout has elapsed. /** * @par Thread Safety * When an asynchronous operation is used with cancel_after, a timer async_wait * operation is performed in parallel to the main operation. If this parallel * async_wait completes first, a cancellation request is emitted to cancel the * main operation. Consequently, the application must ensure that the * asynchronous operation is performed within an implicit or explicit strand. */ template <typename Clock, typename WaitTraits, typename Executor, typename Rep, typename Period, typename CompletionToken> ASIO_NODISCARD inline cancel_after_timer<decay_t<CompletionToken>, chrono::steady_clock> cancel_after(basic_waitable_timer<Clock, WaitTraits, Executor>& timer, const chrono::duration<Rep, Period>& timeout, cancellation_type_t cancel_type, CompletionToken&& completion_token) { return cancel_after_timer<decay_t<CompletionToken>, Clock, WaitTraits, Executor>( static_cast<CompletionToken&&>(completion_token), timer, timeout, cancel_type); } } // namespace asio #include "asio/detail/pop_options.hpp" #include "asio/impl/cancel_after.hpp" #endif // ASIO_CANCEL_AFTER_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/basic_streambuf_fwd.hpp
// // basic_streambuf_fwd.hpp // ~~~~~~~~~~~~~~~~~~~~~~~ // // 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) // #ifndef ASIO_BASIC_STREAMBUF_FWD_HPP #define ASIO_BASIC_STREAMBUF_FWD_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #if !defined(ASIO_NO_IOSTREAM) #include <memory> namespace asio { template <typename Allocator = std::allocator<char>> class basic_streambuf; template <typename Allocator = std::allocator<char>> class basic_streambuf_ref; } // namespace asio #endif // !defined(ASIO_NO_IOSTREAM) #endif // ASIO_BASIC_STREAMBUF_FWD_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/is_write_buffered.hpp
// // is_write_buffered.hpp // ~~~~~~~~~~~~~~~~~~~~~ // // 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) // #ifndef ASIO_IS_WRITE_BUFFERED_HPP #define ASIO_IS_WRITE_BUFFERED_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include "asio/buffered_stream_fwd.hpp" #include "asio/buffered_write_stream_fwd.hpp" #include "asio/detail/push_options.hpp" namespace asio { namespace detail { template <typename Stream> char is_write_buffered_helper(buffered_stream<Stream>* s); template <typename Stream> char is_write_buffered_helper(buffered_write_stream<Stream>* s); struct is_write_buffered_big_type { char data[10]; }; is_write_buffered_big_type is_write_buffered_helper(...); } // namespace detail /// The is_write_buffered class is a traits class that may be used to determine /// whether a stream type supports buffering of written data. template <typename Stream> class is_write_buffered { public: #if defined(GENERATING_DOCUMENTATION) /// The value member is true only if the Stream type supports buffering of /// written data. static const bool value; #else ASIO_STATIC_CONSTANT(bool, value = sizeof(detail::is_write_buffered_helper((Stream*)0)) == 1); #endif }; } // namespace asio #include "asio/detail/pop_options.hpp" #endif // ASIO_IS_WRITE_BUFFERED_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/io_context.hpp
// // io_context.hpp // ~~~~~~~~~~~~~~ // // 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) // #ifndef ASIO_IO_CONTEXT_HPP #define ASIO_IO_CONTEXT_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include <cstddef> #include <stdexcept> #include <typeinfo> #include "asio/async_result.hpp" #include "asio/detail/chrono.hpp" #include "asio/detail/concurrency_hint.hpp" #include "asio/detail/cstdint.hpp" #include "asio/detail/wrapped_handler.hpp" #include "asio/error_code.hpp" #include "asio/execution.hpp" #include "asio/execution_context.hpp" #if defined(ASIO_WINDOWS) || defined(__CYGWIN__) # include "asio/detail/winsock_init.hpp" #elif defined(__sun) || defined(__QNX__) || defined(__hpux) || defined(_AIX) \ || defined(__osf__) # include "asio/detail/signal_init.hpp" #endif #if defined(ASIO_HAS_IOCP) # include "asio/detail/win_iocp_io_context.hpp" #else # include "asio/detail/scheduler.hpp" #endif #include "asio/detail/push_options.hpp" namespace asio { namespace detail { #if defined(ASIO_HAS_IOCP) typedef win_iocp_io_context io_context_impl; class win_iocp_overlapped_ptr; #else typedef scheduler io_context_impl; #endif struct io_context_bits { static constexpr uintptr_t blocking_never = 1; static constexpr uintptr_t relationship_continuation = 2; static constexpr uintptr_t outstanding_work_tracked = 4; static constexpr uintptr_t runtime_bits = 3; }; } // namespace detail /// Provides core I/O functionality. /** * The io_context class provides the core I/O functionality for users of the * asynchronous I/O objects, including: * * @li asio::ip::tcp::socket * @li asio::ip::tcp::acceptor * @li asio::ip::udp::socket * @li asio::deadline_timer. * * The io_context class also includes facilities intended for developers of * custom asynchronous services. * * @par Thread Safety * @e Distinct @e objects: Safe.@n * @e Shared @e objects: Safe, with the specific exceptions of the restart() * and notify_fork() functions. Calling restart() while there are unfinished * run(), run_one(), run_for(), run_until(), poll() or poll_one() calls results * in undefined behaviour. The notify_fork() function should not be called * while any io_context function, or any function on an I/O object that is * associated with the io_context, is being called in another thread. * * @par Concepts: * Dispatcher. * * @par Synchronous and asynchronous operations * * Synchronous operations on I/O objects implicitly run the io_context object * for an individual operation. The io_context functions run(), run_one(), * run_for(), run_until(), poll() or poll_one() must be called for the * io_context to perform asynchronous operations on behalf of a C++ program. * Notification that an asynchronous operation has completed is delivered by * invocation of the associated handler. Handlers are invoked only by a thread * that is currently calling any overload of run(), run_one(), run_for(), * run_until(), poll() or poll_one() for the io_context. * * @par Effect of exceptions thrown from handlers * * If an exception is thrown from a handler, the exception is allowed to * propagate through the throwing thread's invocation of run(), run_one(), * run_for(), run_until(), poll() or poll_one(). No other threads that are * calling any of these functions are affected. It is then the responsibility * of the application to catch the exception. * * After the exception has been caught, the run(), run_one(), run_for(), * run_until(), poll() or poll_one() call may be restarted @em without the need * for an intervening call to restart(). This allows the thread to rejoin the * io_context object's thread pool without impacting any other threads in the * pool. * * For example: * * @code * asio::io_context io_context; * ... * for (;;) * { * try * { * io_context.run(); * break; // run() exited normally * } * catch (my_exception& e) * { * // Deal with exception as appropriate. * } * } * @endcode * * @par Submitting arbitrary tasks to the io_context * * To submit functions to the io_context, use the @ref asio::dispatch, * @ref asio::post or @ref asio::defer free functions. * * For example: * * @code void my_task() * { * ... * } * * ... * * asio::io_context io_context; * * // Submit a function to the io_context. * asio::post(io_context, my_task); * * // Submit a lambda object to the io_context. * asio::post(io_context, * []() * { * ... * }); * * // Run the io_context until it runs out of work. * io_context.run(); @endcode * * @par Stopping the io_context from running out of work * * Some applications may need to prevent an io_context object's run() call from * returning when there is no more work to do. For example, the io_context may * be being run in a background thread that is launched prior to the * application's asynchronous operations. The run() call may be kept running by * using the @ref make_work_guard function to create an object of type * asio::executor_work_guard<io_context::executor_type>: * * @code asio::io_context io_context; * asio::executor_work_guard<asio::io_context::executor_type> * = asio::make_work_guard(io_context); * ... @endcode * * To effect a shutdown, the application will then need to call the io_context * object's stop() member function. This will cause the io_context run() call * to return as soon as possible, abandoning unfinished operations and without * permitting ready handlers to be dispatched. * * Alternatively, if the application requires that all operations and handlers * be allowed to finish normally, the work object may be explicitly reset. * * @code asio::io_context io_context; * asio::executor_work_guard<asio::io_context::executor_type> * = asio::make_work_guard(io_context); * ... * work.reset(); // Allow run() to exit. @endcode */ class io_context : public execution_context { private: typedef detail::io_context_impl impl_type; #if defined(ASIO_HAS_IOCP) friend class detail::win_iocp_overlapped_ptr; #endif #if !defined(ASIO_NO_DEPRECATED) struct initiate_dispatch; struct initiate_post; #endif // !defined(ASIO_NO_DEPRECATED) public: template <typename Allocator, uintptr_t Bits> class basic_executor_type; template <typename Allocator, uintptr_t Bits> friend class basic_executor_type; /// Executor used to submit functions to an io_context. typedef basic_executor_type<std::allocator<void>, 0> executor_type; #if !defined(ASIO_NO_DEPRECATED) class work; friend class work; #endif // !defined(ASIO_NO_DEPRECATED) class service; #if !defined(ASIO_NO_EXTENSIONS) \ && !defined(ASIO_NO_TS_EXECUTORS) class strand; #endif // !defined(ASIO_NO_EXTENSIONS) // && !defined(ASIO_NO_TS_EXECUTORS) /// The type used to count the number of handlers executed by the context. typedef std::size_t count_type; /// Constructor. ASIO_DECL io_context(); /// Constructor. /** * Construct with a hint about the required level of concurrency. * * @param concurrency_hint A suggestion to the implementation on how many * threads it should allow to run simultaneously. */ ASIO_DECL explicit io_context(int concurrency_hint); /// Destructor. /** * On destruction, the io_context performs the following sequence of * operations: * * @li For each service object @c svc in the io_context set, in reverse order * of the beginning of service object lifetime, performs * @c svc->shutdown(). * * @li Uninvoked handler objects that were scheduled for deferred invocation * on the io_context, or any associated strand, are destroyed. * * @li For each service object @c svc in the io_context set, in reverse order * of the beginning of service object lifetime, performs * <tt>delete static_cast<io_context::service*>(svc)</tt>. * * @note The destruction sequence described above permits programs to * simplify their resource management by using @c shared_ptr<>. Where an * object's lifetime is tied to the lifetime of a connection (or some other * sequence of asynchronous operations), a @c shared_ptr to the object would * be bound into the handlers for all asynchronous operations associated with * it. This works as follows: * * @li When a single connection ends, all associated asynchronous operations * complete. The corresponding handler objects are destroyed, and all * @c shared_ptr references to the objects are destroyed. * * @li To shut down the whole program, the io_context function stop() is * called to terminate any run() calls as soon as possible. The io_context * destructor defined above destroys all handlers, causing all @c shared_ptr * references to all connection objects to be destroyed. */ ASIO_DECL ~io_context(); /// Obtains the executor associated with the io_context. executor_type get_executor() noexcept; /// Run the io_context object's event processing loop. /** * The run() function blocks until all work has finished and there are no * more handlers to be dispatched, or until the io_context has been stopped. * * Multiple threads may call the run() function to set up a pool of threads * from which the io_context may execute handlers. All threads that are * waiting in the pool are equivalent and the io_context may choose any one * of them to invoke a handler. * * A normal exit from the run() function implies that the io_context object * is stopped (the stopped() function returns @c true). Subsequent calls to * run(), run_one(), poll() or poll_one() will return immediately unless there * is a prior call to restart(). * * @return The number of handlers that were executed. * * @note Calling the run() function from a thread that is currently calling * one of run(), run_one(), run_for(), run_until(), poll() or poll_one() on * the same io_context object may introduce the potential for deadlock. It is * the caller's reponsibility to avoid this. * * The poll() function may also be used to dispatch ready handlers, but * without blocking. */ ASIO_DECL count_type run(); #if !defined(ASIO_NO_DEPRECATED) /// (Deprecated: Use non-error_code overload.) Run the io_context object's /// event processing loop. /** * The run() function blocks until all work has finished and there are no * more handlers to be dispatched, or until the io_context has been stopped. * * Multiple threads may call the run() function to set up a pool of threads * from which the io_context may execute handlers. All threads that are * waiting in the pool are equivalent and the io_context may choose any one * of them to invoke a handler. * * A normal exit from the run() function implies that the io_context object * is stopped (the stopped() function returns @c true). Subsequent calls to * run(), run_one(), poll() or poll_one() will return immediately unless there * is a prior call to restart(). * * @param ec Set to indicate what error occurred, if any. * * @return The number of handlers that were executed. * * @note Calling the run() function from a thread that is currently calling * one of run(), run_one(), run_for(), run_until(), poll() or poll_one() on * the same io_context object may introduce the potential for deadlock. It is * the caller's reponsibility to avoid this. * * The poll() function may also be used to dispatch ready handlers, but * without blocking. */ ASIO_DECL count_type run(asio::error_code& ec); #endif // !defined(ASIO_NO_DEPRECATED) /// Run the io_context object's event processing loop for a specified /// duration. /** * The run_for() function blocks until all work has finished and there are no * more handlers to be dispatched, until the io_context has been stopped, or * until the specified duration has elapsed. * * @param rel_time The duration for which the call may block. * * @return The number of handlers that were executed. */ template <typename Rep, typename Period> std::size_t run_for(const chrono::duration<Rep, Period>& rel_time); /// Run the io_context object's event processing loop until a specified time. /** * The run_until() function blocks until all work has finished and there are * no more handlers to be dispatched, until the io_context has been stopped, * or until the specified time has been reached. * * @param abs_time The time point until which the call may block. * * @return The number of handlers that were executed. */ template <typename Clock, typename Duration> std::size_t run_until(const chrono::time_point<Clock, Duration>& abs_time); /// Run the io_context object's event processing loop to execute at most one /// handler. /** * The run_one() function blocks until one handler has been dispatched, or * until the io_context has been stopped. * * @return The number of handlers that were executed. A zero return value * implies that the io_context object is stopped (the stopped() function * returns @c true). Subsequent calls to run(), run_one(), poll() or * poll_one() will return immediately unless there is a prior call to * restart(). * * @note Calling the run_one() function from a thread that is currently * calling one of run(), run_one(), run_for(), run_until(), poll() or * poll_one() on the same io_context object may introduce the potential for * deadlock. It is the caller's reponsibility to avoid this. */ ASIO_DECL count_type run_one(); #if !defined(ASIO_NO_DEPRECATED) /// (Deprecated: Use non-error_code overload.) Run the io_context object's /// event processing loop to execute at most one handler. /** * The run_one() function blocks until one handler has been dispatched, or * until the io_context has been stopped. * * @return The number of handlers that were executed. A zero return value * implies that the io_context object is stopped (the stopped() function * returns @c true). Subsequent calls to run(), run_one(), poll() or * poll_one() will return immediately unless there is a prior call to * restart(). * * @return The number of handlers that were executed. * * @note Calling the run_one() function from a thread that is currently * calling one of run(), run_one(), run_for(), run_until(), poll() or * poll_one() on the same io_context object may introduce the potential for * deadlock. It is the caller's reponsibility to avoid this. */ ASIO_DECL count_type run_one(asio::error_code& ec); #endif // !defined(ASIO_NO_DEPRECATED) /// Run the io_context object's event processing loop for a specified duration /// to execute at most one handler. /** * The run_one_for() function blocks until one handler has been dispatched, * until the io_context has been stopped, or until the specified duration has * elapsed. * * @param rel_time The duration for which the call may block. * * @return The number of handlers that were executed. */ template <typename Rep, typename Period> std::size_t run_one_for(const chrono::duration<Rep, Period>& rel_time); /// Run the io_context object's event processing loop until a specified time /// to execute at most one handler. /** * The run_one_until() function blocks until one handler has been dispatched, * until the io_context has been stopped, or until the specified time has * been reached. * * @param abs_time The time point until which the call may block. * * @return The number of handlers that were executed. */ template <typename Clock, typename Duration> std::size_t run_one_until( const chrono::time_point<Clock, Duration>& abs_time); /// Run the io_context object's event processing loop to execute ready /// handlers. /** * The poll() function runs handlers that are ready to run, without blocking, * until the io_context has been stopped or there are no more ready handlers. * * @return The number of handlers that were executed. */ ASIO_DECL count_type poll(); #if !defined(ASIO_NO_DEPRECATED) /// (Deprecated: Use non-error_code overload.) Run the io_context object's /// event processing loop to execute ready handlers. /** * The poll() function runs handlers that are ready to run, without blocking, * until the io_context has been stopped or there are no more ready handlers. * * @param ec Set to indicate what error occurred, if any. * * @return The number of handlers that were executed. */ ASIO_DECL count_type poll(asio::error_code& ec); #endif // !defined(ASIO_NO_DEPRECATED) /// Run the io_context object's event processing loop to execute one ready /// handler. /** * The poll_one() function runs at most one handler that is ready to run, * without blocking. * * @return The number of handlers that were executed. */ ASIO_DECL count_type poll_one(); #if !defined(ASIO_NO_DEPRECATED) /// (Deprecated: Use non-error_code overload.) Run the io_context object's /// event processing loop to execute one ready handler. /** * The poll_one() function runs at most one handler that is ready to run, * without blocking. * * @param ec Set to indicate what error occurred, if any. * * @return The number of handlers that were executed. */ ASIO_DECL count_type poll_one(asio::error_code& ec); #endif // !defined(ASIO_NO_DEPRECATED) /// Stop the io_context object's event processing loop. /** * This function does not block, but instead simply signals the io_context to * stop. All invocations of its run() or run_one() member functions should * return as soon as possible. Subsequent calls to run(), run_one(), poll() * or poll_one() will return immediately until restart() is called. */ ASIO_DECL void stop(); /// Determine whether the io_context object has been stopped. /** * This function is used to determine whether an io_context object has been * stopped, either through an explicit call to stop(), or due to running out * of work. When an io_context object is stopped, calls to run(), run_one(), * poll() or poll_one() will return immediately without invoking any * handlers. * * @return @c true if the io_context object is stopped, otherwise @c false. */ ASIO_DECL bool stopped() const; /// Restart the io_context in preparation for a subsequent run() invocation. /** * This function must be called prior to any second or later set of * invocations of the run(), run_one(), poll() or poll_one() functions when a * previous invocation of these functions returned due to the io_context * being stopped or running out of work. After a call to restart(), the * io_context object's stopped() function will return @c false. * * This function must not be called while there are any unfinished calls to * the run(), run_one(), poll() or poll_one() functions. */ ASIO_DECL void restart(); #if !defined(ASIO_NO_DEPRECATED) /// (Deprecated: Use restart().) Reset the io_context in preparation for a /// subsequent run() invocation. /** * This function must be called prior to any second or later set of * invocations of the run(), run_one(), poll() or poll_one() functions when a * previous invocation of these functions returned due to the io_context * being stopped or running out of work. After a call to restart(), the * io_context object's stopped() function will return @c false. * * This function must not be called while there are any unfinished calls to * the run(), run_one(), poll() or poll_one() functions. */ void reset(); /// (Deprecated: Use asio::dispatch().) Request the io_context to /// invoke the given handler. /** * This function is used to ask the io_context to execute the given handler. * * The io_context guarantees that the handler will only be called in a thread * in which the run(), run_one(), poll() or poll_one() member functions is * currently being invoked. The handler may be executed inside this function * if the guarantee can be met. * * @param handler The handler to be called. The io_context will make * a copy of the handler object as required. The function signature of the * handler must be: @code void handler(); @endcode * * @note This function throws an exception only if: * * @li the handler's associated allocator; or * * @li the handler's copy constructor * * throws an exception. */ template <typename LegacyCompletionHandler> auto dispatch(LegacyCompletionHandler&& handler) -> decltype( async_initiate<LegacyCompletionHandler, void ()>( declval<initiate_dispatch>(), handler, this)); /// (Deprecated: Use asio::post().) Request the io_context to invoke /// the given handler and return immediately. /** * This function is used to ask the io_context to execute the given handler, * but without allowing the io_context to call the handler from inside this * function. * * The io_context guarantees that the handler will only be called in a thread * in which the run(), run_one(), poll() or poll_one() member functions is * currently being invoked. * * @param handler The handler to be called. The io_context will make * a copy of the handler object as required. The function signature of the * handler must be: @code void handler(); @endcode * * @note This function throws an exception only if: * * @li the handler's associated allocator; or * * @li the handler's copy constructor * * throws an exception. */ template <typename LegacyCompletionHandler> auto post(LegacyCompletionHandler&& handler) -> decltype( async_initiate<LegacyCompletionHandler, void ()>( declval<initiate_post>(), handler, this)); /// (Deprecated: Use asio::bind_executor().) Create a new handler that /// automatically dispatches the wrapped handler on the io_context. /** * This function is used to create a new handler function object that, when * invoked, will automatically pass the wrapped handler to the io_context * object's dispatch function. * * @param handler The handler to be wrapped. The io_context will make a copy * of the handler object as required. The function signature of the handler * must be: @code void handler(A1 a1, ... An an); @endcode * * @return A function object that, when invoked, passes the wrapped handler to * the io_context object's dispatch function. Given a function object with the * signature: * @code R f(A1 a1, ... An an); @endcode * If this function object is passed to the wrap function like so: * @code io_context.wrap(f); @endcode * then the return value is a function object with the signature * @code void g(A1 a1, ... An an); @endcode * that, when invoked, executes code equivalent to: * @code io_context.dispatch(boost::bind(f, a1, ... an)); @endcode */ template <typename Handler> #if defined(GENERATING_DOCUMENTATION) unspecified #else detail::wrapped_handler<io_context&, Handler> #endif wrap(Handler handler); #endif // !defined(ASIO_NO_DEPRECATED) private: io_context(const io_context&) = delete; io_context& operator=(const io_context&) = delete; // Helper function to add the implementation. ASIO_DECL impl_type& add_impl(impl_type* impl); // Backwards compatible overload for use with services derived from // io_context::service. template <typename Service> friend Service& use_service(io_context& ioc); #if defined(ASIO_WINDOWS) || defined(__CYGWIN__) detail::winsock_init<> init_; #elif defined(__sun) || defined(__QNX__) || defined(__hpux) || defined(_AIX) \ || defined(__osf__) detail::signal_init<> init_; #endif // The implementation. impl_type& impl_; }; /// Executor implementation type used to submit functions to an io_context. template <typename Allocator, uintptr_t Bits> class io_context::basic_executor_type : detail::io_context_bits, Allocator { public: /// Copy constructor. basic_executor_type(const basic_executor_type& other) noexcept : Allocator(static_cast<const Allocator&>(other)), target_(other.target_) { if (Bits & outstanding_work_tracked) if (context_ptr()) context_ptr()->impl_.work_started(); } /// Move constructor. basic_executor_type(basic_executor_type&& other) noexcept : Allocator(static_cast<Allocator&&>(other)), target_(other.target_) { if (Bits & outstanding_work_tracked) other.target_ = 0; } /// Destructor. ~basic_executor_type() noexcept { if (Bits & outstanding_work_tracked) if (context_ptr()) context_ptr()->impl_.work_finished(); } /// Assignment operator. basic_executor_type& operator=(const basic_executor_type& other) noexcept; /// Move assignment operator. basic_executor_type& operator=(basic_executor_type&& other) noexcept; #if !defined(GENERATING_DOCUMENTATION) private: friend struct asio_require_fn::impl; friend struct asio_prefer_fn::impl; #endif // !defined(GENERATING_DOCUMENTATION) /// Obtain an executor with the @c blocking.possibly property. /** * Do not call this function directly. It is intended for use with the * asio::require customisation point. * * For example: * @code auto ex1 = my_io_context.get_executor(); * auto ex2 = asio::require(ex1, * asio::execution::blocking.possibly); @endcode */ constexpr basic_executor_type require(execution::blocking_t::possibly_t) const { return basic_executor_type(context_ptr(), *this, bits() & ~blocking_never); } /// Obtain an executor with the @c blocking.never property. /** * Do not call this function directly. It is intended for use with the * asio::require customisation point. * * For example: * @code auto ex1 = my_io_context.get_executor(); * auto ex2 = asio::require(ex1, * asio::execution::blocking.never); @endcode */ constexpr basic_executor_type require(execution::blocking_t::never_t) const { return basic_executor_type(context_ptr(), *this, bits() | blocking_never); } /// Obtain an executor with the @c relationship.fork property. /** * Do not call this function directly. It is intended for use with the * asio::require customisation point. * * For example: * @code auto ex1 = my_io_context.get_executor(); * auto ex2 = asio::require(ex1, * asio::execution::relationship.fork); @endcode */ constexpr basic_executor_type require(execution::relationship_t::fork_t) const { return basic_executor_type(context_ptr(), *this, bits() & ~relationship_continuation); } /// Obtain an executor with the @c relationship.continuation property. /** * Do not call this function directly. It is intended for use with the * asio::require customisation point. * * For example: * @code auto ex1 = my_io_context.get_executor(); * auto ex2 = asio::require(ex1, * asio::execution::relationship.continuation); @endcode */ constexpr basic_executor_type require( execution::relationship_t::continuation_t) const { return basic_executor_type(context_ptr(), *this, bits() | relationship_continuation); } /// Obtain an executor with the @c outstanding_work.tracked property. /** * Do not call this function directly. It is intended for use with the * asio::require customisation point. * * For example: * @code auto ex1 = my_io_context.get_executor(); * auto ex2 = asio::require(ex1, * asio::execution::outstanding_work.tracked); @endcode */ constexpr basic_executor_type<Allocator, ASIO_UNSPECIFIED(Bits | outstanding_work_tracked)> require(execution::outstanding_work_t::tracked_t) const { return basic_executor_type<Allocator, Bits | outstanding_work_tracked>( context_ptr(), *this, bits()); } /// Obtain an executor with the @c outstanding_work.untracked property. /** * Do not call this function directly. It is intended for use with the * asio::require customisation point. * * For example: * @code auto ex1 = my_io_context.get_executor(); * auto ex2 = asio::require(ex1, * asio::execution::outstanding_work.untracked); @endcode */ constexpr basic_executor_type<Allocator, ASIO_UNSPECIFIED(Bits & ~outstanding_work_tracked)> require(execution::outstanding_work_t::untracked_t) const { return basic_executor_type<Allocator, Bits & ~outstanding_work_tracked>( context_ptr(), *this, bits()); } /// Obtain an executor with the specified @c allocator property. /** * Do not call this function directly. It is intended for use with the * asio::require customisation point. * * For example: * @code auto ex1 = my_io_context.get_executor(); * auto ex2 = asio::require(ex1, * asio::execution::allocator(my_allocator)); @endcode */ template <typename OtherAllocator> constexpr basic_executor_type<OtherAllocator, Bits> require(execution::allocator_t<OtherAllocator> a) const { return basic_executor_type<OtherAllocator, Bits>( context_ptr(), a.value(), bits()); } /// Obtain an executor with the default @c allocator property. /** * Do not call this function directly. It is intended for use with the * asio::require customisation point. * * For example: * @code auto ex1 = my_io_context.get_executor(); * auto ex2 = asio::require(ex1, * asio::execution::allocator); @endcode */ constexpr basic_executor_type<std::allocator<void>, Bits> require(execution::allocator_t<void>) const { return basic_executor_type<std::allocator<void>, Bits>( context_ptr(), std::allocator<void>(), bits()); } #if !defined(GENERATING_DOCUMENTATION) private: friend struct asio_query_fn::impl; friend struct asio::execution::detail::mapping_t<0>; friend struct asio::execution::detail::outstanding_work_t<0>; #endif // !defined(GENERATING_DOCUMENTATION) /// Query the current value of the @c mapping property. /** * Do not call this function directly. It is intended for use with the * asio::query customisation point. * * For example: * @code auto ex = my_io_context.get_executor(); * if (asio::query(ex, asio::execution::mapping) * == asio::execution::mapping.thread) * ... @endcode */ static constexpr execution::mapping_t query(execution::mapping_t) noexcept { return execution::mapping.thread; } /// Query the current value of the @c context property. /** * Do not call this function directly. It is intended for use with the * asio::query customisation point. * * For example: * @code auto ex = my_io_context.get_executor(); * asio::io_context& ctx = asio::query( * ex, asio::execution::context); @endcode */ io_context& query(execution::context_t) const noexcept { return *context_ptr(); } /// Query the current value of the @c blocking property. /** * Do not call this function directly. It is intended for use with the * asio::query customisation point. * * For example: * @code auto ex = my_io_context.get_executor(); * if (asio::query(ex, asio::execution::blocking) * == asio::execution::blocking.always) * ... @endcode */ constexpr execution::blocking_t query(execution::blocking_t) const noexcept { return (bits() & blocking_never) ? execution::blocking_t(execution::blocking.never) : execution::blocking_t(execution::blocking.possibly); } /// Query the current value of the @c relationship property. /** * Do not call this function directly. It is intended for use with the * asio::query customisation point. * * For example: * @code auto ex = my_io_context.get_executor(); * if (asio::query(ex, asio::execution::relationship) * == asio::execution::relationship.continuation) * ... @endcode */ constexpr execution::relationship_t query( execution::relationship_t) const noexcept { return (bits() & relationship_continuation) ? execution::relationship_t(execution::relationship.continuation) : execution::relationship_t(execution::relationship.fork); } /// Query the current value of the @c outstanding_work property. /** * Do not call this function directly. It is intended for use with the * asio::query customisation point. * * For example: * @code auto ex = my_io_context.get_executor(); * if (asio::query(ex, asio::execution::outstanding_work) * == asio::execution::outstanding_work.tracked) * ... @endcode */ static constexpr execution::outstanding_work_t query( execution::outstanding_work_t) noexcept { return (Bits & outstanding_work_tracked) ? execution::outstanding_work_t(execution::outstanding_work.tracked) : execution::outstanding_work_t(execution::outstanding_work.untracked); } /// Query the current value of the @c allocator property. /** * Do not call this function directly. It is intended for use with the * asio::query customisation point. * * For example: * @code auto ex = my_io_context.get_executor(); * auto alloc = asio::query(ex, * asio::execution::allocator); @endcode */ template <typename OtherAllocator> constexpr Allocator query( execution::allocator_t<OtherAllocator>) const noexcept { return static_cast<const Allocator&>(*this); } /// Query the current value of the @c allocator property. /** * Do not call this function directly. It is intended for use with the * asio::query customisation point. * * For example: * @code auto ex = my_io_context.get_executor(); * auto alloc = asio::query(ex, * asio::execution::allocator); @endcode */ constexpr Allocator query(execution::allocator_t<void>) const noexcept { return static_cast<const Allocator&>(*this); } public: /// Determine whether the io_context is running in the current thread. /** * @return @c true if the current thread is running the io_context. Otherwise * returns @c false. */ bool running_in_this_thread() const noexcept; /// Compare two executors for equality. /** * Two executors are equal if they refer to the same underlying io_context. */ friend bool operator==(const basic_executor_type& a, const basic_executor_type& b) noexcept { return a.target_ == b.target_ && static_cast<const Allocator&>(a) == static_cast<const Allocator&>(b); } /// Compare two executors for inequality. /** * Two executors are equal if they refer to the same underlying io_context. */ friend bool operator!=(const basic_executor_type& a, const basic_executor_type& b) noexcept { return a.target_ != b.target_ || static_cast<const Allocator&>(a) != static_cast<const Allocator&>(b); } /// Execution function. template <typename Function> void execute(Function&& f) const; #if !defined(ASIO_NO_TS_EXECUTORS) public: /// Obtain the underlying execution context. io_context& context() const noexcept; /// Inform the io_context that it has some outstanding work to do. /** * This function is used to inform the io_context that some work has begun. * This ensures that the io_context's run() and run_one() functions do not * exit while the work is underway. */ void on_work_started() const noexcept; /// Inform the io_context that some work is no longer outstanding. /** * This function is used to inform the io_context that some work has * finished. Once the count of unfinished work reaches zero, the io_context * is stopped and the run() and run_one() functions may exit. */ void on_work_finished() const noexcept; /// Request the io_context to invoke the given function object. /** * This function is used to ask the io_context to execute the given function * object. If the current thread is running the io_context, @c dispatch() * executes the function before returning. Otherwise, the function will be * scheduled to run on the io_context. * * @param f The function object to be called. The executor will make a copy * of the handler object as required. The function signature of the function * object must be: @code void function(); @endcode * * @param a An allocator that may be used by the executor to allocate the * internal storage needed for function invocation. */ template <typename Function, typename OtherAllocator> void dispatch(Function&& f, const OtherAllocator& a) const; /// Request the io_context to invoke the given function object. /** * This function is used to ask the io_context to execute the given function * object. The function object will never be executed inside @c post(). * Instead, it will be scheduled to run on the io_context. * * @param f The function object to be called. The executor will make a copy * of the handler object as required. The function signature of the function * object must be: @code void function(); @endcode * * @param a An allocator that may be used by the executor to allocate the * internal storage needed for function invocation. */ template <typename Function, typename OtherAllocator> void post(Function&& f, const OtherAllocator& a) const; /// Request the io_context to invoke the given function object. /** * This function is used to ask the io_context to execute the given function * object. The function object will never be executed inside @c defer(). * Instead, it will be scheduled to run on the io_context. * * If the current thread belongs to the io_context, @c defer() will delay * scheduling the function object until the current thread returns control to * the pool. * * @param f The function object to be called. The executor will make a copy * of the handler object as required. The function signature of the function * object must be: @code void function(); @endcode * * @param a An allocator that may be used by the executor to allocate the * internal storage needed for function invocation. */ template <typename Function, typename OtherAllocator> void defer(Function&& f, const OtherAllocator& a) const; #endif // !defined(ASIO_NO_TS_EXECUTORS) private: friend class io_context; template <typename, uintptr_t> friend class basic_executor_type; // Constructor used by io_context::get_executor(). explicit basic_executor_type(io_context& i) noexcept : Allocator(), target_(reinterpret_cast<uintptr_t>(&i)) { if (Bits & outstanding_work_tracked) context_ptr()->impl_.work_started(); } // Constructor used by require(). basic_executor_type(io_context* i, const Allocator& a, uintptr_t bits) noexcept : Allocator(a), target_(reinterpret_cast<uintptr_t>(i) | bits) { if (Bits & outstanding_work_tracked) if (context_ptr()) context_ptr()->impl_.work_started(); } io_context* context_ptr() const noexcept { return reinterpret_cast<io_context*>(target_ & ~runtime_bits); } uintptr_t bits() const noexcept { return target_ & runtime_bits; } // The underlying io_context and runtime bits. uintptr_t target_; }; #if !defined(ASIO_NO_DEPRECATED) /// (Deprecated: Use executor_work_guard.) Class to inform the io_context when /// it has work to do. /** * The work class is used to inform the io_context when work starts and * finishes. This ensures that the io_context object's run() function will not * exit while work is underway, and that it does exit when there is no * unfinished work remaining. * * The work class is copy-constructible so that it may be used as a data member * in a handler class. It is not assignable. */ class io_context::work { public: /// Constructor notifies the io_context that work is starting. /** * The constructor is used to inform the io_context that some work has begun. * This ensures that the io_context object's run() function will not exit * while the work is underway. */ explicit work(asio::io_context& io_context); /// Copy constructor notifies the io_context that work is starting. /** * The constructor is used to inform the io_context that some work has begun. * This ensures that the io_context object's run() function will not exit * while the work is underway. */ work(const work& other); /// Destructor notifies the io_context that the work is complete. /** * The destructor is used to inform the io_context that some work has * finished. Once the count of unfinished work reaches zero, the io_context * object's run() function is permitted to exit. */ ~work(); /// Get the io_context associated with the work. asio::io_context& get_io_context(); private: // Prevent assignment. void operator=(const work& other); // The io_context implementation. detail::io_context_impl& io_context_impl_; }; #endif // !defined(ASIO_NO_DEPRECATED) /// Base class for all io_context services. class io_context::service : public execution_context::service { public: /// Get the io_context object that owns the service. asio::io_context& get_io_context(); private: /// Destroy all user-defined handler objects owned by the service. ASIO_DECL virtual void shutdown(); #if !defined(ASIO_NO_DEPRECATED) /// (Deprecated: Use shutdown().) Destroy all user-defined handler objects /// owned by the service. ASIO_DECL virtual void shutdown_service(); #endif // !defined(ASIO_NO_DEPRECATED) /// Handle notification of a fork-related event to perform any necessary /// housekeeping. /** * This function is not a pure virtual so that services only have to * implement it if necessary. The default implementation does nothing. */ ASIO_DECL virtual void notify_fork( execution_context::fork_event event); #if !defined(ASIO_NO_DEPRECATED) /// (Deprecated: Use notify_fork().) Handle notification of a fork-related /// event to perform any necessary housekeeping. /** * This function is not a pure virtual so that services only have to * implement it if necessary. The default implementation does nothing. */ ASIO_DECL virtual void fork_service( execution_context::fork_event event); #endif // !defined(ASIO_NO_DEPRECATED) protected: /// Constructor. /** * @param owner The io_context object that owns the service. */ ASIO_DECL service(asio::io_context& owner); /// Destructor. ASIO_DECL virtual ~service(); }; namespace detail { // Special service base class to keep classes header-file only. template <typename Type> class service_base : public asio::io_context::service { public: static asio::detail::service_id<Type> id; // Constructor. service_base(asio::io_context& io_context) : asio::io_context::service(io_context) { } }; template <typename Type> asio::detail::service_id<Type> service_base<Type>::id; } // namespace detail #if !defined(GENERATING_DOCUMENTATION) namespace traits { #if !defined(ASIO_HAS_DEDUCED_EQUALITY_COMPARABLE_TRAIT) template <typename Allocator, uintptr_t Bits> struct equality_comparable< asio::io_context::basic_executor_type<Allocator, Bits> > { static constexpr bool is_valid = true; static constexpr bool is_noexcept = true; }; #endif // !defined(ASIO_HAS_DEDUCED_EQUALITY_COMPARABLE_TRAIT) #if !defined(ASIO_HAS_DEDUCED_EXECUTE_MEMBER_TRAIT) template <typename Allocator, uintptr_t Bits, typename Function> struct execute_member< asio::io_context::basic_executor_type<Allocator, Bits>, Function > { static constexpr bool is_valid = true; static constexpr bool is_noexcept = false; typedef void result_type; }; #endif // !defined(ASIO_HAS_DEDUCED_EXECUTE_MEMBER_TRAIT) #if !defined(ASIO_HAS_DEDUCED_REQUIRE_MEMBER_TRAIT) template <typename Allocator, uintptr_t Bits> struct require_member< asio::io_context::basic_executor_type<Allocator, Bits>, asio::execution::blocking_t::possibly_t > { static constexpr bool is_valid = true; static constexpr bool is_noexcept = false; typedef asio::io_context::basic_executor_type< Allocator, Bits> result_type; }; template <typename Allocator, uintptr_t Bits> struct require_member< asio::io_context::basic_executor_type<Allocator, Bits>, asio::execution::blocking_t::never_t > { static constexpr bool is_valid = true; static constexpr bool is_noexcept = false; typedef asio::io_context::basic_executor_type< Allocator, Bits> result_type; }; template <typename Allocator, uintptr_t Bits> struct require_member< asio::io_context::basic_executor_type<Allocator, Bits>, asio::execution::relationship_t::fork_t > { static constexpr bool is_valid = true; static constexpr bool is_noexcept = false; typedef asio::io_context::basic_executor_type< Allocator, Bits> result_type; }; template <typename Allocator, uintptr_t Bits> struct require_member< asio::io_context::basic_executor_type<Allocator, Bits>, asio::execution::relationship_t::continuation_t > { static constexpr bool is_valid = true; static constexpr bool is_noexcept = false; typedef asio::io_context::basic_executor_type< Allocator, Bits> result_type; }; template <typename Allocator, uintptr_t Bits> struct require_member< asio::io_context::basic_executor_type<Allocator, Bits>, asio::execution::outstanding_work_t::tracked_t > : asio::detail::io_context_bits { static constexpr bool is_valid = true; static constexpr bool is_noexcept = false; typedef asio::io_context::basic_executor_type< Allocator, Bits | outstanding_work_tracked> result_type; }; template <typename Allocator, uintptr_t Bits> struct require_member< asio::io_context::basic_executor_type<Allocator, Bits>, asio::execution::outstanding_work_t::untracked_t > : asio::detail::io_context_bits { static constexpr bool is_valid = true; static constexpr bool is_noexcept = false; typedef asio::io_context::basic_executor_type< Allocator, Bits & ~outstanding_work_tracked> result_type; }; template <typename Allocator, uintptr_t Bits> struct require_member< asio::io_context::basic_executor_type<Allocator, Bits>, asio::execution::allocator_t<void> > { static constexpr bool is_valid = true; static constexpr bool is_noexcept = false; typedef asio::io_context::basic_executor_type< std::allocator<void>, Bits> result_type; }; template <uintptr_t Bits, typename Allocator, typename OtherAllocator> struct require_member< asio::io_context::basic_executor_type<Allocator, Bits>, asio::execution::allocator_t<OtherAllocator> > { static constexpr bool is_valid = true; static constexpr bool is_noexcept = false; typedef asio::io_context::basic_executor_type< OtherAllocator, Bits> result_type; }; #endif // !defined(ASIO_HAS_DEDUCED_REQUIRE_MEMBER_TRAIT) #if !defined(ASIO_HAS_DEDUCED_QUERY_STATIC_CONSTEXPR_MEMBER_TRAIT) template <typename Allocator, uintptr_t Bits, typename Property> struct query_static_constexpr_member< asio::io_context::basic_executor_type<Allocator, Bits>, Property, typename asio::enable_if< asio::is_convertible< Property, asio::execution::outstanding_work_t >::value >::type > : asio::detail::io_context_bits { static constexpr bool is_valid = true; static constexpr bool is_noexcept = true; typedef asio::execution::outstanding_work_t result_type; static constexpr result_type value() noexcept { return (Bits & outstanding_work_tracked) ? execution::outstanding_work_t(execution::outstanding_work.tracked) : execution::outstanding_work_t(execution::outstanding_work.untracked); } }; template <typename Allocator, uintptr_t Bits, typename Property> struct query_static_constexpr_member< asio::io_context::basic_executor_type<Allocator, Bits>, Property, typename asio::enable_if< asio::is_convertible< Property, asio::execution::mapping_t >::value >::type > { static constexpr bool is_valid = true; static constexpr bool is_noexcept = true; typedef asio::execution::mapping_t::thread_t result_type; static constexpr result_type value() noexcept { return result_type(); } }; #endif // !defined(ASIO_HAS_DEDUCED_QUERY_STATIC_CONSTEXPR_MEMBER_TRAIT) #if !defined(ASIO_HAS_DEDUCED_QUERY_MEMBER_TRAIT) template <typename Allocator, uintptr_t Bits, typename Property> struct query_member< asio::io_context::basic_executor_type<Allocator, Bits>, Property, typename asio::enable_if< asio::is_convertible< Property, asio::execution::blocking_t >::value >::type > { static constexpr bool is_valid = true; static constexpr bool is_noexcept = true; typedef asio::execution::blocking_t result_type; }; template <typename Allocator, uintptr_t Bits, typename Property> struct query_member< asio::io_context::basic_executor_type<Allocator, Bits>, Property, typename asio::enable_if< asio::is_convertible< Property, asio::execution::relationship_t >::value >::type > { static constexpr bool is_valid = true; static constexpr bool is_noexcept = true; typedef asio::execution::relationship_t result_type; }; template <typename Allocator, uintptr_t Bits> struct query_member< asio::io_context::basic_executor_type<Allocator, Bits>, asio::execution::context_t > { static constexpr bool is_valid = true; static constexpr bool is_noexcept = true; typedef asio::io_context& result_type; }; template <typename Allocator, uintptr_t Bits> struct query_member< asio::io_context::basic_executor_type<Allocator, Bits>, asio::execution::allocator_t<void> > { static constexpr bool is_valid = true; static constexpr bool is_noexcept = true; typedef Allocator result_type; }; template <typename Allocator, uintptr_t Bits, typename OtherAllocator> struct query_member< asio::io_context::basic_executor_type<Allocator, Bits>, asio::execution::allocator_t<OtherAllocator> > { static constexpr bool is_valid = true; static constexpr bool is_noexcept = true; typedef Allocator result_type; }; #endif // !defined(ASIO_HAS_DEDUCED_QUERY_MEMBER_TRAIT) } // namespace traits namespace execution { template <> struct is_executor<io_context> : false_type { }; } // namespace execution #endif // !defined(GENERATING_DOCUMENTATION) } // namespace asio #include "asio/detail/pop_options.hpp" #include "asio/impl/io_context.hpp" #if defined(ASIO_HEADER_ONLY) # include "asio/impl/io_context.ipp" #endif // defined(ASIO_HEADER_ONLY) // If both io_context.hpp and strand.hpp have been included, automatically // include the header file needed for the io_context::strand class. #if !defined(ASIO_NO_EXTENSIONS) # if defined(ASIO_STRAND_HPP) # include "asio/io_context_strand.hpp" # endif // defined(ASIO_STRAND_HPP) #endif // !defined(ASIO_NO_EXTENSIONS) #endif // ASIO_IO_CONTEXT_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/handler_continuation_hook.hpp
// // handler_continuation_hook.hpp // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // // 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) // #ifndef ASIO_HANDLER_CONTINUATION_HOOK_HPP #define ASIO_HANDLER_CONTINUATION_HOOK_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include "asio/detail/push_options.hpp" namespace asio { /// Default continuation function for handlers. /** * Asynchronous operations may represent a continuation of the asynchronous * control flow associated with the current handler. The implementation can use * this knowledge to optimise scheduling of the handler. * * Implement asio_handler_is_continuation for your own handlers to indicate * when a handler represents a continuation. * * The default implementation of the continuation hook returns <tt>false</tt>. * * @par Example * @code * class my_handler; * * bool asio_handler_is_continuation(my_handler* context) * { * return true; * } * @endcode */ inline bool asio_handler_is_continuation(...) { return false; } } // namespace asio #include "asio/detail/pop_options.hpp" #endif // ASIO_HANDLER_CONTINUATION_HOOK_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/basic_stream_file.hpp
// // basic_stream_file.hpp // ~~~~~~~~~~~~~~~~~~~~~ // // 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) // #ifndef ASIO_BASIC_STREAM_FILE_HPP #define ASIO_BASIC_STREAM_FILE_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #if defined(ASIO_HAS_FILE) \ || defined(GENERATING_DOCUMENTATION) #include <cstddef> #include "asio/async_result.hpp" #include "asio/basic_file.hpp" #include "asio/detail/handler_type_requirements.hpp" #include "asio/detail/non_const_lvalue.hpp" #include "asio/detail/throw_error.hpp" #include "asio/error.hpp" #include "asio/detail/push_options.hpp" namespace asio { #if !defined(ASIO_BASIC_STREAM_FILE_FWD_DECL) #define ASIO_BASIC_STREAM_FILE_FWD_DECL // Forward declaration with defaulted arguments. template <typename Executor = any_io_executor> class basic_stream_file; #endif // !defined(ASIO_BASIC_STREAM_FILE_FWD_DECL) /// Provides stream-oriented file functionality. /** * The basic_stream_file class template provides asynchronous and blocking * stream-oriented file functionality. * * @par Thread Safety * @e Distinct @e objects: Safe.@n * @e Shared @e objects: Unsafe. * * @par Concepts: * AsyncReadStream, AsyncWriteStream, Stream, SyncReadStream, SyncWriteStream. */ template <typename Executor> class basic_stream_file : public basic_file<Executor> { private: class initiate_async_write_some; class initiate_async_read_some; public: /// The type of the executor associated with the object. typedef Executor executor_type; /// Rebinds the file type to another executor. template <typename Executor1> struct rebind_executor { /// The file type when rebound to the specified executor. typedef basic_stream_file<Executor1> other; }; /// The native representation of a file. #if defined(GENERATING_DOCUMENTATION) typedef implementation_defined native_handle_type; #else typedef typename basic_file<Executor>::native_handle_type native_handle_type; #endif /// Construct a basic_stream_file without opening it. /** * This constructor initialises a file without opening it. The file needs to * be opened before data can be read from or or written to it. * * @param ex The I/O executor that the file will use, by default, to * dispatch handlers for any asynchronous operations performed on the file. */ explicit basic_stream_file(const executor_type& ex) : basic_file<Executor>(ex) { this->impl_.get_service().set_is_stream( this->impl_.get_implementation(), true); } /// Construct a basic_stream_file without opening it. /** * This constructor initialises a file without opening it. The file needs to * be opened before data can be read from or or written to it. * * @param context An execution context which provides the I/O executor that * the file will use, by default, to dispatch handlers for any asynchronous * operations performed on the file. */ template <typename ExecutionContext> explicit basic_stream_file(ExecutionContext& context, constraint_t< is_convertible<ExecutionContext&, execution_context&>::value, defaulted_constraint > = defaulted_constraint()) : basic_file<Executor>(context) { this->impl_.get_service().set_is_stream( this->impl_.get_implementation(), true); } /// Construct and open a basic_stream_file. /** * This constructor initialises and opens a file. * * @param ex The I/O executor that the file will use, by default, to * dispatch handlers for any asynchronous operations performed on the file. * * @param path The path name identifying the file to be opened. * * @param open_flags A set of flags that determine how the file should be * opened. * * @throws asio::system_error Thrown on failure. */ basic_stream_file(const executor_type& ex, const char* path, file_base::flags open_flags) : basic_file<Executor>(ex) { asio::error_code ec; this->impl_.get_service().set_is_stream( this->impl_.get_implementation(), true); this->impl_.get_service().open( this->impl_.get_implementation(), path, open_flags, ec); asio::detail::throw_error(ec, "open"); } /// Construct and open a basic_stream_file. /** * This constructor initialises and opens a file. * * @param context An execution context which provides the I/O executor that * the file will use, by default, to dispatch handlers for any asynchronous * operations performed on the file. * * @param path The path name identifying the file to be opened. * * @param open_flags A set of flags that determine how the file should be * opened. * * @throws asio::system_error Thrown on failure. */ template <typename ExecutionContext> basic_stream_file(ExecutionContext& context, const char* path, file_base::flags open_flags, constraint_t< is_convertible<ExecutionContext&, execution_context&>::value, defaulted_constraint > = defaulted_constraint()) : basic_file<Executor>(context) { asio::error_code ec; this->impl_.get_service().set_is_stream( this->impl_.get_implementation(), true); this->impl_.get_service().open( this->impl_.get_implementation(), path, open_flags, ec); asio::detail::throw_error(ec, "open"); } /// Construct and open a basic_stream_file. /** * This constructor initialises and opens a file. * * @param ex The I/O executor that the file will use, by default, to * dispatch handlers for any asynchronous operations performed on the file. * * @param path The path name identifying the file to be opened. * * @param open_flags A set of flags that determine how the file should be * opened. * * @throws asio::system_error Thrown on failure. */ basic_stream_file(const executor_type& ex, const std::string& path, file_base::flags open_flags) : basic_file<Executor>(ex) { asio::error_code ec; this->impl_.get_service().set_is_stream( this->impl_.get_implementation(), true); this->impl_.get_service().open( this->impl_.get_implementation(), path.c_str(), open_flags, ec); asio::detail::throw_error(ec, "open"); } /// Construct and open a basic_stream_file. /** * This constructor initialises and opens a file. * * @param context An execution context which provides the I/O executor that * the file will use, by default, to dispatch handlers for any asynchronous * operations performed on the file. * * @param path The path name identifying the file to be opened. * * @param open_flags A set of flags that determine how the file should be * opened. * * @throws asio::system_error Thrown on failure. */ template <typename ExecutionContext> basic_stream_file(ExecutionContext& context, const std::string& path, file_base::flags open_flags, constraint_t< is_convertible<ExecutionContext&, execution_context&>::value, defaulted_constraint > = defaulted_constraint()) : basic_file<Executor>(context) { asio::error_code ec; this->impl_.get_service().set_is_stream( this->impl_.get_implementation(), true); this->impl_.get_service().open( this->impl_.get_implementation(), path.c_str(), open_flags, ec); asio::detail::throw_error(ec, "open"); } /// Construct a basic_stream_file on an existing native file. /** * This constructor initialises a stream file object to hold an existing * native file. * * @param ex The I/O executor that the file will use, by default, to * dispatch handlers for any asynchronous operations performed on the file. * * @param native_file The new underlying file implementation. * * @throws asio::system_error Thrown on failure. */ basic_stream_file(const executor_type& ex, const native_handle_type& native_file) : basic_file<Executor>(ex, native_file) { this->impl_.get_service().set_is_stream( this->impl_.get_implementation(), true); } /// Construct a basic_stream_file on an existing native file. /** * This constructor initialises a stream file object to hold an existing * native file. * * @param context An execution context which provides the I/O executor that * the file will use, by default, to dispatch handlers for any asynchronous * operations performed on the file. * * @param native_file The new underlying file implementation. * * @throws asio::system_error Thrown on failure. */ template <typename ExecutionContext> basic_stream_file(ExecutionContext& context, const native_handle_type& native_file, constraint_t< is_convertible<ExecutionContext&, execution_context&>::value, defaulted_constraint > = defaulted_constraint()) : basic_file<Executor>(context, native_file) { this->impl_.get_service().set_is_stream( this->impl_.get_implementation(), true); } /// Move-construct a basic_stream_file from another. /** * This constructor moves a stream file from one object to another. * * @param other The other basic_stream_file object from which the move * will occur. * * @note Following the move, the moved-from object is in the same state as if * constructed using the @c basic_stream_file(const executor_type&) * constructor. */ basic_stream_file(basic_stream_file&& other) noexcept : basic_file<Executor>(std::move(other)) { } /// Move-assign a basic_stream_file from another. /** * This assignment operator moves a stream file from one object to another. * * @param other The other basic_stream_file object from which the move * will occur. * * @note Following the move, the moved-from object is in the same state as if * constructed using the @c basic_stream_file(const executor_type&) * constructor. */ basic_stream_file& operator=(basic_stream_file&& other) { basic_file<Executor>::operator=(std::move(other)); return *this; } /// Move-construct a basic_stream_file from a file of another executor /// type. /** * This constructor moves a stream file from one object to another. * * @param other The other basic_stream_file object from which the move * will occur. * * @note Following the move, the moved-from object is in the same state as if * constructed using the @c basic_stream_file(const executor_type&) * constructor. */ template <typename Executor1> basic_stream_file(basic_stream_file<Executor1>&& other, constraint_t< is_convertible<Executor1, Executor>::value, defaulted_constraint > = defaulted_constraint()) : basic_file<Executor>(std::move(other)) { } /// Move-assign a basic_stream_file from a file of another executor type. /** * This assignment operator moves a stream file from one object to another. * * @param other The other basic_stream_file object from which the move * will occur. * * @note Following the move, the moved-from object is in the same state as if * constructed using the @c basic_stream_file(const executor_type&) * constructor. */ template <typename Executor1> constraint_t< is_convertible<Executor1, Executor>::value, basic_stream_file& > operator=(basic_stream_file<Executor1>&& other) { basic_file<Executor>::operator=(std::move(other)); return *this; } /// Destroys the file. /** * This function destroys the file, cancelling any outstanding asynchronous * operations associated with the file as if by calling @c cancel. */ ~basic_stream_file() { } /// Seek to a position in the file. /** * This function updates the current position in the file. * * @param offset The requested position in the file, relative to @c whence. * * @param whence One of @c seek_set, @c seek_cur or @c seek_end. * * @returns The new position relative to the beginning of the file. * * @throws asio::system_error Thrown on failure. */ uint64_t seek(int64_t offset, file_base::seek_basis whence) { asio::error_code ec; uint64_t n = this->impl_.get_service().seek( this->impl_.get_implementation(), offset, whence, ec); asio::detail::throw_error(ec, "seek"); return n; } /// Seek to a position in the file. /** * This function updates the current position in the file. * * @param offset The requested position in the file, relative to @c whence. * * @param whence One of @c seek_set, @c seek_cur or @c seek_end. * * @param ec Set to indicate what error occurred, if any. * * @returns The new position relative to the beginning of the file. */ uint64_t seek(int64_t offset, file_base::seek_basis whence, asio::error_code& ec) { return this->impl_.get_service().seek( this->impl_.get_implementation(), offset, whence, ec); } /// Write some data to the file. /** * This function is used to write data to the stream file. The function call * will block until one or more bytes of the data has been written * successfully, or until an error occurs. * * @param buffers One or more data buffers to be written to the file. * * @returns The number of bytes written. * * @throws asio::system_error Thrown on failure. An error code of * asio::error::eof indicates that the end of the file was reached. * * @note The write_some operation may not transmit all of the data to the * peer. Consider using the @ref write function if you need to ensure that * all data is written before the blocking operation completes. * * @par Example * To write a single data buffer use the @ref buffer function as follows: * @code * file.write_some(asio::buffer(data, size)); * @endcode * See the @ref buffer documentation for information on writing multiple * buffers in one go, and how to use it with arrays, boost::array or * std::vector. */ template <typename ConstBufferSequence> std::size_t write_some(const ConstBufferSequence& buffers) { asio::error_code ec; std::size_t s = this->impl_.get_service().write_some( this->impl_.get_implementation(), buffers, ec); asio::detail::throw_error(ec, "write_some"); return s; } /// Write some data to the file. /** * This function is used to write data to the stream file. The function call * will block until one or more bytes of the data has been written * successfully, or until an error occurs. * * @param buffers One or more data buffers to be written to the file. * * @param ec Set to indicate what error occurred, if any. * * @returns The number of bytes written. Returns 0 if an error occurred. * * @note The write_some operation may not transmit all of the data to the * peer. Consider using the @ref write function if you need to ensure that * all data is written before the blocking operation completes. */ template <typename ConstBufferSequence> std::size_t write_some(const ConstBufferSequence& buffers, asio::error_code& ec) { return this->impl_.get_service().write_some( this->impl_.get_implementation(), buffers, ec); } /// Start an asynchronous write. /** * This function is used to asynchronously write data to the stream file. * It is an initiating function for an @ref asynchronous_operation, and always * returns immediately. * * @param buffers One or more data buffers to be written to the file. * Although the buffers object may be copied as necessary, ownership of the * underlying memory blocks is retained by the caller, which must guarantee * that they remain valid until the completion handler is called. * * @param token The @ref completion_token that will be used to produce a * completion handler, which will be called when the write completes. * Potential completion tokens include @ref use_future, @ref use_awaitable, * @ref yield_context, or a function object with the correct completion * signature. The function signature of the completion handler must be: * @code void handler( * const asio::error_code& error, // Result of operation. * std::size_t bytes_transferred // Number of bytes written. * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the completion handler will not be invoked from within this function. * On immediate completion, invocation of the handler will be performed in a * manner equivalent to using asio::async_immediate(). * * @par Completion Signature * @code void(asio::error_code, std::size_t) @endcode * * @note The write operation may not transmit all of the data to the peer. * Consider using the @ref async_write function if you need to ensure that all * data is written before the asynchronous operation completes. * * @par Example * To write a single data buffer use the @ref buffer function as follows: * @code * file.async_write_some(asio::buffer(data, size), handler); * @endcode * See the @ref buffer documentation for information on writing multiple * buffers in one go, and how to use it with arrays, boost::array or * std::vector. * * @par Per-Operation Cancellation * On POSIX or Windows operating systems, this asynchronous operation supports * cancellation for the following asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * @li @c cancellation_type::total */ template <typename ConstBufferSequence, ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code, std::size_t)) WriteToken = default_completion_token_t<executor_type>> auto async_write_some(const ConstBufferSequence& buffers, WriteToken&& token = default_completion_token_t<executor_type>()) -> decltype( async_initiate<WriteToken, void (asio::error_code, std::size_t)>( declval<initiate_async_write_some>(), token, buffers)) { return async_initiate<WriteToken, void (asio::error_code, std::size_t)>( initiate_async_write_some(this), token, buffers); } /// Read some data from the file. /** * This function is used to read data from the stream file. The function * call will block until one or more bytes of data has been read successfully, * or until an error occurs. * * @param buffers One or more buffers into which the data will be read. * * @returns The number of bytes read. * * @throws asio::system_error Thrown on failure. An error code of * asio::error::eof indicates that the end of the file was reached. * * @note The read_some operation may not read all of the requested number of * bytes. Consider using the @ref read function if you need to ensure that * the requested amount of data is read before the blocking operation * completes. * * @par Example * To read into a single data buffer use the @ref buffer function as follows: * @code * file.read_some(asio::buffer(data, size)); * @endcode * See the @ref buffer documentation for information on reading into multiple * buffers in one go, and how to use it with arrays, boost::array or * std::vector. */ template <typename MutableBufferSequence> std::size_t read_some(const MutableBufferSequence& buffers) { asio::error_code ec; std::size_t s = this->impl_.get_service().read_some( this->impl_.get_implementation(), buffers, ec); asio::detail::throw_error(ec, "read_some"); return s; } /// Read some data from the file. /** * This function is used to read data from the stream file. The function * call will block until one or more bytes of data has been read successfully, * or until an error occurs. * * @param buffers One or more buffers into which the data will be read. * * @param ec Set to indicate what error occurred, if any. * * @returns The number of bytes read. Returns 0 if an error occurred. * * @note The read_some operation may not read all of the requested number of * bytes. Consider using the @ref read function if you need to ensure that * the requested amount of data is read before the blocking operation * completes. */ template <typename MutableBufferSequence> std::size_t read_some(const MutableBufferSequence& buffers, asio::error_code& ec) { return this->impl_.get_service().read_some( this->impl_.get_implementation(), buffers, ec); } /// Start an asynchronous read. /** * This function is used to asynchronously read data from the stream file. * It is an initiating function for an @ref asynchronous_operation, and always * returns immediately. * * @param buffers One or more buffers into which the data will be read. * Although the buffers object may be copied as necessary, ownership of the * underlying memory blocks is retained by the caller, which must guarantee * that they remain valid until the completion handler is called. * * @param token The @ref completion_token that will be used to produce a * completion handler, which will be called when the read completes. * Potential completion tokens include @ref use_future, @ref use_awaitable, * @ref yield_context, or a function object with the correct completion * signature. The function signature of the completion handler must be: * @code void handler( * const asio::error_code& error, // Result of operation. * std::size_t bytes_transferred // Number of bytes read. * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the completion handler will not be invoked from within this function. * On immediate completion, invocation of the handler will be performed in a * manner equivalent to using asio::async_immediate(). * * @par Completion Signature * @code void(asio::error_code, std::size_t) @endcode * * @note The read operation may not read all of the requested number of bytes. * Consider using the @ref async_read function if you need to ensure that the * requested amount of data is read before the asynchronous operation * completes. * * @par Example * To read into a single data buffer use the @ref buffer function as follows: * @code * file.async_read_some(asio::buffer(data, size), handler); * @endcode * See the @ref buffer documentation for information on reading into multiple * buffers in one go, and how to use it with arrays, boost::array or * std::vector. * * @par Per-Operation Cancellation * On POSIX or Windows operating systems, this asynchronous operation supports * cancellation for the following asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * @li @c cancellation_type::total */ template <typename MutableBufferSequence, ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code, std::size_t)) ReadToken = default_completion_token_t<executor_type>> auto async_read_some(const MutableBufferSequence& buffers, ReadToken&& token = default_completion_token_t<executor_type>()) -> decltype( async_initiate<ReadToken, void (asio::error_code, std::size_t)>( declval<initiate_async_read_some>(), token, buffers)) { return async_initiate<ReadToken, void (asio::error_code, std::size_t)>( initiate_async_read_some(this), token, buffers); } private: // Disallow copying and assignment. basic_stream_file(const basic_stream_file&) = delete; basic_stream_file& operator=(const basic_stream_file&) = delete; class initiate_async_write_some { public: typedef Executor executor_type; explicit initiate_async_write_some(basic_stream_file* self) : self_(self) { } const executor_type& get_executor() const noexcept { return self_->get_executor(); } template <typename WriteHandler, typename ConstBufferSequence> void operator()(WriteHandler&& handler, const ConstBufferSequence& buffers) const { // If you get an error on the following line it means that your handler // does not meet the documented type requirements for a WriteHandler. ASIO_WRITE_HANDLER_CHECK(WriteHandler, handler) type_check; detail::non_const_lvalue<WriteHandler> handler2(handler); self_->impl_.get_service().async_write_some( self_->impl_.get_implementation(), buffers, handler2.value, self_->impl_.get_executor()); } private: basic_stream_file* self_; }; class initiate_async_read_some { public: typedef Executor executor_type; explicit initiate_async_read_some(basic_stream_file* self) : self_(self) { } const executor_type& get_executor() const noexcept { return self_->get_executor(); } template <typename ReadHandler, typename MutableBufferSequence> void operator()(ReadHandler&& handler, const MutableBufferSequence& buffers) const { // If you get an error on the following line it means that your handler // does not meet the documented type requirements for a ReadHandler. ASIO_READ_HANDLER_CHECK(ReadHandler, handler) type_check; detail::non_const_lvalue<ReadHandler> handler2(handler); self_->impl_.get_service().async_read_some( self_->impl_.get_implementation(), buffers, handler2.value, self_->impl_.get_executor()); } private: basic_stream_file* self_; }; }; } // namespace asio #include "asio/detail/pop_options.hpp" #endif // defined(ASIO_HAS_FILE) // || defined(GENERATING_DOCUMENTATION) #endif // ASIO_BASIC_STREAM_FILE_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/connect_pipe.hpp
// // connect_pipe.hpp // ~~~~~~~~~~~~~~~~ // // 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) // #ifndef ASIO_CONNECT_PIPE_HPP #define ASIO_CONNECT_PIPE_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #if defined(ASIO_HAS_PIPE) \ || defined(GENERATING_DOCUMENTATION) #include "asio/basic_readable_pipe.hpp" #include "asio/basic_writable_pipe.hpp" #include "asio/error.hpp" #include "asio/detail/push_options.hpp" namespace asio { namespace detail { #if defined(ASIO_HAS_IOCP) typedef HANDLE native_pipe_handle; #else // defined(ASIO_HAS_IOCP) typedef int native_pipe_handle; #endif // defined(ASIO_HAS_IOCP) ASIO_DECL void create_pipe(native_pipe_handle p[2], asio::error_code& ec); ASIO_DECL void close_pipe(native_pipe_handle p); } // namespace detail /// Connect two pipe ends using an anonymous pipe. /** * @param read_end The read end of the pipe. * * @param write_end The write end of the pipe. * * @throws asio::system_error Thrown on failure. */ template <typename Executor1, typename Executor2> void connect_pipe(basic_readable_pipe<Executor1>& read_end, basic_writable_pipe<Executor2>& write_end); /// Connect two pipe ends using an anonymous pipe. /** * @param read_end The read end of the pipe. * * @param write_end The write end of the pipe. * * @throws asio::system_error Thrown on failure. * * @param ec Set to indicate what error occurred, if any. */ template <typename Executor1, typename Executor2> ASIO_SYNC_OP_VOID connect_pipe(basic_readable_pipe<Executor1>& read_end, basic_writable_pipe<Executor2>& write_end, asio::error_code& ec); } // namespace asio #include "asio/detail/pop_options.hpp" #include "asio/impl/connect_pipe.hpp" #if defined(ASIO_HEADER_ONLY) # include "asio/impl/connect_pipe.ipp" #endif // defined(ASIO_HEADER_ONLY) #endif // defined(ASIO_HAS_PIPE) // || defined(GENERATING_DOCUMENTATION) #endif // ASIO_CONNECT_PIPE_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/associated_cancellation_slot.hpp
// // associated_cancellation_slot.hpp // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // // 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) // #ifndef ASIO_ASSOCIATED_CANCELLATION_SLOT_HPP #define ASIO_ASSOCIATED_CANCELLATION_SLOT_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include "asio/associator.hpp" #include "asio/cancellation_signal.hpp" #include "asio/detail/functional.hpp" #include "asio/detail/type_traits.hpp" #include "asio/detail/push_options.hpp" namespace asio { template <typename T, typename CancellationSlot> struct associated_cancellation_slot; namespace detail { template <typename T, typename = void> struct has_cancellation_slot_type : false_type { }; template <typename T> struct has_cancellation_slot_type<T, void_t<typename T::cancellation_slot_type>> : true_type { }; template <typename T, typename S, typename = void, typename = void> struct associated_cancellation_slot_impl { typedef void asio_associated_cancellation_slot_is_unspecialised; typedef S type; static type get(const T&) noexcept { return type(); } static const type& get(const T&, const S& s) noexcept { return s; } }; template <typename T, typename S> struct associated_cancellation_slot_impl<T, S, void_t<typename T::cancellation_slot_type>> { typedef typename T::cancellation_slot_type type; static auto get(const T& t) noexcept -> decltype(t.get_cancellation_slot()) { return t.get_cancellation_slot(); } static auto get(const T& t, const S&) noexcept -> decltype(t.get_cancellation_slot()) { return t.get_cancellation_slot(); } }; template <typename T, typename S> struct associated_cancellation_slot_impl<T, S, enable_if_t< !has_cancellation_slot_type<T>::value >, void_t< typename associator<associated_cancellation_slot, T, S>::type >> : associator<associated_cancellation_slot, T, S> { }; } // namespace detail /// Traits type used to obtain the cancellation_slot associated with an object. /** * A program may specialise this traits type if the @c T template parameter in * the specialisation is a user-defined type. The template parameter @c * CancellationSlot shall be a type meeting the CancellationSlot requirements. * * Specialisations shall meet the following requirements, where @c t is a const * reference to an object of type @c T, and @c s is an object of type @c * CancellationSlot. * * @li Provide a nested typedef @c type that identifies a type meeting the * CancellationSlot requirements. * * @li Provide a noexcept static member function named @c get, callable as @c * get(t) and with return type @c type or a (possibly const) reference to @c * type. * * @li Provide a noexcept static member function named @c get, callable as @c * get(t,s) and with return type @c type or a (possibly const) reference to @c * type. */ template <typename T, typename CancellationSlot = cancellation_slot> struct associated_cancellation_slot #if !defined(GENERATING_DOCUMENTATION) : detail::associated_cancellation_slot_impl<T, CancellationSlot> #endif // !defined(GENERATING_DOCUMENTATION) { #if defined(GENERATING_DOCUMENTATION) /// If @c T has a nested type @c cancellation_slot_type, /// <tt>T::cancellation_slot_type</tt>. Otherwise /// @c CancellationSlot. typedef see_below type; /// If @c T has a nested type @c cancellation_slot_type, returns /// <tt>t.get_cancellation_slot()</tt>. Otherwise returns @c type(). static decltype(auto) get(const T& t) noexcept; /// If @c T has a nested type @c cancellation_slot_type, returns /// <tt>t.get_cancellation_slot()</tt>. Otherwise returns @c s. static decltype(auto) get(const T& t, const CancellationSlot& s) noexcept; #endif // defined(GENERATING_DOCUMENTATION) }; /// Helper function to obtain an object's associated cancellation_slot. /** * @returns <tt>associated_cancellation_slot<T>::get(t)</tt> */ template <typename T> ASIO_NODISCARD inline typename associated_cancellation_slot<T>::type get_associated_cancellation_slot(const T& t) noexcept { return associated_cancellation_slot<T>::get(t); } /// Helper function to obtain an object's associated cancellation_slot. /** * @returns <tt>associated_cancellation_slot<T, * CancellationSlot>::get(t, st)</tt> */ template <typename T, typename CancellationSlot> ASIO_NODISCARD inline auto get_associated_cancellation_slot( const T& t, const CancellationSlot& st) noexcept -> decltype(associated_cancellation_slot<T, CancellationSlot>::get(t, st)) { return associated_cancellation_slot<T, CancellationSlot>::get(t, st); } template <typename T, typename CancellationSlot = cancellation_slot> using associated_cancellation_slot_t = typename associated_cancellation_slot<T, CancellationSlot>::type; namespace detail { template <typename T, typename S, typename = void> struct associated_cancellation_slot_forwarding_base { }; template <typename T, typename S> struct associated_cancellation_slot_forwarding_base<T, S, enable_if_t< is_same< typename associated_cancellation_slot<T, S>::asio_associated_cancellation_slot_is_unspecialised, void >::value >> { typedef void asio_associated_cancellation_slot_is_unspecialised; }; } // namespace detail /// Specialisation of associated_cancellation_slot for @c /// std::reference_wrapper. template <typename T, typename CancellationSlot> struct associated_cancellation_slot<reference_wrapper<T>, CancellationSlot> #if !defined(GENERATING_DOCUMENTATION) : detail::associated_cancellation_slot_forwarding_base<T, CancellationSlot> #endif // !defined(GENERATING_DOCUMENTATION) { /// Forwards @c type to the associator specialisation for the unwrapped type /// @c T. typedef typename associated_cancellation_slot<T, CancellationSlot>::type type; /// Forwards the request to get the cancellation slot to the associator /// specialisation for the unwrapped type @c T. static type get(reference_wrapper<T> t) noexcept { return associated_cancellation_slot<T, CancellationSlot>::get(t.get()); } /// Forwards the request to get the cancellation slot to the associator /// specialisation for the unwrapped type @c T. static auto get(reference_wrapper<T> t, const CancellationSlot& s) noexcept -> decltype( associated_cancellation_slot<T, CancellationSlot>::get(t.get(), s)) { return associated_cancellation_slot<T, CancellationSlot>::get(t.get(), s); } }; } // namespace asio #include "asio/detail/pop_options.hpp" #endif // ASIO_ASSOCIATED_CANCELLATION_SLOT_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/associated_immediate_executor.hpp
// // associated_immediate_executor.hpp // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // // 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) // #ifndef ASIO_ASSOCIATED_IMMEDIATE_EXECUTOR_HPP #define ASIO_ASSOCIATED_IMMEDIATE_EXECUTOR_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include "asio/associator.hpp" #include "asio/detail/functional.hpp" #include "asio/detail/type_traits.hpp" #include "asio/execution/blocking.hpp" #include "asio/execution/executor.hpp" #include "asio/execution_context.hpp" #include "asio/is_executor.hpp" #include "asio/require.hpp" #include "asio/detail/push_options.hpp" namespace asio { template <typename T, typename Executor> struct associated_immediate_executor; namespace detail { template <typename T, typename = void> struct has_immediate_executor_type : false_type { }; template <typename T> struct has_immediate_executor_type<T, void_t<typename T::immediate_executor_type>> : true_type { }; template <typename E, typename = void, typename = void> struct default_immediate_executor { typedef decay_t<require_result_t<E, execution::blocking_t::never_t>> type; static auto get(const E& e) noexcept -> decltype(asio::require(e, execution::blocking.never)) { return asio::require(e, execution::blocking.never); } }; template <typename E> struct default_immediate_executor<E, enable_if_t< !execution::is_executor<E>::value >, enable_if_t< is_executor<E>::value >> { class type : public E { public: template <typename Executor1> explicit type(const Executor1& e, constraint_t< conditional_t< !is_same<Executor1, type>::value, is_convertible<Executor1, E>, false_type >::value > = 0) noexcept : E(e) { } type(const type& other) noexcept : E(static_cast<const E&>(other)) { } type(type&& other) noexcept : E(static_cast<E&&>(other)) { } template <typename Function, typename Allocator> void dispatch(Function&& f, const Allocator& a) const { this->post(static_cast<Function&&>(f), a); } friend bool operator==(const type& a, const type& b) noexcept { return static_cast<const E&>(a) == static_cast<const E&>(b); } friend bool operator!=(const type& a, const type& b) noexcept { return static_cast<const E&>(a) != static_cast<const E&>(b); } }; static type get(const E& e) noexcept { return type(e); } }; template <typename T, typename E, typename = void, typename = void> struct associated_immediate_executor_impl { typedef void asio_associated_immediate_executor_is_unspecialised; typedef typename default_immediate_executor<E>::type type; static auto get(const T&, const E& e) noexcept -> decltype(default_immediate_executor<E>::get(e)) { return default_immediate_executor<E>::get(e); } }; template <typename T, typename E> struct associated_immediate_executor_impl<T, E, void_t<typename T::immediate_executor_type>> { typedef typename T::immediate_executor_type type; static auto get(const T& t, const E&) noexcept -> decltype(t.get_immediate_executor()) { return t.get_immediate_executor(); } }; template <typename T, typename E> struct associated_immediate_executor_impl<T, E, enable_if_t< !has_immediate_executor_type<T>::value >, void_t< typename associator<associated_immediate_executor, T, E>::type >> : associator<associated_immediate_executor, T, E> { }; } // namespace detail /// Traits type used to obtain the immediate executor associated with an object. /** * A program may specialise this traits type if the @c T template parameter in * the specialisation is a user-defined type. The template parameter @c * Executor shall be a type meeting the Executor requirements. * * Specialisations shall meet the following requirements, where @c t is a const * reference to an object of type @c T, and @c e is an object of type @c * Executor. * * @li Provide a nested typedef @c type that identifies a type meeting the * Executor requirements. * * @li Provide a noexcept static member function named @c get, callable as @c * get(t) and with return type @c type or a (possibly const) reference to @c * type. * * @li Provide a noexcept static member function named @c get, callable as @c * get(t,e) and with return type @c type or a (possibly const) reference to @c * type. */ template <typename T, typename Executor> struct associated_immediate_executor #if !defined(GENERATING_DOCUMENTATION) : detail::associated_immediate_executor_impl<T, Executor> #endif // !defined(GENERATING_DOCUMENTATION) { #if defined(GENERATING_DOCUMENTATION) /// If @c T has a nested type @c immediate_executor_type, // <tt>T::immediate_executor_type</tt>. Otherwise @c Executor. typedef see_below type; /// If @c T has a nested type @c immediate_executor_type, returns /// <tt>t.get_immediate_executor()</tt>. Otherwise returns /// <tt>asio::require(ex, asio::execution::blocking.never)</tt>. static decltype(auto) get(const T& t, const Executor& ex) noexcept; #endif // defined(GENERATING_DOCUMENTATION) }; /// Helper function to obtain an object's associated executor. /** * @returns <tt>associated_immediate_executor<T, Executor>::get(t, ex)</tt> */ template <typename T, typename Executor> ASIO_NODISCARD inline auto get_associated_immediate_executor( const T& t, const Executor& ex, constraint_t< is_executor<Executor>::value || execution::is_executor<Executor>::value > = 0) noexcept -> decltype(associated_immediate_executor<T, Executor>::get(t, ex)) { return associated_immediate_executor<T, Executor>::get(t, ex); } /// Helper function to obtain an object's associated executor. /** * @returns <tt>associated_immediate_executor<T, typename * ExecutionContext::executor_type>::get(t, ctx.get_executor())</tt> */ template <typename T, typename ExecutionContext> ASIO_NODISCARD inline typename associated_immediate_executor<T, typename ExecutionContext::executor_type>::type get_associated_immediate_executor(const T& t, ExecutionContext& ctx, constraint_t< is_convertible<ExecutionContext&, execution_context&>::value > = 0) noexcept { return associated_immediate_executor<T, typename ExecutionContext::executor_type>::get(t, ctx.get_executor()); } template <typename T, typename Executor> using associated_immediate_executor_t = typename associated_immediate_executor<T, Executor>::type; namespace detail { template <typename T, typename E, typename = void> struct associated_immediate_executor_forwarding_base { }; template <typename T, typename E> struct associated_immediate_executor_forwarding_base<T, E, enable_if_t< is_same< typename associated_immediate_executor<T, E>::asio_associated_immediate_executor_is_unspecialised, void >::value >> { typedef void asio_associated_immediate_executor_is_unspecialised; }; } // namespace detail /// Specialisation of associated_immediate_executor for /// @c std::reference_wrapper. template <typename T, typename Executor> struct associated_immediate_executor<reference_wrapper<T>, Executor> #if !defined(GENERATING_DOCUMENTATION) : detail::associated_immediate_executor_forwarding_base<T, Executor> #endif // !defined(GENERATING_DOCUMENTATION) { /// Forwards @c type to the associator specialisation for the unwrapped type /// @c T. typedef typename associated_immediate_executor<T, Executor>::type type; /// Forwards the request to get the executor to the associator specialisation /// for the unwrapped type @c T. static auto get(reference_wrapper<T> t, const Executor& ex) noexcept -> decltype(associated_immediate_executor<T, Executor>::get(t.get(), ex)) { return associated_immediate_executor<T, Executor>::get(t.get(), ex); } }; } // namespace asio #include "asio/detail/pop_options.hpp" #endif // ASIO_ASSOCIATED_IMMEDIATE_EXECUTOR_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/as_tuple.hpp
// // as_tuple.hpp // ~~~~~~~~~~~~ // // 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) // #ifndef ASIO_AS_TUPLE_HPP #define ASIO_AS_TUPLE_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include "asio/detail/type_traits.hpp" #include "asio/detail/push_options.hpp" namespace asio { /// A @ref completion_token adapter used to specify that the completion handler /// arguments should be combined into a single tuple argument. /** * The as_tuple_t class is used to indicate that any arguments to the * completion handler should be combined and passed as a single tuple argument. * The arguments are first moved into a @c std::tuple and that tuple is then * passed to the completion handler. */ template <typename CompletionToken> class as_tuple_t { public: /// Tag type used to prevent the "default" constructor from being used for /// conversions. struct default_constructor_tag {}; /// Default constructor. /** * This constructor is only valid if the underlying completion token is * default constructible and move constructible. The underlying completion * token is itself defaulted as an argument to allow it to capture a source * location. */ constexpr as_tuple_t( default_constructor_tag = default_constructor_tag(), CompletionToken token = CompletionToken()) : token_(static_cast<CompletionToken&&>(token)) { } /// Constructor. template <typename T> constexpr explicit as_tuple_t( T&& completion_token) : token_(static_cast<T&&>(completion_token)) { } /// Adapts an executor to add the @c as_tuple_t completion token as the /// default. template <typename InnerExecutor> struct executor_with_default : InnerExecutor { /// Specify @c as_tuple_t as the default completion token type. typedef as_tuple_t default_completion_token_type; /// Construct the adapted executor from the inner executor type. template <typename InnerExecutor1> executor_with_default(const InnerExecutor1& ex, constraint_t< conditional_t< !is_same<InnerExecutor1, executor_with_default>::value, is_convertible<InnerExecutor1, InnerExecutor>, false_type >::value > = 0) noexcept : InnerExecutor(ex) { } }; /// Type alias to adapt an I/O object to use @c as_tuple_t as its /// default completion token type. template <typename T> using as_default_on_t = typename T::template rebind_executor< executor_with_default<typename T::executor_type>>::other; /// Function helper to adapt an I/O object to use @c as_tuple_t as its /// default completion token type. template <typename T> static typename decay_t<T>::template rebind_executor< executor_with_default<typename decay_t<T>::executor_type> >::other as_default_on(T&& object) { return typename decay_t<T>::template rebind_executor< executor_with_default<typename decay_t<T>::executor_type> >::other(static_cast<T&&>(object)); } //private: CompletionToken token_; }; /// A function object type that adapts a @ref completion_token to specify that /// the completion handler arguments should be combined into a single tuple /// argument. /** * May also be used directly as a completion token, in which case it adapts the * asynchronous operation's default completion token (or asio::deferred * if no default is available). */ struct partial_as_tuple { /// Default constructor. constexpr partial_as_tuple() { } /// Adapt a @ref completion_token to specify that the completion handler /// arguments should be combined into a single tuple argument. template <typename CompletionToken> ASIO_NODISCARD inline constexpr as_tuple_t<decay_t<CompletionToken>> operator()(CompletionToken&& completion_token) const { return as_tuple_t<decay_t<CompletionToken>>( static_cast<CompletionToken&&>(completion_token)); } }; /// A function object that adapts a @ref completion_token to specify that the /// completion handler arguments should be combined into a single tuple /// argument. /** * May also be used directly as a completion token, in which case it adapts the * asynchronous operation's default completion token (or asio::deferred * if no default is available). */ ASIO_INLINE_VARIABLE constexpr partial_as_tuple as_tuple; } // namespace asio #include "asio/detail/pop_options.hpp" #include "asio/impl/as_tuple.hpp" #endif // ASIO_AS_TUPLE_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/query.hpp
// // query.hpp // ~~~~~~~~~ // // 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) // #ifndef ASIO_QUERY_HPP #define ASIO_QUERY_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include "asio/detail/type_traits.hpp" #include "asio/is_applicable_property.hpp" #include "asio/traits/query_member.hpp" #include "asio/traits/query_free.hpp" #include "asio/traits/static_query.hpp" #include "asio/detail/push_options.hpp" #if defined(GENERATING_DOCUMENTATION) namespace asio { /// A customisation point that queries the value of a property. /** * The name <tt>query</tt> denotes a customization point object. The * expression <tt>asio::query(E, P)</tt> for some * subexpressions <tt>E</tt> and <tt>P</tt> (with types <tt>T = * decay_t<decltype(E)></tt> and <tt>Prop = decay_t<decltype(P)></tt>) is * expression-equivalent to: * * @li If <tt>is_applicable_property_v<T, Prop></tt> is not a well-formed * constant expression with value <tt>true</tt>, <tt>asio::query(E, * P)</tt> is ill-formed. * * @li Otherwise, <tt>Prop::template static_query_v<T></tt> if the expression * <tt>Prop::template static_query_v<T></tt> is a well-formed constant * expression. * * @li Otherwise, <tt>(E).query(P)</tt> if the expression * <tt>(E).query(P)</tt> is well-formed. * * @li Otherwise, <tt>query(E, P)</tt> if the expression * <tt>query(E, P)</tt> is a valid expression with overload * resolution performed in a context that does not include the declaration * of the <tt>query</tt> customization point object. * * @li Otherwise, <tt>asio::query(E, P)</tt> is ill-formed. */ inline constexpr unspecified query = unspecified; /// A type trait that determines whether a @c query expression is well-formed. /** * Class template @c can_query is a trait that is derived from * @c true_type if the expression <tt>asio::query(std::declval<T>(), * std::declval<Property>())</tt> is well formed; otherwise @c false_type. */ template <typename T, typename Property> struct can_query : integral_constant<bool, automatically_determined> { }; /// A type trait that determines whether a @c query expression will /// not throw. /** * Class template @c is_nothrow_query is a trait that is derived from * @c true_type if the expression <tt>asio::query(std::declval<T>(), * std::declval<Property>())</tt> is @c noexcept; otherwise @c false_type. */ template <typename T, typename Property> struct is_nothrow_query : integral_constant<bool, automatically_determined> { }; /// A type trait that determines the result type of a @c query expression. /** * Class template @c query_result is a trait that determines the result * type of the expression <tt>asio::query(std::declval<T>(), * std::declval<Property>())</tt>. */ template <typename T, typename Property> struct query_result { /// The result of the @c query expression. typedef automatically_determined type; }; } // namespace asio #else // defined(GENERATING_DOCUMENTATION) namespace asio_query_fn { using asio::conditional_t; using asio::decay_t; using asio::declval; using asio::enable_if_t; using asio::is_applicable_property; using asio::traits::query_free; using asio::traits::query_member; using asio::traits::static_query; void query(); enum overload_type { static_value, call_member, call_free, ill_formed }; template <typename Impl, typename T, typename Properties, typename = void, typename = void, typename = void, typename = void> struct call_traits { static constexpr overload_type overload = ill_formed; static constexpr bool is_noexcept = false; typedef void result_type; }; template <typename Impl, typename T, typename Property> struct call_traits<Impl, T, void(Property), enable_if_t< is_applicable_property< decay_t<T>, decay_t<Property> >::value >, enable_if_t< static_query<T, Property>::is_valid >> : static_query<T, Property> { static constexpr overload_type overload = static_value; }; template <typename Impl, typename T, typename Property> struct call_traits<Impl, T, void(Property), enable_if_t< is_applicable_property< decay_t<T>, decay_t<Property> >::value >, enable_if_t< !static_query<T, Property>::is_valid >, enable_if_t< query_member<typename Impl::template proxy<T>::type, Property>::is_valid >> : query_member<typename Impl::template proxy<T>::type, Property> { static constexpr overload_type overload = call_member; }; template <typename Impl, typename T, typename Property> struct call_traits<Impl, T, void(Property), enable_if_t< is_applicable_property< decay_t<T>, decay_t<Property> >::value >, enable_if_t< !static_query<T, Property>::is_valid >, enable_if_t< !query_member<typename Impl::template proxy<T>::type, Property>::is_valid >, enable_if_t< query_free<T, Property>::is_valid >> : query_free<T, Property> { static constexpr overload_type overload = call_free; }; struct impl { template <typename T> struct proxy { #if defined(ASIO_HAS_DEDUCED_QUERY_MEMBER_TRAIT) struct type { template <typename P> auto query(P&& p) noexcept( noexcept( declval<conditional_t<true, T, P>>().query(static_cast<P&&>(p)) ) ) -> decltype( declval<conditional_t<true, T, P>>().query(static_cast<P&&>(p)) ); }; #else // defined(ASIO_HAS_DEDUCED_QUERY_MEMBER_TRAIT) typedef T type; #endif // defined(ASIO_HAS_DEDUCED_QUERY_MEMBER_TRAIT) }; template <typename T, typename Property> ASIO_NODISCARD constexpr enable_if_t< call_traits<impl, T, void(Property)>::overload == static_value, typename call_traits<impl, T, void(Property)>::result_type > operator()(T&&, Property&&) const noexcept(call_traits<impl, T, void(Property)>::is_noexcept) { return static_query<decay_t<T>, decay_t<Property>>::value(); } template <typename T, typename Property> ASIO_NODISCARD constexpr enable_if_t< call_traits<impl, T, void(Property)>::overload == call_member, typename call_traits<impl, T, void(Property)>::result_type > operator()(T&& t, Property&& p) const noexcept(call_traits<impl, T, void(Property)>::is_noexcept) { return static_cast<T&&>(t).query(static_cast<Property&&>(p)); } template <typename T, typename Property> ASIO_NODISCARD constexpr enable_if_t< call_traits<impl, T, void(Property)>::overload == call_free, typename call_traits<impl, T, void(Property)>::result_type > operator()(T&& t, Property&& p) const noexcept(call_traits<impl, T, void(Property)>::is_noexcept) { return query(static_cast<T&&>(t), static_cast<Property&&>(p)); } }; template <typename T = impl> struct static_instance { static const T instance; }; template <typename T> const T static_instance<T>::instance = {}; } // namespace asio_query_fn namespace asio { namespace { static constexpr const asio_query_fn::impl& query = asio_query_fn::static_instance<>::instance; } // namespace typedef asio_query_fn::impl query_t; template <typename T, typename Property> struct can_query : integral_constant<bool, asio_query_fn::call_traits<query_t, T, void(Property)>::overload != asio_query_fn::ill_formed> { }; #if defined(ASIO_HAS_VARIABLE_TEMPLATES) template <typename T, typename Property> constexpr bool can_query_v = can_query<T, Property>::value; #endif // defined(ASIO_HAS_VARIABLE_TEMPLATES) template <typename T, typename Property> struct is_nothrow_query : integral_constant<bool, asio_query_fn::call_traits<query_t, T, void(Property)>::is_noexcept> { }; #if defined(ASIO_HAS_VARIABLE_TEMPLATES) template <typename T, typename Property> constexpr bool is_nothrow_query_v = is_nothrow_query<T, Property>::value; #endif // defined(ASIO_HAS_VARIABLE_TEMPLATES) template <typename T, typename Property> struct query_result { typedef typename asio_query_fn::call_traits< query_t, T, void(Property)>::result_type type; }; template <typename T, typename Property> using query_result_t = typename query_result<T, Property>::type; } // namespace asio #endif // defined(GENERATING_DOCUMENTATION) #include "asio/detail/pop_options.hpp" #endif // ASIO_QUERY_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/read_until.hpp
// // read_until.hpp // ~~~~~~~~~~~~~~ // // 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) // #ifndef ASIO_READ_UNTIL_HPP #define ASIO_READ_UNTIL_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include <cstddef> #include <string> #include "asio/async_result.hpp" #include "asio/buffer.hpp" #include "asio/detail/regex_fwd.hpp" #include "asio/detail/string_view.hpp" #include "asio/detail/type_traits.hpp" #include "asio/error.hpp" #if !defined(ASIO_NO_EXTENSIONS) # include "asio/basic_streambuf_fwd.hpp" #endif // !defined(ASIO_NO_EXTENSIONS) #include "asio/detail/push_options.hpp" namespace asio { namespace detail { char (&has_result_type_helper(...))[2]; template <typename T> char has_result_type_helper(T*, typename T::result_type* = 0); template <typename T> struct has_result_type { enum { value = (sizeof((has_result_type_helper)((T*)(0))) == 1) }; }; #if !defined(ASIO_NO_DYNAMIC_BUFFER_V1) template <typename> class initiate_async_read_until_delim_v1; template <typename> class initiate_async_read_until_delim_string_v1; #if defined(ASIO_HAS_BOOST_REGEX) template <typename> class initiate_async_read_until_expr_v1; #endif // defined(ASIO_HAS_BOOST_REGEX) template <typename> class initiate_async_read_until_match_v1; #endif // !defined(ASIO_NO_DYNAMIC_BUFFER_V1) template <typename> class initiate_async_read_until_delim_v2; template <typename> class initiate_async_read_until_delim_string_v2; #if defined(ASIO_HAS_BOOST_REGEX) template <typename> class initiate_async_read_until_expr_v2; #endif // defined(ASIO_HAS_BOOST_REGEX) template <typename> class initiate_async_read_until_match_v2; } // namespace detail /// Type trait used to determine whether a type can be used as a match condition /// function with read_until and async_read_until. template <typename T> struct is_match_condition { #if defined(GENERATING_DOCUMENTATION) /// The value member is true if the type may be used as a match condition. static const bool value; #else enum { value = asio::is_function<remove_pointer_t<T>>::value || detail::has_result_type<T>::value }; #endif }; /** * @defgroup read_until asio::read_until * * @brief The @c read_until function is a composed operation that reads data * into a dynamic buffer sequence, or into a streambuf, until it contains a * delimiter, matches a regular expression, or a function object indicates a * match. */ /*@{*/ #if !defined(ASIO_NO_DYNAMIC_BUFFER_V1) /// Read data into a dynamic buffer sequence until it contains a specified /// delimiter. /** * This function is used to read data into the specified dynamic buffer * sequence until the dynamic buffer sequence's get area contains the specified * delimiter. The call will block until one of the following conditions is * true: * * @li The get area of the dynamic buffer sequence contains the specified * delimiter. * * @li An error occurred. * * This operation is implemented in terms of zero or more calls to the stream's * read_some function. If the dynamic buffer sequence's get area already * contains the delimiter, the function returns immediately. * * @param s The stream from which the data is to be read. The type must support * the SyncReadStream concept. * * @param buffers The dynamic buffer sequence into which the data will be read. * * @param delim The delimiter character. * * @returns The number of bytes in the dynamic buffer sequence's get area up to * and including the delimiter. * * @throws asio::system_error Thrown on failure. * * @note After a successful read_until operation, the dynamic buffer sequence * may contain additional data beyond the delimiter. An application will * typically leave that data in the dynamic buffer sequence for a subsequent * read_until operation to examine. * * @par Example * To read data into a @c std::string until a newline is encountered: * @code std::string data; * std::size_t n = asio::read_until(s, * asio::dynamic_buffer(data), '\n'); * std::string line = data.substr(0, n); * data.erase(0, n); @endcode * After the @c read_until operation completes successfully, the string @c data * contains the delimiter: * @code { 'a', 'b', ..., 'c', '\n', 'd', 'e', ... } @endcode * The call to @c substr then extracts the data up to and including the * delimiter, so that the string @c line contains: * @code { 'a', 'b', ..., 'c', '\n' } @endcode * After the call to @c erase, the remaining data is left in the buffer @c b as * follows: * @code { 'd', 'e', ... } @endcode * This data may be the start of a new line, to be extracted by a subsequent * @c read_until operation. */ template <typename SyncReadStream, typename DynamicBuffer_v1> std::size_t read_until(SyncReadStream& s, DynamicBuffer_v1&& buffers, char delim, constraint_t< is_dynamic_buffer_v1<decay_t<DynamicBuffer_v1>>::value > = 0, constraint_t< !is_dynamic_buffer_v2<decay_t<DynamicBuffer_v1>>::value > = 0); /// Read data into a dynamic buffer sequence until it contains a specified /// delimiter. /** * This function is used to read data into the specified dynamic buffer * sequence until the dynamic buffer sequence's get area contains the specified * delimiter. The call will block until one of the following conditions is * true: * * @li The get area of the dynamic buffer sequence contains the specified * delimiter. * * @li An error occurred. * * This operation is implemented in terms of zero or more calls to the stream's * read_some function. If the dynamic buffer sequence's get area already * contains the delimiter, the function returns immediately. * * @param s The stream from which the data is to be read. The type must support * the SyncReadStream concept. * * @param buffers The dynamic buffer sequence into which the data will be read. * * @param delim The delimiter character. * * @param ec Set to indicate what error occurred, if any. * * @returns The number of bytes in the dynamic buffer sequence's get area up to * and including the delimiter. Returns 0 if an error occurred. * * @note After a successful read_until operation, the dynamic buffer sequence * may contain additional data beyond the delimiter. An application will * typically leave that data in the dynamic buffer sequence for a subsequent * read_until operation to examine. */ template <typename SyncReadStream, typename DynamicBuffer_v1> std::size_t read_until(SyncReadStream& s, DynamicBuffer_v1&& buffers, char delim, asio::error_code& ec, constraint_t< is_dynamic_buffer_v1<decay_t<DynamicBuffer_v1>>::value > = 0, constraint_t< !is_dynamic_buffer_v2<decay_t<DynamicBuffer_v1>>::value > = 0); /// Read data into a dynamic buffer sequence until it contains a specified /// delimiter. /** * This function is used to read data into the specified dynamic buffer * sequence until the dynamic buffer sequence's get area contains the specified * delimiter. The call will block until one of the following conditions is * true: * * @li The get area of the dynamic buffer sequence contains the specified * delimiter. * * @li An error occurred. * * This operation is implemented in terms of zero or more calls to the stream's * read_some function. If the dynamic buffer sequence's get area already * contains the delimiter, the function returns immediately. * * @param s The stream from which the data is to be read. The type must support * the SyncReadStream concept. * * @param buffers The dynamic buffer sequence into which the data will be read. * * @param delim The delimiter string. * * @returns The number of bytes in the dynamic buffer sequence's get area up to * and including the delimiter. * * @note After a successful read_until operation, the dynamic buffer sequence * may contain additional data beyond the delimiter. An application will * typically leave that data in the dynamic buffer sequence for a subsequent * read_until operation to examine. * * @par Example * To read data into a @c std::string until a CR-LF sequence is encountered: * @code std::string data; * std::size_t n = asio::read_until(s, * asio::dynamic_buffer(data), "\r\n"); * std::string line = data.substr(0, n); * data.erase(0, n); @endcode * After the @c read_until operation completes successfully, the string @c data * contains the delimiter: * @code { 'a', 'b', ..., 'c', '\r', '\n', 'd', 'e', ... } @endcode * The call to @c substr then extracts the data up to and including the * delimiter, so that the string @c line contains: * @code { 'a', 'b', ..., 'c', '\r', '\n' } @endcode * After the call to @c erase, the remaining data is left in the buffer @c b as * follows: * @code { 'd', 'e', ... } @endcode * This data may be the start of a new line, to be extracted by a subsequent * @c read_until operation. */ template <typename SyncReadStream, typename DynamicBuffer_v1> std::size_t read_until(SyncReadStream& s, DynamicBuffer_v1&& buffers, ASIO_STRING_VIEW_PARAM delim, constraint_t< is_dynamic_buffer_v1<decay_t<DynamicBuffer_v1>>::value > = 0, constraint_t< !is_dynamic_buffer_v2<decay_t<DynamicBuffer_v1>>::value > = 0); /// Read data into a dynamic buffer sequence until it contains a specified /// delimiter. /** * This function is used to read data into the specified dynamic buffer * sequence until the dynamic buffer sequence's get area contains the specified * delimiter. The call will block until one of the following conditions is * true: * * @li The get area of the dynamic buffer sequence contains the specified * delimiter. * * @li An error occurred. * * This operation is implemented in terms of zero or more calls to the stream's * read_some function. If the dynamic buffer sequence's get area already * contains the delimiter, the function returns immediately. * * @param s The stream from which the data is to be read. The type must support * the SyncReadStream concept. * * @param buffers The dynamic buffer sequence into which the data will be read. * * @param delim The delimiter string. * * @param ec Set to indicate what error occurred, if any. * * @returns The number of bytes in the dynamic buffer sequence's get area up to * and including the delimiter. Returns 0 if an error occurred. * * @note After a successful read_until operation, the dynamic buffer sequence * may contain additional data beyond the delimiter. An application will * typically leave that data in the dynamic buffer sequence for a subsequent * read_until operation to examine. */ template <typename SyncReadStream, typename DynamicBuffer_v1> std::size_t read_until(SyncReadStream& s, DynamicBuffer_v1&& buffers, ASIO_STRING_VIEW_PARAM delim, asio::error_code& ec, constraint_t< is_dynamic_buffer_v1<decay_t<DynamicBuffer_v1>>::value > = 0, constraint_t< !is_dynamic_buffer_v2<decay_t<DynamicBuffer_v1>>::value > = 0); #if !defined(ASIO_NO_EXTENSIONS) #if defined(ASIO_HAS_BOOST_REGEX) \ || defined(GENERATING_DOCUMENTATION) /// Read data into a dynamic buffer sequence until some part of the data it /// contains matches a regular expression. /** * This function is used to read data into the specified dynamic buffer * sequence until the dynamic buffer sequence's get area contains some data * that matches a regular expression. The call will block until one of the * following conditions is true: * * @li A substring of the dynamic buffer sequence's get area matches the * regular expression. * * @li An error occurred. * * This operation is implemented in terms of zero or more calls to the stream's * read_some function. If the dynamic buffer sequence's get area already * contains data that matches the regular expression, the function returns * immediately. * * @param s The stream from which the data is to be read. The type must support * the SyncReadStream concept. * * @param buffers A dynamic buffer sequence into which the data will be read. * * @param expr The regular expression. * * @returns The number of bytes in the dynamic buffer sequence's get area up to * and including the substring that matches the regular expression. * * @throws asio::system_error Thrown on failure. * * @note After a successful read_until operation, the dynamic buffer sequence * may contain additional data beyond that which matched the regular * expression. An application will typically leave that data in the dynamic * buffer sequence for a subsequent read_until operation to examine. * * @par Example * To read data into a @c std::string until a CR-LF sequence is encountered: * @code std::string data; * std::size_t n = asio::read_until(s, * asio::dynamic_buffer(data), boost::regex("\r\n")); * std::string line = data.substr(0, n); * data.erase(0, n); @endcode * After the @c read_until operation completes successfully, the string @c data * contains the delimiter: * @code { 'a', 'b', ..., 'c', '\r', '\n', 'd', 'e', ... } @endcode * The call to @c substr then extracts the data up to and including the * delimiter, so that the string @c line contains: * @code { 'a', 'b', ..., 'c', '\r', '\n' } @endcode * After the call to @c erase, the remaining data is left in the buffer @c b as * follows: * @code { 'd', 'e', ... } @endcode * This data may be the start of a new line, to be extracted by a subsequent * @c read_until operation. */ template <typename SyncReadStream, typename DynamicBuffer_v1, typename Traits> std::size_t read_until(SyncReadStream& s, DynamicBuffer_v1&& buffers, const boost::basic_regex<char, Traits>& expr, constraint_t< is_dynamic_buffer_v1<decay_t<DynamicBuffer_v1>>::value > = 0, constraint_t< !is_dynamic_buffer_v2<decay_t<DynamicBuffer_v1>>::value > = 0); /// Read data into a dynamic buffer sequence until some part of the data it /// contains matches a regular expression. /** * This function is used to read data into the specified dynamic buffer * sequence until the dynamic buffer sequence's get area contains some data * that matches a regular expression. The call will block until one of the * following conditions is true: * * @li A substring of the dynamic buffer sequence's get area matches the * regular expression. * * @li An error occurred. * * This operation is implemented in terms of zero or more calls to the stream's * read_some function. If the dynamic buffer sequence's get area already * contains data that matches the regular expression, the function returns * immediately. * * @param s The stream from which the data is to be read. The type must support * the SyncReadStream concept. * * @param buffers A dynamic buffer sequence into which the data will be read. * * @param expr The regular expression. * * @param ec Set to indicate what error occurred, if any. * * @returns The number of bytes in the dynamic buffer sequence's get area up to * and including the substring that matches the regular expression. Returns 0 * if an error occurred. * * @note After a successful read_until operation, the dynamic buffer sequence * may contain additional data beyond that which matched the regular * expression. An application will typically leave that data in the dynamic * buffer sequence for a subsequent read_until operation to examine. */ template <typename SyncReadStream, typename DynamicBuffer_v1, typename Traits> std::size_t read_until(SyncReadStream& s, DynamicBuffer_v1&& buffers, const boost::basic_regex<char, Traits>& expr, asio::error_code& ec, constraint_t< is_dynamic_buffer_v1<decay_t<DynamicBuffer_v1>>::value > = 0, constraint_t< !is_dynamic_buffer_v2<decay_t<DynamicBuffer_v1>>::value > = 0); #endif // defined(ASIO_HAS_BOOST_REGEX) // || defined(GENERATING_DOCUMENTATION) /// Read data into a dynamic buffer sequence until a function object indicates a /// match. /** * This function is used to read data into the specified dynamic buffer * sequence until a user-defined match condition function object, when applied * to the data contained in the dynamic buffer sequence, indicates a successful * match. The call will block until one of the following conditions is true: * * @li The match condition function object returns a std::pair where the second * element evaluates to true. * * @li An error occurred. * * This operation is implemented in terms of zero or more calls to the stream's * read_some function. If the match condition function object already indicates * a match, the function returns immediately. * * @param s The stream from which the data is to be read. The type must support * the SyncReadStream concept. * * @param buffers A dynamic buffer sequence into which the data will be read. * * @param match_condition The function object to be called to determine whether * a match exists. The signature of the function object must be: * @code pair<iterator, bool> match_condition(iterator begin, iterator end); * @endcode * where @c iterator represents the type: * @code buffers_iterator<typename DynamicBuffer_v1::const_buffers_type> * @endcode * The iterator parameters @c begin and @c end define the range of bytes to be * scanned to determine whether there is a match. The @c first member of the * return value is an iterator marking one-past-the-end of the bytes that have * been consumed by the match function. This iterator is used to calculate the * @c begin parameter for any subsequent invocation of the match condition. The * @c second member of the return value is true if a match has been found, false * otherwise. * * @returns The number of bytes in the dynamic_buffer's get area that * have been fully consumed by the match function. * * @throws asio::system_error Thrown on failure. * * @note After a successful read_until operation, the dynamic buffer sequence * may contain additional data beyond that which matched the function object. * An application will typically leave that data in the dynamic buffer sequence * for a subsequent read_until operation to examine. * @note The default implementation of the @c is_match_condition type trait * evaluates to true for function pointers and function objects with a * @c result_type typedef. It must be specialised for other user-defined * function objects. * * @par Examples * To read data into a dynamic buffer sequence until whitespace is encountered: * @code typedef asio::buffers_iterator< * asio::const_buffers_1> iterator; * * std::pair<iterator, bool> * match_whitespace(iterator begin, iterator end) * { * iterator i = begin; * while (i != end) * if (std::isspace(*i++)) * return std::make_pair(i, true); * return std::make_pair(i, false); * } * ... * std::string data; * asio::read_until(s, data, match_whitespace); * @endcode * * To read data into a @c std::string until a matching character is found: * @code class match_char * { * public: * explicit match_char(char c) : c_(c) {} * * template <typename Iterator> * std::pair<Iterator, bool> operator()( * Iterator begin, Iterator end) const * { * Iterator i = begin; * while (i != end) * if (c_ == *i++) * return std::make_pair(i, true); * return std::make_pair(i, false); * } * * private: * char c_; * }; * * namespace asio { * template <> struct is_match_condition<match_char> * : public boost::true_type {}; * } // namespace asio * ... * std::string data; * asio::read_until(s, data, match_char('a')); * @endcode */ template <typename SyncReadStream, typename DynamicBuffer_v1, typename MatchCondition> std::size_t read_until(SyncReadStream& s, DynamicBuffer_v1&& buffers, MatchCondition match_condition, constraint_t< is_match_condition<MatchCondition>::value > = 0, constraint_t< is_dynamic_buffer_v1<decay_t<DynamicBuffer_v1>>::value > = 0, constraint_t< !is_dynamic_buffer_v2<decay_t<DynamicBuffer_v1>>::value > = 0); /// Read data into a dynamic buffer sequence until a function object indicates a /// match. /** * This function is used to read data into the specified dynamic buffer * sequence until a user-defined match condition function object, when applied * to the data contained in the dynamic buffer sequence, indicates a successful * match. The call will block until one of the following conditions is true: * * @li The match condition function object returns a std::pair where the second * element evaluates to true. * * @li An error occurred. * * This operation is implemented in terms of zero or more calls to the stream's * read_some function. If the match condition function object already indicates * a match, the function returns immediately. * * @param s The stream from which the data is to be read. The type must support * the SyncReadStream concept. * * @param buffers A dynamic buffer sequence into which the data will be read. * * @param match_condition The function object to be called to determine whether * a match exists. The signature of the function object must be: * @code pair<iterator, bool> match_condition(iterator begin, iterator end); * @endcode * where @c iterator represents the type: * @code buffers_iterator<DynamicBuffer_v1::const_buffers_type> * @endcode * The iterator parameters @c begin and @c end define the range of bytes to be * scanned to determine whether there is a match. The @c first member of the * return value is an iterator marking one-past-the-end of the bytes that have * been consumed by the match function. This iterator is used to calculate the * @c begin parameter for any subsequent invocation of the match condition. The * @c second member of the return value is true if a match has been found, false * otherwise. * * @param ec Set to indicate what error occurred, if any. * * @returns The number of bytes in the dynamic buffer sequence's get area that * have been fully consumed by the match function. Returns 0 if an error * occurred. * * @note After a successful read_until operation, the dynamic buffer sequence * may contain additional data beyond that which matched the function object. * An application will typically leave that data in the dynamic buffer sequence * for a subsequent read_until operation to examine. * * @note The default implementation of the @c is_match_condition type trait * evaluates to true for function pointers and function objects with a * @c result_type typedef. It must be specialised for other user-defined * function objects. */ template <typename SyncReadStream, typename DynamicBuffer_v1, typename MatchCondition> std::size_t read_until(SyncReadStream& s, DynamicBuffer_v1&& buffers, MatchCondition match_condition, asio::error_code& ec, constraint_t< is_match_condition<MatchCondition>::value > = 0, constraint_t< is_dynamic_buffer_v1<decay_t<DynamicBuffer_v1>>::value > = 0, constraint_t< !is_dynamic_buffer_v2<decay_t<DynamicBuffer_v1>>::value > = 0); #if !defined(ASIO_NO_IOSTREAM) /// Read data into a streambuf until it contains a specified delimiter. /** * This function is used to read data into the specified streambuf until the * streambuf's get area contains the specified delimiter. The call will block * until one of the following conditions is true: * * @li The get area of the streambuf contains the specified delimiter. * * @li An error occurred. * * This operation is implemented in terms of zero or more calls to the stream's * read_some function. If the streambuf's get area already contains the * delimiter, the function returns immediately. * * @param s The stream from which the data is to be read. The type must support * the SyncReadStream concept. * * @param b A streambuf object into which the data will be read. * * @param delim The delimiter character. * * @returns The number of bytes in the streambuf's get area up to and including * the delimiter. * * @throws asio::system_error Thrown on failure. * * @note After a successful read_until operation, the streambuf may contain * additional data beyond the delimiter. An application will typically leave * that data in the streambuf for a subsequent read_until operation to examine. * * @par Example * To read data into a streambuf until a newline is encountered: * @code asio::streambuf b; * asio::read_until(s, b, '\n'); * std::istream is(&b); * std::string line; * std::getline(is, line); @endcode * After the @c read_until operation completes successfully, the buffer @c b * contains the delimiter: * @code { 'a', 'b', ..., 'c', '\n', 'd', 'e', ... } @endcode * The call to @c std::getline then extracts the data up to and including the * newline (which is discarded), so that the string @c line contains: * @code { 'a', 'b', ..., 'c' } @endcode * The remaining data is left in the buffer @c b as follows: * @code { 'd', 'e', ... } @endcode * This data may be the start of a new line, to be extracted by a subsequent * @c read_until operation. */ template <typename SyncReadStream, typename Allocator> std::size_t read_until(SyncReadStream& s, asio::basic_streambuf<Allocator>& b, char delim); /// Read data into a streambuf until it contains a specified delimiter. /** * This function is used to read data into the specified streambuf until the * streambuf's get area contains the specified delimiter. The call will block * until one of the following conditions is true: * * @li The get area of the streambuf contains the specified delimiter. * * @li An error occurred. * * This operation is implemented in terms of zero or more calls to the stream's * read_some function. If the streambuf's get area already contains the * delimiter, the function returns immediately. * * @param s The stream from which the data is to be read. The type must support * the SyncReadStream concept. * * @param b A streambuf object into which the data will be read. * * @param delim The delimiter character. * * @param ec Set to indicate what error occurred, if any. * * @returns The number of bytes in the streambuf's get area up to and including * the delimiter. Returns 0 if an error occurred. * * @note After a successful read_until operation, the streambuf may contain * additional data beyond the delimiter. An application will typically leave * that data in the streambuf for a subsequent read_until operation to examine. */ template <typename SyncReadStream, typename Allocator> std::size_t read_until(SyncReadStream& s, asio::basic_streambuf<Allocator>& b, char delim, asio::error_code& ec); /// Read data into a streambuf until it contains a specified delimiter. /** * This function is used to read data into the specified streambuf until the * streambuf's get area contains the specified delimiter. The call will block * until one of the following conditions is true: * * @li The get area of the streambuf contains the specified delimiter. * * @li An error occurred. * * This operation is implemented in terms of zero or more calls to the stream's * read_some function. If the streambuf's get area already contains the * delimiter, the function returns immediately. * * @param s The stream from which the data is to be read. The type must support * the SyncReadStream concept. * * @param b A streambuf object into which the data will be read. * * @param delim The delimiter string. * * @returns The number of bytes in the streambuf's get area up to and including * the delimiter. * * @throws asio::system_error Thrown on failure. * * @note After a successful read_until operation, the streambuf may contain * additional data beyond the delimiter. An application will typically leave * that data in the streambuf for a subsequent read_until operation to examine. * * @par Example * To read data into a streambuf until a newline is encountered: * @code asio::streambuf b; * asio::read_until(s, b, "\r\n"); * std::istream is(&b); * std::string line; * std::getline(is, line); @endcode * After the @c read_until operation completes successfully, the buffer @c b * contains the delimiter: * @code { 'a', 'b', ..., 'c', '\r', '\n', 'd', 'e', ... } @endcode * The call to @c std::getline then extracts the data up to and including the * newline (which is discarded), so that the string @c line contains: * @code { 'a', 'b', ..., 'c', '\r' } @endcode * The remaining data is left in the buffer @c b as follows: * @code { 'd', 'e', ... } @endcode * This data may be the start of a new line, to be extracted by a subsequent * @c read_until operation. */ template <typename SyncReadStream, typename Allocator> std::size_t read_until(SyncReadStream& s, asio::basic_streambuf<Allocator>& b, ASIO_STRING_VIEW_PARAM delim); /// Read data into a streambuf until it contains a specified delimiter. /** * This function is used to read data into the specified streambuf until the * streambuf's get area contains the specified delimiter. The call will block * until one of the following conditions is true: * * @li The get area of the streambuf contains the specified delimiter. * * @li An error occurred. * * This operation is implemented in terms of zero or more calls to the stream's * read_some function. If the streambuf's get area already contains the * delimiter, the function returns immediately. * * @param s The stream from which the data is to be read. The type must support * the SyncReadStream concept. * * @param b A streambuf object into which the data will be read. * * @param delim The delimiter string. * * @param ec Set to indicate what error occurred, if any. * * @returns The number of bytes in the streambuf's get area up to and including * the delimiter. Returns 0 if an error occurred. * * @note After a successful read_until operation, the streambuf may contain * additional data beyond the delimiter. An application will typically leave * that data in the streambuf for a subsequent read_until operation to examine. */ template <typename SyncReadStream, typename Allocator> std::size_t read_until(SyncReadStream& s, asio::basic_streambuf<Allocator>& b, ASIO_STRING_VIEW_PARAM delim, asio::error_code& ec); #if defined(ASIO_HAS_BOOST_REGEX) \ || defined(GENERATING_DOCUMENTATION) /// Read data into a streambuf until some part of the data it contains matches /// a regular expression. /** * This function is used to read data into the specified streambuf until the * streambuf's get area contains some data that matches a regular expression. * The call will block until one of the following conditions is true: * * @li A substring of the streambuf's get area matches the regular expression. * * @li An error occurred. * * This operation is implemented in terms of zero or more calls to the stream's * read_some function. If the streambuf's get area already contains data that * matches the regular expression, the function returns immediately. * * @param s The stream from which the data is to be read. The type must support * the SyncReadStream concept. * * @param b A streambuf object into which the data will be read. * * @param expr The regular expression. * * @returns The number of bytes in the streambuf's get area up to and including * the substring that matches the regular expression. * * @throws asio::system_error Thrown on failure. * * @note After a successful read_until operation, the streambuf may contain * additional data beyond that which matched the regular expression. An * application will typically leave that data in the streambuf for a subsequent * read_until operation to examine. * * @par Example * To read data into a streambuf until a CR-LF sequence is encountered: * @code asio::streambuf b; * asio::read_until(s, b, boost::regex("\r\n")); * std::istream is(&b); * std::string line; * std::getline(is, line); @endcode * After the @c read_until operation completes successfully, the buffer @c b * contains the data which matched the regular expression: * @code { 'a', 'b', ..., 'c', '\r', '\n', 'd', 'e', ... } @endcode * The call to @c std::getline then extracts the data up to and including the * newline (which is discarded), so that the string @c line contains: * @code { 'a', 'b', ..., 'c', '\r' } @endcode * The remaining data is left in the buffer @c b as follows: * @code { 'd', 'e', ... } @endcode * This data may be the start of a new line, to be extracted by a subsequent * @c read_until operation. */ template <typename SyncReadStream, typename Allocator, typename Traits> std::size_t read_until(SyncReadStream& s, asio::basic_streambuf<Allocator>& b, const boost::basic_regex<char, Traits>& expr); /// Read data into a streambuf until some part of the data it contains matches /// a regular expression. /** * This function is used to read data into the specified streambuf until the * streambuf's get area contains some data that matches a regular expression. * The call will block until one of the following conditions is true: * * @li A substring of the streambuf's get area matches the regular expression. * * @li An error occurred. * * This operation is implemented in terms of zero or more calls to the stream's * read_some function. If the streambuf's get area already contains data that * matches the regular expression, the function returns immediately. * * @param s The stream from which the data is to be read. The type must support * the SyncReadStream concept. * * @param b A streambuf object into which the data will be read. * * @param expr The regular expression. * * @param ec Set to indicate what error occurred, if any. * * @returns The number of bytes in the streambuf's get area up to and including * the substring that matches the regular expression. Returns 0 if an error * occurred. * * @note After a successful read_until operation, the streambuf may contain * additional data beyond that which matched the regular expression. An * application will typically leave that data in the streambuf for a subsequent * read_until operation to examine. */ template <typename SyncReadStream, typename Allocator, typename Traits> std::size_t read_until(SyncReadStream& s, asio::basic_streambuf<Allocator>& b, const boost::basic_regex<char, Traits>& expr, asio::error_code& ec); #endif // defined(ASIO_HAS_BOOST_REGEX) // || defined(GENERATING_DOCUMENTATION) /// Read data into a streambuf until a function object indicates a match. /** * This function is used to read data into the specified streambuf until a * user-defined match condition function object, when applied to the data * contained in the streambuf, indicates a successful match. The call will * block until one of the following conditions is true: * * @li The match condition function object returns a std::pair where the second * element evaluates to true. * * @li An error occurred. * * This operation is implemented in terms of zero or more calls to the stream's * read_some function. If the match condition function object already indicates * a match, the function returns immediately. * * @param s The stream from which the data is to be read. The type must support * the SyncReadStream concept. * * @param b A streambuf object into which the data will be read. * * @param match_condition The function object to be called to determine whether * a match exists. The signature of the function object must be: * @code pair<iterator, bool> match_condition(iterator begin, iterator end); * @endcode * where @c iterator represents the type: * @code buffers_iterator<basic_streambuf<Allocator>::const_buffers_type> * @endcode * The iterator parameters @c begin and @c end define the range of bytes to be * scanned to determine whether there is a match. The @c first member of the * return value is an iterator marking one-past-the-end of the bytes that have * been consumed by the match function. This iterator is used to calculate the * @c begin parameter for any subsequent invocation of the match condition. The * @c second member of the return value is true if a match has been found, false * otherwise. * * @returns The number of bytes in the streambuf's get area that have been fully * consumed by the match function. * * @throws asio::system_error Thrown on failure. * * @note After a successful read_until operation, the streambuf may contain * additional data beyond that which matched the function object. An application * will typically leave that data in the streambuf for a subsequent read_until * operation to examine. * * @note The default implementation of the @c is_match_condition type trait * evaluates to true for function pointers and function objects with a * @c result_type typedef. It must be specialised for other user-defined * function objects. * * @par Examples * To read data into a streambuf until whitespace is encountered: * @code typedef asio::buffers_iterator< * asio::streambuf::const_buffers_type> iterator; * * std::pair<iterator, bool> * match_whitespace(iterator begin, iterator end) * { * iterator i = begin; * while (i != end) * if (std::isspace(*i++)) * return std::make_pair(i, true); * return std::make_pair(i, false); * } * ... * asio::streambuf b; * asio::read_until(s, b, match_whitespace); * @endcode * * To read data into a streambuf until a matching character is found: * @code class match_char * { * public: * explicit match_char(char c) : c_(c) {} * * template <typename Iterator> * std::pair<Iterator, bool> operator()( * Iterator begin, Iterator end) const * { * Iterator i = begin; * while (i != end) * if (c_ == *i++) * return std::make_pair(i, true); * return std::make_pair(i, false); * } * * private: * char c_; * }; * * namespace asio { * template <> struct is_match_condition<match_char> * : public boost::true_type {}; * } // namespace asio * ... * asio::streambuf b; * asio::read_until(s, b, match_char('a')); * @endcode */ template <typename SyncReadStream, typename Allocator, typename MatchCondition> std::size_t read_until(SyncReadStream& s, asio::basic_streambuf<Allocator>& b, MatchCondition match_condition, constraint_t<is_match_condition<MatchCondition>::value> = 0); /// Read data into a streambuf until a function object indicates a match. /** * This function is used to read data into the specified streambuf until a * user-defined match condition function object, when applied to the data * contained in the streambuf, indicates a successful match. The call will * block until one of the following conditions is true: * * @li The match condition function object returns a std::pair where the second * element evaluates to true. * * @li An error occurred. * * This operation is implemented in terms of zero or more calls to the stream's * read_some function. If the match condition function object already indicates * a match, the function returns immediately. * * @param s The stream from which the data is to be read. The type must support * the SyncReadStream concept. * * @param b A streambuf object into which the data will be read. * * @param match_condition The function object to be called to determine whether * a match exists. The signature of the function object must be: * @code pair<iterator, bool> match_condition(iterator begin, iterator end); * @endcode * where @c iterator represents the type: * @code buffers_iterator<basic_streambuf<Allocator>::const_buffers_type> * @endcode * The iterator parameters @c begin and @c end define the range of bytes to be * scanned to determine whether there is a match. The @c first member of the * return value is an iterator marking one-past-the-end of the bytes that have * been consumed by the match function. This iterator is used to calculate the * @c begin parameter for any subsequent invocation of the match condition. The * @c second member of the return value is true if a match has been found, false * otherwise. * * @param ec Set to indicate what error occurred, if any. * * @returns The number of bytes in the streambuf's get area that have been fully * consumed by the match function. Returns 0 if an error occurred. * * @note After a successful read_until operation, the streambuf may contain * additional data beyond that which matched the function object. An application * will typically leave that data in the streambuf for a subsequent read_until * operation to examine. * * @note The default implementation of the @c is_match_condition type trait * evaluates to true for function pointers and function objects with a * @c result_type typedef. It must be specialised for other user-defined * function objects. */ template <typename SyncReadStream, typename Allocator, typename MatchCondition> std::size_t read_until(SyncReadStream& s, asio::basic_streambuf<Allocator>& b, MatchCondition match_condition, asio::error_code& ec, constraint_t<is_match_condition<MatchCondition>::value> = 0); #endif // !defined(ASIO_NO_IOSTREAM) #endif // !defined(ASIO_NO_EXTENSIONS) #endif // !defined(ASIO_NO_DYNAMIC_BUFFER_V1) /// Read data into a dynamic buffer sequence until it contains a specified /// delimiter. /** * This function is used to read data into the specified dynamic buffer * sequence until the dynamic buffer sequence's get area contains the specified * delimiter. The call will block until one of the following conditions is * true: * * @li The get area of the dynamic buffer sequence contains the specified * delimiter. * * @li An error occurred. * * This operation is implemented in terms of zero or more calls to the stream's * read_some function. If the dynamic buffer sequence's get area already * contains the delimiter, the function returns immediately. * * @param s The stream from which the data is to be read. The type must support * the SyncReadStream concept. * * @param buffers The dynamic buffer sequence into which the data will be read. * * @param delim The delimiter character. * * @returns The number of bytes in the dynamic buffer sequence's get area up to * and including the delimiter. * * @throws asio::system_error Thrown on failure. * * @note After a successful read_until operation, the dynamic buffer sequence * may contain additional data beyond the delimiter. An application will * typically leave that data in the dynamic buffer sequence for a subsequent * read_until operation to examine. * * @par Example * To read data into a @c std::string until a newline is encountered: * @code std::string data; * std::size_t n = asio::read_until(s, * asio::dynamic_buffer(data), '\n'); * std::string line = data.substr(0, n); * data.erase(0, n); @endcode * After the @c read_until operation completes successfully, the string @c data * contains the delimiter: * @code { 'a', 'b', ..., 'c', '\n', 'd', 'e', ... } @endcode * The call to @c substr then extracts the data up to and including the * delimiter, so that the string @c line contains: * @code { 'a', 'b', ..., 'c', '\n' } @endcode * After the call to @c erase, the remaining data is left in the buffer @c b as * follows: * @code { 'd', 'e', ... } @endcode * This data may be the start of a new line, to be extracted by a subsequent * @c read_until operation. */ template <typename SyncReadStream, typename DynamicBuffer_v2> std::size_t read_until(SyncReadStream& s, DynamicBuffer_v2 buffers, char delim, constraint_t< is_dynamic_buffer_v2<DynamicBuffer_v2>::value > = 0); /// Read data into a dynamic buffer sequence until it contains a specified /// delimiter. /** * This function is used to read data into the specified dynamic buffer * sequence until the dynamic buffer sequence's get area contains the specified * delimiter. The call will block until one of the following conditions is * true: * * @li The get area of the dynamic buffer sequence contains the specified * delimiter. * * @li An error occurred. * * This operation is implemented in terms of zero or more calls to the stream's * read_some function. If the dynamic buffer sequence's get area already * contains the delimiter, the function returns immediately. * * @param s The stream from which the data is to be read. The type must support * the SyncReadStream concept. * * @param buffers The dynamic buffer sequence into which the data will be read. * * @param delim The delimiter character. * * @param ec Set to indicate what error occurred, if any. * * @returns The number of bytes in the dynamic buffer sequence's get area up to * and including the delimiter. Returns 0 if an error occurred. * * @note After a successful read_until operation, the dynamic buffer sequence * may contain additional data beyond the delimiter. An application will * typically leave that data in the dynamic buffer sequence for a subsequent * read_until operation to examine. */ template <typename SyncReadStream, typename DynamicBuffer_v2> std::size_t read_until(SyncReadStream& s, DynamicBuffer_v2 buffers, char delim, asio::error_code& ec, constraint_t< is_dynamic_buffer_v2<DynamicBuffer_v2>::value > = 0); /// Read data into a dynamic buffer sequence until it contains a specified /// delimiter. /** * This function is used to read data into the specified dynamic buffer * sequence until the dynamic buffer sequence's get area contains the specified * delimiter. The call will block until one of the following conditions is * true: * * @li The get area of the dynamic buffer sequence contains the specified * delimiter. * * @li An error occurred. * * This operation is implemented in terms of zero or more calls to the stream's * read_some function. If the dynamic buffer sequence's get area already * contains the delimiter, the function returns immediately. * * @param s The stream from which the data is to be read. The type must support * the SyncReadStream concept. * * @param buffers The dynamic buffer sequence into which the data will be read. * * @param delim The delimiter string. * * @returns The number of bytes in the dynamic buffer sequence's get area up to * and including the delimiter. * * @note After a successful read_until operation, the dynamic buffer sequence * may contain additional data beyond the delimiter. An application will * typically leave that data in the dynamic buffer sequence for a subsequent * read_until operation to examine. * * @par Example * To read data into a @c std::string until a CR-LF sequence is encountered: * @code std::string data; * std::size_t n = asio::read_until(s, * asio::dynamic_buffer(data), "\r\n"); * std::string line = data.substr(0, n); * data.erase(0, n); @endcode * After the @c read_until operation completes successfully, the string @c data * contains the delimiter: * @code { 'a', 'b', ..., 'c', '\r', '\n', 'd', 'e', ... } @endcode * The call to @c substr then extracts the data up to and including the * delimiter, so that the string @c line contains: * @code { 'a', 'b', ..., 'c', '\r', '\n' } @endcode * After the call to @c erase, the remaining data is left in the buffer @c b as * follows: * @code { 'd', 'e', ... } @endcode * This data may be the start of a new line, to be extracted by a subsequent * @c read_until operation. */ template <typename SyncReadStream, typename DynamicBuffer_v2> std::size_t read_until(SyncReadStream& s, DynamicBuffer_v2 buffers, ASIO_STRING_VIEW_PARAM delim, constraint_t< is_dynamic_buffer_v2<DynamicBuffer_v2>::value > = 0); /// Read data into a dynamic buffer sequence until it contains a specified /// delimiter. /** * This function is used to read data into the specified dynamic buffer * sequence until the dynamic buffer sequence's get area contains the specified * delimiter. The call will block until one of the following conditions is * true: * * @li The get area of the dynamic buffer sequence contains the specified * delimiter. * * @li An error occurred. * * This operation is implemented in terms of zero or more calls to the stream's * read_some function. If the dynamic buffer sequence's get area already * contains the delimiter, the function returns immediately. * * @param s The stream from which the data is to be read. The type must support * the SyncReadStream concept. * * @param buffers The dynamic buffer sequence into which the data will be read. * * @param delim The delimiter string. * * @param ec Set to indicate what error occurred, if any. * * @returns The number of bytes in the dynamic buffer sequence's get area up to * and including the delimiter. Returns 0 if an error occurred. * * @note After a successful read_until operation, the dynamic buffer sequence * may contain additional data beyond the delimiter. An application will * typically leave that data in the dynamic buffer sequence for a subsequent * read_until operation to examine. */ template <typename SyncReadStream, typename DynamicBuffer_v2> std::size_t read_until(SyncReadStream& s, DynamicBuffer_v2 buffers, ASIO_STRING_VIEW_PARAM delim, asio::error_code& ec, constraint_t< is_dynamic_buffer_v2<DynamicBuffer_v2>::value > = 0); #if !defined(ASIO_NO_EXTENSIONS) #if defined(ASIO_HAS_BOOST_REGEX) \ || defined(GENERATING_DOCUMENTATION) /// Read data into a dynamic buffer sequence until some part of the data it /// contains matches a regular expression. /** * This function is used to read data into the specified dynamic buffer * sequence until the dynamic buffer sequence's get area contains some data * that matches a regular expression. The call will block until one of the * following conditions is true: * * @li A substring of the dynamic buffer sequence's get area matches the * regular expression. * * @li An error occurred. * * This operation is implemented in terms of zero or more calls to the stream's * read_some function. If the dynamic buffer sequence's get area already * contains data that matches the regular expression, the function returns * immediately. * * @param s The stream from which the data is to be read. The type must support * the SyncReadStream concept. * * @param buffers A dynamic buffer sequence into which the data will be read. * * @param expr The regular expression. * * @returns The number of bytes in the dynamic buffer sequence's get area up to * and including the substring that matches the regular expression. * * @throws asio::system_error Thrown on failure. * * @note After a successful read_until operation, the dynamic buffer sequence * may contain additional data beyond that which matched the regular * expression. An application will typically leave that data in the dynamic * buffer sequence for a subsequent read_until operation to examine. * * @par Example * To read data into a @c std::string until a CR-LF sequence is encountered: * @code std::string data; * std::size_t n = asio::read_until(s, * asio::dynamic_buffer(data), boost::regex("\r\n")); * std::string line = data.substr(0, n); * data.erase(0, n); @endcode * After the @c read_until operation completes successfully, the string @c data * contains the delimiter: * @code { 'a', 'b', ..., 'c', '\r', '\n', 'd', 'e', ... } @endcode * The call to @c substr then extracts the data up to and including the * delimiter, so that the string @c line contains: * @code { 'a', 'b', ..., 'c', '\r', '\n' } @endcode * After the call to @c erase, the remaining data is left in the buffer @c b as * follows: * @code { 'd', 'e', ... } @endcode * This data may be the start of a new line, to be extracted by a subsequent * @c read_until operation. */ template <typename SyncReadStream, typename DynamicBuffer_v2, typename Traits> std::size_t read_until(SyncReadStream& s, DynamicBuffer_v2 buffers, const boost::basic_regex<char, Traits>& expr, constraint_t< is_dynamic_buffer_v2<DynamicBuffer_v2>::value > = 0); /// Read data into a dynamic buffer sequence until some part of the data it /// contains matches a regular expression. /** * This function is used to read data into the specified dynamic buffer * sequence until the dynamic buffer sequence's get area contains some data * that matches a regular expression. The call will block until one of the * following conditions is true: * * @li A substring of the dynamic buffer sequence's get area matches the * regular expression. * * @li An error occurred. * * This operation is implemented in terms of zero or more calls to the stream's * read_some function. If the dynamic buffer sequence's get area already * contains data that matches the regular expression, the function returns * immediately. * * @param s The stream from which the data is to be read. The type must support * the SyncReadStream concept. * * @param buffers A dynamic buffer sequence into which the data will be read. * * @param expr The regular expression. * * @param ec Set to indicate what error occurred, if any. * * @returns The number of bytes in the dynamic buffer sequence's get area up to * and including the substring that matches the regular expression. Returns 0 * if an error occurred. * * @note After a successful read_until operation, the dynamic buffer sequence * may contain additional data beyond that which matched the regular * expression. An application will typically leave that data in the dynamic * buffer sequence for a subsequent read_until operation to examine. */ template <typename SyncReadStream, typename DynamicBuffer_v2, typename Traits> std::size_t read_until(SyncReadStream& s, DynamicBuffer_v2 buffers, const boost::basic_regex<char, Traits>& expr, asio::error_code& ec, constraint_t< is_dynamic_buffer_v2<DynamicBuffer_v2>::value > = 0); #endif // defined(ASIO_HAS_BOOST_REGEX) // || defined(GENERATING_DOCUMENTATION) /// Read data into a dynamic buffer sequence until a function object indicates a /// match. /** * This function is used to read data into the specified dynamic buffer * sequence until a user-defined match condition function object, when applied * to the data contained in the dynamic buffer sequence, indicates a successful * match. The call will block until one of the following conditions is true: * * @li The match condition function object returns a std::pair where the second * element evaluates to true. * * @li An error occurred. * * This operation is implemented in terms of zero or more calls to the stream's * read_some function. If the match condition function object already indicates * a match, the function returns immediately. * * @param s The stream from which the data is to be read. The type must support * the SyncReadStream concept. * * @param buffers A dynamic buffer sequence into which the data will be read. * * @param match_condition The function object to be called to determine whether * a match exists. The signature of the function object must be: * @code pair<iterator, bool> match_condition(iterator begin, iterator end); * @endcode * where @c iterator represents the type: * @code buffers_iterator<typename DynamicBuffer_v2::const_buffers_type> * @endcode * The iterator parameters @c begin and @c end define the range of bytes to be * scanned to determine whether there is a match. The @c first member of the * return value is an iterator marking one-past-the-end of the bytes that have * been consumed by the match function. This iterator is used to calculate the * @c begin parameter for any subsequent invocation of the match condition. The * @c second member of the return value is true if a match has been found, false * otherwise. * * @returns The number of bytes in the dynamic_buffer's get area that * have been fully consumed by the match function. * * @throws asio::system_error Thrown on failure. * * @note After a successful read_until operation, the dynamic buffer sequence * may contain additional data beyond that which matched the function object. * An application will typically leave that data in the dynamic buffer sequence * for a subsequent read_until operation to examine. * @note The default implementation of the @c is_match_condition type trait * evaluates to true for function pointers and function objects with a * @c result_type typedef. It must be specialised for other user-defined * function objects. * * @par Examples * To read data into a dynamic buffer sequence until whitespace is encountered: * @code typedef asio::buffers_iterator< * asio::const_buffers_1> iterator; * * std::pair<iterator, bool> * match_whitespace(iterator begin, iterator end) * { * iterator i = begin; * while (i != end) * if (std::isspace(*i++)) * return std::make_pair(i, true); * return std::make_pair(i, false); * } * ... * std::string data; * asio::read_until(s, data, match_whitespace); * @endcode * * To read data into a @c std::string until a matching character is found: * @code class match_char * { * public: * explicit match_char(char c) : c_(c) {} * * template <typename Iterator> * std::pair<Iterator, bool> operator()( * Iterator begin, Iterator end) const * { * Iterator i = begin; * while (i != end) * if (c_ == *i++) * return std::make_pair(i, true); * return std::make_pair(i, false); * } * * private: * char c_; * }; * * namespace asio { * template <> struct is_match_condition<match_char> * : public boost::true_type {}; * } // namespace asio * ... * std::string data; * asio::read_until(s, data, match_char('a')); * @endcode */ template <typename SyncReadStream, typename DynamicBuffer_v2, typename MatchCondition> std::size_t read_until(SyncReadStream& s, DynamicBuffer_v2 buffers, MatchCondition match_condition, constraint_t< is_match_condition<MatchCondition>::value > = 0, constraint_t< is_dynamic_buffer_v2<DynamicBuffer_v2>::value > = 0); /// Read data into a dynamic buffer sequence until a function object indicates a /// match. /** * This function is used to read data into the specified dynamic buffer * sequence until a user-defined match condition function object, when applied * to the data contained in the dynamic buffer sequence, indicates a successful * match. The call will block until one of the following conditions is true: * * @li The match condition function object returns a std::pair where the second * element evaluates to true. * * @li An error occurred. * * This operation is implemented in terms of zero or more calls to the stream's * read_some function. If the match condition function object already indicates * a match, the function returns immediately. * * @param s The stream from which the data is to be read. The type must support * the SyncReadStream concept. * * @param buffers A dynamic buffer sequence into which the data will be read. * * @param match_condition The function object to be called to determine whether * a match exists. The signature of the function object must be: * @code pair<iterator, bool> match_condition(iterator begin, iterator end); * @endcode * where @c iterator represents the type: * @code buffers_iterator<DynamicBuffer_v2::const_buffers_type> * @endcode * The iterator parameters @c begin and @c end define the range of bytes to be * scanned to determine whether there is a match. The @c first member of the * return value is an iterator marking one-past-the-end of the bytes that have * been consumed by the match function. This iterator is used to calculate the * @c begin parameter for any subsequent invocation of the match condition. The * @c second member of the return value is true if a match has been found, false * otherwise. * * @param ec Set to indicate what error occurred, if any. * * @returns The number of bytes in the dynamic buffer sequence's get area that * have been fully consumed by the match function. Returns 0 if an error * occurred. * * @note After a successful read_until operation, the dynamic buffer sequence * may contain additional data beyond that which matched the function object. * An application will typically leave that data in the dynamic buffer sequence * for a subsequent read_until operation to examine. * * @note The default implementation of the @c is_match_condition type trait * evaluates to true for function pointers and function objects with a * @c result_type typedef. It must be specialised for other user-defined * function objects. */ template <typename SyncReadStream, typename DynamicBuffer_v2, typename MatchCondition> std::size_t read_until(SyncReadStream& s, DynamicBuffer_v2 buffers, MatchCondition match_condition, asio::error_code& ec, constraint_t< is_match_condition<MatchCondition>::value > = 0, constraint_t< is_dynamic_buffer_v2<DynamicBuffer_v2>::value > = 0); #endif // !defined(ASIO_NO_EXTENSIONS) /*@}*/ /** * @defgroup async_read_until asio::async_read_until * * @brief The @c async_read_until function is a composed asynchronous operation * that reads data into a dynamic buffer sequence, or into a streambuf, until * it contains a delimiter, matches a regular expression, or a function object * indicates a match. */ /*@{*/ #if !defined(ASIO_NO_DYNAMIC_BUFFER_V1) /// Start an asynchronous operation to read data into a dynamic buffer sequence /// until it contains a specified delimiter. /** * This function is used to asynchronously read data into the specified dynamic * buffer sequence until the dynamic buffer sequence's get area contains the * specified delimiter. It is an initiating function for an @ref * asynchronous_operation, and always returns immediately. The asynchronous * operation will continue until one of the following conditions is true: * * @li The get area of the dynamic buffer sequence contains the specified * delimiter. * * @li An error occurred. * * This operation is implemented in terms of zero or more calls to the stream's * async_read_some function, and is known as a <em>composed operation</em>. If * the dynamic buffer sequence's get area already contains the delimiter, this * asynchronous operation completes immediately. The program must ensure that * the stream performs no other read operations (such as async_read, * async_read_until, the stream's async_read_some function, or any other * composed operations that perform reads) until this operation completes. * * @param s The stream from which the data is to be read. The type must support * the AsyncReadStream concept. * * @param buffers The dynamic buffer sequence into which the data will be read. * Although the buffers object may be copied as necessary, ownership of the * underlying memory blocks is retained by the caller, which must guarantee * that they remain valid until the completion handler is called. * * @param delim The delimiter character. * * @param token The @ref completion_token that will be used to produce a * completion handler, which will be called when the read completes. * Potential completion tokens include @ref use_future, @ref use_awaitable, * @ref yield_context, or a function object with the correct completion * signature. The function signature of the completion handler must be: * @code void handler( * // Result of operation. * const asio::error_code& error, * * // The number of bytes in the dynamic buffer sequence's * // get area up to and including the delimiter. * std::size_t bytes_transferred * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the completion handler will not be invoked from within this function. * On immediate completion, invocation of the handler will be performed in a * manner equivalent to using asio::async_immediate(). * * @par Completion Signature * @code void(asio::error_code, std::size_t) @endcode * * @note After a successful async_read_until operation, the dynamic buffer * sequence may contain additional data beyond the delimiter. An application * will typically leave that data in the dynamic buffer sequence for a * subsequent async_read_until operation to examine. * * @par Example * To asynchronously read data into a @c std::string until a newline is * encountered: * @code std::string data; * ... * void handler(const asio::error_code& e, std::size_t size) * { * if (!e) * { * std::string line = data.substr(0, n); * data.erase(0, n); * ... * } * } * ... * asio::async_read_until(s, data, '\n', handler); @endcode * After the @c async_read_until operation completes successfully, the buffer * @c data contains the delimiter: * @code { 'a', 'b', ..., 'c', '\n', 'd', 'e', ... } @endcode * The call to @c substr then extracts the data up to and including the * delimiter, so that the string @c line contains: * @code { 'a', 'b', ..., 'c', '\n' } @endcode * After the call to @c erase, the remaining data is left in the buffer @c data * as follows: * @code { 'd', 'e', ... } @endcode * This data may be the start of a new line, to be extracted by a subsequent * @c async_read_until operation. * * @par Per-Operation Cancellation * This asynchronous operation supports cancellation for the following * asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * if they are also supported by the @c AsyncReadStream type's * @c async_read_some operation. */ template <typename AsyncReadStream, typename DynamicBuffer_v1, ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code, std::size_t)) ReadToken = default_completion_token_t< typename AsyncReadStream::executor_type>> inline auto async_read_until(AsyncReadStream& s, DynamicBuffer_v1&& buffers, char delim, ReadToken&& token = default_completion_token_t< typename AsyncReadStream::executor_type>(), constraint_t< is_dynamic_buffer_v1<decay_t<DynamicBuffer_v1>>::value > = 0, constraint_t< !is_dynamic_buffer_v2<decay_t<DynamicBuffer_v1>>::value > = 0) -> decltype( async_initiate<ReadToken, void (asio::error_code, std::size_t)>( declval<detail::initiate_async_read_until_delim_v1<AsyncReadStream>>(), token, static_cast<DynamicBuffer_v1&&>(buffers), delim)) { return async_initiate<ReadToken, void (asio::error_code, std::size_t)>( detail::initiate_async_read_until_delim_v1<AsyncReadStream>(s), token, static_cast<DynamicBuffer_v1&&>(buffers), delim); } /// Start an asynchronous operation to read data into a dynamic buffer sequence /// until it contains a specified delimiter. /** * This function is used to asynchronously read data into the specified dynamic * buffer sequence until the dynamic buffer sequence's get area contains the * specified delimiter. It is an initiating function for an @ref * asynchronous_operation, and always returns immediately. The asynchronous * operation will continue until one of the following conditions is true: * * @li The get area of the dynamic buffer sequence contains the specified * delimiter. * * @li An error occurred. * * This operation is implemented in terms of zero or more calls to the stream's * async_read_some function, and is known as a <em>composed operation</em>. If * the dynamic buffer sequence's get area already contains the delimiter, this * asynchronous operation completes immediately. The program must ensure that * the stream performs no other read operations (such as async_read, * async_read_until, the stream's async_read_some function, or any other * composed operations that perform reads) until this operation completes. * * @param s The stream from which the data is to be read. The type must support * the AsyncReadStream concept. * * @param buffers The dynamic buffer sequence into which the data will be read. * Although the buffers object may be copied as necessary, ownership of the * underlying memory blocks is retained by the caller, which must guarantee * that they remain valid until the completion handler is called. * * @param delim The delimiter string. * * @param token The @ref completion_token that will be used to produce a * completion handler, which will be called when the read completes. * Potential completion tokens include @ref use_future, @ref use_awaitable, * @ref yield_context, or a function object with the correct completion * signature. The function signature of the completion handler must be: * @code void handler( * // Result of operation. * const asio::error_code& error, * * // The number of bytes in the dynamic buffer sequence's * // get area up to and including the delimiter. * std::size_t bytes_transferred * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the completion handler will not be invoked from within this function. * On immediate completion, invocation of the handler will be performed in a * manner equivalent to using asio::async_immediate(). * * @par Completion Signature * @code void(asio::error_code, std::size_t) @endcode * * @note After a successful async_read_until operation, the dynamic buffer * sequence may contain additional data beyond the delimiter. An application * will typically leave that data in the dynamic buffer sequence for a * subsequent async_read_until operation to examine. * * @par Example * To asynchronously read data into a @c std::string until a CR-LF sequence is * encountered: * @code std::string data; * ... * void handler(const asio::error_code& e, std::size_t size) * { * if (!e) * { * std::string line = data.substr(0, n); * data.erase(0, n); * ... * } * } * ... * asio::async_read_until(s, data, "\r\n", handler); @endcode * After the @c async_read_until operation completes successfully, the string * @c data contains the delimiter: * @code { 'a', 'b', ..., 'c', '\r', '\n', 'd', 'e', ... } @endcode * The call to @c substr then extracts the data up to and including the * delimiter, so that the string @c line contains: * @code { 'a', 'b', ..., 'c', '\r', '\n' } @endcode * After the call to @c erase, the remaining data is left in the string @c data * as follows: * @code { 'd', 'e', ... } @endcode * This data may be the start of a new line, to be extracted by a subsequent * @c async_read_until operation. * * @par Per-Operation Cancellation * This asynchronous operation supports cancellation for the following * asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * if they are also supported by the @c AsyncReadStream type's * @c async_read_some operation. */ template <typename AsyncReadStream, typename DynamicBuffer_v1, ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code, std::size_t)) ReadToken = default_completion_token_t< typename AsyncReadStream::executor_type>> inline auto async_read_until(AsyncReadStream& s, DynamicBuffer_v1&& buffers, ASIO_STRING_VIEW_PARAM delim, ReadToken&& token = default_completion_token_t< typename AsyncReadStream::executor_type>(), constraint_t< is_dynamic_buffer_v1<decay_t<DynamicBuffer_v1>>::value > = 0, constraint_t< !is_dynamic_buffer_v2<decay_t<DynamicBuffer_v1>>::value > = 0) -> decltype( async_initiate<ReadToken, void (asio::error_code, std::size_t)>( declval<detail::initiate_async_read_until_delim_string_v1< AsyncReadStream>>(), token, static_cast<DynamicBuffer_v1&&>(buffers), static_cast<std::string>(delim))) { return async_initiate<ReadToken, void (asio::error_code, std::size_t)>( detail::initiate_async_read_until_delim_string_v1<AsyncReadStream>(s), token, static_cast<DynamicBuffer_v1&&>(buffers), static_cast<std::string>(delim)); } #if !defined(ASIO_NO_EXTENSIONS) #if defined(ASIO_HAS_BOOST_REGEX) \ || defined(GENERATING_DOCUMENTATION) /// Start an asynchronous operation to read data into a dynamic buffer sequence /// until some part of its data matches a regular expression. /** * This function is used to asynchronously read data into the specified dynamic * buffer sequence until the dynamic buffer sequence's get area contains some * data that matches a regular expression. It is an initiating function for an * @ref asynchronous_operation, and always returns immediately. The * asynchronous operation will continue until one of the following conditions * is true: * * @li A substring of the dynamic buffer sequence's get area matches the regular * expression. * * @li An error occurred. * * This operation is implemented in terms of zero or more calls to the stream's * async_read_some function, and is known as a <em>composed operation</em>. If * the dynamic buffer sequence's get area already contains data that matches * the regular expression, this asynchronous operation completes immediately. * The program must ensure that the stream performs no other read operations * (such as async_read, async_read_until, the stream's async_read_some * function, or any other composed operations that perform reads) until this * operation completes. * * @param s The stream from which the data is to be read. The type must support * the AsyncReadStream concept. * * @param buffers The dynamic buffer sequence into which the data will be read. * Although the buffers object may be copied as necessary, ownership of the * underlying memory blocks is retained by the caller, which must guarantee * that they remain valid until the completion handler is called. * * @param expr The regular expression. * * @param token The @ref completion_token that will be used to produce a * completion handler, which will be called when the read completes. * Potential completion tokens include @ref use_future, @ref use_awaitable, * @ref yield_context, or a function object with the correct completion * signature. The function signature of the completion handler must be: * @code void handler( * // Result of operation. * const asio::error_code& error, * * // The number of bytes in the dynamic buffer * // sequence's get area up to and including the * // substring that matches the regular expression. * // 0 if an error occurred. * std::size_t bytes_transferred * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the completion handler will not be invoked from within this function. * On immediate completion, invocation of the handler will be performed in a * manner equivalent to using asio::async_immediate(). * * @par Completion Signature * @code void(asio::error_code, std::size_t) @endcode * * @note After a successful async_read_until operation, the dynamic buffer * sequence may contain additional data beyond that which matched the regular * expression. An application will typically leave that data in the dynamic * buffer sequence for a subsequent async_read_until operation to examine. * * @par Example * To asynchronously read data into a @c std::string until a CR-LF sequence is * encountered: * @code std::string data; * ... * void handler(const asio::error_code& e, std::size_t size) * { * if (!e) * { * std::string line = data.substr(0, n); * data.erase(0, n); * ... * } * } * ... * asio::async_read_until(s, data, * boost::regex("\r\n"), handler); @endcode * After the @c async_read_until operation completes successfully, the string * @c data contains the data which matched the regular expression: * @code { 'a', 'b', ..., 'c', '\r', '\n', 'd', 'e', ... } @endcode * The call to @c substr then extracts the data up to and including the match, * so that the string @c line contains: * @code { 'a', 'b', ..., 'c', '\r', '\n' } @endcode * After the call to @c erase, the remaining data is left in the string @c data * as follows: * @code { 'd', 'e', ... } @endcode * This data may be the start of a new line, to be extracted by a subsequent * @c async_read_until operation. * * @par Per-Operation Cancellation * This asynchronous operation supports cancellation for the following * asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * if they are also supported by the @c AsyncReadStream type's * @c async_read_some operation. */ template <typename AsyncReadStream, typename DynamicBuffer_v1, typename Traits, ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code, std::size_t)) ReadToken = default_completion_token_t< typename AsyncReadStream::executor_type>> inline auto async_read_until(AsyncReadStream& s, DynamicBuffer_v1&& buffers, const boost::basic_regex<char, Traits>& expr, ReadToken&& token = default_completion_token_t< typename AsyncReadStream::executor_type>(), constraint_t< is_dynamic_buffer_v1<decay_t<DynamicBuffer_v1>>::value > = 0, constraint_t< !is_dynamic_buffer_v2<decay_t<DynamicBuffer_v1>>::value > = 0) -> decltype( async_initiate<ReadToken, void (asio::error_code, std::size_t)>( declval<detail::initiate_async_read_until_expr_v1<AsyncReadStream>>(), token, static_cast<DynamicBuffer_v1&&>(buffers), expr)) { return async_initiate<ReadToken, void (asio::error_code, std::size_t)>( detail::initiate_async_read_until_expr_v1<AsyncReadStream>(s), token, static_cast<DynamicBuffer_v1&&>(buffers), expr); } #endif // defined(ASIO_HAS_BOOST_REGEX) // || defined(GENERATING_DOCUMENTATION) /// Start an asynchronous operation to read data into a dynamic buffer sequence /// until a function object indicates a match. /** * This function is used to asynchronously read data into the specified dynamic * buffer sequence until a user-defined match condition function object, when * applied to the data contained in the dynamic buffer sequence, indicates a * successful match. It is an initiating function for an @ref * asynchronous_operation, and always returns immediately. The asynchronous * operation will continue until one of the following conditions is true: * * @li The match condition function object returns a std::pair where the second * element evaluates to true. * * @li An error occurred. * * This operation is implemented in terms of zero or more calls to the stream's * async_read_some function, and is known as a <em>composed operation</em>. If * the match condition function object already indicates a match, this * asynchronous operation completes immediately. The program must ensure that * the stream performs no other read operations (such as async_read, * async_read_until, the stream's async_read_some function, or any other * composed operations that perform reads) until this operation completes. * * @param s The stream from which the data is to be read. The type must support * the AsyncReadStream concept. * * @param buffers The dynamic buffer sequence into which the data will be read. * Although the buffers object may be copied as necessary, ownership of the * underlying memory blocks is retained by the caller, which must guarantee * that they remain valid until the completion handler is called. * * @param match_condition The function object to be called to determine whether * a match exists. The signature of the function object must be: * @code pair<iterator, bool> match_condition(iterator begin, iterator end); * @endcode * where @c iterator represents the type: * @code buffers_iterator<typename DynamicBuffer_v1::const_buffers_type> * @endcode * The iterator parameters @c begin and @c end define the range of bytes to be * scanned to determine whether there is a match. The @c first member of the * return value is an iterator marking one-past-the-end of the bytes that have * been consumed by the match function. This iterator is used to calculate the * @c begin parameter for any subsequent invocation of the match condition. The * @c second member of the return value is true if a match has been found, false * otherwise. * * @param token The @ref completion_token that will be used to produce a * completion handler, which will be called when the read completes. * Potential completion tokens include @ref use_future, @ref use_awaitable, * @ref yield_context, or a function object with the correct completion * signature. The function signature of the completion handler must be: * @code void handler( * // Result of operation. * const asio::error_code& error, * * // The number of bytes in the dynamic buffer sequence's * // get area that have been fully consumed by the match * // function. O if an error occurred. * std::size_t bytes_transferred * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the completion handler will not be invoked from within this function. * On immediate completion, invocation of the handler will be performed in a * manner equivalent to using asio::async_immediate(). * * @note After a successful async_read_until operation, the dynamic buffer * sequence may contain additional data beyond that which matched the function * object. An application will typically leave that data in the dynamic buffer * sequence for a subsequent async_read_until operation to examine. * * @par Completion Signature * @code void(asio::error_code, std::size_t) @endcode * * @note The default implementation of the @c is_match_condition type trait * evaluates to true for function pointers and function objects with a * @c result_type typedef. It must be specialised for other user-defined * function objects. * * @par Examples * To asynchronously read data into a @c std::string until whitespace is * encountered: * @code typedef asio::buffers_iterator< * asio::const_buffers_1> iterator; * * std::pair<iterator, bool> * match_whitespace(iterator begin, iterator end) * { * iterator i = begin; * while (i != end) * if (std::isspace(*i++)) * return std::make_pair(i, true); * return std::make_pair(i, false); * } * ... * void handler(const asio::error_code& e, std::size_t size); * ... * std::string data; * asio::async_read_until(s, data, match_whitespace, handler); * @endcode * * To asynchronously read data into a @c std::string until a matching character * is found: * @code class match_char * { * public: * explicit match_char(char c) : c_(c) {} * * template <typename Iterator> * std::pair<Iterator, bool> operator()( * Iterator begin, Iterator end) const * { * Iterator i = begin; * while (i != end) * if (c_ == *i++) * return std::make_pair(i, true); * return std::make_pair(i, false); * } * * private: * char c_; * }; * * namespace asio { * template <> struct is_match_condition<match_char> * : public boost::true_type {}; * } // namespace asio * ... * void handler(const asio::error_code& e, std::size_t size); * ... * std::string data; * asio::async_read_until(s, data, match_char('a'), handler); * @endcode * * @par Per-Operation Cancellation * This asynchronous operation supports cancellation for the following * asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * if they are also supported by the @c AsyncReadStream type's * @c async_read_some operation. */ template <typename AsyncReadStream, typename DynamicBuffer_v1, typename MatchCondition, ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code, std::size_t)) ReadToken = default_completion_token_t< typename AsyncReadStream::executor_type>> inline auto async_read_until(AsyncReadStream& s, DynamicBuffer_v1&& buffers, MatchCondition match_condition, ReadToken&& token = default_completion_token_t< typename AsyncReadStream::executor_type>(), constraint_t< is_match_condition<MatchCondition>::value > = 0, constraint_t< is_dynamic_buffer_v1<decay_t<DynamicBuffer_v1>>::value > = 0, constraint_t< !is_dynamic_buffer_v2<decay_t<DynamicBuffer_v1>>::value > = 0) -> decltype( async_initiate<ReadToken, void (asio::error_code, std::size_t)>( declval<detail::initiate_async_read_until_match_v1<AsyncReadStream>>(), token, static_cast<DynamicBuffer_v1&&>(buffers), match_condition)) { return async_initiate<ReadToken, void (asio::error_code, std::size_t)>( detail::initiate_async_read_until_match_v1<AsyncReadStream>(s), token, static_cast<DynamicBuffer_v1&&>(buffers), match_condition); } #if !defined(ASIO_NO_IOSTREAM) /// Start an asynchronous operation to read data into a streambuf until it /// contains a specified delimiter. /** * This function is used to asynchronously read data into the specified * streambuf until the streambuf's get area contains the specified delimiter. * It is an initiating function for an @ref asynchronous_operation, and always * returns immediately. The asynchronous operation will continue until one of * the following conditions is true: * * @li The get area of the streambuf contains the specified delimiter. * * @li An error occurred. * * This operation is implemented in terms of zero or more calls to the stream's * async_read_some function, and is known as a <em>composed operation</em>. If * the streambuf's get area already contains the delimiter, this asynchronous * operation completes immediately. The program must ensure that the stream * performs no other read operations (such as async_read, async_read_until, the * stream's async_read_some function, or any other composed operations that * perform reads) until this operation completes. * * @param s The stream from which the data is to be read. The type must support * the AsyncReadStream concept. * * @param b A streambuf object into which the data will be read. Ownership of * the streambuf is retained by the caller, which must guarantee that it remains * valid until the completion handler is called. * * @param delim The delimiter character. * * @param token The @ref completion_token that will be used to produce a * completion handler, which will be called when the read completes. * Potential completion tokens include @ref use_future, @ref use_awaitable, * @ref yield_context, or a function object with the correct completion * signature. The function signature of the completion handler must be: * @code void handler( * // Result of operation. * const asio::error_code& error, * * // The number of bytes in the streambuf's get * // area up to and including the delimiter. * // 0 if an error occurred. * std::size_t bytes_transferred * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the completion handler will not be invoked from within this function. * On immediate completion, invocation of the handler will be performed in a * manner equivalent to using asio::async_immediate(). * * @par Completion Signature * @code void(asio::error_code, std::size_t) @endcode * * @note After a successful async_read_until operation, the streambuf may * contain additional data beyond the delimiter. An application will typically * leave that data in the streambuf for a subsequent async_read_until operation * to examine. * * @par Example * To asynchronously read data into a streambuf until a newline is encountered: * @code asio::streambuf b; * ... * void handler(const asio::error_code& e, std::size_t size) * { * if (!e) * { * std::istream is(&b); * std::string line; * std::getline(is, line); * ... * } * } * ... * asio::async_read_until(s, b, '\n', handler); @endcode * After the @c async_read_until operation completes successfully, the buffer * @c b contains the delimiter: * @code { 'a', 'b', ..., 'c', '\n', 'd', 'e', ... } @endcode * The call to @c std::getline then extracts the data up to and including the * newline (which is discarded), so that the string @c line contains: * @code { 'a', 'b', ..., 'c' } @endcode * The remaining data is left in the buffer @c b as follows: * @code { 'd', 'e', ... } @endcode * This data may be the start of a new line, to be extracted by a subsequent * @c async_read_until operation. * * @par Per-Operation Cancellation * This asynchronous operation supports cancellation for the following * asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * if they are also supported by the @c AsyncReadStream type's * @c async_read_some operation. */ template <typename AsyncReadStream, typename Allocator, ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code, std::size_t)) ReadToken = default_completion_token_t< typename AsyncReadStream::executor_type>> inline auto async_read_until(AsyncReadStream& s, asio::basic_streambuf<Allocator>& b, char delim, ReadToken&& token = default_completion_token_t< typename AsyncReadStream::executor_type>()) -> decltype( async_initiate<ReadToken, void (asio::error_code, std::size_t)>( declval<detail::initiate_async_read_until_delim_v1<AsyncReadStream>>(), token, basic_streambuf_ref<Allocator>(b), delim)) { return async_initiate<ReadToken, void (asio::error_code, std::size_t)>( detail::initiate_async_read_until_delim_v1<AsyncReadStream>(s), token, basic_streambuf_ref<Allocator>(b), delim); } /// Start an asynchronous operation to read data into a streambuf until it /// contains a specified delimiter. /** * This function is used to asynchronously read data into the specified * streambuf until the streambuf's get area contains the specified delimiter. * It is an initiating function for an @ref asynchronous_operation, and always * returns immediately. The asynchronous operation will continue until one of * the following conditions is true: * * @li The get area of the streambuf contains the specified delimiter. * * @li An error occurred. * * This operation is implemented in terms of zero or more calls to the stream's * async_read_some function, and is known as a <em>composed operation</em>. If * the streambuf's get area already contains the delimiter, this asynchronous * operation completes immediately. The program must ensure that the stream * performs no other read operations (such as async_read, async_read_until, the * stream's async_read_some function, or any other composed operations that * perform reads) until this operation completes. * * @param s The stream from which the data is to be read. The type must support * the AsyncReadStream concept. * * @param b A streambuf object into which the data will be read. Ownership of * the streambuf is retained by the caller, which must guarantee that it remains * valid until the completion handler is called. * * @param delim The delimiter string. * * @param token The @ref completion_token that will be used to produce a * completion handler, which will be called when the read completes. * Potential completion tokens include @ref use_future, @ref use_awaitable, * @ref yield_context, or a function object with the correct completion * signature. The function signature of the completion handler must be: * @code void handler( * // Result of operation. * const asio::error_code& error, * * // The number of bytes in the streambuf's get * // area up to and including the delimiter. * // 0 if an error occurred. * std::size_t bytes_transferred * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the completion handler will not be invoked from within this function. * On immediate completion, invocation of the handler will be performed in a * manner equivalent to using asio::async_immediate(). * * @par Completion Signature * @code void(asio::error_code, std::size_t) @endcode * * @note After a successful async_read_until operation, the streambuf may * contain additional data beyond the delimiter. An application will typically * leave that data in the streambuf for a subsequent async_read_until operation * to examine. * * @par Example * To asynchronously read data into a streambuf until a newline is encountered: * @code asio::streambuf b; * ... * void handler(const asio::error_code& e, std::size_t size) * { * if (!e) * { * std::istream is(&b); * std::string line; * std::getline(is, line); * ... * } * } * ... * asio::async_read_until(s, b, "\r\n", handler); @endcode * After the @c async_read_until operation completes successfully, the buffer * @c b contains the delimiter: * @code { 'a', 'b', ..., 'c', '\r', '\n', 'd', 'e', ... } @endcode * The call to @c std::getline then extracts the data up to and including the * newline (which is discarded), so that the string @c line contains: * @code { 'a', 'b', ..., 'c', '\r' } @endcode * The remaining data is left in the buffer @c b as follows: * @code { 'd', 'e', ... } @endcode * This data may be the start of a new line, to be extracted by a subsequent * @c async_read_until operation. * * @par Per-Operation Cancellation * This asynchronous operation supports cancellation for the following * asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * if they are also supported by the @c AsyncReadStream type's * @c async_read_some operation. */ template <typename AsyncReadStream, typename Allocator, ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code, std::size_t)) ReadToken = default_completion_token_t< typename AsyncReadStream::executor_type>> inline auto async_read_until(AsyncReadStream& s, asio::basic_streambuf<Allocator>& b, ASIO_STRING_VIEW_PARAM delim, ReadToken&& token = default_completion_token_t< typename AsyncReadStream::executor_type>()) -> decltype( async_initiate<ReadToken, void (asio::error_code, std::size_t)>( declval<detail::initiate_async_read_until_delim_string_v1< AsyncReadStream>>(), token, basic_streambuf_ref<Allocator>(b), static_cast<std::string>(delim))) { return async_initiate<ReadToken, void (asio::error_code, std::size_t)>( detail::initiate_async_read_until_delim_string_v1<AsyncReadStream>(s), token, basic_streambuf_ref<Allocator>(b), static_cast<std::string>(delim)); } #if defined(ASIO_HAS_BOOST_REGEX) \ || defined(GENERATING_DOCUMENTATION) /// Start an asynchronous operation to read data into a streambuf until some /// part of its data matches a regular expression. /** * This function is used to asynchronously read data into the specified * streambuf until the streambuf's get area contains some data that matches a * regular expression. It is an initiating function for an @ref * asynchronous_operation, and always returns immediately. The asynchronous * operation will continue until one of the following conditions is true: * * @li A substring of the streambuf's get area matches the regular expression. * * @li An error occurred. * * This operation is implemented in terms of zero or more calls to the stream's * async_read_some function, and is known as a <em>composed operation</em>. If * the streambuf's get area already contains data that matches the regular * expression, this asynchronous operation completes immediately. The program * must ensure that the stream performs no other read operations (such as * async_read, async_read_until, the stream's async_read_some function, or any * other composed operations that perform reads) until this operation * completes. * * @param s The stream from which the data is to be read. The type must support * the AsyncReadStream concept. * * @param b A streambuf object into which the data will be read. Ownership of * the streambuf is retained by the caller, which must guarantee that it remains * valid until the completion handler is called. * * @param expr The regular expression. * * @param token The @ref completion_token that will be used to produce a * completion handler, which will be called when the read completes. * Potential completion tokens include @ref use_future, @ref use_awaitable, * @ref yield_context, or a function object with the correct completion * signature. The function signature of the completion handler must be: * @code void handler( * // Result of operation. * const asio::error_code& error, * * // The number of bytes in the streambuf's get * // area up to and including the substring * // that matches the regular. expression. * // 0 if an error occurred. * std::size_t bytes_transferred * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the completion handler will not be invoked from within this function. * On immediate completion, invocation of the handler will be performed in a * manner equivalent to using asio::async_immediate(). * * @par Completion Signature * @code void(asio::error_code, std::size_t) @endcode * * @note After a successful async_read_until operation, the streambuf may * contain additional data beyond that which matched the regular expression. An * application will typically leave that data in the streambuf for a subsequent * async_read_until operation to examine. * * @par Example * To asynchronously read data into a streambuf until a CR-LF sequence is * encountered: * @code asio::streambuf b; * ... * void handler(const asio::error_code& e, std::size_t size) * { * if (!e) * { * std::istream is(&b); * std::string line; * std::getline(is, line); * ... * } * } * ... * asio::async_read_until(s, b, boost::regex("\r\n"), handler); @endcode * After the @c async_read_until operation completes successfully, the buffer * @c b contains the data which matched the regular expression: * @code { 'a', 'b', ..., 'c', '\r', '\n', 'd', 'e', ... } @endcode * The call to @c std::getline then extracts the data up to and including the * newline (which is discarded), so that the string @c line contains: * @code { 'a', 'b', ..., 'c', '\r' } @endcode * The remaining data is left in the buffer @c b as follows: * @code { 'd', 'e', ... } @endcode * This data may be the start of a new line, to be extracted by a subsequent * @c async_read_until operation. * * @par Per-Operation Cancellation * This asynchronous operation supports cancellation for the following * asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * if they are also supported by the @c AsyncReadStream type's * @c async_read_some operation. */ template <typename AsyncReadStream, typename Allocator, typename Traits, ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code, std::size_t)) ReadToken = default_completion_token_t< typename AsyncReadStream::executor_type>> inline auto async_read_until(AsyncReadStream& s, asio::basic_streambuf<Allocator>& b, const boost::basic_regex<char, Traits>& expr, ReadToken&& token = default_completion_token_t< typename AsyncReadStream::executor_type>()) -> decltype( async_initiate<ReadToken, void (asio::error_code, std::size_t)>( declval<detail::initiate_async_read_until_expr_v1<AsyncReadStream>>(), token, basic_streambuf_ref<Allocator>(b), expr)) { return async_initiate<ReadToken, void (asio::error_code, std::size_t)>( detail::initiate_async_read_until_expr_v1<AsyncReadStream>(s), token, basic_streambuf_ref<Allocator>(b), expr); } #endif // defined(ASIO_HAS_BOOST_REGEX) // || defined(GENERATING_DOCUMENTATION) /// Start an asynchronous operation to read data into a streambuf until a /// function object indicates a match. /** * This function is used to asynchronously read data into the specified * streambuf until a user-defined match condition function object, when applied * to the data contained in the streambuf, indicates a successful match. It is * an initiating function for an @ref asynchronous_operation, and always * returns immediately. The asynchronous operation will continue until one of * the following conditions is true: * * @li The match condition function object returns a std::pair where the second * element evaluates to true. * * @li An error occurred. * * This operation is implemented in terms of zero or more calls to the stream's * async_read_some function, and is known as a <em>composed operation</em>. If * the match condition function object already indicates a match, this * asynchronous operation completes immediately. The program must ensure that * the stream performs no other read operations (such as async_read, * async_read_until, the stream's async_read_some function, or any other * composed operations that perform reads) until this operation completes. * * @param s The stream from which the data is to be read. The type must support * the AsyncReadStream concept. * * @param b A streambuf object into which the data will be read. * * @param match_condition The function object to be called to determine whether * a match exists. The signature of the function object must be: * @code pair<iterator, bool> match_condition(iterator begin, iterator end); * @endcode * where @c iterator represents the type: * @code buffers_iterator<basic_streambuf<Allocator>::const_buffers_type> * @endcode * The iterator parameters @c begin and @c end define the range of bytes to be * scanned to determine whether there is a match. The @c first member of the * return value is an iterator marking one-past-the-end of the bytes that have * been consumed by the match function. This iterator is used to calculate the * @c begin parameter for any subsequent invocation of the match condition. The * @c second member of the return value is true if a match has been found, false * otherwise. * * @param token The @ref completion_token that will be used to produce a * completion handler, which will be called when the read completes. * Potential completion tokens include @ref use_future, @ref use_awaitable, * @ref yield_context, or a function object with the correct completion * signature. The function signature of the completion handler must be: * @code void handler( * // Result of operation. * const asio::error_code& error, * * // The number of bytes in the streambuf's get * // area that have been fully consumed by the * // match function. O if an error occurred. * std::size_t bytes_transferred * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the completion handler will not be invoked from within this function. * On immediate completion, invocation of the handler will be performed in a * manner equivalent to using asio::async_immediate(). * * @note After a successful async_read_until operation, the streambuf may * contain additional data beyond that which matched the function object. An * application will typically leave that data in the streambuf for a subsequent * async_read_until operation to examine. * * @par Completion Signature * @code void(asio::error_code, std::size_t) @endcode * * @note The default implementation of the @c is_match_condition type trait * evaluates to true for function pointers and function objects with a * @c result_type typedef. It must be specialised for other user-defined * function objects. * * @par Examples * To asynchronously read data into a streambuf until whitespace is encountered: * @code typedef asio::buffers_iterator< * asio::streambuf::const_buffers_type> iterator; * * std::pair<iterator, bool> * match_whitespace(iterator begin, iterator end) * { * iterator i = begin; * while (i != end) * if (std::isspace(*i++)) * return std::make_pair(i, true); * return std::make_pair(i, false); * } * ... * void handler(const asio::error_code& e, std::size_t size); * ... * asio::streambuf b; * asio::async_read_until(s, b, match_whitespace, handler); * @endcode * * To asynchronously read data into a streambuf until a matching character is * found: * @code class match_char * { * public: * explicit match_char(char c) : c_(c) {} * * template <typename Iterator> * std::pair<Iterator, bool> operator()( * Iterator begin, Iterator end) const * { * Iterator i = begin; * while (i != end) * if (c_ == *i++) * return std::make_pair(i, true); * return std::make_pair(i, false); * } * * private: * char c_; * }; * * namespace asio { * template <> struct is_match_condition<match_char> * : public boost::true_type {}; * } // namespace asio * ... * void handler(const asio::error_code& e, std::size_t size); * ... * asio::streambuf b; * asio::async_read_until(s, b, match_char('a'), handler); * @endcode * * @par Per-Operation Cancellation * This asynchronous operation supports cancellation for the following * asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * if they are also supported by the @c AsyncReadStream type's * @c async_read_some operation. */ template <typename AsyncReadStream, typename Allocator, typename MatchCondition, ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code, std::size_t)) ReadToken = default_completion_token_t< typename AsyncReadStream::executor_type>> inline auto async_read_until(AsyncReadStream& s, asio::basic_streambuf<Allocator>& b, MatchCondition match_condition, ReadToken&& token = default_completion_token_t< typename AsyncReadStream::executor_type>(), constraint_t<is_match_condition<MatchCondition>::value> = 0) -> decltype( async_initiate<ReadToken, void (asio::error_code, std::size_t)>( declval<detail::initiate_async_read_until_match_v1<AsyncReadStream>>(), token, basic_streambuf_ref<Allocator>(b), match_condition)) { return async_initiate<ReadToken, void (asio::error_code, std::size_t)>( detail::initiate_async_read_until_match_v1<AsyncReadStream>(s), token, basic_streambuf_ref<Allocator>(b), match_condition); } #endif // !defined(ASIO_NO_IOSTREAM) #endif // !defined(ASIO_NO_EXTENSIONS) #endif // !defined(ASIO_NO_DYNAMIC_BUFFER_V1) /// Start an asynchronous operation to read data into a dynamic buffer sequence /// until it contains a specified delimiter. /** * This function is used to asynchronously read data into the specified dynamic * buffer sequence until the dynamic buffer sequence's get area contains the * specified delimiter. It is an initiating function for an @ref * asynchronous_operation, and always returns immediately. The asynchronous * operation will continue until one of the following conditions is true: * * @li The get area of the dynamic buffer sequence contains the specified * delimiter. * * @li An error occurred. * * This operation is implemented in terms of zero or more calls to the stream's * async_read_some function, and is known as a <em>composed operation</em>. If * the dynamic buffer sequence's get area already contains the delimiter, this * asynchronous operation completes immediately. The program must ensure that * the stream performs no other read operations (such as async_read, * async_read_until, the stream's async_read_some function, or any other * composed operations that perform reads) until this operation completes. * * @param s The stream from which the data is to be read. The type must support * the AsyncReadStream concept. * * @param buffers The dynamic buffer sequence into which the data will be read. * Although the buffers object may be copied as necessary, ownership of the * underlying memory blocks is retained by the caller, which must guarantee * that they remain valid until the completion handler is called. * * @param delim The delimiter character. * * @param token The @ref completion_token that will be used to produce a * completion handler, which will be called when the read completes. * Potential completion tokens include @ref use_future, @ref use_awaitable, * @ref yield_context, or a function object with the correct completion * signature. The function signature of the completion handler must be: * @code void handler( * // Result of operation. * const asio::error_code& error, * * // The number of bytes in the dynamic buffer sequence's * // get area up to and including the delimiter. * // 0 if an error occurred. * std::size_t bytes_transferred * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the completion handler will not be invoked from within this function. * On immediate completion, invocation of the handler will be performed in a * manner equivalent to using asio::async_immediate(). * * @par Completion Signature * @code void(asio::error_code, std::size_t) @endcode * * @note After a successful async_read_until operation, the dynamic buffer * sequence may contain additional data beyond the delimiter. An application * will typically leave that data in the dynamic buffer sequence for a * subsequent async_read_until operation to examine. * * @par Example * To asynchronously read data into a @c std::string until a newline is * encountered: * @code std::string data; * ... * void handler(const asio::error_code& e, std::size_t size) * { * if (!e) * { * std::string line = data.substr(0, n); * data.erase(0, n); * ... * } * } * ... * asio::async_read_until(s, data, '\n', handler); @endcode * After the @c async_read_until operation completes successfully, the buffer * @c data contains the delimiter: * @code { 'a', 'b', ..., 'c', '\n', 'd', 'e', ... } @endcode * The call to @c substr then extracts the data up to and including the * delimiter, so that the string @c line contains: * @code { 'a', 'b', ..., 'c', '\n' } @endcode * After the call to @c erase, the remaining data is left in the buffer @c data * as follows: * @code { 'd', 'e', ... } @endcode * This data may be the start of a new line, to be extracted by a subsequent * @c async_read_until operation. * * @par Per-Operation Cancellation * This asynchronous operation supports cancellation for the following * asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * if they are also supported by the @c AsyncReadStream type's * @c async_read_some operation. */ template <typename AsyncReadStream, typename DynamicBuffer_v2, ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code, std::size_t)) ReadToken = default_completion_token_t< typename AsyncReadStream::executor_type>> inline auto async_read_until(AsyncReadStream& s, DynamicBuffer_v2 buffers, char delim, ReadToken&& token = default_completion_token_t< typename AsyncReadStream::executor_type>(), constraint_t< is_dynamic_buffer_v2<DynamicBuffer_v2>::value > = 0) -> decltype( async_initiate<ReadToken, void (asio::error_code, std::size_t)>( declval<detail::initiate_async_read_until_delim_v2<AsyncReadStream>>(), token, static_cast<DynamicBuffer_v2&&>(buffers), delim)) { return async_initiate<ReadToken, void (asio::error_code, std::size_t)>( detail::initiate_async_read_until_delim_v2<AsyncReadStream>(s), token, static_cast<DynamicBuffer_v2&&>(buffers), delim); } /// Start an asynchronous operation to read data into a dynamic buffer sequence /// until it contains a specified delimiter. /** * This function is used to asynchronously read data into the specified dynamic * buffer sequence until the dynamic buffer sequence's get area contains the * specified delimiter. It is an initiating function for an @ref * asynchronous_operation, and always returns immediately. The asynchronous * operation will continue until one of the following conditions is true: * * @li The get area of the dynamic buffer sequence contains the specified * delimiter. * * @li An error occurred. * * This operation is implemented in terms of zero or more calls to the stream's * async_read_some function, and is known as a <em>composed operation</em>. If * the dynamic buffer sequence's get area already contains the delimiter, this * asynchronous operation completes immediately. The program must ensure that * the stream performs no other read operations (such as async_read, * async_read_until, the stream's async_read_some function, or any other * composed operations that perform reads) until this operation completes. * * @param s The stream from which the data is to be read. The type must support * the AsyncReadStream concept. * * @param buffers The dynamic buffer sequence into which the data will be read. * Although the buffers object may be copied as necessary, ownership of the * underlying memory blocks is retained by the caller, which must guarantee * that they remain valid until the completion handler is called. * * @param delim The delimiter string. * * @param token The @ref completion_token that will be used to produce a * completion handler, which will be called when the read completes. * Potential completion tokens include @ref use_future, @ref use_awaitable, * @ref yield_context, or a function object with the correct completion * signature. The function signature of the completion handler must be: * @code void handler( * // Result of operation. * const asio::error_code& error, * * // The number of bytes in the dynamic buffer sequence's * // get area up to and including the delimiter. * std::size_t bytes_transferred * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the completion handler will not be invoked from within this function. * On immediate completion, invocation of the handler will be performed in a * manner equivalent to using asio::async_immediate(). * * @par Completion Signature * @code void(asio::error_code, std::size_t) @endcode * * @note After a successful async_read_until operation, the dynamic buffer * sequence may contain additional data beyond the delimiter. An application * will typically leave that data in the dynamic buffer sequence for a * subsequent async_read_until operation to examine. * * @par Example * To asynchronously read data into a @c std::string until a CR-LF sequence is * encountered: * @code std::string data; * ... * void handler(const asio::error_code& e, std::size_t size) * { * if (!e) * { * std::string line = data.substr(0, n); * data.erase(0, n); * ... * } * } * ... * asio::async_read_until(s, data, "\r\n", handler); @endcode * After the @c async_read_until operation completes successfully, the string * @c data contains the delimiter: * @code { 'a', 'b', ..., 'c', '\r', '\n', 'd', 'e', ... } @endcode * The call to @c substr then extracts the data up to and including the * delimiter, so that the string @c line contains: * @code { 'a', 'b', ..., 'c', '\r', '\n' } @endcode * After the call to @c erase, the remaining data is left in the string @c data * as follows: * @code { 'd', 'e', ... } @endcode * This data may be the start of a new line, to be extracted by a subsequent * @c async_read_until operation. * * @par Per-Operation Cancellation * This asynchronous operation supports cancellation for the following * asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * if they are also supported by the @c AsyncReadStream type's * @c async_read_some operation. */ template <typename AsyncReadStream, typename DynamicBuffer_v2, ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code, std::size_t)) ReadToken = default_completion_token_t< typename AsyncReadStream::executor_type>> inline auto async_read_until(AsyncReadStream& s, DynamicBuffer_v2 buffers, ASIO_STRING_VIEW_PARAM delim, ReadToken&& token = default_completion_token_t< typename AsyncReadStream::executor_type>(), constraint_t< is_dynamic_buffer_v2<DynamicBuffer_v2>::value > = 0) -> decltype( async_initiate<ReadToken, void (asio::error_code, std::size_t)>( declval<detail::initiate_async_read_until_delim_string_v2< AsyncReadStream>>(), token, static_cast<DynamicBuffer_v2&&>(buffers), static_cast<std::string>(delim))) { return async_initiate<ReadToken, void (asio::error_code, std::size_t)>( detail::initiate_async_read_until_delim_string_v2<AsyncReadStream>(s), token, static_cast<DynamicBuffer_v2&&>(buffers), static_cast<std::string>(delim)); } #if !defined(ASIO_NO_EXTENSIONS) #if defined(ASIO_HAS_BOOST_REGEX) \ || defined(GENERATING_DOCUMENTATION) /// Start an asynchronous operation to read data into a dynamic buffer sequence /// until some part of its data matches a regular expression. /** * This function is used to asynchronously read data into the specified dynamic * buffer sequence until the dynamic buffer sequence's get area contains some * data that matches a regular expression. It is an initiating function for an * @ref asynchronous_operation, and always returns immediately. The * asynchronous operation will continue until one of the following conditions * is true: * * @li A substring of the dynamic buffer sequence's get area matches the regular * expression. * * @li An error occurred. * * This operation is implemented in terms of zero or more calls to the stream's * async_read_some function, and is known as a <em>composed operation</em>. If * the dynamic buffer sequence's get area already contains data that matches * the regular expression, this asynchronous operation completes immediately. * The program must ensure that the stream performs no other read operations * (such as async_read, async_read_until, the stream's async_read_some * function, or any other composed operations that perform reads) until this * operation completes. * * @param s The stream from which the data is to be read. The type must support * the AsyncReadStream concept. * * @param buffers The dynamic buffer sequence into which the data will be read. * Although the buffers object may be copied as necessary, ownership of the * underlying memory blocks is retained by the caller, which must guarantee * that they remain valid until the completion handler is called. * * @param expr The regular expression. * * @param token The @ref completion_token that will be used to produce a * completion handler, which will be called when the read completes. * Potential completion tokens include @ref use_future, @ref use_awaitable, * @ref yield_context, or a function object with the correct completion * signature. The function signature of the completion handler must be: * @code void handler( * // Result of operation. * const asio::error_code& error, * * // The number of bytes in the dynamic buffer * // sequence's get area up to and including the * // substring that matches the regular expression. * // 0 if an error occurred. * std::size_t bytes_transferred * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the completion handler will not be invoked from within this function. * On immediate completion, invocation of the handler will be performed in a * manner equivalent to using asio::async_immediate(). * * @par Completion Signature * @code void(asio::error_code, std::size_t) @endcode * * @note After a successful async_read_until operation, the dynamic buffer * sequence may contain additional data beyond that which matched the regular * expression. An application will typically leave that data in the dynamic * buffer sequence for a subsequent async_read_until operation to examine. * * @par Example * To asynchronously read data into a @c std::string until a CR-LF sequence is * encountered: * @code std::string data; * ... * void handler(const asio::error_code& e, std::size_t size) * { * if (!e) * { * std::string line = data.substr(0, n); * data.erase(0, n); * ... * } * } * ... * asio::async_read_until(s, data, * boost::regex("\r\n"), handler); @endcode * After the @c async_read_until operation completes successfully, the string * @c data contains the data which matched the regular expression: * @code { 'a', 'b', ..., 'c', '\r', '\n', 'd', 'e', ... } @endcode * The call to @c substr then extracts the data up to and including the match, * so that the string @c line contains: * @code { 'a', 'b', ..., 'c', '\r', '\n' } @endcode * After the call to @c erase, the remaining data is left in the string @c data * as follows: * @code { 'd', 'e', ... } @endcode * This data may be the start of a new line, to be extracted by a subsequent * @c async_read_until operation. * * @par Per-Operation Cancellation * This asynchronous operation supports cancellation for the following * asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * if they are also supported by the @c AsyncReadStream type's * @c async_read_some operation. */ template <typename AsyncReadStream, typename DynamicBuffer_v2, typename Traits, ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code, std::size_t)) ReadToken = default_completion_token_t< typename AsyncReadStream::executor_type>> inline auto async_read_until(AsyncReadStream& s, DynamicBuffer_v2 buffers, const boost::basic_regex<char, Traits>& expr, ReadToken&& token = default_completion_token_t< typename AsyncReadStream::executor_type>(), constraint_t< is_dynamic_buffer_v2<DynamicBuffer_v2>::value > = 0) -> decltype( async_initiate<ReadToken, void (asio::error_code, std::size_t)>( declval<detail::initiate_async_read_until_expr_v2<AsyncReadStream>>(), token, static_cast<DynamicBuffer_v2&&>(buffers), expr)) { return async_initiate<ReadToken, void (asio::error_code, std::size_t)>( detail::initiate_async_read_until_expr_v2<AsyncReadStream>(s), token, static_cast<DynamicBuffer_v2&&>(buffers), expr); } #endif // defined(ASIO_HAS_BOOST_REGEX) // || defined(GENERATING_DOCUMENTATION) /// Start an asynchronous operation to read data into a dynamic buffer sequence /// until a function object indicates a match. /** * This function is used to asynchronously read data into the specified dynamic * buffer sequence until a user-defined match condition function object, when * applied to the data contained in the dynamic buffer sequence, indicates a * successful match. It is an initiating function for an @ref * asynchronous_operation, and always returns immediately. The asynchronous * operation will continue until one of the following conditions is true: * * @li The match condition function object returns a std::pair where the second * element evaluates to true. * * @li An error occurred. * * This operation is implemented in terms of zero or more calls to the stream's * async_read_some function, and is known as a <em>composed operation</em>. If * the match condition function object already indicates a match, this * asynchronous operation completes immediately. The program must ensure that * the stream performs no other read operations (such as async_read, * async_read_until, the stream's async_read_some function, or any other * composed operations that perform reads) until this operation completes. * * @param s The stream from which the data is to be read. The type must support * the AsyncReadStream concept. * * @param buffers The dynamic buffer sequence into which the data will be read. * Although the buffers object may be copied as necessary, ownership of the * underlying memory blocks is retained by the caller, which must guarantee * that they remain valid until the completion handler is called. * * @param match_condition The function object to be called to determine whether * a match exists. The signature of the function object must be: * @code pair<iterator, bool> match_condition(iterator begin, iterator end); * @endcode * where @c iterator represents the type: * @code buffers_iterator<typename DynamicBuffer_v2::const_buffers_type> * @endcode * The iterator parameters @c begin and @c end define the range of bytes to be * scanned to determine whether there is a match. The @c first member of the * return value is an iterator marking one-past-the-end of the bytes that have * been consumed by the match function. This iterator is used to calculate the * @c begin parameter for any subsequent invocation of the match condition. The * @c second member of the return value is true if a match has been found, false * otherwise. * * @param token The @ref completion_token that will be used to produce a * completion handler, which will be called when the read completes. * Potential completion tokens include @ref use_future, @ref use_awaitable, * @ref yield_context, or a function object with the correct completion * signature. The function signature of the completion handler must be: * @code void handler( * // Result of operation. * const asio::error_code& error, * * // The number of bytes in the dynamic buffer sequence's * // get area that have been fully consumed by the match * // function. O if an error occurred. * std::size_t bytes_transferred * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the completion handler will not be invoked from within this function. * On immediate completion, invocation of the handler will be performed in a * manner equivalent to using asio::async_immediate(). * * @note After a successful async_read_until operation, the dynamic buffer * sequence may contain additional data beyond that which matched the function * object. An application will typically leave that data in the dynamic buffer * sequence for a subsequent async_read_until operation to examine. * * @par Completion Signature * @code void(asio::error_code, std::size_t) @endcode * * @note The default implementation of the @c is_match_condition type trait * evaluates to true for function pointers and function objects with a * @c result_type typedef. It must be specialised for other user-defined * function objects. * * @par Examples * To asynchronously read data into a @c std::string until whitespace is * encountered: * @code typedef asio::buffers_iterator< * asio::const_buffers_1> iterator; * * std::pair<iterator, bool> * match_whitespace(iterator begin, iterator end) * { * iterator i = begin; * while (i != end) * if (std::isspace(*i++)) * return std::make_pair(i, true); * return std::make_pair(i, false); * } * ... * void handler(const asio::error_code& e, std::size_t size); * ... * std::string data; * asio::async_read_until(s, data, match_whitespace, handler); * @endcode * * To asynchronously read data into a @c std::string until a matching character * is found: * @code class match_char * { * public: * explicit match_char(char c) : c_(c) {} * * template <typename Iterator> * std::pair<Iterator, bool> operator()( * Iterator begin, Iterator end) const * { * Iterator i = begin; * while (i != end) * if (c_ == *i++) * return std::make_pair(i, true); * return std::make_pair(i, false); * } * * private: * char c_; * }; * * namespace asio { * template <> struct is_match_condition<match_char> * : public boost::true_type {}; * } // namespace asio * ... * void handler(const asio::error_code& e, std::size_t size); * ... * std::string data; * asio::async_read_until(s, data, match_char('a'), handler); * @endcode * * @par Per-Operation Cancellation * This asynchronous operation supports cancellation for the following * asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * if they are also supported by the @c AsyncReadStream type's * @c async_read_some operation. */ template <typename AsyncReadStream, typename DynamicBuffer_v2, typename MatchCondition, ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code, std::size_t)) ReadToken = default_completion_token_t< typename AsyncReadStream::executor_type>> inline auto async_read_until(AsyncReadStream& s, DynamicBuffer_v2 buffers, MatchCondition match_condition, ReadToken&& token = default_completion_token_t< typename AsyncReadStream::executor_type>(), constraint_t< is_match_condition<MatchCondition>::value > = 0, constraint_t< is_dynamic_buffer_v2<DynamicBuffer_v2>::value > = 0) -> decltype( async_initiate<ReadToken, void (asio::error_code, std::size_t)>( declval<detail::initiate_async_read_until_match_v2<AsyncReadStream>>(), token, static_cast<DynamicBuffer_v2&&>(buffers), match_condition)) { return async_initiate<ReadToken, void (asio::error_code, std::size_t)>( detail::initiate_async_read_until_match_v2<AsyncReadStream>(s), token, static_cast<DynamicBuffer_v2&&>(buffers), match_condition); } #endif // !defined(ASIO_NO_EXTENSIONS) /*@}*/ } // namespace asio #include "asio/detail/pop_options.hpp" #include "asio/impl/read_until.hpp" #endif // ASIO_READ_UNTIL_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/unyield.hpp
// // unyield.hpp // ~~~~~~~~~~~ // // 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) // #ifdef reenter # undef reenter #endif #ifdef yield # undef yield #endif #ifdef fork # undef fork #endif
0
repos/asio/asio/include
repos/asio/asio/include/asio/signal_set.hpp
// // signal_set.hpp // ~~~~~~~~~~~~~~ // // 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) // #ifndef ASIO_SIGNAL_SET_HPP #define ASIO_SIGNAL_SET_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include "asio/basic_signal_set.hpp" namespace asio { /// Typedef for the typical usage of a signal set. typedef basic_signal_set<> signal_set; } // namespace asio #endif // ASIO_SIGNAL_SET_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/writable_pipe.hpp
// // writable_pipe.hpp // ~~~~~~~~~~~~~~~~~ // // 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) // #ifndef ASIO_WRITABLE_PIPE_HPP #define ASIO_WRITABLE_PIPE_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #if defined(ASIO_HAS_PIPE) \ || defined(GENERATING_DOCUMENTATION) #include "asio/basic_writable_pipe.hpp" namespace asio { /// Typedef for the typical usage of a writable pipe. typedef basic_writable_pipe<> writable_pipe; } // namespace asio #endif // defined(ASIO_HAS_PIPE) // || defined(GENERATING_DOCUMENTATION) #endif // ASIO_WRITABLE_PIPE_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/executor_work_guard.hpp
// // executor_work_guard.hpp // ~~~~~~~~~~~~~~~~~~~~~~~ // // 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) // #ifndef ASIO_EXECUTOR_WORK_GUARD_HPP #define ASIO_EXECUTOR_WORK_GUARD_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include "asio/associated_executor.hpp" #include "asio/detail/type_traits.hpp" #include "asio/execution.hpp" #include "asio/is_executor.hpp" #include "asio/detail/push_options.hpp" namespace asio { #if !defined(ASIO_EXECUTOR_WORK_GUARD_DECL) #define ASIO_EXECUTOR_WORK_GUARD_DECL template <typename Executor, typename = void, typename = void> class executor_work_guard; #endif // !defined(ASIO_EXECUTOR_WORK_GUARD_DECL) #if defined(GENERATING_DOCUMENTATION) /// An object of type @c executor_work_guard controls ownership of outstanding /// executor work within a scope. template <typename Executor> class executor_work_guard { public: /// The underlying executor type. typedef Executor executor_type; /// Constructs a @c executor_work_guard object for the specified executor. /** * Stores a copy of @c e and calls <tt>on_work_started()</tt> on it. */ explicit executor_work_guard(const executor_type& e) noexcept; /// Copy constructor. executor_work_guard(const executor_work_guard& other) noexcept; /// Move constructor. executor_work_guard(executor_work_guard&& other) noexcept; /// Destructor. /** * Unless the object has already been reset, or is in a moved-from state, * calls <tt>on_work_finished()</tt> on the stored executor. */ ~executor_work_guard(); /// Obtain the associated executor. executor_type get_executor() const noexcept; /// Whether the executor_work_guard object owns some outstanding work. bool owns_work() const noexcept; /// Indicate that the work is no longer outstanding. /** * Unless the object has already been reset, or is in a moved-from state, * calls <tt>on_work_finished()</tt> on the stored executor. */ void reset() noexcept; }; #endif // defined(GENERATING_DOCUMENTATION) #if !defined(GENERATING_DOCUMENTATION) #if !defined(ASIO_NO_TS_EXECUTORS) template <typename Executor> class executor_work_guard<Executor, enable_if_t< is_executor<Executor>::value >> { public: typedef Executor executor_type; explicit executor_work_guard(const executor_type& e) noexcept : executor_(e), owns_(true) { executor_.on_work_started(); } executor_work_guard(const executor_work_guard& other) noexcept : executor_(other.executor_), owns_(other.owns_) { if (owns_) executor_.on_work_started(); } executor_work_guard(executor_work_guard&& other) noexcept : executor_(static_cast<Executor&&>(other.executor_)), owns_(other.owns_) { other.owns_ = false; } ~executor_work_guard() { if (owns_) executor_.on_work_finished(); } executor_type get_executor() const noexcept { return executor_; } bool owns_work() const noexcept { return owns_; } void reset() noexcept { if (owns_) { executor_.on_work_finished(); owns_ = false; } } private: // Disallow assignment. executor_work_guard& operator=(const executor_work_guard&); executor_type executor_; bool owns_; }; #endif // !defined(ASIO_NO_TS_EXECUTORS) template <typename Executor> class executor_work_guard<Executor, enable_if_t< !is_executor<Executor>::value >, enable_if_t< execution::is_executor<Executor>::value >> { public: typedef Executor executor_type; explicit executor_work_guard(const executor_type& e) noexcept : executor_(e), owns_(true) { new (&work_) work_type(asio::prefer(executor_, execution::outstanding_work.tracked)); } executor_work_guard(const executor_work_guard& other) noexcept : executor_(other.executor_), owns_(other.owns_) { if (owns_) { new (&work_) work_type(asio::prefer(executor_, execution::outstanding_work.tracked)); } } executor_work_guard(executor_work_guard&& other) noexcept : executor_(static_cast<Executor&&>(other.executor_)), owns_(other.owns_) { if (owns_) { new (&work_) work_type( static_cast<work_type&&>( *static_cast<work_type*>( static_cast<void*>(&other.work_)))); other.owns_ = false; } } ~executor_work_guard() { if (owns_) static_cast<work_type*>(static_cast<void*>(&work_))->~work_type(); } executor_type get_executor() const noexcept { return executor_; } bool owns_work() const noexcept { return owns_; } void reset() noexcept { if (owns_) { static_cast<work_type*>(static_cast<void*>(&work_))->~work_type(); owns_ = false; } } private: // Disallow assignment. executor_work_guard& operator=(const executor_work_guard&); typedef decay_t< prefer_result_t< const executor_type&, execution::outstanding_work_t::tracked_t > > work_type; executor_type executor_; aligned_storage_t<sizeof(work_type), alignment_of<work_type>::value> work_; bool owns_; }; #endif // !defined(GENERATING_DOCUMENTATION) /// Create an @ref executor_work_guard object. /** * @param ex An executor. * * @returns A work guard constructed with the specified executor. */ template <typename Executor> ASIO_NODISCARD inline executor_work_guard<Executor> make_work_guard(const Executor& ex, constraint_t< is_executor<Executor>::value || execution::is_executor<Executor>::value > = 0) { return executor_work_guard<Executor>(ex); } /// Create an @ref executor_work_guard object. /** * @param ctx An execution context, from which an executor will be obtained. * * @returns A work guard constructed with the execution context's executor, * obtained by performing <tt>ctx.get_executor()</tt>. */ template <typename ExecutionContext> ASIO_NODISCARD inline executor_work_guard<typename ExecutionContext::executor_type> make_work_guard(ExecutionContext& ctx, constraint_t< is_convertible<ExecutionContext&, execution_context&>::value > = 0) { return executor_work_guard<typename ExecutionContext::executor_type>( ctx.get_executor()); } /// Create an @ref executor_work_guard object. /** * @param t An arbitrary object, such as a completion handler, for which the * associated executor will be obtained. * * @returns A work guard constructed with the associated executor of the object * @c t, which is obtained as if by calling <tt>get_associated_executor(t)</tt>. */ template <typename T> ASIO_NODISCARD inline executor_work_guard< typename constraint_t< !is_executor<T>::value && !execution::is_executor<T>::value && !is_convertible<T&, execution_context&>::value, associated_executor<T> >::type> make_work_guard(const T& t) { return executor_work_guard<associated_executor_t<T>>( associated_executor<T>::get(t)); } /// Create an @ref executor_work_guard object. /** * @param t An arbitrary object, such as a completion handler, for which the * associated executor will be obtained. * * @param ex An executor to be used as the candidate object when determining the * associated executor. * * @returns A work guard constructed with the associated executor of the object * @c t, which is obtained as if by calling <tt>get_associated_executor(t, * ex)</tt>. */ template <typename T, typename Executor> ASIO_NODISCARD inline executor_work_guard<associated_executor_t<T, Executor>> make_work_guard(const T& t, const Executor& ex, constraint_t< is_executor<Executor>::value || execution::is_executor<Executor>::value > = 0) { return executor_work_guard<associated_executor_t<T, Executor>>( associated_executor<T, Executor>::get(t, ex)); } /// Create an @ref executor_work_guard object. /** * @param t An arbitrary object, such as a completion handler, for which the * associated executor will be obtained. * * @param ctx An execution context, from which an executor is obtained to use as * the candidate object for determining the associated executor. * * @returns A work guard constructed with the associated executor of the object * @c t, which is obtained as if by calling <tt>get_associated_executor(t, * ctx.get_executor())</tt>. */ template <typename T, typename ExecutionContext> ASIO_NODISCARD inline executor_work_guard< associated_executor_t<T, typename ExecutionContext::executor_type>> make_work_guard(const T& t, ExecutionContext& ctx, constraint_t< !is_executor<T>::value > = 0, constraint_t< !execution::is_executor<T>::value > = 0, constraint_t< !is_convertible<T&, execution_context&>::value > = 0, constraint_t< is_convertible<ExecutionContext&, execution_context&>::value > = 0) { return executor_work_guard< associated_executor_t<T, typename ExecutionContext::executor_type>>( associated_executor<T, typename ExecutionContext::executor_type>::get( t, ctx.get_executor())); } } // namespace asio #include "asio/detail/pop_options.hpp" #endif // ASIO_EXECUTOR_WORK_GUARD_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/deferred.hpp
// // deferred.hpp // ~~~~~~~~~~~~ // // 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) // #ifndef ASIO_DEFERRED_HPP #define ASIO_DEFERRED_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include <tuple> #include "asio/associator.hpp" #include "asio/async_result.hpp" #include "asio/detail/type_traits.hpp" #include "asio/detail/utility.hpp" #include "asio/detail/push_options.hpp" namespace asio { /// Trait for detecting objects that are usable as deferred operations. template <typename T> struct is_deferred : false_type { }; /// Helper type to wrap multiple completion signatures. template <typename... Signatures> struct deferred_signatures { }; namespace detail { // Helper trait for getting the completion signatures of the tail in a sequence // when invoked with the specified arguments. template <typename Tail, typename... Signatures> struct deferred_sequence_signatures; template <typename Tail, typename R, typename... Args, typename... Signatures> struct deferred_sequence_signatures<Tail, R(Args...), Signatures...> : completion_signature_of<decltype(declval<Tail>()(declval<Args>()...))> { static_assert( !is_same<decltype(declval<Tail>()(declval<Args>()...)), void>::value, "deferred functions must produce a deferred return type"); }; // Completion handler for the head component of a deferred sequence. template <typename Handler, typename Tail> class deferred_sequence_handler { public: template <typename H, typename T> explicit deferred_sequence_handler(H&& handler, T&& tail) : handler_(static_cast<H&&>(handler)), tail_(static_cast<T&&>(tail)) { } template <typename... Args> void operator()(Args&&... args) { static_cast<Tail&&>(tail_)( static_cast<Args&&>(args)...)( static_cast<Handler&&>(handler_)); } //private: Handler handler_; Tail tail_; }; template <typename Head, typename Tail, typename... Signatures> class deferred_sequence_base { private: struct initiate { template <typename Handler> void operator()(Handler&& handler, Head head, Tail&& tail) { static_cast<Head&&>(head)( deferred_sequence_handler<decay_t<Handler>, decay_t<Tail>>( static_cast<Handler&&>(handler), static_cast<Tail&&>(tail))); } }; Head head_; Tail tail_; public: template <typename H, typename T> constexpr explicit deferred_sequence_base(H&& head, T&& tail) : head_(static_cast<H&&>(head)), tail_(static_cast<T&&>(tail)) { } template <ASIO_COMPLETION_TOKEN_FOR(Signatures...) CompletionToken> auto operator()(CompletionToken&& token) && -> decltype( async_initiate<CompletionToken, Signatures...>( initiate(), token, static_cast<Head&&>(this->head_), static_cast<Tail&&>(this->tail_))) { return async_initiate<CompletionToken, Signatures...>(initiate(), token, static_cast<Head&&>(head_), static_cast<Tail&&>(tail_)); } template <ASIO_COMPLETION_TOKEN_FOR(Signatures...) CompletionToken> auto operator()(CompletionToken&& token) const & -> decltype( async_initiate<CompletionToken, Signatures...>( initiate(), token, this->head_, this->tail_)) { return async_initiate<CompletionToken, Signatures...>( initiate(), token, head_, tail_); } }; // Two-step application of variadic Signatures to determine correct base type. template <typename Head, typename Tail> struct deferred_sequence_types { template <typename... Signatures> struct op1 { typedef deferred_sequence_base<Head, Tail, Signatures...> type; }; template <typename... Signatures> struct op2 { typedef typename deferred_sequence_signatures<Tail, Signatures...>::template apply<op1>::type::type type; }; typedef typename completion_signature_of<Head>::template apply<op2>::type::type base; }; } // namespace detail /// Used to represent an empty deferred action. struct deferred_noop { /// No effect. template <typename... Args> void operator()(Args&&...) && { } /// No effect. template <typename... Args> void operator()(Args&&...) const & { } }; #if !defined(GENERATING_DOCUMENTATION) template <> struct is_deferred<deferred_noop> : true_type { }; #endif // !defined(GENERATING_DOCUMENTATION) /// Tag type to disambiguate deferred constructors. struct deferred_init_tag {}; /// Wraps a function object so that it may be used as an element in a deferred /// composition. template <typename Function> class deferred_function { public: /// Constructor. template <typename F> constexpr explicit deferred_function(deferred_init_tag, F&& function) : function_(static_cast<F&&>(function)) { } //private: Function function_; public: template <typename... Args> auto operator()(Args&&... args) && -> decltype( static_cast<Function&&>(this->function_)(static_cast<Args&&>(args)...)) { return static_cast<Function&&>(function_)(static_cast<Args&&>(args)...); } template <typename... Args> auto operator()(Args&&... args) const & -> decltype(Function(function_)(static_cast<Args&&>(args)...)) { return Function(function_)(static_cast<Args&&>(args)...); } }; #if !defined(GENERATING_DOCUMENTATION) template <typename Function> struct is_deferred<deferred_function<Function>> : true_type { }; #endif // !defined(GENERATING_DOCUMENTATION) /// Encapsulates deferred values. template <typename... Values> class ASIO_NODISCARD deferred_values { private: std::tuple<Values...> values_; struct initiate { template <typename Handler, typename... V> void operator()(Handler handler, V&&... values) { static_cast<Handler&&>(handler)(static_cast<V&&>(values)...); } }; template <typename CompletionToken, std::size_t... I> auto invoke_helper(CompletionToken&& token, detail::index_sequence<I...>) -> decltype( async_initiate<CompletionToken, void(Values...)>(initiate(), token, std::get<I>(static_cast<std::tuple<Values...>&&>(this->values_))...)) { return async_initiate<CompletionToken, void(Values...)>(initiate(), token, std::get<I>(static_cast<std::tuple<Values...>&&>(values_))...); } template <typename CompletionToken, std::size_t... I> auto const_invoke_helper(CompletionToken&& token, detail::index_sequence<I...>) -> decltype( async_initiate<CompletionToken, void(Values...)>( initiate(), token, std::get<I>(values_)...)) { return async_initiate<CompletionToken, void(Values...)>( initiate(), token, std::get<I>(values_)...); } public: /// Construct a deferred asynchronous operation from the arguments to an /// initiation function object. template <typename... V> constexpr explicit deferred_values( deferred_init_tag, V&&... values) : values_(static_cast<V&&>(values)...) { } /// Initiate the deferred operation using the supplied completion token. template <ASIO_COMPLETION_TOKEN_FOR(void(Values...)) CompletionToken> auto operator()(CompletionToken&& token) && -> decltype( this->invoke_helper( static_cast<CompletionToken&&>(token), detail::index_sequence_for<Values...>())) { return this->invoke_helper( static_cast<CompletionToken&&>(token), detail::index_sequence_for<Values...>()); } template <ASIO_COMPLETION_TOKEN_FOR(void(Values...)) CompletionToken> auto operator()(CompletionToken&& token) const & -> decltype( this->const_invoke_helper( static_cast<CompletionToken&&>(token), detail::index_sequence_for<Values...>())) { return this->const_invoke_helper( static_cast<CompletionToken&&>(token), detail::index_sequence_for<Values...>()); } }; #if !defined(GENERATING_DOCUMENTATION) template <typename... Values> struct is_deferred<deferred_values<Values...>> : true_type { }; #endif // !defined(GENERATING_DOCUMENTATION) /// Encapsulates a deferred asynchronous operation. template <typename Signature, typename Initiation, typename... InitArgs> class ASIO_NODISCARD deferred_async_operation { private: typedef decay_t<Initiation> initiation_t; initiation_t initiation_; typedef std::tuple<decay_t<InitArgs>...> init_args_t; init_args_t init_args_; template <typename CompletionToken, std::size_t... I> auto invoke_helper(CompletionToken&& token, detail::index_sequence<I...>) -> decltype( async_initiate<CompletionToken, Signature>( static_cast<initiation_t&&>(initiation_), token, std::get<I>(static_cast<init_args_t&&>(init_args_))...)) { return async_initiate<CompletionToken, Signature>( static_cast<initiation_t&&>(initiation_), token, std::get<I>(static_cast<init_args_t&&>(init_args_))...); } template <typename CompletionToken, std::size_t... I> auto const_invoke_helper(CompletionToken&& token, detail::index_sequence<I...>) const & -> decltype( async_initiate<CompletionToken, Signature>( conditional_t<true, initiation_t, CompletionToken>(initiation_), token, std::get<I>(init_args_)...)) { return async_initiate<CompletionToken, Signature>( initiation_t(initiation_), token, std::get<I>(init_args_)...); } public: /// Construct a deferred asynchronous operation from the arguments to an /// initiation function object. template <typename I, typename... A> constexpr explicit deferred_async_operation( deferred_init_tag, I&& initiation, A&&... init_args) : initiation_(static_cast<I&&>(initiation)), init_args_(static_cast<A&&>(init_args)...) { } /// Initiate the asynchronous operation using the supplied completion token. template <ASIO_COMPLETION_TOKEN_FOR(Signature) CompletionToken> auto operator()(CompletionToken&& token) && -> decltype( this->invoke_helper( static_cast<CompletionToken&&>(token), detail::index_sequence_for<InitArgs...>())) { return this->invoke_helper( static_cast<CompletionToken&&>(token), detail::index_sequence_for<InitArgs...>()); } template <ASIO_COMPLETION_TOKEN_FOR(Signature) CompletionToken> auto operator()(CompletionToken&& token) const & -> decltype( this->const_invoke_helper( static_cast<CompletionToken&&>(token), detail::index_sequence_for<InitArgs...>())) { return this->const_invoke_helper( static_cast<CompletionToken&&>(token), detail::index_sequence_for<InitArgs...>()); } }; /// Encapsulates a deferred asynchronous operation thas has multiple completion /// signatures. template <typename... Signatures, typename Initiation, typename... InitArgs> class ASIO_NODISCARD deferred_async_operation< deferred_signatures<Signatures...>, Initiation, InitArgs...> { private: typedef decay_t<Initiation> initiation_t; initiation_t initiation_; typedef std::tuple<decay_t<InitArgs>...> init_args_t; init_args_t init_args_; template <typename CompletionToken, std::size_t... I> auto invoke_helper(CompletionToken&& token, detail::index_sequence<I...>) -> decltype( async_initiate<CompletionToken, Signatures...>( static_cast<initiation_t&&>(initiation_), token, std::get<I>(static_cast<init_args_t&&>(init_args_))...)) { return async_initiate<CompletionToken, Signatures...>( static_cast<initiation_t&&>(initiation_), token, std::get<I>(static_cast<init_args_t&&>(init_args_))...); } template <typename CompletionToken, std::size_t... I> auto const_invoke_helper(CompletionToken&& token, detail::index_sequence<I...>) const & -> decltype( async_initiate<CompletionToken, Signatures...>( initiation_t(initiation_), token, std::get<I>(init_args_)...)) { return async_initiate<CompletionToken, Signatures...>( initiation_t(initiation_), token, std::get<I>(init_args_)...); } public: /// Construct a deferred asynchronous operation from the arguments to an /// initiation function object. template <typename I, typename... A> constexpr explicit deferred_async_operation( deferred_init_tag, I&& initiation, A&&... init_args) : initiation_(static_cast<I&&>(initiation)), init_args_(static_cast<A&&>(init_args)...) { } /// Initiate the asynchronous operation using the supplied completion token. template <ASIO_COMPLETION_TOKEN_FOR(Signatures...) CompletionToken> auto operator()(CompletionToken&& token) && -> decltype( this->invoke_helper( static_cast<CompletionToken&&>(token), detail::index_sequence_for<InitArgs...>())) { return this->invoke_helper( static_cast<CompletionToken&&>(token), detail::index_sequence_for<InitArgs...>()); } template <ASIO_COMPLETION_TOKEN_FOR(Signatures...) CompletionToken> auto operator()(CompletionToken&& token) const & -> decltype( this->const_invoke_helper( static_cast<CompletionToken&&>(token), detail::index_sequence_for<InitArgs...>())) { return this->const_invoke_helper( static_cast<CompletionToken&&>(token), detail::index_sequence_for<InitArgs...>()); } }; #if !defined(GENERATING_DOCUMENTATION) template <typename Signature, typename Initiation, typename... InitArgs> struct is_deferred< deferred_async_operation<Signature, Initiation, InitArgs...>> : true_type { }; #endif // !defined(GENERATING_DOCUMENTATION) /// Defines a link between two consecutive operations in a sequence. template <typename Head, typename Tail> class ASIO_NODISCARD deferred_sequence : public detail::deferred_sequence_types<Head, Tail>::base { public: template <typename H, typename T> constexpr explicit deferred_sequence(deferred_init_tag, H&& head, T&& tail) : detail::deferred_sequence_types<Head, Tail>::base( static_cast<H&&>(head), static_cast<T&&>(tail)) { } #if defined(GENERATING_DOCUMENTATION) template <typename CompletionToken> auto operator()(CompletionToken&& token) &&; template <typename CompletionToken> auto operator()(CompletionToken&& token) const &; #endif // defined(GENERATING_DOCUMENTATION) }; #if !defined(GENERATING_DOCUMENTATION) template <typename Head, typename Tail> struct is_deferred<deferred_sequence<Head, Tail>> : true_type { }; #endif // !defined(GENERATING_DOCUMENTATION) /// Used to represent a deferred conditional branch. template <typename OnTrue = deferred_noop, typename OnFalse = deferred_noop> class ASIO_NODISCARD deferred_conditional { private: template <typename T, typename F> friend class deferred_conditional; // Helper constructor. template <typename T, typename F> explicit deferred_conditional(bool b, T&& on_true, F&& on_false) : on_true_(static_cast<T&&>(on_true)), on_false_(static_cast<F&&>(on_false)), bool_(b) { } OnTrue on_true_; OnFalse on_false_; bool bool_; public: /// Construct a deferred conditional with the value to determine which branch /// will be executed. constexpr explicit deferred_conditional(bool b) : on_true_(), on_false_(), bool_(b) { } /// Invoke the conditional branch bsaed on the stored value. template <typename... Args> auto operator()(Args&&... args) && -> decltype(static_cast<OnTrue&&>(on_true_)(static_cast<Args&&>(args)...)) { if (bool_) { return static_cast<OnTrue&&>(on_true_)(static_cast<Args&&>(args)...); } else { return static_cast<OnFalse&&>(on_false_)(static_cast<Args&&>(args)...); } } template <typename... Args> auto operator()(Args&&... args) const & -> decltype(on_true_(static_cast<Args&&>(args)...)) { if (bool_) { return on_true_(static_cast<Args&&>(args)...); } else { return on_false_(static_cast<Args&&>(args)...); } } /// Set the true branch of the conditional. template <typename T> deferred_conditional<T, OnFalse> then(T on_true, constraint_t< is_deferred<T>::value >* = 0, constraint_t< is_same< conditional_t<true, OnTrue, T>, deferred_noop >::value >* = 0) && { return deferred_conditional<T, OnFalse>( bool_, static_cast<T&&>(on_true), static_cast<OnFalse&&>(on_false_)); } /// Set the false branch of the conditional. template <typename T> deferred_conditional<OnTrue, T> otherwise(T on_false, constraint_t< is_deferred<T>::value >* = 0, constraint_t< !is_same< conditional_t<true, OnTrue, T>, deferred_noop >::value >* = 0, constraint_t< is_same< conditional_t<true, OnFalse, T>, deferred_noop >::value >* = 0) && { return deferred_conditional<OnTrue, T>( bool_, static_cast<OnTrue&&>(on_true_), static_cast<T&&>(on_false)); } }; #if !defined(GENERATING_DOCUMENTATION) template <typename OnTrue, typename OnFalse> struct is_deferred<deferred_conditional<OnTrue, OnFalse>> : true_type { }; #endif // !defined(GENERATING_DOCUMENTATION) /// Class used to specify that an asynchronous operation should return a /// function object to lazily launch the operation. /** * The deferred_t class is used to indicate that an asynchronous operation * should return a function object which is itself an initiation function. A * deferred_t object may be passed as a completion token to an asynchronous * operation, typically as the default completion token: * * @code auto my_deferred_op = my_socket.async_read_some(my_buffer); @endcode * * or by explicitly passing the special value @c asio::deferred: * * @code auto my_deferred_op * = my_socket.async_read_some(my_buffer, * asio::deferred); @endcode * * The initiating function (async_read_some in the above example) returns a * function object that will lazily initiate the operation. */ class deferred_t { public: /// Default constructor. constexpr deferred_t() { } /// Adapts an executor to add the @c deferred_t completion token as the /// default. template <typename InnerExecutor> struct executor_with_default : InnerExecutor { /// Specify @c deferred_t as the default completion token type. typedef deferred_t default_completion_token_type; /// Construct the adapted executor from the inner executor type. template <typename InnerExecutor1> executor_with_default(const InnerExecutor1& ex, constraint_t< conditional_t< !is_same<InnerExecutor1, executor_with_default>::value, is_convertible<InnerExecutor1, InnerExecutor>, false_type >::value > = 0) noexcept : InnerExecutor(ex) { } }; /// Type alias to adapt an I/O object to use @c deferred_t as its /// default completion token type. template <typename T> using as_default_on_t = typename T::template rebind_executor< executor_with_default<typename T::executor_type>>::other; /// Function helper to adapt an I/O object to use @c deferred_t as its /// default completion token type. template <typename T> static typename decay_t<T>::template rebind_executor< executor_with_default<typename decay_t<T>::executor_type> >::other as_default_on(T&& object) { return typename decay_t<T>::template rebind_executor< executor_with_default<typename decay_t<T>::executor_type> >::other(static_cast<T&&>(object)); } /// Creates a new deferred from a function. template <typename Function> constraint_t< !is_deferred<decay_t<Function>>::value, deferred_function<decay_t<Function>> > operator()(Function&& function) const { return deferred_function<decay_t<Function>>( deferred_init_tag{}, static_cast<Function&&>(function)); } /// Passes through anything that is already deferred. template <typename T> constraint_t< is_deferred<decay_t<T>>::value, decay_t<T> > operator()(T&& t) const { return static_cast<T&&>(t); } /// Returns a deferred operation that returns the provided values. template <typename... Args> static constexpr deferred_values<decay_t<Args>...> values(Args&&... args) { return deferred_values<decay_t<Args>...>( deferred_init_tag{}, static_cast<Args&&>(args)...); } /// Creates a conditional object for branching deferred operations. static constexpr deferred_conditional<> when(bool b) { return deferred_conditional<>(b); } }; /// Pipe operator used to chain deferred operations. template <typename Head, typename Tail> inline auto operator|(Head head, Tail&& tail) -> constraint_t< is_deferred<Head>::value, decltype(static_cast<Head&&>(head)(static_cast<Tail&&>(tail))) > { return static_cast<Head&&>(head)(static_cast<Tail&&>(tail)); } /// A @ref completion_token object used to specify that an asynchronous /// operation should return a function object to lazily launch the operation. /** * See the documentation for asio::deferred_t for a usage example. */ ASIO_INLINE_VARIABLE constexpr deferred_t deferred; } // namespace asio #include "asio/detail/pop_options.hpp" #include "asio/impl/deferred.hpp" #endif // ASIO_DEFERRED_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/awaitable.hpp
// // awaitable.hpp // ~~~~~~~~~~~~~ // // 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) // #ifndef ASIO_AWAITABLE_HPP #define ASIO_AWAITABLE_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #if defined(ASIO_HAS_CO_AWAIT) || defined(GENERATING_DOCUMENTATION) #if defined(ASIO_HAS_STD_COROUTINE) # include <coroutine> #else // defined(ASIO_HAS_STD_COROUTINE) # include <experimental/coroutine> #endif // defined(ASIO_HAS_STD_COROUTINE) #include <utility> #include "asio/any_io_executor.hpp" #include "asio/detail/push_options.hpp" namespace asio { namespace detail { #if defined(ASIO_HAS_STD_COROUTINE) using std::coroutine_handle; using std::suspend_always; #else // defined(ASIO_HAS_STD_COROUTINE) using std::experimental::coroutine_handle; using std::experimental::suspend_always; #endif // defined(ASIO_HAS_STD_COROUTINE) template <typename> class awaitable_thread; template <typename, typename> class awaitable_frame; } // namespace detail /// The return type of a coroutine or asynchronous operation. template <typename T, typename Executor = any_io_executor> class ASIO_NODISCARD awaitable { public: /// The type of the awaited value. typedef T value_type; /// The executor type that will be used for the coroutine. typedef Executor executor_type; /// Default constructor. constexpr awaitable() noexcept : frame_(nullptr) { } /// Move constructor. awaitable(awaitable&& other) noexcept : frame_(std::exchange(other.frame_, nullptr)) { } /// Destructor ~awaitable() { if (frame_) frame_->destroy(); } /// Move assignment. awaitable& operator=(awaitable&& other) noexcept { if (this != &other) frame_ = std::exchange(other.frame_, nullptr); return *this; } /// Checks if the awaitable refers to a future result. bool valid() const noexcept { return !!frame_; } #if !defined(GENERATING_DOCUMENTATION) // Support for co_await keyword. bool await_ready() const noexcept { return false; } // Support for co_await keyword. template <class U> void await_suspend( detail::coroutine_handle<detail::awaitable_frame<U, Executor>> h) { frame_->push_frame(&h.promise()); } // Support for co_await keyword. T await_resume() { return awaitable(static_cast<awaitable&&>(*this)).frame_->get(); } #endif // !defined(GENERATING_DOCUMENTATION) private: template <typename> friend class detail::awaitable_thread; template <typename, typename> friend class detail::awaitable_frame; // Not copy constructible or copy assignable. awaitable(const awaitable&) = delete; awaitable& operator=(const awaitable&) = delete; // Construct the awaitable from a coroutine's frame object. explicit awaitable(detail::awaitable_frame<T, Executor>* a) : frame_(a) { } detail::awaitable_frame<T, Executor>* frame_; }; } // namespace asio #include "asio/detail/pop_options.hpp" #include "asio/impl/awaitable.hpp" #endif // defined(ASIO_HAS_CO_AWAIT) || defined(GENERATING_DOCUMENTATION) #endif // ASIO_AWAITABLE_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/uses_executor.hpp
// // uses_executor.hpp // ~~~~~~~~~~~~~~~~~ // // 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) // #ifndef ASIO_USES_EXECUTOR_HPP #define ASIO_USES_EXECUTOR_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include "asio/detail/type_traits.hpp" #include "asio/detail/push_options.hpp" namespace asio { /// A special type, similar to std::nothrow_t, used to disambiguate /// constructors that accept executor arguments. /** * The executor_arg_t struct is an empty structure type used as a unique type * to disambiguate constructor and function overloading. Specifically, some * types have constructors with executor_arg_t as the first argument, * immediately followed by an argument of a type that satisfies the Executor * type requirements. */ struct executor_arg_t { /// Constructor. constexpr executor_arg_t() noexcept { } }; /// A special value, similar to std::nothrow, used to disambiguate constructors /// that accept executor arguments. /** * See asio::executor_arg_t and asio::uses_executor * for more information. */ ASIO_INLINE_VARIABLE constexpr executor_arg_t executor_arg; /// The uses_executor trait detects whether a type T has an associated executor /// that is convertible from type Executor. /** * Meets the BinaryTypeTrait requirements. The Asio library provides a * definition that is derived from false_type. A program may specialize this * template to derive from true_type for a user-defined type T that can be * constructed with an executor, where the first argument of a constructor has * type executor_arg_t and the second argument is convertible from type * Executor. */ template <typename T, typename Executor> struct uses_executor : false_type {}; } // namespace asio #include "asio/detail/pop_options.hpp" #endif // ASIO_USES_EXECUTOR_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/redirect_error.hpp
// // redirect_error.hpp // ~~~~~~~~~~~~~~~~~~ // // 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) // #ifndef ASIO_REDIRECT_ERROR_HPP #define ASIO_REDIRECT_ERROR_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include "asio/detail/type_traits.hpp" #include "asio/error_code.hpp" #include "asio/detail/push_options.hpp" namespace asio { /// A @ref completion_token adapter used to specify that an error produced by an /// asynchronous operation is captured to an error_code variable. /** * The redirect_error_t class is used to indicate that any error_code produced * by an asynchronous operation is captured to a specified variable. */ template <typename CompletionToken> class redirect_error_t { public: /// Constructor. template <typename T> redirect_error_t(T&& completion_token, asio::error_code& ec) : token_(static_cast<T&&>(completion_token)), ec_(ec) { } //private: CompletionToken token_; asio::error_code& ec_; }; /// A function object type that adapts a @ref completion_token to capture /// error_code values to a variable. /** * May also be used directly as a completion token, in which case it adapts the * asynchronous operation's default completion token (or asio::deferred * if no default is available). */ class partial_redirect_error { public: /// Constructor that specifies the variable used to capture error_code values. explicit partial_redirect_error(asio::error_code& ec) : ec_(ec) { } /// Adapt a @ref completion_token to specify that the completion handler /// should capture error_code values to a variable. template <typename CompletionToken> ASIO_NODISCARD inline constexpr redirect_error_t<decay_t<CompletionToken>> operator()(CompletionToken&& completion_token) const { return redirect_error_t<decay_t<CompletionToken>>( static_cast<CompletionToken&&>(completion_token), ec_); } //private: asio::error_code& ec_; }; /// Create a partial completion token adapter that captures error_code values /// to a variable. ASIO_NODISCARD inline partial_redirect_error redirect_error(asio::error_code& ec) { return partial_redirect_error(ec); } /// Adapt a @ref completion_token to capture error_code values to a variable. template <typename CompletionToken> ASIO_NODISCARD inline redirect_error_t<decay_t<CompletionToken>> redirect_error(CompletionToken&& completion_token, asio::error_code& ec) { return redirect_error_t<decay_t<CompletionToken>>( static_cast<CompletionToken&&>(completion_token), ec); } } // namespace asio #include "asio/detail/pop_options.hpp" #include "asio/impl/redirect_error.hpp" #endif // ASIO_REDIRECT_ERROR_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/co_composed.hpp
// // co_composed.hpp // ~~~~~~~~~~~~~~~ // // 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) // #ifndef ASIO_CO_COMPOSED_HPP #define ASIO_CO_COMPOSED_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #if defined(ASIO_HAS_CO_AWAIT) || defined(GENERATING_DOCUMENTATION) #include <new> #include <tuple> #include <variant> #include "asio/associated_cancellation_slot.hpp" #include "asio/associator.hpp" #include "asio/async_result.hpp" #include "asio/cancellation_state.hpp" #include "asio/detail/composed_work.hpp" #include "asio/detail/recycling_allocator.hpp" #include "asio/detail/throw_error.hpp" #include "asio/detail/type_traits.hpp" #include "asio/error.hpp" #if defined(ASIO_HAS_STD_COROUTINE) # include <coroutine> #else // defined(ASIO_HAS_STD_COROUTINE) # include <experimental/coroutine> #endif // defined(ASIO_HAS_STD_COROUTINE) #if defined(ASIO_ENABLE_HANDLER_TRACKING) # if defined(ASIO_HAS_SOURCE_LOCATION) # include "asio/detail/source_location.hpp" # endif // defined(ASIO_HAS_SOURCE_LOCATION) #endif // defined(ASIO_ENABLE_HANDLER_TRACKING) #include "asio/detail/push_options.hpp" namespace asio { namespace detail { #if defined(ASIO_HAS_STD_COROUTINE) using std::coroutine_handle; using std::suspend_always; using std::suspend_never; #else // defined(ASIO_HAS_STD_COROUTINE) using std::experimental::coroutine_handle; using std::experimental::suspend_always; using std::experimental::suspend_never; #endif // defined(ASIO_HAS_STD_COROUTINE) using asio::detail::composed_io_executors; using asio::detail::composed_work; using asio::detail::composed_work_guard; using asio::detail::get_composed_io_executor; using asio::detail::make_composed_io_executors; using asio::detail::recycling_allocator; using asio::detail::throw_error; template <typename Executors, typename Handler, typename Return> class co_composed_state; template <typename Executors, typename Handler, typename Return> class co_composed_handler_base; template <typename Executors, typename Handler, typename Return> class co_composed_promise; template <ASIO_COMPLETION_SIGNATURE... Signatures> class co_composed_returns { }; struct co_composed_on_suspend { void (*fn_)(void*) = nullptr; void* arg_ = nullptr; }; template <typename... T> struct co_composed_completion : std::tuple<T&&...> { template <typename... U> co_composed_completion(U&&... u) noexcept : std::tuple<T&&...>(static_cast<U&&>(u)...) { } }; template <typename Executors, typename Handler, typename Return, typename Signature> class co_composed_state_return_overload; template <typename Executors, typename Handler, typename Return, typename R, typename... Args> class co_composed_state_return_overload< Executors, Handler, Return, R(Args...)> { public: using derived_type = co_composed_state<Executors, Handler, Return>; using promise_type = co_composed_promise<Executors, Handler, Return>; using return_type = std::tuple<Args...>; void on_cancellation_complete_with(Args... args) { derived_type& state = *static_cast<derived_type*>(this); state.return_value_ = std::make_tuple(std::move(args)...); state.cancellation_on_suspend_fn( [](void* p) { auto& promise = *static_cast<promise_type*>(p); co_composed_handler_base<Executors, Handler, Return> composed_handler(promise); Handler handler(std::move(promise.state().handler_)); return_type result( std::move(std::get<return_type>(promise.state().return_value_))); co_composed_handler_base<Executors, Handler, Return>(std::move(composed_handler)); std::apply(std::move(handler), std::move(result)); }); } }; template <typename Executors, typename Handler, typename Return> class co_composed_state_return; template <typename Executors, typename Handler, typename... Signatures> class co_composed_state_return< Executors, Handler, co_composed_returns<Signatures...>> : public co_composed_state_return_overload<Executors, Handler, co_composed_returns<Signatures...>, Signatures>... { public: using co_composed_state_return_overload<Executors, Handler, co_composed_returns<Signatures...>, Signatures>::on_cancellation_complete_with...; private: template <typename, typename, typename, typename> friend class co_composed_promise_return_overload; template <typename, typename, typename, typename> friend class co_composed_state_return_overload; std::variant<std::monostate, typename co_composed_state_return_overload< Executors, Handler, co_composed_returns<Signatures...>, Signatures>::return_type...> return_value_; }; template <typename Executors, typename Handler, typename Return, typename... Signatures> struct co_composed_state_default_cancellation_on_suspend_impl; template <typename Executors, typename Handler, typename Return> struct co_composed_state_default_cancellation_on_suspend_impl< Executors, Handler, Return> { static constexpr void (*fn())(void*) { return nullptr; } }; template <typename Executors, typename Handler, typename Return, typename R, typename... Args, typename... Signatures> struct co_composed_state_default_cancellation_on_suspend_impl< Executors, Handler, Return, R(Args...), Signatures...> { static constexpr void (*fn())(void*) { return co_composed_state_default_cancellation_on_suspend_impl< Executors, Handler, Return, Signatures...>::fn(); } }; template <typename Executors, typename Handler, typename Return, typename R, typename... Args, typename... Signatures> struct co_composed_state_default_cancellation_on_suspend_impl<Executors, Handler, Return, R(asio::error_code, Args...), Signatures...> { using promise_type = co_composed_promise<Executors, Handler, Return>; using return_type = std::tuple<asio::error_code, Args...>; static constexpr void (*fn())(void*) { if constexpr ((is_constructible<Args>::value && ...)) { return [](void* p) { auto& promise = *static_cast<promise_type*>(p); co_composed_handler_base<Executors, Handler, Return> composed_handler(promise); Handler handler(std::move(promise.state().handler_)); co_composed_handler_base<Executors, Handler, Return>(std::move(composed_handler)); std::move(handler)( asio::error_code(asio::error::operation_aborted), Args{}...); }; } else { return co_composed_state_default_cancellation_on_suspend_impl< Executors, Handler, Return, Signatures...>::fn(); } } }; template <typename Executors, typename Handler, typename Return, typename R, typename... Args, typename... Signatures> struct co_composed_state_default_cancellation_on_suspend_impl<Executors, Handler, Return, R(std::exception_ptr, Args...), Signatures...> { using promise_type = co_composed_promise<Executors, Handler, Return>; using return_type = std::tuple<std::exception_ptr, Args...>; static constexpr void (*fn())(void*) { if constexpr ((is_constructible<Args>::value && ...)) { return [](void* p) { auto& promise = *static_cast<promise_type*>(p); co_composed_handler_base<Executors, Handler, Return> composed_handler(promise); Handler handler(std::move(promise.state().handler_)); co_composed_handler_base<Executors, Handler, Return>(std::move(composed_handler)); std::move(handler)( std::make_exception_ptr( asio::system_error( asio::error::operation_aborted, "co_await")), Args{}...); }; } else { return co_composed_state_default_cancellation_on_suspend_impl< Executors, Handler, Return, Signatures...>::fn(); } } }; template <typename Executors, typename Handler, typename Return> struct co_composed_state_default_cancellation_on_suspend; template <typename Executors, typename Handler, typename... Signatures> struct co_composed_state_default_cancellation_on_suspend< Executors, Handler, co_composed_returns<Signatures...>> : co_composed_state_default_cancellation_on_suspend_impl<Executors, Handler, co_composed_returns<Signatures...>, Signatures...> { }; template <typename Executors, typename Handler, typename Return> class co_composed_state_cancellation { public: using cancellation_slot_type = cancellation_slot; cancellation_slot_type get_cancellation_slot() const noexcept { return cancellation_state_.slot(); } cancellation_state get_cancellation_state() const noexcept { return cancellation_state_; } void reset_cancellation_state() { cancellation_state_ = cancellation_state( (get_associated_cancellation_slot)( static_cast<co_composed_state<Executors, Handler, Return>*>( this)->handler())); } template <typename Filter> void reset_cancellation_state(Filter filter) { cancellation_state_ = cancellation_state( (get_associated_cancellation_slot)( static_cast<co_composed_state<Executors, Handler, Return>*>( this)->handler()), filter, filter); } template <typename InFilter, typename OutFilter> void reset_cancellation_state(InFilter&& in_filter, OutFilter&& out_filter) { cancellation_state_ = cancellation_state( (get_associated_cancellation_slot)( static_cast<co_composed_state<Executors, Handler, Return>*>( this)->handler()), static_cast<InFilter&&>(in_filter), static_cast<OutFilter&&>(out_filter)); } cancellation_type_t cancelled() const noexcept { return cancellation_state_.cancelled(); } void clear_cancellation_slot() noexcept { cancellation_state_.slot().clear(); } [[nodiscard]] bool throw_if_cancelled() const noexcept { return throw_if_cancelled_; } void throw_if_cancelled(bool b) noexcept { throw_if_cancelled_ = b; } [[nodiscard]] bool complete_if_cancelled() const noexcept { return complete_if_cancelled_; } void complete_if_cancelled(bool b) noexcept { complete_if_cancelled_ = b; } private: template <typename, typename, typename> friend class co_composed_promise; template <typename, typename, typename, typename> friend class co_composed_state_return_overload; void cancellation_on_suspend_fn(void (*fn)(void*)) { cancellation_on_suspend_fn_ = fn; } void check_for_cancellation_on_transform() { if (throw_if_cancelled_ && !!cancelled()) throw_error(asio::error::operation_aborted, "co_await"); } bool check_for_cancellation_on_suspend( co_composed_promise<Executors, Handler, Return>& promise) noexcept { if (complete_if_cancelled_ && !!cancelled() && cancellation_on_suspend_fn_) { promise.state().work_.reset(); promise.state().on_suspend_->fn_ = cancellation_on_suspend_fn_; promise.state().on_suspend_->arg_ = &promise; return false; } return true; } cancellation_state cancellation_state_; void (*cancellation_on_suspend_fn_)(void*) = co_composed_state_default_cancellation_on_suspend< Executors, Handler, Return>::fn(); bool throw_if_cancelled_ = false; bool complete_if_cancelled_ = true; }; template <typename Executors, typename Handler, typename Return> requires is_same< typename associated_cancellation_slot< Handler, cancellation_slot >::asio_associated_cancellation_slot_is_unspecialised, void>::value class co_composed_state_cancellation<Executors, Handler, Return> { public: void reset_cancellation_state() { } template <typename Filter> void reset_cancellation_state(Filter) { } template <typename InFilter, typename OutFilter> void reset_cancellation_state(InFilter&&, OutFilter&&) { } cancellation_type_t cancelled() const noexcept { return cancellation_type::none; } void clear_cancellation_slot() noexcept { } [[nodiscard]] bool throw_if_cancelled() const noexcept { return false; } void throw_if_cancelled(bool) noexcept { } [[nodiscard]] bool complete_if_cancelled() const noexcept { return false; } void complete_if_cancelled(bool) noexcept { } private: template <typename, typename, typename> friend class co_composed_promise; template <typename, typename, typename, typename> friend class co_composed_state_return_overload; void cancellation_on_suspend_fn(void (*)(void*)) { } void check_for_cancellation_on_transform() noexcept { } bool check_for_cancellation_on_suspend( co_composed_promise<Executors, Handler, Return>&) noexcept { return true; } }; template <typename Executors, typename Handler, typename Return> class co_composed_state : public co_composed_state_return<Executors, Handler, Return>, public co_composed_state_cancellation<Executors, Handler, Return> { public: using io_executor_type = typename composed_work_guard< typename composed_work<Executors>::head_type>::executor_type; template <typename H> co_composed_state(composed_io_executors<Executors>&& executors, H&& h, co_composed_on_suspend& on_suspend) : work_(std::move(executors)), handler_(static_cast<H&&>(h)), on_suspend_(&on_suspend) { this->reset_cancellation_state(enable_terminal_cancellation()); } io_executor_type get_io_executor() const noexcept { return work_.head_.get_executor(); } template <typename... Args> [[nodiscard]] co_composed_completion<Args...> complete(Args&&... args) requires requires { declval<Handler>()(static_cast<Args&&>(args)...); } { return co_composed_completion<Args...>(static_cast<Args&&>(args)...); } const Handler& handler() const noexcept { return handler_; } private: template <typename, typename, typename> friend class co_composed_handler_base; template <typename, typename, typename> friend class co_composed_promise; template <typename, typename, typename, typename> friend class co_composed_promise_return_overload; template <typename, typename, typename> friend class co_composed_state_cancellation; template <typename, typename, typename, typename> friend class co_composed_state_return_overload; template <typename, typename, typename, typename...> friend struct co_composed_state_default_cancellation_on_suspend_impl; composed_work<Executors> work_; Handler handler_; co_composed_on_suspend* on_suspend_; }; template <typename Executors, typename Handler, typename Return> class co_composed_handler_cancellation { public: using cancellation_slot_type = cancellation_slot; cancellation_slot_type get_cancellation_slot() const noexcept { return static_cast< const co_composed_handler_base<Executors, Handler, Return>*>( this)->promise().state().get_cancellation_slot(); } }; template <typename Executors, typename Handler, typename Return> requires is_same< typename associated_cancellation_slot< Handler, cancellation_slot >::asio_associated_cancellation_slot_is_unspecialised, void>::value class co_composed_handler_cancellation<Executors, Handler, Return> { }; template <typename Executors, typename Handler, typename Return> class co_composed_handler_base : public co_composed_handler_cancellation<Executors, Handler, Return> { public: co_composed_handler_base( co_composed_promise<Executors, Handler, Return>& p) noexcept : p_(&p) { } co_composed_handler_base(co_composed_handler_base&& other) noexcept : p_(std::exchange(other.p_, nullptr)) { } ~co_composed_handler_base() { if (p_) [[unlikely]] p_->destroy(); } co_composed_promise<Executors, Handler, Return>& promise() const noexcept { return *p_; } protected: void resume(void* result) { co_composed_on_suspend on_suspend{}; std::exchange(p_, nullptr)->resume(p_, result, on_suspend); if (on_suspend.fn_) on_suspend.fn_(on_suspend.arg_); } private: co_composed_promise<Executors, Handler, Return>* p_; }; template <typename Executors, typename Handler, typename Return, typename Signature> class co_composed_handler; template <typename Executors, typename Handler, typename Return, typename R, typename... Args> class co_composed_handler<Executors, Handler, Return, R(Args...)> : public co_composed_handler_base<Executors, Handler, Return> { public: using co_composed_handler_base<Executors, Handler, Return>::co_composed_handler_base; using result_type = std::tuple<decay_t<Args>...>; template <typename... T> void operator()(T&&... args) { result_type result(static_cast<T&&>(args)...); this->resume(&result); } static auto on_resume(void* result) { auto& args = *static_cast<result_type*>(result); if constexpr (sizeof...(Args) == 0) return; else if constexpr (sizeof...(Args) == 1) return std::move(std::get<0>(args)); else return std::move(args); } }; template <typename Executors, typename Handler, typename Return, typename R, typename... Args> class co_composed_handler<Executors, Handler, Return, R(asio::error_code, Args...)> : public co_composed_handler_base<Executors, Handler, Return> { public: using co_composed_handler_base<Executors, Handler, Return>::co_composed_handler_base; using args_type = std::tuple<decay_t<Args>...>; using result_type = std::tuple<asio::error_code, args_type>; template <typename... T> void operator()(const asio::error_code& ec, T&&... args) { result_type result(ec, args_type(static_cast<T&&>(args)...)); this->resume(&result); } static auto on_resume(void* result) { auto& [ec, args] = *static_cast<result_type*>(result); throw_error(ec); if constexpr (sizeof...(Args) == 0) return; else if constexpr (sizeof...(Args) == 1) return std::move(std::get<0>(args)); else return std::move(args); } }; template <typename Executors, typename Handler, typename Return, typename R, typename... Args> class co_composed_handler<Executors, Handler, Return, R(std::exception_ptr, Args...)> : public co_composed_handler_base<Executors, Handler, Return> { public: using co_composed_handler_base<Executors, Handler, Return>::co_composed_handler_base; using args_type = std::tuple<decay_t<Args>...>; using result_type = std::tuple<std::exception_ptr, args_type>; template <typename... T> void operator()(std::exception_ptr ex, T&&... args) { result_type result(std::move(ex), args_type(static_cast<T&&>(args)...)); this->resume(&result); } static auto on_resume(void* result) { auto& [ex, args] = *static_cast<result_type*>(result); if (ex) std::rethrow_exception(ex); if constexpr (sizeof...(Args) == 0) return; else if constexpr (sizeof...(Args) == 1) return std::move(std::get<0>(args)); else return std::move(args); } }; template <typename Executors, typename Handler, typename Return> class co_composed_promise_return; template <typename Executors, typename Handler> class co_composed_promise_return<Executors, Handler, co_composed_returns<>> { public: auto final_suspend() noexcept { return suspend_never(); } void return_void() noexcept { } }; template <typename Executors, typename Handler, typename Return, typename Signature> class co_composed_promise_return_overload; template <typename Executors, typename Handler, typename Return, typename R, typename... Args> class co_composed_promise_return_overload< Executors, Handler, Return, R(Args...)> { public: using derived_type = co_composed_promise<Executors, Handler, Return>; using return_type = std::tuple<Args...>; void return_value(std::tuple<Args...>&& value) { derived_type& promise = *static_cast<derived_type*>(this); promise.state().return_value_ = std::move(value); promise.state().work_.reset(); promise.state().on_suspend_->arg_ = this; promise.state().on_suspend_->fn_ = [](void* p) { auto& promise = *static_cast<derived_type*>(p); co_composed_handler_base<Executors, Handler, Return> composed_handler(promise); Handler handler(std::move(promise.state().handler_)); return_type result( std::move(std::get<return_type>(promise.state().return_value_))); co_composed_handler_base<Executors, Handler, Return>(std::move(composed_handler)); std::apply(std::move(handler), std::move(result)); }; } }; template <typename Executors, typename Handler, typename... Signatures> class co_composed_promise_return<Executors, Handler, co_composed_returns<Signatures...>> : public co_composed_promise_return_overload<Executors, Handler, co_composed_returns<Signatures...>, Signatures>... { public: auto final_suspend() noexcept { return suspend_always(); } using co_composed_promise_return_overload<Executors, Handler, co_composed_returns<Signatures...>, Signatures>::return_value...; private: template <typename, typename, typename, typename> friend class co_composed_promise_return_overload; }; template <typename Executors, typename Handler, typename Return> class co_composed_promise : public co_composed_promise_return<Executors, Handler, Return> { public: template <typename... Args> void* operator new(std::size_t size, co_composed_state<Executors, Handler, Return>& state, Args&&...) { block_allocator_type allocator( (get_associated_allocator)(state.handler_, recycling_allocator<void>())); block* base_ptr = std::allocator_traits<block_allocator_type>::allocate( allocator, blocks(sizeof(allocator_type)) + blocks(size)); new (static_cast<void*>(base_ptr)) allocator_type(std::move(allocator)); return base_ptr + blocks(sizeof(allocator_type)); } template <typename C, typename... Args> void* operator new(std::size_t size, C&&, co_composed_state<Executors, Handler, Return>& state, Args&&...) { return co_composed_promise::operator new(size, state); } void operator delete(void* ptr, std::size_t size) { block* base_ptr = static_cast<block*>(ptr) - blocks(sizeof(allocator_type)); allocator_type* allocator_ptr = std::launder( static_cast<allocator_type*>(static_cast<void*>(base_ptr))); block_allocator_type block_allocator(std::move(*allocator_ptr)); allocator_ptr->~allocator_type(); std::allocator_traits<block_allocator_type>::deallocate(block_allocator, base_ptr, blocks(sizeof(allocator_type)) + blocks(size)); } template <typename... Args> co_composed_promise( co_composed_state<Executors, Handler, Return>& state, Args&&...) : state_(state) { } template <typename C, typename... Args> co_composed_promise(C&&, co_composed_state<Executors, Handler, Return>& state, Args&&...) : state_(state) { } void destroy() noexcept { coroutine_handle<co_composed_promise>::from_promise(*this).destroy(); } void resume(co_composed_promise*& owner, void* result, co_composed_on_suspend& on_suspend) { state_.on_suspend_ = &on_suspend; state_.clear_cancellation_slot(); owner_ = &owner; result_ = result; coroutine_handle<co_composed_promise>::from_promise(*this).resume(); } co_composed_state<Executors, Handler, Return>& state() noexcept { return state_; } void get_return_object() noexcept { } auto initial_suspend() noexcept { return suspend_never(); } void unhandled_exception() { if (owner_) *owner_ = this; throw; } template <async_operation Op> auto await_transform(Op&& op #if defined(ASIO_ENABLE_HANDLER_TRACKING) # if defined(ASIO_HAS_SOURCE_LOCATION) , asio::detail::source_location location = asio::detail::source_location::current() # endif // defined(ASIO_HAS_SOURCE_LOCATION) #endif // defined(ASIO_ENABLE_HANDLER_TRACKING) ) { class [[nodiscard]] awaitable { public: awaitable(Op&& op, co_composed_promise& promise #if defined(ASIO_ENABLE_HANDLER_TRACKING) # if defined(ASIO_HAS_SOURCE_LOCATION) , const asio::detail::source_location& location # endif // defined(ASIO_HAS_SOURCE_LOCATION) #endif // defined(ASIO_ENABLE_HANDLER_TRACKING) ) : op_(static_cast<Op&&>(op)), promise_(promise) #if defined(ASIO_ENABLE_HANDLER_TRACKING) # if defined(ASIO_HAS_SOURCE_LOCATION) , location_(location) # endif // defined(ASIO_HAS_SOURCE_LOCATION) #endif // defined(ASIO_ENABLE_HANDLER_TRACKING) { } constexpr bool await_ready() const noexcept { return false; } void await_suspend(coroutine_handle<co_composed_promise>) { if (promise_.state_.check_for_cancellation_on_suspend(promise_)) { promise_.state_.on_suspend_->arg_ = this; promise_.state_.on_suspend_->fn_ = [](void* p) { #if defined(ASIO_ENABLE_HANDLER_TRACKING) # if defined(ASIO_HAS_SOURCE_LOCATION) ASIO_HANDLER_LOCATION(( static_cast<awaitable*>(p)->location_.file_name(), static_cast<awaitable*>(p)->location_.line(), static_cast<awaitable*>(p)->location_.function_name())); # endif // defined(ASIO_HAS_SOURCE_LOCATION) #endif // defined(ASIO_ENABLE_HANDLER_TRACKING) static_cast<Op&&>(static_cast<awaitable*>(p)->op_)( co_composed_handler<Executors, Handler, Return, completion_signature_of_t<Op>>( static_cast<awaitable*>(p)->promise_)); }; } } auto await_resume() { return co_composed_handler<Executors, Handler, Return, completion_signature_of_t<Op>>::on_resume(promise_.result_); } private: Op&& op_; co_composed_promise& promise_; #if defined(ASIO_ENABLE_HANDLER_TRACKING) # if defined(ASIO_HAS_SOURCE_LOCATION) asio::detail::source_location location_; # endif // defined(ASIO_HAS_SOURCE_LOCATION) #endif // defined(ASIO_ENABLE_HANDLER_TRACKING) }; state_.check_for_cancellation_on_transform(); return awaitable{static_cast<Op&&>(op), *this #if defined(ASIO_ENABLE_HANDLER_TRACKING) # if defined(ASIO_HAS_SOURCE_LOCATION) , location # endif // defined(ASIO_HAS_SOURCE_LOCATION) #endif // defined(ASIO_ENABLE_HANDLER_TRACKING) }; } template <typename... Args> auto yield_value(co_composed_completion<Args...>&& result) { class [[nodiscard]] awaitable { public: awaitable(co_composed_completion<Args...>&& result, co_composed_promise& promise) : result_(std::move(result)), promise_(promise) { } constexpr bool await_ready() const noexcept { return false; } void await_suspend(coroutine_handle<co_composed_promise>) { promise_.state_.work_.reset(); promise_.state_.on_suspend_->arg_ = this; promise_.state_.on_suspend_->fn_ = [](void* p) { awaitable& a = *static_cast<awaitable*>(p); co_composed_handler_base<Executors, Handler, Return> composed_handler(a.promise_); Handler handler(std::move(a.promise_.state_.handler_)); std::tuple<decay_t<Args>...> result( std::move(static_cast<std::tuple<Args&&...>&>(a.result_))); co_composed_handler_base<Executors, Handler, Return>(std::move(composed_handler)); std::apply(std::move(handler), std::move(result)); }; } void await_resume() noexcept { } private: co_composed_completion<Args...> result_; co_composed_promise& promise_; }; return awaitable{std::move(result), *this}; } private: using allocator_type = associated_allocator_t<Handler, recycling_allocator<void>>; union block { std::max_align_t max_align; alignas(allocator_type) char pad[alignof(allocator_type)]; }; using block_allocator_type = typename std::allocator_traits<allocator_type> ::template rebind_alloc<block>; static constexpr std::size_t blocks(std::size_t size) { return (size + sizeof(block) - 1) / sizeof(block); } co_composed_state<Executors, Handler, Return>& state_; co_composed_promise** owner_ = nullptr; void* result_ = nullptr; }; template <typename Implementation, typename Executors, typename... Signatures> class initiate_co_composed { public: using executor_type = typename composed_io_executors<Executors>::head_type; template <typename I> initiate_co_composed(I&& impl, composed_io_executors<Executors>&& executors) : implementation_(static_cast<I&&>(impl)), executors_(std::move(executors)) { } executor_type get_executor() const noexcept { return executors_.head_; } template <typename Handler, typename... InitArgs> void operator()(Handler&& handler, InitArgs&&... init_args) const & { using handler_type = decay_t<Handler>; using returns_type = co_composed_returns<Signatures...>; co_composed_on_suspend on_suspend{}; implementation_( co_composed_state<Executors, handler_type, returns_type>( executors_, static_cast<Handler&&>(handler), on_suspend), static_cast<InitArgs&&>(init_args)...); if (on_suspend.fn_) on_suspend.fn_(on_suspend.arg_); } template <typename Handler, typename... InitArgs> void operator()(Handler&& handler, InitArgs&&... init_args) && { using handler_type = decay_t<Handler>; using returns_type = co_composed_returns<Signatures...>; co_composed_on_suspend on_suspend{}; std::move(implementation_)( co_composed_state<Executors, handler_type, returns_type>( std::move(executors_), static_cast<Handler&&>(handler), on_suspend), static_cast<InitArgs&&>(init_args)...); if (on_suspend.fn_) on_suspend.fn_(on_suspend.arg_); } private: Implementation implementation_; composed_io_executors<Executors> executors_; }; template <typename Implementation, typename... Signatures> class initiate_co_composed<Implementation, void(), Signatures...> { public: template <typename I> initiate_co_composed(I&& impl, composed_io_executors<void()>&&) : implementation_(static_cast<I&&>(impl)) { } template <typename Handler, typename... InitArgs> void operator()(Handler&& handler, InitArgs&&... init_args) const & { using handler_type = decay_t<Handler>; using returns_type = co_composed_returns<Signatures...>; co_composed_on_suspend on_suspend{}; implementation_( co_composed_state<void(), handler_type, returns_type>( composed_io_executors<void()>(), static_cast<Handler&&>(handler), on_suspend), static_cast<InitArgs&&>(init_args)...); if (on_suspend.fn_) on_suspend.fn_(on_suspend.arg_); } template <typename Handler, typename... InitArgs> void operator()(Handler&& handler, InitArgs&&... init_args) && { using handler_type = decay_t<Handler>; using returns_type = co_composed_returns<Signatures...>; co_composed_on_suspend on_suspend{}; std::move(implementation_)( co_composed_state<void(), handler_type, returns_type>( composed_io_executors<void()>(), static_cast<Handler&&>(handler), on_suspend), static_cast<InitArgs&&>(init_args)...); if (on_suspend.fn_) on_suspend.fn_(on_suspend.arg_); } private: Implementation implementation_; }; template <typename... Signatures, typename Implementation, typename Executors> inline initiate_co_composed<decay_t<Implementation>, Executors, Signatures...> make_initiate_co_composed(Implementation&& implementation, composed_io_executors<Executors>&& executors) { return initiate_co_composed< decay_t<Implementation>, Executors, Signatures...>( static_cast<Implementation&&>(implementation), std::move(executors)); } } // namespace detail #if !defined(GENERATING_DOCUMENTATION) template <template <typename, typename> class Associator, typename Executors, typename Handler, typename Return, typename Signature, typename DefaultCandidate> struct associator<Associator, detail::co_composed_handler<Executors, Handler, Return, Signature>, DefaultCandidate> : Associator<Handler, DefaultCandidate> { static typename Associator<Handler, DefaultCandidate>::type get( const detail::co_composed_handler< Executors, Handler, Return, Signature>& h) noexcept { return Associator<Handler, DefaultCandidate>::get( h.promise().state().handler()); } static auto get( const detail::co_composed_handler< Executors, Handler, Return, Signature>& h, const DefaultCandidate& c) noexcept -> decltype( Associator<Handler, DefaultCandidate>::get( h.promise().state().handler(), c)) { return Associator<Handler, DefaultCandidate>::get( h.promise().state().handler(), c); } }; #endif // !defined(GENERATING_DOCUMENTATION) } // namespace asio #if !defined(GENERATING_DOCUMENTATION) # if defined(ASIO_HAS_STD_COROUTINE) namespace std { # else // defined(ASIO_HAS_STD_COROUTINE) namespace std { namespace experimental { # endif // defined(ASIO_HAS_STD_COROUTINE) template <typename C, typename Executors, typename Handler, typename Return, typename... Args> struct coroutine_traits<void, C&, asio::detail::co_composed_state<Executors, Handler, Return>, Args...> { using promise_type = asio::detail::co_composed_promise<Executors, Handler, Return>; }; template <typename C, typename Executors, typename Handler, typename Return, typename... Args> struct coroutine_traits<void, C&&, asio::detail::co_composed_state<Executors, Handler, Return>, Args...> { using promise_type = asio::detail::co_composed_promise<Executors, Handler, Return>; }; template <typename Executors, typename Handler, typename Return, typename... Args> struct coroutine_traits<void, asio::detail::co_composed_state<Executors, Handler, Return>, Args...> { using promise_type = asio::detail::co_composed_promise<Executors, Handler, Return>; }; # if defined(ASIO_HAS_STD_COROUTINE) } // namespace std # else // defined(ASIO_HAS_STD_COROUTINE) }} // namespace std::experimental # endif // defined(ASIO_HAS_STD_COROUTINE) #endif // !defined(GENERATING_DOCUMENTATION) namespace asio { /// Creates an initiation function object that may be used to launch a /// coroutine-based composed asynchronous operation. /** * The co_composed utility simplifies the implementation of composed * asynchronous operations by automatically adapting a coroutine to be an * initiation function object for use with @c async_initiate. When awaiting * asynchronous operations, the coroutine automatically uses a conforming * intermediate completion handler. * * @param implementation A function object that contains the coroutine-based * implementation of the composed asynchronous operation. The first argument to * the function object represents the state of the operation, and may be used * to test for cancellation. The remaining arguments are those passed to @c * async_initiate after the completion token. * * @param io_objects_or_executors Zero or more I/O objects or I/O executors for * which outstanding work must be maintained while the operation is incomplete. * * @par Per-Operation Cancellation * By default, terminal per-operation cancellation is enabled for composed * operations that use co_composed. To disable cancellation for the composed * operation, or to alter its supported cancellation types, call the state's * @c reset_cancellation_state function. * * @par Examples * The following example illustrates manual error handling and explicit checks * for cancellation. The completion handler is invoked via a @c co_yield to the * state's @c complete function, which never returns. * * @code template <typename CompletionToken> * auto async_echo(tcp::socket& socket, * CompletionToken&& token) * { * return asio::async_initiate< * CompletionToken, void(std::error_code)>( * asio::co_composed( * [](auto state, tcp::socket& socket) -> void * { * state.reset_cancellation_state( * asio::enable_terminal_cancellation()); * * while (!state.cancelled()) * { * char data[1024]; * auto [e1, n1] = * co_await socket.async_read_some( * asio::buffer(data)); * * if (e1) * co_yield state.complete(e1); * * if (!!state.cancelled()) * co_yield state.complete( * make_error_code(asio::error::operation_aborted)); * * auto [e2, n2] = * co_await asio::async_write(socket, * asio::buffer(data, n1)); * * if (e2) * co_yield state.complete(e2); * } * }, socket), * token, std::ref(socket)); * } @endcode * * This next example shows exception-based error handling and implicit checks * for cancellation. The completion handler is invoked after returning from the * coroutine via @c co_return. Valid @c co_return values are specified using * completion signatures passed to the @c co_composed function. * * @code template <typename CompletionToken> * auto async_echo(tcp::socket& socket, * CompletionToken&& token) * { * return asio::async_initiate< * CompletionToken, void(std::error_code)>( * asio::co_composed< * void(std::error_code)>( * [](auto state, tcp::socket& socket) -> void * { * try * { * state.throw_if_cancelled(true); * state.reset_cancellation_state( * asio::enable_terminal_cancellation()); * * for (;;) * { * char data[1024]; * std::size_t n = co_await socket.async_read_some( * asio::buffer(data)); * * co_await asio::async_write(socket, * asio::buffer(data, n)); * } * } * catch (const std::system_error& e) * { * co_return {e.code()}; * } * }, socket), * token, std::ref(socket)); * } @endcode */ template <ASIO_COMPLETION_SIGNATURE... Signatures, typename Implementation, typename... IoObjectsOrExecutors> inline auto co_composed(Implementation&& implementation, IoObjectsOrExecutors&&... io_objects_or_executors) { return detail::make_initiate_co_composed<Signatures...>( static_cast<Implementation&&>(implementation), detail::make_composed_io_executors( detail::get_composed_io_executor( static_cast<IoObjectsOrExecutors&&>( io_objects_or_executors))...)); } } // namespace asio #include "asio/detail/pop_options.hpp" #endif // defined(ASIO_HAS_CO_AWAIT) || defined(GENERATING_DOCUMENTATION) #endif // ASIO_CO_COMPOSED_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/is_applicable_property.hpp
// // is_applicable_property.hpp // ~~~~~~~~~~~~~~~~~~~~~~~~~~ // // 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) // #ifndef ASIO_IS_APPLICABLE_PROPERTY_HPP #define ASIO_IS_APPLICABLE_PROPERTY_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include "asio/detail/type_traits.hpp" namespace asio { namespace detail { template <typename T, typename Property, typename = void> struct is_applicable_property_trait : false_type { }; #if defined(ASIO_HAS_VARIABLE_TEMPLATES) template <typename T, typename Property> struct is_applicable_property_trait<T, Property, void_t< enable_if_t< !!Property::template is_applicable_property_v<T> > >> : true_type { }; #endif // defined(ASIO_HAS_VARIABLE_TEMPLATES) } // namespace detail template <typename T, typename Property, typename = void> struct is_applicable_property : detail::is_applicable_property_trait<T, Property> { }; #if defined(ASIO_HAS_VARIABLE_TEMPLATES) template <typename T, typename Property> constexpr const bool is_applicable_property_v = is_applicable_property<T, Property>::value; #endif // defined(ASIO_HAS_VARIABLE_TEMPLATES) } // namespace asio #endif // ASIO_IS_APPLICABLE_PROPERTY_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/basic_stream_socket.hpp
// // basic_stream_socket.hpp // ~~~~~~~~~~~~~~~~~~~~~~~ // // 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) // #ifndef ASIO_BASIC_STREAM_SOCKET_HPP #define ASIO_BASIC_STREAM_SOCKET_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include <cstddef> #include "asio/async_result.hpp" #include "asio/basic_socket.hpp" #include "asio/detail/handler_type_requirements.hpp" #include "asio/detail/non_const_lvalue.hpp" #include "asio/detail/throw_error.hpp" #include "asio/error.hpp" #include "asio/detail/push_options.hpp" namespace asio { #if !defined(ASIO_BASIC_STREAM_SOCKET_FWD_DECL) #define ASIO_BASIC_STREAM_SOCKET_FWD_DECL // Forward declaration with defaulted arguments. template <typename Protocol, typename Executor = any_io_executor> class basic_stream_socket; #endif // !defined(ASIO_BASIC_STREAM_SOCKET_FWD_DECL) /// Provides stream-oriented socket functionality. /** * The basic_stream_socket class template provides asynchronous and blocking * stream-oriented socket functionality. * * @par Thread Safety * @e Distinct @e objects: Safe.@n * @e Shared @e objects: Unsafe. * * Synchronous @c send, @c receive, @c connect, and @c shutdown operations are * thread safe with respect to each other, if the underlying operating system * calls are also thread safe. This means that it is permitted to perform * concurrent calls to these synchronous operations on a single socket object. * Other synchronous operations, such as @c open or @c close, are not thread * safe. * * @par Concepts: * AsyncReadStream, AsyncWriteStream, Stream, SyncReadStream, SyncWriteStream. */ template <typename Protocol, typename Executor> class basic_stream_socket : public basic_socket<Protocol, Executor> { private: class initiate_async_send; class initiate_async_receive; public: /// The type of the executor associated with the object. typedef Executor executor_type; /// Rebinds the socket type to another executor. template <typename Executor1> struct rebind_executor { /// The socket type when rebound to the specified executor. typedef basic_stream_socket<Protocol, Executor1> other; }; /// The native representation of a socket. #if defined(GENERATING_DOCUMENTATION) typedef implementation_defined native_handle_type; #else typedef typename basic_socket<Protocol, Executor>::native_handle_type native_handle_type; #endif /// The protocol type. typedef Protocol protocol_type; /// The endpoint type. typedef typename Protocol::endpoint endpoint_type; /// Construct a basic_stream_socket without opening it. /** * This constructor creates a stream socket without opening it. The socket * needs to be opened and then connected or accepted before data can be sent * or received on it. * * @param ex The I/O executor that the socket will use, by default, to * dispatch handlers for any asynchronous operations performed on the socket. */ explicit basic_stream_socket(const executor_type& ex) : basic_socket<Protocol, Executor>(ex) { } /// Construct a basic_stream_socket without opening it. /** * This constructor creates a stream socket without opening it. The socket * needs to be opened and then connected or accepted before data can be sent * or received on it. * * @param context An execution context which provides the I/O executor that * the socket will use, by default, to dispatch handlers for any asynchronous * operations performed on the socket. */ template <typename ExecutionContext> explicit basic_stream_socket(ExecutionContext& context, constraint_t< is_convertible<ExecutionContext&, execution_context&>::value > = 0) : basic_socket<Protocol, Executor>(context) { } /// Construct and open a basic_stream_socket. /** * This constructor creates and opens a stream socket. The socket needs to be * connected or accepted before data can be sent or received on it. * * @param ex The I/O executor that the socket will use, by default, to * dispatch handlers for any asynchronous operations performed on the socket. * * @param protocol An object specifying protocol parameters to be used. * * @throws asio::system_error Thrown on failure. */ basic_stream_socket(const executor_type& ex, const protocol_type& protocol) : basic_socket<Protocol, Executor>(ex, protocol) { } /// Construct and open a basic_stream_socket. /** * This constructor creates and opens a stream socket. The socket needs to be * connected or accepted before data can be sent or received on it. * * @param context An execution context which provides the I/O executor that * the socket will use, by default, to dispatch handlers for any asynchronous * operations performed on the socket. * * @param protocol An object specifying protocol parameters to be used. * * @throws asio::system_error Thrown on failure. */ template <typename ExecutionContext> basic_stream_socket(ExecutionContext& context, const protocol_type& protocol, constraint_t< is_convertible<ExecutionContext&, execution_context&>::value, defaulted_constraint > = defaulted_constraint()) : basic_socket<Protocol, Executor>(context, protocol) { } /// Construct a basic_stream_socket, opening it and binding it to the given /// local endpoint. /** * This constructor creates a stream socket and automatically opens it bound * to the specified endpoint on the local machine. The protocol used is the * protocol associated with the given endpoint. * * @param ex The I/O executor that the socket will use, by default, to * dispatch handlers for any asynchronous operations performed on the socket. * * @param endpoint An endpoint on the local machine to which the stream * socket will be bound. * * @throws asio::system_error Thrown on failure. */ basic_stream_socket(const executor_type& ex, const endpoint_type& endpoint) : basic_socket<Protocol, Executor>(ex, endpoint) { } /// Construct a basic_stream_socket, opening it and binding it to the given /// local endpoint. /** * This constructor creates a stream socket and automatically opens it bound * to the specified endpoint on the local machine. The protocol used is the * protocol associated with the given endpoint. * * @param context An execution context which provides the I/O executor that * the socket will use, by default, to dispatch handlers for any asynchronous * operations performed on the socket. * * @param endpoint An endpoint on the local machine to which the stream * socket will be bound. * * @throws asio::system_error Thrown on failure. */ template <typename ExecutionContext> basic_stream_socket(ExecutionContext& context, const endpoint_type& endpoint, constraint_t< is_convertible<ExecutionContext&, execution_context&>::value > = 0) : basic_socket<Protocol, Executor>(context, endpoint) { } /// Construct a basic_stream_socket on an existing native socket. /** * This constructor creates a stream socket object to hold an existing native * socket. * * @param ex The I/O executor that the socket will use, by default, to * dispatch handlers for any asynchronous operations performed on the socket. * * @param protocol An object specifying protocol parameters to be used. * * @param native_socket The new underlying socket implementation. * * @throws asio::system_error Thrown on failure. */ basic_stream_socket(const executor_type& ex, const protocol_type& protocol, const native_handle_type& native_socket) : basic_socket<Protocol, Executor>(ex, protocol, native_socket) { } /// Construct a basic_stream_socket on an existing native socket. /** * This constructor creates a stream socket object to hold an existing native * socket. * * @param context An execution context which provides the I/O executor that * the socket will use, by default, to dispatch handlers for any asynchronous * operations performed on the socket. * * @param protocol An object specifying protocol parameters to be used. * * @param native_socket The new underlying socket implementation. * * @throws asio::system_error Thrown on failure. */ template <typename ExecutionContext> basic_stream_socket(ExecutionContext& context, const protocol_type& protocol, const native_handle_type& native_socket, constraint_t< is_convertible<ExecutionContext&, execution_context&>::value > = 0) : basic_socket<Protocol, Executor>(context, protocol, native_socket) { } /// Move-construct a basic_stream_socket from another. /** * This constructor moves a stream socket from one object to another. * * @param other The other basic_stream_socket object from which the move * will occur. * * @note Following the move, the moved-from object is in the same state as if * constructed using the @c basic_stream_socket(const executor_type&) * constructor. */ basic_stream_socket(basic_stream_socket&& other) noexcept : basic_socket<Protocol, Executor>(std::move(other)) { } /// Move-assign a basic_stream_socket from another. /** * This assignment operator moves a stream socket from one object to another. * * @param other The other basic_stream_socket object from which the move * will occur. * * @note Following the move, the moved-from object is in the same state as if * constructed using the @c basic_stream_socket(const executor_type&) * constructor. */ basic_stream_socket& operator=(basic_stream_socket&& other) { basic_socket<Protocol, Executor>::operator=(std::move(other)); return *this; } /// Move-construct a basic_stream_socket from a socket of another protocol /// type. /** * This constructor moves a stream socket from one object to another. * * @param other The other basic_stream_socket object from which the move * will occur. * * @note Following the move, the moved-from object is in the same state as if * constructed using the @c basic_stream_socket(const executor_type&) * constructor. */ template <typename Protocol1, typename Executor1> basic_stream_socket(basic_stream_socket<Protocol1, Executor1>&& other, constraint_t< is_convertible<Protocol1, Protocol>::value && is_convertible<Executor1, Executor>::value > = 0) : basic_socket<Protocol, Executor>(std::move(other)) { } /// Move-assign a basic_stream_socket from a socket of another protocol type. /** * This assignment operator moves a stream socket from one object to another. * * @param other The other basic_stream_socket object from which the move * will occur. * * @note Following the move, the moved-from object is in the same state as if * constructed using the @c basic_stream_socket(const executor_type&) * constructor. */ template <typename Protocol1, typename Executor1> constraint_t< is_convertible<Protocol1, Protocol>::value && is_convertible<Executor1, Executor>::value, basic_stream_socket& > operator=(basic_stream_socket<Protocol1, Executor1>&& other) { basic_socket<Protocol, Executor>::operator=(std::move(other)); return *this; } /// Destroys the socket. /** * This function destroys the socket, cancelling any outstanding asynchronous * operations associated with the socket as if by calling @c cancel. */ ~basic_stream_socket() { } /// Send some data on the socket. /** * This function is used to send data on the stream socket. The function * call will block until one or more bytes of the data has been sent * successfully, or an until error occurs. * * @param buffers One or more data buffers to be sent on the socket. * * @returns The number of bytes sent. * * @throws asio::system_error Thrown on failure. * * @note The send operation may not transmit all of the data to the peer. * Consider using the @ref write function if you need to ensure that all data * is written before the blocking operation completes. * * @par Example * To send a single data buffer use the @ref buffer function as follows: * @code * socket.send(asio::buffer(data, size)); * @endcode * See the @ref buffer documentation for information on sending multiple * buffers in one go, and how to use it with arrays, boost::array or * std::vector. */ template <typename ConstBufferSequence> std::size_t send(const ConstBufferSequence& buffers) { asio::error_code ec; std::size_t s = this->impl_.get_service().send( this->impl_.get_implementation(), buffers, 0, ec); asio::detail::throw_error(ec, "send"); return s; } /// Send some data on the socket. /** * This function is used to send data on the stream socket. The function * call will block until one or more bytes of the data has been sent * successfully, or an until error occurs. * * @param buffers One or more data buffers to be sent on the socket. * * @param flags Flags specifying how the send call is to be made. * * @returns The number of bytes sent. * * @throws asio::system_error Thrown on failure. * * @note The send operation may not transmit all of the data to the peer. * Consider using the @ref write function if you need to ensure that all data * is written before the blocking operation completes. * * @par Example * To send a single data buffer use the @ref buffer function as follows: * @code * socket.send(asio::buffer(data, size), 0); * @endcode * See the @ref buffer documentation for information on sending multiple * buffers in one go, and how to use it with arrays, boost::array or * std::vector. */ template <typename ConstBufferSequence> std::size_t send(const ConstBufferSequence& buffers, socket_base::message_flags flags) { asio::error_code ec; std::size_t s = this->impl_.get_service().send( this->impl_.get_implementation(), buffers, flags, ec); asio::detail::throw_error(ec, "send"); return s; } /// Send some data on the socket. /** * This function is used to send data on the stream socket. The function * call will block until one or more bytes of the data has been sent * successfully, or an until error occurs. * * @param buffers One or more data buffers to be sent on the socket. * * @param flags Flags specifying how the send call is to be made. * * @param ec Set to indicate what error occurred, if any. * * @returns The number of bytes sent. Returns 0 if an error occurred. * * @note The send operation may not transmit all of the data to the peer. * Consider using the @ref write function if you need to ensure that all data * is written before the blocking operation completes. */ template <typename ConstBufferSequence> std::size_t send(const ConstBufferSequence& buffers, socket_base::message_flags flags, asio::error_code& ec) { return this->impl_.get_service().send( this->impl_.get_implementation(), buffers, flags, ec); } /// Start an asynchronous send. /** * This function is used to asynchronously send data on the stream socket. * It is an initiating function for an @ref asynchronous_operation, and always * returns immediately. * * @param buffers One or more data buffers to be sent on the socket. Although * the buffers object may be copied as necessary, ownership of the underlying * memory blocks is retained by the caller, which must guarantee that they * remain valid until the completion handler is called. * * @param token The @ref completion_token that will be used to produce a * completion handler, which will be called when the send completes. * Potential completion tokens include @ref use_future, @ref use_awaitable, * @ref yield_context, or a function object with the correct completion * signature. The function signature of the completion handler must be: * @code void handler( * const asio::error_code& error, // Result of operation. * std::size_t bytes_transferred // Number of bytes sent. * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the completion handler will not be invoked from within this function. * On immediate completion, invocation of the handler will be performed in a * manner equivalent to using asio::async_immediate(). * * @par Completion Signature * @code void(asio::error_code, std::size_t) @endcode * * @note The send operation may not transmit all of the data to the peer. * Consider using the @ref async_write function if you need to ensure that all * data is written before the asynchronous operation completes. * * @par Example * To send a single data buffer use the @ref buffer function as follows: * @code * socket.async_send(asio::buffer(data, size), handler); * @endcode * See the @ref buffer documentation for information on sending multiple * buffers in one go, and how to use it with arrays, boost::array or * std::vector. * * @par Per-Operation Cancellation * On POSIX or Windows operating systems, this asynchronous operation supports * cancellation for the following asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * @li @c cancellation_type::total */ template <typename ConstBufferSequence, ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code, std::size_t)) WriteToken = default_completion_token_t<executor_type>> auto async_send(const ConstBufferSequence& buffers, WriteToken&& token = default_completion_token_t<executor_type>()) -> decltype( async_initiate<WriteToken, void (asio::error_code, std::size_t)>( declval<initiate_async_send>(), token, buffers, socket_base::message_flags(0))) { return async_initiate<WriteToken, void (asio::error_code, std::size_t)>( initiate_async_send(this), token, buffers, socket_base::message_flags(0)); } /// Start an asynchronous send. /** * This function is used to asynchronously send data on the stream socket. * It is an initiating function for an @ref asynchronous_operation, and always * returns immediately. * * @param buffers One or more data buffers to be sent on the socket. Although * the buffers object may be copied as necessary, ownership of the underlying * memory blocks is retained by the caller, which must guarantee that they * remain valid until the completion handler is called. * * @param flags Flags specifying how the send call is to be made. * * @param token The @ref completion_token that will be used to produce a * completion handler, which will be called when the send completes. * Potential completion tokens include @ref use_future, @ref use_awaitable, * @ref yield_context, or a function object with the correct completion * signature. The function signature of the completion handler must be: * @code void handler( * const asio::error_code& error, // Result of operation. * std::size_t bytes_transferred // Number of bytes sent. * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the completion handler will not be invoked from within this function. * On immediate completion, invocation of the handler will be performed in a * manner equivalent to using asio::async_immediate(). * * @par Completion Signature * @code void(asio::error_code, std::size_t) @endcode * * @note The send operation may not transmit all of the data to the peer. * Consider using the @ref async_write function if you need to ensure that all * data is written before the asynchronous operation completes. * * @par Example * To send a single data buffer use the @ref buffer function as follows: * @code * socket.async_send(asio::buffer(data, size), 0, handler); * @endcode * See the @ref buffer documentation for information on sending multiple * buffers in one go, and how to use it with arrays, boost::array or * std::vector. * * @par Per-Operation Cancellation * On POSIX or Windows operating systems, this asynchronous operation supports * cancellation for the following asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * @li @c cancellation_type::total */ template <typename ConstBufferSequence, ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code, std::size_t)) WriteToken = default_completion_token_t<executor_type>> auto async_send(const ConstBufferSequence& buffers, socket_base::message_flags flags, WriteToken&& token = default_completion_token_t<executor_type>()) -> decltype( async_initiate<WriteToken, void (asio::error_code, std::size_t)>( declval<initiate_async_send>(), token, buffers, flags)) { return async_initiate<WriteToken, void (asio::error_code, std::size_t)>( initiate_async_send(this), token, buffers, flags); } /// Receive some data on the socket. /** * This function is used to receive data on the stream socket. The function * call will block until one or more bytes of data has been received * successfully, or until an error occurs. * * @param buffers One or more buffers into which the data will be received. * * @returns The number of bytes received. * * @throws asio::system_error Thrown on failure. An error code of * asio::error::eof indicates that the connection was closed by the * peer. * * @note The receive operation may not receive all of the requested number of * bytes. Consider using the @ref read function if you need to ensure that the * requested amount of data is read before the blocking operation completes. * * @par Example * To receive into a single data buffer use the @ref buffer function as * follows: * @code * socket.receive(asio::buffer(data, size)); * @endcode * See the @ref buffer documentation for information on receiving into * multiple buffers in one go, and how to use it with arrays, boost::array or * std::vector. */ template <typename MutableBufferSequence> std::size_t receive(const MutableBufferSequence& buffers) { asio::error_code ec; std::size_t s = this->impl_.get_service().receive( this->impl_.get_implementation(), buffers, 0, ec); asio::detail::throw_error(ec, "receive"); return s; } /// Receive some data on the socket. /** * This function is used to receive data on the stream socket. The function * call will block until one or more bytes of data has been received * successfully, or until an error occurs. * * @param buffers One or more buffers into which the data will be received. * * @param flags Flags specifying how the receive call is to be made. * * @returns The number of bytes received. * * @throws asio::system_error Thrown on failure. An error code of * asio::error::eof indicates that the connection was closed by the * peer. * * @note The receive operation may not receive all of the requested number of * bytes. Consider using the @ref read function if you need to ensure that the * requested amount of data is read before the blocking operation completes. * * @par Example * To receive into a single data buffer use the @ref buffer function as * follows: * @code * socket.receive(asio::buffer(data, size), 0); * @endcode * See the @ref buffer documentation for information on receiving into * multiple buffers in one go, and how to use it with arrays, boost::array or * std::vector. */ template <typename MutableBufferSequence> std::size_t receive(const MutableBufferSequence& buffers, socket_base::message_flags flags) { asio::error_code ec; std::size_t s = this->impl_.get_service().receive( this->impl_.get_implementation(), buffers, flags, ec); asio::detail::throw_error(ec, "receive"); return s; } /// Receive some data on a connected socket. /** * This function is used to receive data on the stream socket. The function * call will block until one or more bytes of data has been received * successfully, or until an error occurs. * * @param buffers One or more buffers into which the data will be received. * * @param flags Flags specifying how the receive call is to be made. * * @param ec Set to indicate what error occurred, if any. * * @returns The number of bytes received. Returns 0 if an error occurred. * * @note The receive operation may not receive all of the requested number of * bytes. Consider using the @ref read function if you need to ensure that the * requested amount of data is read before the blocking operation completes. */ template <typename MutableBufferSequence> std::size_t receive(const MutableBufferSequence& buffers, socket_base::message_flags flags, asio::error_code& ec) { return this->impl_.get_service().receive( this->impl_.get_implementation(), buffers, flags, ec); } /// Start an asynchronous receive. /** * This function is used to asynchronously receive data from the stream * socket. It is an initiating function for an @ref asynchronous_operation, * and always returns immediately. * * @param buffers One or more buffers into which the data will be received. * Although the buffers object may be copied as necessary, ownership of the * underlying memory blocks is retained by the caller, which must guarantee * that they remain valid until the completion handler is called. * * @param token The @ref completion_token that will be used to produce a * completion handler, which will be called when the receive completes. * Potential completion tokens include @ref use_future, @ref use_awaitable, * @ref yield_context, or a function object with the correct completion * signature. The function signature of the completion handler must be: * @code void handler( * const asio::error_code& error, // Result of operation. * std::size_t bytes_transferred // Number of bytes received. * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the completion handler will not be invoked from within this function. * On immediate completion, invocation of the handler will be performed in a * manner equivalent to using asio::async_immediate(). * * @par Completion Signature * @code void(asio::error_code, std::size_t) @endcode * * @note The receive operation may not receive all of the requested number of * bytes. Consider using the @ref async_read function if you need to ensure * that the requested amount of data is received before the asynchronous * operation completes. * * @par Example * To receive into a single data buffer use the @ref buffer function as * follows: * @code * socket.async_receive(asio::buffer(data, size), handler); * @endcode * See the @ref buffer documentation for information on receiving into * multiple buffers in one go, and how to use it with arrays, boost::array or * std::vector. * * @par Per-Operation Cancellation * On POSIX or Windows operating systems, this asynchronous operation supports * cancellation for the following asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * @li @c cancellation_type::total */ template <typename MutableBufferSequence, ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code, std::size_t)) ReadToken = default_completion_token_t<executor_type>> auto async_receive(const MutableBufferSequence& buffers, ReadToken&& token = default_completion_token_t<executor_type>()) -> decltype( async_initiate<ReadToken, void (asio::error_code, std::size_t)>( declval<initiate_async_receive>(), token, buffers, socket_base::message_flags(0))) { return async_initiate<ReadToken, void (asio::error_code, std::size_t)>( initiate_async_receive(this), token, buffers, socket_base::message_flags(0)); } /// Start an asynchronous receive. /** * This function is used to asynchronously receive data from the stream * socket. It is an initiating function for an @ref asynchronous_operation, * and always returns immediately. * * @param buffers One or more buffers into which the data will be received. * Although the buffers object may be copied as necessary, ownership of the * underlying memory blocks is retained by the caller, which must guarantee * that they remain valid until the completion handler is called. * * @param flags Flags specifying how the receive call is to be made. * * @param token The @ref completion_token that will be used to produce a * completion handler, which will be called when the receive completes. * Potential completion tokens include @ref use_future, @ref use_awaitable, * @ref yield_context, or a function object with the correct completion * signature. The function signature of the completion handler must be: * @code void handler( * const asio::error_code& error, // Result of operation. * std::size_t bytes_transferred // Number of bytes received. * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the completion handler will not be invoked from within this function. * On immediate completion, invocation of the handler will be performed in a * manner equivalent to using asio::async_immediate(). * * @par Completion Signature * @code void(asio::error_code, std::size_t) @endcode * * @note The receive operation may not receive all of the requested number of * bytes. Consider using the @ref async_read function if you need to ensure * that the requested amount of data is received before the asynchronous * operation completes. * * @par Example * To receive into a single data buffer use the @ref buffer function as * follows: * @code * socket.async_receive(asio::buffer(data, size), 0, handler); * @endcode * See the @ref buffer documentation for information on receiving into * multiple buffers in one go, and how to use it with arrays, boost::array or * std::vector. * * @par Per-Operation Cancellation * On POSIX or Windows operating systems, this asynchronous operation supports * cancellation for the following asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * @li @c cancellation_type::total */ template <typename MutableBufferSequence, ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code, std::size_t)) ReadToken = default_completion_token_t<executor_type>> auto async_receive(const MutableBufferSequence& buffers, socket_base::message_flags flags, ReadToken&& token = default_completion_token_t<executor_type>()) -> decltype( async_initiate<ReadToken, void (asio::error_code, std::size_t)>( declval<initiate_async_receive>(), token, buffers, flags)) { return async_initiate<ReadToken, void (asio::error_code, std::size_t)>( initiate_async_receive(this), token, buffers, flags); } /// Write some data to the socket. /** * This function is used to write data to the stream socket. The function call * will block until one or more bytes of the data has been written * successfully, or until an error occurs. * * @param buffers One or more data buffers to be written to the socket. * * @returns The number of bytes written. * * @throws asio::system_error Thrown on failure. An error code of * asio::error::eof indicates that the connection was closed by the * peer. * * @note The write_some operation may not transmit all of the data to the * peer. Consider using the @ref write function if you need to ensure that * all data is written before the blocking operation completes. * * @par Example * To write a single data buffer use the @ref buffer function as follows: * @code * socket.write_some(asio::buffer(data, size)); * @endcode * See the @ref buffer documentation for information on writing multiple * buffers in one go, and how to use it with arrays, boost::array or * std::vector. */ template <typename ConstBufferSequence> std::size_t write_some(const ConstBufferSequence& buffers) { asio::error_code ec; std::size_t s = this->impl_.get_service().send( this->impl_.get_implementation(), buffers, 0, ec); asio::detail::throw_error(ec, "write_some"); return s; } /// Write some data to the socket. /** * This function is used to write data to the stream socket. The function call * will block until one or more bytes of the data has been written * successfully, or until an error occurs. * * @param buffers One or more data buffers to be written to the socket. * * @param ec Set to indicate what error occurred, if any. * * @returns The number of bytes written. Returns 0 if an error occurred. * * @note The write_some operation may not transmit all of the data to the * peer. Consider using the @ref write function if you need to ensure that * all data is written before the blocking operation completes. */ template <typename ConstBufferSequence> std::size_t write_some(const ConstBufferSequence& buffers, asio::error_code& ec) { return this->impl_.get_service().send( this->impl_.get_implementation(), buffers, 0, ec); } /// Start an asynchronous write. /** * This function is used to asynchronously write data to the stream socket. * It is an initiating function for an @ref asynchronous_operation, and always * returns immediately. * * @param buffers One or more data buffers to be written to the socket. * Although the buffers object may be copied as necessary, ownership of the * underlying memory blocks is retained by the caller, which must guarantee * that they remain valid until the completion handler is called. * * @param token The @ref completion_token that will be used to produce a * completion handler, which will be called when the write completes. * Potential completion tokens include @ref use_future, @ref use_awaitable, * @ref yield_context, or a function object with the correct completion * signature. The function signature of the completion handler must be: * @code void handler( * const asio::error_code& error, // Result of operation. * std::size_t bytes_transferred // Number of bytes written. * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the completion handler will not be invoked from within this function. * On immediate completion, invocation of the handler will be performed in a * manner equivalent to using asio::async_immediate(). * * @par Completion Signature * @code void(asio::error_code, std::size_t) @endcode * * @note The write operation may not transmit all of the data to the peer. * Consider using the @ref async_write function if you need to ensure that all * data is written before the asynchronous operation completes. * * @par Example * To write a single data buffer use the @ref buffer function as follows: * @code * socket.async_write_some(asio::buffer(data, size), handler); * @endcode * See the @ref buffer documentation for information on writing multiple * buffers in one go, and how to use it with arrays, boost::array or * std::vector. * * @par Per-Operation Cancellation * On POSIX or Windows operating systems, this asynchronous operation supports * cancellation for the following asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * @li @c cancellation_type::total */ template <typename ConstBufferSequence, ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code, std::size_t)) WriteToken = default_completion_token_t<executor_type>> auto async_write_some(const ConstBufferSequence& buffers, WriteToken&& token = default_completion_token_t<executor_type>()) -> decltype( async_initiate<WriteToken, void (asio::error_code, std::size_t)>( declval<initiate_async_send>(), token, buffers, socket_base::message_flags(0))) { return async_initiate<WriteToken, void (asio::error_code, std::size_t)>( initiate_async_send(this), token, buffers, socket_base::message_flags(0)); } /// Read some data from the socket. /** * This function is used to read data from the stream socket. The function * call will block until one or more bytes of data has been read successfully, * or until an error occurs. * * @param buffers One or more buffers into which the data will be read. * * @returns The number of bytes read. * * @throws asio::system_error Thrown on failure. An error code of * asio::error::eof indicates that the connection was closed by the * peer. * * @note The read_some operation may not read all of the requested number of * bytes. Consider using the @ref read function if you need to ensure that * the requested amount of data is read before the blocking operation * completes. * * @par Example * To read into a single data buffer use the @ref buffer function as follows: * @code * socket.read_some(asio::buffer(data, size)); * @endcode * See the @ref buffer documentation for information on reading into multiple * buffers in one go, and how to use it with arrays, boost::array or * std::vector. */ template <typename MutableBufferSequence> std::size_t read_some(const MutableBufferSequence& buffers) { asio::error_code ec; std::size_t s = this->impl_.get_service().receive( this->impl_.get_implementation(), buffers, 0, ec); asio::detail::throw_error(ec, "read_some"); return s; } /// Read some data from the socket. /** * This function is used to read data from the stream socket. The function * call will block until one or more bytes of data has been read successfully, * or until an error occurs. * * @param buffers One or more buffers into which the data will be read. * * @param ec Set to indicate what error occurred, if any. * * @returns The number of bytes read. Returns 0 if an error occurred. * * @note The read_some operation may not read all of the requested number of * bytes. Consider using the @ref read function if you need to ensure that * the requested amount of data is read before the blocking operation * completes. */ template <typename MutableBufferSequence> std::size_t read_some(const MutableBufferSequence& buffers, asio::error_code& ec) { return this->impl_.get_service().receive( this->impl_.get_implementation(), buffers, 0, ec); } /// Start an asynchronous read. /** * This function is used to asynchronously read data from the stream socket. * socket. It is an initiating function for an @ref asynchronous_operation, * and always returns immediately. * * @param buffers One or more buffers into which the data will be read. * Although the buffers object may be copied as necessary, ownership of the * underlying memory blocks is retained by the caller, which must guarantee * that they remain valid until the completion handler is called. * * @param token The @ref completion_token that will be used to produce a * completion handler, which will be called when the read completes. * Potential completion tokens include @ref use_future, @ref use_awaitable, * @ref yield_context, or a function object with the correct completion * signature. The function signature of the completion handler must be: * @code void handler( * const asio::error_code& error, // Result of operation. * std::size_t bytes_transferred // Number of bytes read. * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the completion handler will not be invoked from within this function. * On immediate completion, invocation of the handler will be performed in a * manner equivalent to using asio::async_immediate(). * * @par Completion Signature * @code void(asio::error_code, std::size_t) @endcode * * @note The read operation may not read all of the requested number of bytes. * Consider using the @ref async_read function if you need to ensure that the * requested amount of data is read before the asynchronous operation * completes. * * @par Example * To read into a single data buffer use the @ref buffer function as follows: * @code * socket.async_read_some(asio::buffer(data, size), handler); * @endcode * See the @ref buffer documentation for information on reading into multiple * buffers in one go, and how to use it with arrays, boost::array or * std::vector. * * @par Per-Operation Cancellation * On POSIX or Windows operating systems, this asynchronous operation supports * cancellation for the following asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * @li @c cancellation_type::total */ template <typename MutableBufferSequence, ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code, std::size_t)) ReadToken = default_completion_token_t<executor_type>> auto async_read_some(const MutableBufferSequence& buffers, ReadToken&& token = default_completion_token_t<executor_type>()) -> decltype( async_initiate<ReadToken, void (asio::error_code, std::size_t)>( declval<initiate_async_receive>(), token, buffers, socket_base::message_flags(0))) { return async_initiate<ReadToken, void (asio::error_code, std::size_t)>( initiate_async_receive(this), token, buffers, socket_base::message_flags(0)); } private: // Disallow copying and assignment. basic_stream_socket(const basic_stream_socket&) = delete; basic_stream_socket& operator=(const basic_stream_socket&) = delete; class initiate_async_send { public: typedef Executor executor_type; explicit initiate_async_send(basic_stream_socket* self) : self_(self) { } const executor_type& get_executor() const noexcept { return self_->get_executor(); } template <typename WriteHandler, typename ConstBufferSequence> void operator()(WriteHandler&& handler, const ConstBufferSequence& buffers, socket_base::message_flags flags) const { // If you get an error on the following line it means that your handler // does not meet the documented type requirements for a WriteHandler. ASIO_WRITE_HANDLER_CHECK(WriteHandler, handler) type_check; detail::non_const_lvalue<WriteHandler> handler2(handler); self_->impl_.get_service().async_send( self_->impl_.get_implementation(), buffers, flags, handler2.value, self_->impl_.get_executor()); } private: basic_stream_socket* self_; }; class initiate_async_receive { public: typedef Executor executor_type; explicit initiate_async_receive(basic_stream_socket* self) : self_(self) { } const executor_type& get_executor() const noexcept { return self_->get_executor(); } template <typename ReadHandler, typename MutableBufferSequence> void operator()(ReadHandler&& handler, const MutableBufferSequence& buffers, socket_base::message_flags flags) const { // If you get an error on the following line it means that your handler // does not meet the documented type requirements for a ReadHandler. ASIO_READ_HANDLER_CHECK(ReadHandler, handler) type_check; detail::non_const_lvalue<ReadHandler> handler2(handler); self_->impl_.get_service().async_receive( self_->impl_.get_implementation(), buffers, flags, handler2.value, self_->impl_.get_executor()); } private: basic_stream_socket* self_; }; }; } // namespace asio #include "asio/detail/pop_options.hpp" #endif // ASIO_BASIC_STREAM_SOCKET_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/basic_io_object.hpp
// // basic_io_object.hpp // ~~~~~~~~~~~~~~~~~~~ // // 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) // #ifndef ASIO_BASIC_IO_OBJECT_HPP #define ASIO_BASIC_IO_OBJECT_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include "asio/io_context.hpp" #include "asio/detail/push_options.hpp" namespace asio { namespace detail { // Type trait used to determine whether a service supports move. template <typename IoObjectService> class service_has_move { private: typedef IoObjectService service_type; typedef typename service_type::implementation_type implementation_type; template <typename T, typename U> static auto asio_service_has_move_eval(T* t, U* u) -> decltype(t->move_construct(*u, *u), char()); static char (&asio_service_has_move_eval(...))[2]; public: static const bool value = sizeof(asio_service_has_move_eval( static_cast<service_type*>(0), static_cast<implementation_type*>(0))) == 1; }; } /// Base class for all I/O objects. /** * @note All I/O objects are non-copyable. However, when using C++0x, certain * I/O objects do support move construction and move assignment. */ #if defined(GENERATING_DOCUMENTATION) template <typename IoObjectService> #else template <typename IoObjectService, bool Movable = detail::service_has_move<IoObjectService>::value> #endif class basic_io_object { public: /// The type of the service that will be used to provide I/O operations. typedef IoObjectService service_type; /// The underlying implementation type of I/O object. typedef typename service_type::implementation_type implementation_type; #if !defined(ASIO_NO_DEPRECATED) /// (Deprecated: Use get_executor().) Get the io_context associated with the /// object. /** * This function may be used to obtain the io_context object that the I/O * object uses to dispatch handlers for asynchronous operations. * * @return A reference to the io_context object that the I/O object will use * to dispatch handlers. Ownership is not transferred to the caller. */ asio::io_context& get_io_context() { return service_.get_io_context(); } /// (Deprecated: Use get_executor().) Get the io_context associated with the /// object. /** * This function may be used to obtain the io_context object that the I/O * object uses to dispatch handlers for asynchronous operations. * * @return A reference to the io_context object that the I/O object will use * to dispatch handlers. Ownership is not transferred to the caller. */ asio::io_context& get_io_service() { return service_.get_io_context(); } #endif // !defined(ASIO_NO_DEPRECATED) /// The type of the executor associated with the object. typedef asio::io_context::executor_type executor_type; /// Get the executor associated with the object. executor_type get_executor() noexcept { return service_.get_io_context().get_executor(); } protected: /// Construct a basic_io_object. /** * Performs: * @code get_service().construct(get_implementation()); @endcode */ explicit basic_io_object(asio::io_context& io_context) : service_(asio::use_service<IoObjectService>(io_context)) { service_.construct(implementation_); } #if defined(GENERATING_DOCUMENTATION) /// Move-construct a basic_io_object. /** * Performs: * @code get_service().move_construct( * get_implementation(), other.get_implementation()); @endcode * * @note Available only for services that support movability, */ basic_io_object(basic_io_object&& other); /// Move-assign a basic_io_object. /** * Performs: * @code get_service().move_assign(get_implementation(), * other.get_service(), other.get_implementation()); @endcode * * @note Available only for services that support movability, */ basic_io_object& operator=(basic_io_object&& other); /// Perform a converting move-construction of a basic_io_object. template <typename IoObjectService1> basic_io_object(IoObjectService1& other_service, typename IoObjectService1::implementation_type& other_implementation); #endif // defined(GENERATING_DOCUMENTATION) /// Protected destructor to prevent deletion through this type. /** * Performs: * @code get_service().destroy(get_implementation()); @endcode */ ~basic_io_object() { service_.destroy(implementation_); } /// Get the service associated with the I/O object. service_type& get_service() { return service_; } /// Get the service associated with the I/O object. const service_type& get_service() const { return service_; } /// Get the underlying implementation of the I/O object. implementation_type& get_implementation() { return implementation_; } /// Get the underlying implementation of the I/O object. const implementation_type& get_implementation() const { return implementation_; } private: basic_io_object(const basic_io_object&); basic_io_object& operator=(const basic_io_object&); // The service associated with the I/O object. service_type& service_; /// The underlying implementation of the I/O object. implementation_type implementation_; }; // Specialisation for movable objects. template <typename IoObjectService> class basic_io_object<IoObjectService, true> { public: typedef IoObjectService service_type; typedef typename service_type::implementation_type implementation_type; #if !defined(ASIO_NO_DEPRECATED) asio::io_context& get_io_context() { return service_->get_io_context(); } asio::io_context& get_io_service() { return service_->get_io_context(); } #endif // !defined(ASIO_NO_DEPRECATED) typedef asio::io_context::executor_type executor_type; executor_type get_executor() noexcept { return service_->get_io_context().get_executor(); } protected: explicit basic_io_object(asio::io_context& io_context) : service_(&asio::use_service<IoObjectService>(io_context)) { service_->construct(implementation_); } basic_io_object(basic_io_object&& other) : service_(&other.get_service()) { service_->move_construct(implementation_, other.implementation_); } template <typename IoObjectService1> basic_io_object(IoObjectService1& other_service, typename IoObjectService1::implementation_type& other_implementation) : service_(&asio::use_service<IoObjectService>( other_service.get_io_context())) { service_->converting_move_construct(implementation_, other_service, other_implementation); } ~basic_io_object() { service_->destroy(implementation_); } basic_io_object& operator=(basic_io_object&& other) { service_->move_assign(implementation_, *other.service_, other.implementation_); service_ = other.service_; return *this; } service_type& get_service() { return *service_; } const service_type& get_service() const { return *service_; } implementation_type& get_implementation() { return implementation_; } const implementation_type& get_implementation() const { return implementation_; } private: basic_io_object(const basic_io_object&); void operator=(const basic_io_object&); IoObjectService* service_; implementation_type implementation_; }; } // namespace asio #include "asio/detail/pop_options.hpp" #endif // ASIO_BASIC_IO_OBJECT_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/default_completion_token.hpp
// // default_completion_token.hpp // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // // 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) // #ifndef ASIO_DEFAULT_COMPLETION_TOKEN_HPP #define ASIO_DEFAULT_COMPLETION_TOKEN_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include "asio/detail/type_traits.hpp" #include "asio/detail/push_options.hpp" namespace asio { class deferred_t; namespace detail { template <typename T, typename = void> struct default_completion_token_impl { typedef deferred_t type; }; template <typename T> struct default_completion_token_impl<T, void_t<typename T::default_completion_token_type> > { typedef typename T::default_completion_token_type type; }; } // namespace detail #if defined(GENERATING_DOCUMENTATION) /// Traits type used to determine the default completion token type associated /// with a type (such as an executor). /** * A program may specialise this traits type if the @c T template parameter in * the specialisation is a user-defined type. * * Specialisations of this trait may provide a nested typedef @c type, which is * a default-constructible completion token type. * * If not otherwise specialised, the default completion token type is * asio::deferred_t. */ template <typename T> struct default_completion_token { /// If @c T has a nested type @c default_completion_token_type, /// <tt>T::default_completion_token_type</tt>. Otherwise the typedef @c type /// is asio::deferred_t. typedef see_below type; }; #else template <typename T> struct default_completion_token : detail::default_completion_token_impl<T> { }; #endif template <typename T> using default_completion_token_t = typename default_completion_token<T>::type; #define ASIO_DEFAULT_COMPLETION_TOKEN_TYPE(e) \ = typename ::asio::default_completion_token<e>::type #define ASIO_DEFAULT_COMPLETION_TOKEN(e) \ = typename ::asio::default_completion_token<e>::type() } // namespace asio #include "asio/detail/pop_options.hpp" #include "asio/deferred.hpp" #endif // ASIO_DEFAULT_COMPLETION_TOKEN_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/read_at.hpp
// // read_at.hpp // ~~~~~~~~~~~ // // 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) // #ifndef ASIO_READ_AT_HPP #define ASIO_READ_AT_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include <cstddef> #include "asio/async_result.hpp" #include "asio/completion_condition.hpp" #include "asio/detail/cstdint.hpp" #include "asio/error.hpp" #if !defined(ASIO_NO_EXTENSIONS) # include "asio/basic_streambuf_fwd.hpp" #endif // !defined(ASIO_NO_EXTENSIONS) #include "asio/detail/push_options.hpp" namespace asio { namespace detail { template <typename> class initiate_async_read_at; #if !defined(ASIO_NO_IOSTREAM) template <typename> class initiate_async_read_at_streambuf; #endif // !defined(ASIO_NO_IOSTREAM) } // namespace detail /** * @defgroup read_at asio::read_at * * @brief The @c read_at function is a composed operation that reads a certain * amount of data at the specified offset before returning. */ /*@{*/ /// Attempt to read a certain amount of data at the specified offset before /// returning. /** * This function is used to read a certain number of bytes of data from a * random access device at the specified offset. The call will block until one * of the following conditions is true: * * @li The supplied buffers are full. That is, the bytes transferred is equal to * the sum of the buffer sizes. * * @li An error occurred. * * This operation is implemented in terms of zero or more calls to the device's * read_some_at function. * * @param d The device from which the data is to be read. The type must support * the SyncRandomAccessReadDevice concept. * * @param offset The offset at which the data will be read. * * @param buffers One or more buffers into which the data will be read. The sum * of the buffer sizes indicates the maximum number of bytes to read from the * device. * * @returns The number of bytes transferred. * * @throws asio::system_error Thrown on failure. * * @par Example * To read into a single data buffer use the @ref buffer function as follows: * @code asio::read_at(d, 42, asio::buffer(data, size)); @endcode * See the @ref buffer documentation for information on reading into multiple * buffers in one go, and how to use it with arrays, boost::array or * std::vector. * * @note This overload is equivalent to calling: * @code asio::read_at( * d, 42, buffers, * asio::transfer_all()); @endcode */ template <typename SyncRandomAccessReadDevice, typename MutableBufferSequence> std::size_t read_at(SyncRandomAccessReadDevice& d, uint64_t offset, const MutableBufferSequence& buffers); /// Attempt to read a certain amount of data at the specified offset before /// returning. /** * This function is used to read a certain number of bytes of data from a * random access device at the specified offset. The call will block until one * of the following conditions is true: * * @li The supplied buffers are full. That is, the bytes transferred is equal to * the sum of the buffer sizes. * * @li An error occurred. * * This operation is implemented in terms of zero or more calls to the device's * read_some_at function. * * @param d The device from which the data is to be read. The type must support * the SyncRandomAccessReadDevice concept. * * @param offset The offset at which the data will be read. * * @param buffers One or more buffers into which the data will be read. The sum * of the buffer sizes indicates the maximum number of bytes to read from the * device. * * @param ec Set to indicate what error occurred, if any. * * @returns The number of bytes transferred. * * @par Example * To read into a single data buffer use the @ref buffer function as follows: * @code asio::read_at(d, 42, * asio::buffer(data, size), ec); @endcode * See the @ref buffer documentation for information on reading into multiple * buffers in one go, and how to use it with arrays, boost::array or * std::vector. * * @note This overload is equivalent to calling: * @code asio::read_at( * d, 42, buffers, * asio::transfer_all(), ec); @endcode */ template <typename SyncRandomAccessReadDevice, typename MutableBufferSequence> std::size_t read_at(SyncRandomAccessReadDevice& d, uint64_t offset, const MutableBufferSequence& buffers, asio::error_code& ec); /// Attempt to read a certain amount of data at the specified offset before /// returning. /** * This function is used to read a certain number of bytes of data from a * random access device at the specified offset. The call will block until one * of the following conditions is true: * * @li The supplied buffers are full. That is, the bytes transferred is equal to * the sum of the buffer sizes. * * @li The completion_condition function object returns 0. * * This operation is implemented in terms of zero or more calls to the device's * read_some_at function. * * @param d The device from which the data is to be read. The type must support * the SyncRandomAccessReadDevice concept. * * @param offset The offset at which the data will be read. * * @param buffers One or more buffers into which the data will be read. The sum * of the buffer sizes indicates the maximum number of bytes to read from the * device. * * @param completion_condition The function object to be called to determine * whether the read operation is complete. The signature of the function object * must be: * @code std::size_t completion_condition( * // Result of latest read_some_at operation. * const asio::error_code& error, * * // Number of bytes transferred so far. * std::size_t bytes_transferred * ); @endcode * A return value of 0 indicates that the read operation is complete. A non-zero * return value indicates the maximum number of bytes to be read on the next * call to the device's read_some_at function. * * @returns The number of bytes transferred. * * @throws asio::system_error Thrown on failure. * * @par Example * To read into a single data buffer use the @ref buffer function as follows: * @code asio::read_at(d, 42, asio::buffer(data, size), * asio::transfer_at_least(32)); @endcode * See the @ref buffer documentation for information on reading into multiple * buffers in one go, and how to use it with arrays, boost::array or * std::vector. */ template <typename SyncRandomAccessReadDevice, typename MutableBufferSequence, typename CompletionCondition> std::size_t read_at(SyncRandomAccessReadDevice& d, uint64_t offset, const MutableBufferSequence& buffers, CompletionCondition completion_condition, constraint_t< is_completion_condition<CompletionCondition>::value > = 0); /// Attempt to read a certain amount of data at the specified offset before /// returning. /** * This function is used to read a certain number of bytes of data from a * random access device at the specified offset. The call will block until one * of the following conditions is true: * * @li The supplied buffers are full. That is, the bytes transferred is equal to * the sum of the buffer sizes. * * @li The completion_condition function object returns 0. * * This operation is implemented in terms of zero or more calls to the device's * read_some_at function. * * @param d The device from which the data is to be read. The type must support * the SyncRandomAccessReadDevice concept. * * @param offset The offset at which the data will be read. * * @param buffers One or more buffers into which the data will be read. The sum * of the buffer sizes indicates the maximum number of bytes to read from the * device. * * @param completion_condition The function object to be called to determine * whether the read operation is complete. The signature of the function object * must be: * @code std::size_t completion_condition( * // Result of latest read_some_at operation. * const asio::error_code& error, * * // Number of bytes transferred so far. * std::size_t bytes_transferred * ); @endcode * A return value of 0 indicates that the read operation is complete. A non-zero * return value indicates the maximum number of bytes to be read on the next * call to the device's read_some_at function. * * @param ec Set to indicate what error occurred, if any. * * @returns The number of bytes read. If an error occurs, returns the total * number of bytes successfully transferred prior to the error. */ template <typename SyncRandomAccessReadDevice, typename MutableBufferSequence, typename CompletionCondition> std::size_t read_at(SyncRandomAccessReadDevice& d, uint64_t offset, const MutableBufferSequence& buffers, CompletionCondition completion_condition, asio::error_code& ec, constraint_t< is_completion_condition<CompletionCondition>::value > = 0); #if !defined(ASIO_NO_EXTENSIONS) #if !defined(ASIO_NO_IOSTREAM) /// Attempt to read a certain amount of data at the specified offset before /// returning. /** * This function is used to read a certain number of bytes of data from a * random access device at the specified offset. The call will block until one * of the following conditions is true: * * @li An error occurred. * * This operation is implemented in terms of zero or more calls to the device's * read_some_at function. * * @param d The device from which the data is to be read. The type must support * the SyncRandomAccessReadDevice concept. * * @param offset The offset at which the data will be read. * * @param b The basic_streambuf object into which the data will be read. * * @returns The number of bytes transferred. * * @throws asio::system_error Thrown on failure. * * @note This overload is equivalent to calling: * @code asio::read_at( * d, 42, b, * asio::transfer_all()); @endcode */ template <typename SyncRandomAccessReadDevice, typename Allocator> std::size_t read_at(SyncRandomAccessReadDevice& d, uint64_t offset, basic_streambuf<Allocator>& b); /// Attempt to read a certain amount of data at the specified offset before /// returning. /** * This function is used to read a certain number of bytes of data from a * random access device at the specified offset. The call will block until one * of the following conditions is true: * * @li An error occurred. * * This operation is implemented in terms of zero or more calls to the device's * read_some_at function. * * @param d The device from which the data is to be read. The type must support * the SyncRandomAccessReadDevice concept. * * @param offset The offset at which the data will be read. * * @param b The basic_streambuf object into which the data will be read. * * @param ec Set to indicate what error occurred, if any. * * @returns The number of bytes transferred. * * @note This overload is equivalent to calling: * @code asio::read_at( * d, 42, b, * asio::transfer_all(), ec); @endcode */ template <typename SyncRandomAccessReadDevice, typename Allocator> std::size_t read_at(SyncRandomAccessReadDevice& d, uint64_t offset, basic_streambuf<Allocator>& b, asio::error_code& ec); /// Attempt to read a certain amount of data at the specified offset before /// returning. /** * This function is used to read a certain number of bytes of data from a * random access device at the specified offset. The call will block until one * of the following conditions is true: * * @li The completion_condition function object returns 0. * * This operation is implemented in terms of zero or more calls to the device's * read_some_at function. * * @param d The device from which the data is to be read. The type must support * the SyncRandomAccessReadDevice concept. * * @param offset The offset at which the data will be read. * * @param b The basic_streambuf object into which the data will be read. * * @param completion_condition The function object to be called to determine * whether the read operation is complete. The signature of the function object * must be: * @code std::size_t completion_condition( * // Result of latest read_some_at operation. * const asio::error_code& error, * * // Number of bytes transferred so far. * std::size_t bytes_transferred * ); @endcode * A return value of 0 indicates that the read operation is complete. A non-zero * return value indicates the maximum number of bytes to be read on the next * call to the device's read_some_at function. * * @returns The number of bytes transferred. * * @throws asio::system_error Thrown on failure. */ template <typename SyncRandomAccessReadDevice, typename Allocator, typename CompletionCondition> std::size_t read_at(SyncRandomAccessReadDevice& d, uint64_t offset, basic_streambuf<Allocator>& b, CompletionCondition completion_condition, constraint_t< is_completion_condition<CompletionCondition>::value > = 0); /// Attempt to read a certain amount of data at the specified offset before /// returning. /** * This function is used to read a certain number of bytes of data from a * random access device at the specified offset. The call will block until one * of the following conditions is true: * * @li The completion_condition function object returns 0. * * This operation is implemented in terms of zero or more calls to the device's * read_some_at function. * * @param d The device from which the data is to be read. The type must support * the SyncRandomAccessReadDevice concept. * * @param offset The offset at which the data will be read. * * @param b The basic_streambuf object into which the data will be read. * * @param completion_condition The function object to be called to determine * whether the read operation is complete. The signature of the function object * must be: * @code std::size_t completion_condition( * // Result of latest read_some_at operation. * const asio::error_code& error, * * // Number of bytes transferred so far. * std::size_t bytes_transferred * ); @endcode * A return value of 0 indicates that the read operation is complete. A non-zero * return value indicates the maximum number of bytes to be read on the next * call to the device's read_some_at function. * * @param ec Set to indicate what error occurred, if any. * * @returns The number of bytes read. If an error occurs, returns the total * number of bytes successfully transferred prior to the error. */ template <typename SyncRandomAccessReadDevice, typename Allocator, typename CompletionCondition> std::size_t read_at(SyncRandomAccessReadDevice& d, uint64_t offset, basic_streambuf<Allocator>& b, CompletionCondition completion_condition, asio::error_code& ec, constraint_t< is_completion_condition<CompletionCondition>::value > = 0); #endif // !defined(ASIO_NO_IOSTREAM) #endif // !defined(ASIO_NO_EXTENSIONS) /*@}*/ /** * @defgroup async_read_at asio::async_read_at * * @brief The @c async_read_at function is a composed asynchronous operation * that reads a certain amount of data at the specified offset. */ /*@{*/ /// Start an asynchronous operation to read a certain amount of data at the /// specified offset. /** * This function is used to asynchronously read a certain number of bytes of * data from a random access device at the specified offset. It is an * initiating function for an @ref asynchronous_operation, and always returns * immediately. The asynchronous operation will continue until one of the * following conditions is true: * * @li The supplied buffers are full. That is, the bytes transferred is equal to * the sum of the buffer sizes. * * @li An error occurred. * * This operation is implemented in terms of zero or more calls to the device's * async_read_some_at function. * * @param d The device from which the data is to be read. The type must support * the AsyncRandomAccessReadDevice concept. * * @param offset The offset at which the data will be read. * * @param buffers One or more buffers into which the data will be read. The sum * of the buffer sizes indicates the maximum number of bytes to read from the * device. Although the buffers object may be copied as necessary, ownership of * the underlying memory blocks is retained by the caller, which must guarantee * that they remain valid until the completion handler is called. * * @param token The @ref completion_token that will be used to produce a * completion handler, which will be called when the read completes. * Potential completion tokens include @ref use_future, @ref use_awaitable, * @ref yield_context, or a function object with the correct completion * signature. The function signature of the completion handler must be: * @code void handler( * // Result of operation. * const asio::error_code& error, * * // Number of bytes copied into the buffers. If an error * // occurred, this will be the number of bytes successfully * // transferred prior to the error. * std::size_t bytes_transferred * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the completion handler will not be invoked from within this function. * On immediate completion, invocation of the handler will be performed in a * manner equivalent to using asio::async_immediate(). * * @par Completion Signature * @code void(asio::error_code, std::size_t) @endcode * * @par Example * To read into a single data buffer use the @ref buffer function as follows: * @code * asio::async_read_at(d, 42, asio::buffer(data, size), handler); * @endcode * See the @ref buffer documentation for information on reading into multiple * buffers in one go, and how to use it with arrays, boost::array or * std::vector. * * @note This overload is equivalent to calling: * @code asio::async_read_at( * d, 42, buffers, * asio::transfer_all(), * handler); @endcode * * @par Per-Operation Cancellation * This asynchronous operation supports cancellation for the following * asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * if they are also supported by the @c AsyncRandomAccessReadDevice type's * async_read_some_at operation. */ template <typename AsyncRandomAccessReadDevice, typename MutableBufferSequence, ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code, std::size_t)) ReadToken = default_completion_token_t< typename AsyncRandomAccessReadDevice::executor_type>> inline auto async_read_at(AsyncRandomAccessReadDevice& d, uint64_t offset, const MutableBufferSequence& buffers, ReadToken&& token = default_completion_token_t< typename AsyncRandomAccessReadDevice::executor_type>(), constraint_t< !is_completion_condition<ReadToken>::value > = 0) -> decltype( async_initiate<ReadToken, void (asio::error_code, std::size_t)>( declval<detail::initiate_async_read_at<AsyncRandomAccessReadDevice>>(), token, offset, buffers, transfer_all())) { return async_initiate<ReadToken, void (asio::error_code, std::size_t)>( detail::initiate_async_read_at<AsyncRandomAccessReadDevice>(d), token, offset, buffers, transfer_all()); } /// Start an asynchronous operation to read a certain amount of data at the /// specified offset. /** * This function is used to asynchronously read a certain number of bytes of * data from a random access device at the specified offset. It is an * initiating function for an @ref asynchronous_operation, and always returns * immediately. The asynchronous operation will continue until one of the * following conditions is true: * * @li The supplied buffers are full. That is, the bytes transferred is equal to * the sum of the buffer sizes. * * @li The completion_condition function object returns 0. * * @param d The device from which the data is to be read. The type must support * the AsyncRandomAccessReadDevice concept. * * @param offset The offset at which the data will be read. * * @param buffers One or more buffers into which the data will be read. The sum * of the buffer sizes indicates the maximum number of bytes to read from the * device. Although the buffers object may be copied as necessary, ownership of * the underlying memory blocks is retained by the caller, which must guarantee * that they remain valid until the completion handler is called. * * @param completion_condition The function object to be called to determine * whether the read operation is complete. The signature of the function object * must be: * @code std::size_t completion_condition( * // Result of latest async_read_some_at operation. * const asio::error_code& error, * * // Number of bytes transferred so far. * std::size_t bytes_transferred * ); @endcode * A return value of 0 indicates that the read operation is complete. A non-zero * return value indicates the maximum number of bytes to be read on the next * call to the device's async_read_some_at function. * * @param token The @ref completion_token that will be used to produce a * completion handler, which will be called when the read completes. * Potential completion tokens include @ref use_future, @ref use_awaitable, * @ref yield_context, or a function object with the correct completion * signature. The function signature of the completion handler must be: * @code void handler( * // Result of operation. * const asio::error_code& error, * * // Number of bytes copied into the buffers. If an error * // occurred, this will be the number of bytes successfully * // transferred prior to the error. * std::size_t bytes_transferred * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the completion handler will not be invoked from within this function. * On immediate completion, invocation of the handler will be performed in a * manner equivalent to using asio::async_immediate(). * * @par Completion Signature * @code void(asio::error_code, std::size_t) @endcode * * @par Example * To read into a single data buffer use the @ref buffer function as follows: * @code asio::async_read_at(d, 42, * asio::buffer(data, size), * asio::transfer_at_least(32), * handler); @endcode * See the @ref buffer documentation for information on reading into multiple * buffers in one go, and how to use it with arrays, boost::array or * std::vector. * * @par Per-Operation Cancellation * This asynchronous operation supports cancellation for the following * asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * if they are also supported by the @c AsyncRandomAccessReadDevice type's * async_read_some_at operation. */ template <typename AsyncRandomAccessReadDevice, typename MutableBufferSequence, typename CompletionCondition, ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code, std::size_t)) ReadToken = default_completion_token_t< typename AsyncRandomAccessReadDevice::executor_type>> inline auto async_read_at(AsyncRandomAccessReadDevice& d, uint64_t offset, const MutableBufferSequence& buffers, CompletionCondition completion_condition, ReadToken&& token = default_completion_token_t< typename AsyncRandomAccessReadDevice::executor_type>(), constraint_t< is_completion_condition<CompletionCondition>::value > = 0) -> decltype( async_initiate<ReadToken, void (asio::error_code, std::size_t)>( declval<detail::initiate_async_read_at<AsyncRandomAccessReadDevice>>(), token, offset, buffers, static_cast<CompletionCondition&&>(completion_condition))) { return async_initiate<ReadToken, void (asio::error_code, std::size_t)>( detail::initiate_async_read_at<AsyncRandomAccessReadDevice>(d), token, offset, buffers, static_cast<CompletionCondition&&>(completion_condition)); } #if !defined(ASIO_NO_EXTENSIONS) #if !defined(ASIO_NO_IOSTREAM) /// Start an asynchronous operation to read a certain amount of data at the /// specified offset. /** * This function is used to asynchronously read a certain number of bytes of * data from a random access device at the specified offset. It is an * initiating function for an @ref asynchronous_operation, and always returns * immediately. The asynchronous operation will continue until one of the * following conditions is true: * * @li An error occurred. * * This operation is implemented in terms of zero or more calls to the device's * async_read_some_at function. * * @param d The device from which the data is to be read. The type must support * the AsyncRandomAccessReadDevice concept. * * @param offset The offset at which the data will be read. * * @param b A basic_streambuf object into which the data will be read. Ownership * of the streambuf is retained by the caller, which must guarantee that it * remains valid until the completion handler is called. * * @param token The @ref completion_token that will be used to produce a * completion handler, which will be called when the read completes. * Potential completion tokens include @ref use_future, @ref use_awaitable, * @ref yield_context, or a function object with the correct completion * signature. The function signature of the completion handler must be: * @code void handler( * // Result of operation. * const asio::error_code& error, * * // Number of bytes copied into the buffers. If an error * // occurred, this will be the number of bytes successfully * // transferred prior to the error. * std::size_t bytes_transferred * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the completion handler will not be invoked from within this function. * On immediate completion, invocation of the handler will be performed in a * manner equivalent to using asio::async_immediate(). * * @par Completion Signature * @code void(asio::error_code, std::size_t) @endcode * * @note This overload is equivalent to calling: * @code asio::async_read_at( * d, 42, b, * asio::transfer_all(), * handler); @endcode * * @par Per-Operation Cancellation * This asynchronous operation supports cancellation for the following * asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * if they are also supported by the @c AsyncRandomAccessReadDevice type's * async_read_some_at operation. */ template <typename AsyncRandomAccessReadDevice, typename Allocator, ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code, std::size_t)) ReadToken = default_completion_token_t< typename AsyncRandomAccessReadDevice::executor_type>> inline auto async_read_at(AsyncRandomAccessReadDevice& d, uint64_t offset, basic_streambuf<Allocator>& b, ReadToken&& token = default_completion_token_t< typename AsyncRandomAccessReadDevice::executor_type>(), constraint_t< !is_completion_condition<ReadToken>::value > = 0) -> decltype( async_initiate<ReadToken, void (asio::error_code, std::size_t)>( declval<detail::initiate_async_read_at_streambuf< AsyncRandomAccessReadDevice>>(), token, offset, &b, transfer_all())) { return async_initiate<ReadToken, void (asio::error_code, std::size_t)>( detail::initiate_async_read_at_streambuf<AsyncRandomAccessReadDevice>(d), token, offset, &b, transfer_all()); } /// Start an asynchronous operation to read a certain amount of data at the /// specified offset. /** * This function is used to asynchronously read a certain number of bytes of * data from a random access device at the specified offset. It is an * initiating function for an @ref asynchronous_operation, and always returns * immediately. The asynchronous operation will continue until one of the * following conditions is true: * * @li The completion_condition function object returns 0. * * This operation is implemented in terms of zero or more calls to the device's * async_read_some_at function. * * @param d The device from which the data is to be read. The type must support * the AsyncRandomAccessReadDevice concept. * * @param offset The offset at which the data will be read. * * @param b A basic_streambuf object into which the data will be read. Ownership * of the streambuf is retained by the caller, which must guarantee that it * remains valid until the completion handler is called. * * @param completion_condition The function object to be called to determine * whether the read operation is complete. The signature of the function object * must be: * @code std::size_t completion_condition( * // Result of latest async_read_some_at operation. * const asio::error_code& error, * * // Number of bytes transferred so far. * std::size_t bytes_transferred * ); @endcode * A return value of 0 indicates that the read operation is complete. A non-zero * return value indicates the maximum number of bytes to be read on the next * call to the device's async_read_some_at function. * * @param token The @ref completion_token that will be used to produce a * completion handler, which will be called when the read completes. * Potential completion tokens include @ref use_future, @ref use_awaitable, * @ref yield_context, or a function object with the correct completion * signature. The function signature of the completion handler must be: * @code void handler( * // Result of operation. * const asio::error_code& error, * * // Number of bytes copied into the buffers. If an error * // occurred, this will be the number of bytes successfully * // transferred prior to the error. * std::size_t bytes_transferred * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the completion handler will not be invoked from within this function. * On immediate completion, invocation of the handler will be performed in a * manner equivalent to using asio::async_immediate(). * * @par Completion Signature * @code void(asio::error_code, std::size_t) @endcode * * @par Per-Operation Cancellation * This asynchronous operation supports cancellation for the following * asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * if they are also supported by the @c AsyncRandomAccessReadDevice type's * async_read_some_at operation. */ template <typename AsyncRandomAccessReadDevice, typename Allocator, typename CompletionCondition, ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code, std::size_t)) ReadToken = default_completion_token_t< typename AsyncRandomAccessReadDevice::executor_type>> inline auto async_read_at(AsyncRandomAccessReadDevice& d, uint64_t offset, basic_streambuf<Allocator>& b, CompletionCondition completion_condition, ReadToken&& token = default_completion_token_t< typename AsyncRandomAccessReadDevice::executor_type>(), constraint_t< is_completion_condition<CompletionCondition>::value > = 0) -> decltype( async_initiate<ReadToken, void (asio::error_code, std::size_t)>( declval<detail::initiate_async_read_at_streambuf< AsyncRandomAccessReadDevice>>(), token, offset, &b, static_cast<CompletionCondition&&>(completion_condition))) { return async_initiate<ReadToken, void (asio::error_code, std::size_t)>( detail::initiate_async_read_at_streambuf<AsyncRandomAccessReadDevice>(d), token, offset, &b, static_cast<CompletionCondition&&>(completion_condition)); } #endif // !defined(ASIO_NO_IOSTREAM) #endif // !defined(ASIO_NO_EXTENSIONS) /*@}*/ } // namespace asio #include "asio/detail/pop_options.hpp" #include "asio/impl/read_at.hpp" #endif // ASIO_READ_AT_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/system_timer.hpp
// // system_timer.hpp // ~~~~~~~~~~~~~~~~ // // 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) // #ifndef ASIO_SYSTEM_TIMER_HPP #define ASIO_SYSTEM_TIMER_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include "asio/basic_waitable_timer.hpp" #include "asio/detail/chrono.hpp" namespace asio { /// Typedef for a timer based on the system clock. /** * This typedef uses the C++11 @c &lt;chrono&gt; standard library facility, if * available. Otherwise, it may use the Boost.Chrono library. To explicitly * utilise Boost.Chrono, use the basic_waitable_timer template directly: * @code * typedef basic_waitable_timer<boost::chrono::system_clock> timer; * @endcode */ typedef basic_waitable_timer<chrono::system_clock> system_timer; } // namespace asio #endif // ASIO_SYSTEM_TIMER_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/random_access_file.hpp
// // random_access_file.hpp // ~~~~~~~~~~~~~~~~~~~~~~ // // 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) // #ifndef ASIO_RANDOM_ACCESS_FILE_HPP #define ASIO_RANDOM_ACCESS_FILE_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #if defined(ASIO_HAS_FILE) \ || defined(GENERATING_DOCUMENTATION) #include "asio/basic_random_access_file.hpp" namespace asio { /// Typedef for the typical usage of a random-access file. typedef basic_random_access_file<> random_access_file; } // namespace asio #endif // defined(ASIO_HAS_FILE) // || defined(GENERATING_DOCUMENTATION) #endif // ASIO_RANDOM_ACCESS_FILE_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/require.hpp
// // require.hpp // ~~~~~~~~~~~ // // 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) // #ifndef ASIO_REQUIRE_HPP #define ASIO_REQUIRE_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include "asio/detail/type_traits.hpp" #include "asio/is_applicable_property.hpp" #include "asio/traits/require_member.hpp" #include "asio/traits/require_free.hpp" #include "asio/traits/static_require.hpp" #include "asio/detail/push_options.hpp" #if defined(GENERATING_DOCUMENTATION) namespace asio { /// A customisation point that applies a concept-preserving property to an /// object. /** * The name <tt>require</tt> denotes a customisation point object. The * expression <tt>asio::require(E, P0, Pn...)</tt> for some * subexpressions <tt>E</tt> and <tt>P0</tt>, and where <tt>Pn...</tt> * represents <tt>N</tt> subexpressions (where <tt>N</tt> is 0 or more, and with * types <tt>T = decay_t<decltype(E)></tt> and <tt>Prop0 = * decay_t<decltype(P0)></tt>) is expression-equivalent to: * * @li If <tt>is_applicable_property_v<T, Prop0> && Prop0::is_requirable</tt> is * not a well-formed constant expression with value <tt>true</tt>, * <tt>asio::require(E, P0, Pn...)</tt> is ill-formed. * * @li Otherwise, <tt>E</tt> if <tt>N == 0</tt> and the expression * <tt>Prop0::template static_query_v<T> == Prop0::value()</tt> is a * well-formed constant expression with value <tt>true</tt>. * * @li Otherwise, <tt>(E).require(P0)</tt> if <tt>N == 0</tt> and the expression * <tt>(E).require(P0)</tt> is a valid expression. * * @li Otherwise, <tt>require(E, P0)</tt> if <tt>N == 0</tt> and the expression * <tt>require(E, P0)</tt> is a valid expression with overload resolution * performed in a context that does not include the declaration of the * <tt>require</tt> customization point object. * * @li Otherwise, * <tt>asio::require(asio::require(E, P0), Pn...)</tt> * if <tt>N > 0</tt> and the expression * <tt>asio::require(asio::require(E, P0), Pn...)</tt> * is a valid expression. * * @li Otherwise, <tt>asio::require(E, P0, Pn...)</tt> is ill-formed. */ inline constexpr unspecified require = unspecified; /// A type trait that determines whether a @c require expression is well-formed. /** * Class template @c can_require is a trait that is derived from * @c true_type if the expression <tt>asio::require(std::declval<T>(), * std::declval<Properties>()...)</tt> is well formed; otherwise @c false_type. */ template <typename T, typename... Properties> struct can_require : integral_constant<bool, automatically_determined> { }; /// A type trait that determines whether a @c require expression will not throw. /** * Class template @c is_nothrow_require is a trait that is derived from * @c true_type if the expression <tt>asio::require(std::declval<T>(), * std::declval<Properties>()...)</tt> is @c noexcept; otherwise @c false_type. */ template <typename T, typename... Properties> struct is_nothrow_require : integral_constant<bool, automatically_determined> { }; /// A type trait that determines the result type of a @c require expression. /** * Class template @c require_result is a trait that determines the result * type of the expression <tt>asio::require(std::declval<T>(), * std::declval<Properties>()...)</tt>. */ template <typename T, typename... Properties> struct require_result { /// The result of the @c require expression. typedef automatically_determined type; }; } // namespace asio #else // defined(GENERATING_DOCUMENTATION) namespace asio_require_fn { using asio::conditional_t; using asio::decay_t; using asio::declval; using asio::enable_if_t; using asio::is_applicable_property; using asio::traits::require_free; using asio::traits::require_member; using asio::traits::static_require; void require(); enum overload_type { identity, call_member, call_free, two_props, n_props, ill_formed }; template <typename Impl, typename T, typename Properties, typename = void, typename = void, typename = void, typename = void, typename = void> struct call_traits { static constexpr overload_type overload = ill_formed; static constexpr bool is_noexcept = false; typedef void result_type; }; template <typename Impl, typename T, typename Property> struct call_traits<Impl, T, void(Property), enable_if_t< is_applicable_property< decay_t<T>, decay_t<Property> >::value >, enable_if_t< decay_t<Property>::is_requirable >, enable_if_t< static_require<T, Property>::is_valid >> { static constexpr overload_type overload = identity; static constexpr bool is_noexcept = true; typedef T&& result_type; }; template <typename Impl, typename T, typename Property> struct call_traits<Impl, T, void(Property), enable_if_t< is_applicable_property< decay_t<T>, decay_t<Property> >::value >, enable_if_t< decay_t<Property>::is_requirable >, enable_if_t< !static_require<T, Property>::is_valid >, enable_if_t< require_member<typename Impl::template proxy<T>::type, Property>::is_valid >> : require_member<typename Impl::template proxy<T>::type, Property> { static constexpr overload_type overload = call_member; }; template <typename Impl, typename T, typename Property> struct call_traits<Impl, T, void(Property), enable_if_t< is_applicable_property< decay_t<T>, decay_t<Property> >::value >, enable_if_t< decay_t<Property>::is_requirable >, enable_if_t< !static_require<T, Property>::is_valid >, enable_if_t< !require_member<typename Impl::template proxy<T>::type, Property>::is_valid >, enable_if_t< require_free<T, Property>::is_valid >> : require_free<T, Property> { static constexpr overload_type overload = call_free; }; template <typename Impl, typename T, typename P0, typename P1> struct call_traits<Impl, T, void(P0, P1), enable_if_t< call_traits<Impl, T, void(P0)>::overload != ill_formed >, enable_if_t< call_traits< Impl, typename call_traits<Impl, T, void(P0)>::result_type, void(P1) >::overload != ill_formed >> { static constexpr overload_type overload = two_props; static constexpr bool is_noexcept = ( call_traits<Impl, T, void(P0)>::is_noexcept && call_traits< Impl, typename call_traits<Impl, T, void(P0)>::result_type, void(P1) >::is_noexcept ); typedef decay_t< typename call_traits< Impl, typename call_traits<Impl, T, void(P0)>::result_type, void(P1) >::result_type > result_type; }; template <typename Impl, typename T, typename P0, typename P1, typename... PN> struct call_traits<Impl, T, void(P0, P1, PN...), enable_if_t< call_traits<Impl, T, void(P0)>::overload != ill_formed >, enable_if_t< call_traits< Impl, typename call_traits<Impl, T, void(P0)>::result_type, void(P1, PN...) >::overload != ill_formed >> { static constexpr overload_type overload = n_props; static constexpr bool is_noexcept = ( call_traits<Impl, T, void(P0)>::is_noexcept && call_traits< Impl, typename call_traits<Impl, T, void(P0)>::result_type, void(P1, PN...) >::is_noexcept ); typedef decay_t< typename call_traits< Impl, typename call_traits<Impl, T, void(P0)>::result_type, void(P1, PN...) >::result_type > result_type; }; struct impl { template <typename T> struct proxy { #if defined(ASIO_HAS_DEDUCED_REQUIRE_MEMBER_TRAIT) struct type { template <typename P> auto require(P&& p) noexcept( noexcept( declval<conditional_t<true, T, P>>().require(static_cast<P&&>(p)) ) ) -> decltype( declval<conditional_t<true, T, P>>().require(static_cast<P&&>(p)) ); }; #else // defined(ASIO_HAS_DEDUCED_REQUIRE_MEMBER_TRAIT) typedef T type; #endif // defined(ASIO_HAS_DEDUCED_REQUIRE_MEMBER_TRAIT) }; template <typename T, typename Property> ASIO_NODISCARD constexpr enable_if_t< call_traits<impl, T, void(Property)>::overload == identity, typename call_traits<impl, T, void(Property)>::result_type > operator()(T&& t, Property&&) const noexcept(call_traits<impl, T, void(Property)>::is_noexcept) { return static_cast<T&&>(t); } template <typename T, typename Property> ASIO_NODISCARD constexpr enable_if_t< call_traits<impl, T, void(Property)>::overload == call_member, typename call_traits<impl, T, void(Property)>::result_type > operator()(T&& t, Property&& p) const noexcept(call_traits<impl, T, void(Property)>::is_noexcept) { return static_cast<T&&>(t).require(static_cast<Property&&>(p)); } template <typename T, typename Property> ASIO_NODISCARD constexpr enable_if_t< call_traits<impl, T, void(Property)>::overload == call_free, typename call_traits<impl, T, void(Property)>::result_type > operator()(T&& t, Property&& p) const noexcept(call_traits<impl, T, void(Property)>::is_noexcept) { return require(static_cast<T&&>(t), static_cast<Property&&>(p)); } template <typename T, typename P0, typename P1> ASIO_NODISCARD constexpr enable_if_t< call_traits<impl, T, void(P0, P1)>::overload == two_props, typename call_traits<impl, T, void(P0, P1)>::result_type > operator()(T&& t, P0&& p0, P1&& p1) const noexcept(call_traits<impl, T, void(P0, P1)>::is_noexcept) { return (*this)( (*this)(static_cast<T&&>(t), static_cast<P0&&>(p0)), static_cast<P1&&>(p1)); } template <typename T, typename P0, typename P1, typename... PN> ASIO_NODISCARD constexpr enable_if_t< call_traits<impl, T, void(P0, P1, PN...)>::overload == n_props, typename call_traits<impl, T, void(P0, P1, PN...)>::result_type > operator()(T&& t, P0&& p0, P1&& p1, PN&&... pn) const noexcept(call_traits<impl, T, void(P0, P1, PN...)>::is_noexcept) { return (*this)( (*this)(static_cast<T&&>(t), static_cast<P0&&>(p0)), static_cast<P1&&>(p1), static_cast<PN&&>(pn)...); } }; template <typename T = impl> struct static_instance { static const T instance; }; template <typename T> const T static_instance<T>::instance = {}; } // namespace asio_require_fn namespace asio { namespace { static constexpr const asio_require_fn::impl& require = asio_require_fn::static_instance<>::instance; } // namespace typedef asio_require_fn::impl require_t; template <typename T, typename... Properties> struct can_require : integral_constant<bool, asio_require_fn::call_traits< require_t, T, void(Properties...)>::overload != asio_require_fn::ill_formed> { }; #if defined(ASIO_HAS_VARIABLE_TEMPLATES) template <typename T, typename... Properties> constexpr bool can_require_v = can_require<T, Properties...>::value; #endif // defined(ASIO_HAS_VARIABLE_TEMPLATES) template <typename T, typename... Properties> struct is_nothrow_require : integral_constant<bool, asio_require_fn::call_traits< require_t, T, void(Properties...)>::is_noexcept> { }; #if defined(ASIO_HAS_VARIABLE_TEMPLATES) template <typename T, typename... Properties> constexpr bool is_nothrow_require_v = is_nothrow_require<T, Properties...>::value; #endif // defined(ASIO_HAS_VARIABLE_TEMPLATES) template <typename T, typename... Properties> struct require_result { typedef typename asio_require_fn::call_traits< require_t, T, void(Properties...)>::result_type type; }; template <typename T, typename... Properties> using require_result_t = typename require_result<T, Properties...>::type; } // namespace asio #endif // defined(GENERATING_DOCUMENTATION) #include "asio/detail/pop_options.hpp" #endif // ASIO_REQUIRE_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/co_spawn.hpp
// // co_spawn.hpp // ~~~~~~~~~~~~ // // 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) // #ifndef ASIO_CO_SPAWN_HPP #define ASIO_CO_SPAWN_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #if defined(ASIO_HAS_CO_AWAIT) || defined(GENERATING_DOCUMENTATION) #include "asio/awaitable.hpp" #include "asio/execution/executor.hpp" #include "asio/execution_context.hpp" #include "asio/is_executor.hpp" #include "asio/detail/push_options.hpp" namespace asio { namespace detail { template <typename T> struct awaitable_signature; template <typename T, typename Executor> struct awaitable_signature<awaitable<T, Executor>> { typedef void type(std::exception_ptr, T); }; template <typename Executor> struct awaitable_signature<awaitable<void, Executor>> { typedef void type(std::exception_ptr); }; } // namespace detail /// Spawn a new coroutined-based thread of execution. /** * @param ex The executor that will be used to schedule the new thread of * execution. * * @param a The asio::awaitable object that is the result of calling the * coroutine's entry point function. * * @param token The @ref completion_token that will handle the notification that * the thread of execution has completed. The function signature of the * completion handler must be: * @code void handler(std::exception_ptr, T); @endcode * * @par Completion Signature * @code void(std::exception_ptr, T) @endcode * * @par Example * @code * asio::awaitable<std::size_t> echo(tcp::socket socket) * { * std::size_t bytes_transferred = 0; * * try * { * char data[1024]; * for (;;) * { * std::size_t n = co_await socket.async_read_some( * asio::buffer(data), asio::use_awaitable); * * co_await asio::async_write(socket, * asio::buffer(data, n), asio::use_awaitable); * * bytes_transferred += n; * } * } * catch (const std::exception&) * { * } * * co_return bytes_transferred; * } * * // ... * * asio::co_spawn(my_executor, * echo(std::move(my_tcp_socket)), * [](std::exception_ptr e, std::size_t n) * { * std::cout << "transferred " << n << "\n"; * }); * @endcode * * @par Per-Operation Cancellation * The new thread of execution is created with a cancellation state that * supports @c cancellation_type::terminal values only. To change the * cancellation state, call asio::this_coro::reset_cancellation_state. */ template <typename Executor, typename T, typename AwaitableExecutor, ASIO_COMPLETION_TOKEN_FOR( void(std::exception_ptr, T)) CompletionToken ASIO_DEFAULT_COMPLETION_TOKEN_TYPE(Executor)> inline ASIO_INITFN_AUTO_RESULT_TYPE( CompletionToken, void(std::exception_ptr, T)) co_spawn(const Executor& ex, awaitable<T, AwaitableExecutor> a, CompletionToken&& token ASIO_DEFAULT_COMPLETION_TOKEN(Executor), constraint_t< (is_executor<Executor>::value || execution::is_executor<Executor>::value) && is_convertible<Executor, AwaitableExecutor>::value > = 0); /// Spawn a new coroutined-based thread of execution. /** * @param ex The executor that will be used to schedule the new thread of * execution. * * @param a The asio::awaitable object that is the result of calling the * coroutine's entry point function. * * @param token The @ref completion_token that will handle the notification that * the thread of execution has completed. The function signature of the * completion handler must be: * @code void handler(std::exception_ptr); @endcode * * @par Completion Signature * @code void(std::exception_ptr) @endcode * * @par Example * @code * asio::awaitable<void> echo(tcp::socket socket) * { * try * { * char data[1024]; * for (;;) * { * std::size_t n = co_await socket.async_read_some( * asio::buffer(data), asio::use_awaitable); * * co_await asio::async_write(socket, * asio::buffer(data, n), asio::use_awaitable); * } * } * catch (const std::exception& e) * { * std::cerr << "Exception: " << e.what() << "\n"; * } * } * * // ... * * asio::co_spawn(my_executor, * echo(std::move(my_tcp_socket)), * asio::detached); * @endcode * * @par Per-Operation Cancellation * The new thread of execution is created with a cancellation state that * supports @c cancellation_type::terminal values only. To change the * cancellation state, call asio::this_coro::reset_cancellation_state. */ template <typename Executor, typename AwaitableExecutor, ASIO_COMPLETION_TOKEN_FOR( void(std::exception_ptr)) CompletionToken ASIO_DEFAULT_COMPLETION_TOKEN_TYPE(Executor)> inline ASIO_INITFN_AUTO_RESULT_TYPE( CompletionToken, void(std::exception_ptr)) co_spawn(const Executor& ex, awaitable<void, AwaitableExecutor> a, CompletionToken&& token ASIO_DEFAULT_COMPLETION_TOKEN(Executor), constraint_t< (is_executor<Executor>::value || execution::is_executor<Executor>::value) && is_convertible<Executor, AwaitableExecutor>::value > = 0); /// Spawn a new coroutined-based thread of execution. /** * @param ctx An execution context that will provide the executor to be used to * schedule the new thread of execution. * * @param a The asio::awaitable object that is the result of calling the * coroutine's entry point function. * * @param token The @ref completion_token that will handle the notification that * the thread of execution has completed. The function signature of the * completion handler must be: * @code void handler(std::exception_ptr); @endcode * * @par Completion Signature * @code void(std::exception_ptr, T) @endcode * * @par Example * @code * asio::awaitable<std::size_t> echo(tcp::socket socket) * { * std::size_t bytes_transferred = 0; * * try * { * char data[1024]; * for (;;) * { * std::size_t n = co_await socket.async_read_some( * asio::buffer(data), asio::use_awaitable); * * co_await asio::async_write(socket, * asio::buffer(data, n), asio::use_awaitable); * * bytes_transferred += n; * } * } * catch (const std::exception&) * { * } * * co_return bytes_transferred; * } * * // ... * * asio::co_spawn(my_io_context, * echo(std::move(my_tcp_socket)), * [](std::exception_ptr e, std::size_t n) * { * std::cout << "transferred " << n << "\n"; * }); * @endcode * * @par Per-Operation Cancellation * The new thread of execution is created with a cancellation state that * supports @c cancellation_type::terminal values only. To change the * cancellation state, call asio::this_coro::reset_cancellation_state. */ template <typename ExecutionContext, typename T, typename AwaitableExecutor, ASIO_COMPLETION_TOKEN_FOR( void(std::exception_ptr, T)) CompletionToken ASIO_DEFAULT_COMPLETION_TOKEN_TYPE( typename ExecutionContext::executor_type)> inline ASIO_INITFN_AUTO_RESULT_TYPE( CompletionToken, void(std::exception_ptr, T)) co_spawn(ExecutionContext& ctx, awaitable<T, AwaitableExecutor> a, CompletionToken&& token ASIO_DEFAULT_COMPLETION_TOKEN( typename ExecutionContext::executor_type), constraint_t< is_convertible<ExecutionContext&, execution_context&>::value && is_convertible<typename ExecutionContext::executor_type, AwaitableExecutor>::value > = 0); /// Spawn a new coroutined-based thread of execution. /** * @param ctx An execution context that will provide the executor to be used to * schedule the new thread of execution. * * @param a The asio::awaitable object that is the result of calling the * coroutine's entry point function. * * @param token The @ref completion_token that will handle the notification that * the thread of execution has completed. The function signature of the * completion handler must be: * @code void handler(std::exception_ptr); @endcode * * @par Completion Signature * @code void(std::exception_ptr) @endcode * * @par Example * @code * asio::awaitable<void> echo(tcp::socket socket) * { * try * { * char data[1024]; * for (;;) * { * std::size_t n = co_await socket.async_read_some( * asio::buffer(data), asio::use_awaitable); * * co_await asio::async_write(socket, * asio::buffer(data, n), asio::use_awaitable); * } * } * catch (const std::exception& e) * { * std::cerr << "Exception: " << e.what() << "\n"; * } * } * * // ... * * asio::co_spawn(my_io_context, * echo(std::move(my_tcp_socket)), * asio::detached); * @endcode * * @par Per-Operation Cancellation * The new thread of execution is created with a cancellation state that * supports @c cancellation_type::terminal values only. To change the * cancellation state, call asio::this_coro::reset_cancellation_state. */ template <typename ExecutionContext, typename AwaitableExecutor, ASIO_COMPLETION_TOKEN_FOR( void(std::exception_ptr)) CompletionToken ASIO_DEFAULT_COMPLETION_TOKEN_TYPE( typename ExecutionContext::executor_type)> inline ASIO_INITFN_AUTO_RESULT_TYPE( CompletionToken, void(std::exception_ptr)) co_spawn(ExecutionContext& ctx, awaitable<void, AwaitableExecutor> a, CompletionToken&& token ASIO_DEFAULT_COMPLETION_TOKEN( typename ExecutionContext::executor_type), constraint_t< is_convertible<ExecutionContext&, execution_context&>::value && is_convertible<typename ExecutionContext::executor_type, AwaitableExecutor>::value > = 0); /// Spawn a new coroutined-based thread of execution. /** * @param ex The executor that will be used to schedule the new thread of * execution. * * @param f A nullary function object with a return type of the form * @c asio::awaitable<R,E> that will be used as the coroutine's entry * point. * * @param token The @ref completion_token that will handle the notification * that the thread of execution has completed. If @c R is @c void, the function * signature of the completion handler must be: * * @code void handler(std::exception_ptr); @endcode * Otherwise, the function signature of the completion handler must be: * @code void handler(std::exception_ptr, R); @endcode * * @par Completion Signature * @code void(std::exception_ptr, R) @endcode * where @c R is the first template argument to the @c awaitable returned by the * supplied function object @c F: * @code asio::awaitable<R, AwaitableExecutor> F() @endcode * * @par Example * @code * asio::awaitable<std::size_t> echo(tcp::socket socket) * { * std::size_t bytes_transferred = 0; * * try * { * char data[1024]; * for (;;) * { * std::size_t n = co_await socket.async_read_some( * asio::buffer(data), asio::use_awaitable); * * co_await asio::async_write(socket, * asio::buffer(data, n), asio::use_awaitable); * * bytes_transferred += n; * } * } * catch (const std::exception&) * { * } * * co_return bytes_transferred; * } * * // ... * * asio::co_spawn(my_executor, * [socket = std::move(my_tcp_socket)]() mutable * -> asio::awaitable<void> * { * try * { * char data[1024]; * for (;;) * { * std::size_t n = co_await socket.async_read_some( * asio::buffer(data), asio::use_awaitable); * * co_await asio::async_write(socket, * asio::buffer(data, n), asio::use_awaitable); * } * } * catch (const std::exception& e) * { * std::cerr << "Exception: " << e.what() << "\n"; * } * }, asio::detached); * @endcode * * @par Per-Operation Cancellation * The new thread of execution is created with a cancellation state that * supports @c cancellation_type::terminal values only. To change the * cancellation state, call asio::this_coro::reset_cancellation_state. */ template <typename Executor, typename F, ASIO_COMPLETION_TOKEN_FOR(typename detail::awaitable_signature< result_of_t<F()>>::type) CompletionToken ASIO_DEFAULT_COMPLETION_TOKEN_TYPE(Executor)> ASIO_INITFN_AUTO_RESULT_TYPE(CompletionToken, typename detail::awaitable_signature<result_of_t<F()>>::type) co_spawn(const Executor& ex, F&& f, CompletionToken&& token ASIO_DEFAULT_COMPLETION_TOKEN(Executor), constraint_t< is_executor<Executor>::value || execution::is_executor<Executor>::value > = 0); /// Spawn a new coroutined-based thread of execution. /** * @param ctx An execution context that will provide the executor to be used to * schedule the new thread of execution. * * @param f A nullary function object with a return type of the form * @c asio::awaitable<R,E> that will be used as the coroutine's entry * point. * * @param token The @ref completion_token that will handle the notification * that the thread of execution has completed. If @c R is @c void, the function * signature of the completion handler must be: * * @code void handler(std::exception_ptr); @endcode * Otherwise, the function signature of the completion handler must be: * @code void handler(std::exception_ptr, R); @endcode * * @par Completion Signature * @code void(std::exception_ptr, R) @endcode * where @c R is the first template argument to the @c awaitable returned by the * supplied function object @c F: * @code asio::awaitable<R, AwaitableExecutor> F() @endcode * * @par Example * @code * asio::awaitable<std::size_t> echo(tcp::socket socket) * { * std::size_t bytes_transferred = 0; * * try * { * char data[1024]; * for (;;) * { * std::size_t n = co_await socket.async_read_some( * asio::buffer(data), asio::use_awaitable); * * co_await asio::async_write(socket, * asio::buffer(data, n), asio::use_awaitable); * * bytes_transferred += n; * } * } * catch (const std::exception&) * { * } * * co_return bytes_transferred; * } * * // ... * * asio::co_spawn(my_io_context, * [socket = std::move(my_tcp_socket)]() mutable * -> asio::awaitable<void> * { * try * { * char data[1024]; * for (;;) * { * std::size_t n = co_await socket.async_read_some( * asio::buffer(data), asio::use_awaitable); * * co_await asio::async_write(socket, * asio::buffer(data, n), asio::use_awaitable); * } * } * catch (const std::exception& e) * { * std::cerr << "Exception: " << e.what() << "\n"; * } * }, asio::detached); * @endcode * * @par Per-Operation Cancellation * The new thread of execution is created with a cancellation state that * supports @c cancellation_type::terminal values only. To change the * cancellation state, call asio::this_coro::reset_cancellation_state. */ template <typename ExecutionContext, typename F, ASIO_COMPLETION_TOKEN_FOR(typename detail::awaitable_signature< result_of_t<F()>>::type) CompletionToken ASIO_DEFAULT_COMPLETION_TOKEN_TYPE( typename ExecutionContext::executor_type)> ASIO_INITFN_AUTO_RESULT_TYPE(CompletionToken, typename detail::awaitable_signature<result_of_t<F()>>::type) co_spawn(ExecutionContext& ctx, F&& f, CompletionToken&& token ASIO_DEFAULT_COMPLETION_TOKEN( typename ExecutionContext::executor_type), constraint_t< is_convertible<ExecutionContext&, execution_context&>::value > = 0); } // namespace asio #include "asio/detail/pop_options.hpp" #include "asio/impl/co_spawn.hpp" #endif // defined(ASIO_HAS_CO_AWAIT) || defined(GENERATING_DOCUMENTATION) #endif // ASIO_CO_SPAWN_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/packaged_task.hpp
// // packaged_task.hpp // ~~~~~~~~~~~~~~~~~ // // 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) // #ifndef ASIO_PACKAGED_TASK_HPP #define ASIO_PACKAGED_TASK_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include "asio/detail/future.hpp" #if defined(ASIO_HAS_STD_FUTURE_CLASS) \ || defined(GENERATING_DOCUMENTATION) #include "asio/async_result.hpp" #include "asio/detail/type_traits.hpp" #include "asio/detail/push_options.hpp" namespace asio { /// Partial specialisation of @c async_result for @c std::packaged_task. template <typename Result, typename... Args, typename Signature> class async_result<std::packaged_task<Result(Args...)>, Signature> { public: /// The packaged task is the concrete completion handler type. typedef std::packaged_task<Result(Args...)> completion_handler_type; /// The return type of the initiating function is the future obtained from /// the packaged task. typedef std::future<Result> return_type; /// The constructor extracts the future from the packaged task. explicit async_result(completion_handler_type& h) : future_(h.get_future()) { } /// Returns the packaged task's future. return_type get() { return std::move(future_); } private: return_type future_; }; } // namespace asio #include "asio/detail/pop_options.hpp" #endif // defined(ASIO_HAS_STD_FUTURE_CLASS) // || defined(GENERATING_DOCUMENTATION) #endif // ASIO_PACKAGED_TASK_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/bind_cancellation_slot.hpp
// // bind_cancellation_slot.hpp // ~~~~~~~~~~~~~~~~~~~~~~~~~~ // // 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) // #ifndef ASIO_BIND_CANCELLATION_SLOT_HPP #define ASIO_BIND_CANCELLATION_SLOT_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include "asio/associated_cancellation_slot.hpp" #include "asio/associated_executor.hpp" #include "asio/associator.hpp" #include "asio/async_result.hpp" #include "asio/detail/initiation_base.hpp" #include "asio/detail/type_traits.hpp" #include "asio/detail/push_options.hpp" namespace asio { namespace detail { // Helper to automatically define nested typedef result_type. template <typename T, typename = void> struct cancellation_slot_binder_result_type { protected: typedef void result_type_or_void; }; template <typename T> struct cancellation_slot_binder_result_type<T, void_t<typename T::result_type>> { typedef typename T::result_type result_type; protected: typedef result_type result_type_or_void; }; template <typename R> struct cancellation_slot_binder_result_type<R(*)()> { typedef R result_type; protected: typedef result_type result_type_or_void; }; template <typename R> struct cancellation_slot_binder_result_type<R(&)()> { typedef R result_type; protected: typedef result_type result_type_or_void; }; template <typename R, typename A1> struct cancellation_slot_binder_result_type<R(*)(A1)> { typedef R result_type; protected: typedef result_type result_type_or_void; }; template <typename R, typename A1> struct cancellation_slot_binder_result_type<R(&)(A1)> { typedef R result_type; protected: typedef result_type result_type_or_void; }; template <typename R, typename A1, typename A2> struct cancellation_slot_binder_result_type<R(*)(A1, A2)> { typedef R result_type; protected: typedef result_type result_type_or_void; }; template <typename R, typename A1, typename A2> struct cancellation_slot_binder_result_type<R(&)(A1, A2)> { typedef R result_type; protected: typedef result_type result_type_or_void; }; // Helper to automatically define nested typedef argument_type. template <typename T, typename = void> struct cancellation_slot_binder_argument_type {}; template <typename T> struct cancellation_slot_binder_argument_type<T, void_t<typename T::argument_type>> { typedef typename T::argument_type argument_type; }; template <typename R, typename A1> struct cancellation_slot_binder_argument_type<R(*)(A1)> { typedef A1 argument_type; }; template <typename R, typename A1> struct cancellation_slot_binder_argument_type<R(&)(A1)> { typedef A1 argument_type; }; // Helper to automatically define nested typedefs first_argument_type and // second_argument_type. template <typename T, typename = void> struct cancellation_slot_binder_argument_types {}; template <typename T> struct cancellation_slot_binder_argument_types<T, void_t<typename T::first_argument_type>> { typedef typename T::first_argument_type first_argument_type; typedef typename T::second_argument_type second_argument_type; }; template <typename R, typename A1, typename A2> struct cancellation_slot_binder_argument_type<R(*)(A1, A2)> { typedef A1 first_argument_type; typedef A2 second_argument_type; }; template <typename R, typename A1, typename A2> struct cancellation_slot_binder_argument_type<R(&)(A1, A2)> { typedef A1 first_argument_type; typedef A2 second_argument_type; }; } // namespace detail /// A call wrapper type to bind a cancellation slot of type @c CancellationSlot /// to an object of type @c T. template <typename T, typename CancellationSlot> class cancellation_slot_binder #if !defined(GENERATING_DOCUMENTATION) : public detail::cancellation_slot_binder_result_type<T>, public detail::cancellation_slot_binder_argument_type<T>, public detail::cancellation_slot_binder_argument_types<T> #endif // !defined(GENERATING_DOCUMENTATION) { public: /// The type of the target object. typedef T target_type; /// The type of the associated cancellation slot. typedef CancellationSlot cancellation_slot_type; #if defined(GENERATING_DOCUMENTATION) /// The return type if a function. /** * The type of @c result_type is based on the type @c T of the wrapper's * target object: * * @li if @c T is a pointer to function type, @c result_type is a synonym for * the return type of @c T; * * @li if @c T is a class type with a member type @c result_type, then @c * result_type is a synonym for @c T::result_type; * * @li otherwise @c result_type is not defined. */ typedef see_below result_type; /// The type of the function's argument. /** * The type of @c argument_type is based on the type @c T of the wrapper's * target object: * * @li if @c T is a pointer to a function type accepting a single argument, * @c argument_type is a synonym for the return type of @c T; * * @li if @c T is a class type with a member type @c argument_type, then @c * argument_type is a synonym for @c T::argument_type; * * @li otherwise @c argument_type is not defined. */ typedef see_below argument_type; /// The type of the function's first argument. /** * The type of @c first_argument_type is based on the type @c T of the * wrapper's target object: * * @li if @c T is a pointer to a function type accepting two arguments, @c * first_argument_type is a synonym for the return type of @c T; * * @li if @c T is a class type with a member type @c first_argument_type, * then @c first_argument_type is a synonym for @c T::first_argument_type; * * @li otherwise @c first_argument_type is not defined. */ typedef see_below first_argument_type; /// The type of the function's second argument. /** * The type of @c second_argument_type is based on the type @c T of the * wrapper's target object: * * @li if @c T is a pointer to a function type accepting two arguments, @c * second_argument_type is a synonym for the return type of @c T; * * @li if @c T is a class type with a member type @c first_argument_type, * then @c second_argument_type is a synonym for @c T::second_argument_type; * * @li otherwise @c second_argument_type is not defined. */ typedef see_below second_argument_type; #endif // defined(GENERATING_DOCUMENTATION) /// Construct a cancellation slot wrapper for the specified object. /** * This constructor is only valid if the type @c T is constructible from type * @c U. */ template <typename U> cancellation_slot_binder(const cancellation_slot_type& s, U&& u) : slot_(s), target_(static_cast<U&&>(u)) { } /// Copy constructor. cancellation_slot_binder(const cancellation_slot_binder& other) : slot_(other.get_cancellation_slot()), target_(other.get()) { } /// Construct a copy, but specify a different cancellation slot. cancellation_slot_binder(const cancellation_slot_type& s, const cancellation_slot_binder& other) : slot_(s), target_(other.get()) { } /// Construct a copy of a different cancellation slot wrapper type. /** * This constructor is only valid if the @c CancellationSlot type is * constructible from type @c OtherCancellationSlot, and the type @c T is * constructible from type @c U. */ template <typename U, typename OtherCancellationSlot> cancellation_slot_binder( const cancellation_slot_binder<U, OtherCancellationSlot>& other, constraint_t<is_constructible<CancellationSlot, OtherCancellationSlot>::value> = 0, constraint_t<is_constructible<T, U>::value> = 0) : slot_(other.get_cancellation_slot()), target_(other.get()) { } /// Construct a copy of a different cancellation slot wrapper type, but /// specify a different cancellation slot. /** * This constructor is only valid if the type @c T is constructible from type * @c U. */ template <typename U, typename OtherCancellationSlot> cancellation_slot_binder(const cancellation_slot_type& s, const cancellation_slot_binder<U, OtherCancellationSlot>& other, constraint_t<is_constructible<T, U>::value> = 0) : slot_(s), target_(other.get()) { } /// Move constructor. cancellation_slot_binder(cancellation_slot_binder&& other) : slot_(static_cast<cancellation_slot_type&&>( other.get_cancellation_slot())), target_(static_cast<T&&>(other.get())) { } /// Move construct the target object, but specify a different cancellation /// slot. cancellation_slot_binder(const cancellation_slot_type& s, cancellation_slot_binder&& other) : slot_(s), target_(static_cast<T&&>(other.get())) { } /// Move construct from a different cancellation slot wrapper type. template <typename U, typename OtherCancellationSlot> cancellation_slot_binder( cancellation_slot_binder<U, OtherCancellationSlot>&& other, constraint_t<is_constructible<CancellationSlot, OtherCancellationSlot>::value> = 0, constraint_t<is_constructible<T, U>::value> = 0) : slot_(static_cast<OtherCancellationSlot&&>( other.get_cancellation_slot())), target_(static_cast<U&&>(other.get())) { } /// Move construct from a different cancellation slot wrapper type, but /// specify a different cancellation slot. template <typename U, typename OtherCancellationSlot> cancellation_slot_binder(const cancellation_slot_type& s, cancellation_slot_binder<U, OtherCancellationSlot>&& other, constraint_t<is_constructible<T, U>::value> = 0) : slot_(s), target_(static_cast<U&&>(other.get())) { } /// Destructor. ~cancellation_slot_binder() { } /// Obtain a reference to the target object. target_type& get() noexcept { return target_; } /// Obtain a reference to the target object. const target_type& get() const noexcept { return target_; } /// Obtain the associated cancellation slot. cancellation_slot_type get_cancellation_slot() const noexcept { return slot_; } /// Forwarding function call operator. template <typename... Args> result_of_t<T(Args...)> operator()(Args&&... args) { return target_(static_cast<Args&&>(args)...); } /// Forwarding function call operator. template <typename... Args> result_of_t<T(Args...)> operator()(Args&&... args) const { return target_(static_cast<Args&&>(args)...); } private: CancellationSlot slot_; T target_; }; /// A function object type that adapts a @ref completion_token to specify that /// the completion handler should have the supplied cancellation slot as its /// associated cancellation slot. /** * May also be used directly as a completion token, in which case it adapts the * asynchronous operation's default completion token (or asio::deferred * if no default is available). */ template <typename CancellationSlot> struct partial_cancellation_slot_binder { /// Constructor that specifies associated cancellation slot. explicit partial_cancellation_slot_binder(const CancellationSlot& ex) : cancellation_slot_(ex) { } /// Adapt a @ref completion_token to specify that the completion handler /// should have the cancellation slot as its associated cancellation slot. template <typename CompletionToken> ASIO_NODISCARD inline constexpr cancellation_slot_binder<decay_t<CompletionToken>, CancellationSlot> operator()(CompletionToken&& completion_token) const { return cancellation_slot_binder<decay_t<CompletionToken>, CancellationSlot>( static_cast<CompletionToken&&>(completion_token), cancellation_slot_); } //private: CancellationSlot cancellation_slot_; }; /// Create a partial completion token that associates a cancellation slot. template <typename CancellationSlot> ASIO_NODISCARD inline partial_cancellation_slot_binder<CancellationSlot> bind_cancellation_slot(const CancellationSlot& ex) { return partial_cancellation_slot_binder<CancellationSlot>(ex); } /// Associate an object of type @c T with a cancellation slot of type /// @c CancellationSlot. template <typename CancellationSlot, typename T> ASIO_NODISCARD inline cancellation_slot_binder<decay_t<T>, CancellationSlot> bind_cancellation_slot(const CancellationSlot& s, T&& t) { return cancellation_slot_binder<decay_t<T>, CancellationSlot>( s, static_cast<T&&>(t)); } #if !defined(GENERATING_DOCUMENTATION) namespace detail { template <typename TargetAsyncResult, typename CancellationSlot, typename = void> class cancellation_slot_binder_completion_handler_async_result { public: template <typename T> explicit cancellation_slot_binder_completion_handler_async_result(T&) { } }; template <typename TargetAsyncResult, typename CancellationSlot> class cancellation_slot_binder_completion_handler_async_result< TargetAsyncResult, CancellationSlot, void_t<typename TargetAsyncResult::completion_handler_type>> { private: TargetAsyncResult target_; public: typedef cancellation_slot_binder< typename TargetAsyncResult::completion_handler_type, CancellationSlot> completion_handler_type; explicit cancellation_slot_binder_completion_handler_async_result( typename TargetAsyncResult::completion_handler_type& handler) : target_(handler) { } auto get() -> decltype(target_.get()) { return target_.get(); } }; template <typename TargetAsyncResult, typename = void> struct cancellation_slot_binder_async_result_return_type { }; template <typename TargetAsyncResult> struct cancellation_slot_binder_async_result_return_type< TargetAsyncResult, void_t<typename TargetAsyncResult::return_type>> { typedef typename TargetAsyncResult::return_type return_type; }; } // namespace detail template <typename T, typename CancellationSlot, typename Signature> class async_result<cancellation_slot_binder<T, CancellationSlot>, Signature> : public detail::cancellation_slot_binder_completion_handler_async_result< async_result<T, Signature>, CancellationSlot>, public detail::cancellation_slot_binder_async_result_return_type< async_result<T, Signature>> { public: explicit async_result(cancellation_slot_binder<T, CancellationSlot>& b) : detail::cancellation_slot_binder_completion_handler_async_result< async_result<T, Signature>, CancellationSlot>(b.get()) { } template <typename Initiation> struct init_wrapper : detail::initiation_base<Initiation> { using detail::initiation_base<Initiation>::initiation_base; template <typename Handler, typename... Args> void operator()(Handler&& handler, const CancellationSlot& slot, Args&&... args) && { static_cast<Initiation&&>(*this)( cancellation_slot_binder<decay_t<Handler>, CancellationSlot>( slot, static_cast<Handler&&>(handler)), static_cast<Args&&>(args)...); } template <typename Handler, typename... Args> void operator()(Handler&& handler, const CancellationSlot& slot, Args&&... args) const & { static_cast<const Initiation&>(*this)( cancellation_slot_binder<decay_t<Handler>, CancellationSlot>( slot, static_cast<Handler&&>(handler)), static_cast<Args&&>(args)...); } }; template <typename Initiation, typename RawCompletionToken, typename... Args> static auto initiate(Initiation&& initiation, RawCompletionToken&& token, Args&&... args) -> decltype( async_initiate< conditional_t< is_const<remove_reference_t<RawCompletionToken>>::value, const T, T>, Signature>( declval<init_wrapper<decay_t<Initiation>>>(), token.get(), token.get_cancellation_slot(), static_cast<Args&&>(args)...)) { return async_initiate< conditional_t< is_const<remove_reference_t<RawCompletionToken>>::value, const T, T>, Signature>( init_wrapper<decay_t<Initiation>>( static_cast<Initiation&&>(initiation)), token.get(), token.get_cancellation_slot(), static_cast<Args&&>(args)...); } private: async_result(const async_result&) = delete; async_result& operator=(const async_result&) = delete; async_result<T, Signature> target_; }; template <typename CancellationSlot, typename... Signatures> struct async_result<partial_cancellation_slot_binder<CancellationSlot>, Signatures...> { template <typename Initiation, typename RawCompletionToken, typename... Args> static auto initiate(Initiation&& initiation, RawCompletionToken&& token, Args&&... args) -> decltype( async_initiate<Signatures...>( static_cast<Initiation&&>(initiation), cancellation_slot_binder< default_completion_token_t<associated_executor_t<Initiation>>, CancellationSlot>(token.cancellation_slot_, default_completion_token_t<associated_executor_t<Initiation>>{}), static_cast<Args&&>(args)...)) { return async_initiate<Signatures...>( static_cast<Initiation&&>(initiation), cancellation_slot_binder< default_completion_token_t<associated_executor_t<Initiation>>, CancellationSlot>(token.cancellation_slot_, default_completion_token_t<associated_executor_t<Initiation>>{}), static_cast<Args&&>(args)...); } }; template <template <typename, typename> class Associator, typename T, typename CancellationSlot, typename DefaultCandidate> struct associator<Associator, cancellation_slot_binder<T, CancellationSlot>, DefaultCandidate> : Associator<T, DefaultCandidate> { static typename Associator<T, DefaultCandidate>::type get( const cancellation_slot_binder<T, CancellationSlot>& b) noexcept { return Associator<T, DefaultCandidate>::get(b.get()); } static auto get(const cancellation_slot_binder<T, CancellationSlot>& b, const DefaultCandidate& c) noexcept -> decltype(Associator<T, DefaultCandidate>::get(b.get(), c)) { return Associator<T, DefaultCandidate>::get(b.get(), c); } }; template <typename T, typename CancellationSlot, typename CancellationSlot1> struct associated_cancellation_slot< cancellation_slot_binder<T, CancellationSlot>, CancellationSlot1> { typedef CancellationSlot type; static auto get(const cancellation_slot_binder<T, CancellationSlot>& b, const CancellationSlot1& = CancellationSlot1()) noexcept -> decltype(b.get_cancellation_slot()) { return b.get_cancellation_slot(); } }; #endif // !defined(GENERATING_DOCUMENTATION) } // namespace asio #include "asio/detail/pop_options.hpp" #endif // ASIO_BIND_CANCELLATION_SLOT_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/associated_executor.hpp
// // associated_executor.hpp // ~~~~~~~~~~~~~~~~~~~~~~~ // // 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) // #ifndef ASIO_ASSOCIATED_EXECUTOR_HPP #define ASIO_ASSOCIATED_EXECUTOR_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include "asio/associator.hpp" #include "asio/detail/functional.hpp" #include "asio/detail/type_traits.hpp" #include "asio/execution/executor.hpp" #include "asio/is_executor.hpp" #include "asio/system_executor.hpp" #include "asio/detail/push_options.hpp" namespace asio { template <typename T, typename Executor> struct associated_executor; namespace detail { template <typename T, typename = void> struct has_executor_type : false_type { }; template <typename T> struct has_executor_type<T, void_t<typename T::executor_type>> : true_type { }; template <typename T, typename E, typename = void, typename = void> struct associated_executor_impl { typedef void asio_associated_executor_is_unspecialised; typedef E type; static type get(const T&) noexcept { return type(); } static const type& get(const T&, const E& e) noexcept { return e; } }; template <typename T, typename E> struct associated_executor_impl<T, E, void_t<typename T::executor_type>> { typedef typename T::executor_type type; static auto get(const T& t) noexcept -> decltype(t.get_executor()) { return t.get_executor(); } static auto get(const T& t, const E&) noexcept -> decltype(t.get_executor()) { return t.get_executor(); } }; template <typename T, typename E> struct associated_executor_impl<T, E, enable_if_t< !has_executor_type<T>::value >, void_t< typename associator<associated_executor, T, E>::type >> : associator<associated_executor, T, E> { }; } // namespace detail /// Traits type used to obtain the executor associated with an object. /** * A program may specialise this traits type if the @c T template parameter in * the specialisation is a user-defined type. The template parameter @c * Executor shall be a type meeting the Executor requirements. * * Specialisations shall meet the following requirements, where @c t is a const * reference to an object of type @c T, and @c e is an object of type @c * Executor. * * @li Provide a nested typedef @c type that identifies a type meeting the * Executor requirements. * * @li Provide a noexcept static member function named @c get, callable as @c * get(t) and with return type @c type or a (possibly const) reference to @c * type. * * @li Provide a noexcept static member function named @c get, callable as @c * get(t,e) and with return type @c type or a (possibly const) reference to @c * type. */ template <typename T, typename Executor = system_executor> struct associated_executor #if !defined(GENERATING_DOCUMENTATION) : detail::associated_executor_impl<T, Executor> #endif // !defined(GENERATING_DOCUMENTATION) { #if defined(GENERATING_DOCUMENTATION) /// If @c T has a nested type @c executor_type, <tt>T::executor_type</tt>. /// Otherwise @c Executor. typedef see_below type; /// If @c T has a nested type @c executor_type, returns /// <tt>t.get_executor()</tt>. Otherwise returns @c type(). static decltype(auto) get(const T& t) noexcept; /// If @c T has a nested type @c executor_type, returns /// <tt>t.get_executor()</tt>. Otherwise returns @c ex. static decltype(auto) get(const T& t, const Executor& ex) noexcept; #endif // defined(GENERATING_DOCUMENTATION) }; /// Helper function to obtain an object's associated executor. /** * @returns <tt>associated_executor<T>::get(t)</tt> */ template <typename T> ASIO_NODISCARD inline typename associated_executor<T>::type get_associated_executor(const T& t) noexcept { return associated_executor<T>::get(t); } /// Helper function to obtain an object's associated executor. /** * @returns <tt>associated_executor<T, Executor>::get(t, ex)</tt> */ template <typename T, typename Executor> ASIO_NODISCARD inline auto get_associated_executor( const T& t, const Executor& ex, constraint_t< is_executor<Executor>::value || execution::is_executor<Executor>::value > = 0) noexcept -> decltype(associated_executor<T, Executor>::get(t, ex)) { return associated_executor<T, Executor>::get(t, ex); } /// Helper function to obtain an object's associated executor. /** * @returns <tt>associated_executor<T, typename * ExecutionContext::executor_type>::get(t, ctx.get_executor())</tt> */ template <typename T, typename ExecutionContext> ASIO_NODISCARD inline typename associated_executor<T, typename ExecutionContext::executor_type>::type get_associated_executor(const T& t, ExecutionContext& ctx, constraint_t<is_convertible<ExecutionContext&, execution_context&>::value> = 0) noexcept { return associated_executor<T, typename ExecutionContext::executor_type>::get(t, ctx.get_executor()); } template <typename T, typename Executor = system_executor> using associated_executor_t = typename associated_executor<T, Executor>::type; namespace detail { template <typename T, typename E, typename = void> struct associated_executor_forwarding_base { }; template <typename T, typename E> struct associated_executor_forwarding_base<T, E, enable_if_t< is_same< typename associated_executor<T, E>::asio_associated_executor_is_unspecialised, void >::value >> { typedef void asio_associated_executor_is_unspecialised; }; } // namespace detail /// Specialisation of associated_executor for @c std::reference_wrapper. template <typename T, typename Executor> struct associated_executor<reference_wrapper<T>, Executor> #if !defined(GENERATING_DOCUMENTATION) : detail::associated_executor_forwarding_base<T, Executor> #endif // !defined(GENERATING_DOCUMENTATION) { /// Forwards @c type to the associator specialisation for the unwrapped type /// @c T. typedef typename associated_executor<T, Executor>::type type; /// Forwards the request to get the executor to the associator specialisation /// for the unwrapped type @c T. static type get(reference_wrapper<T> t) noexcept { return associated_executor<T, Executor>::get(t.get()); } /// Forwards the request to get the executor to the associator specialisation /// for the unwrapped type @c T. static auto get(reference_wrapper<T> t, const Executor& ex) noexcept -> decltype(associated_executor<T, Executor>::get(t.get(), ex)) { return associated_executor<T, Executor>::get(t.get(), ex); } }; } // namespace asio #include "asio/detail/pop_options.hpp" #endif // ASIO_ASSOCIATED_EXECUTOR_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/socket_base.hpp
// // socket_base.hpp // ~~~~~~~~~~~~~~~ // // 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) // #ifndef ASIO_SOCKET_BASE_HPP #define ASIO_SOCKET_BASE_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include "asio/detail/io_control.hpp" #include "asio/detail/socket_option.hpp" #include "asio/detail/socket_types.hpp" #include "asio/detail/push_options.hpp" namespace asio { /// The socket_base class is used as a base for the basic_stream_socket and /// basic_datagram_socket class templates so that we have a common place to /// define the shutdown_type and enum. class socket_base { public: /// Different ways a socket may be shutdown. enum shutdown_type { #if defined(GENERATING_DOCUMENTATION) /// Shutdown the receive side of the socket. shutdown_receive = implementation_defined, /// Shutdown the send side of the socket. shutdown_send = implementation_defined, /// Shutdown both send and receive on the socket. shutdown_both = implementation_defined #else shutdown_receive = ASIO_OS_DEF(SHUT_RD), shutdown_send = ASIO_OS_DEF(SHUT_WR), shutdown_both = ASIO_OS_DEF(SHUT_RDWR) #endif }; /// Bitmask type for flags that can be passed to send and receive operations. typedef int message_flags; #if defined(GENERATING_DOCUMENTATION) /// Peek at incoming data without removing it from the input queue. static const int message_peek = implementation_defined; /// Process out-of-band data. static const int message_out_of_band = implementation_defined; /// Specify that the data should not be subject to routing. static const int message_do_not_route = implementation_defined; /// Specifies that the data marks the end of a record. static const int message_end_of_record = implementation_defined; #else ASIO_STATIC_CONSTANT(int, message_peek = ASIO_OS_DEF(MSG_PEEK)); ASIO_STATIC_CONSTANT(int, message_out_of_band = ASIO_OS_DEF(MSG_OOB)); ASIO_STATIC_CONSTANT(int, message_do_not_route = ASIO_OS_DEF(MSG_DONTROUTE)); ASIO_STATIC_CONSTANT(int, message_end_of_record = ASIO_OS_DEF(MSG_EOR)); #endif /// Wait types. /** * For use with basic_socket::wait() and basic_socket::async_wait(). */ enum wait_type { /// Wait for a socket to become ready to read. wait_read, /// Wait for a socket to become ready to write. wait_write, /// Wait for a socket to have error conditions pending. wait_error }; /// Socket option to permit sending of broadcast messages. /** * Implements the SOL_SOCKET/SO_BROADCAST socket option. * * @par Examples * Setting the option: * @code * asio::ip::udp::socket socket(my_context); * ... * asio::socket_base::broadcast option(true); * socket.set_option(option); * @endcode * * @par * Getting the current option value: * @code * asio::ip::udp::socket socket(my_context); * ... * asio::socket_base::broadcast option; * socket.get_option(option); * bool is_set = option.value(); * @endcode * * @par Concepts: * Socket_Option, Boolean_Socket_Option. */ #if defined(GENERATING_DOCUMENTATION) typedef implementation_defined broadcast; #else typedef asio::detail::socket_option::boolean< ASIO_OS_DEF(SOL_SOCKET), ASIO_OS_DEF(SO_BROADCAST)> broadcast; #endif /// Socket option to enable socket-level debugging. /** * Implements the SOL_SOCKET/SO_DEBUG socket option. * * @par Examples * Setting the option: * @code * asio::ip::tcp::socket socket(my_context); * ... * asio::socket_base::debug option(true); * socket.set_option(option); * @endcode * * @par * Getting the current option value: * @code * asio::ip::tcp::socket socket(my_context); * ... * asio::socket_base::debug option; * socket.get_option(option); * bool is_set = option.value(); * @endcode * * @par Concepts: * Socket_Option, Boolean_Socket_Option. */ #if defined(GENERATING_DOCUMENTATION) typedef implementation_defined debug; #else typedef asio::detail::socket_option::boolean< ASIO_OS_DEF(SOL_SOCKET), ASIO_OS_DEF(SO_DEBUG)> debug; #endif /// Socket option to prevent routing, use local interfaces only. /** * Implements the SOL_SOCKET/SO_DONTROUTE socket option. * * @par Examples * Setting the option: * @code * asio::ip::udp::socket socket(my_context); * ... * asio::socket_base::do_not_route option(true); * socket.set_option(option); * @endcode * * @par * Getting the current option value: * @code * asio::ip::udp::socket socket(my_context); * ... * asio::socket_base::do_not_route option; * socket.get_option(option); * bool is_set = option.value(); * @endcode * * @par Concepts: * Socket_Option, Boolean_Socket_Option. */ #if defined(GENERATING_DOCUMENTATION) typedef implementation_defined do_not_route; #else typedef asio::detail::socket_option::boolean< ASIO_OS_DEF(SOL_SOCKET), ASIO_OS_DEF(SO_DONTROUTE)> do_not_route; #endif /// Socket option to send keep-alives. /** * Implements the SOL_SOCKET/SO_KEEPALIVE socket option. * * @par Examples * Setting the option: * @code * asio::ip::tcp::socket socket(my_context); * ... * asio::socket_base::keep_alive option(true); * socket.set_option(option); * @endcode * * @par * Getting the current option value: * @code * asio::ip::tcp::socket socket(my_context); * ... * asio::socket_base::keep_alive option; * socket.get_option(option); * bool is_set = option.value(); * @endcode * * @par Concepts: * Socket_Option, Boolean_Socket_Option. */ #if defined(GENERATING_DOCUMENTATION) typedef implementation_defined keep_alive; #else typedef asio::detail::socket_option::boolean< ASIO_OS_DEF(SOL_SOCKET), ASIO_OS_DEF(SO_KEEPALIVE)> keep_alive; #endif /// Socket option for the send buffer size of a socket. /** * Implements the SOL_SOCKET/SO_SNDBUF socket option. * * @par Examples * Setting the option: * @code * asio::ip::tcp::socket socket(my_context); * ... * asio::socket_base::send_buffer_size option(8192); * socket.set_option(option); * @endcode * * @par * Getting the current option value: * @code * asio::ip::tcp::socket socket(my_context); * ... * asio::socket_base::send_buffer_size option; * socket.get_option(option); * int size = option.value(); * @endcode * * @par Concepts: * Socket_Option, Integer_Socket_Option. */ #if defined(GENERATING_DOCUMENTATION) typedef implementation_defined send_buffer_size; #else typedef asio::detail::socket_option::integer< ASIO_OS_DEF(SOL_SOCKET), ASIO_OS_DEF(SO_SNDBUF)> send_buffer_size; #endif /// Socket option for the send low watermark. /** * Implements the SOL_SOCKET/SO_SNDLOWAT socket option. * * @par Examples * Setting the option: * @code * asio::ip::tcp::socket socket(my_context); * ... * asio::socket_base::send_low_watermark option(1024); * socket.set_option(option); * @endcode * * @par * Getting the current option value: * @code * asio::ip::tcp::socket socket(my_context); * ... * asio::socket_base::send_low_watermark option; * socket.get_option(option); * int size = option.value(); * @endcode * * @par Concepts: * Socket_Option, Integer_Socket_Option. */ #if defined(GENERATING_DOCUMENTATION) typedef implementation_defined send_low_watermark; #else typedef asio::detail::socket_option::integer< ASIO_OS_DEF(SOL_SOCKET), ASIO_OS_DEF(SO_SNDLOWAT)> send_low_watermark; #endif /// Socket option for the receive buffer size of a socket. /** * Implements the SOL_SOCKET/SO_RCVBUF socket option. * * @par Examples * Setting the option: * @code * asio::ip::tcp::socket socket(my_context); * ... * asio::socket_base::receive_buffer_size option(8192); * socket.set_option(option); * @endcode * * @par * Getting the current option value: * @code * asio::ip::tcp::socket socket(my_context); * ... * asio::socket_base::receive_buffer_size option; * socket.get_option(option); * int size = option.value(); * @endcode * * @par Concepts: * Socket_Option, Integer_Socket_Option. */ #if defined(GENERATING_DOCUMENTATION) typedef implementation_defined receive_buffer_size; #else typedef asio::detail::socket_option::integer< ASIO_OS_DEF(SOL_SOCKET), ASIO_OS_DEF(SO_RCVBUF)> receive_buffer_size; #endif /// Socket option for the receive low watermark. /** * Implements the SOL_SOCKET/SO_RCVLOWAT socket option. * * @par Examples * Setting the option: * @code * asio::ip::tcp::socket socket(my_context); * ... * asio::socket_base::receive_low_watermark option(1024); * socket.set_option(option); * @endcode * * @par * Getting the current option value: * @code * asio::ip::tcp::socket socket(my_context); * ... * asio::socket_base::receive_low_watermark option; * socket.get_option(option); * int size = option.value(); * @endcode * * @par Concepts: * Socket_Option, Integer_Socket_Option. */ #if defined(GENERATING_DOCUMENTATION) typedef implementation_defined receive_low_watermark; #else typedef asio::detail::socket_option::integer< ASIO_OS_DEF(SOL_SOCKET), ASIO_OS_DEF(SO_RCVLOWAT)> receive_low_watermark; #endif /// Socket option to allow the socket to be bound to an address that is /// already in use. /** * Implements the SOL_SOCKET/SO_REUSEADDR socket option. * * @par Examples * Setting the option: * @code * asio::ip::tcp::acceptor acceptor(my_context); * ... * asio::socket_base::reuse_address option(true); * acceptor.set_option(option); * @endcode * * @par * Getting the current option value: * @code * asio::ip::tcp::acceptor acceptor(my_context); * ... * asio::socket_base::reuse_address option; * acceptor.get_option(option); * bool is_set = option.value(); * @endcode * * @par Concepts: * Socket_Option, Boolean_Socket_Option. */ #if defined(GENERATING_DOCUMENTATION) typedef implementation_defined reuse_address; #else typedef asio::detail::socket_option::boolean< ASIO_OS_DEF(SOL_SOCKET), ASIO_OS_DEF(SO_REUSEADDR)> reuse_address; #endif /// Socket option to specify whether the socket lingers on close if unsent /// data is present. /** * Implements the SOL_SOCKET/SO_LINGER socket option. * * @par Examples * Setting the option: * @code * asio::ip::tcp::socket socket(my_context); * ... * asio::socket_base::linger option(true, 30); * socket.set_option(option); * @endcode * * @par * Getting the current option value: * @code * asio::ip::tcp::socket socket(my_context); * ... * asio::socket_base::linger option; * socket.get_option(option); * bool is_set = option.enabled(); * unsigned short timeout = option.timeout(); * @endcode * * @par Concepts: * Socket_Option, Linger_Socket_Option. */ #if defined(GENERATING_DOCUMENTATION) typedef implementation_defined linger; #else typedef asio::detail::socket_option::linger< ASIO_OS_DEF(SOL_SOCKET), ASIO_OS_DEF(SO_LINGER)> linger; #endif /// Socket option for putting received out-of-band data inline. /** * Implements the SOL_SOCKET/SO_OOBINLINE socket option. * * @par Examples * Setting the option: * @code * asio::ip::tcp::socket socket(my_context); * ... * asio::socket_base::out_of_band_inline option(true); * socket.set_option(option); * @endcode * * @par * Getting the current option value: * @code * asio::ip::tcp::socket socket(my_context); * ... * asio::socket_base::out_of_band_inline option; * socket.get_option(option); * bool value = option.value(); * @endcode * * @par Concepts: * Socket_Option, Boolean_Socket_Option. */ #if defined(GENERATING_DOCUMENTATION) typedef implementation_defined out_of_band_inline; #else typedef asio::detail::socket_option::boolean< ASIO_OS_DEF(SOL_SOCKET), ASIO_OS_DEF(SO_OOBINLINE)> out_of_band_inline; #endif /// Socket option to report aborted connections on accept. /** * Implements a custom socket option that determines whether or not an accept * operation is permitted to fail with asio::error::connection_aborted. * By default the option is false. * * @par Examples * Setting the option: * @code * asio::ip::tcp::acceptor acceptor(my_context); * ... * asio::socket_base::enable_connection_aborted option(true); * acceptor.set_option(option); * @endcode * * @par * Getting the current option value: * @code * asio::ip::tcp::acceptor acceptor(my_context); * ... * asio::socket_base::enable_connection_aborted option; * acceptor.get_option(option); * bool is_set = option.value(); * @endcode * * @par Concepts: * Socket_Option, Boolean_Socket_Option. */ #if defined(GENERATING_DOCUMENTATION) typedef implementation_defined enable_connection_aborted; #else typedef asio::detail::socket_option::boolean< asio::detail::custom_socket_option_level, asio::detail::enable_connection_aborted_option> enable_connection_aborted; #endif /// IO control command to get the amount of data that can be read without /// blocking. /** * Implements the FIONREAD IO control command. * * @par Example * @code * asio::ip::tcp::socket socket(my_context); * ... * asio::socket_base::bytes_readable command(true); * socket.io_control(command); * std::size_t bytes_readable = command.get(); * @endcode * * @par Concepts: * IO_Control_Command, Size_IO_Control_Command. */ #if defined(GENERATING_DOCUMENTATION) typedef implementation_defined bytes_readable; #else typedef asio::detail::io_control::bytes_readable bytes_readable; #endif /// The maximum length of the queue of pending incoming connections. #if defined(GENERATING_DOCUMENTATION) static const int max_listen_connections = implementation_defined; #else ASIO_STATIC_CONSTANT(int, max_listen_connections = ASIO_OS_DEF(SOMAXCONN)); #endif #if !defined(ASIO_NO_DEPRECATED) /// (Deprecated: Use max_listen_connections.) The maximum length of the queue /// of pending incoming connections. #if defined(GENERATING_DOCUMENTATION) static const int max_connections = implementation_defined; #else ASIO_STATIC_CONSTANT(int, max_connections = ASIO_OS_DEF(SOMAXCONN)); #endif #endif // !defined(ASIO_NO_DEPRECATED) protected: /// Protected destructor to prevent deletion through this type. ~socket_base() { } }; } // namespace asio #include "asio/detail/pop_options.hpp" #endif // ASIO_SOCKET_BASE_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/stream_file.hpp
// // stream_file.hpp // ~~~~~~~~~~~~~~~ // // 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) // #ifndef ASIO_STREAM_FILE_HPP #define ASIO_STREAM_FILE_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #if defined(ASIO_HAS_FILE) \ || defined(GENERATING_DOCUMENTATION) #include "asio/basic_stream_file.hpp" namespace asio { /// Typedef for the typical usage of a stream-oriented file. typedef basic_stream_file<> stream_file; } // namespace asio #endif // defined(ASIO_HAS_FILE) // || defined(GENERATING_DOCUMENTATION) #endif // ASIO_STREAM_FILE_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/version.hpp
// // version.hpp // ~~~~~~~~~~~ // // 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) // #ifndef ASIO_VERSION_HPP #define ASIO_VERSION_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) // ASIO_VERSION % 100 is the sub-minor version // ASIO_VERSION / 100 % 1000 is the minor version // ASIO_VERSION / 100000 is the major version #define ASIO_VERSION 103100 // 1.31.0 #endif // ASIO_VERSION_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/dispatch.hpp
// // dispatch.hpp // ~~~~~~~~~~~~ // // 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) // #ifndef ASIO_DISPATCH_HPP #define ASIO_DISPATCH_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include "asio/async_result.hpp" #include "asio/detail/initiate_dispatch.hpp" #include "asio/detail/type_traits.hpp" #include "asio/execution_context.hpp" #include "asio/execution/executor.hpp" #include "asio/is_executor.hpp" #include "asio/detail/push_options.hpp" namespace asio { /// Submits a completion token or function object for execution. /** * This function submits an object for execution using the object's associated * executor. The function object may be called from the current thread prior to * returning from <tt>dispatch()</tt>. Otherwise, it is queued for execution. * * @param token The @ref completion_token that will be used to produce a * completion handler. The function signature of the completion handler must be: * @code void handler(); @endcode * * @returns This function returns <tt>async_initiate<NullaryToken, * void()>(Init{}, token)</tt>, where @c Init is a function object type defined * as: * * @code class Init * { * public: * template <typename CompletionHandler> * void operator()(CompletionHandler&& completion_handler) const; * }; @endcode * * The function call operator of @c Init: * * @li Obtains the handler's associated executor object @c ex of type @c Ex by * performing @code auto ex = get_associated_executor(handler); @endcode * * @li Obtains the handler's associated allocator object @c alloc by performing * @code auto alloc = get_associated_allocator(handler); @endcode * * @li If <tt>execution::is_executor<Ex>::value</tt> is true, performs * @code prefer(ex, execution::allocator(alloc)).execute( * std::forward<CompletionHandler>(completion_handler)); @endcode * * @li If <tt>execution::is_executor<Ex>::value</tt> is false, performs * @code ex.dispatch( * std::forward<CompletionHandler>(completion_handler), * alloc); @endcode * * @par Completion Signature * @code void() @endcode */ template <ASIO_COMPLETION_TOKEN_FOR(void()) NullaryToken> inline auto dispatch(NullaryToken&& token) -> decltype( async_initiate<NullaryToken, void()>( declval<detail::initiate_dispatch>(), token)) { return async_initiate<NullaryToken, void()>( detail::initiate_dispatch(), token); } /// Submits a completion token or function object for execution. /** * This function submits an object for execution using the specified executor. * The function object may be called from the current thread prior to returning * from <tt>dispatch()</tt>. Otherwise, it is queued for execution. * * @param ex The target executor. * * @param token The @ref completion_token that will be used to produce a * completion handler. The function signature of the completion handler must be: * @code void handler(); @endcode * * @returns This function returns <tt>async_initiate<NullaryToken, * void()>(Init{ex}, token)</tt>, where @c Init is a function object type * defined as: * * @code class Init * { * public: * using executor_type = Executor; * explicit Init(const Executor& ex) : ex_(ex) {} * executor_type get_executor() const noexcept { return ex_; } * template <typename CompletionHandler> * void operator()(CompletionHandler&& completion_handler) const; * private: * Executor ex_; // exposition only * }; @endcode * * The function call operator of @c Init: * * @li Obtains the handler's associated executor object @c ex1 of type @c Ex1 by * performing @code auto ex1 = get_associated_executor(handler, ex); @endcode * * @li Obtains the handler's associated allocator object @c alloc by performing * @code auto alloc = get_associated_allocator(handler); @endcode * * @li If <tt>execution::is_executor<Ex1>::value</tt> is true, constructs a * function object @c f with a member @c executor_ that is initialised with * <tt>prefer(ex1, execution::outstanding_work.tracked)</tt>, a member @c * handler_ that is a decay-copy of @c completion_handler, and a function call * operator that performs: * @code auto a = get_associated_allocator(handler_); * prefer(executor_, execution::allocator(a)).execute(std::move(handler_)); * @endcode * * @li If <tt>execution::is_executor<Ex1>::value</tt> is false, constructs a * function object @c f with a member @c work_ that is initialised with * <tt>make_work_guard(ex1)</tt>, a member @c handler_ that is a decay-copy of * @c completion_handler, and a function call operator that performs: * @code auto a = get_associated_allocator(handler_); * work_.get_executor().dispatch(std::move(handler_), a); * work_.reset(); @endcode * * @li If <tt>execution::is_executor<Ex>::value</tt> is true, performs * @code prefer(ex, execution::allocator(alloc)).execute(std::move(f)); @endcode * * @li If <tt>execution::is_executor<Ex>::value</tt> is false, performs * @code ex.dispatch(std::move(f), alloc); @endcode * * @par Completion Signature * @code void() @endcode */ template <typename Executor, ASIO_COMPLETION_TOKEN_FOR(void()) NullaryToken = default_completion_token_t<Executor>> inline auto dispatch(const Executor& ex, NullaryToken&& token = default_completion_token_t<Executor>(), constraint_t< execution::is_executor<Executor>::value || is_executor<Executor>::value > = 0) -> decltype( async_initiate<NullaryToken, void()>( declval<detail::initiate_dispatch_with_executor<Executor>>(), token)) { return async_initiate<NullaryToken, void()>( detail::initiate_dispatch_with_executor<Executor>(ex), token); } /// Submits a completion token or function object for execution. /** * @param ctx An execution context, from which the target executor is obtained. * * @param token The @ref completion_token that will be used to produce a * completion handler. The function signature of the completion handler must be: * @code void handler(); @endcode * * @returns <tt>dispatch(ctx.get_executor(), * forward<NullaryToken>(token))</tt>. * * @par Completion Signature * @code void() @endcode */ template <typename ExecutionContext, ASIO_COMPLETION_TOKEN_FOR(void()) NullaryToken = default_completion_token_t<typename ExecutionContext::executor_type>> inline auto dispatch(ExecutionContext& ctx, NullaryToken&& token = default_completion_token_t< typename ExecutionContext::executor_type>(), constraint_t< is_convertible<ExecutionContext&, execution_context&>::value > = 0) -> decltype( async_initiate<NullaryToken, void()>( declval<detail::initiate_dispatch_with_executor< typename ExecutionContext::executor_type>>(), token)) { return async_initiate<NullaryToken, void()>( detail::initiate_dispatch_with_executor< typename ExecutionContext::executor_type>( ctx.get_executor()), token); } } // namespace asio #include "asio/detail/pop_options.hpp" #endif // ASIO_DISPATCH_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/basic_waitable_timer.hpp
// // basic_waitable_timer.hpp // ~~~~~~~~~~~~~~~~~~~~~~~~ // // 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) // #ifndef ASIO_BASIC_WAITABLE_TIMER_HPP #define ASIO_BASIC_WAITABLE_TIMER_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include <cstddef> #include <utility> #include "asio/any_io_executor.hpp" #include "asio/detail/chrono_time_traits.hpp" #include "asio/detail/deadline_timer_service.hpp" #include "asio/detail/handler_type_requirements.hpp" #include "asio/detail/io_object_impl.hpp" #include "asio/detail/non_const_lvalue.hpp" #include "asio/detail/throw_error.hpp" #include "asio/error.hpp" #include "asio/wait_traits.hpp" #include "asio/detail/push_options.hpp" namespace asio { #if !defined(ASIO_BASIC_WAITABLE_TIMER_FWD_DECL) #define ASIO_BASIC_WAITABLE_TIMER_FWD_DECL // Forward declaration with defaulted arguments. template <typename Clock, typename WaitTraits = asio::wait_traits<Clock>, typename Executor = any_io_executor> class basic_waitable_timer; #endif // !defined(ASIO_BASIC_WAITABLE_TIMER_FWD_DECL) /// Provides waitable timer functionality. /** * The basic_waitable_timer class template provides the ability to perform a * blocking or asynchronous wait for a timer to expire. * * A waitable timer is always in one of two states: "expired" or "not expired". * If the wait() or async_wait() function is called on an expired timer, the * wait operation will complete immediately. * * Most applications will use one of the asio::steady_timer, * asio::system_timer or asio::high_resolution_timer typedefs. * * @note This waitable timer functionality is for use with the C++11 standard * library's @c &lt;chrono&gt; facility, or with the Boost.Chrono library. * * @par Thread Safety * @e Distinct @e objects: Safe.@n * @e Shared @e objects: Unsafe. * * @par Examples * Performing a blocking wait (C++11): * @code * // Construct a timer without setting an expiry time. * asio::steady_timer timer(my_context); * * // Set an expiry time relative to now. * timer.expires_after(std::chrono::seconds(5)); * * // Wait for the timer to expire. * timer.wait(); * @endcode * * @par * Performing an asynchronous wait (C++11): * @code * void handler(const asio::error_code& error) * { * if (!error) * { * // Timer expired. * } * } * * ... * * // Construct a timer with an absolute expiry time. * asio::steady_timer timer(my_context, * std::chrono::steady_clock::now() + std::chrono::seconds(60)); * * // Start an asynchronous wait. * timer.async_wait(handler); * @endcode * * @par Changing an active waitable timer's expiry time * * Changing the expiry time of a timer while there are pending asynchronous * waits causes those wait operations to be cancelled. To ensure that the action * associated with the timer is performed only once, use something like this: * used: * * @code * void on_some_event() * { * if (my_timer.expires_after(seconds(5)) > 0) * { * // We managed to cancel the timer. Start new asynchronous wait. * my_timer.async_wait(on_timeout); * } * else * { * // Too late, timer has already expired! * } * } * * void on_timeout(const asio::error_code& e) * { * if (e != asio::error::operation_aborted) * { * // Timer was not cancelled, take necessary action. * } * } * @endcode * * @li The asio::basic_waitable_timer::expires_after() function * cancels any pending asynchronous waits, and returns the number of * asynchronous waits that were cancelled. If it returns 0 then you were too * late and the wait handler has already been executed, or will soon be * executed. If it returns 1 then the wait handler was successfully cancelled. * * @li If a wait handler is cancelled, the asio::error_code passed to * it contains the value asio::error::operation_aborted. */ template <typename Clock, typename WaitTraits, typename Executor> class basic_waitable_timer { private: class initiate_async_wait; public: /// The type of the executor associated with the object. typedef Executor executor_type; /// Rebinds the timer type to another executor. template <typename Executor1> struct rebind_executor { /// The timer type when rebound to the specified executor. typedef basic_waitable_timer<Clock, WaitTraits, Executor1> other; }; /// The clock type. typedef Clock clock_type; /// The duration type of the clock. typedef typename clock_type::duration duration; /// The time point type of the clock. typedef typename clock_type::time_point time_point; /// The wait traits type. typedef WaitTraits traits_type; /// Constructor. /** * This constructor creates a timer without setting an expiry time. The * expires_at() or expires_after() functions must be called to set an expiry * time before the timer can be waited on. * * @param ex The I/O executor that the timer will use, by default, to * dispatch handlers for any asynchronous operations performed on the timer. */ explicit basic_waitable_timer(const executor_type& ex) : impl_(0, ex) { } /// Constructor. /** * This constructor creates a timer without setting an expiry time. The * expires_at() or expires_after() functions must be called to set an expiry * time before the timer can be waited on. * * @param context An execution context which provides the I/O executor that * the timer will use, by default, to dispatch handlers for any asynchronous * operations performed on the timer. */ template <typename ExecutionContext> explicit basic_waitable_timer(ExecutionContext& context, constraint_t< is_convertible<ExecutionContext&, execution_context&>::value > = 0) : impl_(0, 0, context) { } /// Constructor to set a particular expiry time as an absolute time. /** * This constructor creates a timer and sets the expiry time. * * @param ex The I/O executor object that the timer will use, by default, to * dispatch handlers for any asynchronous operations performed on the timer. * * @param expiry_time The expiry time to be used for the timer, expressed * as an absolute time. */ basic_waitable_timer(const executor_type& ex, const time_point& expiry_time) : impl_(0, ex) { asio::error_code ec; impl_.get_service().expires_at(impl_.get_implementation(), expiry_time, ec); asio::detail::throw_error(ec, "expires_at"); } /// Constructor to set a particular expiry time as an absolute time. /** * This constructor creates a timer and sets the expiry time. * * @param context An execution context which provides the I/O executor that * the timer will use, by default, to dispatch handlers for any asynchronous * operations performed on the timer. * * @param expiry_time The expiry time to be used for the timer, expressed * as an absolute time. */ template <typename ExecutionContext> explicit basic_waitable_timer(ExecutionContext& context, const time_point& expiry_time, constraint_t< is_convertible<ExecutionContext&, execution_context&>::value > = 0) : impl_(0, 0, context) { asio::error_code ec; impl_.get_service().expires_at(impl_.get_implementation(), expiry_time, ec); asio::detail::throw_error(ec, "expires_at"); } /// Constructor to set a particular expiry time relative to now. /** * This constructor creates a timer and sets the expiry time. * * @param ex The I/O executor that the timer will use, by default, to * dispatch handlers for any asynchronous operations performed on the timer. * * @param expiry_time The expiry time to be used for the timer, relative to * now. */ basic_waitable_timer(const executor_type& ex, const duration& expiry_time) : impl_(0, ex) { asio::error_code ec; impl_.get_service().expires_after( impl_.get_implementation(), expiry_time, ec); asio::detail::throw_error(ec, "expires_after"); } /// Constructor to set a particular expiry time relative to now. /** * This constructor creates a timer and sets the expiry time. * * @param context An execution context which provides the I/O executor that * the timer will use, by default, to dispatch handlers for any asynchronous * operations performed on the timer. * * @param expiry_time The expiry time to be used for the timer, relative to * now. */ template <typename ExecutionContext> explicit basic_waitable_timer(ExecutionContext& context, const duration& expiry_time, constraint_t< is_convertible<ExecutionContext&, execution_context&>::value > = 0) : impl_(0, 0, context) { asio::error_code ec; impl_.get_service().expires_after( impl_.get_implementation(), expiry_time, ec); asio::detail::throw_error(ec, "expires_after"); } /// Move-construct a basic_waitable_timer from another. /** * This constructor moves a timer from one object to another. * * @param other The other basic_waitable_timer object from which the move will * occur. * * @note Following the move, the moved-from object is in the same state as if * constructed using the @c basic_waitable_timer(const executor_type&) * constructor. */ basic_waitable_timer(basic_waitable_timer&& other) : impl_(std::move(other.impl_)) { } /// Move-assign a basic_waitable_timer from another. /** * This assignment operator moves a timer from one object to another. Cancels * any outstanding asynchronous operations associated with the target object. * * @param other The other basic_waitable_timer object from which the move will * occur. * * @note Following the move, the moved-from object is in the same state as if * constructed using the @c basic_waitable_timer(const executor_type&) * constructor. */ basic_waitable_timer& operator=(basic_waitable_timer&& other) { impl_ = std::move(other.impl_); return *this; } // All timers have access to each other's implementations. template <typename Clock1, typename WaitTraits1, typename Executor1> friend class basic_waitable_timer; /// Move-construct a basic_waitable_timer from another. /** * This constructor moves a timer from one object to another. * * @param other The other basic_waitable_timer object from which the move will * occur. * * @note Following the move, the moved-from object is in the same state as if * constructed using the @c basic_waitable_timer(const executor_type&) * constructor. */ template <typename Executor1> basic_waitable_timer( basic_waitable_timer<Clock, WaitTraits, Executor1>&& other, constraint_t< is_convertible<Executor1, Executor>::value > = 0) : impl_(std::move(other.impl_)) { } /// Move-assign a basic_waitable_timer from another. /** * This assignment operator moves a timer from one object to another. Cancels * any outstanding asynchronous operations associated with the target object. * * @param other The other basic_waitable_timer object from which the move will * occur. * * @note Following the move, the moved-from object is in the same state as if * constructed using the @c basic_waitable_timer(const executor_type&) * constructor. */ template <typename Executor1> constraint_t< is_convertible<Executor1, Executor>::value, basic_waitable_timer& > operator=(basic_waitable_timer<Clock, WaitTraits, Executor1>&& other) { basic_waitable_timer tmp(std::move(other)); impl_ = std::move(tmp.impl_); return *this; } /// Destroys the timer. /** * This function destroys the timer, cancelling any outstanding asynchronous * wait operations associated with the timer as if by calling @c cancel. */ ~basic_waitable_timer() { } /// Get the executor associated with the object. const executor_type& get_executor() noexcept { return impl_.get_executor(); } /// Cancel any asynchronous operations that are waiting on the timer. /** * This function forces the completion of any pending asynchronous wait * operations against the timer. The handler for each cancelled operation will * be invoked with the asio::error::operation_aborted error code. * * Cancelling the timer does not change the expiry time. * * @return The number of asynchronous operations that were cancelled. * * @throws asio::system_error Thrown on failure. * * @note If the timer has already expired when cancel() is called, then the * handlers for asynchronous wait operations will: * * @li have already been invoked; or * * @li have been queued for invocation in the near future. * * These handlers can no longer be cancelled, and therefore are passed an * error code that indicates the successful completion of the wait operation. */ std::size_t cancel() { asio::error_code ec; std::size_t s = impl_.get_service().cancel(impl_.get_implementation(), ec); asio::detail::throw_error(ec, "cancel"); return s; } #if !defined(ASIO_NO_DEPRECATED) /// (Deprecated: Use non-error_code overload.) Cancel any asynchronous /// operations that are waiting on the timer. /** * This function forces the completion of any pending asynchronous wait * operations against the timer. The handler for each cancelled operation will * be invoked with the asio::error::operation_aborted error code. * * Cancelling the timer does not change the expiry time. * * @param ec Set to indicate what error occurred, if any. * * @return The number of asynchronous operations that were cancelled. * * @note If the timer has already expired when cancel() is called, then the * handlers for asynchronous wait operations will: * * @li have already been invoked; or * * @li have been queued for invocation in the near future. * * These handlers can no longer be cancelled, and therefore are passed an * error code that indicates the successful completion of the wait operation. */ std::size_t cancel(asio::error_code& ec) { return impl_.get_service().cancel(impl_.get_implementation(), ec); } #endif // !defined(ASIO_NO_DEPRECATED) /// Cancels one asynchronous operation that is waiting on the timer. /** * This function forces the completion of one pending asynchronous wait * operation against the timer. Handlers are cancelled in FIFO order. The * handler for the cancelled operation will be invoked with the * asio::error::operation_aborted error code. * * Cancelling the timer does not change the expiry time. * * @return The number of asynchronous operations that were cancelled. That is, * either 0 or 1. * * @throws asio::system_error Thrown on failure. * * @note If the timer has already expired when cancel_one() is called, then * the handlers for asynchronous wait operations will: * * @li have already been invoked; or * * @li have been queued for invocation in the near future. * * These handlers can no longer be cancelled, and therefore are passed an * error code that indicates the successful completion of the wait operation. */ std::size_t cancel_one() { asio::error_code ec; std::size_t s = impl_.get_service().cancel_one( impl_.get_implementation(), ec); asio::detail::throw_error(ec, "cancel_one"); return s; } #if !defined(ASIO_NO_DEPRECATED) /// (Deprecated: Use non-error_code overload.) Cancels one asynchronous /// operation that is waiting on the timer. /** * This function forces the completion of one pending asynchronous wait * operation against the timer. Handlers are cancelled in FIFO order. The * handler for the cancelled operation will be invoked with the * asio::error::operation_aborted error code. * * Cancelling the timer does not change the expiry time. * * @param ec Set to indicate what error occurred, if any. * * @return The number of asynchronous operations that were cancelled. That is, * either 0 or 1. * * @note If the timer has already expired when cancel_one() is called, then * the handlers for asynchronous wait operations will: * * @li have already been invoked; or * * @li have been queued for invocation in the near future. * * These handlers can no longer be cancelled, and therefore are passed an * error code that indicates the successful completion of the wait operation. */ std::size_t cancel_one(asio::error_code& ec) { return impl_.get_service().cancel_one(impl_.get_implementation(), ec); } /// (Deprecated: Use expiry().) Get the timer's expiry time as an absolute /// time. /** * This function may be used to obtain the timer's current expiry time. * Whether the timer has expired or not does not affect this value. */ time_point expires_at() const { return impl_.get_service().expires_at(impl_.get_implementation()); } #endif // !defined(ASIO_NO_DEPRECATED) /// Get the timer's expiry time as an absolute time. /** * This function may be used to obtain the timer's current expiry time. * Whether the timer has expired or not does not affect this value. */ time_point expiry() const { return impl_.get_service().expiry(impl_.get_implementation()); } /// Set the timer's expiry time as an absolute time. /** * This function sets the expiry time. Any pending asynchronous wait * operations will be cancelled. The handler for each cancelled operation will * be invoked with the asio::error::operation_aborted error code. * * @param expiry_time The expiry time to be used for the timer. * * @return The number of asynchronous operations that were cancelled. * * @throws asio::system_error Thrown on failure. * * @note If the timer has already expired when expires_at() is called, then * the handlers for asynchronous wait operations will: * * @li have already been invoked; or * * @li have been queued for invocation in the near future. * * These handlers can no longer be cancelled, and therefore are passed an * error code that indicates the successful completion of the wait operation. */ std::size_t expires_at(const time_point& expiry_time) { asio::error_code ec; std::size_t s = impl_.get_service().expires_at( impl_.get_implementation(), expiry_time, ec); asio::detail::throw_error(ec, "expires_at"); return s; } #if !defined(ASIO_NO_DEPRECATED) /// (Deprecated: Use non-error_code overload.) Set the timer's expiry time as /// an absolute time. /** * This function sets the expiry time. Any pending asynchronous wait * operations will be cancelled. The handler for each cancelled operation will * be invoked with the asio::error::operation_aborted error code. * * @param expiry_time The expiry time to be used for the timer. * * @param ec Set to indicate what error occurred, if any. * * @return The number of asynchronous operations that were cancelled. * * @note If the timer has already expired when expires_at() is called, then * the handlers for asynchronous wait operations will: * * @li have already been invoked; or * * @li have been queued for invocation in the near future. * * These handlers can no longer be cancelled, and therefore are passed an * error code that indicates the successful completion of the wait operation. */ std::size_t expires_at(const time_point& expiry_time, asio::error_code& ec) { return impl_.get_service().expires_at( impl_.get_implementation(), expiry_time, ec); } #endif // !defined(ASIO_NO_DEPRECATED) /// Set the timer's expiry time relative to now. /** * This function sets the expiry time. Any pending asynchronous wait * operations will be cancelled. The handler for each cancelled operation will * be invoked with the asio::error::operation_aborted error code. * * @param expiry_time The expiry time to be used for the timer. * * @return The number of asynchronous operations that were cancelled. * * @throws asio::system_error Thrown on failure. * * @note If the timer has already expired when expires_after() is called, * then the handlers for asynchronous wait operations will: * * @li have already been invoked; or * * @li have been queued for invocation in the near future. * * These handlers can no longer be cancelled, and therefore are passed an * error code that indicates the successful completion of the wait operation. */ std::size_t expires_after(const duration& expiry_time) { asio::error_code ec; std::size_t s = impl_.get_service().expires_after( impl_.get_implementation(), expiry_time, ec); asio::detail::throw_error(ec, "expires_after"); return s; } #if !defined(ASIO_NO_DEPRECATED) /// (Deprecated: Use expiry().) Get the timer's expiry time relative to now. /** * This function may be used to obtain the timer's current expiry time. * Whether the timer has expired or not does not affect this value. */ duration expires_from_now() const { return impl_.get_service().expires_from_now(impl_.get_implementation()); } /// (Deprecated: Use expires_after().) Set the timer's expiry time relative /// to now. /** * This function sets the expiry time. Any pending asynchronous wait * operations will be cancelled. The handler for each cancelled operation will * be invoked with the asio::error::operation_aborted error code. * * @param expiry_time The expiry time to be used for the timer. * * @return The number of asynchronous operations that were cancelled. * * @throws asio::system_error Thrown on failure. * * @note If the timer has already expired when expires_from_now() is called, * then the handlers for asynchronous wait operations will: * * @li have already been invoked; or * * @li have been queued for invocation in the near future. * * These handlers can no longer be cancelled, and therefore are passed an * error code that indicates the successful completion of the wait operation. */ std::size_t expires_from_now(const duration& expiry_time) { asio::error_code ec; std::size_t s = impl_.get_service().expires_from_now( impl_.get_implementation(), expiry_time, ec); asio::detail::throw_error(ec, "expires_from_now"); return s; } /// (Deprecated: Use expires_after().) Set the timer's expiry time relative /// to now. /** * This function sets the expiry time. Any pending asynchronous wait * operations will be cancelled. The handler for each cancelled operation will * be invoked with the asio::error::operation_aborted error code. * * @param expiry_time The expiry time to be used for the timer. * * @param ec Set to indicate what error occurred, if any. * * @return The number of asynchronous operations that were cancelled. * * @note If the timer has already expired when expires_from_now() is called, * then the handlers for asynchronous wait operations will: * * @li have already been invoked; or * * @li have been queued for invocation in the near future. * * These handlers can no longer be cancelled, and therefore are passed an * error code that indicates the successful completion of the wait operation. */ std::size_t expires_from_now(const duration& expiry_time, asio::error_code& ec) { return impl_.get_service().expires_from_now( impl_.get_implementation(), expiry_time, ec); } #endif // !defined(ASIO_NO_DEPRECATED) /// Perform a blocking wait on the timer. /** * This function is used to wait for the timer to expire. This function * blocks and does not return until the timer has expired. * * @throws asio::system_error Thrown on failure. */ void wait() { asio::error_code ec; impl_.get_service().wait(impl_.get_implementation(), ec); asio::detail::throw_error(ec, "wait"); } /// Perform a blocking wait on the timer. /** * This function is used to wait for the timer to expire. This function * blocks and does not return until the timer has expired. * * @param ec Set to indicate what error occurred, if any. */ void wait(asio::error_code& ec) { impl_.get_service().wait(impl_.get_implementation(), ec); } /// Start an asynchronous wait on the timer. /** * This function may be used to initiate an asynchronous wait against the * timer. It is an initiating function for an @ref asynchronous_operation, * and always returns immediately. * * For each call to async_wait(), the completion handler will be called * exactly once. The completion handler will be called when: * * @li The timer has expired. * * @li The timer was cancelled, in which case the handler is passed the error * code asio::error::operation_aborted. * * @param token The @ref completion_token that will be used to produce a * completion handler, which will be called when the timer expires. Potential * completion tokens include @ref use_future, @ref use_awaitable, @ref * yield_context, or a function object with the correct completion signature. * The function signature of the completion handler must be: * @code void handler( * const asio::error_code& error // Result of operation. * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the completion handler will not be invoked from within this function. * On immediate completion, invocation of the handler will be performed in a * manner equivalent to using asio::async_immediate(). * * @par Completion Signature * @code void(asio::error_code) @endcode * * @par Per-Operation Cancellation * This asynchronous operation supports cancellation for the following * asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * @li @c cancellation_type::total */ template < ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code)) WaitToken = default_completion_token_t<executor_type>> auto async_wait( WaitToken&& token = default_completion_token_t<executor_type>()) -> decltype( async_initiate<WaitToken, void (asio::error_code)>( declval<initiate_async_wait>(), token)) { return async_initiate<WaitToken, void (asio::error_code)>( initiate_async_wait(this), token); } private: // Disallow copying and assignment. basic_waitable_timer(const basic_waitable_timer&) = delete; basic_waitable_timer& operator=(const basic_waitable_timer&) = delete; class initiate_async_wait { public: typedef Executor executor_type; explicit initiate_async_wait(basic_waitable_timer* self) : self_(self) { } const executor_type& get_executor() const noexcept { return self_->get_executor(); } template <typename WaitHandler> void operator()(WaitHandler&& handler) const { // If you get an error on the following line it means that your handler // does not meet the documented type requirements for a WaitHandler. ASIO_WAIT_HANDLER_CHECK(WaitHandler, handler) type_check; detail::non_const_lvalue<WaitHandler> handler2(handler); self_->impl_.get_service().async_wait( self_->impl_.get_implementation(), handler2.value, self_->impl_.get_executor()); } private: basic_waitable_timer* self_; }; detail::io_object_impl< detail::deadline_timer_service< detail::chrono_time_traits<Clock, WaitTraits>>, executor_type > impl_; }; } // namespace asio #include "asio/detail/pop_options.hpp" #endif // ASIO_BASIC_WAITABLE_TIMER_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/compose.hpp
// // compose.hpp // ~~~~~~~~~~~ // // 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) // #ifndef ASIO_COMPOSE_HPP #define ASIO_COMPOSE_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include "asio/composed.hpp" #include "asio/detail/push_options.hpp" namespace asio { /// Launch an asynchronous operation with a stateful implementation. /** * The async_compose function simplifies the implementation of composed * asynchronous operations automatically wrapping a stateful function object * with a conforming intermediate completion handler. * * @param implementation A function object that contains the implementation of * the composed asynchronous operation. The first argument to the function * object is a non-const reference to the enclosing intermediate completion * handler. The remaining arguments are any arguments that originate from the * completion handlers of any asynchronous operations performed by the * implementation. * * @param token The completion token. * * @param io_objects_or_executors Zero or more I/O objects or I/O executors for * which outstanding work must be maintained. * * @par Per-Operation Cancellation * By default, terminal per-operation cancellation is enabled for * composed operations that are implemented using @c async_compose. To * disable cancellation for the composed operation, or to alter its * supported cancellation types, call the @c self object's @c * reset_cancellation_state function. * * @par Example: * * @code struct async_echo_implementation * { * tcp::socket& socket_; * asio::mutable_buffer buffer_; * enum { starting, reading, writing } state_; * * template <typename Self> * void operator()(Self& self, * asio::error_code error = {}, * std::size_t n = 0) * { * switch (state_) * { * case starting: * state_ = reading; * socket_.async_read_some( * buffer_, std::move(self)); * break; * case reading: * if (error) * { * self.complete(error, 0); * } * else * { * state_ = writing; * asio::async_write(socket_, buffer_, * asio::transfer_exactly(n), * std::move(self)); * } * break; * case writing: * self.complete(error, n); * break; * } * } * }; * * template <typename CompletionToken> * auto async_echo(tcp::socket& socket, * asio::mutable_buffer buffer, * CompletionToken&& token) * -> decltype( * asio::async_compose<CompletionToken, * void(asio::error_code, std::size_t)>( * std::declval<async_echo_implementation>(), * token, socket)) * { * return asio::async_compose<CompletionToken, * void(asio::error_code, std::size_t)>( * async_echo_implementation{socket, buffer, * async_echo_implementation::starting}, * token, socket); * } @endcode */ template <typename CompletionToken, typename Signature, typename Implementation, typename... IoObjectsOrExecutors> inline auto async_compose(Implementation&& implementation, type_identity_t<CompletionToken>& token, IoObjectsOrExecutors&&... io_objects_or_executors) -> decltype( async_initiate<CompletionToken, Signature>( composed<Signature>(static_cast<Implementation&&>(implementation), static_cast<IoObjectsOrExecutors&&>(io_objects_or_executors)...), token)) { return async_initiate<CompletionToken, Signature>( composed<Signature>(static_cast<Implementation&&>(implementation), static_cast<IoObjectsOrExecutors&&>(io_objects_or_executors)...), token); } } // namespace asio #include "asio/detail/pop_options.hpp" #endif // ASIO_COMPOSE_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/cancellation_signal.hpp
// // cancellation_signal.hpp // ~~~~~~~~~~~~~~~~~~~~~~~ // // 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) // #ifndef ASIO_CANCELLATION_SIGNAL_HPP #define ASIO_CANCELLATION_SIGNAL_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include <cassert> #include <new> #include <utility> #include "asio/cancellation_type.hpp" #include "asio/detail/cstddef.hpp" #include "asio/detail/type_traits.hpp" #include "asio/detail/push_options.hpp" namespace asio { namespace detail { class cancellation_handler_base { public: virtual void call(cancellation_type_t) = 0; virtual std::pair<void*, std::size_t> destroy() noexcept = 0; protected: ~cancellation_handler_base() {} }; template <typename Handler> class cancellation_handler : public cancellation_handler_base { public: template <typename... Args> cancellation_handler(std::size_t size, Args&&... args) : handler_(static_cast<Args&&>(args)...), size_(size) { } void call(cancellation_type_t type) { handler_(type); } std::pair<void*, std::size_t> destroy() noexcept { std::pair<void*, std::size_t> mem(this, size_); this->cancellation_handler::~cancellation_handler(); return mem; } Handler& handler() noexcept { return handler_; } private: ~cancellation_handler() { } Handler handler_; std::size_t size_; }; } // namespace detail class cancellation_slot; /// A cancellation signal with a single slot. class cancellation_signal { public: constexpr cancellation_signal() : handler_(0) { } ASIO_DECL ~cancellation_signal(); /// Emits the signal and causes invocation of the slot's handler, if any. void emit(cancellation_type_t type) { if (handler_) handler_->call(type); } /// Returns the single slot associated with the signal. /** * The signal object must remain valid for as long the slot may be used. * Destruction of the signal invalidates the slot. */ cancellation_slot slot() noexcept; private: cancellation_signal(const cancellation_signal&) = delete; cancellation_signal& operator=(const cancellation_signal&) = delete; detail::cancellation_handler_base* handler_; }; /// A slot associated with a cancellation signal. class cancellation_slot { public: /// Creates a slot that is not connected to any cancellation signal. constexpr cancellation_slot() : handler_(0) { } /// Installs a handler into the slot, constructing the new object directly. /** * Destroys any existing handler in the slot, then installs the new handler, * constructing it with the supplied @c args. * * The handler is a function object to be called when the signal is emitted. * The signature of the handler must be * @code void handler(asio::cancellation_type_t); @endcode * * @param args Arguments to be passed to the @c CancellationHandler object's * constructor. * * @returns A reference to the newly installed handler. * * @note Handlers installed into the slot via @c emplace are not required to * be copy constructible or move constructible. */ template <typename CancellationHandler, typename... Args> CancellationHandler& emplace(Args&&... args) { typedef detail::cancellation_handler<CancellationHandler> cancellation_handler_type; auto_delete_helper del = { prepare_memory( sizeof(cancellation_handler_type), alignof(CancellationHandler)) }; cancellation_handler_type* handler_obj = new (del.mem.first) cancellation_handler_type( del.mem.second, static_cast<Args&&>(args)...); del.mem.first = 0; *handler_ = handler_obj; return handler_obj->handler(); } /// Installs a handler into the slot. /** * Destroys any existing handler in the slot, then installs the new handler, * constructing it as a decay-copy of the supplied handler. * * The handler is a function object to be called when the signal is emitted. * The signature of the handler must be * @code void handler(asio::cancellation_type_t); @endcode * * @param handler The handler to be installed. * * @returns A reference to the newly installed handler. */ template <typename CancellationHandler> decay_t<CancellationHandler>& assign(CancellationHandler&& handler) { return this->emplace<decay_t<CancellationHandler>>( static_cast<CancellationHandler&&>(handler)); } /// Clears the slot. /** * Destroys any existing handler in the slot. */ ASIO_DECL void clear(); /// Returns whether the slot is connected to a signal. constexpr bool is_connected() const noexcept { return handler_ != 0; } /// Returns whether the slot is connected and has an installed handler. constexpr bool has_handler() const noexcept { return handler_ != 0 && *handler_ != 0; } /// Compare two slots for equality. friend constexpr bool operator==(const cancellation_slot& lhs, const cancellation_slot& rhs) noexcept { return lhs.handler_ == rhs.handler_; } /// Compare two slots for inequality. friend constexpr bool operator!=(const cancellation_slot& lhs, const cancellation_slot& rhs) noexcept { return lhs.handler_ != rhs.handler_; } private: friend class cancellation_signal; constexpr cancellation_slot(int, detail::cancellation_handler_base** handler) : handler_(handler) { } ASIO_DECL std::pair<void*, std::size_t> prepare_memory( std::size_t size, std::size_t align); struct auto_delete_helper { std::pair<void*, std::size_t> mem; ASIO_DECL ~auto_delete_helper(); }; detail::cancellation_handler_base** handler_; }; inline cancellation_slot cancellation_signal::slot() noexcept { return cancellation_slot(0, &handler_); } } // namespace asio #include "asio/detail/pop_options.hpp" #if defined(ASIO_HEADER_ONLY) # include "asio/impl/cancellation_signal.ipp" #endif // defined(ASIO_HEADER_ONLY) #endif // ASIO_CANCELLATION_SIGNAL_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/write.hpp
// // write.hpp // ~~~~~~~~~ // // 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) // #ifndef ASIO_WRITE_HPP #define ASIO_WRITE_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include <cstddef> #include "asio/async_result.hpp" #include "asio/buffer.hpp" #include "asio/completion_condition.hpp" #include "asio/error.hpp" #if !defined(ASIO_NO_EXTENSIONS) # include "asio/basic_streambuf_fwd.hpp" #endif // !defined(ASIO_NO_EXTENSIONS) #include "asio/detail/push_options.hpp" namespace asio { namespace detail { template <typename> class initiate_async_write; #if !defined(ASIO_NO_DYNAMIC_BUFFER_V1) template <typename> class initiate_async_write_dynbuf_v1; #endif // !defined(ASIO_NO_DYNAMIC_BUFFER_V1) template <typename> class initiate_async_write_dynbuf_v2; } // namespace detail /** * @defgroup write asio::write * * @brief The @c write function is a composed operation that writes a certain * amount of data to a stream before returning. */ /*@{*/ /// Write all of the supplied data to a stream before returning. /** * This function is used to write a certain number of bytes of data to a stream. * The call will block until one of the following conditions is true: * * @li All of the data in the supplied buffers has been written. That is, the * bytes transferred is equal to the sum of the buffer sizes. * * @li An error occurred. * * This operation is implemented in terms of zero or more calls to the stream's * write_some function. * * @param s The stream to which the data is to be written. The type must support * the SyncWriteStream concept. * * @param buffers One or more buffers containing the data to be written. The sum * of the buffer sizes indicates the maximum number of bytes to write to the * stream. * * @returns The number of bytes transferred. * * @throws asio::system_error Thrown on failure. * * @par Example * To write a single data buffer use the @ref buffer function as follows: * @code asio::write(s, asio::buffer(data, size)); @endcode * See the @ref buffer documentation for information on writing multiple * buffers in one go, and how to use it with arrays, boost::array or * std::vector. * * @note This overload is equivalent to calling: * @code asio::write( * s, buffers, * asio::transfer_all()); @endcode */ template <typename SyncWriteStream, typename ConstBufferSequence> std::size_t write(SyncWriteStream& s, const ConstBufferSequence& buffers, constraint_t< is_const_buffer_sequence<ConstBufferSequence>::value > = 0); /// Write all of the supplied data to a stream before returning. /** * This function is used to write a certain number of bytes of data to a stream. * The call will block until one of the following conditions is true: * * @li All of the data in the supplied buffers has been written. That is, the * bytes transferred is equal to the sum of the buffer sizes. * * @li An error occurred. * * This operation is implemented in terms of zero or more calls to the stream's * write_some function. * * @param s The stream to which the data is to be written. The type must support * the SyncWriteStream concept. * * @param buffers One or more buffers containing the data to be written. The sum * of the buffer sizes indicates the maximum number of bytes to write to the * stream. * * @param ec Set to indicate what error occurred, if any. * * @returns The number of bytes transferred. * * @par Example * To write a single data buffer use the @ref buffer function as follows: * @code asio::write(s, asio::buffer(data, size), ec); @endcode * See the @ref buffer documentation for information on writing multiple * buffers in one go, and how to use it with arrays, boost::array or * std::vector. * * @note This overload is equivalent to calling: * @code asio::write( * s, buffers, * asio::transfer_all(), ec); @endcode */ template <typename SyncWriteStream, typename ConstBufferSequence> std::size_t write(SyncWriteStream& s, const ConstBufferSequence& buffers, asio::error_code& ec, constraint_t< is_const_buffer_sequence<ConstBufferSequence>::value > = 0); /// Write a certain amount of data to a stream before returning. /** * This function is used to write a certain number of bytes of data to a stream. * The call will block until one of the following conditions is true: * * @li All of the data in the supplied buffers has been written. That is, the * bytes transferred is equal to the sum of the buffer sizes. * * @li The completion_condition function object returns 0. * * This operation is implemented in terms of zero or more calls to the stream's * write_some function. * * @param s The stream to which the data is to be written. The type must support * the SyncWriteStream concept. * * @param buffers One or more buffers containing the data to be written. The sum * of the buffer sizes indicates the maximum number of bytes to write to the * stream. * * @param completion_condition The function object to be called to determine * whether the write operation is complete. The signature of the function object * must be: * @code std::size_t completion_condition( * // Result of latest write_some operation. * const asio::error_code& error, * * // Number of bytes transferred so far. * std::size_t bytes_transferred * ); @endcode * A return value of 0 indicates that the write operation is complete. A * non-zero return value indicates the maximum number of bytes to be written on * the next call to the stream's write_some function. * * @returns The number of bytes transferred. * * @throws asio::system_error Thrown on failure. * * @par Example * To write a single data buffer use the @ref buffer function as follows: * @code asio::write(s, asio::buffer(data, size), * asio::transfer_at_least(32)); @endcode * See the @ref buffer documentation for information on writing multiple * buffers in one go, and how to use it with arrays, boost::array or * std::vector. */ template <typename SyncWriteStream, typename ConstBufferSequence, typename CompletionCondition> std::size_t write(SyncWriteStream& s, const ConstBufferSequence& buffers, CompletionCondition completion_condition, constraint_t< is_const_buffer_sequence<ConstBufferSequence>::value > = 0, constraint_t< is_completion_condition<CompletionCondition>::value > = 0); /// Write a certain amount of data to a stream before returning. /** * This function is used to write a certain number of bytes of data to a stream. * The call will block until one of the following conditions is true: * * @li All of the data in the supplied buffers has been written. That is, the * bytes transferred is equal to the sum of the buffer sizes. * * @li The completion_condition function object returns 0. * * This operation is implemented in terms of zero or more calls to the stream's * write_some function. * * @param s The stream to which the data is to be written. The type must support * the SyncWriteStream concept. * * @param buffers One or more buffers containing the data to be written. The sum * of the buffer sizes indicates the maximum number of bytes to write to the * stream. * * @param completion_condition The function object to be called to determine * whether the write operation is complete. The signature of the function object * must be: * @code std::size_t completion_condition( * // Result of latest write_some operation. * const asio::error_code& error, * * // Number of bytes transferred so far. * std::size_t bytes_transferred * ); @endcode * A return value of 0 indicates that the write operation is complete. A * non-zero return value indicates the maximum number of bytes to be written on * the next call to the stream's write_some function. * * @param ec Set to indicate what error occurred, if any. * * @returns The number of bytes written. If an error occurs, returns the total * number of bytes successfully transferred prior to the error. */ template <typename SyncWriteStream, typename ConstBufferSequence, typename CompletionCondition> std::size_t write(SyncWriteStream& s, const ConstBufferSequence& buffers, CompletionCondition completion_condition, asio::error_code& ec, constraint_t< is_const_buffer_sequence<ConstBufferSequence>::value > = 0, constraint_t< is_completion_condition<CompletionCondition>::value > = 0); #if !defined(ASIO_NO_DYNAMIC_BUFFER_V1) /// Write all of the supplied data to a stream before returning. /** * This function is used to write a certain number of bytes of data to a stream. * The call will block until one of the following conditions is true: * * @li All of the data in the supplied dynamic buffer sequence has been written. * * @li An error occurred. * * This operation is implemented in terms of zero or more calls to the stream's * write_some function. * * @param s The stream to which the data is to be written. The type must support * the SyncWriteStream concept. * * @param buffers The dynamic buffer sequence from which data will be written. * Successfully written data is automatically consumed from the buffers. * * @returns The number of bytes transferred. * * @throws asio::system_error Thrown on failure. * * @note This overload is equivalent to calling: * @code asio::write( * s, buffers, * asio::transfer_all()); @endcode */ template <typename SyncWriteStream, typename DynamicBuffer_v1> std::size_t write(SyncWriteStream& s, DynamicBuffer_v1&& buffers, constraint_t< is_dynamic_buffer_v1<decay_t<DynamicBuffer_v1>>::value > = 0, constraint_t< !is_dynamic_buffer_v2<decay_t<DynamicBuffer_v1>>::value > = 0); /// Write all of the supplied data to a stream before returning. /** * This function is used to write a certain number of bytes of data to a stream. * The call will block until one of the following conditions is true: * * @li All of the data in the supplied dynamic buffer sequence has been written. * * @li An error occurred. * * This operation is implemented in terms of zero or more calls to the stream's * write_some function. * * @param s The stream to which the data is to be written. The type must support * the SyncWriteStream concept. * * @param buffers The dynamic buffer sequence from which data will be written. * Successfully written data is automatically consumed from the buffers. * * @param ec Set to indicate what error occurred, if any. * * @returns The number of bytes transferred. * * @note This overload is equivalent to calling: * @code asio::write( * s, buffers, * asio::transfer_all(), ec); @endcode */ template <typename SyncWriteStream, typename DynamicBuffer_v1> std::size_t write(SyncWriteStream& s, DynamicBuffer_v1&& buffers, asio::error_code& ec, constraint_t< is_dynamic_buffer_v1<decay_t<DynamicBuffer_v1>>::value > = 0, constraint_t< !is_dynamic_buffer_v2<decay_t<DynamicBuffer_v1>>::value > = 0); /// Write a certain amount of data to a stream before returning. /** * This function is used to write a certain number of bytes of data to a stream. * The call will block until one of the following conditions is true: * * @li All of the data in the supplied dynamic buffer sequence has been written. * * @li The completion_condition function object returns 0. * * This operation is implemented in terms of zero or more calls to the stream's * write_some function. * * @param s The stream to which the data is to be written. The type must support * the SyncWriteStream concept. * * @param buffers The dynamic buffer sequence from which data will be written. * Successfully written data is automatically consumed from the buffers. * * @param completion_condition The function object to be called to determine * whether the write operation is complete. The signature of the function object * must be: * @code std::size_t completion_condition( * // Result of latest write_some operation. * const asio::error_code& error, * * // Number of bytes transferred so far. * std::size_t bytes_transferred * ); @endcode * A return value of 0 indicates that the write operation is complete. A * non-zero return value indicates the maximum number of bytes to be written on * the next call to the stream's write_some function. * * @returns The number of bytes transferred. * * @throws asio::system_error Thrown on failure. */ template <typename SyncWriteStream, typename DynamicBuffer_v1, typename CompletionCondition> std::size_t write(SyncWriteStream& s, DynamicBuffer_v1&& buffers, CompletionCondition completion_condition, constraint_t< is_dynamic_buffer_v1<decay_t<DynamicBuffer_v1>>::value > = 0, constraint_t< !is_dynamic_buffer_v2<decay_t<DynamicBuffer_v1>>::value > = 0, constraint_t< is_completion_condition<CompletionCondition>::value > = 0); /// Write a certain amount of data to a stream before returning. /** * This function is used to write a certain number of bytes of data to a stream. * The call will block until one of the following conditions is true: * * @li All of the data in the supplied dynamic buffer sequence has been written. * * @li The completion_condition function object returns 0. * * This operation is implemented in terms of zero or more calls to the stream's * write_some function. * * @param s The stream to which the data is to be written. The type must support * the SyncWriteStream concept. * * @param buffers The dynamic buffer sequence from which data will be written. * Successfully written data is automatically consumed from the buffers. * * @param completion_condition The function object to be called to determine * whether the write operation is complete. The signature of the function object * must be: * @code std::size_t completion_condition( * // Result of latest write_some operation. * const asio::error_code& error, * * // Number of bytes transferred so far. * std::size_t bytes_transferred * ); @endcode * A return value of 0 indicates that the write operation is complete. A * non-zero return value indicates the maximum number of bytes to be written on * the next call to the stream's write_some function. * * @param ec Set to indicate what error occurred, if any. * * @returns The number of bytes written. If an error occurs, returns the total * number of bytes successfully transferred prior to the error. */ template <typename SyncWriteStream, typename DynamicBuffer_v1, typename CompletionCondition> std::size_t write(SyncWriteStream& s, DynamicBuffer_v1&& buffers, CompletionCondition completion_condition, asio::error_code& ec, constraint_t< is_dynamic_buffer_v1<decay_t<DynamicBuffer_v1>>::value > = 0, constraint_t< !is_dynamic_buffer_v2<decay_t<DynamicBuffer_v1>>::value > = 0, constraint_t< is_completion_condition<CompletionCondition>::value > = 0); #if !defined(ASIO_NO_EXTENSIONS) #if !defined(ASIO_NO_IOSTREAM) /// Write all of the supplied data to a stream before returning. /** * This function is used to write a certain number of bytes of data to a stream. * The call will block until one of the following conditions is true: * * @li All of the data in the supplied basic_streambuf has been written. * * @li An error occurred. * * This operation is implemented in terms of zero or more calls to the stream's * write_some function. * * @param s The stream to which the data is to be written. The type must support * the SyncWriteStream concept. * * @param b The basic_streambuf object from which data will be written. * * @returns The number of bytes transferred. * * @throws asio::system_error Thrown on failure. * * @note This overload is equivalent to calling: * @code asio::write( * s, b, * asio::transfer_all()); @endcode */ template <typename SyncWriteStream, typename Allocator> std::size_t write(SyncWriteStream& s, basic_streambuf<Allocator>& b); /// Write all of the supplied data to a stream before returning. /** * This function is used to write a certain number of bytes of data to a stream. * The call will block until one of the following conditions is true: * * @li All of the data in the supplied basic_streambuf has been written. * * @li An error occurred. * * This operation is implemented in terms of zero or more calls to the stream's * write_some function. * * @param s The stream to which the data is to be written. The type must support * the SyncWriteStream concept. * * @param b The basic_streambuf object from which data will be written. * * @param ec Set to indicate what error occurred, if any. * * @returns The number of bytes transferred. * * @note This overload is equivalent to calling: * @code asio::write( * s, b, * asio::transfer_all(), ec); @endcode */ template <typename SyncWriteStream, typename Allocator> std::size_t write(SyncWriteStream& s, basic_streambuf<Allocator>& b, asio::error_code& ec); /// Write a certain amount of data to a stream before returning. /** * This function is used to write a certain number of bytes of data to a stream. * The call will block until one of the following conditions is true: * * @li All of the data in the supplied basic_streambuf has been written. * * @li The completion_condition function object returns 0. * * This operation is implemented in terms of zero or more calls to the stream's * write_some function. * * @param s The stream to which the data is to be written. The type must support * the SyncWriteStream concept. * * @param b The basic_streambuf object from which data will be written. * * @param completion_condition The function object to be called to determine * whether the write operation is complete. The signature of the function object * must be: * @code std::size_t completion_condition( * // Result of latest write_some operation. * const asio::error_code& error, * * // Number of bytes transferred so far. * std::size_t bytes_transferred * ); @endcode * A return value of 0 indicates that the write operation is complete. A * non-zero return value indicates the maximum number of bytes to be written on * the next call to the stream's write_some function. * * @returns The number of bytes transferred. * * @throws asio::system_error Thrown on failure. */ template <typename SyncWriteStream, typename Allocator, typename CompletionCondition> std::size_t write(SyncWriteStream& s, basic_streambuf<Allocator>& b, CompletionCondition completion_condition, constraint_t< is_completion_condition<CompletionCondition>::value > = 0); /// Write a certain amount of data to a stream before returning. /** * This function is used to write a certain number of bytes of data to a stream. * The call will block until one of the following conditions is true: * * @li All of the data in the supplied basic_streambuf has been written. * * @li The completion_condition function object returns 0. * * This operation is implemented in terms of zero or more calls to the stream's * write_some function. * * @param s The stream to which the data is to be written. The type must support * the SyncWriteStream concept. * * @param b The basic_streambuf object from which data will be written. * * @param completion_condition The function object to be called to determine * whether the write operation is complete. The signature of the function object * must be: * @code std::size_t completion_condition( * // Result of latest write_some operation. * const asio::error_code& error, * * // Number of bytes transferred so far. * std::size_t bytes_transferred * ); @endcode * A return value of 0 indicates that the write operation is complete. A * non-zero return value indicates the maximum number of bytes to be written on * the next call to the stream's write_some function. * * @param ec Set to indicate what error occurred, if any. * * @returns The number of bytes written. If an error occurs, returns the total * number of bytes successfully transferred prior to the error. */ template <typename SyncWriteStream, typename Allocator, typename CompletionCondition> std::size_t write(SyncWriteStream& s, basic_streambuf<Allocator>& b, CompletionCondition completion_condition, asio::error_code& ec, constraint_t< is_completion_condition<CompletionCondition>::value > = 0); #endif // !defined(ASIO_NO_IOSTREAM) #endif // !defined(ASIO_NO_EXTENSIONS) #endif // !defined(ASIO_NO_DYNAMIC_BUFFER_V1) /// Write all of the supplied data to a stream before returning. /** * This function is used to write a certain number of bytes of data to a stream. * The call will block until one of the following conditions is true: * * @li All of the data in the supplied dynamic buffer sequence has been written. * * @li An error occurred. * * This operation is implemented in terms of zero or more calls to the stream's * write_some function. * * @param s The stream to which the data is to be written. The type must support * the SyncWriteStream concept. * * @param buffers The dynamic buffer sequence from which data will be written. * Successfully written data is automatically consumed from the buffers. * * @returns The number of bytes transferred. * * @throws asio::system_error Thrown on failure. * * @note This overload is equivalent to calling: * @code asio::write( * s, buffers, * asio::transfer_all()); @endcode */ template <typename SyncWriteStream, typename DynamicBuffer_v2> std::size_t write(SyncWriteStream& s, DynamicBuffer_v2 buffers, constraint_t< is_dynamic_buffer_v2<DynamicBuffer_v2>::value > = 0); /// Write all of the supplied data to a stream before returning. /** * This function is used to write a certain number of bytes of data to a stream. * The call will block until one of the following conditions is true: * * @li All of the data in the supplied dynamic buffer sequence has been written. * * @li An error occurred. * * This operation is implemented in terms of zero or more calls to the stream's * write_some function. * * @param s The stream to which the data is to be written. The type must support * the SyncWriteStream concept. * * @param buffers The dynamic buffer sequence from which data will be written. * Successfully written data is automatically consumed from the buffers. * * @param ec Set to indicate what error occurred, if any. * * @returns The number of bytes transferred. * * @note This overload is equivalent to calling: * @code asio::write( * s, buffers, * asio::transfer_all(), ec); @endcode */ template <typename SyncWriteStream, typename DynamicBuffer_v2> std::size_t write(SyncWriteStream& s, DynamicBuffer_v2 buffers, asio::error_code& ec, constraint_t< is_dynamic_buffer_v2<DynamicBuffer_v2>::value > = 0); /// Write a certain amount of data to a stream before returning. /** * This function is used to write a certain number of bytes of data to a stream. * The call will block until one of the following conditions is true: * * @li All of the data in the supplied dynamic buffer sequence has been written. * * @li The completion_condition function object returns 0. * * This operation is implemented in terms of zero or more calls to the stream's * write_some function. * * @param s The stream to which the data is to be written. The type must support * the SyncWriteStream concept. * * @param buffers The dynamic buffer sequence from which data will be written. * Successfully written data is automatically consumed from the buffers. * * @param completion_condition The function object to be called to determine * whether the write operation is complete. The signature of the function object * must be: * @code std::size_t completion_condition( * // Result of latest write_some operation. * const asio::error_code& error, * * // Number of bytes transferred so far. * std::size_t bytes_transferred * ); @endcode * A return value of 0 indicates that the write operation is complete. A * non-zero return value indicates the maximum number of bytes to be written on * the next call to the stream's write_some function. * * @returns The number of bytes transferred. * * @throws asio::system_error Thrown on failure. */ template <typename SyncWriteStream, typename DynamicBuffer_v2, typename CompletionCondition> std::size_t write(SyncWriteStream& s, DynamicBuffer_v2 buffers, CompletionCondition completion_condition, constraint_t< is_dynamic_buffer_v2<DynamicBuffer_v2>::value > = 0, constraint_t< is_completion_condition<CompletionCondition>::value > = 0); /// Write a certain amount of data to a stream before returning. /** * This function is used to write a certain number of bytes of data to a stream. * The call will block until one of the following conditions is true: * * @li All of the data in the supplied dynamic buffer sequence has been written. * * @li The completion_condition function object returns 0. * * This operation is implemented in terms of zero or more calls to the stream's * write_some function. * * @param s The stream to which the data is to be written. The type must support * the SyncWriteStream concept. * * @param buffers The dynamic buffer sequence from which data will be written. * Successfully written data is automatically consumed from the buffers. * * @param completion_condition The function object to be called to determine * whether the write operation is complete. The signature of the function object * must be: * @code std::size_t completion_condition( * // Result of latest write_some operation. * const asio::error_code& error, * * // Number of bytes transferred so far. * std::size_t bytes_transferred * ); @endcode * A return value of 0 indicates that the write operation is complete. A * non-zero return value indicates the maximum number of bytes to be written on * the next call to the stream's write_some function. * * @param ec Set to indicate what error occurred, if any. * * @returns The number of bytes written. If an error occurs, returns the total * number of bytes successfully transferred prior to the error. */ template <typename SyncWriteStream, typename DynamicBuffer_v2, typename CompletionCondition> std::size_t write(SyncWriteStream& s, DynamicBuffer_v2 buffers, CompletionCondition completion_condition, asio::error_code& ec, constraint_t< is_dynamic_buffer_v2<DynamicBuffer_v2>::value > = 0, constraint_t< is_completion_condition<CompletionCondition>::value > = 0); /*@}*/ /** * @defgroup async_write asio::async_write * * @brief The @c async_write function is a composed asynchronous operation that * writes a certain amount of data to a stream before completion. */ /*@{*/ /// Start an asynchronous operation to write all of the supplied data to a /// stream. /** * This function is used to asynchronously write a certain number of bytes of * data to a stream. It is an initiating function for an @ref * asynchronous_operation, and always returns immediately. The asynchronous * operation will continue until one of the following conditions is true: * * @li All of the data in the supplied buffers has been written. That is, the * bytes transferred is equal to the sum of the buffer sizes. * * @li An error occurred. * * This operation is implemented in terms of zero or more calls to the stream's * async_write_some function, and is known as a <em>composed operation</em>. The * program must ensure that the stream performs no other write operations (such * as async_write, the stream's async_write_some function, or any other composed * operations that perform writes) until this operation completes. * * @param s The stream to which the data is to be written. The type must support * the AsyncWriteStream concept. * * @param buffers One or more buffers containing the data to be written. * Although the buffers object may be copied as necessary, ownership of the * underlying memory blocks is retained by the caller, which must guarantee * that they remain valid until the completion handler is called. * * @param token The @ref completion_token that will be used to produce a * completion handler, which will be called when the write completes. * Potential completion tokens include @ref use_future, @ref use_awaitable, * @ref yield_context, or a function object with the correct completion * signature. The function signature of the completion handler must be: * @code void handler( * // Result of operation. * const asio::error_code& error, * * // Number of bytes written from the buffers. If an error * // occurred, this will be less than the sum of the buffer sizes. * std::size_t bytes_transferred * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the completion handler will not be invoked from within this function. * On immediate completion, invocation of the handler will be performed in a * manner equivalent to using asio::async_immediate(). * * @par Completion Signature * @code void(asio::error_code, std::size_t) @endcode * * @par Example * To write a single data buffer use the @ref buffer function as follows: * @code * asio::async_write(s, asio::buffer(data, size), handler); * @endcode * See the @ref buffer documentation for information on writing multiple * buffers in one go, and how to use it with arrays, boost::array or * std::vector. * * @par Per-Operation Cancellation * This asynchronous operation supports cancellation for the following * asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * if they are also supported by the @c AsyncWriteStream type's * @c async_write_some operation. */ template <typename AsyncWriteStream, typename ConstBufferSequence, ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code, std::size_t)) WriteToken = default_completion_token_t<typename AsyncWriteStream::executor_type>> inline auto async_write(AsyncWriteStream& s, const ConstBufferSequence& buffers, WriteToken&& token = default_completion_token_t<typename AsyncWriteStream::executor_type>(), constraint_t< is_const_buffer_sequence<ConstBufferSequence>::value > = 0, constraint_t< !is_completion_condition<decay_t<WriteToken>>::value > = 0) -> decltype( async_initiate<WriteToken, void (asio::error_code, std::size_t)>( declval<detail::initiate_async_write<AsyncWriteStream>>(), token, buffers, transfer_all())) { return async_initiate<WriteToken, void (asio::error_code, std::size_t)>( detail::initiate_async_write<AsyncWriteStream>(s), token, buffers, transfer_all()); } /// Start an asynchronous operation to write a certain amount of data to a /// stream. /** * This function is used to asynchronously write a certain number of bytes of * data to a stream. It is an initiating function for an @ref * asynchronous_operation, and always returns immediately. The asynchronous * operation will continue until one of the following conditions is true: * * @li All of the data in the supplied buffers has been written. That is, the * bytes transferred is equal to the sum of the buffer sizes. * * @li The completion_condition function object returns 0. * * This operation is implemented in terms of zero or more calls to the stream's * async_write_some function, and is known as a <em>composed operation</em>. The * program must ensure that the stream performs no other write operations (such * as async_write, the stream's async_write_some function, or any other composed * operations that perform writes) until this operation completes. * * @param s The stream to which the data is to be written. The type must support * the AsyncWriteStream concept. * * @param buffers One or more buffers containing the data to be written. * Although the buffers object may be copied as necessary, ownership of the * underlying memory blocks is retained by the caller, which must guarantee * that they remain valid until the completion handler is called. * * @param completion_condition The function object to be called to determine * whether the write operation is complete. The signature of the function object * must be: * @code std::size_t completion_condition( * // Result of latest async_write_some operation. * const asio::error_code& error, * * // Number of bytes transferred so far. * std::size_t bytes_transferred * ); @endcode * A return value of 0 indicates that the write operation is complete. A * non-zero return value indicates the maximum number of bytes to be written on * the next call to the stream's async_write_some function. * * @param token The @ref completion_token that will be used to produce a * completion handler, which will be called when the write completes. * Potential completion tokens include @ref use_future, @ref use_awaitable, * @ref yield_context, or a function object with the correct completion * signature. The function signature of the completion handler must be: * @code void handler( * // Result of operation. * const asio::error_code& error, * * // Number of bytes written from the buffers. If an error * // occurred, this will be less than the sum of the buffer sizes. * std::size_t bytes_transferred * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the completion handler will not be invoked from within this function. * On immediate completion, invocation of the handler will be performed in a * manner equivalent to using asio::async_immediate(). * * @par Completion Signature * @code void(asio::error_code, std::size_t) @endcode * * @par Example * To write a single data buffer use the @ref buffer function as follows: * @code asio::async_write(s, * asio::buffer(data, size), * asio::transfer_at_least(32), * handler); @endcode * See the @ref buffer documentation for information on writing multiple * buffers in one go, and how to use it with arrays, boost::array or * std::vector. * * @par Per-Operation Cancellation * This asynchronous operation supports cancellation for the following * asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * if they are also supported by the @c AsyncWriteStream type's * @c async_write_some operation. */ template <typename AsyncWriteStream, typename ConstBufferSequence, typename CompletionCondition, ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code, std::size_t)) WriteToken = default_completion_token_t<typename AsyncWriteStream::executor_type>> inline auto async_write(AsyncWriteStream& s, const ConstBufferSequence& buffers, CompletionCondition completion_condition, WriteToken&& token = default_completion_token_t<typename AsyncWriteStream::executor_type>(), constraint_t< is_const_buffer_sequence<ConstBufferSequence>::value > = 0, constraint_t< is_completion_condition<CompletionCondition>::value > = 0) -> decltype( async_initiate<WriteToken, void (asio::error_code, std::size_t)>( declval<detail::initiate_async_write<AsyncWriteStream>>(), token, buffers, static_cast<CompletionCondition&&>(completion_condition))) { return async_initiate<WriteToken, void (asio::error_code, std::size_t)>( detail::initiate_async_write<AsyncWriteStream>(s), token, buffers, static_cast<CompletionCondition&&>(completion_condition)); } #if !defined(ASIO_NO_DYNAMIC_BUFFER_V1) /// Start an asynchronous operation to write all of the supplied data to a /// stream. /** * This function is used to asynchronously write a certain number of bytes of * data to a stream. It is an initiating function for an @ref * asynchronous_operation, and always returns immediately. The asynchronous * operation will continue until one of the following conditions is true: * * @li All of the data in the supplied dynamic buffer sequence has been written. * * @li An error occurred. * * This operation is implemented in terms of zero or more calls to the stream's * async_write_some function, and is known as a <em>composed operation</em>. The * program must ensure that the stream performs no other write operations (such * as async_write, the stream's async_write_some function, or any other composed * operations that perform writes) until this operation completes. * * @param s The stream to which the data is to be written. The type must support * the AsyncWriteStream concept. * * @param buffers The dynamic buffer sequence from which data will be written. * Although the buffers object may be copied as necessary, ownership of the * underlying memory blocks is retained by the caller, which must guarantee * that they remain valid until the completion handler is called. Successfully * written data is automatically consumed from the buffers. * * @param token The @ref completion_token that will be used to produce a * completion handler, which will be called when the write completes. * Potential completion tokens include @ref use_future, @ref use_awaitable, * @ref yield_context, or a function object with the correct completion * signature. The function signature of the completion handler must be: * @code void handler( * // Result of operation. * const asio::error_code& error, * * // Number of bytes written from the buffers. If an error * // occurred, this will be less than the sum of the buffer sizes. * std::size_t bytes_transferred * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the completion handler will not be invoked from within this function. * On immediate completion, invocation of the handler will be performed in a * manner equivalent to using asio::async_immediate(). * * @par Completion Signature * @code void(asio::error_code, std::size_t) @endcode * * @par Per-Operation Cancellation * This asynchronous operation supports cancellation for the following * asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * if they are also supported by the @c AsyncWriteStream type's * @c async_write_some operation. */ template <typename AsyncWriteStream, typename DynamicBuffer_v1, ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code, std::size_t)) WriteToken = default_completion_token_t<typename AsyncWriteStream::executor_type>> inline auto async_write(AsyncWriteStream& s, DynamicBuffer_v1&& buffers, WriteToken&& token = default_completion_token_t<typename AsyncWriteStream::executor_type>(), constraint_t< is_dynamic_buffer_v1<decay_t<DynamicBuffer_v1>>::value > = 0, constraint_t< !is_dynamic_buffer_v2<decay_t<DynamicBuffer_v1>>::value > = 0, constraint_t< !is_completion_condition<decay_t<WriteToken>>::value > = 0) -> decltype( async_initiate<WriteToken, void (asio::error_code, std::size_t)>( declval<detail::initiate_async_write_dynbuf_v1<AsyncWriteStream>>(), token, static_cast<DynamicBuffer_v1&&>(buffers), transfer_all())) { return async_initiate<WriteToken, void (asio::error_code, std::size_t)>( detail::initiate_async_write_dynbuf_v1<AsyncWriteStream>(s), token, static_cast<DynamicBuffer_v1&&>(buffers), transfer_all()); } /// Start an asynchronous operation to write a certain amount of data to a /// stream. /** * This function is used to asynchronously write a certain number of bytes of * data to a stream. It is an initiating function for an @ref * asynchronous_operation, and always returns immediately. The asynchronous * operation will continue until one of the following conditions is true: * * @li All of the data in the supplied dynamic buffer sequence has been written. * * @li The completion_condition function object returns 0. * * This operation is implemented in terms of zero or more calls to the stream's * async_write_some function, and is known as a <em>composed operation</em>. The * program must ensure that the stream performs no other write operations (such * as async_write, the stream's async_write_some function, or any other composed * operations that perform writes) until this operation completes. * * @param s The stream to which the data is to be written. The type must support * the AsyncWriteStream concept. * * @param buffers The dynamic buffer sequence from which data will be written. * Although the buffers object may be copied as necessary, ownership of the * underlying memory blocks is retained by the caller, which must guarantee * that they remain valid until the completion handler is called. Successfully * written data is automatically consumed from the buffers. * * @param completion_condition The function object to be called to determine * whether the write operation is complete. The signature of the function object * must be: * @code std::size_t completion_condition( * // Result of latest async_write_some operation. * const asio::error_code& error, * * // Number of bytes transferred so far. * std::size_t bytes_transferred * ); @endcode * A return value of 0 indicates that the write operation is complete. A * non-zero return value indicates the maximum number of bytes to be written on * the next call to the stream's async_write_some function. * * @param token The @ref completion_token that will be used to produce a * completion handler, which will be called when the write completes. * Potential completion tokens include @ref use_future, @ref use_awaitable, * @ref yield_context, or a function object with the correct completion * signature. The function signature of the completion handler must be: * @code void handler( * // Result of operation. * const asio::error_code& error, * * // Number of bytes written from the buffers. If an error * // occurred, this will be less than the sum of the buffer sizes. * std::size_t bytes_transferred * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the completion handler will not be invoked from within this function. * On immediate completion, invocation of the handler will be performed in a * manner equivalent to using asio::async_immediate(). * * @par Completion Signature * @code void(asio::error_code, std::size_t) @endcode * * @par Per-Operation Cancellation * This asynchronous operation supports cancellation for the following * asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * if they are also supported by the @c AsyncWriteStream type's * @c async_write_some operation. */ template <typename AsyncWriteStream, typename DynamicBuffer_v1, typename CompletionCondition, ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code, std::size_t)) WriteToken = default_completion_token_t<typename AsyncWriteStream::executor_type>> inline auto async_write(AsyncWriteStream& s, DynamicBuffer_v1&& buffers, CompletionCondition completion_condition, WriteToken&& token = default_completion_token_t<typename AsyncWriteStream::executor_type>(), constraint_t< is_dynamic_buffer_v1<decay_t<DynamicBuffer_v1>>::value > = 0, constraint_t< !is_dynamic_buffer_v2<decay_t<DynamicBuffer_v1>>::value > = 0, constraint_t< is_completion_condition<CompletionCondition>::value > = 0) -> decltype( async_initiate<WriteToken, void (asio::error_code, std::size_t)>( declval<detail::initiate_async_write_dynbuf_v1<AsyncWriteStream>>(), token, static_cast<DynamicBuffer_v1&&>(buffers), static_cast<CompletionCondition&&>(completion_condition))) { return async_initiate<WriteToken, void (asio::error_code, std::size_t)>( detail::initiate_async_write_dynbuf_v1<AsyncWriteStream>(s), token, static_cast<DynamicBuffer_v1&&>(buffers), static_cast<CompletionCondition&&>(completion_condition)); } #if !defined(ASIO_NO_EXTENSIONS) #if !defined(ASIO_NO_IOSTREAM) /// Start an asynchronous operation to write all of the supplied data to a /// stream. /** * This function is used to asynchronously write a certain number of bytes of * data to a stream. It is an initiating function for an @ref * asynchronous_operation, and always returns immediately. The asynchronous * operation will continue until one of the following conditions is true: * * @li All of the data in the supplied basic_streambuf has been written. * * @li An error occurred. * * This operation is implemented in terms of zero or more calls to the stream's * async_write_some function, and is known as a <em>composed operation</em>. The * program must ensure that the stream performs no other write operations (such * as async_write, the stream's async_write_some function, or any other composed * operations that perform writes) until this operation completes. * * @param s The stream to which the data is to be written. The type must support * the AsyncWriteStream concept. * * @param b A basic_streambuf object from which data will be written. Ownership * of the streambuf is retained by the caller, which must guarantee that it * remains valid until the completion handler is called. * * @param token The @ref completion_token that will be used to produce a * completion handler, which will be called when the write completes. * Potential completion tokens include @ref use_future, @ref use_awaitable, * @ref yield_context, or a function object with the correct completion * signature. The function signature of the completion handler must be: * @code void handler( * // Result of operation. * const asio::error_code& error, * * // Number of bytes written from the buffers. If an error * // occurred, this will be less than the sum of the buffer sizes. * std::size_t bytes_transferred * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the completion handler will not be invoked from within this function. * On immediate completion, invocation of the handler will be performed in a * manner equivalent to using asio::async_immediate(). * * @par Completion Signature * @code void(asio::error_code, std::size_t) @endcode * * @par Per-Operation Cancellation * This asynchronous operation supports cancellation for the following * asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * if they are also supported by the @c AsyncWriteStream type's * @c async_write_some operation. */ template <typename AsyncWriteStream, typename Allocator, ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code, std::size_t)) WriteToken = default_completion_token_t<typename AsyncWriteStream::executor_type>> inline auto async_write(AsyncWriteStream& s, basic_streambuf<Allocator>& b, WriteToken&& token = default_completion_token_t<typename AsyncWriteStream::executor_type>(), constraint_t< !is_completion_condition<decay_t<WriteToken>>::value > = 0) -> decltype( async_initiate<WriteToken, void (asio::error_code, std::size_t)>( declval<detail::initiate_async_write_dynbuf_v1<AsyncWriteStream>>(), token, basic_streambuf_ref<Allocator>(b), transfer_all())) { return async_initiate<WriteToken, void (asio::error_code, std::size_t)>( detail::initiate_async_write_dynbuf_v1<AsyncWriteStream>(s), token, basic_streambuf_ref<Allocator>(b), transfer_all()); } /// Start an asynchronous operation to write a certain amount of data to a /// stream. /** * This function is used to asynchronously write a certain number of bytes of * data to a stream. It is an initiating function for an @ref * asynchronous_operation, and always returns immediately. The asynchronous * operation will continue until one of the following conditions is true: * * @li All of the data in the supplied basic_streambuf has been written. * * @li The completion_condition function object returns 0. * * This operation is implemented in terms of zero or more calls to the stream's * async_write_some function, and is known as a <em>composed operation</em>. The * program must ensure that the stream performs no other write operations (such * as async_write, the stream's async_write_some function, or any other composed * operations that perform writes) until this operation completes. * * @param s The stream to which the data is to be written. The type must support * the AsyncWriteStream concept. * * @param b A basic_streambuf object from which data will be written. Ownership * of the streambuf is retained by the caller, which must guarantee that it * remains valid until the completion handler is called. * * @param completion_condition The function object to be called to determine * whether the write operation is complete. The signature of the function object * must be: * @code std::size_t completion_condition( * // Result of latest async_write_some operation. * const asio::error_code& error, * * // Number of bytes transferred so far. * std::size_t bytes_transferred * ); @endcode * A return value of 0 indicates that the write operation is complete. A * non-zero return value indicates the maximum number of bytes to be written on * the next call to the stream's async_write_some function. * * @param token The @ref completion_token that will be used to produce a * completion handler, which will be called when the write completes. * Potential completion tokens include @ref use_future, @ref use_awaitable, * @ref yield_context, or a function object with the correct completion * signature. The function signature of the completion handler must be: * @code void handler( * // Result of operation. * const asio::error_code& error, * * // Number of bytes written from the buffers. If an error * // occurred, this will be less than the sum of the buffer sizes. * std::size_t bytes_transferred * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the completion handler will not be invoked from within this function. * On immediate completion, invocation of the handler will be performed in a * manner equivalent to using asio::async_immediate(). * * @par Completion Signature * @code void(asio::error_code, std::size_t) @endcode * * @par Per-Operation Cancellation * This asynchronous operation supports cancellation for the following * asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * if they are also supported by the @c AsyncWriteStream type's * @c async_write_some operation. */ template <typename AsyncWriteStream, typename Allocator, typename CompletionCondition, ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code, std::size_t)) WriteToken = default_completion_token_t<typename AsyncWriteStream::executor_type>> inline auto async_write(AsyncWriteStream& s, basic_streambuf<Allocator>& b, CompletionCondition completion_condition, WriteToken&& token = default_completion_token_t<typename AsyncWriteStream::executor_type>(), constraint_t< is_completion_condition<CompletionCondition>::value > = 0) -> decltype( async_initiate<WriteToken, void (asio::error_code, std::size_t)>( declval<detail::initiate_async_write_dynbuf_v1<AsyncWriteStream>>(), token, basic_streambuf_ref<Allocator>(b), static_cast<CompletionCondition&&>(completion_condition))) { return async_initiate<WriteToken, void (asio::error_code, std::size_t)>( detail::initiate_async_write_dynbuf_v1<AsyncWriteStream>(s), token, basic_streambuf_ref<Allocator>(b), static_cast<CompletionCondition&&>(completion_condition)); } #endif // !defined(ASIO_NO_IOSTREAM) #endif // !defined(ASIO_NO_EXTENSIONS) #endif // !defined(ASIO_NO_DYNAMIC_BUFFER_V1) /// Start an asynchronous operation to write all of the supplied data to a /// stream. /** * This function is used to asynchronously write a certain number of bytes of * data to a stream. It is an initiating function for an @ref * asynchronous_operation, and always returns immediately. The asynchronous * operation will continue until one of the following conditions is true: * * @li All of the data in the supplied dynamic buffer sequence has been written. * * @li An error occurred. * * This operation is implemented in terms of zero or more calls to the stream's * async_write_some function, and is known as a <em>composed operation</em>. The * program must ensure that the stream performs no other write operations (such * as async_write, the stream's async_write_some function, or any other composed * operations that perform writes) until this operation completes. * * @param s The stream to which the data is to be written. The type must support * the AsyncWriteStream concept. * * @param buffers The dynamic buffer sequence from which data will be written. * Although the buffers object may be copied as necessary, ownership of the * underlying memory blocks is retained by the caller, which must guarantee * that they remain valid until the completion handler is called. Successfully * written data is automatically consumed from the buffers. * * @param token The @ref completion_token that will be used to produce a * completion handler, which will be called when the write completes. * Potential completion tokens include @ref use_future, @ref use_awaitable, * @ref yield_context, or a function object with the correct completion * signature. The function signature of the completion handler must be: * @code void handler( * // Result of operation. * const asio::error_code& error, * * // Number of bytes written from the buffers. If an error * // occurred, this will be less than the sum of the buffer sizes. * std::size_t bytes_transferred * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the completion handler will not be invoked from within this function. * On immediate completion, invocation of the handler will be performed in a * manner equivalent to using asio::async_immediate(). * * @par Completion Signature * @code void(asio::error_code, std::size_t) @endcode * * @par Per-Operation Cancellation * This asynchronous operation supports cancellation for the following * asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * if they are also supported by the @c AsyncWriteStream type's * @c async_write_some operation. */ template <typename AsyncWriteStream, typename DynamicBuffer_v2, ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code, std::size_t)) WriteToken = default_completion_token_t<typename AsyncWriteStream::executor_type>> inline auto async_write(AsyncWriteStream& s, DynamicBuffer_v2 buffers, WriteToken&& token = default_completion_token_t<typename AsyncWriteStream::executor_type>(), constraint_t< is_dynamic_buffer_v2<DynamicBuffer_v2>::value > = 0, constraint_t< !is_completion_condition<decay_t<WriteToken>>::value > = 0) -> decltype( async_initiate<WriteToken, void (asio::error_code, std::size_t)>( declval<detail::initiate_async_write_dynbuf_v2<AsyncWriteStream>>(), token, static_cast<DynamicBuffer_v2&&>(buffers), transfer_all())) { return async_initiate<WriteToken, void (asio::error_code, std::size_t)>( detail::initiate_async_write_dynbuf_v2<AsyncWriteStream>(s), token, static_cast<DynamicBuffer_v2&&>(buffers), transfer_all()); } /// Start an asynchronous operation to write a certain amount of data to a /// stream. /** * This function is used to asynchronously write a certain number of bytes of * data to a stream. It is an initiating function for an @ref * asynchronous_operation, and always returns immediately. The asynchronous * operation will continue until one of the following conditions is true: * * @li All of the data in the supplied dynamic buffer sequence has been written. * * @li The completion_condition function object returns 0. * * This operation is implemented in terms of zero or more calls to the stream's * async_write_some function, and is known as a <em>composed operation</em>. The * program must ensure that the stream performs no other write operations (such * as async_write, the stream's async_write_some function, or any other composed * operations that perform writes) until this operation completes. * * @param s The stream to which the data is to be written. The type must support * the AsyncWriteStream concept. * * @param buffers The dynamic buffer sequence from which data will be written. * Although the buffers object may be copied as necessary, ownership of the * underlying memory blocks is retained by the caller, which must guarantee * that they remain valid until the completion handler is called. Successfully * written data is automatically consumed from the buffers. * * @param completion_condition The function object to be called to determine * whether the write operation is complete. The signature of the function object * must be: * @code std::size_t completion_condition( * // Result of latest async_write_some operation. * const asio::error_code& error, * * // Number of bytes transferred so far. * std::size_t bytes_transferred * ); @endcode * A return value of 0 indicates that the write operation is complete. A * non-zero return value indicates the maximum number of bytes to be written on * the next call to the stream's async_write_some function. * * @param token The @ref completion_token that will be used to produce a * completion handler, which will be called when the write completes. * Potential completion tokens include @ref use_future, @ref use_awaitable, * @ref yield_context, or a function object with the correct completion * signature. The function signature of the completion handler must be: * @code void handler( * // Result of operation. * const asio::error_code& error, * * // Number of bytes written from the buffers. If an error * // occurred, this will be less than the sum of the buffer sizes. * std::size_t bytes_transferred * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the completion handler will not be invoked from within this function. * On immediate completion, invocation of the handler will be performed in a * manner equivalent to using asio::async_immediate(). * * @par Completion Signature * @code void(asio::error_code, std::size_t) @endcode * * @par Per-Operation Cancellation * This asynchronous operation supports cancellation for the following * asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * if they are also supported by the @c AsyncWriteStream type's * @c async_write_some operation. */ template <typename AsyncWriteStream, typename DynamicBuffer_v2, typename CompletionCondition, ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code, std::size_t)) WriteToken = default_completion_token_t<typename AsyncWriteStream::executor_type>> inline auto async_write(AsyncWriteStream& s, DynamicBuffer_v2 buffers, CompletionCondition completion_condition, WriteToken&& token = default_completion_token_t<typename AsyncWriteStream::executor_type>(), constraint_t< is_dynamic_buffer_v2<DynamicBuffer_v2>::value > = 0, constraint_t< is_completion_condition<CompletionCondition>::value > = 0) -> decltype( async_initiate<WriteToken, void (asio::error_code, std::size_t)>( declval<detail::initiate_async_write_dynbuf_v2<AsyncWriteStream>>(), token, static_cast<DynamicBuffer_v2&&>(buffers), static_cast<CompletionCondition&&>(completion_condition))) { return async_initiate<WriteToken, void (asio::error_code, std::size_t)>( detail::initiate_async_write_dynbuf_v2<AsyncWriteStream>(s), token, static_cast<DynamicBuffer_v2&&>(buffers), static_cast<CompletionCondition&&>(completion_condition)); } /*@}*/ } // namespace asio #include "asio/detail/pop_options.hpp" #include "asio/impl/write.hpp" #endif // ASIO_WRITE_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/is_executor.hpp
// // is_executor.hpp // ~~~~~~~~~~~~~~~ // // 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) // #ifndef ASIO_IS_EXECUTOR_HPP #define ASIO_IS_EXECUTOR_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include "asio/detail/is_executor.hpp" #include "asio/detail/push_options.hpp" namespace asio { /// The is_executor trait detects whether a type T meets the Executor type /// requirements. /** * Class template @c is_executor is a UnaryTypeTrait that is derived from @c * true_type if the type @c T meets the syntactic requirements for Executor, * otherwise @c false_type. */ template <typename T> struct is_executor #if defined(GENERATING_DOCUMENTATION) : integral_constant<bool, automatically_determined> #else // defined(GENERATING_DOCUMENTATION) : asio::detail::is_executor<T> #endif // defined(GENERATING_DOCUMENTATION) { }; } // namespace asio #include "asio/detail/pop_options.hpp" #endif // ASIO_IS_EXECUTOR_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/is_read_buffered.hpp
// // is_read_buffered.hpp // ~~~~~~~~~~~~~~~~~~~~ // // 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) // #ifndef ASIO_IS_READ_BUFFERED_HPP #define ASIO_IS_READ_BUFFERED_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include "asio/buffered_read_stream_fwd.hpp" #include "asio/buffered_stream_fwd.hpp" #include "asio/detail/push_options.hpp" namespace asio { namespace detail { template <typename Stream> char is_read_buffered_helper(buffered_stream<Stream>* s); template <typename Stream> char is_read_buffered_helper(buffered_read_stream<Stream>* s); struct is_read_buffered_big_type { char data[10]; }; is_read_buffered_big_type is_read_buffered_helper(...); } // namespace detail /// The is_read_buffered class is a traits class that may be used to determine /// whether a stream type supports buffering of read data. template <typename Stream> class is_read_buffered { public: #if defined(GENERATING_DOCUMENTATION) /// The value member is true only if the Stream type supports buffering of /// read data. static const bool value; #else ASIO_STATIC_CONSTANT(bool, value = sizeof(detail::is_read_buffered_helper((Stream*)0)) == 1); #endif }; } // namespace asio #include "asio/detail/pop_options.hpp" #endif // ASIO_IS_READ_BUFFERED_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/time_traits.hpp
// // time_traits.hpp // ~~~~~~~~~~~~~~~ // // 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) // #ifndef ASIO_TIME_TRAITS_HPP #define ASIO_TIME_TRAITS_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/socket_types.hpp" // Must come before posix_time. #if defined(ASIO_HAS_BOOST_DATE_TIME) \ || defined(GENERATING_DOCUMENTATION) #include <boost/date_time/posix_time/posix_time_types.hpp> #include "asio/detail/push_options.hpp" namespace asio { /// Time traits suitable for use with the deadline timer. template <typename Time> struct time_traits; /// Time traits specialised for posix_time. template <> struct time_traits<boost::posix_time::ptime> { /// The time type. typedef boost::posix_time::ptime time_type; /// The duration type. typedef boost::posix_time::time_duration duration_type; /// Get the current time. static time_type now() { #if defined(BOOST_DATE_TIME_HAS_HIGH_PRECISION_CLOCK) return boost::posix_time::microsec_clock::universal_time(); #else // defined(BOOST_DATE_TIME_HAS_HIGH_PRECISION_CLOCK) return boost::posix_time::second_clock::universal_time(); #endif // defined(BOOST_DATE_TIME_HAS_HIGH_PRECISION_CLOCK) } /// Add a duration to a time. static time_type add(const time_type& t, const duration_type& d) { return t + d; } /// Subtract one time from another. static duration_type subtract(const time_type& t1, const time_type& t2) { return t1 - t2; } /// Test whether one time is less than another. static bool less_than(const time_type& t1, const time_type& t2) { return t1 < t2; } /// Convert to POSIX duration type. static boost::posix_time::time_duration to_posix_duration( const duration_type& d) { return d; } }; } // namespace asio #include "asio/detail/pop_options.hpp" #endif // defined(ASIO_HAS_BOOST_DATE_TIME) // || defined(GENERATING_DOCUMENTATION) #endif // ASIO_TIME_TRAITS_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/prefer.hpp
// // prefer.hpp // ~~~~~~~~~~ // // 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) // #ifndef ASIO_PREFER_HPP #define ASIO_PREFER_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include "asio/detail/type_traits.hpp" #include "asio/is_applicable_property.hpp" #include "asio/traits/prefer_free.hpp" #include "asio/traits/prefer_member.hpp" #include "asio/traits/require_free.hpp" #include "asio/traits/require_member.hpp" #include "asio/traits/static_require.hpp" #include "asio/detail/push_options.hpp" #if defined(GENERATING_DOCUMENTATION) namespace asio { /// A customisation point that attempts to apply a property to an object. /** * The name <tt>prefer</tt> denotes a customisation point object. The * expression <tt>asio::prefer(E, P0, Pn...)</tt> for some subexpressions * <tt>E</tt> and <tt>P0</tt>, and where <tt>Pn...</tt> represents <tt>N</tt> * subexpressions (where <tt>N</tt> is 0 or more, and with types <tt>T = * decay_t<decltype(E)></tt> and <tt>Prop0 = decay_t<decltype(P0)></tt>) is * expression-equivalent to: * * @li If <tt>is_applicable_property_v<T, Prop0> && Prop0::is_preferable</tt> is * not a well-formed constant expression with value <tt>true</tt>, * <tt>asio::prefer(E, P0, Pn...)</tt> is ill-formed. * * @li Otherwise, <tt>E</tt> if <tt>N == 0</tt> and the expression * <tt>Prop0::template static_query_v<T> == Prop0::value()</tt> is a * well-formed constant expression with value <tt>true</tt>. * * @li Otherwise, <tt>(E).require(P0)</tt> if <tt>N == 0</tt> and the expression * <tt>(E).require(P0)</tt> is a valid expression. * * @li Otherwise, <tt>require(E, P0)</tt> if <tt>N == 0</tt> and the expression * <tt>require(E, P0)</tt> is a valid expression with overload resolution * performed in a context that does not include the declaration of the * <tt>require</tt> customization point object. * * @li Otherwise, <tt>(E).prefer(P0)</tt> if <tt>N == 0</tt> and the expression * <tt>(E).prefer(P0)</tt> is a valid expression. * * @li Otherwise, <tt>prefer(E, P0)</tt> if <tt>N == 0</tt> and the expression * <tt>prefer(E, P0)</tt> is a valid expression with overload resolution * performed in a context that does not include the declaration of the * <tt>prefer</tt> customization point object. * * @li Otherwise, <tt>E</tt> if <tt>N == 0</tt>. * * @li Otherwise, * <tt>asio::prefer(asio::prefer(E, P0), Pn...)</tt> * if <tt>N > 0</tt> and the expression * <tt>asio::prefer(asio::prefer(E, P0), Pn...)</tt> * is a valid expression. * * @li Otherwise, <tt>asio::prefer(E, P0, Pn...)</tt> is ill-formed. */ inline constexpr unspecified prefer = unspecified; /// A type trait that determines whether a @c prefer expression is well-formed. /** * Class template @c can_prefer is a trait that is derived from * @c true_type if the expression <tt>asio::prefer(std::declval<T>(), * std::declval<Properties>()...)</tt> is well formed; otherwise @c false_type. */ template <typename T, typename... Properties> struct can_prefer : integral_constant<bool, automatically_determined> { }; /// A type trait that determines whether a @c prefer expression will not throw. /** * Class template @c is_nothrow_prefer is a trait that is derived from * @c true_type if the expression <tt>asio::prefer(std::declval<T>(), * std::declval<Properties>()...)</tt> is @c noexcept; otherwise @c false_type. */ template <typename T, typename... Properties> struct is_nothrow_prefer : integral_constant<bool, automatically_determined> { }; /// A type trait that determines the result type of a @c prefer expression. /** * Class template @c prefer_result is a trait that determines the result * type of the expression <tt>asio::prefer(std::declval<T>(), * std::declval<Properties>()...)</tt>. */ template <typename T, typename... Properties> struct prefer_result { /// The result of the @c prefer expression. typedef automatically_determined type; }; } // namespace asio #else // defined(GENERATING_DOCUMENTATION) namespace asio_prefer_fn { using asio::conditional_t; using asio::decay_t; using asio::declval; using asio::enable_if_t; using asio::is_applicable_property; using asio::traits::prefer_free; using asio::traits::prefer_member; using asio::traits::require_free; using asio::traits::require_member; using asio::traits::static_require; void prefer(); void require(); enum overload_type { identity, call_require_member, call_require_free, call_prefer_member, call_prefer_free, two_props, n_props, ill_formed }; template <typename Impl, typename T, typename Properties, typename = void, typename = void, typename = void, typename = void, typename = void, typename = void, typename = void> struct call_traits { static constexpr overload_type overload = ill_formed; static constexpr bool is_noexcept = false; typedef void result_type; }; template <typename Impl, typename T, typename Property> struct call_traits<Impl, T, void(Property), enable_if_t< is_applicable_property< decay_t<T>, decay_t<Property> >::value >, enable_if_t< decay_t<Property>::is_preferable >, enable_if_t< static_require<T, Property>::is_valid >> { static constexpr overload_type overload = identity; static constexpr bool is_noexcept = true; typedef T&& result_type; }; template <typename Impl, typename T, typename Property> struct call_traits<Impl, T, void(Property), enable_if_t< is_applicable_property< decay_t<T>, decay_t<Property> >::value >, enable_if_t< decay_t<Property>::is_preferable >, enable_if_t< !static_require<T, Property>::is_valid >, enable_if_t< require_member<typename Impl::template proxy<T>::type, Property>::is_valid >> : require_member<typename Impl::template proxy<T>::type, Property> { static constexpr overload_type overload = call_require_member; }; template <typename Impl, typename T, typename Property> struct call_traits<Impl, T, void(Property), enable_if_t< is_applicable_property< decay_t<T>, decay_t<Property> >::value >, enable_if_t< decay_t<Property>::is_preferable >, enable_if_t< !static_require<T, Property>::is_valid >, enable_if_t< !require_member<typename Impl::template proxy<T>::type, Property>::is_valid >, enable_if_t< require_free<T, Property>::is_valid >> : require_free<T, Property> { static constexpr overload_type overload = call_require_free; }; template <typename Impl, typename T, typename Property> struct call_traits<Impl, T, void(Property), enable_if_t< is_applicable_property< decay_t<T>, decay_t<Property> >::value >, enable_if_t< decay_t<Property>::is_preferable >, enable_if_t< !static_require<T, Property>::is_valid >, enable_if_t< !require_member<typename Impl::template proxy<T>::type, Property>::is_valid >, enable_if_t< !require_free<T, Property>::is_valid >, enable_if_t< prefer_member<typename Impl::template proxy<T>::type, Property>::is_valid >> : prefer_member<typename Impl::template proxy<T>::type, Property> { static constexpr overload_type overload = call_prefer_member; }; template <typename Impl, typename T, typename Property> struct call_traits<Impl, T, void(Property), enable_if_t< is_applicable_property< decay_t<T>, decay_t<Property> >::value >, enable_if_t< decay_t<Property>::is_preferable >, enable_if_t< !static_require<T, Property>::is_valid >, enable_if_t< !require_member<typename Impl::template proxy<T>::type, Property>::is_valid >, enable_if_t< !require_free<T, Property>::is_valid >, enable_if_t< !prefer_member<typename Impl::template proxy<T>::type, Property>::is_valid >, enable_if_t< prefer_free<T, Property>::is_valid >> : prefer_free<T, Property> { static constexpr overload_type overload = call_prefer_free; }; template <typename Impl, typename T, typename Property> struct call_traits<Impl, T, void(Property), enable_if_t< is_applicable_property< decay_t<T>, decay_t<Property> >::value >, enable_if_t< decay_t<Property>::is_preferable >, enable_if_t< !static_require<T, Property>::is_valid >, enable_if_t< !require_member<typename Impl::template proxy<T>::type, Property>::is_valid >, enable_if_t< !require_free<T, Property>::is_valid >, enable_if_t< !prefer_member<typename Impl::template proxy<T>::type, Property>::is_valid >, enable_if_t< !prefer_free<T, Property>::is_valid >> { static constexpr overload_type overload = identity; static constexpr bool is_noexcept = true; typedef T&& result_type; }; template <typename Impl, typename T, typename P0, typename P1> struct call_traits<Impl, T, void(P0, P1), enable_if_t< call_traits<Impl, T, void(P0)>::overload != ill_formed >, enable_if_t< call_traits< Impl, typename call_traits<Impl, T, void(P0)>::result_type, void(P1) >::overload != ill_formed >> { static constexpr overload_type overload = two_props; static constexpr bool is_noexcept = ( call_traits<Impl, T, void(P0)>::is_noexcept && call_traits< Impl, typename call_traits<Impl, T, void(P0)>::result_type, void(P1) >::is_noexcept ); typedef decay_t< typename call_traits< Impl, typename call_traits<Impl, T, void(P0)>::result_type, void(P1) >::result_type > result_type; }; template <typename Impl, typename T, typename P0, typename P1, typename... PN> struct call_traits<Impl, T, void(P0, P1, PN...), enable_if_t< call_traits<Impl, T, void(P0)>::overload != ill_formed >, enable_if_t< call_traits< Impl, typename call_traits<Impl, T, void(P0)>::result_type, void(P1, PN...) >::overload != ill_formed >> { static constexpr overload_type overload = n_props; static constexpr bool is_noexcept = ( call_traits<Impl, T, void(P0)>::is_noexcept && call_traits< Impl, typename call_traits<Impl, T, void(P0)>::result_type, void(P1, PN...) >::is_noexcept ); typedef decay_t< typename call_traits< Impl, typename call_traits<Impl, T, void(P0)>::result_type, void(P1, PN...) >::result_type > result_type; }; struct impl { template <typename T> struct proxy { #if defined(ASIO_HAS_DEDUCED_REQUIRE_MEMBER_TRAIT) \ && defined(ASIO_HAS_DEDUCED_PREFER_MEMBER_TRAIT) struct type { template <typename P> auto require(P&& p) noexcept( noexcept( declval<conditional_t<true, T, P>>().require(static_cast<P&&>(p)) ) ) -> decltype( declval<conditional_t<true, T, P>>().require(static_cast<P&&>(p)) ); template <typename P> auto prefer(P&& p) noexcept( noexcept( declval<conditional_t<true, T, P>>().prefer(static_cast<P&&>(p)) ) ) -> decltype( declval<conditional_t<true, T, P>>().prefer(static_cast<P&&>(p)) ); }; #else // defined(ASIO_HAS_DEDUCED_REQUIRE_MEMBER_TRAIT) // && defined(ASIO_HAS_DEDUCED_PREFER_MEMBER_TRAIT) typedef T type; #endif // defined(ASIO_HAS_DEDUCED_REQUIRE_MEMBER_TRAIT) // && defined(ASIO_HAS_DEDUCED_PREFER_MEMBER_TRAIT) }; template <typename T, typename Property> ASIO_NODISCARD constexpr enable_if_t< call_traits<impl, T, void(Property)>::overload == identity, typename call_traits<impl, T, void(Property)>::result_type > operator()(T&& t, Property&&) const noexcept(call_traits<impl, T, void(Property)>::is_noexcept) { return static_cast<T&&>(t); } template <typename T, typename Property> ASIO_NODISCARD constexpr enable_if_t< call_traits<impl, T, void(Property)>::overload == call_require_member, typename call_traits<impl, T, void(Property)>::result_type > operator()(T&& t, Property&& p) const noexcept(call_traits<impl, T, void(Property)>::is_noexcept) { return static_cast<T&&>(t).require(static_cast<Property&&>(p)); } template <typename T, typename Property> ASIO_NODISCARD constexpr enable_if_t< call_traits<impl, T, void(Property)>::overload == call_require_free, typename call_traits<impl, T, void(Property)>::result_type > operator()(T&& t, Property&& p) const noexcept(call_traits<impl, T, void(Property)>::is_noexcept) { return require(static_cast<T&&>(t), static_cast<Property&&>(p)); } template <typename T, typename Property> ASIO_NODISCARD constexpr enable_if_t< call_traits<impl, T, void(Property)>::overload == call_prefer_member, typename call_traits<impl, T, void(Property)>::result_type > operator()(T&& t, Property&& p) const noexcept(call_traits<impl, T, void(Property)>::is_noexcept) { return static_cast<T&&>(t).prefer(static_cast<Property&&>(p)); } template <typename T, typename Property> ASIO_NODISCARD constexpr enable_if_t< call_traits<impl, T, void(Property)>::overload == call_prefer_free, typename call_traits<impl, T, void(Property)>::result_type > operator()(T&& t, Property&& p) const noexcept(call_traits<impl, T, void(Property)>::is_noexcept) { return prefer(static_cast<T&&>(t), static_cast<Property&&>(p)); } template <typename T, typename P0, typename P1> ASIO_NODISCARD constexpr enable_if_t< call_traits<impl, T, void(P0, P1)>::overload == two_props, typename call_traits<impl, T, void(P0, P1)>::result_type > operator()(T&& t, P0&& p0, P1&& p1) const noexcept(call_traits<impl, T, void(P0, P1)>::is_noexcept) { return (*this)( (*this)(static_cast<T&&>(t), static_cast<P0&&>(p0)), static_cast<P1&&>(p1)); } template <typename T, typename P0, typename P1, typename... PN> ASIO_NODISCARD constexpr enable_if_t< call_traits<impl, T, void(P0, P1, PN...)>::overload == n_props, typename call_traits<impl, T, void(P0, P1, PN...)>::result_type > operator()(T&& t, P0&& p0, P1&& p1, PN&&... pn) const noexcept(call_traits<impl, T, void(P0, P1, PN...)>::is_noexcept) { return (*this)( (*this)(static_cast<T&&>(t), static_cast<P0&&>(p0)), static_cast<P1&&>(p1), static_cast<PN&&>(pn)...); } }; template <typename T = impl> struct static_instance { static const T instance; }; template <typename T> const T static_instance<T>::instance = {}; } // namespace asio_prefer_fn namespace asio { namespace { static constexpr const asio_prefer_fn::impl& prefer = asio_prefer_fn::static_instance<>::instance; } // namespace typedef asio_prefer_fn::impl prefer_t; template <typename T, typename... Properties> struct can_prefer : integral_constant<bool, asio_prefer_fn::call_traits< prefer_t, T, void(Properties...)>::overload != asio_prefer_fn::ill_formed> { }; #if defined(ASIO_HAS_VARIABLE_TEMPLATES) template <typename T, typename... Properties> constexpr bool can_prefer_v = can_prefer<T, Properties...>::value; #endif // defined(ASIO_HAS_VARIABLE_TEMPLATES) template <typename T, typename... Properties> struct is_nothrow_prefer : integral_constant<bool, asio_prefer_fn::call_traits< prefer_t, T, void(Properties...)>::is_noexcept> { }; #if defined(ASIO_HAS_VARIABLE_TEMPLATES) template <typename T, typename... Properties> constexpr bool is_nothrow_prefer_v = is_nothrow_prefer<T, Properties...>::value; #endif // defined(ASIO_HAS_VARIABLE_TEMPLATES) template <typename T, typename... Properties> struct prefer_result { typedef typename asio_prefer_fn::call_traits< prefer_t, T, void(Properties...)>::result_type type; }; template <typename T, typename... Properties> using prefer_result_t = typename prefer_result<T, Properties...>::type; } // namespace asio #endif // defined(GENERATING_DOCUMENTATION) #include "asio/detail/pop_options.hpp" #endif // ASIO_PREFER_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/io_service_strand.hpp
// // io_service_strand.hpp // ~~~~~~~~~~~~~~~~~~~~~ // // 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) // #ifndef ASIO_IO_SERVICE_STRAND_HPP #define ASIO_IO_SERVICE_STRAND_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/io_context_strand.hpp" #endif // ASIO_IO_SERVICE_STRAND_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/basic_seq_packet_socket.hpp
// // basic_seq_packet_socket.hpp // ~~~~~~~~~~~~~~~~~~~~~~~~~~~ // // 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) // #ifndef ASIO_BASIC_SEQ_PACKET_SOCKET_HPP #define ASIO_BASIC_SEQ_PACKET_SOCKET_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include <cstddef> #include "asio/basic_socket.hpp" #include "asio/detail/handler_type_requirements.hpp" #include "asio/detail/throw_error.hpp" #include "asio/error.hpp" #include "asio/detail/push_options.hpp" namespace asio { #if !defined(ASIO_BASIC_SEQ_PACKET_SOCKET_FWD_DECL) #define ASIO_BASIC_SEQ_PACKET_SOCKET_FWD_DECL // Forward declaration with defaulted arguments. template <typename Protocol, typename Executor = any_io_executor> class basic_seq_packet_socket; #endif // !defined(ASIO_BASIC_SEQ_PACKET_SOCKET_FWD_DECL) /// Provides sequenced packet socket functionality. /** * The basic_seq_packet_socket class template provides asynchronous and blocking * sequenced packet socket functionality. * * @par Thread Safety * @e Distinct @e objects: Safe.@n * @e Shared @e objects: Unsafe. * * Synchronous @c send, @c receive, @c connect, and @c shutdown operations are * thread safe with respect to each other, if the underlying operating system * calls are also thread safe. This means that it is permitted to perform * concurrent calls to these synchronous operations on a single socket object. * Other synchronous operations, such as @c open or @c close, are not thread * safe. */ template <typename Protocol, typename Executor> class basic_seq_packet_socket : public basic_socket<Protocol, Executor> { private: class initiate_async_send; class initiate_async_receive_with_flags; public: /// The type of the executor associated with the object. typedef Executor executor_type; /// Rebinds the socket type to another executor. template <typename Executor1> struct rebind_executor { /// The socket type when rebound to the specified executor. typedef basic_seq_packet_socket<Protocol, Executor1> other; }; /// The native representation of a socket. #if defined(GENERATING_DOCUMENTATION) typedef implementation_defined native_handle_type; #else typedef typename basic_socket<Protocol, Executor>::native_handle_type native_handle_type; #endif /// The protocol type. typedef Protocol protocol_type; /// The endpoint type. typedef typename Protocol::endpoint endpoint_type; /// Construct a basic_seq_packet_socket without opening it. /** * This constructor creates a sequenced packet socket without opening it. The * socket needs to be opened and then connected or accepted before data can * be sent or received on it. * * @param ex The I/O executor that the socket will use, by default, to * dispatch handlers for any asynchronous operations performed on the socket. */ explicit basic_seq_packet_socket(const executor_type& ex) : basic_socket<Protocol, Executor>(ex) { } /// Construct a basic_seq_packet_socket without opening it. /** * This constructor creates a sequenced packet socket without opening it. The * socket needs to be opened and then connected or accepted before data can * be sent or received on it. * * @param context An execution context which provides the I/O executor that * the socket will use, by default, to dispatch handlers for any asynchronous * operations performed on the socket. */ template <typename ExecutionContext> explicit basic_seq_packet_socket(ExecutionContext& context, constraint_t< is_convertible<ExecutionContext&, execution_context&>::value > = 0) : basic_socket<Protocol, Executor>(context) { } /// Construct and open a basic_seq_packet_socket. /** * This constructor creates and opens a sequenced_packet socket. The socket * needs to be connected or accepted before data can be sent or received on * it. * * @param ex The I/O executor that the socket will use, by default, to * dispatch handlers for any asynchronous operations performed on the socket. * * @param protocol An object specifying protocol parameters to be used. * * @throws asio::system_error Thrown on failure. */ basic_seq_packet_socket(const executor_type& ex, const protocol_type& protocol) : basic_socket<Protocol, Executor>(ex, protocol) { } /// Construct and open a basic_seq_packet_socket. /** * This constructor creates and opens a sequenced_packet socket. The socket * needs to be connected or accepted before data can be sent or received on * it. * * @param context An execution context which provides the I/O executor that * the socket will use, by default, to dispatch handlers for any asynchronous * operations performed on the socket. * * @param protocol An object specifying protocol parameters to be used. * * @throws asio::system_error Thrown on failure. */ template <typename ExecutionContext> basic_seq_packet_socket(ExecutionContext& context, const protocol_type& protocol, constraint_t< is_convertible<ExecutionContext&, execution_context&>::value, defaulted_constraint > = defaulted_constraint()) : basic_socket<Protocol, Executor>(context, protocol) { } /// Construct a basic_seq_packet_socket, opening it and binding it to the /// given local endpoint. /** * This constructor creates a sequenced packet socket and automatically opens * it bound to the specified endpoint on the local machine. The protocol used * is the protocol associated with the given endpoint. * * @param ex The I/O executor that the socket will use, by default, to * dispatch handlers for any asynchronous operations performed on the socket. * * @param endpoint An endpoint on the local machine to which the sequenced * packet socket will be bound. * * @throws asio::system_error Thrown on failure. */ basic_seq_packet_socket(const executor_type& ex, const endpoint_type& endpoint) : basic_socket<Protocol, Executor>(ex, endpoint) { } /// Construct a basic_seq_packet_socket, opening it and binding it to the /// given local endpoint. /** * This constructor creates a sequenced packet socket and automatically opens * it bound to the specified endpoint on the local machine. The protocol used * is the protocol associated with the given endpoint. * * @param context An execution context which provides the I/O executor that * the socket will use, by default, to dispatch handlers for any asynchronous * operations performed on the socket. * * @param endpoint An endpoint on the local machine to which the sequenced * packet socket will be bound. * * @throws asio::system_error Thrown on failure. */ template <typename ExecutionContext> basic_seq_packet_socket(ExecutionContext& context, const endpoint_type& endpoint, constraint_t< is_convertible<ExecutionContext&, execution_context&>::value > = 0) : basic_socket<Protocol, Executor>(context, endpoint) { } /// Construct a basic_seq_packet_socket on an existing native socket. /** * This constructor creates a sequenced packet socket object to hold an * existing native socket. * * @param ex The I/O executor that the socket will use, by default, to * dispatch handlers for any asynchronous operations performed on the socket. * * @param protocol An object specifying protocol parameters to be used. * * @param native_socket The new underlying socket implementation. * * @throws asio::system_error Thrown on failure. */ basic_seq_packet_socket(const executor_type& ex, const protocol_type& protocol, const native_handle_type& native_socket) : basic_socket<Protocol, Executor>(ex, protocol, native_socket) { } /// Construct a basic_seq_packet_socket on an existing native socket. /** * This constructor creates a sequenced packet socket object to hold an * existing native socket. * * @param context An execution context which provides the I/O executor that * the socket will use, by default, to dispatch handlers for any asynchronous * operations performed on the socket. * * @param protocol An object specifying protocol parameters to be used. * * @param native_socket The new underlying socket implementation. * * @throws asio::system_error Thrown on failure. */ template <typename ExecutionContext> basic_seq_packet_socket(ExecutionContext& context, const protocol_type& protocol, const native_handle_type& native_socket, constraint_t< is_convertible<ExecutionContext&, execution_context&>::value > = 0) : basic_socket<Protocol, Executor>(context, protocol, native_socket) { } /// Move-construct a basic_seq_packet_socket from another. /** * This constructor moves a sequenced packet socket from one object to * another. * * @param other The other basic_seq_packet_socket object from which the move * will occur. * * @note Following the move, the moved-from object is in the same state as if * constructed using the @c basic_seq_packet_socket(const executor_type&) * constructor. */ basic_seq_packet_socket(basic_seq_packet_socket&& other) noexcept : basic_socket<Protocol, Executor>(std::move(other)) { } /// Move-assign a basic_seq_packet_socket from another. /** * This assignment operator moves a sequenced packet socket from one object to * another. * * @param other The other basic_seq_packet_socket object from which the move * will occur. * * @note Following the move, the moved-from object is in the same state as if * constructed using the @c basic_seq_packet_socket(const executor_type&) * constructor. */ basic_seq_packet_socket& operator=(basic_seq_packet_socket&& other) { basic_socket<Protocol, Executor>::operator=(std::move(other)); return *this; } /// Move-construct a basic_seq_packet_socket from a socket of another protocol /// type. /** * This constructor moves a sequenced packet socket from one object to * another. * * @param other The other basic_seq_packet_socket object from which the move * will occur. * * @note Following the move, the moved-from object is in the same state as if * constructed using the @c basic_seq_packet_socket(const executor_type&) * constructor. */ template <typename Protocol1, typename Executor1> basic_seq_packet_socket(basic_seq_packet_socket<Protocol1, Executor1>&& other, constraint_t< is_convertible<Protocol1, Protocol>::value && is_convertible<Executor1, Executor>::value > = 0) : basic_socket<Protocol, Executor>(std::move(other)) { } /// Move-assign a basic_seq_packet_socket from a socket of another protocol /// type. /** * This assignment operator moves a sequenced packet socket from one object to * another. * * @param other The other basic_seq_packet_socket object from which the move * will occur. * * @note Following the move, the moved-from object is in the same state as if * constructed using the @c basic_seq_packet_socket(const executor_type&) * constructor. */ template <typename Protocol1, typename Executor1> constraint_t< is_convertible<Protocol1, Protocol>::value && is_convertible<Executor1, Executor>::value, basic_seq_packet_socket& > operator=(basic_seq_packet_socket<Protocol1, Executor1>&& other) { basic_socket<Protocol, Executor>::operator=(std::move(other)); return *this; } /// Destroys the socket. /** * This function destroys the socket, cancelling any outstanding asynchronous * operations associated with the socket as if by calling @c cancel. */ ~basic_seq_packet_socket() { } /// Send some data on the socket. /** * This function is used to send data on the sequenced packet socket. The * function call will block until the data has been sent successfully, or an * until error occurs. * * @param buffers One or more data buffers to be sent on the socket. * * @param flags Flags specifying how the send call is to be made. * * @returns The number of bytes sent. * * @throws asio::system_error Thrown on failure. * * @par Example * To send a single data buffer use the @ref buffer function as follows: * @code * socket.send(asio::buffer(data, size), 0); * @endcode * See the @ref buffer documentation for information on sending multiple * buffers in one go, and how to use it with arrays, boost::array or * std::vector. */ template <typename ConstBufferSequence> std::size_t send(const ConstBufferSequence& buffers, socket_base::message_flags flags) { asio::error_code ec; std::size_t s = this->impl_.get_service().send( this->impl_.get_implementation(), buffers, flags, ec); asio::detail::throw_error(ec, "send"); return s; } /// Send some data on the socket. /** * This function is used to send data on the sequenced packet socket. The * function call will block the data has been sent successfully, or an until * error occurs. * * @param buffers One or more data buffers to be sent on the socket. * * @param flags Flags specifying how the send call is to be made. * * @param ec Set to indicate what error occurred, if any. * * @returns The number of bytes sent. Returns 0 if an error occurred. * * @note The send operation may not transmit all of the data to the peer. * Consider using the @ref write function if you need to ensure that all data * is written before the blocking operation completes. */ template <typename ConstBufferSequence> std::size_t send(const ConstBufferSequence& buffers, socket_base::message_flags flags, asio::error_code& ec) { return this->impl_.get_service().send( this->impl_.get_implementation(), buffers, flags, ec); } /// Start an asynchronous send. /** * This function is used to asynchronously send data on the sequenced packet * socket. It is an initiating function for an @ref asynchronous_operation, * and always returns immediately. * * @param buffers One or more data buffers to be sent on the socket. Although * the buffers object may be copied as necessary, ownership of the underlying * memory blocks is retained by the caller, which must guarantee that they * remain valid until the completion handler is called. * * @param flags Flags specifying how the send call is to be made. * * @param token The @ref completion_token that will be used to produce a * completion handler, which will be called when the send completes. * Potential completion tokens include @ref use_future, @ref use_awaitable, * @ref yield_context, or a function object with the correct completion * signature. The function signature of the completion handler must be: * @code void handler( * const asio::error_code& error, // Result of operation. * std::size_t bytes_transferred // Number of bytes sent. * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the completion handler will not be invoked from within this function. * On immediate completion, invocation of the handler will be performed in a * manner equivalent to using asio::async_immediate(). * * @par Completion Signature * @code void(asio::error_code, std::size_t) @endcode * * @par Example * To send a single data buffer use the @ref buffer function as follows: * @code * socket.async_send(asio::buffer(data, size), 0, handler); * @endcode * See the @ref buffer documentation for information on sending multiple * buffers in one go, and how to use it with arrays, boost::array or * std::vector. * * @par Per-Operation Cancellation * On POSIX or Windows operating systems, this asynchronous operation supports * cancellation for the following asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * @li @c cancellation_type::total */ template <typename ConstBufferSequence, ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code, std::size_t)) WriteToken = default_completion_token_t<executor_type>> auto async_send(const ConstBufferSequence& buffers, socket_base::message_flags flags, WriteToken&& token = default_completion_token_t<executor_type>()) -> decltype( async_initiate<WriteToken, void (asio::error_code, std::size_t)>( declval<initiate_async_send>(), token, buffers, flags)) { return async_initiate<WriteToken, void (asio::error_code, std::size_t)>( initiate_async_send(this), token, buffers, flags); } /// Receive some data on the socket. /** * This function is used to receive data on the sequenced packet socket. The * function call will block until data has been received successfully, or * until an error occurs. * * @param buffers One or more buffers into which the data will be received. * * @param out_flags After the receive call completes, contains flags * associated with the received data. For example, if the * socket_base::message_end_of_record bit is set then the received data marks * the end of a record. * * @returns The number of bytes received. * * @throws asio::system_error Thrown on failure. An error code of * asio::error::eof indicates that the connection was closed by the * peer. * * @par Example * To receive into a single data buffer use the @ref buffer function as * follows: * @code * socket.receive(asio::buffer(data, size), out_flags); * @endcode * See the @ref buffer documentation for information on receiving into * multiple buffers in one go, and how to use it with arrays, boost::array or * std::vector. */ template <typename MutableBufferSequence> std::size_t receive(const MutableBufferSequence& buffers, socket_base::message_flags& out_flags) { asio::error_code ec; std::size_t s = this->impl_.get_service().receive_with_flags( this->impl_.get_implementation(), buffers, 0, out_flags, ec); asio::detail::throw_error(ec, "receive"); return s; } /// Receive some data on the socket. /** * This function is used to receive data on the sequenced packet socket. The * function call will block until data has been received successfully, or * until an error occurs. * * @param buffers One or more buffers into which the data will be received. * * @param in_flags Flags specifying how the receive call is to be made. * * @param out_flags After the receive call completes, contains flags * associated with the received data. For example, if the * socket_base::message_end_of_record bit is set then the received data marks * the end of a record. * * @returns The number of bytes received. * * @throws asio::system_error Thrown on failure. An error code of * asio::error::eof indicates that the connection was closed by the * peer. * * @note The receive operation may not receive all of the requested number of * bytes. Consider using the @ref read function if you need to ensure that the * requested amount of data is read before the blocking operation completes. * * @par Example * To receive into a single data buffer use the @ref buffer function as * follows: * @code * socket.receive(asio::buffer(data, size), 0, out_flags); * @endcode * See the @ref buffer documentation for information on receiving into * multiple buffers in one go, and how to use it with arrays, boost::array or * std::vector. */ template <typename MutableBufferSequence> std::size_t receive(const MutableBufferSequence& buffers, socket_base::message_flags in_flags, socket_base::message_flags& out_flags) { asio::error_code ec; std::size_t s = this->impl_.get_service().receive_with_flags( this->impl_.get_implementation(), buffers, in_flags, out_flags, ec); asio::detail::throw_error(ec, "receive"); return s; } /// Receive some data on a connected socket. /** * This function is used to receive data on the sequenced packet socket. The * function call will block until data has been received successfully, or * until an error occurs. * * @param buffers One or more buffers into which the data will be received. * * @param in_flags Flags specifying how the receive call is to be made. * * @param out_flags After the receive call completes, contains flags * associated with the received data. For example, if the * socket_base::message_end_of_record bit is set then the received data marks * the end of a record. * * @param ec Set to indicate what error occurred, if any. * * @returns The number of bytes received. Returns 0 if an error occurred. * * @note The receive operation may not receive all of the requested number of * bytes. Consider using the @ref read function if you need to ensure that the * requested amount of data is read before the blocking operation completes. */ template <typename MutableBufferSequence> std::size_t receive(const MutableBufferSequence& buffers, socket_base::message_flags in_flags, socket_base::message_flags& out_flags, asio::error_code& ec) { return this->impl_.get_service().receive_with_flags( this->impl_.get_implementation(), buffers, in_flags, out_flags, ec); } /// Start an asynchronous receive. /** * This function is used to asynchronously receive data from the sequenced * packet socket. It is an initiating function for an @ref * asynchronous_operation, and always returns immediately. * * @param buffers One or more buffers into which the data will be received. * Although the buffers object may be copied as necessary, ownership of the * underlying memory blocks is retained by the caller, which must guarantee * that they remain valid until the completion handler is called. * * @param out_flags Once the asynchronous operation completes, contains flags * associated with the received data. For example, if the * socket_base::message_end_of_record bit is set then the received data marks * the end of a record. The caller must guarantee that the referenced * variable remains valid until the completion handler is called. * * @param token The @ref completion_token that will be used to produce a * completion handler, which will be called when the receive completes. * Potential completion tokens include @ref use_future, @ref use_awaitable, * @ref yield_context, or a function object with the correct completion * signature. The function signature of the completion handler must be: * @code void handler( * const asio::error_code& error, // Result of operation. * std::size_t bytes_transferred // Number of bytes received. * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the completion handler will not be invoked from within this function. * On immediate completion, invocation of the handler will be performed in a * manner equivalent to using asio::async_immediate(). * * @par Completion Signature * @code void(asio::error_code, std::size_t) @endcode * * @par Example * To receive into a single data buffer use the @ref buffer function as * follows: * @code * socket.async_receive(asio::buffer(data, size), out_flags, handler); * @endcode * See the @ref buffer documentation for information on receiving into * multiple buffers in one go, and how to use it with arrays, boost::array or * std::vector. * * @par Per-Operation Cancellation * On POSIX or Windows operating systems, this asynchronous operation supports * cancellation for the following asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * @li @c cancellation_type::total */ template <typename MutableBufferSequence, ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code, std::size_t)) ReadToken = default_completion_token_t<executor_type>> auto async_receive(const MutableBufferSequence& buffers, socket_base::message_flags& out_flags, ReadToken&& token = default_completion_token_t<executor_type>()) -> decltype( async_initiate<ReadToken, void (asio::error_code, std::size_t)>( declval<initiate_async_receive_with_flags>(), token, buffers, socket_base::message_flags(0), &out_flags)) { return async_initiate<ReadToken, void (asio::error_code, std::size_t)>( initiate_async_receive_with_flags(this), token, buffers, socket_base::message_flags(0), &out_flags); } /// Start an asynchronous receive. /** * This function is used to asynchronously receive data from the sequenced * data socket. It is an initiating function for an @ref * asynchronous_operation, and always returns immediately. * * @param buffers One or more buffers into which the data will be received. * Although the buffers object may be copied as necessary, ownership of the * underlying memory blocks is retained by the caller, which must guarantee * that they remain valid until the completion handler is called. * * @param in_flags Flags specifying how the receive call is to be made. * * @param out_flags Once the asynchronous operation completes, contains flags * associated with the received data. For example, if the * socket_base::message_end_of_record bit is set then the received data marks * the end of a record. The caller must guarantee that the referenced * variable remains valid until the completion handler is called. * * @param token The @ref completion_token that will be used to produce a * completion handler, which will be called when the receive completes. * Potential completion tokens include @ref use_future, @ref use_awaitable, * @ref yield_context, or a function object with the correct completion * signature. The function signature of the completion handler must be: * @code void handler( * const asio::error_code& error, // Result of operation. * std::size_t bytes_transferred // Number of bytes received. * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the completion handler will not be invoked from within this function. * On immediate completion, invocation of the handler will be performed in a * manner equivalent to using asio::async_immediate(). * * @par Completion Signature * @code void(asio::error_code, std::size_t) @endcode * * @par Example * To receive into a single data buffer use the @ref buffer function as * follows: * @code * socket.async_receive( * asio::buffer(data, size), * 0, out_flags, handler); * @endcode * See the @ref buffer documentation for information on receiving into * multiple buffers in one go, and how to use it with arrays, boost::array or * std::vector. * * @par Per-Operation Cancellation * On POSIX or Windows operating systems, this asynchronous operation supports * cancellation for the following asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * @li @c cancellation_type::total */ template <typename MutableBufferSequence, ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code, std::size_t)) ReadToken = default_completion_token_t<executor_type>> auto async_receive(const MutableBufferSequence& buffers, socket_base::message_flags in_flags, socket_base::message_flags& out_flags, ReadToken&& token = default_completion_token_t<executor_type>()) -> decltype( async_initiate<ReadToken, void (asio::error_code, std::size_t)>( declval<initiate_async_receive_with_flags>(), token, buffers, in_flags, &out_flags)) { return async_initiate<ReadToken, void (asio::error_code, std::size_t)>( initiate_async_receive_with_flags(this), token, buffers, in_flags, &out_flags); } private: // Disallow copying and assignment. basic_seq_packet_socket(const basic_seq_packet_socket&) = delete; basic_seq_packet_socket& operator=( const basic_seq_packet_socket&) = delete; class initiate_async_send { public: typedef Executor executor_type; explicit initiate_async_send(basic_seq_packet_socket* self) : self_(self) { } const executor_type& get_executor() const noexcept { return self_->get_executor(); } template <typename WriteHandler, typename ConstBufferSequence> void operator()(WriteHandler&& handler, const ConstBufferSequence& buffers, socket_base::message_flags flags) const { // If you get an error on the following line it means that your handler // does not meet the documented type requirements for a WriteHandler. ASIO_WRITE_HANDLER_CHECK(WriteHandler, handler) type_check; detail::non_const_lvalue<WriteHandler> handler2(handler); self_->impl_.get_service().async_send( self_->impl_.get_implementation(), buffers, flags, handler2.value, self_->impl_.get_executor()); } private: basic_seq_packet_socket* self_; }; class initiate_async_receive_with_flags { public: typedef Executor executor_type; explicit initiate_async_receive_with_flags(basic_seq_packet_socket* self) : self_(self) { } const executor_type& get_executor() const noexcept { return self_->get_executor(); } template <typename ReadHandler, typename MutableBufferSequence> void operator()(ReadHandler&& handler, const MutableBufferSequence& buffers, socket_base::message_flags in_flags, socket_base::message_flags* out_flags) const { // If you get an error on the following line it means that your handler // does not meet the documented type requirements for a ReadHandler. ASIO_READ_HANDLER_CHECK(ReadHandler, handler) type_check; detail::non_const_lvalue<ReadHandler> handler2(handler); self_->impl_.get_service().async_receive_with_flags( self_->impl_.get_implementation(), buffers, in_flags, *out_flags, handler2.value, self_->impl_.get_executor()); } private: basic_seq_packet_socket* self_; }; }; } // namespace asio #include "asio/detail/pop_options.hpp" #endif // ASIO_BASIC_SEQ_PACKET_SOCKET_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/associated_allocator.hpp
// // associated_allocator.hpp // ~~~~~~~~~~~~~~~~~~~~~~~~ // // 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) // #ifndef ASIO_ASSOCIATED_ALLOCATOR_HPP #define ASIO_ASSOCIATED_ALLOCATOR_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include <memory> #include "asio/associator.hpp" #include "asio/detail/functional.hpp" #include "asio/detail/type_traits.hpp" #include "asio/detail/push_options.hpp" namespace asio { template <typename T, typename Allocator> struct associated_allocator; namespace detail { template <typename T, typename = void> struct has_allocator_type : false_type { }; template <typename T> struct has_allocator_type<T, void_t<typename T::allocator_type>> : true_type { }; template <typename T, typename A, typename = void, typename = void> struct associated_allocator_impl { typedef void asio_associated_allocator_is_unspecialised; typedef A type; static type get(const T&) noexcept { return type(); } static const type& get(const T&, const A& a) noexcept { return a; } }; template <typename T, typename A> struct associated_allocator_impl<T, A, void_t<typename T::allocator_type>> { typedef typename T::allocator_type type; static auto get(const T& t) noexcept -> decltype(t.get_allocator()) { return t.get_allocator(); } static auto get(const T& t, const A&) noexcept -> decltype(t.get_allocator()) { return t.get_allocator(); } }; template <typename T, typename A> struct associated_allocator_impl<T, A, enable_if_t< !has_allocator_type<T>::value >, void_t< typename associator<associated_allocator, T, A>::type >> : associator<associated_allocator, T, A> { }; } // namespace detail /// Traits type used to obtain the allocator associated with an object. /** * A program may specialise this traits type if the @c T template parameter in * the specialisation is a user-defined type. The template parameter @c * Allocator shall be a type meeting the Allocator requirements. * * Specialisations shall meet the following requirements, where @c t is a const * reference to an object of type @c T, and @c a is an object of type @c * Allocator. * * @li Provide a nested typedef @c type that identifies a type meeting the * Allocator requirements. * * @li Provide a noexcept static member function named @c get, callable as @c * get(t) and with return type @c type or a (possibly const) reference to @c * type. * * @li Provide a noexcept static member function named @c get, callable as @c * get(t,a) and with return type @c type or a (possibly const) reference to @c * type. */ template <typename T, typename Allocator = std::allocator<void>> struct associated_allocator #if !defined(GENERATING_DOCUMENTATION) : detail::associated_allocator_impl<T, Allocator> #endif // !defined(GENERATING_DOCUMENTATION) { #if defined(GENERATING_DOCUMENTATION) /// If @c T has a nested type @c allocator_type, <tt>T::allocator_type</tt>. /// Otherwise @c Allocator. typedef see_below type; /// If @c T has a nested type @c allocator_type, returns /// <tt>t.get_allocator()</tt>. Otherwise returns @c type(). static decltype(auto) get(const T& t) noexcept; /// If @c T has a nested type @c allocator_type, returns /// <tt>t.get_allocator()</tt>. Otherwise returns @c a. static decltype(auto) get(const T& t, const Allocator& a) noexcept; #endif // defined(GENERATING_DOCUMENTATION) }; /// Helper function to obtain an object's associated allocator. /** * @returns <tt>associated_allocator<T>::get(t)</tt> */ template <typename T> ASIO_NODISCARD inline typename associated_allocator<T>::type get_associated_allocator(const T& t) noexcept { return associated_allocator<T>::get(t); } /// Helper function to obtain an object's associated allocator. /** * @returns <tt>associated_allocator<T, Allocator>::get(t, a)</tt> */ template <typename T, typename Allocator> ASIO_NODISCARD inline auto get_associated_allocator( const T& t, const Allocator& a) noexcept -> decltype(associated_allocator<T, Allocator>::get(t, a)) { return associated_allocator<T, Allocator>::get(t, a); } template <typename T, typename Allocator = std::allocator<void>> using associated_allocator_t = typename associated_allocator<T, Allocator>::type; namespace detail { template <typename T, typename A, typename = void> struct associated_allocator_forwarding_base { }; template <typename T, typename A> struct associated_allocator_forwarding_base<T, A, enable_if_t< is_same< typename associated_allocator<T, A>::asio_associated_allocator_is_unspecialised, void >::value >> { typedef void asio_associated_allocator_is_unspecialised; }; } // namespace detail /// Specialisation of associated_allocator for @c std::reference_wrapper. template <typename T, typename Allocator> struct associated_allocator<reference_wrapper<T>, Allocator> #if !defined(GENERATING_DOCUMENTATION) : detail::associated_allocator_forwarding_base<T, Allocator> #endif // !defined(GENERATING_DOCUMENTATION) { /// Forwards @c type to the associator specialisation for the unwrapped type /// @c T. typedef typename associated_allocator<T, Allocator>::type type; /// Forwards the request to get the allocator to the associator specialisation /// for the unwrapped type @c T. static type get(reference_wrapper<T> t) noexcept { return associated_allocator<T, Allocator>::get(t.get()); } /// Forwards the request to get the allocator to the associator specialisation /// for the unwrapped type @c T. static auto get(reference_wrapper<T> t, const Allocator& a) noexcept -> decltype(associated_allocator<T, Allocator>::get(t.get(), a)) { return associated_allocator<T, Allocator>::get(t.get(), a); } }; } // namespace asio #include "asio/detail/pop_options.hpp" #endif // ASIO_ASSOCIATED_ALLOCATOR_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/use_awaitable.hpp
// // use_awaitable.hpp // ~~~~~~~~~~~~~~~~~ // // 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) // #ifndef ASIO_USE_AWAITABLE_HPP #define ASIO_USE_AWAITABLE_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #if defined(ASIO_HAS_CO_AWAIT) || defined(GENERATING_DOCUMENTATION) #include "asio/awaitable.hpp" #include "asio/detail/handler_tracking.hpp" #if defined(ASIO_ENABLE_HANDLER_TRACKING) # if defined(ASIO_HAS_SOURCE_LOCATION) # include "asio/detail/source_location.hpp" # endif // defined(ASIO_HAS_SOURCE_LOCATION) #endif // defined(ASIO_ENABLE_HANDLER_TRACKING) #include "asio/detail/push_options.hpp" namespace asio { /// A @ref completion_token that represents the currently executing coroutine. /** * The @c use_awaitable_t class, with its value @c use_awaitable, is used to * represent the currently executing coroutine. This completion token may be * passed as a handler to an asynchronous operation. For example: * * @code awaitable<void> my_coroutine() * { * std::size_t n = co_await my_socket.async_read_some(buffer, use_awaitable); * ... * } @endcode * * When used with co_await, the initiating function (@c async_read_some in the * above example) suspends the current coroutine. The coroutine is resumed when * the asynchronous operation completes, and the result of the operation is * returned. */ template <typename Executor = any_io_executor> struct use_awaitable_t { /// Default constructor. constexpr use_awaitable_t( #if defined(ASIO_ENABLE_HANDLER_TRACKING) # if defined(ASIO_HAS_SOURCE_LOCATION) detail::source_location location = detail::source_location::current() # endif // defined(ASIO_HAS_SOURCE_LOCATION) #endif // defined(ASIO_ENABLE_HANDLER_TRACKING) ) #if defined(ASIO_ENABLE_HANDLER_TRACKING) # if defined(ASIO_HAS_SOURCE_LOCATION) : file_name_(location.file_name()), line_(location.line()), function_name_(location.function_name()) # else // defined(ASIO_HAS_SOURCE_LOCATION) : file_name_(0), line_(0), function_name_(0) # endif // defined(ASIO_HAS_SOURCE_LOCATION) #endif // defined(ASIO_ENABLE_HANDLER_TRACKING) { } /// Constructor used to specify file name, line, and function name. constexpr use_awaitable_t(const char* file_name, int line, const char* function_name) #if defined(ASIO_ENABLE_HANDLER_TRACKING) : file_name_(file_name), line_(line), function_name_(function_name) #endif // defined(ASIO_ENABLE_HANDLER_TRACKING) { #if !defined(ASIO_ENABLE_HANDLER_TRACKING) (void)file_name; (void)line; (void)function_name; #endif // !defined(ASIO_ENABLE_HANDLER_TRACKING) } /// Adapts an executor to add the @c use_awaitable_t completion token as the /// default. template <typename InnerExecutor> struct executor_with_default : InnerExecutor { /// Specify @c use_awaitable_t as the default completion token type. typedef use_awaitable_t default_completion_token_type; /// Construct the adapted executor from the inner executor type. template <typename InnerExecutor1> executor_with_default(const InnerExecutor1& ex, constraint_t< conditional_t< !is_same<InnerExecutor1, executor_with_default>::value, is_convertible<InnerExecutor1, InnerExecutor>, false_type >::value > = 0) noexcept : InnerExecutor(ex) { } }; /// Type alias to adapt an I/O object to use @c use_awaitable_t as its /// default completion token type. template <typename T> using as_default_on_t = typename T::template rebind_executor< executor_with_default<typename T::executor_type>>::other; /// Function helper to adapt an I/O object to use @c use_awaitable_t as its /// default completion token type. template <typename T> static typename decay_t<T>::template rebind_executor< executor_with_default<typename decay_t<T>::executor_type> >::other as_default_on(T&& object) { return typename decay_t<T>::template rebind_executor< executor_with_default<typename decay_t<T>::executor_type> >::other(static_cast<T&&>(object)); } #if defined(ASIO_ENABLE_HANDLER_TRACKING) const char* file_name_; int line_; const char* function_name_; #endif // defined(ASIO_ENABLE_HANDLER_TRACKING) }; /// A @ref completion_token object that represents the currently executing /// coroutine. /** * See the documentation for asio::use_awaitable_t for a usage example. */ #if defined(GENERATING_DOCUMENTATION) ASIO_INLINE_VARIABLE constexpr use_awaitable_t<> use_awaitable; #else ASIO_INLINE_VARIABLE constexpr use_awaitable_t<> use_awaitable(0, 0, 0); #endif } // namespace asio #include "asio/detail/pop_options.hpp" #include "asio/impl/use_awaitable.hpp" #endif // defined(ASIO_HAS_CO_AWAIT) || defined(GENERATING_DOCUMENTATION) #endif // ASIO_USE_AWAITABLE_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/is_contiguous_iterator.hpp
// // is_contiguous_iterator.hpp // ~~~~~~~~~~~~~~~~~~~~~~~~~~ // // 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) // #ifndef ASIO_IS_CONTIGUOUS_ITERATOR_HPP #define ASIO_IS_CONTIGUOUS_ITERATOR_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include <iterator> #include "asio/detail/type_traits.hpp" #include "asio/detail/push_options.hpp" namespace asio { /// The is_contiguous_iterator class is a traits class that may be used to /// determine whether a type is a contiguous iterator. template <typename T> struct is_contiguous_iterator : #if defined(ASIO_HAS_STD_CONCEPTS) \ || defined(GENERATING_DOCUMENTATION) integral_constant<bool, std::contiguous_iterator<T>> #else // defined(ASIO_HAS_STD_CONCEPTS) // || defined(GENERATING_DOCUMENTATION) is_pointer<T> #endif // defined(ASIO_HAS_STD_CONCEPTS) // || defined(GENERATING_DOCUMENTATION) { }; } // namespace asio #include "asio/detail/pop_options.hpp" #endif // ASIO_IS_CONTIGUOUS_ITERATOR_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/post.hpp
// // post.hpp // ~~~~~~~~ // // 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) // #ifndef ASIO_POST_HPP #define ASIO_POST_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include "asio/async_result.hpp" #include "asio/detail/initiate_post.hpp" #include "asio/detail/type_traits.hpp" #include "asio/execution_context.hpp" #include "asio/execution/blocking.hpp" #include "asio/execution/executor.hpp" #include "asio/is_executor.hpp" #include "asio/require.hpp" #include "asio/detail/push_options.hpp" namespace asio { /// Submits a completion token or function object for execution. /** * This function submits an object for execution using the object's associated * executor. The function object is queued for execution, and is never called * from the current thread prior to returning from <tt>post()</tt>. * * The use of @c post(), rather than @ref defer(), indicates the caller's * preference that the function object be eagerly queued for execution. * * @param token The @ref completion_token that will be used to produce a * completion handler. The function signature of the completion handler must be: * @code void handler(); @endcode * * @returns This function returns <tt>async_initiate<NullaryToken, * void()>(Init{}, token)</tt>, where @c Init is a function object type defined * as: * * @code class Init * { * public: * template <typename CompletionHandler> * void operator()(CompletionHandler&& completion_handler) const; * }; @endcode * * The function call operator of @c Init: * * @li Obtains the handler's associated executor object @c ex of type @c Ex by * performing @code auto ex = get_associated_executor(handler); @endcode * * @li Obtains the handler's associated allocator object @c alloc by performing * @code auto alloc = get_associated_allocator(handler); @endcode * * @li If <tt>execution::is_executor<Ex>::value</tt> is true, performs * @code prefer( * require(ex, execution::blocking.never), * execution::relationship.fork, * execution::allocator(alloc) * ).execute(std::forward<CompletionHandler>(completion_handler)); @endcode * * @li If <tt>execution::is_executor<Ex>::value</tt> is false, performs * @code ex.post( * std::forward<CompletionHandler>(completion_handler), * alloc); @endcode * * @par Completion Signature * @code void() @endcode */ template <ASIO_COMPLETION_TOKEN_FOR(void()) NullaryToken> inline auto post(NullaryToken&& token) -> decltype( async_initiate<NullaryToken, void()>( declval<detail::initiate_post>(), token)) { return async_initiate<NullaryToken, void()>( detail::initiate_post(), token); } /// Submits a completion token or function object for execution. /** * This function submits an object for execution using the specified executor. * The function object is queued for execution, and is never called from the * current thread prior to returning from <tt>post()</tt>. * * The use of @c post(), rather than @ref defer(), indicates the caller's * preference that the function object be eagerly queued for execution. * * @param ex The target executor. * * @param token The @ref completion_token that will be used to produce a * completion handler. The function signature of the completion handler must be: * @code void handler(); @endcode * * @returns This function returns <tt>async_initiate<NullaryToken, * void()>(Init{ex}, token)</tt>, where @c Init is a function object type * defined as: * * @code class Init * { * public: * using executor_type = Executor; * explicit Init(const Executor& ex) : ex_(ex) {} * executor_type get_executor() const noexcept { return ex_; } * template <typename CompletionHandler> * void operator()(CompletionHandler&& completion_handler) const; * private: * Executor ex_; // exposition only * }; @endcode * * The function call operator of @c Init: * * @li Obtains the handler's associated executor object @c ex1 of type @c Ex1 by * performing @code auto ex1 = get_associated_executor(handler, ex); @endcode * * @li Obtains the handler's associated allocator object @c alloc by performing * @code auto alloc = get_associated_allocator(handler); @endcode * * @li If <tt>execution::is_executor<Ex1>::value</tt> is true, constructs a * function object @c f with a member @c executor_ that is initialised with * <tt>prefer(ex1, execution::outstanding_work.tracked)</tt>, a member @c * handler_ that is a decay-copy of @c completion_handler, and a function call * operator that performs: * @code auto a = get_associated_allocator(handler_); * prefer(executor_, execution::allocator(a)).execute(std::move(handler_)); * @endcode * * @li If <tt>execution::is_executor<Ex1>::value</tt> is false, constructs a * function object @c f with a member @c work_ that is initialised with * <tt>make_work_guard(ex1)</tt>, a member @c handler_ that is a decay-copy of * @c completion_handler, and a function call operator that performs: * @code auto a = get_associated_allocator(handler_); * work_.get_executor().dispatch(std::move(handler_), a); * work_.reset(); @endcode * * @li If <tt>execution::is_executor<Ex>::value</tt> is true, performs * @code prefer( * require(ex, execution::blocking.never), * execution::relationship.fork, * execution::allocator(alloc) * ).execute(std::move(f)); @endcode * * @li If <tt>execution::is_executor<Ex>::value</tt> is false, performs * @code ex.post(std::move(f), alloc); @endcode * * @par Completion Signature * @code void() @endcode */ template <typename Executor, ASIO_COMPLETION_TOKEN_FOR(void()) NullaryToken = default_completion_token_t<Executor>> inline auto post(const Executor& ex, NullaryToken&& token = default_completion_token_t<Executor>(), constraint_t< (execution::is_executor<Executor>::value && can_require<Executor, execution::blocking_t::never_t>::value) || is_executor<Executor>::value > = 0) -> decltype( async_initiate<NullaryToken, void()>( declval<detail::initiate_post_with_executor<Executor>>(), token)) { return async_initiate<NullaryToken, void()>( detail::initiate_post_with_executor<Executor>(ex), token); } /// Submits a completion token or function object for execution. /** * @param ctx An execution context, from which the target executor is obtained. * * @param token The @ref completion_token that will be used to produce a * completion handler. The function signature of the completion handler must be: * @code void handler(); @endcode * * @returns <tt>post(ctx.get_executor(), forward<NullaryToken>(token))</tt>. * * @par Completion Signature * @code void() @endcode */ template <typename ExecutionContext, ASIO_COMPLETION_TOKEN_FOR(void()) NullaryToken = default_completion_token_t<typename ExecutionContext::executor_type>> inline auto post(ExecutionContext& ctx, NullaryToken&& token = default_completion_token_t< typename ExecutionContext::executor_type>(), constraint_t< is_convertible<ExecutionContext&, execution_context&>::value > = 0) -> decltype( async_initiate<NullaryToken, void()>( declval<detail::initiate_post_with_executor< typename ExecutionContext::executor_type>>(), token)) { return async_initiate<NullaryToken, void()>( detail::initiate_post_with_executor< typename ExecutionContext::executor_type>( ctx.get_executor()), token); } } // namespace asio #include "asio/detail/pop_options.hpp" #endif // ASIO_POST_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/prepend.hpp
// // prepend.hpp // ~~~~~~~~~~~ // // 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) // #ifndef ASIO_PREPEND_HPP #define ASIO_PREPEND_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include <tuple> #include "asio/detail/type_traits.hpp" #include "asio/detail/push_options.hpp" namespace asio { /// Completion token type used to specify that the completion handler /// arguments should be passed additional values before the results of the /// operation. template <typename CompletionToken, typename... Values> class prepend_t { public: /// Constructor. template <typename T, typename... V> constexpr explicit prepend_t(T&& completion_token, V&&... values) : token_(static_cast<T&&>(completion_token)), values_(static_cast<V&&>(values)...) { } //private: CompletionToken token_; std::tuple<Values...> values_; }; /// Completion token type used to specify that the completion handler /// arguments should be passed additional values before the results of the /// operation. template <typename CompletionToken, typename... Values> ASIO_NODISCARD inline constexpr prepend_t<decay_t<CompletionToken>, decay_t<Values>...> prepend(CompletionToken&& completion_token, Values&&... values) { return prepend_t<decay_t<CompletionToken>, decay_t<Values>...>( static_cast<CompletionToken&&>(completion_token), static_cast<Values&&>(values)...); } } // namespace asio #include "asio/detail/pop_options.hpp" #include "asio/impl/prepend.hpp" #endif // ASIO_PREPEND_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/recycling_allocator.hpp
// // recycling_allocator.hpp // ~~~~~~~~~~~~~~~~~~~~~~~ // // 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) // #ifndef ASIO_RECYCLING_ALLOCATOR_HPP #define ASIO_RECYCLING_ALLOCATOR_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include "asio/detail/recycling_allocator.hpp" #include "asio/detail/push_options.hpp" namespace asio { /// An allocator that caches memory blocks in thread-local storage for reuse. /** * The @recycling_allocator uses a simple strategy where a limited number of * small memory blocks are cached in thread-local storage, if the current * thread is running an @c io_context or is part of a @c thread_pool. */ template <typename T> class recycling_allocator { public: /// The type of object allocated by the recycling allocator. typedef T value_type; /// Rebind the allocator to another value_type. template <typename U> struct rebind { /// The rebound @c allocator type. typedef recycling_allocator<U> other; }; /// Default constructor. constexpr recycling_allocator() noexcept { } /// Converting constructor. template <typename U> constexpr recycling_allocator( const recycling_allocator<U>&) noexcept { } /// Equality operator. Always returns true. constexpr bool operator==( const recycling_allocator&) const noexcept { return true; } /// Inequality operator. Always returns false. constexpr bool operator!=( const recycling_allocator&) const noexcept { return false; } /// Allocate memory for the specified number of values. T* allocate(std::size_t n) { return detail::recycling_allocator<T>().allocate(n); } /// Deallocate memory for the specified number of values. void deallocate(T* p, std::size_t n) { detail::recycling_allocator<T>().deallocate(p, n); } }; /// A proto-allocator that caches memory blocks in thread-local storage for /// reuse. /** * The @recycling_allocator uses a simple strategy where a limited number of * small memory blocks are cached in thread-local storage, if the current * thread is running an @c io_context or is part of a @c thread_pool. */ template <> class recycling_allocator<void> { public: /// No values are allocated by a proto-allocator. typedef void value_type; /// Rebind the allocator to another value_type. template <typename U> struct rebind { /// The rebound @c allocator type. typedef recycling_allocator<U> other; }; /// Default constructor. constexpr recycling_allocator() noexcept { } /// Converting constructor. template <typename U> constexpr recycling_allocator( const recycling_allocator<U>&) noexcept { } /// Equality operator. Always returns true. constexpr bool operator==( const recycling_allocator&) const noexcept { return true; } /// Inequality operator. Always returns false. constexpr bool operator!=( const recycling_allocator&) const noexcept { return false; } }; } // namespace asio #include "asio/detail/pop_options.hpp" #endif // ASIO_RECYCLING_ALLOCATOR_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/completion_condition.hpp
// // completion_condition.hpp // ~~~~~~~~~~~~~~~~~~~~~~~~ // // 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) // #ifndef ASIO_COMPLETION_CONDITION_HPP #define ASIO_COMPLETION_CONDITION_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include <cstddef> #include "asio/detail/type_traits.hpp" #include "asio/error_code.hpp" #include "asio/detail/push_options.hpp" namespace asio { namespace detail { // The default maximum number of bytes to transfer in a single operation. enum default_max_transfer_size_t { default_max_transfer_size = 65536 }; // Adapt result of old-style completion conditions (which had a bool result // where true indicated that the operation was complete). inline std::size_t adapt_completion_condition_result(bool result) { return result ? 0 : default_max_transfer_size; } // Adapt result of current completion conditions (which have a size_t result // where 0 means the operation is complete, and otherwise the result is the // maximum number of bytes to transfer on the next underlying operation). inline std::size_t adapt_completion_condition_result(std::size_t result) { return result; } class transfer_all_t { public: typedef std::size_t result_type; template <typename Error> std::size_t operator()(const Error& err, std::size_t) { return !!err ? 0 : default_max_transfer_size; } }; class transfer_at_least_t { public: typedef std::size_t result_type; explicit transfer_at_least_t(std::size_t minimum) : minimum_(minimum) { } template <typename Error> std::size_t operator()(const Error& err, std::size_t bytes_transferred) { return (!!err || bytes_transferred >= minimum_) ? 0 : default_max_transfer_size; } private: std::size_t minimum_; }; class transfer_exactly_t { public: typedef std::size_t result_type; explicit transfer_exactly_t(std::size_t size) : size_(size) { } template <typename Error> std::size_t operator()(const Error& err, std::size_t bytes_transferred) { return (!!err || bytes_transferred >= size_) ? 0 : (size_ - bytes_transferred < default_max_transfer_size ? size_ - bytes_transferred : std::size_t(default_max_transfer_size)); } private: std::size_t size_; }; template <typename T, typename = void> struct is_completion_condition_helper : false_type { }; template <typename T> struct is_completion_condition_helper<T, enable_if_t< is_same< result_of_t<T(asio::error_code, std::size_t)>, bool >::value > > : true_type { }; template <typename T> struct is_completion_condition_helper<T, enable_if_t< is_same< result_of_t<T(asio::error_code, std::size_t)>, std::size_t >::value > > : true_type { }; } // namespace detail #if defined(GENERATING_DOCUMENTATION) /// Trait for determining whether a function object is a completion condition. template <typename T> struct is_completion_condition { static constexpr bool value = automatically_determined; }; #else // defined(GENERATING_DOCUMENTATION) template <typename T> struct is_completion_condition : detail::is_completion_condition_helper<T> { }; #endif // defined(GENERATING_DOCUMENTATION) /** * @defgroup completion_condition Completion Condition Function Objects * * Function objects used for determining when a read or write operation should * complete. */ /*@{*/ /// Return a completion condition function object that indicates that a read or /// write operation should continue until all of the data has been transferred, /// or until an error occurs. /** * This function is used to create an object, of unspecified type, that meets * CompletionCondition requirements. * * @par Example * Reading until a buffer is full: * @code * boost::array<char, 128> buf; * asio::error_code ec; * std::size_t n = asio::read( * sock, asio::buffer(buf), * asio::transfer_all(), ec); * if (ec) * { * // An error occurred. * } * else * { * // n == 128 * } * @endcode */ #if defined(GENERATING_DOCUMENTATION) unspecified transfer_all(); #else inline detail::transfer_all_t transfer_all() { return detail::transfer_all_t(); } #endif /// Return a completion condition function object that indicates that a read or /// write operation should continue until a minimum number of bytes has been /// transferred, or until an error occurs. /** * This function is used to create an object, of unspecified type, that meets * CompletionCondition requirements. * * @par Example * Reading until a buffer is full or contains at least 64 bytes: * @code * boost::array<char, 128> buf; * asio::error_code ec; * std::size_t n = asio::read( * sock, asio::buffer(buf), * asio::transfer_at_least(64), ec); * if (ec) * { * // An error occurred. * } * else * { * // n >= 64 && n <= 128 * } * @endcode */ #if defined(GENERATING_DOCUMENTATION) unspecified transfer_at_least(std::size_t minimum); #else inline detail::transfer_at_least_t transfer_at_least(std::size_t minimum) { return detail::transfer_at_least_t(minimum); } #endif /// Return a completion condition function object that indicates that a read or /// write operation should continue until an exact number of bytes has been /// transferred, or until an error occurs. /** * This function is used to create an object, of unspecified type, that meets * CompletionCondition requirements. * * @par Example * Reading until a buffer is full or contains exactly 64 bytes: * @code * boost::array<char, 128> buf; * asio::error_code ec; * std::size_t n = asio::read( * sock, asio::buffer(buf), * asio::transfer_exactly(64), ec); * if (ec) * { * // An error occurred. * } * else * { * // n == 64 * } * @endcode */ #if defined(GENERATING_DOCUMENTATION) unspecified transfer_exactly(std::size_t size); #else inline detail::transfer_exactly_t transfer_exactly(std::size_t size) { return detail::transfer_exactly_t(size); } #endif /*@}*/ } // namespace asio #include "asio/detail/pop_options.hpp" #endif // ASIO_COMPLETION_CONDITION_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/basic_serial_port.hpp
// // basic_serial_port.hpp // ~~~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // Copyright (c) 2008 Rep Invariant Systems, Inc. ([email protected]) // // 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) // #ifndef ASIO_BASIC_SERIAL_PORT_HPP #define ASIO_BASIC_SERIAL_PORT_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #if defined(ASIO_HAS_SERIAL_PORT) \ || defined(GENERATING_DOCUMENTATION) #include <string> #include <utility> #include "asio/any_io_executor.hpp" #include "asio/async_result.hpp" #include "asio/detail/handler_type_requirements.hpp" #include "asio/detail/io_object_impl.hpp" #include "asio/detail/non_const_lvalue.hpp" #include "asio/detail/throw_error.hpp" #include "asio/detail/type_traits.hpp" #include "asio/error.hpp" #include "asio/execution_context.hpp" #include "asio/serial_port_base.hpp" #if defined(ASIO_HAS_IOCP) # include "asio/detail/win_iocp_serial_port_service.hpp" #else # include "asio/detail/posix_serial_port_service.hpp" #endif #include "asio/detail/push_options.hpp" namespace asio { /// Provides serial port functionality. /** * The basic_serial_port class provides a wrapper over serial port * functionality. * * @par Thread Safety * @e Distinct @e objects: Safe.@n * @e Shared @e objects: Unsafe. */ template <typename Executor = any_io_executor> class basic_serial_port : public serial_port_base { private: class initiate_async_write_some; class initiate_async_read_some; public: /// The type of the executor associated with the object. typedef Executor executor_type; /// Rebinds the serial port type to another executor. template <typename Executor1> struct rebind_executor { /// The serial port type when rebound to the specified executor. typedef basic_serial_port<Executor1> other; }; /// The native representation of a serial port. #if defined(GENERATING_DOCUMENTATION) typedef implementation_defined native_handle_type; #elif defined(ASIO_HAS_IOCP) typedef detail::win_iocp_serial_port_service::native_handle_type native_handle_type; #else typedef detail::posix_serial_port_service::native_handle_type native_handle_type; #endif /// A basic_basic_serial_port is always the lowest layer. typedef basic_serial_port lowest_layer_type; /// Construct a basic_serial_port without opening it. /** * This constructor creates a serial port without opening it. * * @param ex The I/O executor that the serial port will use, by default, to * dispatch handlers for any asynchronous operations performed on the * serial port. */ explicit basic_serial_port(const executor_type& ex) : impl_(0, ex) { } /// Construct a basic_serial_port without opening it. /** * This constructor creates a serial port without opening it. * * @param context An execution context which provides the I/O executor that * the serial port will use, by default, to dispatch handlers for any * asynchronous operations performed on the serial port. */ template <typename ExecutionContext> explicit basic_serial_port(ExecutionContext& context, constraint_t< is_convertible<ExecutionContext&, execution_context&>::value, defaulted_constraint > = defaulted_constraint()) : impl_(0, 0, context) { } /// Construct and open a basic_serial_port. /** * This constructor creates and opens a serial port for the specified device * name. * * @param ex The I/O executor that the serial port will use, by default, to * dispatch handlers for any asynchronous operations performed on the * serial port. * * @param device The platform-specific device name for this serial * port. */ basic_serial_port(const executor_type& ex, const char* device) : impl_(0, ex) { asio::error_code ec; impl_.get_service().open(impl_.get_implementation(), device, ec); asio::detail::throw_error(ec, "open"); } /// Construct and open a basic_serial_port. /** * This constructor creates and opens a serial port for the specified device * name. * * @param context An execution context which provides the I/O executor that * the serial port will use, by default, to dispatch handlers for any * asynchronous operations performed on the serial port. * * @param device The platform-specific device name for this serial * port. */ template <typename ExecutionContext> basic_serial_port(ExecutionContext& context, const char* device, constraint_t< is_convertible<ExecutionContext&, execution_context&>::value > = 0) : impl_(0, 0, context) { asio::error_code ec; impl_.get_service().open(impl_.get_implementation(), device, ec); asio::detail::throw_error(ec, "open"); } /// Construct and open a basic_serial_port. /** * This constructor creates and opens a serial port for the specified device * name. * * @param ex The I/O executor that the serial port will use, by default, to * dispatch handlers for any asynchronous operations performed on the * serial port. * * @param device The platform-specific device name for this serial * port. */ basic_serial_port(const executor_type& ex, const std::string& device) : impl_(0, ex) { asio::error_code ec; impl_.get_service().open(impl_.get_implementation(), device, ec); asio::detail::throw_error(ec, "open"); } /// Construct and open a basic_serial_port. /** * This constructor creates and opens a serial port for the specified device * name. * * @param context An execution context which provides the I/O executor that * the serial port will use, by default, to dispatch handlers for any * asynchronous operations performed on the serial port. * * @param device The platform-specific device name for this serial * port. */ template <typename ExecutionContext> basic_serial_port(ExecutionContext& context, const std::string& device, constraint_t< is_convertible<ExecutionContext&, execution_context&>::value > = 0) : impl_(0, 0, context) { asio::error_code ec; impl_.get_service().open(impl_.get_implementation(), device, ec); asio::detail::throw_error(ec, "open"); } /// Construct a basic_serial_port on an existing native serial port. /** * This constructor creates a serial port object to hold an existing native * serial port. * * @param ex The I/O executor that the serial port will use, by default, to * dispatch handlers for any asynchronous operations performed on the * serial port. * * @param native_serial_port A native serial port. * * @throws asio::system_error Thrown on failure. */ basic_serial_port(const executor_type& ex, const native_handle_type& native_serial_port) : impl_(0, ex) { asio::error_code ec; impl_.get_service().assign(impl_.get_implementation(), native_serial_port, ec); asio::detail::throw_error(ec, "assign"); } /// Construct a basic_serial_port on an existing native serial port. /** * This constructor creates a serial port object to hold an existing native * serial port. * * @param context An execution context which provides the I/O executor that * the serial port will use, by default, to dispatch handlers for any * asynchronous operations performed on the serial port. * * @param native_serial_port A native serial port. * * @throws asio::system_error Thrown on failure. */ template <typename ExecutionContext> basic_serial_port(ExecutionContext& context, const native_handle_type& native_serial_port, constraint_t< is_convertible<ExecutionContext&, execution_context&>::value > = 0) : impl_(0, 0, context) { asio::error_code ec; impl_.get_service().assign(impl_.get_implementation(), native_serial_port, ec); asio::detail::throw_error(ec, "assign"); } /// Move-construct a basic_serial_port from another. /** * This constructor moves a serial port from one object to another. * * @param other The other basic_serial_port object from which the move will * occur. * * @note Following the move, the moved-from object is in the same state as if * constructed using the @c basic_serial_port(const executor_type&) * constructor. */ basic_serial_port(basic_serial_port&& other) : impl_(std::move(other.impl_)) { } /// Move-assign a basic_serial_port from another. /** * This assignment operator moves a serial port from one object to another. * * @param other The other basic_serial_port object from which the move will * occur. * * @note Following the move, the moved-from object is in the same state as if * constructed using the @c basic_serial_port(const executor_type&) * constructor. */ basic_serial_port& operator=(basic_serial_port&& other) { impl_ = std::move(other.impl_); return *this; } // All serial ports have access to each other's implementations. template <typename Executor1> friend class basic_serial_port; /// Move-construct a basic_serial_port from a serial port of another executor /// type. /** * This constructor moves a serial port from one object to another. * * @param other The other basic_serial_port object from which the move will * occur. * * @note Following the move, the moved-from object is in the same state as if * constructed using the @c basic_serial_port(const executor_type&) * constructor. */ template <typename Executor1> basic_serial_port(basic_serial_port<Executor1>&& other, constraint_t< is_convertible<Executor1, Executor>::value, defaulted_constraint > = defaulted_constraint()) : impl_(std::move(other.impl_)) { } /// Move-assign a basic_serial_port from a serial port of another executor /// type. /** * This assignment operator moves a serial port from one object to another. * * @param other The other basic_serial_port object from which the move will * occur. * * @note Following the move, the moved-from object is in the same state as if * constructed using the @c basic_serial_port(const executor_type&) * constructor. */ template <typename Executor1> constraint_t< is_convertible<Executor1, Executor>::value, basic_serial_port& > operator=(basic_serial_port<Executor1>&& other) { basic_serial_port tmp(std::move(other)); impl_ = std::move(tmp.impl_); return *this; } /// Destroys the serial port. /** * This function destroys the serial port, cancelling any outstanding * asynchronous wait operations associated with the serial port as if by * calling @c cancel. */ ~basic_serial_port() { } /// Get the executor associated with the object. const executor_type& get_executor() noexcept { return impl_.get_executor(); } /// Get a reference to the lowest layer. /** * This function returns a reference to the lowest layer in a stack of * layers. Since a basic_serial_port cannot contain any further layers, it * simply returns a reference to itself. * * @return A reference to the lowest layer in the stack of layers. Ownership * is not transferred to the caller. */ lowest_layer_type& lowest_layer() { return *this; } /// Get a const reference to the lowest layer. /** * This function returns a const reference to the lowest layer in a stack of * layers. Since a basic_serial_port cannot contain any further layers, it * simply returns a reference to itself. * * @return A const reference to the lowest layer in the stack of layers. * Ownership is not transferred to the caller. */ const lowest_layer_type& lowest_layer() const { return *this; } /// Open the serial port using the specified device name. /** * This function opens the serial port for the specified device name. * * @param device The platform-specific device name. * * @throws asio::system_error Thrown on failure. */ void open(const std::string& device) { asio::error_code ec; impl_.get_service().open(impl_.get_implementation(), device, ec); asio::detail::throw_error(ec, "open"); } /// Open the serial port using the specified device name. /** * This function opens the serial port using the given platform-specific * device name. * * @param device The platform-specific device name. * * @param ec Set the indicate what error occurred, if any. */ ASIO_SYNC_OP_VOID open(const std::string& device, asio::error_code& ec) { impl_.get_service().open(impl_.get_implementation(), device, ec); ASIO_SYNC_OP_VOID_RETURN(ec); } /// Assign an existing native serial port to the serial port. /* * This function opens the serial port to hold an existing native serial port. * * @param native_serial_port A native serial port. * * @throws asio::system_error Thrown on failure. */ void assign(const native_handle_type& native_serial_port) { asio::error_code ec; impl_.get_service().assign(impl_.get_implementation(), native_serial_port, ec); asio::detail::throw_error(ec, "assign"); } /// Assign an existing native serial port to the serial port. /* * This function opens the serial port to hold an existing native serial port. * * @param native_serial_port A native serial port. * * @param ec Set to indicate what error occurred, if any. */ ASIO_SYNC_OP_VOID assign(const native_handle_type& native_serial_port, asio::error_code& ec) { impl_.get_service().assign(impl_.get_implementation(), native_serial_port, ec); ASIO_SYNC_OP_VOID_RETURN(ec); } /// Determine whether the serial port is open. bool is_open() const { return impl_.get_service().is_open(impl_.get_implementation()); } /// Close the serial port. /** * This function is used to close the serial port. Any asynchronous read or * write operations will be cancelled immediately, and will complete with the * asio::error::operation_aborted error. * * @throws asio::system_error Thrown on failure. */ void close() { asio::error_code ec; impl_.get_service().close(impl_.get_implementation(), ec); asio::detail::throw_error(ec, "close"); } /// Close the serial port. /** * This function is used to close the serial port. Any asynchronous read or * write operations will be cancelled immediately, and will complete with the * asio::error::operation_aborted error. * * @param ec Set to indicate what error occurred, if any. */ ASIO_SYNC_OP_VOID close(asio::error_code& ec) { impl_.get_service().close(impl_.get_implementation(), ec); ASIO_SYNC_OP_VOID_RETURN(ec); } /// Get the native serial port representation. /** * This function may be used to obtain the underlying representation of the * serial port. This is intended to allow access to native serial port * functionality that is not otherwise provided. */ native_handle_type native_handle() { return impl_.get_service().native_handle(impl_.get_implementation()); } /// Cancel all asynchronous operations associated with the serial port. /** * This function causes all outstanding asynchronous read or write operations * to finish immediately, and the handlers for cancelled operations will be * passed the asio::error::operation_aborted error. * * @throws asio::system_error Thrown on failure. */ void cancel() { asio::error_code ec; impl_.get_service().cancel(impl_.get_implementation(), ec); asio::detail::throw_error(ec, "cancel"); } /// Cancel all asynchronous operations associated with the serial port. /** * This function causes all outstanding asynchronous read or write operations * to finish immediately, and the handlers for cancelled operations will be * passed the asio::error::operation_aborted error. * * @param ec Set to indicate what error occurred, if any. */ ASIO_SYNC_OP_VOID cancel(asio::error_code& ec) { impl_.get_service().cancel(impl_.get_implementation(), ec); ASIO_SYNC_OP_VOID_RETURN(ec); } /// Send a break sequence to the serial port. /** * This function causes a break sequence of platform-specific duration to be * sent out the serial port. * * @throws asio::system_error Thrown on failure. */ void send_break() { asio::error_code ec; impl_.get_service().send_break(impl_.get_implementation(), ec); asio::detail::throw_error(ec, "send_break"); } /// Send a break sequence to the serial port. /** * This function causes a break sequence of platform-specific duration to be * sent out the serial port. * * @param ec Set to indicate what error occurred, if any. */ ASIO_SYNC_OP_VOID send_break(asio::error_code& ec) { impl_.get_service().send_break(impl_.get_implementation(), ec); ASIO_SYNC_OP_VOID_RETURN(ec); } /// Set an option on the serial port. /** * This function is used to set an option on the serial port. * * @param option The option value to be set on the serial port. * * @throws asio::system_error Thrown on failure. * * @sa SettableSerialPortOption @n * asio::serial_port_base::baud_rate @n * asio::serial_port_base::flow_control @n * asio::serial_port_base::parity @n * asio::serial_port_base::stop_bits @n * asio::serial_port_base::character_size */ template <typename SettableSerialPortOption> void set_option(const SettableSerialPortOption& option) { asio::error_code ec; impl_.get_service().set_option(impl_.get_implementation(), option, ec); asio::detail::throw_error(ec, "set_option"); } /// Set an option on the serial port. /** * This function is used to set an option on the serial port. * * @param option The option value to be set on the serial port. * * @param ec Set to indicate what error occurred, if any. * * @sa SettableSerialPortOption @n * asio::serial_port_base::baud_rate @n * asio::serial_port_base::flow_control @n * asio::serial_port_base::parity @n * asio::serial_port_base::stop_bits @n * asio::serial_port_base::character_size */ template <typename SettableSerialPortOption> ASIO_SYNC_OP_VOID set_option(const SettableSerialPortOption& option, asio::error_code& ec) { impl_.get_service().set_option(impl_.get_implementation(), option, ec); ASIO_SYNC_OP_VOID_RETURN(ec); } /// Get an option from the serial port. /** * This function is used to get the current value of an option on the serial * port. * * @param option The option value to be obtained from the serial port. * * @throws asio::system_error Thrown on failure. * * @sa GettableSerialPortOption @n * asio::serial_port_base::baud_rate @n * asio::serial_port_base::flow_control @n * asio::serial_port_base::parity @n * asio::serial_port_base::stop_bits @n * asio::serial_port_base::character_size */ template <typename GettableSerialPortOption> void get_option(GettableSerialPortOption& option) const { asio::error_code ec; impl_.get_service().get_option(impl_.get_implementation(), option, ec); asio::detail::throw_error(ec, "get_option"); } /// Get an option from the serial port. /** * This function is used to get the current value of an option on the serial * port. * * @param option The option value to be obtained from the serial port. * * @param ec Set to indicate what error occurred, if any. * * @sa GettableSerialPortOption @n * asio::serial_port_base::baud_rate @n * asio::serial_port_base::flow_control @n * asio::serial_port_base::parity @n * asio::serial_port_base::stop_bits @n * asio::serial_port_base::character_size */ template <typename GettableSerialPortOption> ASIO_SYNC_OP_VOID get_option(GettableSerialPortOption& option, asio::error_code& ec) const { impl_.get_service().get_option(impl_.get_implementation(), option, ec); ASIO_SYNC_OP_VOID_RETURN(ec); } /// Write some data to the serial port. /** * This function is used to write data to the serial port. The function call * will block until one or more bytes of the data has been written * successfully, or until an error occurs. * * @param buffers One or more data buffers to be written to the serial port. * * @returns The number of bytes written. * * @throws asio::system_error Thrown on failure. An error code of * asio::error::eof indicates that the connection was closed by the * peer. * * @note The write_some operation may not transmit all of the data to the * peer. Consider using the @ref write function if you need to ensure that * all data is written before the blocking operation completes. * * @par Example * To write a single data buffer use the @ref buffer function as follows: * @code * basic_serial_port.write_some(asio::buffer(data, size)); * @endcode * See the @ref buffer documentation for information on writing multiple * buffers in one go, and how to use it with arrays, boost::array or * std::vector. */ template <typename ConstBufferSequence> std::size_t write_some(const ConstBufferSequence& buffers) { asio::error_code ec; std::size_t s = impl_.get_service().write_some( impl_.get_implementation(), buffers, ec); asio::detail::throw_error(ec, "write_some"); return s; } /// Write some data to the serial port. /** * This function is used to write data to the serial port. The function call * will block until one or more bytes of the data has been written * successfully, or until an error occurs. * * @param buffers One or more data buffers to be written to the serial port. * * @param ec Set to indicate what error occurred, if any. * * @returns The number of bytes written. Returns 0 if an error occurred. * * @note The write_some operation may not transmit all of the data to the * peer. Consider using the @ref write function if you need to ensure that * all data is written before the blocking operation completes. */ template <typename ConstBufferSequence> std::size_t write_some(const ConstBufferSequence& buffers, asio::error_code& ec) { return impl_.get_service().write_some( impl_.get_implementation(), buffers, ec); } /// Start an asynchronous write. /** * This function is used to asynchronously write data to the serial port. * It is an initiating function for an @ref asynchronous_operation, and always * returns immediately. * * @param buffers One or more data buffers to be written to the serial port. * Although the buffers object may be copied as necessary, ownership of the * underlying memory blocks is retained by the caller, which must guarantee * that they remain valid until the completion handler is called. * * @param token The @ref completion_token that will be used to produce a * completion handler, which will be called when the write completes. * Potential completion tokens include @ref use_future, @ref use_awaitable, * @ref yield_context, or a function object with the correct completion * signature. The function signature of the completion handler must be: * @code void handler( * const asio::error_code& error, // Result of operation. * std::size_t bytes_transferred // Number of bytes written. * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the completion handler will not be invoked from within this function. * On immediate completion, invocation of the handler will be performed in a * manner equivalent to using asio::async_immediate(). * * @par Completion Signature * @code void(asio::error_code, std::size_t) @endcode * * @note The write operation may not transmit all of the data to the peer. * Consider using the @ref async_write function if you need to ensure that all * data is written before the asynchronous operation completes. * * @par Example * To write a single data buffer use the @ref buffer function as follows: * @code * basic_serial_port.async_write_some( * asio::buffer(data, size), handler); * @endcode * See the @ref buffer documentation for information on writing multiple * buffers in one go, and how to use it with arrays, boost::array or * std::vector. * * @par Per-Operation Cancellation * On POSIX or Windows operating systems, this asynchronous operation supports * cancellation for the following asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * @li @c cancellation_type::total */ template <typename ConstBufferSequence, ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code, std::size_t)) WriteToken = default_completion_token_t<executor_type>> auto async_write_some(const ConstBufferSequence& buffers, WriteToken&& token = default_completion_token_t<executor_type>()) -> decltype( async_initiate<WriteToken, void (asio::error_code, std::size_t)>( declval<initiate_async_write_some>(), token, buffers)) { return async_initiate<WriteToken, void (asio::error_code, std::size_t)>( initiate_async_write_some(this), token, buffers); } /// Read some data from the serial port. /** * This function is used to read data from the serial port. The function * call will block until one or more bytes of data has been read successfully, * or until an error occurs. * * @param buffers One or more buffers into which the data will be read. * * @returns The number of bytes read. * * @throws asio::system_error Thrown on failure. An error code of * asio::error::eof indicates that the connection was closed by the * peer. * * @note The read_some operation may not read all of the requested number of * bytes. Consider using the @ref read function if you need to ensure that * the requested amount of data is read before the blocking operation * completes. * * @par Example * To read into a single data buffer use the @ref buffer function as follows: * @code * basic_serial_port.read_some(asio::buffer(data, size)); * @endcode * See the @ref buffer documentation for information on reading into multiple * buffers in one go, and how to use it with arrays, boost::array or * std::vector. */ template <typename MutableBufferSequence> std::size_t read_some(const MutableBufferSequence& buffers) { asio::error_code ec; std::size_t s = impl_.get_service().read_some( impl_.get_implementation(), buffers, ec); asio::detail::throw_error(ec, "read_some"); return s; } /// Read some data from the serial port. /** * This function is used to read data from the serial port. The function * call will block until one or more bytes of data has been read successfully, * or until an error occurs. * * @param buffers One or more buffers into which the data will be read. * * @param ec Set to indicate what error occurred, if any. * * @returns The number of bytes read. Returns 0 if an error occurred. * * @note The read_some operation may not read all of the requested number of * bytes. Consider using the @ref read function if you need to ensure that * the requested amount of data is read before the blocking operation * completes. */ template <typename MutableBufferSequence> std::size_t read_some(const MutableBufferSequence& buffers, asio::error_code& ec) { return impl_.get_service().read_some( impl_.get_implementation(), buffers, ec); } /// Start an asynchronous read. /** * This function is used to asynchronously read data from the serial port. * It is an initiating function for an @ref asynchronous_operation, and always * returns immediately. * * @param buffers One or more buffers into which the data will be read. * Although the buffers object may be copied as necessary, ownership of the * underlying memory blocks is retained by the caller, which must guarantee * that they remain valid until the completion handler is called. * * @param token The @ref completion_token that will be used to produce a * completion handler, which will be called when the read completes. * Potential completion tokens include @ref use_future, @ref use_awaitable, * @ref yield_context, or a function object with the correct completion * signature. The function signature of the completion handler must be: * @code void handler( * const asio::error_code& error, // Result of operation. * std::size_t bytes_transferred // Number of bytes read. * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the completion handler will not be invoked from within this function. * On immediate completion, invocation of the handler will be performed in a * manner equivalent to using asio::async_immediate(). * * @par Completion Signature * @code void(asio::error_code, std::size_t) @endcode * * @note The read operation may not read all of the requested number of bytes. * Consider using the @ref async_read function if you need to ensure that the * requested amount of data is read before the asynchronous operation * completes. * * @par Example * To read into a single data buffer use the @ref buffer function as follows: * @code * basic_serial_port.async_read_some( * asio::buffer(data, size), handler); * @endcode * See the @ref buffer documentation for information on reading into multiple * buffers in one go, and how to use it with arrays, boost::array or * std::vector. * * @par Per-Operation Cancellation * On POSIX or Windows operating systems, this asynchronous operation supports * cancellation for the following asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * @li @c cancellation_type::total */ template <typename MutableBufferSequence, ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code, std::size_t)) ReadToken = default_completion_token_t<executor_type>> auto async_read_some(const MutableBufferSequence& buffers, ReadToken&& token = default_completion_token_t<executor_type>()) -> decltype( async_initiate<ReadToken, void (asio::error_code, std::size_t)>( declval<initiate_async_read_some>(), token, buffers)) { return async_initiate<ReadToken, void (asio::error_code, std::size_t)>( initiate_async_read_some(this), token, buffers); } private: // Disallow copying and assignment. basic_serial_port(const basic_serial_port&) = delete; basic_serial_port& operator=(const basic_serial_port&) = delete; class initiate_async_write_some { public: typedef Executor executor_type; explicit initiate_async_write_some(basic_serial_port* self) : self_(self) { } const executor_type& get_executor() const noexcept { return self_->get_executor(); } template <typename WriteHandler, typename ConstBufferSequence> void operator()(WriteHandler&& handler, const ConstBufferSequence& buffers) const { // If you get an error on the following line it means that your handler // does not meet the documented type requirements for a WriteHandler. ASIO_WRITE_HANDLER_CHECK(WriteHandler, handler) type_check; detail::non_const_lvalue<WriteHandler> handler2(handler); self_->impl_.get_service().async_write_some( self_->impl_.get_implementation(), buffers, handler2.value, self_->impl_.get_executor()); } private: basic_serial_port* self_; }; class initiate_async_read_some { public: typedef Executor executor_type; explicit initiate_async_read_some(basic_serial_port* self) : self_(self) { } const executor_type& get_executor() const noexcept { return self_->get_executor(); } template <typename ReadHandler, typename MutableBufferSequence> void operator()(ReadHandler&& handler, const MutableBufferSequence& buffers) const { // If you get an error on the following line it means that your handler // does not meet the documented type requirements for a ReadHandler. ASIO_READ_HANDLER_CHECK(ReadHandler, handler) type_check; detail::non_const_lvalue<ReadHandler> handler2(handler); self_->impl_.get_service().async_read_some( self_->impl_.get_implementation(), buffers, handler2.value, self_->impl_.get_executor()); } private: basic_serial_port* self_; }; #if defined(ASIO_HAS_IOCP) detail::io_object_impl<detail::win_iocp_serial_port_service, Executor> impl_; #else detail::io_object_impl<detail::posix_serial_port_service, Executor> impl_; #endif }; } // namespace asio #include "asio/detail/pop_options.hpp" #endif // defined(ASIO_HAS_SERIAL_PORT) // || defined(GENERATING_DOCUMENTATION) #endif // ASIO_BASIC_SERIAL_PORT_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/file_base.hpp
// // file_base.hpp // ~~~~~~~~~~~~~ // // 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) // #ifndef ASIO_FILE_BASE_HPP #define ASIO_FILE_BASE_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #if defined(ASIO_HAS_FILE) \ || defined(GENERATING_DOCUMENTATION) #if !defined(ASIO_WINDOWS) # include <fcntl.h> #endif // !defined(ASIO_WINDOWS) #include "asio/detail/push_options.hpp" namespace asio { /// The file_base class is used as a base for the basic_stream_file and /// basic_random_access_file class templates so that we have a common place to /// define flags. class file_base { public: #if defined(GENERATING_DOCUMENTATION) /// A bitmask type (C++ Std [lib.bitmask.types]). typedef unspecified flags; /// Open the file for reading. static const flags read_only = implementation_defined; /// Open the file for writing. static const flags write_only = implementation_defined; /// Open the file for reading and writing. static const flags read_write = implementation_defined; /// Open the file in append mode. static const flags append = implementation_defined; /// Create the file if it does not exist. static const flags create = implementation_defined; /// Ensure a new file is created. Must be combined with @c create. static const flags exclusive = implementation_defined; /// Open the file with any existing contents truncated. static const flags truncate = implementation_defined; /// Open the file so that write operations automatically synchronise the file /// data and metadata to disk. static const flags sync_all_on_write = implementation_defined; #else enum flags { #if defined(ASIO_WINDOWS) read_only = 1, write_only = 2, read_write = 4, append = 8, create = 16, exclusive = 32, truncate = 64, sync_all_on_write = 128 #else // defined(ASIO_WINDOWS) read_only = O_RDONLY, write_only = O_WRONLY, read_write = O_RDWR, append = O_APPEND, create = O_CREAT, exclusive = O_EXCL, truncate = O_TRUNC, sync_all_on_write = O_SYNC #endif // defined(ASIO_WINDOWS) }; // Implement bitmask operations as shown in C++ Std [lib.bitmask.types]. friend flags operator&(flags x, flags y) { return static_cast<flags>( static_cast<unsigned int>(x) & static_cast<unsigned int>(y)); } friend flags operator|(flags x, flags y) { return static_cast<flags>( static_cast<unsigned int>(x) | static_cast<unsigned int>(y)); } friend flags operator^(flags x, flags y) { return static_cast<flags>( static_cast<unsigned int>(x) ^ static_cast<unsigned int>(y)); } friend flags operator~(flags x) { return static_cast<flags>(~static_cast<unsigned int>(x)); } friend flags& operator&=(flags& x, flags y) { x = x & y; return x; } friend flags& operator|=(flags& x, flags y) { x = x | y; return x; } friend flags& operator^=(flags& x, flags y) { x = x ^ y; return x; } #endif /// Basis for seeking in a file. enum seek_basis { #if defined(GENERATING_DOCUMENTATION) /// Seek to an absolute position. seek_set = implementation_defined, /// Seek to an offset relative to the current file position. seek_cur = implementation_defined, /// Seek to an offset relative to the end of the file. seek_end = implementation_defined #else seek_set = SEEK_SET, seek_cur = SEEK_CUR, seek_end = SEEK_END #endif }; protected: /// Protected destructor to prevent deletion through this type. ~file_base() { } }; } // namespace asio #include "asio/detail/pop_options.hpp" #endif // defined(ASIO_HAS_FILE) // || defined(GENERATING_DOCUMENTATION) #endif // ASIO_FILE_BASE_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/buffered_stream.hpp
// // buffered_stream.hpp // ~~~~~~~~~~~~~~~~~~~ // // 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) // #ifndef ASIO_BUFFERED_STREAM_HPP #define ASIO_BUFFERED_STREAM_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include <cstddef> #include "asio/async_result.hpp" #include "asio/buffered_read_stream.hpp" #include "asio/buffered_write_stream.hpp" #include "asio/buffered_stream_fwd.hpp" #include "asio/detail/noncopyable.hpp" #include "asio/error.hpp" #include "asio/detail/push_options.hpp" namespace asio { /// Adds buffering to the read- and write-related operations of a stream. /** * The buffered_stream class template can be used to add buffering to the * synchronous and asynchronous read and write operations of a stream. * * @par Thread Safety * @e Distinct @e objects: Safe.@n * @e Shared @e objects: Unsafe. * * @par Concepts: * AsyncReadStream, AsyncWriteStream, Stream, SyncReadStream, SyncWriteStream. */ template <typename Stream> class buffered_stream : private noncopyable { public: /// The type of the next layer. typedef remove_reference_t<Stream> next_layer_type; /// The type of the lowest layer. typedef typename next_layer_type::lowest_layer_type lowest_layer_type; /// The type of the executor associated with the object. typedef typename lowest_layer_type::executor_type executor_type; /// Construct, passing the specified argument to initialise the next layer. template <typename Arg> explicit buffered_stream(Arg&& a) : inner_stream_impl_(static_cast<Arg&&>(a)), stream_impl_(inner_stream_impl_) { } /// Construct, passing the specified argument to initialise the next layer. template <typename Arg> explicit buffered_stream(Arg&& a, std::size_t read_buffer_size, std::size_t write_buffer_size) : inner_stream_impl_(static_cast<Arg&&>(a), write_buffer_size), stream_impl_(inner_stream_impl_, read_buffer_size) { } /// Get a reference to the next layer. next_layer_type& next_layer() { return stream_impl_.next_layer().next_layer(); } /// Get a reference to the lowest layer. lowest_layer_type& lowest_layer() { return stream_impl_.lowest_layer(); } /// Get a const reference to the lowest layer. const lowest_layer_type& lowest_layer() const { return stream_impl_.lowest_layer(); } /// Get the executor associated with the object. executor_type get_executor() noexcept { return stream_impl_.lowest_layer().get_executor(); } /// Close the stream. void close() { stream_impl_.close(); } /// Close the stream. ASIO_SYNC_OP_VOID close(asio::error_code& ec) { stream_impl_.close(ec); ASIO_SYNC_OP_VOID_RETURN(ec); } /// Flush all data from the buffer to the next layer. Returns the number of /// bytes written to the next layer on the last write operation. Throws an /// exception on failure. std::size_t flush() { return stream_impl_.next_layer().flush(); } /// Flush all data from the buffer to the next layer. Returns the number of /// bytes written to the next layer on the last write operation, or 0 if an /// error occurred. std::size_t flush(asio::error_code& ec) { return stream_impl_.next_layer().flush(ec); } /// Start an asynchronous flush. /** * @par Completion Signature * @code void(asio::error_code, std::size_t) @endcode */ template < ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code, std::size_t)) WriteHandler = default_completion_token_t<executor_type>> auto async_flush( WriteHandler&& handler = default_completion_token_t<executor_type>()) -> decltype( declval<buffered_write_stream<Stream>&>().async_flush( static_cast<WriteHandler&&>(handler))) { return stream_impl_.next_layer().async_flush( static_cast<WriteHandler&&>(handler)); } /// Write the given data to the stream. Returns the number of bytes written. /// Throws an exception on failure. template <typename ConstBufferSequence> std::size_t write_some(const ConstBufferSequence& buffers) { return stream_impl_.write_some(buffers); } /// Write the given data to the stream. Returns the number of bytes written, /// or 0 if an error occurred. template <typename ConstBufferSequence> std::size_t write_some(const ConstBufferSequence& buffers, asio::error_code& ec) { return stream_impl_.write_some(buffers, ec); } /// Start an asynchronous write. The data being written must be valid for the /// lifetime of the asynchronous operation. /** * @par Completion Signature * @code void(asio::error_code, std::size_t) @endcode */ template <typename ConstBufferSequence, ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code, std::size_t)) WriteHandler = default_completion_token_t<executor_type>> auto async_write_some(const ConstBufferSequence& buffers, WriteHandler&& handler = default_completion_token_t<executor_type>()) -> decltype( declval<Stream&>().async_write_some(buffers, static_cast<WriteHandler&&>(handler))) { return stream_impl_.async_write_some(buffers, static_cast<WriteHandler&&>(handler)); } /// Fill the buffer with some data. Returns the number of bytes placed in the /// buffer as a result of the operation. Throws an exception on failure. std::size_t fill() { return stream_impl_.fill(); } /// Fill the buffer with some data. Returns the number of bytes placed in the /// buffer as a result of the operation, or 0 if an error occurred. std::size_t fill(asio::error_code& ec) { return stream_impl_.fill(ec); } /// Start an asynchronous fill. /** * @par Completion Signature * @code void(asio::error_code, std::size_t) @endcode */ template < ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code, std::size_t)) ReadHandler = default_completion_token_t<executor_type>> auto async_fill( ReadHandler&& handler = default_completion_token_t<executor_type>()) -> decltype( declval<buffered_read_stream< buffered_write_stream<Stream>>&>().async_fill( static_cast<ReadHandler&&>(handler))) { return stream_impl_.async_fill(static_cast<ReadHandler&&>(handler)); } /// Read some data from the stream. Returns the number of bytes read. Throws /// an exception on failure. template <typename MutableBufferSequence> std::size_t read_some(const MutableBufferSequence& buffers) { return stream_impl_.read_some(buffers); } /// Read some data from the stream. Returns the number of bytes read or 0 if /// an error occurred. template <typename MutableBufferSequence> std::size_t read_some(const MutableBufferSequence& buffers, asio::error_code& ec) { return stream_impl_.read_some(buffers, ec); } /// Start an asynchronous read. The buffer into which the data will be read /// must be valid for the lifetime of the asynchronous operation. /** * @par Completion Signature * @code void(asio::error_code, std::size_t) @endcode */ template <typename MutableBufferSequence, ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code, std::size_t)) ReadHandler = default_completion_token_t<executor_type>> auto async_read_some(const MutableBufferSequence& buffers, ReadHandler&& handler = default_completion_token_t<executor_type>()) -> decltype( declval<Stream&>().async_read_some(buffers, static_cast<ReadHandler&&>(handler))) { return stream_impl_.async_read_some(buffers, static_cast<ReadHandler&&>(handler)); } /// Peek at the incoming data on the stream. Returns the number of bytes read. /// Throws an exception on failure. template <typename MutableBufferSequence> std::size_t peek(const MutableBufferSequence& buffers) { return stream_impl_.peek(buffers); } /// Peek at the incoming data on the stream. Returns the number of bytes read, /// or 0 if an error occurred. template <typename MutableBufferSequence> std::size_t peek(const MutableBufferSequence& buffers, asio::error_code& ec) { return stream_impl_.peek(buffers, ec); } /// Determine the amount of data that may be read without blocking. std::size_t in_avail() { return stream_impl_.in_avail(); } /// Determine the amount of data that may be read without blocking. std::size_t in_avail(asio::error_code& ec) { return stream_impl_.in_avail(ec); } private: // The buffered write stream. typedef buffered_write_stream<Stream> write_stream_type; write_stream_type inner_stream_impl_; // The buffered read stream. typedef buffered_read_stream<write_stream_type&> read_stream_type; read_stream_type stream_impl_; }; } // namespace asio #include "asio/detail/pop_options.hpp" #endif // ASIO_BUFFERED_STREAM_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/cancellation_type.hpp
// // cancellation_type.hpp // ~~~~~~~~~~~~~~~~~~~~~ // // 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) // #ifndef ASIO_CANCELLATION_TYPE_HPP #define ASIO_CANCELLATION_TYPE_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include "asio/detail/push_options.hpp" namespace asio { # if defined(GENERATING_DOCUMENTATION) /// Enumeration representing the different types of cancellation that may /// be requested from or implemented by an asynchronous operation. enum cancellation_type { /// Bitmask representing no types of cancellation. none = 0, /// Requests cancellation where, following a successful cancellation, the only /// safe operations on the I/O object are closure or destruction. terminal = 1, /// Requests cancellation where a successful cancellation may result in /// partial side effects or no side effects. Following cancellation, the I/O /// object is in a well-known state, and may be used for further operations. partial = 2, /// Requests cancellation where a successful cancellation results in no /// apparent side effects. Following cancellation, the I/O object is in the /// same observable state as it was prior to the operation. total = 4, /// Bitmask representing all types of cancellation. all = 0xFFFFFFFF }; /// Portability typedef. typedef cancellation_type cancellation_type_t; #else // defined(GENERATING_DOCUMENTATION) enum class cancellation_type : unsigned int { none = 0, terminal = 1, partial = 2, total = 4, all = 0xFFFFFFFF }; typedef cancellation_type cancellation_type_t; #endif // defined(GENERATING_DOCUMENTATION) /// Negation operator. /** * @relates cancellation_type */ inline constexpr bool operator!(cancellation_type_t x) { return static_cast<unsigned int>(x) == 0; } /// Bitwise and operator. /** * @relates cancellation_type */ inline constexpr cancellation_type_t operator&( cancellation_type_t x, cancellation_type_t y) { return static_cast<cancellation_type_t>( static_cast<unsigned int>(x) & static_cast<unsigned int>(y)); } /// Bitwise or operator. /** * @relates cancellation_type */ inline constexpr cancellation_type_t operator|( cancellation_type_t x, cancellation_type_t y) { return static_cast<cancellation_type_t>( static_cast<unsigned int>(x) | static_cast<unsigned int>(y)); } /// Bitwise xor operator. /** * @relates cancellation_type */ inline constexpr cancellation_type_t operator^( cancellation_type_t x, cancellation_type_t y) { return static_cast<cancellation_type_t>( static_cast<unsigned int>(x) ^ static_cast<unsigned int>(y)); } /// Bitwise negation operator. /** * @relates cancellation_type */ inline constexpr cancellation_type_t operator~(cancellation_type_t x) { return static_cast<cancellation_type_t>(~static_cast<unsigned int>(x)); } /// Bitwise and-assignment operator. /** * @relates cancellation_type */ inline cancellation_type_t& operator&=( cancellation_type_t& x, cancellation_type_t y) { x = x & y; return x; } /// Bitwise or-assignment operator. /** * @relates cancellation_type */ inline cancellation_type_t& operator|=( cancellation_type_t& x, cancellation_type_t y) { x = x | y; return x; } /// Bitwise xor-assignment operator. /** * @relates cancellation_type */ inline cancellation_type_t& operator^=( cancellation_type_t& x, cancellation_type_t y) { x = x ^ y; return x; } } // namespace asio #include "asio/detail/pop_options.hpp" #endif // ASIO_CANCELLATION_TYPE_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/basic_writable_pipe.hpp
// // basic_writable_pipe.hpp // ~~~~~~~~~~~~~~~~~~~~~~~ // // 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) // #ifndef ASIO_BASIC_WRITABLE_PIPE_HPP #define ASIO_BASIC_WRITABLE_PIPE_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #if defined(ASIO_HAS_PIPE) \ || defined(GENERATING_DOCUMENTATION) #include <string> #include <utility> #include "asio/any_io_executor.hpp" #include "asio/async_result.hpp" #include "asio/detail/handler_type_requirements.hpp" #include "asio/detail/io_object_impl.hpp" #include "asio/detail/non_const_lvalue.hpp" #include "asio/detail/throw_error.hpp" #include "asio/detail/type_traits.hpp" #include "asio/error.hpp" #include "asio/execution_context.hpp" #if defined(ASIO_HAS_IOCP) # include "asio/detail/win_iocp_handle_service.hpp" #elif defined(ASIO_HAS_IO_URING_AS_DEFAULT) # include "asio/detail/io_uring_descriptor_service.hpp" #else # include "asio/detail/reactive_descriptor_service.hpp" #endif #include "asio/detail/push_options.hpp" namespace asio { /// Provides pipe functionality. /** * The basic_writable_pipe class provides a wrapper over pipe * functionality. * * @par Thread Safety * @e Distinct @e objects: Safe.@n * @e Shared @e objects: Unsafe. */ template <typename Executor = any_io_executor> class basic_writable_pipe { private: class initiate_async_write_some; public: /// The type of the executor associated with the object. typedef Executor executor_type; /// Rebinds the pipe type to another executor. template <typename Executor1> struct rebind_executor { /// The pipe type when rebound to the specified executor. typedef basic_writable_pipe<Executor1> other; }; /// The native representation of a pipe. #if defined(GENERATING_DOCUMENTATION) typedef implementation_defined native_handle_type; #elif defined(ASIO_HAS_IOCP) typedef detail::win_iocp_handle_service::native_handle_type native_handle_type; #elif defined(ASIO_HAS_IO_URING_AS_DEFAULT) typedef detail::io_uring_descriptor_service::native_handle_type native_handle_type; #else typedef detail::reactive_descriptor_service::native_handle_type native_handle_type; #endif /// A basic_writable_pipe is always the lowest layer. typedef basic_writable_pipe lowest_layer_type; /// Construct a basic_writable_pipe without opening it. /** * This constructor creates a pipe without opening it. * * @param ex The I/O executor that the pipe will use, by default, to dispatch * handlers for any asynchronous operations performed on the pipe. */ explicit basic_writable_pipe(const executor_type& ex) : impl_(0, ex) { } /// Construct a basic_writable_pipe without opening it. /** * This constructor creates a pipe without opening it. * * @param context An execution context which provides the I/O executor that * the pipe will use, by default, to dispatch handlers for any asynchronous * operations performed on the pipe. */ template <typename ExecutionContext> explicit basic_writable_pipe(ExecutionContext& context, constraint_t< is_convertible<ExecutionContext&, execution_context&>::value, defaulted_constraint > = defaulted_constraint()) : impl_(0, 0, context) { } /// Construct a basic_writable_pipe on an existing native pipe. /** * This constructor creates a pipe object to hold an existing native * pipe. * * @param ex The I/O executor that the pipe will use, by default, to * dispatch handlers for any asynchronous operations performed on the * pipe. * * @param native_pipe A native pipe. * * @throws asio::system_error Thrown on failure. */ basic_writable_pipe(const executor_type& ex, const native_handle_type& native_pipe) : impl_(0, ex) { asio::error_code ec; impl_.get_service().assign(impl_.get_implementation(), native_pipe, ec); asio::detail::throw_error(ec, "assign"); } /// Construct a basic_writable_pipe on an existing native pipe. /** * This constructor creates a pipe object to hold an existing native * pipe. * * @param context An execution context which provides the I/O executor that * the pipe will use, by default, to dispatch handlers for any * asynchronous operations performed on the pipe. * * @param native_pipe A native pipe. * * @throws asio::system_error Thrown on failure. */ template <typename ExecutionContext> basic_writable_pipe(ExecutionContext& context, const native_handle_type& native_pipe, constraint_t< is_convertible<ExecutionContext&, execution_context&>::value > = 0) : impl_(0, 0, context) { asio::error_code ec; impl_.get_service().assign(impl_.get_implementation(), native_pipe, ec); asio::detail::throw_error(ec, "assign"); } /// Move-construct a basic_writable_pipe from another. /** * This constructor moves a pipe from one object to another. * * @param other The other basic_writable_pipe object from which the move will * occur. * * @note Following the move, the moved-from object is in the same state as if * constructed using the @c basic_writable_pipe(const executor_type&) * constructor. */ basic_writable_pipe(basic_writable_pipe&& other) : impl_(std::move(other.impl_)) { } /// Move-assign a basic_writable_pipe from another. /** * This assignment operator moves a pipe from one object to another. * * @param other The other basic_writable_pipe object from which the move will * occur. * * @note Following the move, the moved-from object is in the same state as if * constructed using the @c basic_writable_pipe(const executor_type&) * constructor. */ basic_writable_pipe& operator=(basic_writable_pipe&& other) { impl_ = std::move(other.impl_); return *this; } // All pipes have access to each other's implementations. template <typename Executor1> friend class basic_writable_pipe; /// Move-construct a basic_writable_pipe from a pipe of another executor type. /** * This constructor moves a pipe from one object to another. * * @param other The other basic_writable_pipe object from which the move will * occur. * * @note Following the move, the moved-from object is in the same state as if * constructed using the @c basic_writable_pipe(const executor_type&) * constructor. */ template <typename Executor1> basic_writable_pipe(basic_writable_pipe<Executor1>&& other, constraint_t< is_convertible<Executor1, Executor>::value, defaulted_constraint > = defaulted_constraint()) : impl_(std::move(other.impl_)) { } /// Move-assign a basic_writable_pipe from a pipe of another executor type. /** * This assignment operator moves a pipe from one object to another. * * @param other The other basic_writable_pipe object from which the move will * occur. * * @note Following the move, the moved-from object is in the same state as if * constructed using the @c basic_writable_pipe(const executor_type&) * constructor. */ template <typename Executor1> constraint_t< is_convertible<Executor1, Executor>::value, basic_writable_pipe& > operator=(basic_writable_pipe<Executor1>&& other) { basic_writable_pipe tmp(std::move(other)); impl_ = std::move(tmp.impl_); return *this; } /// Destroys the pipe. /** * This function destroys the pipe, cancelling any outstanding * asynchronous wait operations associated with the pipe as if by * calling @c cancel. */ ~basic_writable_pipe() { } /// Get the executor associated with the object. const executor_type& get_executor() noexcept { return impl_.get_executor(); } /// Get a reference to the lowest layer. /** * This function returns a reference to the lowest layer in a stack of * layers. Since a basic_writable_pipe cannot contain any further layers, it * simply returns a reference to itself. * * @return A reference to the lowest layer in the stack of layers. Ownership * is not transferred to the caller. */ lowest_layer_type& lowest_layer() { return *this; } /// Get a const reference to the lowest layer. /** * This function returns a const reference to the lowest layer in a stack of * layers. Since a basic_writable_pipe cannot contain any further layers, it * simply returns a reference to itself. * * @return A const reference to the lowest layer in the stack of layers. * Ownership is not transferred to the caller. */ const lowest_layer_type& lowest_layer() const { return *this; } /// Assign an existing native pipe to the pipe. /* * This function opens the pipe to hold an existing native pipe. * * @param native_pipe A native pipe. * * @throws asio::system_error Thrown on failure. */ void assign(const native_handle_type& native_pipe) { asio::error_code ec; impl_.get_service().assign(impl_.get_implementation(), native_pipe, ec); asio::detail::throw_error(ec, "assign"); } /// Assign an existing native pipe to the pipe. /* * This function opens the pipe to hold an existing native pipe. * * @param native_pipe A native pipe. * * @param ec Set to indicate what error occurred, if any. */ ASIO_SYNC_OP_VOID assign(const native_handle_type& native_pipe, asio::error_code& ec) { impl_.get_service().assign(impl_.get_implementation(), native_pipe, ec); ASIO_SYNC_OP_VOID_RETURN(ec); } /// Determine whether the pipe is open. bool is_open() const { return impl_.get_service().is_open(impl_.get_implementation()); } /// Close the pipe. /** * This function is used to close the pipe. Any asynchronous write operations * will be cancelled immediately, and will complete with the * asio::error::operation_aborted error. * * @throws asio::system_error Thrown on failure. */ void close() { asio::error_code ec; impl_.get_service().close(impl_.get_implementation(), ec); asio::detail::throw_error(ec, "close"); } /// Close the pipe. /** * This function is used to close the pipe. Any asynchronous write operations * will be cancelled immediately, and will complete with the * asio::error::operation_aborted error. * * @param ec Set to indicate what error occurred, if any. */ ASIO_SYNC_OP_VOID close(asio::error_code& ec) { impl_.get_service().close(impl_.get_implementation(), ec); ASIO_SYNC_OP_VOID_RETURN(ec); } /// Release ownership of the underlying native pipe. /** * This function causes all outstanding asynchronous write operations to * finish immediately, and the handlers for cancelled operations will be * passed the asio::error::operation_aborted error. Ownership of the * native pipe is then transferred to the caller. * * @throws asio::system_error Thrown on failure. * * @note This function is unsupported on Windows versions prior to Windows * 8.1, and will fail with asio::error::operation_not_supported on * these platforms. */ #if defined(ASIO_MSVC) && (ASIO_MSVC >= 1400) \ && (!defined(_WIN32_WINNT) || _WIN32_WINNT < 0x0603) __declspec(deprecated("This function always fails with " "operation_not_supported when used on Windows versions " "prior to Windows 8.1.")) #endif native_handle_type release() { asio::error_code ec; native_handle_type s = impl_.get_service().release( impl_.get_implementation(), ec); asio::detail::throw_error(ec, "release"); return s; } /// Release ownership of the underlying native pipe. /** * This function causes all outstanding asynchronous write operations to * finish immediately, and the handlers for cancelled operations will be * passed the asio::error::operation_aborted error. Ownership of the * native pipe is then transferred to the caller. * * @param ec Set to indicate what error occurred, if any. * * @note This function is unsupported on Windows versions prior to Windows * 8.1, and will fail with asio::error::operation_not_supported on * these platforms. */ #if defined(ASIO_MSVC) && (ASIO_MSVC >= 1400) \ && (!defined(_WIN32_WINNT) || _WIN32_WINNT < 0x0603) __declspec(deprecated("This function always fails with " "operation_not_supported when used on Windows versions " "prior to Windows 8.1.")) #endif native_handle_type release(asio::error_code& ec) { return impl_.get_service().release(impl_.get_implementation(), ec); } /// Get the native pipe representation. /** * This function may be used to obtain the underlying representation of the * pipe. This is intended to allow access to native pipe * functionality that is not otherwise provided. */ native_handle_type native_handle() { return impl_.get_service().native_handle(impl_.get_implementation()); } /// Cancel all asynchronous operations associated with the pipe. /** * This function causes all outstanding asynchronous write operations to * finish immediately, and the handlers for cancelled operations will be * passed the asio::error::operation_aborted error. * * @throws asio::system_error Thrown on failure. */ void cancel() { asio::error_code ec; impl_.get_service().cancel(impl_.get_implementation(), ec); asio::detail::throw_error(ec, "cancel"); } /// Cancel all asynchronous operations associated with the pipe. /** * This function causes all outstanding asynchronous write operations to * finish immediately, and the handlers for cancelled operations will be * passed the asio::error::operation_aborted error. * * @param ec Set to indicate what error occurred, if any. */ ASIO_SYNC_OP_VOID cancel(asio::error_code& ec) { impl_.get_service().cancel(impl_.get_implementation(), ec); ASIO_SYNC_OP_VOID_RETURN(ec); } /// Write some data to the pipe. /** * This function is used to write data to the pipe. The function call will * block until one or more bytes of the data has been written successfully, * or until an error occurs. * * @param buffers One or more data buffers to be written to the pipe. * * @returns The number of bytes written. * * @throws asio::system_error Thrown on failure. An error code of * asio::error::eof indicates that the connection was closed by the * peer. * * @note The write_some operation may not transmit all of the data to the * peer. Consider using the @ref write function if you need to ensure that * all data is written before the blocking operation completes. * * @par Example * To write a single data buffer use the @ref buffer function as follows: * @code * pipe.write_some(asio::buffer(data, size)); * @endcode * See the @ref buffer documentation for information on writing multiple * buffers in one go, and how to use it with arrays, boost::array or * std::vector. */ template <typename ConstBufferSequence> std::size_t write_some(const ConstBufferSequence& buffers) { asio::error_code ec; std::size_t s = impl_.get_service().write_some( impl_.get_implementation(), buffers, ec); asio::detail::throw_error(ec, "write_some"); return s; } /// Write some data to the pipe. /** * This function is used to write data to the pipe. The function call will * block until one or more bytes of the data has been written successfully, * or until an error occurs. * * @param buffers One or more data buffers to be written to the pipe. * * @param ec Set to indicate what error occurred, if any. * * @returns The number of bytes written. Returns 0 if an error occurred. * * @note The write_some operation may not transmit all of the data to the * peer. Consider using the @ref write function if you need to ensure that * all data is written before the blocking operation completes. */ template <typename ConstBufferSequence> std::size_t write_some(const ConstBufferSequence& buffers, asio::error_code& ec) { return impl_.get_service().write_some( impl_.get_implementation(), buffers, ec); } /// Start an asynchronous write. /** * This function is used to asynchronously write data to the pipe. It is an * initiating function for an @ref asynchronous_operation, and always returns * immediately. * * @param buffers One or more data buffers to be written to the pipe. * Although the buffers object may be copied as necessary, ownership of the * underlying memory blocks is retained by the caller, which must guarantee * that they remain valid until the completion handler is called. * * @param token The @ref completion_token that will be used to produce a * completion handler, which will be called when the write completes. * Potential completion tokens include @ref use_future, @ref use_awaitable, * @ref yield_context, or a function object with the correct completion * signature. The function signature of the completion handler must be: * @code void handler( * const asio::error_code& error, // Result of operation. * std::size_t bytes_transferred // Number of bytes written. * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the completion handler will not be invoked from within this function. * On immediate completion, invocation of the handler will be performed in a * manner equivalent to using asio::async_immediate(). * * @par Completion Signature * @code void(asio::error_code, std::size_t) @endcode * * @note The write operation may not transmit all of the data to the peer. * Consider using the @ref async_write function if you need to ensure that all * data is written before the asynchronous operation completes. * * @par Example * To write a single data buffer use the @ref buffer function as follows: * @code * pipe.async_write_some(asio::buffer(data, size), handler); * @endcode * See the @ref buffer documentation for information on writing multiple * buffers in one go, and how to use it with arrays, boost::array or * std::vector. */ template <typename ConstBufferSequence, ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code, std::size_t)) WriteToken = default_completion_token_t<executor_type>> auto async_write_some(const ConstBufferSequence& buffers, WriteToken&& token = default_completion_token_t<executor_type>()) -> decltype( async_initiate<WriteToken, void (asio::error_code, std::size_t)>( declval<initiate_async_write_some>(), token, buffers)) { return async_initiate<WriteToken, void (asio::error_code, std::size_t)>( initiate_async_write_some(this), token, buffers); } private: // Disallow copying and assignment. basic_writable_pipe(const basic_writable_pipe&) = delete; basic_writable_pipe& operator=(const basic_writable_pipe&) = delete; class initiate_async_write_some { public: typedef Executor executor_type; explicit initiate_async_write_some(basic_writable_pipe* self) : self_(self) { } const executor_type& get_executor() const noexcept { return self_->get_executor(); } template <typename WriteHandler, typename ConstBufferSequence> void operator()(WriteHandler&& handler, const ConstBufferSequence& buffers) const { // If you get an error on the following line it means that your handler // does not meet the documented type requirements for a WriteHandler. ASIO_WRITE_HANDLER_CHECK(WriteHandler, handler) type_check; detail::non_const_lvalue<WriteHandler> handler2(handler); self_->impl_.get_service().async_write_some( self_->impl_.get_implementation(), buffers, handler2.value, self_->impl_.get_executor()); } private: basic_writable_pipe* self_; }; #if defined(ASIO_HAS_IOCP) detail::io_object_impl<detail::win_iocp_handle_service, Executor> impl_; #elif defined(ASIO_HAS_IO_URING_AS_DEFAULT) detail::io_object_impl<detail::io_uring_descriptor_service, Executor> impl_; #else detail::io_object_impl<detail::reactive_descriptor_service, Executor> impl_; #endif }; } // namespace asio #include "asio/detail/pop_options.hpp" #endif // defined(ASIO_HAS_PIPE) // || defined(GENERATING_DOCUMENTATION) #endif // ASIO_BASIC_WRITABLE_PIPE_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/buffer_registration.hpp
// // buffer_registration.hpp // ~~~~~~~~~~~~~~~~~~~~~~~ // // 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) // #ifndef ASIO_BUFFER_REGISTRATION_HPP #define ASIO_BUFFER_REGISTRATION_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include <iterator> #include <utility> #include <vector> #include "asio/detail/memory.hpp" #include "asio/execution/context.hpp" #include "asio/execution/executor.hpp" #include "asio/execution_context.hpp" #include "asio/is_executor.hpp" #include "asio/query.hpp" #include "asio/registered_buffer.hpp" #if defined(ASIO_HAS_IO_URING) # include "asio/detail/scheduler.hpp" # include "asio/detail/io_uring_service.hpp" #endif // defined(ASIO_HAS_IO_URING) #include "asio/detail/push_options.hpp" namespace asio { namespace detail { class buffer_registration_base { protected: static mutable_registered_buffer make_buffer(const mutable_buffer& b, const void* scope, int index) noexcept { return mutable_registered_buffer(b, registered_buffer_id(scope, index)); } }; } // namespace detail /// Automatically registers and unregistered buffers with an execution context. /** * For portability, applications should assume that only one registration is * permitted per execution context. */ template <typename MutableBufferSequence, typename Allocator = std::allocator<void>> class buffer_registration : detail::buffer_registration_base { public: /// The allocator type used for allocating storage for the buffers container. typedef Allocator allocator_type; #if defined(GENERATING_DOCUMENTATION) /// The type of an iterator over the registered buffers. typedef unspecified iterator; /// The type of a const iterator over the registered buffers. typedef unspecified const_iterator; #else // defined(GENERATING_DOCUMENTATION) typedef std::vector<mutable_registered_buffer>::const_iterator iterator; typedef std::vector<mutable_registered_buffer>::const_iterator const_iterator; #endif // defined(GENERATING_DOCUMENTATION) /// Register buffers with an executor's execution context. template <typename Executor> buffer_registration(const Executor& ex, const MutableBufferSequence& buffer_sequence, const allocator_type& alloc = allocator_type(), constraint_t< is_executor<Executor>::value || execution::is_executor<Executor>::value > = 0) : buffer_sequence_(buffer_sequence), buffers_( ASIO_REBIND_ALLOC(allocator_type, mutable_registered_buffer)(alloc)) { init_buffers(buffer_registration::get_context(ex), asio::buffer_sequence_begin(buffer_sequence_), asio::buffer_sequence_end(buffer_sequence_)); } /// Register buffers with an execution context. template <typename ExecutionContext> buffer_registration(ExecutionContext& ctx, const MutableBufferSequence& buffer_sequence, const allocator_type& alloc = allocator_type(), constraint_t< is_convertible<ExecutionContext&, execution_context&>::value > = 0) : buffer_sequence_(buffer_sequence), buffers_( ASIO_REBIND_ALLOC(allocator_type, mutable_registered_buffer)(alloc)) { init_buffers(ctx, asio::buffer_sequence_begin(buffer_sequence_), asio::buffer_sequence_end(buffer_sequence_)); } /// Move constructor. buffer_registration(buffer_registration&& other) noexcept : buffer_sequence_(std::move(other.buffer_sequence_)), buffers_(std::move(other.buffers_)) { #if defined(ASIO_HAS_IO_URING) service_ = other.service_; other.service_ = 0; #endif // defined(ASIO_HAS_IO_URING) } /// Unregisters the buffers. ~buffer_registration() { #if defined(ASIO_HAS_IO_URING) if (service_) service_->unregister_buffers(); #endif // defined(ASIO_HAS_IO_URING) } /// Move assignment. buffer_registration& operator=(buffer_registration&& other) noexcept { if (this != &other) { buffer_sequence_ = std::move(other.buffer_sequence_); buffers_ = std::move(other.buffers_); #if defined(ASIO_HAS_IO_URING) if (service_) service_->unregister_buffers(); service_ = other.service_; other.service_ = 0; #endif // defined(ASIO_HAS_IO_URING) } return *this; } /// Get the number of registered buffers. std::size_t size() const noexcept { return buffers_.size(); } /// Get the begin iterator for the sequence of registered buffers. const_iterator begin() const noexcept { return buffers_.begin(); } /// Get the begin iterator for the sequence of registered buffers. const_iterator cbegin() const noexcept { return buffers_.cbegin(); } /// Get the end iterator for the sequence of registered buffers. const_iterator end() const noexcept { return buffers_.end(); } /// Get the end iterator for the sequence of registered buffers. const_iterator cend() const noexcept { return buffers_.cend(); } /// Get the buffer at the specified index. const mutable_registered_buffer& operator[](std::size_t i) noexcept { return buffers_[i]; } /// Get the buffer at the specified index. const mutable_registered_buffer& at(std::size_t i) noexcept { return buffers_.at(i); } private: // Disallow copying and assignment. buffer_registration(const buffer_registration&) = delete; buffer_registration& operator=(const buffer_registration&) = delete; // Helper function to get an executor's context. template <typename T> static execution_context& get_context(const T& t, enable_if_t<execution::is_executor<T>::value>* = 0) { return asio::query(t, execution::context); } // Helper function to get an executor's context. template <typename T> static execution_context& get_context(const T& t, enable_if_t<!execution::is_executor<T>::value>* = 0) { return t.context(); } // Helper function to initialise the container of buffers. template <typename Iterator> void init_buffers(execution_context& ctx, Iterator begin, Iterator end) { std::size_t n = std::distance(begin, end); buffers_.resize(n); #if defined(ASIO_HAS_IO_URING) service_ = &use_service<detail::io_uring_service>(ctx); std::vector<iovec, ASIO_REBIND_ALLOC(allocator_type, iovec)> iovecs(n, ASIO_REBIND_ALLOC(allocator_type, iovec)( buffers_.get_allocator())); #endif // defined(ASIO_HAS_IO_URING) Iterator iter = begin; for (int index = 0; iter != end; ++index, ++iter) { mutable_buffer b(*iter); std::size_t i = static_cast<std::size_t>(index); buffers_[i] = this->make_buffer(b, &ctx, index); #if defined(ASIO_HAS_IO_URING) iovecs[i].iov_base = buffers_[i].data(); iovecs[i].iov_len = buffers_[i].size(); #endif // defined(ASIO_HAS_IO_URING) } #if defined(ASIO_HAS_IO_URING) if (n > 0) { service_->register_buffers(&iovecs[0], static_cast<unsigned>(iovecs.size())); } #endif // defined(ASIO_HAS_IO_URING) } MutableBufferSequence buffer_sequence_; std::vector<mutable_registered_buffer, ASIO_REBIND_ALLOC(allocator_type, mutable_registered_buffer)> buffers_; #if defined(ASIO_HAS_IO_URING) detail::io_uring_service* service_; #endif // defined(ASIO_HAS_IO_URING) }; /// Register buffers with an execution context. template <typename Executor, typename MutableBufferSequence> ASIO_NODISCARD inline buffer_registration<MutableBufferSequence> register_buffers(const Executor& ex, const MutableBufferSequence& buffer_sequence, constraint_t< is_executor<Executor>::value || execution::is_executor<Executor>::value > = 0) { return buffer_registration<MutableBufferSequence>(ex, buffer_sequence); } /// Register buffers with an execution context. template <typename Executor, typename MutableBufferSequence, typename Allocator> ASIO_NODISCARD inline buffer_registration<MutableBufferSequence, Allocator> register_buffers(const Executor& ex, const MutableBufferSequence& buffer_sequence, const Allocator& alloc, constraint_t< is_executor<Executor>::value || execution::is_executor<Executor>::value > = 0) { return buffer_registration<MutableBufferSequence, Allocator>( ex, buffer_sequence, alloc); } /// Register buffers with an execution context. template <typename ExecutionContext, typename MutableBufferSequence> ASIO_NODISCARD inline buffer_registration<MutableBufferSequence> register_buffers(ExecutionContext& ctx, const MutableBufferSequence& buffer_sequence, constraint_t< is_convertible<ExecutionContext&, execution_context&>::value > = 0) { return buffer_registration<MutableBufferSequence>(ctx, buffer_sequence); } /// Register buffers with an execution context. template <typename ExecutionContext, typename MutableBufferSequence, typename Allocator> ASIO_NODISCARD inline buffer_registration<MutableBufferSequence, Allocator> register_buffers(ExecutionContext& ctx, const MutableBufferSequence& buffer_sequence, const Allocator& alloc, constraint_t< is_convertible<ExecutionContext&, execution_context&>::value > = 0) { return buffer_registration<MutableBufferSequence, Allocator>( ctx, buffer_sequence, alloc); } } // namespace asio #include "asio/detail/pop_options.hpp" #endif // ASIO_BUFFER_REGISTRATION_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/bind_allocator.hpp
// // bind_allocator.hpp // ~~~~~~~~~~~~~~~~~~ // // 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) // #ifndef ASIO_BIND_ALLOCATOR_HPP #define ASIO_BIND_ALLOCATOR_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include "asio/associated_allocator.hpp" #include "asio/associated_executor.hpp" #include "asio/associator.hpp" #include "asio/async_result.hpp" #include "asio/detail/initiation_base.hpp" #include "asio/detail/type_traits.hpp" #include "asio/detail/push_options.hpp" namespace asio { namespace detail { // Helper to automatically define nested typedef result_type. template <typename T, typename = void> struct allocator_binder_result_type { protected: typedef void result_type_or_void; }; template <typename T> struct allocator_binder_result_type<T, void_t<typename T::result_type>> { typedef typename T::result_type result_type; protected: typedef result_type result_type_or_void; }; template <typename R> struct allocator_binder_result_type<R(*)()> { typedef R result_type; protected: typedef result_type result_type_or_void; }; template <typename R> struct allocator_binder_result_type<R(&)()> { typedef R result_type; protected: typedef result_type result_type_or_void; }; template <typename R, typename A1> struct allocator_binder_result_type<R(*)(A1)> { typedef R result_type; protected: typedef result_type result_type_or_void; }; template <typename R, typename A1> struct allocator_binder_result_type<R(&)(A1)> { typedef R result_type; protected: typedef result_type result_type_or_void; }; template <typename R, typename A1, typename A2> struct allocator_binder_result_type<R(*)(A1, A2)> { typedef R result_type; protected: typedef result_type result_type_or_void; }; template <typename R, typename A1, typename A2> struct allocator_binder_result_type<R(&)(A1, A2)> { typedef R result_type; protected: typedef result_type result_type_or_void; }; // Helper to automatically define nested typedef argument_type. template <typename T, typename = void> struct allocator_binder_argument_type {}; template <typename T> struct allocator_binder_argument_type<T, void_t<typename T::argument_type>> { typedef typename T::argument_type argument_type; }; template <typename R, typename A1> struct allocator_binder_argument_type<R(*)(A1)> { typedef A1 argument_type; }; template <typename R, typename A1> struct allocator_binder_argument_type<R(&)(A1)> { typedef A1 argument_type; }; // Helper to automatically define nested typedefs first_argument_type and // second_argument_type. template <typename T, typename = void> struct allocator_binder_argument_types {}; template <typename T> struct allocator_binder_argument_types<T, void_t<typename T::first_argument_type>> { typedef typename T::first_argument_type first_argument_type; typedef typename T::second_argument_type second_argument_type; }; template <typename R, typename A1, typename A2> struct allocator_binder_argument_type<R(*)(A1, A2)> { typedef A1 first_argument_type; typedef A2 second_argument_type; }; template <typename R, typename A1, typename A2> struct allocator_binder_argument_type<R(&)(A1, A2)> { typedef A1 first_argument_type; typedef A2 second_argument_type; }; } // namespace detail /// A call wrapper type to bind an allocator of type @c Allocator /// to an object of type @c T. template <typename T, typename Allocator> class allocator_binder #if !defined(GENERATING_DOCUMENTATION) : public detail::allocator_binder_result_type<T>, public detail::allocator_binder_argument_type<T>, public detail::allocator_binder_argument_types<T> #endif // !defined(GENERATING_DOCUMENTATION) { public: /// The type of the target object. typedef T target_type; /// The type of the associated allocator. typedef Allocator allocator_type; #if defined(GENERATING_DOCUMENTATION) /// The return type if a function. /** * The type of @c result_type is based on the type @c T of the wrapper's * target object: * * @li if @c T is a pointer to function type, @c result_type is a synonym for * the return type of @c T; * * @li if @c T is a class type with a member type @c result_type, then @c * result_type is a synonym for @c T::result_type; * * @li otherwise @c result_type is not defined. */ typedef see_below result_type; /// The type of the function's argument. /** * The type of @c argument_type is based on the type @c T of the wrapper's * target object: * * @li if @c T is a pointer to a function type accepting a single argument, * @c argument_type is a synonym for the return type of @c T; * * @li if @c T is a class type with a member type @c argument_type, then @c * argument_type is a synonym for @c T::argument_type; * * @li otherwise @c argument_type is not defined. */ typedef see_below argument_type; /// The type of the function's first argument. /** * The type of @c first_argument_type is based on the type @c T of the * wrapper's target object: * * @li if @c T is a pointer to a function type accepting two arguments, @c * first_argument_type is a synonym for the return type of @c T; * * @li if @c T is a class type with a member type @c first_argument_type, * then @c first_argument_type is a synonym for @c T::first_argument_type; * * @li otherwise @c first_argument_type is not defined. */ typedef see_below first_argument_type; /// The type of the function's second argument. /** * The type of @c second_argument_type is based on the type @c T of the * wrapper's target object: * * @li if @c T is a pointer to a function type accepting two arguments, @c * second_argument_type is a synonym for the return type of @c T; * * @li if @c T is a class type with a member type @c first_argument_type, * then @c second_argument_type is a synonym for @c T::second_argument_type; * * @li otherwise @c second_argument_type is not defined. */ typedef see_below second_argument_type; #endif // defined(GENERATING_DOCUMENTATION) /// Construct an allocator wrapper for the specified object. /** * This constructor is only valid if the type @c T is constructible from type * @c U. */ template <typename U> allocator_binder(const allocator_type& s, U&& u) : allocator_(s), target_(static_cast<U&&>(u)) { } /// Copy constructor. allocator_binder(const allocator_binder& other) : allocator_(other.get_allocator()), target_(other.get()) { } /// Construct a copy, but specify a different allocator. allocator_binder(const allocator_type& s, const allocator_binder& other) : allocator_(s), target_(other.get()) { } /// Construct a copy of a different allocator wrapper type. /** * This constructor is only valid if the @c Allocator type is * constructible from type @c OtherAllocator, and the type @c T is * constructible from type @c U. */ template <typename U, typename OtherAllocator> allocator_binder(const allocator_binder<U, OtherAllocator>& other, constraint_t<is_constructible<Allocator, OtherAllocator>::value> = 0, constraint_t<is_constructible<T, U>::value> = 0) : allocator_(other.get_allocator()), target_(other.get()) { } /// Construct a copy of a different allocator wrapper type, but /// specify a different allocator. /** * This constructor is only valid if the type @c T is constructible from type * @c U. */ template <typename U, typename OtherAllocator> allocator_binder(const allocator_type& s, const allocator_binder<U, OtherAllocator>& other, constraint_t<is_constructible<T, U>::value> = 0) : allocator_(s), target_(other.get()) { } /// Move constructor. allocator_binder(allocator_binder&& other) : allocator_(static_cast<allocator_type&&>( other.get_allocator())), target_(static_cast<T&&>(other.get())) { } /// Move construct the target object, but specify a different allocator. allocator_binder(const allocator_type& s, allocator_binder&& other) : allocator_(s), target_(static_cast<T&&>(other.get())) { } /// Move construct from a different allocator wrapper type. template <typename U, typename OtherAllocator> allocator_binder( allocator_binder<U, OtherAllocator>&& other, constraint_t<is_constructible<Allocator, OtherAllocator>::value> = 0, constraint_t<is_constructible<T, U>::value> = 0) : allocator_(static_cast<OtherAllocator&&>( other.get_allocator())), target_(static_cast<U&&>(other.get())) { } /// Move construct from a different allocator wrapper type, but /// specify a different allocator. template <typename U, typename OtherAllocator> allocator_binder(const allocator_type& s, allocator_binder<U, OtherAllocator>&& other, constraint_t<is_constructible<T, U>::value> = 0) : allocator_(s), target_(static_cast<U&&>(other.get())) { } /// Destructor. ~allocator_binder() { } /// Obtain a reference to the target object. target_type& get() noexcept { return target_; } /// Obtain a reference to the target object. const target_type& get() const noexcept { return target_; } /// Obtain the associated allocator. allocator_type get_allocator() const noexcept { return allocator_; } /// Forwarding function call operator. template <typename... Args> result_of_t<T(Args...)> operator()(Args&&... args) { return target_(static_cast<Args&&>(args)...); } /// Forwarding function call operator. template <typename... Args> result_of_t<T(Args...)> operator()(Args&&... args) const { return target_(static_cast<Args&&>(args)...); } private: Allocator allocator_; T target_; }; /// A function object type that adapts a @ref completion_token to specify that /// the completion handler should have the supplied allocator as its associated /// allocator. /** * May also be used directly as a completion token, in which case it adapts the * asynchronous operation's default completion token (or asio::deferred * if no default is available). */ template <typename Allocator> struct partial_allocator_binder { /// Constructor that specifies associated allocator. explicit partial_allocator_binder(const Allocator& ex) : allocator_(ex) { } /// Adapt a @ref completion_token to specify that the completion handler /// should have the allocator as its associated allocator. template <typename CompletionToken> ASIO_NODISCARD inline constexpr allocator_binder<decay_t<CompletionToken>, Allocator> operator()(CompletionToken&& completion_token) const { return allocator_binder<decay_t<CompletionToken>, Allocator>( allocator_, static_cast<CompletionToken&&>(completion_token)); } //private: Allocator allocator_; }; /// Create a partial completion token that associates an allocator. template <typename Allocator> ASIO_NODISCARD inline partial_allocator_binder<Allocator> bind_allocator(const Allocator& ex) { return partial_allocator_binder<Allocator>(ex); } /// Associate an object of type @c T with an allocator of type /// @c Allocator. template <typename Allocator, typename T> ASIO_NODISCARD inline allocator_binder<decay_t<T>, Allocator> bind_allocator(const Allocator& s, T&& t) { return allocator_binder<decay_t<T>, Allocator>(s, static_cast<T&&>(t)); } #if !defined(GENERATING_DOCUMENTATION) namespace detail { template <typename TargetAsyncResult, typename Allocator, typename = void> class allocator_binder_completion_handler_async_result { public: template <typename T> explicit allocator_binder_completion_handler_async_result(T&) { } }; template <typename TargetAsyncResult, typename Allocator> class allocator_binder_completion_handler_async_result< TargetAsyncResult, Allocator, void_t<typename TargetAsyncResult::completion_handler_type>> { private: TargetAsyncResult target_; public: typedef allocator_binder< typename TargetAsyncResult::completion_handler_type, Allocator> completion_handler_type; explicit allocator_binder_completion_handler_async_result( typename TargetAsyncResult::completion_handler_type& handler) : target_(handler) { } auto get() -> decltype(target_.get()) { return target_.get(); } }; template <typename TargetAsyncResult, typename = void> struct allocator_binder_async_result_return_type { }; template <typename TargetAsyncResult> struct allocator_binder_async_result_return_type< TargetAsyncResult, void_type<typename TargetAsyncResult::return_type>> { typedef typename TargetAsyncResult::return_type return_type; }; } // namespace detail template <typename T, typename Allocator, typename Signature> class async_result<allocator_binder<T, Allocator>, Signature> : public detail::allocator_binder_completion_handler_async_result< async_result<T, Signature>, Allocator>, public detail::allocator_binder_async_result_return_type< async_result<T, Signature>> { public: explicit async_result(allocator_binder<T, Allocator>& b) : detail::allocator_binder_completion_handler_async_result< async_result<T, Signature>, Allocator>(b.get()) { } template <typename Initiation> struct init_wrapper : detail::initiation_base<Initiation> { using detail::initiation_base<Initiation>::initiation_base; template <typename Handler, typename... Args> void operator()(Handler&& handler, const Allocator& a, Args&&... args) && { static_cast<Initiation&&>(*this)( allocator_binder<decay_t<Handler>, Allocator>( a, static_cast<Handler&&>(handler)), static_cast<Args&&>(args)...); } template <typename Handler, typename... Args> void operator()(Handler&& handler, const Allocator& a, Args&&... args) const & { static_cast<const Initiation&>(*this)( allocator_binder<decay_t<Handler>, Allocator>( a, static_cast<Handler&&>(handler)), static_cast<Args&&>(args)...); } }; template <typename Initiation, typename RawCompletionToken, typename... Args> static auto initiate(Initiation&& initiation, RawCompletionToken&& token, Args&&... args) -> decltype( async_initiate< conditional_t< is_const<remove_reference_t<RawCompletionToken>>::value, const T, T>, Signature>( declval<init_wrapper<decay_t<Initiation>>>(), token.get(), token.get_allocator(), static_cast<Args&&>(args)...)) { return async_initiate< conditional_t< is_const<remove_reference_t<RawCompletionToken>>::value, const T, T>, Signature>( init_wrapper<decay_t<Initiation>>( static_cast<Initiation&&>(initiation)), token.get(), token.get_allocator(), static_cast<Args&&>(args)...); } private: async_result(const async_result&) = delete; async_result& operator=(const async_result&) = delete; async_result<T, Signature> target_; }; template <typename Allocator, typename... Signatures> struct async_result<partial_allocator_binder<Allocator>, Signatures...> { template <typename Initiation, typename RawCompletionToken, typename... Args> static auto initiate(Initiation&& initiation, RawCompletionToken&& token, Args&&... args) -> decltype( async_initiate<Signatures...>( static_cast<Initiation&&>(initiation), allocator_binder< default_completion_token_t<associated_executor_t<Initiation>>, Allocator>(token.allocator_, default_completion_token_t<associated_executor_t<Initiation>>{}), static_cast<Args&&>(args)...)) { return async_initiate<Signatures...>( static_cast<Initiation&&>(initiation), allocator_binder< default_completion_token_t<associated_executor_t<Initiation>>, Allocator>(token.allocator_, default_completion_token_t<associated_executor_t<Initiation>>{}), static_cast<Args&&>(args)...); } }; template <template <typename, typename> class Associator, typename T, typename Allocator, typename DefaultCandidate> struct associator<Associator, allocator_binder<T, Allocator>, DefaultCandidate> : Associator<T, DefaultCandidate> { static typename Associator<T, DefaultCandidate>::type get( const allocator_binder<T, Allocator>& b) noexcept { return Associator<T, DefaultCandidate>::get(b.get()); } static auto get(const allocator_binder<T, Allocator>& b, const DefaultCandidate& c) noexcept -> decltype(Associator<T, DefaultCandidate>::get(b.get(), c)) { return Associator<T, DefaultCandidate>::get(b.get(), c); } }; template <typename T, typename Allocator, typename Allocator1> struct associated_allocator<allocator_binder<T, Allocator>, Allocator1> { typedef Allocator type; static auto get(const allocator_binder<T, Allocator>& b, const Allocator1& = Allocator1()) noexcept -> decltype(b.get_allocator()) { return b.get_allocator(); } }; #endif // !defined(GENERATING_DOCUMENTATION) } // namespace asio #include "asio/detail/pop_options.hpp" #endif // ASIO_BIND_ALLOCATOR_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/composed.hpp
// // composed.hpp // ~~~~~~~~~~~~ // // 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) // #ifndef ASIO_COMPOSED_HPP #define ASIO_COMPOSED_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include "asio/associated_executor.hpp" #include "asio/async_result.hpp" #include "asio/detail/base_from_cancellation_state.hpp" #include "asio/detail/composed_work.hpp" #include "asio/detail/handler_cont_helpers.hpp" #include "asio/detail/type_traits.hpp" #include "asio/detail/push_options.hpp" namespace asio { namespace detail { template <typename Impl, typename Work, typename Handler, typename... Signatures> class composed_op; template <typename Impl, typename Work, typename Handler> class composed_op<Impl, Work, Handler> : public base_from_cancellation_state<Handler> { public: template <typename I, typename W, typename H> composed_op(I&& impl, W&& work, H&& handler) : base_from_cancellation_state<Handler>( handler, enable_terminal_cancellation()), impl_(static_cast<I&&>(impl)), work_(static_cast<W&&>(work)), handler_(static_cast<H&&>(handler)), invocations_(0) { } composed_op(composed_op&& other) : base_from_cancellation_state<Handler>( static_cast<base_from_cancellation_state<Handler>&&>(other)), impl_(static_cast<Impl&&>(other.impl_)), work_(static_cast<Work&&>(other.work_)), handler_(static_cast<Handler&&>(other.handler_)), invocations_(other.invocations_) { } typedef typename composed_work_guard< typename Work::head_type>::executor_type io_executor_type; io_executor_type get_io_executor() const noexcept { return work_.head_.get_executor(); } typedef associated_executor_t<Handler, io_executor_type> executor_type; executor_type get_executor() const noexcept { return (get_associated_executor)(handler_, work_.head_.get_executor()); } typedef associated_allocator_t<Handler, std::allocator<void>> allocator_type; allocator_type get_allocator() const noexcept { return (get_associated_allocator)(handler_, std::allocator<void>()); } template <typename... T> void operator()(T&&... t) { if (invocations_ < ~0u) ++invocations_; this->get_cancellation_state().slot().clear(); impl_(*this, static_cast<T&&>(t)...); } template <typename... Args> auto complete(Args&&... args) -> decltype(declval<Handler>()(static_cast<Args&&>(args)...)) { return static_cast<Handler&&>(this->handler_)(static_cast<Args&&>(args)...); } void reset_cancellation_state() { base_from_cancellation_state<Handler>::reset_cancellation_state(handler_); } template <typename Filter> void reset_cancellation_state(Filter&& filter) { base_from_cancellation_state<Handler>::reset_cancellation_state(handler_, static_cast<Filter&&>(filter)); } template <typename InFilter, typename OutFilter> void reset_cancellation_state(InFilter&& in_filter, OutFilter&& out_filter) { base_from_cancellation_state<Handler>::reset_cancellation_state(handler_, static_cast<InFilter&&>(in_filter), static_cast<OutFilter&&>(out_filter)); } cancellation_type_t cancelled() const noexcept { return base_from_cancellation_state<Handler>::cancelled(); } //private: Impl impl_; Work work_; Handler handler_; unsigned invocations_; }; template <typename Impl, typename Work, typename Handler, typename R, typename... Args> class composed_op<Impl, Work, Handler, R(Args...)> : public composed_op<Impl, Work, Handler> { public: using composed_op<Impl, Work, Handler>::composed_op; template <typename... T> void operator()(T&&... t) { if (this->invocations_ < ~0u) ++this->invocations_; this->get_cancellation_state().slot().clear(); this->impl_(*this, static_cast<T&&>(t)...); } void complete(Args... args) { this->work_.reset(); static_cast<Handler&&>(this->handler_)(static_cast<Args&&>(args)...); } }; template <typename Impl, typename Work, typename Handler, typename R, typename... Args, typename... Signatures> class composed_op<Impl, Work, Handler, R(Args...), Signatures...> : public composed_op<Impl, Work, Handler, Signatures...> { public: using composed_op<Impl, Work, Handler, Signatures...>::composed_op; template <typename... T> void operator()(T&&... t) { if (this->invocations_ < ~0u) ++this->invocations_; this->get_cancellation_state().slot().clear(); this->impl_(*this, static_cast<T&&>(t)...); } using composed_op<Impl, Work, Handler, Signatures...>::complete; void complete(Args... args) { this->work_.reset(); static_cast<Handler&&>(this->handler_)(static_cast<Args&&>(args)...); } }; template <typename Impl, typename Work, typename Handler, typename Signature> inline bool asio_handler_is_continuation( composed_op<Impl, Work, Handler, Signature>* this_handler) { return this_handler->invocations_ > 1 ? true : asio_handler_cont_helpers::is_continuation( this_handler->handler_); } template <typename Implementation, typename Executors, typename... Signatures> class initiate_composed { public: typedef typename composed_io_executors<Executors>::head_type executor_type; template <typename I> initiate_composed(I&& impl, composed_io_executors<Executors>&& executors) : implementation_(std::forward<I>(impl)), executors_(std::move(executors)) { } executor_type get_executor() const noexcept { return executors_.head_; } template <typename Handler, typename... Args> void operator()(Handler&& handler, Args&&... args) const & { composed_op<decay_t<Implementation>, composed_work<Executors>, decay_t<Handler>, Signatures...>(implementation_, composed_work<Executors>(executors_), static_cast<Handler&&>(handler))(static_cast<Args&&>(args)...); } template <typename Handler, typename... Args> void operator()(Handler&& handler, Args&&... args) && { composed_op<decay_t<Implementation>, composed_work<Executors>, decay_t<Handler>, Signatures...>( static_cast<Implementation&&>(implementation_), composed_work<Executors>(executors_), static_cast<Handler&&>(handler))(static_cast<Args&&>(args)...); } private: Implementation implementation_; composed_io_executors<Executors> executors_; }; template <typename Implementation, typename... Signatures> class initiate_composed<Implementation, void(), Signatures...> { public: template <typename I> initiate_composed(I&& impl, composed_io_executors<void()>&&) : implementation_(std::forward<I>(impl)) { } template <typename Handler, typename... Args> void operator()(Handler&& handler, Args&&... args) const & { composed_op<decay_t<Implementation>, composed_work<void()>, decay_t<Handler>, Signatures...>(implementation_, composed_work<void()>(composed_io_executors<void()>()), static_cast<Handler&&>(handler))(static_cast<Args&&>(args)...); } template <typename Handler, typename... Args> void operator()(Handler&& handler, Args&&... args) && { composed_op<decay_t<Implementation>, composed_work<void()>, decay_t<Handler>, Signatures...>( static_cast<Implementation&&>(implementation_), composed_work<void()>(composed_io_executors<void()>()), static_cast<Handler&&>(handler))(static_cast<Args&&>(args)...); } private: Implementation implementation_; }; template <typename... Signatures, typename Implementation, typename Executors> inline initiate_composed<Implementation, Executors, Signatures...> make_initiate_composed(Implementation&& implementation, composed_io_executors<Executors>&& executors) { return initiate_composed<decay_t<Implementation>, Executors, Signatures...>( static_cast<Implementation&&>(implementation), static_cast<composed_io_executors<Executors>&&>(executors)); } } // namespace detail #if !defined(GENERATING_DOCUMENTATION) template <template <typename, typename> class Associator, typename Impl, typename Work, typename Handler, typename Signature, typename DefaultCandidate> struct associator<Associator, detail::composed_op<Impl, Work, Handler, Signature>, DefaultCandidate> : Associator<Handler, DefaultCandidate> { static typename Associator<Handler, DefaultCandidate>::type get( const detail::composed_op<Impl, Work, Handler, Signature>& h) noexcept { return Associator<Handler, DefaultCandidate>::get(h.handler_); } static auto get(const detail::composed_op<Impl, Work, Handler, Signature>& h, const DefaultCandidate& c) noexcept -> decltype(Associator<Handler, DefaultCandidate>::get(h.handler_, c)) { return Associator<Handler, DefaultCandidate>::get(h.handler_, c); } }; #endif // !defined(GENERATING_DOCUMENTATION) /// Creates an initiation function object that may be used to launch an /// asynchronous operation with a stateful implementation. /** * The @c composed function simplifies the implementation of composed * asynchronous operations automatically by wrapping a stateful function object * for use as an initiation function object. * * @param implementation A function object that contains the implementation of * the composed asynchronous operation. The first argument to the function * object is a non-const reference to the enclosing intermediate completion * handler. The remaining arguments are any arguments that originate from the * completion handlers of any asynchronous operations performed by the * implementation. * * @param io_objects_or_executors Zero or more I/O objects or I/O executors for * which outstanding work must be maintained. * * @par Per-Operation Cancellation * By default, terminal per-operation cancellation is enabled for composed * operations that are implemented using @c composed. To disable cancellation * for the composed operation, or to alter its supported cancellation types, * call the @c self object's @c reset_cancellation_state function. * * @par Example: * * @code struct async_echo_implementation * { * tcp::socket& socket_; * asio::mutable_buffer buffer_; * enum { starting, reading, writing } state_; * * template <typename Self> * void operator()(Self& self, * asio::error_code error, * std::size_t n) * { * switch (state_) * { * case starting: * state_ = reading; * socket_.async_read_some( * buffer_, std::move(self)); * break; * case reading: * if (error) * { * self.complete(error, 0); * } * else * { * state_ = writing; * asio::async_write(socket_, buffer_, * asio::transfer_exactly(n), * std::move(self)); * } * break; * case writing: * self.complete(error, n); * break; * } * } * }; * * template <typename CompletionToken> * auto async_echo(tcp::socket& socket, * asio::mutable_buffer buffer, * CompletionToken&& token) * -> decltype( * asio::async_initiate<CompletionToken, * void(asio::error_code, std::size_t)>( * asio::composed( * async_echo_implementation{socket, buffer, * async_echo_implementation::starting}, socket), * token)) * { * return asio::async_initiate<CompletionToken, * void(asio::error_code, std::size_t)>( * asio::composed( * async_echo_implementation{socket, buffer, * async_echo_implementation::starting}, socket), * token, asio::error_code{}, 0); * } @endcode */ template <ASIO_COMPLETION_SIGNATURE... Signatures, typename Implementation, typename... IoObjectsOrExecutors> inline auto composed(Implementation&& implementation, IoObjectsOrExecutors&&... io_objects_or_executors) -> decltype( detail::make_initiate_composed<Signatures...>( static_cast<Implementation&&>(implementation), detail::make_composed_io_executors( detail::get_composed_io_executor( static_cast<IoObjectsOrExecutors&&>( io_objects_or_executors))...))) { return detail::make_initiate_composed<Signatures...>( static_cast<Implementation&&>(implementation), detail::make_composed_io_executors( detail::get_composed_io_executor( static_cast<IoObjectsOrExecutors&&>( io_objects_or_executors))...)); } } // namespace asio #include "asio/detail/pop_options.hpp" #endif // ASIO_COMPOSE_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/this_coro.hpp
// // this_coro.hpp // ~~~~~~~~~~~~~ // // 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) // #ifndef ASIO_THIS_CORO_HPP #define ASIO_THIS_CORO_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include "asio/detail/type_traits.hpp" #include "asio/detail/push_options.hpp" namespace asio { namespace this_coro { /// Awaitable type that returns the executor of the current coroutine. struct executor_t { constexpr executor_t() { } }; /// Awaitable object that returns the executor of the current coroutine. ASIO_INLINE_VARIABLE constexpr executor_t executor; /// Awaitable type that returns the cancellation state of the current coroutine. struct cancellation_state_t { constexpr cancellation_state_t() { } }; /// Awaitable object that returns the cancellation state of the current /// coroutine. /** * @par Example * @code asio::awaitable<void> my_coroutine() * { * asio::cancellation_state cs * = co_await asio::this_coro::cancellation_state; * * // ... * * if (cs.cancelled() != asio::cancellation_type::none) * // ... * } @endcode */ ASIO_INLINE_VARIABLE constexpr cancellation_state_t cancellation_state; #if defined(GENERATING_DOCUMENTATION) /// Returns an awaitable object that may be used to reset the cancellation state /// of the current coroutine. /** * Let <tt>P</tt> be the cancellation slot associated with the current * coroutine's @ref co_spawn completion handler. Assigns a new * asio::cancellation_state object <tt>S</tt>, constructed as * <tt>S(P)</tt>, into the current coroutine's cancellation state object. * * @par Example * @code asio::awaitable<void> my_coroutine() * { * co_await asio::this_coro::reset_cancellation_state(); * * // ... * } @endcode * * @note The cancellation state is shared by all coroutines in the same "thread * of execution" that was created using asio::co_spawn. */ ASIO_NODISCARD constexpr unspecified reset_cancellation_state(); /// Returns an awaitable object that may be used to reset the cancellation state /// of the current coroutine. /** * Let <tt>P</tt> be the cancellation slot associated with the current * coroutine's @ref co_spawn completion handler. Assigns a new * asio::cancellation_state object <tt>S</tt>, constructed as <tt>S(P, * std::forward<Filter>(filter))</tt>, into the current coroutine's * cancellation state object. * * @par Example * @code asio::awaitable<void> my_coroutine() * { * co_await asio::this_coro::reset_cancellation_state( * asio::enable_partial_cancellation()); * * // ... * } @endcode * * @note The cancellation state is shared by all coroutines in the same "thread * of execution" that was created using asio::co_spawn. */ template <typename Filter> ASIO_NODISCARD constexpr unspecified reset_cancellation_state(Filter&& filter); /// Returns an awaitable object that may be used to reset the cancellation state /// of the current coroutine. /** * Let <tt>P</tt> be the cancellation slot associated with the current * coroutine's @ref co_spawn completion handler. Assigns a new * asio::cancellation_state object <tt>S</tt>, constructed as <tt>S(P, * std::forward<InFilter>(in_filter), * std::forward<OutFilter>(out_filter))</tt>, into the current coroutine's * cancellation state object. * * @par Example * @code asio::awaitable<void> my_coroutine() * { * co_await asio::this_coro::reset_cancellation_state( * asio::enable_partial_cancellation(), * asio::disable_cancellation()); * * // ... * } @endcode * * @note The cancellation state is shared by all coroutines in the same "thread * of execution" that was created using asio::co_spawn. */ template <typename InFilter, typename OutFilter> ASIO_NODISCARD constexpr unspecified reset_cancellation_state( InFilter&& in_filter, OutFilter&& out_filter); /// Returns an awaitable object that may be used to determine whether the /// coroutine throws if trying to suspend when it has been cancelled. /** * @par Example * @code asio::awaitable<void> my_coroutine() * { * if (co_await asio::this_coro::throw_if_cancelled) * // ... * * // ... * } @endcode */ ASIO_NODISCARD constexpr unspecified throw_if_cancelled(); /// Returns an awaitable object that may be used to specify whether the /// coroutine throws if trying to suspend when it has been cancelled. /** * @par Example * @code asio::awaitable<void> my_coroutine() * { * co_await asio::this_coro::throw_if_cancelled(false); * * // ... * } @endcode */ ASIO_NODISCARD constexpr unspecified throw_if_cancelled(bool value); #else // defined(GENERATING_DOCUMENTATION) struct reset_cancellation_state_0_t { constexpr reset_cancellation_state_0_t() { } }; ASIO_NODISCARD inline constexpr reset_cancellation_state_0_t reset_cancellation_state() { return reset_cancellation_state_0_t(); } template <typename Filter> struct reset_cancellation_state_1_t { template <typename F> explicit constexpr reset_cancellation_state_1_t( F&& filt) : filter(static_cast<F&&>(filt)) { } Filter filter; }; template <typename Filter> ASIO_NODISCARD inline constexpr reset_cancellation_state_1_t< decay_t<Filter>> reset_cancellation_state(Filter&& filter) { return reset_cancellation_state_1_t<decay_t<Filter>>( static_cast<Filter&&>(filter)); } template <typename InFilter, typename OutFilter> struct reset_cancellation_state_2_t { template <typename F1, typename F2> constexpr reset_cancellation_state_2_t( F1&& in_filt, F2&& out_filt) : in_filter(static_cast<F1&&>(in_filt)), out_filter(static_cast<F2&&>(out_filt)) { } InFilter in_filter; OutFilter out_filter; }; template <typename InFilter, typename OutFilter> ASIO_NODISCARD inline constexpr reset_cancellation_state_2_t<decay_t<InFilter>, decay_t<OutFilter>> reset_cancellation_state(InFilter&& in_filter, OutFilter&& out_filter) { return reset_cancellation_state_2_t<decay_t<InFilter>, decay_t<OutFilter>>( static_cast<InFilter&&>(in_filter), static_cast<OutFilter&&>(out_filter)); } struct throw_if_cancelled_0_t { constexpr throw_if_cancelled_0_t() { } }; ASIO_NODISCARD inline constexpr throw_if_cancelled_0_t throw_if_cancelled() { return throw_if_cancelled_0_t(); } struct throw_if_cancelled_1_t { explicit constexpr throw_if_cancelled_1_t(bool val) : value(val) { } bool value; }; ASIO_NODISCARD inline constexpr throw_if_cancelled_1_t throw_if_cancelled(bool value) { return throw_if_cancelled_1_t(value); } #endif // defined(GENERATING_DOCUMENTATION) } // namespace this_coro } // namespace asio #include "asio/detail/pop_options.hpp" #endif // ASIO_THIS_CORO_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/steady_timer.hpp
// // steady_timer.hpp // ~~~~~~~~~~~~~~~~ // // 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) // #ifndef ASIO_STEADY_TIMER_HPP #define ASIO_STEADY_TIMER_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include "asio/basic_waitable_timer.hpp" #include "asio/detail/chrono.hpp" namespace asio { /// Typedef for a timer based on the steady clock. /** * This typedef uses the C++11 @c &lt;chrono&gt; standard library facility, if * available. Otherwise, it may use the Boost.Chrono library. To explicitly * utilise Boost.Chrono, use the basic_waitable_timer template directly: * @code * typedef basic_waitable_timer<boost::chrono::steady_clock> timer; * @endcode */ typedef basic_waitable_timer<chrono::steady_clock> steady_timer; } // namespace asio #endif // ASIO_STEADY_TIMER_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/basic_random_access_file.hpp
// // basic_random_access_file.hpp // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // // 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) // #ifndef ASIO_BASIC_RANDOM_ACCESS_FILE_HPP #define ASIO_BASIC_RANDOM_ACCESS_FILE_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #if defined(ASIO_HAS_FILE) \ || defined(GENERATING_DOCUMENTATION) #include <cstddef> #include "asio/async_result.hpp" #include "asio/basic_file.hpp" #include "asio/detail/handler_type_requirements.hpp" #include "asio/detail/non_const_lvalue.hpp" #include "asio/detail/throw_error.hpp" #include "asio/error.hpp" #include "asio/detail/push_options.hpp" namespace asio { #if !defined(ASIO_BASIC_RANDOM_ACCESS_FILE_FWD_DECL) #define ASIO_BASIC_RANDOM_ACCESS_FILE_FWD_DECL // Forward declaration with defaulted arguments. template <typename Executor = any_io_executor> class basic_random_access_file; #endif // !defined(ASIO_BASIC_RANDOM_ACCESS_FILE_FWD_DECL) /// Provides random-access file functionality. /** * The basic_random_access_file class template provides asynchronous and * blocking random-access file functionality. * * @par Thread Safety * @e Distinct @e objects: Safe.@n * @e Shared @e objects: Unsafe. * * Synchronous @c read_some_at and @c write_some_at operations are thread safe * with respect to each other, if the underlying operating system calls are * also thread safe. This means that it is permitted to perform concurrent * calls to these synchronous operations on a single file object. Other * synchronous operations, such as @c open or @c close, are not thread safe. */ template <typename Executor> class basic_random_access_file : public basic_file<Executor> { private: class initiate_async_write_some_at; class initiate_async_read_some_at; public: /// The type of the executor associated with the object. typedef Executor executor_type; /// Rebinds the file type to another executor. template <typename Executor1> struct rebind_executor { /// The file type when rebound to the specified executor. typedef basic_random_access_file<Executor1> other; }; /// The native representation of a file. #if defined(GENERATING_DOCUMENTATION) typedef implementation_defined native_handle_type; #else typedef typename basic_file<Executor>::native_handle_type native_handle_type; #endif /// Construct a basic_random_access_file without opening it. /** * This constructor initialises a file without opening it. The file needs to * be opened before data can be read from or or written to it. * * @param ex The I/O executor that the file will use, by default, to * dispatch handlers for any asynchronous operations performed on the file. */ explicit basic_random_access_file(const executor_type& ex) : basic_file<Executor>(ex) { } /// Construct a basic_random_access_file without opening it. /** * This constructor initialises a file without opening it. The file needs to * be opened before data can be read from or or written to it. * * @param context An execution context which provides the I/O executor that * the file will use, by default, to dispatch handlers for any asynchronous * operations performed on the file. */ template <typename ExecutionContext> explicit basic_random_access_file(ExecutionContext& context, constraint_t< is_convertible<ExecutionContext&, execution_context&>::value, defaulted_constraint > = defaulted_constraint()) : basic_file<Executor>(context) { } /// Construct and open a basic_random_access_file. /** * This constructor initialises and opens a file. * * @param ex The I/O executor that the file will use, by default, to * dispatch handlers for any asynchronous operations performed on the file. * * @param path The path name identifying the file to be opened. * * @param open_flags A set of flags that determine how the file should be * opened. * * @throws asio::system_error Thrown on failure. */ basic_random_access_file(const executor_type& ex, const char* path, file_base::flags open_flags) : basic_file<Executor>(ex, path, open_flags) { } /// Construct and open a basic_random_access_file. /** * This constructor initialises and opens a file. * * @param context An execution context which provides the I/O executor that * the file will use, by default, to dispatch handlers for any asynchronous * operations performed on the file. * * @param path The path name identifying the file to be opened. * * @param open_flags A set of flags that determine how the file should be * opened. * * @throws asio::system_error Thrown on failure. */ template <typename ExecutionContext> basic_random_access_file(ExecutionContext& context, const char* path, file_base::flags open_flags, constraint_t< is_convertible<ExecutionContext&, execution_context&>::value, defaulted_constraint > = defaulted_constraint()) : basic_file<Executor>(context, path, open_flags) { } /// Construct and open a basic_random_access_file. /** * This constructor initialises and opens a file. * * @param ex The I/O executor that the file will use, by default, to * dispatch handlers for any asynchronous operations performed on the file. * * @param path The path name identifying the file to be opened. * * @param open_flags A set of flags that determine how the file should be * opened. * * @throws asio::system_error Thrown on failure. */ basic_random_access_file(const executor_type& ex, const std::string& path, file_base::flags open_flags) : basic_file<Executor>(ex, path, open_flags) { } /// Construct and open a basic_random_access_file. /** * This constructor initialises and opens a file. * * @param context An execution context which provides the I/O executor that * the file will use, by default, to dispatch handlers for any asynchronous * operations performed on the file. * * @param path The path name identifying the file to be opened. * * @param open_flags A set of flags that determine how the file should be * opened. * * @throws asio::system_error Thrown on failure. */ template <typename ExecutionContext> basic_random_access_file(ExecutionContext& context, const std::string& path, file_base::flags open_flags, constraint_t< is_convertible<ExecutionContext&, execution_context&>::value, defaulted_constraint > = defaulted_constraint()) : basic_file<Executor>(context, path, open_flags) { } /// Construct a basic_random_access_file on an existing native file. /** * This constructor initialises a random-access file object to hold an * existing native file. * * @param ex The I/O executor that the file will use, by default, to * dispatch handlers for any asynchronous operations performed on the file. * * @param native_file The new underlying file implementation. * * @throws asio::system_error Thrown on failure. */ basic_random_access_file(const executor_type& ex, const native_handle_type& native_file) : basic_file<Executor>(ex, native_file) { } /// Construct a basic_random_access_file on an existing native file. /** * This constructor initialises a random-access file object to hold an * existing native file. * * @param context An execution context which provides the I/O executor that * the file will use, by default, to dispatch handlers for any asynchronous * operations performed on the file. * * @param native_file The new underlying file implementation. * * @throws asio::system_error Thrown on failure. */ template <typename ExecutionContext> basic_random_access_file(ExecutionContext& context, const native_handle_type& native_file, constraint_t< is_convertible<ExecutionContext&, execution_context&>::value, defaulted_constraint > = defaulted_constraint()) : basic_file<Executor>(context, native_file) { } /// Move-construct a basic_random_access_file from another. /** * This constructor moves a random-access file from one object to another. * * @param other The other basic_random_access_file object from which the move * will occur. * * @note Following the move, the moved-from object is in the same state as if * constructed using the @c basic_random_access_file(const executor_type&) * constructor. */ basic_random_access_file(basic_random_access_file&& other) noexcept : basic_file<Executor>(std::move(other)) { } /// Move-assign a basic_random_access_file from another. /** * This assignment operator moves a random-access file from one object to * another. * * @param other The other basic_random_access_file object from which the move * will occur. * * @note Following the move, the moved-from object is in the same state as if * constructed using the @c basic_random_access_file(const executor_type&) * constructor. */ basic_random_access_file& operator=(basic_random_access_file&& other) { basic_file<Executor>::operator=(std::move(other)); return *this; } /// Move-construct a basic_random_access_file from a file of another executor /// type. /** * This constructor moves a random-access file from one object to another. * * @param other The other basic_random_access_file object from which the move * will occur. * * @note Following the move, the moved-from object is in the same state as if * constructed using the @c basic_random_access_file(const executor_type&) * constructor. */ template <typename Executor1> basic_random_access_file(basic_random_access_file<Executor1>&& other, constraint_t< is_convertible<Executor1, Executor>::value, defaulted_constraint > = defaulted_constraint()) : basic_file<Executor>(std::move(other)) { } /// Move-assign a basic_random_access_file from a file of another executor /// type. /** * This assignment operator moves a random-access file from one object to * another. * * @param other The other basic_random_access_file object from which the move * will occur. * * @note Following the move, the moved-from object is in the same state as if * constructed using the @c basic_random_access_file(const executor_type&) * constructor. */ template <typename Executor1> constraint_t< is_convertible<Executor1, Executor>::value, basic_random_access_file& > operator=(basic_random_access_file<Executor1>&& other) { basic_file<Executor>::operator=(std::move(other)); return *this; } /// Destroys the file. /** * This function destroys the file, cancelling any outstanding asynchronous * operations associated with the file as if by calling @c cancel. */ ~basic_random_access_file() { } /// Write some data to the handle at the specified offset. /** * This function is used to write data to the random-access handle. The * function call will block until one or more bytes of the data has been * written successfully, or until an error occurs. * * @param offset The offset at which the data will be written. * * @param buffers One or more data buffers to be written to the handle. * * @returns The number of bytes written. * * @throws asio::system_error Thrown on failure. An error code of * asio::error::eof indicates that the end of the file was reached. * * @note The write_some_at operation may not write all of the data. Consider * using the @ref write_at function if you need to ensure that all data is * written before the blocking operation completes. * * @par Example * To write a single data buffer use the @ref buffer function as follows: * @code * handle.write_some_at(42, asio::buffer(data, size)); * @endcode * See the @ref buffer documentation for information on writing multiple * buffers in one go, and how to use it with arrays, boost::array or * std::vector. */ template <typename ConstBufferSequence> std::size_t write_some_at(uint64_t offset, const ConstBufferSequence& buffers) { asio::error_code ec; std::size_t s = this->impl_.get_service().write_some_at( this->impl_.get_implementation(), offset, buffers, ec); asio::detail::throw_error(ec, "write_some_at"); return s; } /// Write some data to the handle at the specified offset. /** * This function is used to write data to the random-access handle. The * function call will block until one or more bytes of the data has been * written successfully, or until an error occurs. * * @param offset The offset at which the data will be written. * * @param buffers One or more data buffers to be written to the handle. * * @param ec Set to indicate what error occurred, if any. * * @returns The number of bytes written. Returns 0 if an error occurred. * * @note The write_some operation may not write all of the data to the * file. Consider using the @ref write_at function if you need to ensure that * all data is written before the blocking operation completes. */ template <typename ConstBufferSequence> std::size_t write_some_at(uint64_t offset, const ConstBufferSequence& buffers, asio::error_code& ec) { return this->impl_.get_service().write_some_at( this->impl_.get_implementation(), offset, buffers, ec); } /// Start an asynchronous write at the specified offset. /** * This function is used to asynchronously write data to the random-access * handle. It is an initiating function for an @ref asynchronous_operation, * and always returns immediately. * * @param offset The offset at which the data will be written. * * @param buffers One or more data buffers to be written to the handle. * Although the buffers object may be copied as necessary, ownership of the * underlying memory blocks is retained by the caller, which must guarantee * that they remain valid until the completion handler is called. * * @param token The @ref completion_token that will be used to produce a * completion handler, which will be called when the write completes. * Potential completion tokens include @ref use_future, @ref use_awaitable, * @ref yield_context, or a function object with the correct completion * signature. The function signature of the completion handler must be: * @code void handler( * const asio::error_code& error, // Result of operation. * std::size_t bytes_transferred // Number of bytes written. * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the completion handler will not be invoked from within this function. * On immediate completion, invocation of the handler will be performed in a * manner equivalent to using asio::async_immediate(). * * @par Completion Signature * @code void(asio::error_code, std::size_t) @endcode * * @note The write operation may not write all of the data to the file. * Consider using the @ref async_write_at function if you need to ensure that * all data is written before the asynchronous operation completes. * * @par Example * To write a single data buffer use the @ref buffer function as follows: * @code * handle.async_write_some_at(42, asio::buffer(data, size), handler); * @endcode * See the @ref buffer documentation for information on writing multiple * buffers in one go, and how to use it with arrays, boost::array or * std::vector. * * @par Per-Operation Cancellation * This asynchronous operation supports cancellation for the following * asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * @li @c cancellation_type::total */ template <typename ConstBufferSequence, ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code, std::size_t)) WriteToken = default_completion_token_t<executor_type>> auto async_write_some_at(uint64_t offset, const ConstBufferSequence& buffers, WriteToken&& token = default_completion_token_t<executor_type>()) -> decltype( async_initiate<WriteToken, void (asio::error_code, std::size_t)>( declval<initiate_async_write_some_at>(), token, offset, buffers)) { return async_initiate<WriteToken, void (asio::error_code, std::size_t)>( initiate_async_write_some_at(this), token, offset, buffers); } /// Read some data from the handle at the specified offset. /** * This function is used to read data from the random-access handle. The * function call will block until one or more bytes of data has been read * successfully, or until an error occurs. * * @param offset The offset at which the data will be read. * * @param buffers One or more buffers into which the data will be read. * * @returns The number of bytes read. * * @throws asio::system_error Thrown on failure. An error code of * asio::error::eof indicates that the end of the file was reached. * * @note The read_some operation may not read all of the requested number of * bytes. Consider using the @ref read_at function if you need to ensure that * the requested amount of data is read before the blocking operation * completes. * * @par Example * To read into a single data buffer use the @ref buffer function as follows: * @code * handle.read_some_at(42, asio::buffer(data, size)); * @endcode * See the @ref buffer documentation for information on reading into multiple * buffers in one go, and how to use it with arrays, boost::array or * std::vector. */ template <typename MutableBufferSequence> std::size_t read_some_at(uint64_t offset, const MutableBufferSequence& buffers) { asio::error_code ec; std::size_t s = this->impl_.get_service().read_some_at( this->impl_.get_implementation(), offset, buffers, ec); asio::detail::throw_error(ec, "read_some_at"); return s; } /// Read some data from the handle at the specified offset. /** * This function is used to read data from the random-access handle. The * function call will block until one or more bytes of data has been read * successfully, or until an error occurs. * * @param offset The offset at which the data will be read. * * @param buffers One or more buffers into which the data will be read. * * @param ec Set to indicate what error occurred, if any. * * @returns The number of bytes read. Returns 0 if an error occurred. * * @note The read_some operation may not read all of the requested number of * bytes. Consider using the @ref read_at function if you need to ensure that * the requested amount of data is read before the blocking operation * completes. */ template <typename MutableBufferSequence> std::size_t read_some_at(uint64_t offset, const MutableBufferSequence& buffers, asio::error_code& ec) { return this->impl_.get_service().read_some_at( this->impl_.get_implementation(), offset, buffers, ec); } /// Start an asynchronous read at the specified offset. /** * This function is used to asynchronously read data from the random-access * handle. It is an initiating function for an @ref asynchronous_operation, * and always returns immediately. * * @param offset The offset at which the data will be read. * * @param buffers One or more buffers into which the data will be read. * Although the buffers object may be copied as necessary, ownership of the * underlying memory blocks is retained by the caller, which must guarantee * that they remain valid until the completion handler is called. * * @param token The @ref completion_token that will be used to produce a * completion handler, which will be called when the read completes. * Potential completion tokens include @ref use_future, @ref use_awaitable, * @ref yield_context, or a function object with the correct completion * signature. The function signature of the completion handler must be: * @code void handler( * const asio::error_code& error, // Result of operation. * std::size_t bytes_transferred // Number of bytes read. * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the completion handler will not be invoked from within this function. * On immediate completion, invocation of the handler will be performed in a * manner equivalent to using asio::async_immediate(). * * @par Completion Signature * @code void(asio::error_code, std::size_t) @endcode * * @note The read operation may not read all of the requested number of bytes. * Consider using the @ref async_read_at function if you need to ensure that * the requested amount of data is read before the asynchronous operation * completes. * * @par Example * To read into a single data buffer use the @ref buffer function as follows: * @code * handle.async_read_some_at(42, asio::buffer(data, size), handler); * @endcode * See the @ref buffer documentation for information on reading into multiple * buffers in one go, and how to use it with arrays, boost::array or * std::vector. * * @par Per-Operation Cancellation * This asynchronous operation supports cancellation for the following * asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * @li @c cancellation_type::total */ template <typename MutableBufferSequence, ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code, std::size_t)) ReadToken = default_completion_token_t<executor_type>> auto async_read_some_at(uint64_t offset, const MutableBufferSequence& buffers, ReadToken&& token = default_completion_token_t<executor_type>()) -> decltype( async_initiate<ReadToken, void (asio::error_code, std::size_t)>( declval<initiate_async_read_some_at>(), token, offset, buffers)) { return async_initiate<ReadToken, void (asio::error_code, std::size_t)>( initiate_async_read_some_at(this), token, offset, buffers); } private: // Disallow copying and assignment. basic_random_access_file(const basic_random_access_file&) = delete; basic_random_access_file& operator=( const basic_random_access_file&) = delete; class initiate_async_write_some_at { public: typedef Executor executor_type; explicit initiate_async_write_some_at(basic_random_access_file* self) : self_(self) { } const executor_type& get_executor() const noexcept { return self_->get_executor(); } template <typename WriteHandler, typename ConstBufferSequence> void operator()(WriteHandler&& handler, uint64_t offset, const ConstBufferSequence& buffers) const { // If you get an error on the following line it means that your handler // does not meet the documented type requirements for a WriteHandler. ASIO_WRITE_HANDLER_CHECK(WriteHandler, handler) type_check; detail::non_const_lvalue<WriteHandler> handler2(handler); self_->impl_.get_service().async_write_some_at( self_->impl_.get_implementation(), offset, buffers, handler2.value, self_->impl_.get_executor()); } private: basic_random_access_file* self_; }; class initiate_async_read_some_at { public: typedef Executor executor_type; explicit initiate_async_read_some_at(basic_random_access_file* self) : self_(self) { } const executor_type& get_executor() const noexcept { return self_->get_executor(); } template <typename ReadHandler, typename MutableBufferSequence> void operator()(ReadHandler&& handler, uint64_t offset, const MutableBufferSequence& buffers) const { // If you get an error on the following line it means that your handler // does not meet the documented type requirements for a ReadHandler. ASIO_READ_HANDLER_CHECK(ReadHandler, handler) type_check; detail::non_const_lvalue<ReadHandler> handler2(handler); self_->impl_.get_service().async_read_some_at( self_->impl_.get_implementation(), offset, buffers, handler2.value, self_->impl_.get_executor()); } private: basic_random_access_file* self_; }; }; } // namespace asio #include "asio/detail/pop_options.hpp" #endif // defined(ASIO_HAS_FILE) // || defined(GENERATING_DOCUMENTATION) #endif // ASIO_BASIC_RANDOM_ACCESS_FILE_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/deadline_timer.hpp
// // deadline_timer.hpp // ~~~~~~~~~~~~~~~~~~ // // 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) // #ifndef ASIO_DEADLINE_TIMER_HPP #define ASIO_DEADLINE_TIMER_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #if defined(ASIO_HAS_BOOST_DATE_TIME) \ || defined(GENERATING_DOCUMENTATION) #include "asio/detail/socket_types.hpp" // Must come before posix_time. #include "asio/basic_deadline_timer.hpp" #include <boost/date_time/posix_time/posix_time_types.hpp> namespace asio { /// Typedef for the typical usage of timer. Uses a UTC clock. typedef basic_deadline_timer<boost::posix_time::ptime> deadline_timer; } // namespace asio #endif // defined(ASIO_HAS_BOOST_DATE_TIME) // || defined(GENERATING_DOCUMENTATION) #endif // ASIO_DEADLINE_TIMER_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/basic_streambuf.hpp
// // basic_streambuf.hpp // ~~~~~~~~~~~~~~~~~~~ // // 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) // #ifndef ASIO_BASIC_STREAMBUF_HPP #define ASIO_BASIC_STREAMBUF_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #if !defined(ASIO_NO_IOSTREAM) #include <algorithm> #include <cstring> #include <stdexcept> #include <streambuf> #include <vector> #include "asio/basic_streambuf_fwd.hpp" #include "asio/buffer.hpp" #include "asio/detail/limits.hpp" #include "asio/detail/noncopyable.hpp" #include "asio/detail/throw_exception.hpp" #include "asio/detail/push_options.hpp" namespace asio { /// Automatically resizable buffer class based on std::streambuf. /** * The @c basic_streambuf class is derived from @c std::streambuf to associate * the streambuf's input and output sequences with one or more character * arrays. These character arrays are internal to the @c basic_streambuf * object, but direct access to the array elements is provided to permit them * to be used efficiently with I/O operations. Characters written to the output * sequence of a @c basic_streambuf object are appended to the input sequence * of the same object. * * The @c basic_streambuf class's public interface is intended to permit the * following implementation strategies: * * @li A single contiguous character array, which is reallocated as necessary * to accommodate changes in the size of the character sequence. This is the * implementation approach currently used in Asio. * * @li A sequence of one or more character arrays, where each array is of the * same size. Additional character array objects are appended to the sequence * to accommodate changes in the size of the character sequence. * * @li A sequence of one or more character arrays of varying sizes. Additional * character array objects are appended to the sequence to accommodate changes * in the size of the character sequence. * * The constructor for basic_streambuf accepts a @c size_t argument specifying * the maximum of the sum of the sizes of the input sequence and output * sequence. During the lifetime of the @c basic_streambuf object, the following * invariant holds: * @code size() <= max_size()@endcode * Any member function that would, if successful, cause the invariant to be * violated shall throw an exception of class @c std::length_error. * * The constructor for @c basic_streambuf takes an Allocator argument. A copy * of this argument is used for any memory allocation performed, by the * constructor and by all member functions, during the lifetime of each @c * basic_streambuf object. * * @par Examples * Writing directly from an streambuf to a socket: * @code * asio::streambuf b; * std::ostream os(&b); * os << "Hello, World!\n"; * * // try sending some data in input sequence * size_t n = sock.send(b.data()); * * b.consume(n); // sent data is removed from input sequence * @endcode * * Reading from a socket directly into a streambuf: * @code * asio::streambuf b; * * // reserve 512 bytes in output sequence * asio::streambuf::mutable_buffers_type bufs = b.prepare(512); * * size_t n = sock.receive(bufs); * * // received data is "committed" from output sequence to input sequence * b.commit(n); * * std::istream is(&b); * std::string s; * is >> s; * @endcode */ #if defined(GENERATING_DOCUMENTATION) template <typename Allocator = std::allocator<char>> #else template <typename Allocator> #endif class basic_streambuf : public std::streambuf, private noncopyable { public: #if defined(GENERATING_DOCUMENTATION) /// The type used to represent the input sequence as a list of buffers. typedef implementation_defined const_buffers_type; /// The type used to represent the output sequence as a list of buffers. typedef implementation_defined mutable_buffers_type; #else typedef ASIO_CONST_BUFFER const_buffers_type; typedef ASIO_MUTABLE_BUFFER mutable_buffers_type; #endif /// Construct a basic_streambuf object. /** * Constructs a streambuf with the specified maximum size. The initial size * of the streambuf's input sequence is 0. */ explicit basic_streambuf( std::size_t maximum_size = (std::numeric_limits<std::size_t>::max)(), const Allocator& allocator = Allocator()) : max_size_(maximum_size), buffer_(allocator) { std::size_t pend = (std::min<std::size_t>)(max_size_, buffer_delta); buffer_.resize((std::max<std::size_t>)(pend, 1)); setg(&buffer_[0], &buffer_[0], &buffer_[0]); setp(&buffer_[0], &buffer_[0] + pend); } /// Get the size of the input sequence. /** * @returns The size of the input sequence. The value is equal to that * calculated for @c s in the following code: * @code * size_t s = 0; * const_buffers_type bufs = data(); * const_buffers_type::const_iterator i = bufs.begin(); * while (i != bufs.end()) * { * const_buffer buf(*i++); * s += buf.size(); * } * @endcode */ std::size_t size() const noexcept { return pptr() - gptr(); } /// Get the maximum size of the basic_streambuf. /** * @returns The allowed maximum of the sum of the sizes of the input sequence * and output sequence. */ std::size_t max_size() const noexcept { return max_size_; } /// Get the current capacity of the basic_streambuf. /** * @returns The current total capacity of the streambuf, i.e. for both the * input sequence and output sequence. */ std::size_t capacity() const noexcept { return buffer_.capacity(); } /// Get a list of buffers that represents the input sequence. /** * @returns An object of type @c const_buffers_type that satisfies * ConstBufferSequence requirements, representing all character arrays in the * input sequence. * * @note The returned object is invalidated by any @c basic_streambuf member * function that modifies the input sequence or output sequence. */ const_buffers_type data() const noexcept { return asio::buffer(asio::const_buffer(gptr(), (pptr() - gptr()) * sizeof(char_type))); } /// Get a list of buffers that represents the output sequence, with the given /// size. /** * Ensures that the output sequence can accommodate @c n characters, * reallocating character array objects as necessary. * * @returns An object of type @c mutable_buffers_type that satisfies * MutableBufferSequence requirements, representing character array objects * at the start of the output sequence such that the sum of the buffer sizes * is @c n. * * @throws std::length_error If <tt>size() + n > max_size()</tt>. * * @note The returned object is invalidated by any @c basic_streambuf member * function that modifies the input sequence or output sequence. */ mutable_buffers_type prepare(std::size_t n) { reserve(n); return asio::buffer(asio::mutable_buffer( pptr(), n * sizeof(char_type))); } /// Move characters from the output sequence to the input sequence. /** * Appends @c n characters from the start of the output sequence to the input * sequence. The beginning of the output sequence is advanced by @c n * characters. * * Requires a preceding call <tt>prepare(x)</tt> where <tt>x >= n</tt>, and * no intervening operations that modify the input or output sequence. * * @note If @c n is greater than the size of the output sequence, the entire * output sequence is moved to the input sequence and no error is issued. */ void commit(std::size_t n) { n = std::min<std::size_t>(n, epptr() - pptr()); pbump(static_cast<int>(n)); setg(eback(), gptr(), pptr()); } /// Remove characters from the input sequence. /** * Removes @c n characters from the beginning of the input sequence. * * @note If @c n is greater than the size of the input sequence, the entire * input sequence is consumed and no error is issued. */ void consume(std::size_t n) { if (egptr() < pptr()) setg(&buffer_[0], gptr(), pptr()); if (gptr() + n > pptr()) n = pptr() - gptr(); gbump(static_cast<int>(n)); } protected: enum { buffer_delta = 128 }; /// Override std::streambuf behaviour. /** * Behaves according to the specification of @c std::streambuf::underflow(). */ int_type underflow() { if (gptr() < pptr()) { setg(&buffer_[0], gptr(), pptr()); return traits_type::to_int_type(*gptr()); } else { return traits_type::eof(); } } /// Override std::streambuf behaviour. /** * Behaves according to the specification of @c std::streambuf::overflow(), * with the specialisation that @c std::length_error is thrown if appending * the character to the input sequence would require the condition * <tt>size() > max_size()</tt> to be true. */ int_type overflow(int_type c) { if (!traits_type::eq_int_type(c, traits_type::eof())) { if (pptr() == epptr()) { std::size_t buffer_size = pptr() - gptr(); if (buffer_size < max_size_ && max_size_ - buffer_size < buffer_delta) { reserve(max_size_ - buffer_size); } else { reserve(buffer_delta); } } *pptr() = traits_type::to_char_type(c); pbump(1); return c; } return traits_type::not_eof(c); } void reserve(std::size_t n) { // Get current stream positions as offsets. std::size_t gnext = gptr() - &buffer_[0]; std::size_t pnext = pptr() - &buffer_[0]; std::size_t pend = epptr() - &buffer_[0]; // Check if there is already enough space in the put area. if (n <= pend - pnext) { return; } // Shift existing contents of get area to start of buffer. if (gnext > 0) { pnext -= gnext; std::memmove(&buffer_[0], &buffer_[0] + gnext, pnext); } // Ensure buffer is large enough to hold at least the specified size. if (n > pend - pnext) { if (n <= max_size_ && pnext <= max_size_ - n) { pend = pnext + n; buffer_.resize((std::max<std::size_t>)(pend, 1)); } else { std::length_error ex("asio::streambuf too long"); asio::detail::throw_exception(ex); } } // Update stream positions. setg(&buffer_[0], &buffer_[0], &buffer_[0] + pnext); setp(&buffer_[0] + pnext, &buffer_[0] + pend); } private: std::size_t max_size_; std::vector<char_type, Allocator> buffer_; // Helper function to get the preferred size for reading data. friend std::size_t read_size_helper( basic_streambuf& sb, std::size_t max_size) { return std::min<std::size_t>( std::max<std::size_t>(512, sb.buffer_.capacity() - sb.size()), std::min<std::size_t>(max_size, sb.max_size() - sb.size())); } }; /// Adapts basic_streambuf to the dynamic buffer sequence type requirements. #if defined(GENERATING_DOCUMENTATION) template <typename Allocator = std::allocator<char>> #else template <typename Allocator> #endif class basic_streambuf_ref { public: /// The type used to represent the input sequence as a list of buffers. typedef typename basic_streambuf<Allocator>::const_buffers_type const_buffers_type; /// The type used to represent the output sequence as a list of buffers. typedef typename basic_streambuf<Allocator>::mutable_buffers_type mutable_buffers_type; /// Construct a basic_streambuf_ref for the given basic_streambuf object. explicit basic_streambuf_ref(basic_streambuf<Allocator>& sb) : sb_(sb) { } /// Copy construct a basic_streambuf_ref. basic_streambuf_ref(const basic_streambuf_ref& other) noexcept : sb_(other.sb_) { } /// Move construct a basic_streambuf_ref. basic_streambuf_ref(basic_streambuf_ref&& other) noexcept : sb_(other.sb_) { } /// Get the size of the input sequence. std::size_t size() const noexcept { return sb_.size(); } /// Get the maximum size of the dynamic buffer. std::size_t max_size() const noexcept { return sb_.max_size(); } /// Get the current capacity of the dynamic buffer. std::size_t capacity() const noexcept { return sb_.capacity(); } /// Get a list of buffers that represents the input sequence. const_buffers_type data() const noexcept { return sb_.data(); } /// Get a list of buffers that represents the output sequence, with the given /// size. mutable_buffers_type prepare(std::size_t n) { return sb_.prepare(n); } /// Move bytes from the output sequence to the input sequence. void commit(std::size_t n) { return sb_.commit(n); } /// Remove characters from the input sequence. void consume(std::size_t n) { return sb_.consume(n); } private: basic_streambuf<Allocator>& sb_; }; } // namespace asio #include "asio/detail/pop_options.hpp" #endif // !defined(ASIO_NO_IOSTREAM) #endif // ASIO_BASIC_STREAMBUF_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/associator.hpp
// // associator.hpp // ~~~~~~~~~~~~~~ // // 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) // #ifndef ASIO_ASSOCIATOR_HPP #define ASIO_ASSOCIATOR_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include "asio/detail/push_options.hpp" namespace asio { /// Used to generically specialise associators for a type. template <template <typename, typename> class Associator, typename T, typename DefaultCandidate, typename _ = void> struct associator { }; } // namespace asio #include "asio/detail/pop_options.hpp" #endif // ASIO_ASSOCIATOR_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/any_completion_executor.hpp
// // any_completion_executor.hpp // ~~~~~~~~~~~~~~~~~~~~~~~~~~~ // // 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) // #ifndef ASIO_ANY_COMPLETION_EXECUTOR_HPP #define ASIO_ANY_COMPLETION_EXECUTOR_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #if defined(ASIO_USE_TS_EXECUTOR_AS_DEFAULT) # include "asio/executor.hpp" #else // defined(ASIO_USE_TS_EXECUTOR_AS_DEFAULT) # include "asio/execution.hpp" #endif // defined(ASIO_USE_TS_EXECUTOR_AS_DEFAULT) #include "asio/detail/push_options.hpp" namespace asio { #if defined(ASIO_USE_TS_EXECUTOR_AS_DEFAULT) typedef executor any_completion_executor; #else // defined(ASIO_USE_TS_EXECUTOR_AS_DEFAULT) /// Polymorphic executor type for use with I/O objects. /** * The @c any_completion_executor type is a polymorphic executor that supports * the set of properties required for the execution of completion handlers. It * is defined as the execution::any_executor class template parameterised as * follows: * @code execution::any_executor< * execution::prefer_only<execution::outstanding_work_t::tracked_t>, * execution::prefer_only<execution::outstanding_work_t::untracked_t> * execution::prefer_only<execution::relationship_t::fork_t>, * execution::prefer_only<execution::relationship_t::continuation_t> * > @endcode */ class any_completion_executor : #if defined(GENERATING_DOCUMENTATION) public execution::any_executor<...> #else // defined(GENERATING_DOCUMENTATION) public execution::any_executor< execution::prefer_only<execution::outstanding_work_t::tracked_t>, execution::prefer_only<execution::outstanding_work_t::untracked_t>, execution::prefer_only<execution::relationship_t::fork_t>, execution::prefer_only<execution::relationship_t::continuation_t> > #endif // defined(GENERATING_DOCUMENTATION) { public: #if !defined(GENERATING_DOCUMENTATION) typedef execution::any_executor< execution::prefer_only<execution::outstanding_work_t::tracked_t>, execution::prefer_only<execution::outstanding_work_t::untracked_t>, execution::prefer_only<execution::relationship_t::fork_t>, execution::prefer_only<execution::relationship_t::continuation_t> > base_type; typedef void supportable_properties_type( execution::prefer_only<execution::outstanding_work_t::tracked_t>, execution::prefer_only<execution::outstanding_work_t::untracked_t>, execution::prefer_only<execution::relationship_t::fork_t>, execution::prefer_only<execution::relationship_t::continuation_t> ); #endif // !defined(GENERATING_DOCUMENTATION) /// Default constructor. ASIO_DECL any_completion_executor() noexcept; /// Construct in an empty state. Equivalent effects to default constructor. ASIO_DECL any_completion_executor(nullptr_t) noexcept; /// Copy constructor. ASIO_DECL any_completion_executor( const any_completion_executor& e) noexcept; /// Move constructor. ASIO_DECL any_completion_executor( any_completion_executor&& e) noexcept; /// Construct to point to the same target as another any_executor. #if defined(GENERATING_DOCUMENTATION) template <class... OtherSupportableProperties> any_completion_executor( execution::any_executor<OtherSupportableProperties...> e); #else // defined(GENERATING_DOCUMENTATION) template <typename OtherAnyExecutor> any_completion_executor(OtherAnyExecutor e, constraint_t< conditional< !is_same<OtherAnyExecutor, any_completion_executor>::value && is_base_of<execution::detail::any_executor_base, OtherAnyExecutor>::value, typename execution::detail::supportable_properties< 0, supportable_properties_type>::template is_valid_target<OtherAnyExecutor>, false_type >::type::value > = 0) : base_type(static_cast<OtherAnyExecutor&&>(e)) { } #endif // defined(GENERATING_DOCUMENTATION) /// Construct to point to the same target as another any_executor. #if defined(GENERATING_DOCUMENTATION) template <class... OtherSupportableProperties> any_completion_executor(std::nothrow_t, execution::any_executor<OtherSupportableProperties...> e); #else // defined(GENERATING_DOCUMENTATION) template <typename OtherAnyExecutor> any_completion_executor(std::nothrow_t, OtherAnyExecutor e, constraint_t< conditional< !is_same<OtherAnyExecutor, any_completion_executor>::value && is_base_of<execution::detail::any_executor_base, OtherAnyExecutor>::value, typename execution::detail::supportable_properties< 0, supportable_properties_type>::template is_valid_target<OtherAnyExecutor>, false_type >::type::value > = 0) noexcept : base_type(std::nothrow, static_cast<OtherAnyExecutor&&>(e)) { } #endif // defined(GENERATING_DOCUMENTATION) /// Construct to point to the same target as another any_executor. ASIO_DECL any_completion_executor(std::nothrow_t, const any_completion_executor& e) noexcept; /// Construct to point to the same target as another any_executor. ASIO_DECL any_completion_executor(std::nothrow_t, any_completion_executor&& e) noexcept; /// Construct a polymorphic wrapper for the specified executor. #if defined(GENERATING_DOCUMENTATION) template <ASIO_EXECUTION_EXECUTOR Executor> any_completion_executor(Executor e); #else // defined(GENERATING_DOCUMENTATION) template <ASIO_EXECUTION_EXECUTOR Executor> any_completion_executor(Executor e, constraint_t< conditional< !is_same<Executor, any_completion_executor>::value && !is_base_of<execution::detail::any_executor_base, Executor>::value, execution::detail::is_valid_target_executor< Executor, supportable_properties_type>, false_type >::type::value > = 0) : base_type(static_cast<Executor&&>(e)) { } #endif // defined(GENERATING_DOCUMENTATION) /// Construct a polymorphic wrapper for the specified executor. #if defined(GENERATING_DOCUMENTATION) template <ASIO_EXECUTION_EXECUTOR Executor> any_completion_executor(std::nothrow_t, Executor e); #else // defined(GENERATING_DOCUMENTATION) template <ASIO_EXECUTION_EXECUTOR Executor> any_completion_executor(std::nothrow_t, Executor e, constraint_t< conditional< !is_same<Executor, any_completion_executor>::value && !is_base_of<execution::detail::any_executor_base, Executor>::value, execution::detail::is_valid_target_executor< Executor, supportable_properties_type>, false_type >::type::value > = 0) noexcept : base_type(std::nothrow, static_cast<Executor&&>(e)) { } #endif // defined(GENERATING_DOCUMENTATION) /// Assignment operator. ASIO_DECL any_completion_executor& operator=( const any_completion_executor& e) noexcept; /// Move assignment operator. ASIO_DECL any_completion_executor& operator=( any_completion_executor&& e) noexcept; /// Assignment operator that sets the polymorphic wrapper to the empty state. ASIO_DECL any_completion_executor& operator=(nullptr_t); /// Destructor. ASIO_DECL ~any_completion_executor(); /// Swap targets with another polymorphic wrapper. ASIO_DECL void swap(any_completion_executor& other) noexcept; /// Obtain a polymorphic wrapper with the specified property. /** * Do not call this function directly. It is intended for use with the * asio::require and asio::prefer customisation points. * * For example: * @code any_completion_executor ex = ...; * auto ex2 = asio::require(ex, execution::relationship.fork); @endcode */ template <typename Property> any_completion_executor require(const Property& p, constraint_t< traits::require_member<const base_type&, const Property&>::is_valid > = 0) const { return static_cast<const base_type&>(*this).require(p); } /// Obtain a polymorphic wrapper with the specified property. /** * Do not call this function directly. It is intended for use with the * asio::prefer customisation point. * * For example: * @code any_completion_executor ex = ...; * auto ex2 = asio::prefer(ex, execution::relationship.fork); @endcode */ template <typename Property> any_completion_executor prefer(const Property& p, constraint_t< traits::prefer_member<const base_type&, const Property&>::is_valid > = 0) const { return static_cast<const base_type&>(*this).prefer(p); } }; #if !defined(GENERATING_DOCUMENTATION) template <> ASIO_DECL any_completion_executor any_completion_executor::prefer( const execution::outstanding_work_t::tracked_t&, int) const; template <> ASIO_DECL any_completion_executor any_completion_executor::prefer( const execution::outstanding_work_t::untracked_t&, int) const; template <> ASIO_DECL any_completion_executor any_completion_executor::prefer( const execution::relationship_t::fork_t&, int) const; template <> ASIO_DECL any_completion_executor any_completion_executor::prefer( const execution::relationship_t::continuation_t&, int) const; namespace traits { #if !defined(ASIO_HAS_DEDUCED_EQUALITY_COMPARABLE_TRAIT) template <> struct equality_comparable<any_completion_executor> { static const bool is_valid = true; static const bool is_noexcept = true; }; #endif // !defined(ASIO_HAS_DEDUCED_EQUALITY_COMPARABLE_TRAIT) #if !defined(ASIO_HAS_DEDUCED_EXECUTE_MEMBER_TRAIT) template <typename F> struct execute_member<any_completion_executor, F> { static const bool is_valid = true; static const bool is_noexcept = false; typedef void result_type; }; #endif // !defined(ASIO_HAS_DEDUCED_EXECUTE_MEMBER_TRAIT) #if !defined(ASIO_HAS_DEDUCED_QUERY_MEMBER_TRAIT) template <typename Prop> struct query_member<any_completion_executor, Prop> : query_member<any_completion_executor::base_type, Prop> { }; #endif // !defined(ASIO_HAS_DEDUCED_QUERY_MEMBER_TRAIT) #if !defined(ASIO_HAS_DEDUCED_REQUIRE_MEMBER_TRAIT) template <typename Prop> struct require_member<any_completion_executor, Prop> : require_member<any_completion_executor::base_type, Prop> { typedef any_completion_executor result_type; }; #endif // !defined(ASIO_HAS_DEDUCED_REQUIRE_MEMBER_TRAIT) #if !defined(ASIO_HAS_DEDUCED_PREFER_MEMBER_TRAIT) template <typename Prop> struct prefer_member<any_completion_executor, Prop> : prefer_member<any_completion_executor::base_type, Prop> { typedef any_completion_executor result_type; }; #endif // !defined(ASIO_HAS_DEDUCED_PREFER_MEMBER_TRAIT) } // namespace traits #endif // !defined(GENERATING_DOCUMENTATION) #endif // defined(ASIO_USE_TS_EXECUTOR_AS_DEFAULT) } // namespace asio #include "asio/detail/pop_options.hpp" #if defined(ASIO_HEADER_ONLY) \ && !defined(ASIO_USE_TS_EXECUTOR_AS_DEFAULT) # include "asio/impl/any_completion_executor.ipp" #endif // defined(ASIO_HEADER_ONLY) // && !defined(ASIO_USE_TS_EXECUTOR_AS_DEFAULT) #endif // ASIO_ANY_COMPLETION_EXECUTOR_HPP