repo_name
stringclasses
10 values
file_path
stringlengths
29
222
content
stringlengths
24
926k
extention
stringclasses
5 values
asio
data/projects/asio/include/boost/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) // // See www.boost.org/libs/asio for documentation. // #ifndef BOOST_ASIO_HPP #define BOOST_ASIO_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <boost/asio/any_completion_executor.hpp> #include <boost/asio/any_completion_handler.hpp> #include <boost/asio/any_io_executor.hpp> #include <boost/asio/append.hpp> #include <boost/asio/as_tuple.hpp> #include <boost/asio/associated_allocator.hpp> #include <boost/asio/associated_cancellation_slot.hpp> #include <boost/asio/associated_executor.hpp> #include <boost/asio/associated_immediate_executor.hpp> #include <boost/asio/associator.hpp> #include <boost/asio/async_result.hpp> #include <boost/asio/awaitable.hpp> #include <boost/asio/basic_datagram_socket.hpp> #include <boost/asio/basic_deadline_timer.hpp> #include <boost/asio/basic_file.hpp> #include <boost/asio/basic_io_object.hpp> #include <boost/asio/basic_random_access_file.hpp> #include <boost/asio/basic_raw_socket.hpp> #include <boost/asio/basic_readable_pipe.hpp> #include <boost/asio/basic_seq_packet_socket.hpp> #include <boost/asio/basic_serial_port.hpp> #include <boost/asio/basic_signal_set.hpp> #include <boost/asio/basic_socket.hpp> #include <boost/asio/basic_socket_acceptor.hpp> #include <boost/asio/basic_socket_iostream.hpp> #include <boost/asio/basic_socket_streambuf.hpp> #include <boost/asio/basic_stream_file.hpp> #include <boost/asio/basic_stream_socket.hpp> #include <boost/asio/basic_streambuf.hpp> #include <boost/asio/basic_waitable_timer.hpp> #include <boost/asio/basic_writable_pipe.hpp> #include <boost/asio/bind_allocator.hpp> #include <boost/asio/bind_cancellation_slot.hpp> #include <boost/asio/bind_executor.hpp> #include <boost/asio/bind_immediate_executor.hpp> #include <boost/asio/buffer.hpp> #include <boost/asio/buffer_registration.hpp> #include <boost/asio/buffered_read_stream_fwd.hpp> #include <boost/asio/buffered_read_stream.hpp> #include <boost/asio/buffered_stream_fwd.hpp> #include <boost/asio/buffered_stream.hpp> #include <boost/asio/buffered_write_stream_fwd.hpp> #include <boost/asio/buffered_write_stream.hpp> #include <boost/asio/buffers_iterator.hpp> #include <boost/asio/cancellation_signal.hpp> #include <boost/asio/cancellation_state.hpp> #include <boost/asio/cancellation_type.hpp> #include <boost/asio/co_spawn.hpp> #include <boost/asio/completion_condition.hpp> #include <boost/asio/compose.hpp> #include <boost/asio/connect.hpp> #include <boost/asio/connect_pipe.hpp> #include <boost/asio/consign.hpp> #include <boost/asio/coroutine.hpp> #include <boost/asio/deadline_timer.hpp> #include <boost/asio/defer.hpp> #include <boost/asio/deferred.hpp> #include <boost/asio/detached.hpp> #include <boost/asio/dispatch.hpp> #include <boost/asio/error.hpp> #include <boost/asio/execution.hpp> #include <boost/asio/execution/allocator.hpp> #include <boost/asio/execution/any_executor.hpp> #include <boost/asio/execution/blocking.hpp> #include <boost/asio/execution/blocking_adaptation.hpp> #include <boost/asio/execution/context.hpp> #include <boost/asio/execution/context_as.hpp> #include <boost/asio/execution/executor.hpp> #include <boost/asio/execution/invocable_archetype.hpp> #include <boost/asio/execution/mapping.hpp> #include <boost/asio/execution/occupancy.hpp> #include <boost/asio/execution/outstanding_work.hpp> #include <boost/asio/execution/prefer_only.hpp> #include <boost/asio/execution/relationship.hpp> #include <boost/asio/executor.hpp> #include <boost/asio/executor_work_guard.hpp> #include <boost/asio/file_base.hpp> #include <boost/asio/generic/basic_endpoint.hpp> #include <boost/asio/generic/datagram_protocol.hpp> #include <boost/asio/generic/raw_protocol.hpp> #include <boost/asio/generic/seq_packet_protocol.hpp> #include <boost/asio/generic/stream_protocol.hpp> #include <boost/asio/handler_continuation_hook.hpp> #include <boost/asio/high_resolution_timer.hpp> #include <boost/asio/io_context.hpp> #include <boost/asio/io_context_strand.hpp> #include <boost/asio/io_service.hpp> #include <boost/asio/io_service_strand.hpp> #include <boost/asio/ip/address.hpp> #include <boost/asio/ip/address_v4.hpp> #include <boost/asio/ip/address_v4_iterator.hpp> #include <boost/asio/ip/address_v4_range.hpp> #include <boost/asio/ip/address_v6.hpp> #include <boost/asio/ip/address_v6_iterator.hpp> #include <boost/asio/ip/address_v6_range.hpp> #include <boost/asio/ip/network_v4.hpp> #include <boost/asio/ip/network_v6.hpp> #include <boost/asio/ip/bad_address_cast.hpp> #include <boost/asio/ip/basic_endpoint.hpp> #include <boost/asio/ip/basic_resolver.hpp> #include <boost/asio/ip/basic_resolver_entry.hpp> #include <boost/asio/ip/basic_resolver_iterator.hpp> #include <boost/asio/ip/basic_resolver_query.hpp> #include <boost/asio/ip/host_name.hpp> #include <boost/asio/ip/icmp.hpp> #include <boost/asio/ip/multicast.hpp> #include <boost/asio/ip/resolver_base.hpp> #include <boost/asio/ip/resolver_query_base.hpp> #include <boost/asio/ip/tcp.hpp> #include <boost/asio/ip/udp.hpp> #include <boost/asio/ip/unicast.hpp> #include <boost/asio/ip/v6_only.hpp> #include <boost/asio/is_applicable_property.hpp> #include <boost/asio/is_contiguous_iterator.hpp> #include <boost/asio/is_executor.hpp> #include <boost/asio/is_read_buffered.hpp> #include <boost/asio/is_write_buffered.hpp> #include <boost/asio/local/basic_endpoint.hpp> #include <boost/asio/local/connect_pair.hpp> #include <boost/asio/local/datagram_protocol.hpp> #include <boost/asio/local/seq_packet_protocol.hpp> #include <boost/asio/local/stream_protocol.hpp> #include <boost/asio/multiple_exceptions.hpp> #include <boost/asio/packaged_task.hpp> #include <boost/asio/placeholders.hpp> #include <boost/asio/posix/basic_descriptor.hpp> #include <boost/asio/posix/basic_stream_descriptor.hpp> #include <boost/asio/posix/descriptor.hpp> #include <boost/asio/posix/descriptor_base.hpp> #include <boost/asio/posix/stream_descriptor.hpp> #include <boost/asio/post.hpp> #include <boost/asio/prefer.hpp> #include <boost/asio/prepend.hpp> #include <boost/asio/query.hpp> #include <boost/asio/random_access_file.hpp> #include <boost/asio/read.hpp> #include <boost/asio/read_at.hpp> #include <boost/asio/read_until.hpp> #include <boost/asio/readable_pipe.hpp> #include <boost/asio/recycling_allocator.hpp> #include <boost/asio/redirect_error.hpp> #include <boost/asio/registered_buffer.hpp> #include <boost/asio/require.hpp> #include <boost/asio/require_concept.hpp> #include <boost/asio/serial_port.hpp> #include <boost/asio/serial_port_base.hpp> #include <boost/asio/signal_set.hpp> #include <boost/asio/signal_set_base.hpp> #include <boost/asio/socket_base.hpp> #include <boost/asio/static_thread_pool.hpp> #include <boost/asio/steady_timer.hpp> #include <boost/asio/strand.hpp> #include <boost/asio/stream_file.hpp> #include <boost/asio/streambuf.hpp> #include <boost/asio/system_context.hpp> #include <boost/asio/system_executor.hpp> #include <boost/asio/system_timer.hpp> #include <boost/asio/this_coro.hpp> #include <boost/asio/thread_pool.hpp> #include <boost/asio/time_traits.hpp> #include <boost/asio/use_awaitable.hpp> #include <boost/asio/use_future.hpp> #include <boost/asio/uses_executor.hpp> #include <boost/asio/version.hpp> #include <boost/asio/wait_traits.hpp> #include <boost/asio/windows/basic_object_handle.hpp> #include <boost/asio/windows/basic_overlapped_handle.hpp> #include <boost/asio/windows/basic_random_access_handle.hpp> #include <boost/asio/windows/basic_stream_handle.hpp> #include <boost/asio/windows/object_handle.hpp> #include <boost/asio/windows/overlapped_handle.hpp> #include <boost/asio/windows/overlapped_ptr.hpp> #include <boost/asio/windows/random_access_handle.hpp> #include <boost/asio/windows/stream_handle.hpp> #include <boost/asio/writable_pipe.hpp> #include <boost/asio/write.hpp> #include <boost/asio/write_at.hpp> #endif // BOOST_ASIO_HPP
hpp
asio
data/projects/asio/include/boost/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 BOOST_ASIO_ASSOCIATED_ALLOCATOR_HPP #define BOOST_ASIO_ASSOCIATED_ALLOCATOR_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <boost/asio/detail/config.hpp> #include <memory> #include <boost/asio/associator.hpp> #include <boost/asio/detail/functional.hpp> #include <boost/asio/detail/type_traits.hpp> #include <boost/asio/detail/push_options.hpp> namespace boost { 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> BOOST_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> BOOST_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 } // namespace boost #include <boost/asio/detail/pop_options.hpp> #endif // BOOST_ASIO_ASSOCIATED_ALLOCATOR_HPP
hpp
asio
data/projects/asio/include/boost/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 BOOST_ASIO_REDIRECT_ERROR_HPP #define BOOST_ASIO_REDIRECT_ERROR_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <boost/asio/detail/config.hpp> #include <boost/asio/detail/type_traits.hpp> #include <boost/system/error_code.hpp> #include <boost/asio/detail/push_options.hpp> namespace boost { 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, boost::system::error_code& ec) : token_(static_cast<T&&>(completion_token)), ec_(ec) { } //private: CompletionToken token_; boost::system::error_code& ec_; }; /// Adapt a @ref completion_token to capture error_code values to a variable. template <typename CompletionToken> inline redirect_error_t<decay_t<CompletionToken>> redirect_error( CompletionToken&& completion_token, boost::system::error_code& ec) { return redirect_error_t<decay_t<CompletionToken>>( static_cast<CompletionToken&&>(completion_token), ec); } } // namespace asio } // namespace boost #include <boost/asio/detail/pop_options.hpp> #include <boost/asio/impl/redirect_error.hpp> #endif // BOOST_ASIO_REDIRECT_ERROR_HPP
hpp
asio
data/projects/asio/include/boost/asio/read.hpp
// // read.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 BOOST_ASIO_READ_HPP #define BOOST_ASIO_READ_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <boost/asio/detail/config.hpp> #include <cstddef> #include <boost/asio/async_result.hpp> #include <boost/asio/buffer.hpp> #include <boost/asio/completion_condition.hpp> #include <boost/asio/error.hpp> #if !defined(BOOST_ASIO_NO_EXTENSIONS) # include <boost/asio/basic_streambuf_fwd.hpp> #endif // !defined(BOOST_ASIO_NO_EXTENSIONS) #include <boost/asio/detail/push_options.hpp> namespace boost { namespace asio { namespace detail { template <typename> class initiate_async_read; #if !defined(BOOST_ASIO_NO_DYNAMIC_BUFFER_V1) template <typename> class initiate_async_read_dynbuf_v1; #endif // !defined(BOOST_ASIO_NO_DYNAMIC_BUFFER_V1) template <typename> class initiate_async_read_dynbuf_v2; } // namespace detail /** * @defgroup read boost::asio::read * * @brief The @c read function is a composed operation that reads a certain * amount of data from a stream before returning. */ /*@{*/ /// Attempt to read a certain amount of data from a stream before returning. /** * This function is used to read a certain number of bytes of data from a * stream. 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 stream's * read_some function. * * @param s The stream from which the data is to be read. The type must support * the SyncReadStream concept. * * @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 * stream. * * @returns The number of bytes transferred. * * @throws boost::system::system_error Thrown on failure. * * @par Example * To read into a single data buffer use the @ref buffer function as follows: * @code boost::asio::read(s, boost::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 boost::asio::read( * s, buffers, * boost::asio::transfer_all()); @endcode */ template <typename SyncReadStream, typename MutableBufferSequence> std::size_t read(SyncReadStream& s, const MutableBufferSequence& buffers, constraint_t< is_mutable_buffer_sequence<MutableBufferSequence>::value > = 0); /// Attempt to read a certain amount of data from a stream before returning. /** * This function is used to read a certain number of bytes of data from a * stream. 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 stream's * read_some function. * * @param s The stream from which the data is to be read. The type must support * the SyncReadStream concept. * * @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 * stream. * * @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 boost::asio::read(s, boost::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 boost::asio::read( * s, buffers, * boost::asio::transfer_all(), ec); @endcode */ template <typename SyncReadStream, typename MutableBufferSequence> std::size_t read(SyncReadStream& s, const MutableBufferSequence& buffers, boost::system::error_code& ec, constraint_t< is_mutable_buffer_sequence<MutableBufferSequence>::value > = 0); /// Attempt to read a certain amount of data from a stream before returning. /** * This function is used to read a certain number of bytes of data from a * stream. 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 stream's * read_some function. * * @param s The stream from which the data is to be read. The type must support * the SyncReadStream concept. * * @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 * stream. * * @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 operation. * const boost::system::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 stream's read_some function. * * @returns The number of bytes transferred. * * @throws boost::system::system_error Thrown on failure. * * @par Example * To read into a single data buffer use the @ref buffer function as follows: * @code boost::asio::read(s, boost::asio::buffer(data, size), * boost::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 SyncReadStream, typename MutableBufferSequence, typename CompletionCondition> std::size_t read(SyncReadStream& s, const MutableBufferSequence& buffers, CompletionCondition completion_condition, constraint_t< is_mutable_buffer_sequence<MutableBufferSequence>::value > = 0); /// Attempt to read a certain amount of data from a stream before returning. /** * This function is used to read a certain number of bytes of data from a * stream. 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 stream's * read_some function. * * @param s The stream from which the data is to be read. The type must support * the SyncReadStream concept. * * @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 * stream. * * @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 operation. * const boost::system::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 stream's read_some 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 SyncReadStream, typename MutableBufferSequence, typename CompletionCondition> std::size_t read(SyncReadStream& s, const MutableBufferSequence& buffers, CompletionCondition completion_condition, boost::system::error_code& ec, constraint_t< is_mutable_buffer_sequence<MutableBufferSequence>::value > = 0); #if !defined(BOOST_ASIO_NO_DYNAMIC_BUFFER_V1) /// Attempt to read a certain amount of data from a stream before returning. /** * This function is used to read a certain number of bytes of data from a * stream. The call will block until one of the following conditions is true: * * @li The specified dynamic buffer sequence is full (that is, it has reached * maximum size). * * @li An error occurred. * * This operation is implemented in terms of zero or more calls to the stream's * read_some function. * * @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. * * @returns The number of bytes transferred. * * @throws boost::system::system_error Thrown on failure. * * @note This overload is equivalent to calling: * @code boost::asio::read( * s, buffers, * boost::asio::transfer_all()); @endcode */ template <typename SyncReadStream, typename DynamicBuffer_v1> std::size_t read(SyncReadStream& 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); /// Attempt to read a certain amount of data from a stream before returning. /** * This function is used to read a certain number of bytes of data from a * stream. The call will block until one of the following conditions is true: * * @li The supplied buffer is full (that is, it has reached maximum size). * * @li An error occurred. * * This operation is implemented in terms of zero or more calls to the stream's * read_some function. * * @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 ec Set to indicate what error occurred, if any. * * @returns The number of bytes transferred. * * @note This overload is equivalent to calling: * @code boost::asio::read( * s, buffers, * boost::asio::transfer_all(), ec); @endcode */ template <typename SyncReadStream, typename DynamicBuffer_v1> std::size_t read(SyncReadStream& s, DynamicBuffer_v1&& buffers, boost::system::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); /// Attempt to read a certain amount of data from a stream before returning. /** * This function is used to read a certain number of bytes of data from a * stream. The call will block until one of the following conditions is true: * * @li The specified dynamic buffer sequence is full (that is, it has reached * maximum size). * * @li The completion_condition function object returns 0. * * This operation is implemented in terms of zero or more calls to the stream's * read_some function. * * @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 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 operation. * const boost::system::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 stream's read_some function. * * @returns The number of bytes transferred. * * @throws boost::system::system_error Thrown on failure. */ template <typename SyncReadStream, typename DynamicBuffer_v1, typename CompletionCondition> std::size_t read(SyncReadStream& 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); /// Attempt to read a certain amount of data from a stream before returning. /** * This function is used to read a certain number of bytes of data from a * stream. The call will block until one of the following conditions is true: * * @li The specified dynamic buffer sequence is full (that is, it has reached * maximum size). * * @li The completion_condition function object returns 0. * * This operation is implemented in terms of zero or more calls to the stream's * read_some function. * * @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 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 operation. * const boost::system::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 stream's read_some 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 SyncReadStream, typename DynamicBuffer_v1, typename CompletionCondition> std::size_t read(SyncReadStream& s, DynamicBuffer_v1&& buffers, CompletionCondition completion_condition, boost::system::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(BOOST_ASIO_NO_EXTENSIONS) #if !defined(BOOST_ASIO_NO_IOSTREAM) /// Attempt to read a certain amount of data from a stream before returning. /** * This function is used to read a certain number of bytes of data from a * stream. The call will block until one of the following conditions is true: * * @li The supplied buffer is full (that is, it has reached maximum size). * * @li An error occurred. * * This operation is implemented in terms of zero or more calls to the stream's * read_some function. * * @param s The stream from which the data is to be read. The type must support * the SyncReadStream concept. * * @param b The basic_streambuf object into which the data will be read. * * @returns The number of bytes transferred. * * @throws boost::system::system_error Thrown on failure. * * @note This overload is equivalent to calling: * @code boost::asio::read( * s, b, * boost::asio::transfer_all()); @endcode */ template <typename SyncReadStream, typename Allocator> std::size_t read(SyncReadStream& s, basic_streambuf<Allocator>& b); /// Attempt to read a certain amount of data from a stream before returning. /** * This function is used to read a certain number of bytes of data from a * stream. The call will block until one of the following conditions is true: * * @li The supplied buffer is full (that is, it has reached maximum size). * * @li An error occurred. * * This operation is implemented in terms of zero or more calls to the stream's * read_some function. * * @param s The stream from which the data is to be read. The type must support * the SyncReadStream concept. * * @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 boost::asio::read( * s, b, * boost::asio::transfer_all(), ec); @endcode */ template <typename SyncReadStream, typename Allocator> std::size_t read(SyncReadStream& s, basic_streambuf<Allocator>& b, boost::system::error_code& ec); /// Attempt to read a certain amount of data from a stream before returning. /** * This function is used to read a certain number of bytes of data from a * stream. The call will block until one of the following conditions is true: * * @li The supplied buffer is full (that is, it has reached maximum size). * * @li The completion_condition function object returns 0. * * This operation is implemented in terms of zero or more calls to the stream's * read_some function. * * @param s The stream from which the data is to be read. The type must support * the SyncReadStream concept. * * @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 operation. * const boost::system::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 stream's read_some function. * * @returns The number of bytes transferred. * * @throws boost::system::system_error Thrown on failure. */ template <typename SyncReadStream, typename Allocator, typename CompletionCondition> std::size_t read(SyncReadStream& s, basic_streambuf<Allocator>& b, CompletionCondition completion_condition); /// Attempt to read a certain amount of data from a stream before returning. /** * This function is used to read a certain number of bytes of data from a * stream. The call will block until one of the following conditions is true: * * @li The supplied buffer is full (that is, it has reached maximum size). * * @li The completion_condition function object returns 0. * * This operation is implemented in terms of zero or more calls to the stream's * read_some function. * * @param s The stream from which the data is to be read. The type must support * the SyncReadStream concept. * * @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 operation. * const boost::system::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 stream's read_some 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 SyncReadStream, typename Allocator, typename CompletionCondition> std::size_t read(SyncReadStream& s, basic_streambuf<Allocator>& b, CompletionCondition completion_condition, boost::system::error_code& ec); #endif // !defined(BOOST_ASIO_NO_IOSTREAM) #endif // !defined(BOOST_ASIO_NO_EXTENSIONS) #endif // !defined(BOOST_ASIO_NO_DYNAMIC_BUFFER_V1) /// Attempt to read a certain amount of data from a stream before returning. /** * This function is used to read a certain number of bytes of data from a * stream. The call will block until one of the following conditions is true: * * @li The specified dynamic buffer sequence is full (that is, it has reached * maximum size). * * @li An error occurred. * * This operation is implemented in terms of zero or more calls to the stream's * read_some function. * * @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. * * @returns The number of bytes transferred. * * @throws boost::system::system_error Thrown on failure. * * @note This overload is equivalent to calling: * @code boost::asio::read( * s, buffers, * boost::asio::transfer_all()); @endcode */ template <typename SyncReadStream, typename DynamicBuffer_v2> std::size_t read(SyncReadStream& s, DynamicBuffer_v2 buffers, constraint_t< is_dynamic_buffer_v2<DynamicBuffer_v2>::value > = 0); /// Attempt to read a certain amount of data from a stream before returning. /** * This function is used to read a certain number of bytes of data from a * stream. The call will block until one of the following conditions is true: * * @li The supplied buffer is full (that is, it has reached maximum size). * * @li An error occurred. * * This operation is implemented in terms of zero or more calls to the stream's * read_some function. * * @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 ec Set to indicate what error occurred, if any. * * @returns The number of bytes transferred. * * @note This overload is equivalent to calling: * @code boost::asio::read( * s, buffers, * boost::asio::transfer_all(), ec); @endcode */ template <typename SyncReadStream, typename DynamicBuffer_v2> std::size_t read(SyncReadStream& s, DynamicBuffer_v2 buffers, boost::system::error_code& ec, constraint_t< is_dynamic_buffer_v2<DynamicBuffer_v2>::value > = 0); /// Attempt to read a certain amount of data from a stream before returning. /** * This function is used to read a certain number of bytes of data from a * stream. The call will block until one of the following conditions is true: * * @li The specified dynamic buffer sequence is full (that is, it has reached * maximum size). * * @li The completion_condition function object returns 0. * * This operation is implemented in terms of zero or more calls to the stream's * read_some function. * * @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 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 operation. * const boost::system::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 stream's read_some function. * * @returns The number of bytes transferred. * * @throws boost::system::system_error Thrown on failure. */ template <typename SyncReadStream, typename DynamicBuffer_v2, typename CompletionCondition> std::size_t read(SyncReadStream& s, DynamicBuffer_v2 buffers, CompletionCondition completion_condition, constraint_t< is_dynamic_buffer_v2<DynamicBuffer_v2>::value > = 0); /// Attempt to read a certain amount of data from a stream before returning. /** * This function is used to read a certain number of bytes of data from a * stream. The call will block until one of the following conditions is true: * * @li The specified dynamic buffer sequence is full (that is, it has reached * maximum size). * * @li The completion_condition function object returns 0. * * This operation is implemented in terms of zero or more calls to the stream's * read_some function. * * @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 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 operation. * const boost::system::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 stream's read_some 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 SyncReadStream, typename DynamicBuffer_v2, typename CompletionCondition> std::size_t read(SyncReadStream& s, DynamicBuffer_v2 buffers, CompletionCondition completion_condition, boost::system::error_code& ec, constraint_t< is_dynamic_buffer_v2<DynamicBuffer_v2>::value > = 0); /*@}*/ /** * @defgroup async_read boost::asio::async_read * * @brief The @c async_read function is a composed asynchronous operation that * reads a certain amount of data from a stream before completion. */ /*@{*/ /// Start an asynchronous operation to read a certain amount of data from a /// stream. /** * This function is used to asynchronously read a certain number of bytes of * data from 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 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 stream's * async_read_some function, and is known as a <em>composed operation</em>. The * program must ensure that the stream performs no other read operations (such * as async_read, 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 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 * stream. 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 boost::system::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 boost::asio::post(). * * @par Completion Signature * @code void(boost::system::error_code, std::size_t) @endcode * * @par Example * To read into a single data buffer use the @ref buffer function as follows: * @code * boost::asio::async_read(s, boost::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 boost::asio::async_read( * s, buffers, * boost::asio::transfer_all(), * handler); @endcode * * @par Per-Operation Cancellation * This asynchronous operation supports cancellation for the following * boost::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 MutableBufferSequence, BOOST_ASIO_COMPLETION_TOKEN_FOR(void (boost::system::error_code, std::size_t)) ReadToken = default_completion_token_t< typename AsyncReadStream::executor_type>> auto async_read(AsyncReadStream& s, const MutableBufferSequence& buffers, ReadToken&& token = default_completion_token_t< typename AsyncReadStream::executor_type>(), constraint_t< is_mutable_buffer_sequence<MutableBufferSequence>::value > = 0) -> decltype( async_initiate<ReadToken, void (boost::system::error_code, std::size_t)>( declval<detail::initiate_async_read<AsyncReadStream>>(), token, buffers, transfer_all())); /// Start an asynchronous operation to read a certain amount of data from a /// stream. /** * This function is used to asynchronously read a certain number of bytes of * data from 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 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 s The stream from which the data is to be read. The type must support * the AsyncReadStream concept. * * @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 * stream. 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 operation. * const boost::system::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 stream's async_read_some 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 boost::system::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 boost::asio::post(). * * @par Completion Signature * @code void(boost::system::error_code, std::size_t) @endcode * * @par Example * To read into a single data buffer use the @ref buffer function as follows: * @code boost::asio::async_read(s, * boost::asio::buffer(data, size), * boost::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 * boost::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 MutableBufferSequence, typename CompletionCondition, BOOST_ASIO_COMPLETION_TOKEN_FOR(void (boost::system::error_code, std::size_t)) ReadToken = default_completion_token_t< typename AsyncReadStream::executor_type>> auto async_read(AsyncReadStream& s, const MutableBufferSequence& buffers, CompletionCondition completion_condition, ReadToken&& token = default_completion_token_t< typename AsyncReadStream::executor_type>(), constraint_t< is_mutable_buffer_sequence<MutableBufferSequence>::value > = 0) -> decltype( async_initiate<ReadToken, void (boost::system::error_code, std::size_t)>( declval<detail::initiate_async_read<AsyncReadStream>>(), token, buffers, static_cast<CompletionCondition&&>(completion_condition))); #if !defined(BOOST_ASIO_NO_DYNAMIC_BUFFER_V1) /// Start an asynchronous operation to read a certain amount of data from a /// stream. /** * This function is used to asynchronously read a certain number of bytes of * data from 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 The specified dynamic buffer sequence is full (that is, it has reached * maximum size). * * @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>. The * program must ensure that the stream performs no other read operations (such * as async_read, 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 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 boost::system::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 boost::asio::post(). * * @par Completion Signature * @code void(boost::system::error_code, std::size_t) @endcode * * @note This overload is equivalent to calling: * @code boost::asio::async_read( * s, buffers, * boost::asio::transfer_all(), * handler); @endcode * * @par Per-Operation Cancellation * This asynchronous operation supports cancellation for the following * boost::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, BOOST_ASIO_COMPLETION_TOKEN_FOR(void (boost::system::error_code, std::size_t)) ReadToken = default_completion_token_t< typename AsyncReadStream::executor_type>> auto async_read(AsyncReadStream& s, DynamicBuffer_v1&& buffers, 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 (boost::system::error_code, std::size_t)>( declval<detail::initiate_async_read_dynbuf_v1<AsyncReadStream>>(), token, static_cast<DynamicBuffer_v1&&>(buffers), transfer_all())); /// Start an asynchronous operation to read a certain amount of data from a /// stream. /** * This function is used to asynchronously read a certain number of bytes of * data from 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 The specified dynamic buffer sequence is full (that is, it has reached * maximum size). * * @li The completion_condition function object returns 0. * * 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>. The * program must ensure that the stream performs no other read operations (such * as async_read, 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 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 operation. * const boost::system::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 stream's async_read_some 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 boost::system::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 boost::asio::post(). * * @par Completion Signature * @code void(boost::system::error_code, std::size_t) @endcode * * @par Per-Operation Cancellation * This asynchronous operation supports cancellation for the following * boost::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 CompletionCondition, BOOST_ASIO_COMPLETION_TOKEN_FOR(void (boost::system::error_code, std::size_t)) ReadToken = default_completion_token_t< typename AsyncReadStream::executor_type>> auto async_read(AsyncReadStream& s, DynamicBuffer_v1&& buffers, CompletionCondition completion_condition, 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 (boost::system::error_code, std::size_t)>( declval<detail::initiate_async_read_dynbuf_v1<AsyncReadStream>>(), token, static_cast<DynamicBuffer_v1&&>(buffers), static_cast<CompletionCondition&&>(completion_condition))); #if !defined(BOOST_ASIO_NO_EXTENSIONS) #if !defined(BOOST_ASIO_NO_IOSTREAM) /// Start an asynchronous operation to read a certain amount of data from a /// stream. /** * This function is used to asynchronously read a certain number of bytes of * data from 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 The supplied buffer is full (that is, it has reached maximum size). * * @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>. The * program must ensure that the stream performs no other read operations (such * as async_read, 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 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 boost::system::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 boost::asio::post(). * * @par Completion Signature * @code void(boost::system::error_code, std::size_t) @endcode * * @note This overload is equivalent to calling: * @code boost::asio::async_read( * s, b, * boost::asio::transfer_all(), * handler); @endcode * * @par Per-Operation Cancellation * This asynchronous operation supports cancellation for the following * boost::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, BOOST_ASIO_COMPLETION_TOKEN_FOR(void (boost::system::error_code, std::size_t)) ReadToken = default_completion_token_t< typename AsyncReadStream::executor_type>> auto async_read(AsyncReadStream& s, basic_streambuf<Allocator>& b, ReadToken&& token = default_completion_token_t< typename AsyncReadStream::executor_type>()) -> decltype( async_initiate<ReadToken, void (boost::system::error_code, std::size_t)>( declval<detail::initiate_async_read_dynbuf_v1<AsyncReadStream>>(), token, basic_streambuf_ref<Allocator>(b), transfer_all())); /// Start an asynchronous operation to read a certain amount of data from a /// stream. /** * This function is used to asynchronously read a certain number of bytes of * data from 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 The supplied buffer is full (that is, it has reached maximum size). * * @li The completion_condition function object returns 0. * * 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>. The * program must ensure that the stream performs no other read operations (such * as async_read, 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 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 operation. * const boost::system::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 stream's async_read_some 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 boost::system::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 boost::asio::post(). * * @par Completion Signature * @code void(boost::system::error_code, std::size_t) @endcode * * @par Per-Operation Cancellation * This asynchronous operation supports cancellation for the following * boost::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 CompletionCondition, BOOST_ASIO_COMPLETION_TOKEN_FOR(void (boost::system::error_code, std::size_t)) ReadToken = default_completion_token_t< typename AsyncReadStream::executor_type>> auto async_read(AsyncReadStream& s, basic_streambuf<Allocator>& b, CompletionCondition completion_condition, ReadToken&& token = default_completion_token_t< typename AsyncReadStream::executor_type>()) -> decltype( async_initiate<ReadToken, void (boost::system::error_code, std::size_t)>( declval<detail::initiate_async_read_dynbuf_v1<AsyncReadStream>>(), token, basic_streambuf_ref<Allocator>(b), static_cast<CompletionCondition&&>(completion_condition))); #endif // !defined(BOOST_ASIO_NO_IOSTREAM) #endif // !defined(BOOST_ASIO_NO_EXTENSIONS) #endif // !defined(BOOST_ASIO_NO_DYNAMIC_BUFFER_V1) /// Start an asynchronous operation to read a certain amount of data from a /// stream. /** * This function is used to asynchronously read a certain number of bytes of * data from 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 The specified dynamic buffer sequence is full (that is, it has reached * maximum size). * * @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>. The * program must ensure that the stream performs no other read operations (such * as async_read, 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 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 boost::system::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 boost::asio::post(). * * @par Completion Signature * @code void(boost::system::error_code, std::size_t) @endcode * * @note This overload is equivalent to calling: * @code boost::asio::async_read( * s, buffers, * boost::asio::transfer_all(), * handler); @endcode * * @par Per-Operation Cancellation * This asynchronous operation supports cancellation for the following * boost::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, BOOST_ASIO_COMPLETION_TOKEN_FOR(void (boost::system::error_code, std::size_t)) ReadToken = default_completion_token_t< typename AsyncReadStream::executor_type>> auto async_read(AsyncReadStream& s, DynamicBuffer_v2 buffers, 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 (boost::system::error_code, std::size_t)>( declval<detail::initiate_async_read_dynbuf_v2<AsyncReadStream>>(), token, static_cast<DynamicBuffer_v2&&>(buffers), transfer_all())); /// Start an asynchronous operation to read a certain amount of data from a /// stream. /** * This function is used to asynchronously read a certain number of bytes of * data from 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 The specified dynamic buffer sequence is full (that is, it has reached * maximum size). * * @li The completion_condition function object returns 0. * * 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>. The * program must ensure that the stream performs no other read operations (such * as async_read, 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 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 operation. * const boost::system::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 stream's async_read_some 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 boost::system::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 boost::asio::post(). * * @par Completion Signature * @code void(boost::system::error_code, std::size_t) @endcode * * @par Per-Operation Cancellation * This asynchronous operation supports cancellation for the following * boost::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 CompletionCondition, BOOST_ASIO_COMPLETION_TOKEN_FOR(void (boost::system::error_code, std::size_t)) ReadToken = default_completion_token_t< typename AsyncReadStream::executor_type>> auto async_read(AsyncReadStream& s, DynamicBuffer_v2 buffers, CompletionCondition completion_condition, 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 (boost::system::error_code, std::size_t)>( declval<detail::initiate_async_read_dynbuf_v2<AsyncReadStream>>(), token, static_cast<DynamicBuffer_v2&&>(buffers), static_cast<CompletionCondition&&>(completion_condition))); /*@}*/ } // namespace asio } // namespace boost #include <boost/asio/detail/pop_options.hpp> #include <boost/asio/impl/read.hpp> #endif // BOOST_ASIO_READ_HPP
hpp
asio
data/projects/asio/include/boost/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 BOOST_ASIO_PACKAGED_TASK_HPP #define BOOST_ASIO_PACKAGED_TASK_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <boost/asio/detail/config.hpp> #include <boost/asio/detail/future.hpp> #if defined(BOOST_ASIO_HAS_STD_FUTURE_CLASS) \ || defined(GENERATING_DOCUMENTATION) #include <boost/asio/async_result.hpp> #include <boost/asio/detail/type_traits.hpp> #include <boost/asio/detail/push_options.hpp> namespace boost { 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 } // namespace boost #include <boost/asio/detail/pop_options.hpp> #endif // defined(BOOST_ASIO_HAS_STD_FUTURE_CLASS) // || defined(GENERATING_DOCUMENTATION) #endif // BOOST_ASIO_PACKAGED_TASK_HPP
hpp
asio
data/projects/asio/include/boost/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 BOOST_ASIO_ANY_IO_EXECUTOR_HPP #define BOOST_ASIO_ANY_IO_EXECUTOR_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <boost/asio/detail/config.hpp> #if defined(BOOST_ASIO_USE_TS_EXECUTOR_AS_DEFAULT) # include <boost/asio/executor.hpp> #else // defined(BOOST_ASIO_USE_TS_EXECUTOR_AS_DEFAULT) # include <boost/asio/execution.hpp> # include <boost/asio/execution_context.hpp> #endif // defined(BOOST_ASIO_USE_TS_EXECUTOR_AS_DEFAULT) #include <boost/asio/detail/push_options.hpp> namespace boost { namespace asio { #if defined(BOOST_ASIO_USE_TS_EXECUTOR_AS_DEFAULT) typedef executor any_io_executor; #else // defined(BOOST_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. BOOST_ASIO_DECL any_io_executor() noexcept; /// Construct in an empty state. Equivalent effects to default constructor. BOOST_ASIO_DECL any_io_executor(nullptr_t) noexcept; /// Copy constructor. BOOST_ASIO_DECL any_io_executor(const any_io_executor& e) noexcept; /// Move constructor. BOOST_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. BOOST_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. BOOST_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 <BOOST_ASIO_EXECUTION_EXECUTOR Executor> any_io_executor(Executor e); #else // defined(GENERATING_DOCUMENTATION) template <BOOST_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 <BOOST_ASIO_EXECUTION_EXECUTOR Executor> any_io_executor(std::nothrow_t, Executor e); #else // defined(GENERATING_DOCUMENTATION) template <BOOST_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. BOOST_ASIO_DECL any_io_executor& operator=( const any_io_executor& e) noexcept; /// Move assignment operator. BOOST_ASIO_DECL any_io_executor& operator=(any_io_executor&& e) noexcept; /// Assignment operator that sets the polymorphic wrapper to the empty state. BOOST_ASIO_DECL any_io_executor& operator=(nullptr_t); /// Destructor. BOOST_ASIO_DECL ~any_io_executor(); /// Swap targets with another polymorphic wrapper. BOOST_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 * boost::asio::require and boost::asio::prefer customisation points. * * For example: * @code any_io_executor ex = ...; * auto ex2 = boost::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 * boost::asio::prefer customisation point. * * For example: * @code any_io_executor ex = ...; * auto ex2 = boost::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 <> BOOST_ASIO_DECL any_io_executor any_io_executor::require( const execution::blocking_t::never_t&, int) const; template <> BOOST_ASIO_DECL any_io_executor any_io_executor::prefer( const execution::blocking_t::possibly_t&, int) const; template <> BOOST_ASIO_DECL any_io_executor any_io_executor::prefer( const execution::outstanding_work_t::tracked_t&, int) const; template <> BOOST_ASIO_DECL any_io_executor any_io_executor::prefer( const execution::outstanding_work_t::untracked_t&, int) const; template <> BOOST_ASIO_DECL any_io_executor any_io_executor::prefer( const execution::relationship_t::fork_t&, int) const; template <> BOOST_ASIO_DECL any_io_executor any_io_executor::prefer( const execution::relationship_t::continuation_t&, int) const; namespace traits { #if !defined(BOOST_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(BOOST_ASIO_HAS_DEDUCED_EQUALITY_COMPARABLE_TRAIT) #if !defined(BOOST_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(BOOST_ASIO_HAS_DEDUCED_EXECUTE_MEMBER_TRAIT) #if !defined(BOOST_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(BOOST_ASIO_HAS_DEDUCED_QUERY_MEMBER_TRAIT) #if !defined(BOOST_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(BOOST_ASIO_HAS_DEDUCED_REQUIRE_MEMBER_TRAIT) #if !defined(BOOST_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(BOOST_ASIO_HAS_DEDUCED_PREFER_MEMBER_TRAIT) } // namespace traits #endif // !defined(GENERATING_DOCUMENTATION) #endif // defined(BOOST_ASIO_USE_TS_EXECUTOR_AS_DEFAULT) } // namespace asio } // namespace boost #include <boost/asio/detail/pop_options.hpp> #if defined(BOOST_ASIO_HEADER_ONLY) \ && !defined(BOOST_ASIO_USE_TS_EXECUTOR_AS_DEFAULT) # include <boost/asio/impl/any_io_executor.ipp> #endif // defined(BOOST_ASIO_HEADER_ONLY) // && !defined(BOOST_ASIO_USE_TS_EXECUTOR_AS_DEFAULT) #endif // BOOST_ASIO_ANY_IO_EXECUTOR_HPP
hpp
asio
data/projects/asio/include/boost/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 BOOST_ASIO_BASIC_DATAGRAM_SOCKET_HPP #define BOOST_ASIO_BASIC_DATAGRAM_SOCKET_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <boost/asio/detail/config.hpp> #include <cstddef> #include <boost/asio/basic_socket.hpp> #include <boost/asio/detail/handler_type_requirements.hpp> #include <boost/asio/detail/non_const_lvalue.hpp> #include <boost/asio/detail/throw_error.hpp> #include <boost/asio/detail/type_traits.hpp> #include <boost/asio/error.hpp> #include <boost/asio/detail/push_options.hpp> namespace boost { namespace asio { #if !defined(BOOST_ASIO_BASIC_DATAGRAM_SOCKET_FWD_DECL) #define BOOST_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(BOOST_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 boost::system::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 boost::system::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 boost::system::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 boost::system::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 boost::system::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 boost::system::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 boost::system::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(boost::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) { boost::system::error_code ec; std::size_t s = this->impl_.get_service().send( this->impl_.get_implementation(), buffers, 0, ec); boost::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 boost::system::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) { boost::system::error_code ec; std::size_t s = this->impl_.get_service().send( this->impl_.get_implementation(), buffers, flags, ec); boost::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, boost::system::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 boost::system::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 boost::asio::post(). * * @par Completion Signature * @code void(boost::system::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(boost::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 boost::asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * @li @c cancellation_type::total */ template <typename ConstBufferSequence, BOOST_ASIO_COMPLETION_TOKEN_FOR(void (boost::system::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 (boost::system::error_code, std::size_t)>( declval<initiate_async_send>(), token, buffers, socket_base::message_flags(0))) { return async_initiate<WriteToken, void (boost::system::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 boost::system::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 boost::asio::post(). * * @par Completion Signature * @code void(boost::system::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 boost::asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * @li @c cancellation_type::total */ template <typename ConstBufferSequence, BOOST_ASIO_COMPLETION_TOKEN_FOR(void (boost::system::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 (boost::system::error_code, std::size_t)>( declval<initiate_async_send>(), token, buffers, flags)) { return async_initiate<WriteToken, void (boost::system::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 boost::system::system_error Thrown on failure. * * @par Example * To send a single data buffer use the @ref buffer function as follows: * @code * boost::asio::ip::udp::endpoint destination( * boost::asio::ip::address::from_string("1.2.3.4"), 12345); * socket.send_to(boost::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) { boost::system::error_code ec; std::size_t s = this->impl_.get_service().send_to( this->impl_.get_implementation(), buffers, destination, 0, ec); boost::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 boost::system::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) { boost::system::error_code ec; std::size_t s = this->impl_.get_service().send_to( this->impl_.get_implementation(), buffers, destination, flags, ec); boost::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, boost::system::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 boost::system::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 boost::asio::post(). * * @par Completion Signature * @code void(boost::system::error_code, std::size_t) @endcode * * @par Example * To send a single data buffer use the @ref buffer function as follows: * @code * boost::asio::ip::udp::endpoint destination( * boost::asio::ip::address::from_string("1.2.3.4"), 12345); * socket.async_send_to( * boost::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 boost::asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * @li @c cancellation_type::total */ template <typename ConstBufferSequence, BOOST_ASIO_COMPLETION_TOKEN_FOR(void (boost::system::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 (boost::system::error_code, std::size_t)>( declval<initiate_async_send_to>(), token, buffers, destination, socket_base::message_flags(0))) { return async_initiate<WriteToken, void (boost::system::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 boost::system::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 boost::asio::post(). * * @par Completion Signature * @code void(boost::system::error_code, std::size_t) @endcode * * @par Per-Operation Cancellation * On POSIX or Windows operating systems, this asynchronous operation supports * cancellation for the following boost::asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * @li @c cancellation_type::total */ template <typename ConstBufferSequence, BOOST_ASIO_COMPLETION_TOKEN_FOR(void (boost::system::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 (boost::system::error_code, std::size_t)>( declval<initiate_async_send_to>(), token, buffers, destination, flags)) { return async_initiate<WriteToken, void (boost::system::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 boost::system::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(boost::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) { boost::system::error_code ec; std::size_t s = this->impl_.get_service().receive( this->impl_.get_implementation(), buffers, 0, ec); boost::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 boost::system::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) { boost::system::error_code ec; std::size_t s = this->impl_.get_service().receive( this->impl_.get_implementation(), buffers, flags, ec); boost::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, boost::system::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 boost::system::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 boost::asio::post(). * * @par Completion Signature * @code void(boost::system::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(boost::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 boost::asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * @li @c cancellation_type::total */ template <typename MutableBufferSequence, BOOST_ASIO_COMPLETION_TOKEN_FOR(void (boost::system::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 (boost::system::error_code, std::size_t)>( declval<initiate_async_receive>(), token, buffers, socket_base::message_flags(0))) { return async_initiate<ReadToken, void (boost::system::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 boost::system::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 boost::asio::post(). * * @par Completion Signature * @code void(boost::system::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 boost::asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * @li @c cancellation_type::total */ template <typename MutableBufferSequence, BOOST_ASIO_COMPLETION_TOKEN_FOR(void (boost::system::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 (boost::system::error_code, std::size_t)>( declval<initiate_async_receive>(), token, buffers, flags)) { return async_initiate<ReadToken, void (boost::system::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 boost::system::system_error Thrown on failure. * * @par Example * To receive into a single data buffer use the @ref buffer function as * follows: * @code * boost::asio::ip::udp::endpoint sender_endpoint; * socket.receive_from( * boost::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) { boost::system::error_code ec; std::size_t s = this->impl_.get_service().receive_from( this->impl_.get_implementation(), buffers, sender_endpoint, 0, ec); boost::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 boost::system::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) { boost::system::error_code ec; std::size_t s = this->impl_.get_service().receive_from( this->impl_.get_implementation(), buffers, sender_endpoint, flags, ec); boost::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, boost::system::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 boost::system::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 boost::asio::post(). * * @par Completion Signature * @code void(boost::system::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( * boost::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 boost::asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * @li @c cancellation_type::total */ template <typename MutableBufferSequence, BOOST_ASIO_COMPLETION_TOKEN_FOR(void (boost::system::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 (boost::system::error_code, std::size_t)>( declval<initiate_async_receive_from>(), token, buffers, &sender_endpoint, socket_base::message_flags(0))) { return async_initiate<ReadToken, void (boost::system::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 boost::system::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 boost::asio::post(). * * @par Completion Signature * @code void(boost::system::error_code, std::size_t) @endcode * * @par Per-Operation Cancellation * On POSIX or Windows operating systems, this asynchronous operation supports * cancellation for the following boost::asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * @li @c cancellation_type::total */ template <typename MutableBufferSequence, BOOST_ASIO_COMPLETION_TOKEN_FOR(void (boost::system::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 (boost::system::error_code, std::size_t)>( declval<initiate_async_receive_from>(), token, buffers, &sender_endpoint, flags)) { return async_initiate<ReadToken, void (boost::system::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. BOOST_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. BOOST_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. BOOST_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. BOOST_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 } // namespace boost #include <boost/asio/detail/pop_options.hpp> #endif // BOOST_ASIO_BASIC_DATAGRAM_SOCKET_HPP
hpp
asio
data/projects/asio/include/boost/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 BOOST_ASIO_BASIC_STREAM_FILE_HPP #define BOOST_ASIO_BASIC_STREAM_FILE_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <boost/asio/detail/config.hpp> #if defined(BOOST_ASIO_HAS_FILE) \ || defined(GENERATING_DOCUMENTATION) #include <cstddef> #include <boost/asio/async_result.hpp> #include <boost/asio/basic_file.hpp> #include <boost/asio/detail/handler_type_requirements.hpp> #include <boost/asio/detail/non_const_lvalue.hpp> #include <boost/asio/detail/throw_error.hpp> #include <boost/asio/error.hpp> #include <boost/asio/detail/push_options.hpp> namespace boost { namespace asio { #if !defined(BOOST_ASIO_BASIC_STREAM_FILE_FWD_DECL) #define BOOST_ASIO_BASIC_STREAM_FILE_FWD_DECL // Forward declaration with defaulted arguments. template <typename Executor = any_io_executor> class basic_stream_file; #endif // !defined(BOOST_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 boost::system::system_error Thrown on failure. */ basic_stream_file(const executor_type& ex, const char* path, file_base::flags open_flags) : basic_file<Executor>(ex) { boost::system::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); boost::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 boost::system::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) { boost::system::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); boost::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 boost::system::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) { boost::system::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); boost::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 boost::system::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) { boost::system::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); boost::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 boost::system::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 boost::system::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 boost::system::system_error Thrown on failure. */ uint64_t seek(int64_t offset, file_base::seek_basis whence) { boost::system::error_code ec; uint64_t n = this->impl_.get_service().seek( this->impl_.get_implementation(), offset, whence, ec); boost::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, boost::system::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 boost::system::system_error Thrown on failure. An error code of * boost::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(boost::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) { boost::system::error_code ec; std::size_t s = this->impl_.get_service().write_some( this->impl_.get_implementation(), buffers, ec); boost::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, boost::system::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 boost::system::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 boost::asio::post(). * * @par Completion Signature * @code void(boost::system::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(boost::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 boost::asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * @li @c cancellation_type::total */ template <typename ConstBufferSequence, BOOST_ASIO_COMPLETION_TOKEN_FOR(void (boost::system::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 (boost::system::error_code, std::size_t)>( declval<initiate_async_write_some>(), token, buffers)) { return async_initiate<WriteToken, void (boost::system::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 boost::system::system_error Thrown on failure. An error code of * boost::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(boost::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) { boost::system::error_code ec; std::size_t s = this->impl_.get_service().read_some( this->impl_.get_implementation(), buffers, ec); boost::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, boost::system::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 boost::system::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 boost::asio::post(). * * @par Completion Signature * @code void(boost::system::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(boost::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 boost::asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * @li @c cancellation_type::total */ template <typename MutableBufferSequence, BOOST_ASIO_COMPLETION_TOKEN_FOR(void (boost::system::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 (boost::system::error_code, std::size_t)>( declval<initiate_async_read_some>(), token, buffers)) { return async_initiate<ReadToken, void (boost::system::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. BOOST_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. BOOST_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 } // namespace boost #include <boost/asio/detail/pop_options.hpp> #endif // defined(BOOST_ASIO_HAS_FILE) // || defined(GENERATING_DOCUMENTATION) #endif // BOOST_ASIO_BASIC_STREAM_FILE_HPP
hpp
asio
data/projects/asio/include/boost/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 BOOST_ASIO_SERIAL_PORT_BASE_HPP #define BOOST_ASIO_SERIAL_PORT_BASE_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <boost/asio/detail/config.hpp> #if defined(BOOST_ASIO_HAS_SERIAL_PORT) \ || defined(GENERATING_DOCUMENTATION) #if !defined(BOOST_ASIO_WINDOWS) && !defined(__CYGWIN__) # include <termios.h> #endif // !defined(BOOST_ASIO_WINDOWS) && !defined(__CYGWIN__) #include <boost/asio/detail/socket_types.hpp> #include <boost/system/error_code.hpp> #if defined(GENERATING_DOCUMENTATION) # define BOOST_ASIO_OPTION_STORAGE implementation_defined #elif defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__) # define BOOST_ASIO_OPTION_STORAGE DCB #else # define BOOST_ASIO_OPTION_STORAGE termios #endif #include <boost/asio/detail/push_options.hpp> namespace boost { 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; BOOST_ASIO_DECL BOOST_ASIO_SYNC_OP_VOID store( BOOST_ASIO_OPTION_STORAGE& storage, boost::system::error_code& ec) const; BOOST_ASIO_DECL BOOST_ASIO_SYNC_OP_VOID load( const BOOST_ASIO_OPTION_STORAGE& storage, boost::system::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 }; BOOST_ASIO_DECL explicit flow_control(type t = none); type value() const; BOOST_ASIO_DECL BOOST_ASIO_SYNC_OP_VOID store( BOOST_ASIO_OPTION_STORAGE& storage, boost::system::error_code& ec) const; BOOST_ASIO_DECL BOOST_ASIO_SYNC_OP_VOID load( const BOOST_ASIO_OPTION_STORAGE& storage, boost::system::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 }; BOOST_ASIO_DECL explicit parity(type t = none); type value() const; BOOST_ASIO_DECL BOOST_ASIO_SYNC_OP_VOID store( BOOST_ASIO_OPTION_STORAGE& storage, boost::system::error_code& ec) const; BOOST_ASIO_DECL BOOST_ASIO_SYNC_OP_VOID load( const BOOST_ASIO_OPTION_STORAGE& storage, boost::system::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 }; BOOST_ASIO_DECL explicit stop_bits(type t = one); type value() const; BOOST_ASIO_DECL BOOST_ASIO_SYNC_OP_VOID store( BOOST_ASIO_OPTION_STORAGE& storage, boost::system::error_code& ec) const; BOOST_ASIO_DECL BOOST_ASIO_SYNC_OP_VOID load( const BOOST_ASIO_OPTION_STORAGE& storage, boost::system::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: BOOST_ASIO_DECL explicit character_size(unsigned int t = 8); unsigned int value() const; BOOST_ASIO_DECL BOOST_ASIO_SYNC_OP_VOID store( BOOST_ASIO_OPTION_STORAGE& storage, boost::system::error_code& ec) const; BOOST_ASIO_DECL BOOST_ASIO_SYNC_OP_VOID load( const BOOST_ASIO_OPTION_STORAGE& storage, boost::system::error_code& ec); private: unsigned int value_; }; protected: /// Protected destructor to prevent deletion through this type. ~serial_port_base() { } }; } // namespace asio } // namespace boost #include <boost/asio/detail/pop_options.hpp> #undef BOOST_ASIO_OPTION_STORAGE #include <boost/asio/impl/serial_port_base.hpp> #if defined(BOOST_ASIO_HEADER_ONLY) # include <boost/asio/impl/serial_port_base.ipp> #endif // defined(BOOST_ASIO_HEADER_ONLY) #endif // defined(BOOST_ASIO_HAS_SERIAL_PORT) // || defined(GENERATING_DOCUMENTATION) #endif // BOOST_ASIO_SERIAL_PORT_BASE_HPP
hpp
asio
data/projects/asio/include/boost/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 BOOST_ASIO_READ_UNTIL_HPP #define BOOST_ASIO_READ_UNTIL_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <boost/asio/detail/config.hpp> #include <cstddef> #include <string> #include <boost/asio/async_result.hpp> #include <boost/asio/buffer.hpp> #include <boost/asio/detail/regex_fwd.hpp> #include <boost/asio/detail/string_view.hpp> #include <boost/asio/detail/type_traits.hpp> #include <boost/asio/error.hpp> #if !defined(BOOST_ASIO_NO_EXTENSIONS) # include <boost/asio/basic_streambuf_fwd.hpp> #endif // !defined(BOOST_ASIO_NO_EXTENSIONS) #include <boost/asio/detail/push_options.hpp> namespace boost { 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(BOOST_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(BOOST_ASIO_HAS_BOOST_REGEX) template <typename> class initiate_async_read_until_expr_v1; #endif // defined(BOOST_ASIO_HAS_BOOST_REGEX) template <typename> class initiate_async_read_until_match_v1; #endif // !defined(BOOST_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(BOOST_ASIO_HAS_BOOST_REGEX) template <typename> class initiate_async_read_until_expr_v2; #endif // defined(BOOST_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 = boost::asio::is_function<remove_pointer_t<T>>::value || detail::has_result_type<T>::value }; #endif }; /** * @defgroup read_until boost::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(BOOST_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 boost::system::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 = boost::asio::read_until(s, * boost::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, boost::system::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 = boost::asio::read_until(s, * boost::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, BOOST_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, BOOST_ASIO_STRING_VIEW_PARAM delim, boost::system::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(BOOST_ASIO_NO_EXTENSIONS) #if defined(BOOST_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 boost::system::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 = boost::asio::read_until(s, * boost::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, boost::system::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(BOOST_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 boost::system::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 boost::asio::buffers_iterator< * boost::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; * boost::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; * boost::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, boost::system::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(BOOST_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 boost::system::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 boost::asio::streambuf b; * boost::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, boost::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, boost::asio::basic_streambuf<Allocator>& b, char delim, boost::system::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 boost::system::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 boost::asio::streambuf b; * boost::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, boost::asio::basic_streambuf<Allocator>& b, BOOST_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, boost::asio::basic_streambuf<Allocator>& b, BOOST_ASIO_STRING_VIEW_PARAM delim, boost::system::error_code& ec); #if defined(BOOST_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 boost::system::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 boost::asio::streambuf b; * boost::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, boost::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, boost::asio::basic_streambuf<Allocator>& b, const boost::basic_regex<char, Traits>& expr, boost::system::error_code& ec); #endif // defined(BOOST_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 boost::system::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 boost::asio::buffers_iterator< * boost::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); * } * ... * boost::asio::streambuf b; * boost::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 * ... * boost::asio::streambuf b; * boost::asio::read_until(s, b, match_char('a')); * @endcode */ template <typename SyncReadStream, typename Allocator, typename MatchCondition> std::size_t read_until(SyncReadStream& s, boost::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, boost::asio::basic_streambuf<Allocator>& b, MatchCondition match_condition, boost::system::error_code& ec, constraint_t<is_match_condition<MatchCondition>::value> = 0); #endif // !defined(BOOST_ASIO_NO_IOSTREAM) #endif // !defined(BOOST_ASIO_NO_EXTENSIONS) #endif // !defined(BOOST_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 boost::system::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 = boost::asio::read_until(s, * boost::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, boost::system::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 = boost::asio::read_until(s, * boost::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, BOOST_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, BOOST_ASIO_STRING_VIEW_PARAM delim, boost::system::error_code& ec, constraint_t< is_dynamic_buffer_v2<DynamicBuffer_v2>::value > = 0); #if !defined(BOOST_ASIO_NO_EXTENSIONS) #if defined(BOOST_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 boost::system::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 = boost::asio::read_until(s, * boost::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, boost::system::error_code& ec, constraint_t< is_dynamic_buffer_v2<DynamicBuffer_v2>::value > = 0); #endif // defined(BOOST_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 boost::system::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 boost::asio::buffers_iterator< * boost::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; * boost::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; * boost::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, boost::system::error_code& ec, constraint_t< is_match_condition<MatchCondition>::value > = 0, constraint_t< is_dynamic_buffer_v2<DynamicBuffer_v2>::value > = 0); #endif // !defined(BOOST_ASIO_NO_EXTENSIONS) /*@}*/ /** * @defgroup async_read_until boost::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(BOOST_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 boost::system::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 boost::asio::post(). * * @par Completion Signature * @code void(boost::system::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 boost::system::error_code& e, std::size_t size) * { * if (!e) * { * std::string line = data.substr(0, n); * data.erase(0, n); * ... * } * } * ... * boost::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 * boost::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, BOOST_ASIO_COMPLETION_TOKEN_FOR(void (boost::system::error_code, std::size_t)) ReadToken = default_completion_token_t< typename AsyncReadStream::executor_type>> 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 (boost::system::error_code, std::size_t)>( declval<detail::initiate_async_read_until_delim_v1<AsyncReadStream>>(), 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 boost::system::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 boost::asio::post(). * * @par Completion Signature * @code void(boost::system::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 boost::system::error_code& e, std::size_t size) * { * if (!e) * { * std::string line = data.substr(0, n); * data.erase(0, n); * ... * } * } * ... * boost::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 * boost::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, BOOST_ASIO_COMPLETION_TOKEN_FOR(void (boost::system::error_code, std::size_t)) ReadToken = default_completion_token_t< typename AsyncReadStream::executor_type>> auto async_read_until(AsyncReadStream& s, DynamicBuffer_v1&& buffers, BOOST_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 (boost::system::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))); #if !defined(BOOST_ASIO_NO_EXTENSIONS) #if defined(BOOST_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 boost::system::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 boost::asio::post(). * * @par Completion Signature * @code void(boost::system::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 boost::system::error_code& e, std::size_t size) * { * if (!e) * { * std::string line = data.substr(0, n); * data.erase(0, n); * ... * } * } * ... * boost::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 * boost::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, BOOST_ASIO_COMPLETION_TOKEN_FOR(void (boost::system::error_code, std::size_t)) ReadToken = default_completion_token_t< typename AsyncReadStream::executor_type>> 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 (boost::system::error_code, std::size_t)>( declval<detail::initiate_async_read_until_expr_v1<AsyncReadStream>>(), token, static_cast<DynamicBuffer_v1&&>(buffers), expr)); #endif // defined(BOOST_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 boost::system::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 boost::asio::post(). * * @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(boost::system::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 boost::asio::buffers_iterator< * boost::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 boost::system::error_code& e, std::size_t size); * ... * std::string data; * boost::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 boost::system::error_code& e, std::size_t size); * ... * std::string data; * boost::asio::async_read_until(s, data, match_char('a'), handler); * @endcode * * @par Per-Operation Cancellation * This asynchronous operation supports cancellation for the following * boost::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, BOOST_ASIO_COMPLETION_TOKEN_FOR(void (boost::system::error_code, std::size_t)) ReadToken = default_completion_token_t< typename AsyncReadStream::executor_type>> 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 (boost::system::error_code, std::size_t)>( declval<detail::initiate_async_read_until_match_v1<AsyncReadStream>>(), token, static_cast<DynamicBuffer_v1&&>(buffers), match_condition)); #if !defined(BOOST_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 boost::system::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 boost::asio::post(). * * @par Completion Signature * @code void(boost::system::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 boost::asio::streambuf b; * ... * void handler(const boost::system::error_code& e, std::size_t size) * { * if (!e) * { * std::istream is(&b); * std::string line; * std::getline(is, line); * ... * } * } * ... * boost::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 * boost::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, BOOST_ASIO_COMPLETION_TOKEN_FOR(void (boost::system::error_code, std::size_t)) ReadToken = default_completion_token_t< typename AsyncReadStream::executor_type>> auto async_read_until(AsyncReadStream& s, boost::asio::basic_streambuf<Allocator>& b, char delim, ReadToken&& token = default_completion_token_t< typename AsyncReadStream::executor_type>()) -> decltype( async_initiate<ReadToken, void (boost::system::error_code, std::size_t)>( declval<detail::initiate_async_read_until_delim_v1<AsyncReadStream>>(), 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 boost::system::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 boost::asio::post(). * * @par Completion Signature * @code void(boost::system::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 boost::asio::streambuf b; * ... * void handler(const boost::system::error_code& e, std::size_t size) * { * if (!e) * { * std::istream is(&b); * std::string line; * std::getline(is, line); * ... * } * } * ... * boost::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 * boost::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, BOOST_ASIO_COMPLETION_TOKEN_FOR(void (boost::system::error_code, std::size_t)) ReadToken = default_completion_token_t< typename AsyncReadStream::executor_type>> auto async_read_until(AsyncReadStream& s, boost::asio::basic_streambuf<Allocator>& b, BOOST_ASIO_STRING_VIEW_PARAM delim, ReadToken&& token = default_completion_token_t< typename AsyncReadStream::executor_type>()) -> decltype( async_initiate<ReadToken, void (boost::system::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))); #if defined(BOOST_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 boost::system::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 boost::asio::post(). * * @par Completion Signature * @code void(boost::system::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 boost::asio::streambuf b; * ... * void handler(const boost::system::error_code& e, std::size_t size) * { * if (!e) * { * std::istream is(&b); * std::string line; * std::getline(is, line); * ... * } * } * ... * boost::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 * boost::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, BOOST_ASIO_COMPLETION_TOKEN_FOR(void (boost::system::error_code, std::size_t)) ReadToken = default_completion_token_t< typename AsyncReadStream::executor_type>> auto async_read_until(AsyncReadStream& s, boost::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 (boost::system::error_code, std::size_t)>( declval<detail::initiate_async_read_until_expr_v1<AsyncReadStream>>(), token, basic_streambuf_ref<Allocator>(b), expr)); #endif // defined(BOOST_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 boost::system::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 boost::asio::post(). * * @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(boost::system::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 boost::asio::buffers_iterator< * boost::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 boost::system::error_code& e, std::size_t size); * ... * boost::asio::streambuf b; * boost::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 boost::system::error_code& e, std::size_t size); * ... * boost::asio::streambuf b; * boost::asio::async_read_until(s, b, match_char('a'), handler); * @endcode * * @par Per-Operation Cancellation * This asynchronous operation supports cancellation for the following * boost::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, BOOST_ASIO_COMPLETION_TOKEN_FOR(void (boost::system::error_code, std::size_t)) ReadToken = default_completion_token_t< typename AsyncReadStream::executor_type>> auto async_read_until(AsyncReadStream& s, boost::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 (boost::system::error_code, std::size_t)>( declval<detail::initiate_async_read_until_match_v1<AsyncReadStream>>(), token, basic_streambuf_ref<Allocator>(b), match_condition)); #endif // !defined(BOOST_ASIO_NO_IOSTREAM) #endif // !defined(BOOST_ASIO_NO_EXTENSIONS) #endif // !defined(BOOST_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 boost::system::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 boost::asio::post(). * * @par Completion Signature * @code void(boost::system::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 boost::system::error_code& e, std::size_t size) * { * if (!e) * { * std::string line = data.substr(0, n); * data.erase(0, n); * ... * } * } * ... * boost::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 * boost::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, BOOST_ASIO_COMPLETION_TOKEN_FOR(void (boost::system::error_code, std::size_t)) ReadToken = default_completion_token_t< typename AsyncReadStream::executor_type>> 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 (boost::system::error_code, std::size_t)>( declval<detail::initiate_async_read_until_delim_v2<AsyncReadStream>>(), 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 boost::system::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 boost::asio::post(). * * @par Completion Signature * @code void(boost::system::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 boost::system::error_code& e, std::size_t size) * { * if (!e) * { * std::string line = data.substr(0, n); * data.erase(0, n); * ... * } * } * ... * boost::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 * boost::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, BOOST_ASIO_COMPLETION_TOKEN_FOR(void (boost::system::error_code, std::size_t)) ReadToken = default_completion_token_t< typename AsyncReadStream::executor_type>> auto async_read_until(AsyncReadStream& s, DynamicBuffer_v2 buffers, BOOST_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 (boost::system::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))); #if !defined(BOOST_ASIO_NO_EXTENSIONS) #if defined(BOOST_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 boost::system::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 boost::asio::post(). * * @par Completion Signature * @code void(boost::system::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 boost::system::error_code& e, std::size_t size) * { * if (!e) * { * std::string line = data.substr(0, n); * data.erase(0, n); * ... * } * } * ... * boost::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 * boost::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, BOOST_ASIO_COMPLETION_TOKEN_FOR(void (boost::system::error_code, std::size_t)) ReadToken = default_completion_token_t< typename AsyncReadStream::executor_type>> 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 (boost::system::error_code, std::size_t)>( declval<detail::initiate_async_read_until_expr_v2<AsyncReadStream>>(), token, static_cast<DynamicBuffer_v2&&>(buffers), expr)); #endif // defined(BOOST_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 boost::system::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 boost::asio::post(). * * @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(boost::system::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 boost::asio::buffers_iterator< * boost::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 boost::system::error_code& e, std::size_t size); * ... * std::string data; * boost::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 boost::system::error_code& e, std::size_t size); * ... * std::string data; * boost::asio::async_read_until(s, data, match_char('a'), handler); * @endcode * * @par Per-Operation Cancellation * This asynchronous operation supports cancellation for the following * boost::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, BOOST_ASIO_COMPLETION_TOKEN_FOR(void (boost::system::error_code, std::size_t)) ReadToken = default_completion_token_t< typename AsyncReadStream::executor_type>> 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 (boost::system::error_code, std::size_t)>( declval<detail::initiate_async_read_until_match_v2<AsyncReadStream>>(), token, static_cast<DynamicBuffer_v2&&>(buffers), match_condition)); #endif // !defined(BOOST_ASIO_NO_EXTENSIONS) /*@}*/ } // namespace asio } // namespace boost #include <boost/asio/detail/pop_options.hpp> #include <boost/asio/impl/read_until.hpp> #endif // BOOST_ASIO_READ_UNTIL_HPP
hpp
asio
data/projects/asio/include/boost/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 BOOST_ASIO_REQUIRE_HPP #define BOOST_ASIO_REQUIRE_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <boost/asio/detail/config.hpp> #include <boost/asio/detail/type_traits.hpp> #include <boost/asio/is_applicable_property.hpp> #include <boost/asio/traits/require_member.hpp> #include <boost/asio/traits/require_free.hpp> #include <boost/asio/traits/static_require.hpp> #include <boost/asio/detail/push_options.hpp> #if defined(GENERATING_DOCUMENTATION) namespace boost { 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>boost::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>boost::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>boost::asio::require(boost::asio::require(E, P0), Pn...)</tt> * if <tt>N > 0</tt> and the expression * <tt>boost::asio::require(boost::asio::require(E, P0), Pn...)</tt> * is a valid expression. * * @li Otherwise, <tt>boost::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>boost::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>boost::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>boost::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 } // namespace boost #else // defined(GENERATING_DOCUMENTATION) namespace boost_asio_require_fn { using boost::asio::conditional_t; using boost::asio::decay_t; using boost::asio::declval; using boost::asio::enable_if_t; using boost::asio::is_applicable_property; using boost::asio::traits::require_free; using boost::asio::traits::require_member; using boost::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(BOOST_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(BOOST_ASIO_HAS_DEDUCED_REQUIRE_MEMBER_TRAIT) typedef T type; #endif // defined(BOOST_ASIO_HAS_DEDUCED_REQUIRE_MEMBER_TRAIT) }; template <typename T, typename Property> BOOST_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> BOOST_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> BOOST_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> BOOST_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> BOOST_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 boost_asio_require_fn namespace boost { namespace asio { namespace { static constexpr const boost_asio_require_fn::impl& require = boost_asio_require_fn::static_instance<>::instance; } // namespace typedef boost_asio_require_fn::impl require_t; template <typename T, typename... Properties> struct can_require : integral_constant<bool, boost_asio_require_fn::call_traits< require_t, T, void(Properties...)>::overload != boost_asio_require_fn::ill_formed> { }; #if defined(BOOST_ASIO_HAS_VARIABLE_TEMPLATES) template <typename T, typename... Properties> constexpr bool can_require_v = can_require<T, Properties...>::value; #endif // defined(BOOST_ASIO_HAS_VARIABLE_TEMPLATES) template <typename T, typename... Properties> struct is_nothrow_require : integral_constant<bool, boost_asio_require_fn::call_traits< require_t, T, void(Properties...)>::is_noexcept> { }; #if defined(BOOST_ASIO_HAS_VARIABLE_TEMPLATES) template <typename T, typename... Properties> constexpr bool is_nothrow_require_v = is_nothrow_require<T, Properties...>::value; #endif // defined(BOOST_ASIO_HAS_VARIABLE_TEMPLATES) template <typename T, typename... Properties> struct require_result { typedef typename boost_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 } // namespace boost #endif // defined(GENERATING_DOCUMENTATION) #include <boost/asio/detail/pop_options.hpp> #endif // BOOST_ASIO_REQUIRE_HPP
hpp
asio
data/projects/asio/include/boost/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 BOOST_ASIO_DEFERRED_HPP #define BOOST_ASIO_DEFERRED_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <boost/asio/detail/config.hpp> #include <tuple> #include <boost/asio/associator.hpp> #include <boost/asio/async_result.hpp> #include <boost/asio/detail/type_traits.hpp> #include <boost/asio/detail/utility.hpp> #include <boost/asio/detail/push_options.hpp> namespace boost { 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 <BOOST_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 <BOOST_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 BOOST_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 <BOOST_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 <BOOST_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 BOOST_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>( initiation_t(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 <BOOST_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 <BOOST_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 BOOST_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 <BOOST_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 <BOOST_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 BOOST_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 BOOST_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 using the special value @c boost::asio::deferred. For * example: * * @code auto my_deferred_op * = my_socket.async_read_some(my_buffer, * boost::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 boost::asio::deferred_t for a usage example. */ constexpr deferred_t deferred; } // namespace asio } // namespace boost #include <boost/asio/detail/pop_options.hpp> #include <boost/asio/impl/deferred.hpp> #endif // BOOST_ASIO_DEFERRED_HPP
hpp
asio
data/projects/asio/include/boost/asio/strand.hpp
// // 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 BOOST_ASIO_STRAND_HPP #define BOOST_ASIO_STRAND_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <boost/asio/detail/config.hpp> #include <boost/asio/detail/strand_executor_service.hpp> #include <boost/asio/detail/type_traits.hpp> #include <boost/asio/execution/blocking.hpp> #include <boost/asio/execution/executor.hpp> #include <boost/asio/is_executor.hpp> #include <boost/asio/detail/push_options.hpp> namespace boost { namespace asio { /// Provides serialised function invocation for any executor type. template <typename Executor> class strand { public: /// The type of the underlying executor. typedef Executor inner_executor_type; /// Default constructor. /** * This constructor is only valid if the underlying executor type is default * constructible. */ strand() : executor_(), impl_(strand::create_implementation(executor_)) { } /// Construct a strand for the specified executor. template <typename Executor1> explicit strand(const Executor1& e, constraint_t< conditional_t< !is_same<Executor1, strand>::value, is_convertible<Executor1, Executor>, false_type >::value > = 0) : executor_(e), impl_(strand::create_implementation(executor_)) { } /// Copy constructor. strand(const strand& other) noexcept : executor_(other.executor_), impl_(other.impl_) { } /// Converting constructor. /** * This constructor is only valid if the @c OtherExecutor type is convertible * to @c Executor. */ template <class OtherExecutor> strand( const strand<OtherExecutor>& other) noexcept : executor_(other.executor_), impl_(other.impl_) { } /// Assignment operator. strand& operator=(const strand& other) noexcept { executor_ = other.executor_; impl_ = other.impl_; return *this; } /// Converting assignment operator. /** * This assignment operator is only valid if the @c OtherExecutor type is * convertible to @c Executor. */ template <class OtherExecutor> strand& operator=( const strand<OtherExecutor>& other) noexcept { executor_ = other.executor_; impl_ = other.impl_; return *this; } /// Move constructor. strand(strand&& other) noexcept : executor_(static_cast<Executor&&>(other.executor_)), impl_(static_cast<implementation_type&&>(other.impl_)) { } /// Converting move constructor. /** * This constructor is only valid if the @c OtherExecutor type is convertible * to @c Executor. */ template <class OtherExecutor> strand(strand<OtherExecutor>&& other) noexcept : executor_(static_cast<OtherExecutor&&>(other.executor_)), impl_(static_cast<implementation_type&&>(other.impl_)) { } /// Move assignment operator. strand& operator=(strand&& other) noexcept { executor_ = static_cast<Executor&&>(other.executor_); impl_ = static_cast<implementation_type&&>(other.impl_); return *this; } /// Converting move assignment operator. /** * This assignment operator is only valid if the @c OtherExecutor type is * convertible to @c Executor. */ template <class OtherExecutor> strand& operator=(strand<OtherExecutor>&& other) noexcept { executor_ = static_cast<OtherExecutor&&>(other.executor_); impl_ = static_cast<implementation_type&&>(other.impl_); return *this; } /// Destructor. ~strand() noexcept { } /// Obtain the underlying executor. inner_executor_type get_inner_executor() const noexcept { return executor_; } /// Forward a query to the underlying executor. /** * Do not call this function directly. It is intended for use with the * boost::asio::query customisation point. * * For example: * @code boost::asio::strand<my_executor_type> ex = ...; * if (boost::asio::query(ex, boost::asio::execution::blocking) * == boost::asio::execution::blocking.never) * ... @endcode */ template <typename Property> constraint_t< can_query<const Executor&, Property>::value, conditional_t< is_convertible<Property, execution::blocking_t>::value, execution::blocking_t, query_result_t<const Executor&, Property> > > query(const Property& p) const noexcept(is_nothrow_query<const Executor&, Property>::value) { return this->query_helper( is_convertible<Property, execution::blocking_t>(), p); } /// Forward a requirement to the underlying executor. /** * Do not call this function directly. It is intended for use with the * boost::asio::require customisation point. * * For example: * @code boost::asio::strand<my_executor_type> ex1 = ...; * auto ex2 = boost::asio::require(ex1, * boost::asio::execution::blocking.never); @endcode */ template <typename Property> constraint_t< can_require<const Executor&, Property>::value && !is_convertible<Property, execution::blocking_t::always_t>::value, strand<decay_t<require_result_t<const Executor&, Property>>> > require(const Property& p) const noexcept(is_nothrow_require<const Executor&, Property>::value) { return strand<decay_t<require_result_t<const Executor&, Property>>>( boost::asio::require(executor_, p), impl_); } /// Forward a preference to the underlying executor. /** * Do not call this function directly. It is intended for use with the * boost::asio::prefer customisation point. * * For example: * @code boost::asio::strand<my_executor_type> ex1 = ...; * auto ex2 = boost::asio::prefer(ex1, * boost::asio::execution::blocking.never); @endcode */ template <typename Property> constraint_t< can_prefer<const Executor&, Property>::value && !is_convertible<Property, execution::blocking_t::always_t>::value, strand<decay_t<prefer_result_t<const Executor&, Property>>> > prefer(const Property& p) const noexcept(is_nothrow_prefer<const Executor&, Property>::value) { return strand<decay_t<prefer_result_t<const Executor&, Property>>>( boost::asio::prefer(executor_, p), impl_); } #if !defined(BOOST_ASIO_NO_TS_EXECUTORS) /// Obtain the underlying execution context. execution_context& context() const noexcept { return executor_.context(); } /// Inform the strand that it has some outstanding work to do. /** * The strand delegates this call to its underlying executor. */ void on_work_started() const noexcept { executor_.on_work_started(); } /// Inform the strand that some work is no longer outstanding. /** * The strand delegates this call to its underlying executor. */ void on_work_finished() const noexcept { executor_.on_work_finished(); } #endif // !defined(BOOST_ASIO_NO_TS_EXECUTORS) /// Request the strand to invoke the given function object. /** * This function is used to ask the strand to execute the given function * object on its underlying executor. The function object will be executed * according to the properties of the underlying executor. * * @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 */ template <typename Function> constraint_t< traits::execute_member<const Executor&, Function>::is_valid, void > execute(Function&& f) const { detail::strand_executor_service::execute(impl_, executor_, static_cast<Function&&>(f)); } #if !defined(BOOST_ASIO_NO_TS_EXECUTORS) /// Request the strand to invoke the given function object. /** * This function is used to ask the strand to execute the given function * object on its underlying executor. The function object will be executed * inside this function if the strand is not otherwise busy and if the * underlying executor's @c dispatch() function is also able to execute the * function before returning. * * @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 Allocator> void dispatch(Function&& f, const Allocator& a) const { detail::strand_executor_service::dispatch(impl_, executor_, static_cast<Function&&>(f), a); } /// Request the strand 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 by the underlying executor's defer 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 Allocator> void post(Function&& f, const Allocator& a) const { detail::strand_executor_service::post(impl_, executor_, static_cast<Function&&>(f), a); } /// Request the strand 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 by the underlying executor's defer 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 Allocator> void defer(Function&& f, const Allocator& a) const { detail::strand_executor_service::defer(impl_, executor_, static_cast<Function&&>(f), a); } #endif // !defined(BOOST_ASIO_NO_TS_EXECUTORS) /// Determine whether the strand is running in the current thread. /** * @return @c true if the current thread is executing a function that was * submitted to the strand using post(), dispatch() or defer(). Otherwise * returns @c false. */ bool running_in_this_thread() const noexcept { return detail::strand_executor_service::running_in_this_thread(impl_); } /// Compare two strands for equality. /** * Two strands are equal if they refer to the same ordered, non-concurrent * state. */ friend bool operator==(const strand& a, const strand& b) noexcept { return a.impl_ == b.impl_; } /// Compare two strands for inequality. /** * Two strands are equal if they refer to the same ordered, non-concurrent * state. */ friend bool operator!=(const strand& a, const strand& b) noexcept { return a.impl_ != b.impl_; } #if defined(GENERATING_DOCUMENTATION) private: #endif // defined(GENERATING_DOCUMENTATION) typedef detail::strand_executor_service::implementation_type implementation_type; template <typename InnerExecutor> static implementation_type create_implementation(const InnerExecutor& ex, constraint_t< can_query<InnerExecutor, execution::context_t>::value > = 0) { return use_service<detail::strand_executor_service>( boost::asio::query(ex, execution::context)).create_implementation(); } template <typename InnerExecutor> static implementation_type create_implementation(const InnerExecutor& ex, constraint_t< !can_query<InnerExecutor, execution::context_t>::value > = 0) { return use_service<detail::strand_executor_service>( ex.context()).create_implementation(); } strand(const Executor& ex, const implementation_type& impl) : executor_(ex), impl_(impl) { } template <typename Property> query_result_t<const Executor&, Property> query_helper( false_type, const Property& property) const { return boost::asio::query(executor_, property); } template <typename Property> execution::blocking_t query_helper(true_type, const Property& property) const { execution::blocking_t result = boost::asio::query(executor_, property); return result == execution::blocking.always ? execution::blocking.possibly : result; } Executor executor_; implementation_type impl_; }; /** @defgroup make_strand boost::asio::make_strand * * @brief The boost::asio::make_strand function creates a @ref strand object for * an executor or execution context. */ /*@{*/ /// Create a @ref strand object for an executor. /** * @param ex An executor. * * @returns A strand constructed with the specified executor. */ template <typename Executor> inline strand<Executor> make_strand(const Executor& ex, constraint_t< is_executor<Executor>::value || execution::is_executor<Executor>::value > = 0) { return strand<Executor>(ex); } /// Create a @ref strand object for an execution context. /** * @param ctx An execution context, from which an executor will be obtained. * * @returns A strand constructed with the execution context's executor, obtained * by performing <tt>ctx.get_executor()</tt>. */ template <typename ExecutionContext> inline strand<typename ExecutionContext::executor_type> make_strand(ExecutionContext& ctx, constraint_t< is_convertible<ExecutionContext&, execution_context&>::value > = 0) { return strand<typename ExecutionContext::executor_type>(ctx.get_executor()); } /*@}*/ #if !defined(GENERATING_DOCUMENTATION) namespace traits { #if !defined(BOOST_ASIO_HAS_DEDUCED_EQUALITY_COMPARABLE_TRAIT) template <typename Executor> struct equality_comparable<strand<Executor>> { static constexpr bool is_valid = true; static constexpr bool is_noexcept = true; }; #endif // !defined(BOOST_ASIO_HAS_DEDUCED_EQUALITY_COMPARABLE_TRAIT) #if !defined(BOOST_ASIO_HAS_DEDUCED_EXECUTE_MEMBER_TRAIT) template <typename Executor, typename Function> struct execute_member<strand<Executor>, Function, enable_if_t< traits::execute_member<const Executor&, Function>::is_valid >> { static constexpr bool is_valid = true; static constexpr bool is_noexcept = false; typedef void result_type; }; #endif // !defined(BOOST_ASIO_HAS_DEDUCED_EXECUTE_MEMBER_TRAIT) #if !defined(BOOST_ASIO_HAS_DEDUCED_QUERY_MEMBER_TRAIT) template <typename Executor, typename Property> struct query_member<strand<Executor>, Property, enable_if_t< can_query<const Executor&, Property>::value >> { static constexpr bool is_valid = true; static constexpr bool is_noexcept = is_nothrow_query<Executor, Property>::value; typedef conditional_t< is_convertible<Property, execution::blocking_t>::value, execution::blocking_t, query_result_t<Executor, Property>> result_type; }; #endif // !defined(BOOST_ASIO_HAS_DEDUCED_QUERY_MEMBER_TRAIT) #if !defined(BOOST_ASIO_HAS_DEDUCED_REQUIRE_MEMBER_TRAIT) template <typename Executor, typename Property> struct require_member<strand<Executor>, Property, enable_if_t< can_require<const Executor&, Property>::value && !is_convertible<Property, execution::blocking_t::always_t>::value >> { static constexpr bool is_valid = true; static constexpr bool is_noexcept = is_nothrow_require<Executor, Property>::value; typedef strand<decay_t<require_result_t<Executor, Property>>> result_type; }; #endif // !defined(BOOST_ASIO_HAS_DEDUCED_REQUIRE_MEMBER_TRAIT) #if !defined(BOOST_ASIO_HAS_DEDUCED_PREFER_MEMBER_TRAIT) template <typename Executor, typename Property> struct prefer_member<strand<Executor>, Property, enable_if_t< can_prefer<const Executor&, Property>::value && !is_convertible<Property, execution::blocking_t::always_t>::value >> { static constexpr bool is_valid = true; static constexpr bool is_noexcept = is_nothrow_prefer<Executor, Property>::value; typedef strand<decay_t<prefer_result_t<Executor, Property>>> result_type; }; #endif // !defined(BOOST_ASIO_HAS_DEDUCED_PREFER_MEMBER_TRAIT) } // namespace traits #endif // !defined(GENERATING_DOCUMENTATION) } // namespace asio } // namespace boost #include <boost/asio/detail/pop_options.hpp> // 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(BOOST_ASIO_NO_EXTENSIONS) # if defined(BOOST_ASIO_IO_CONTEXT_HPP) # include <boost/asio/io_context_strand.hpp> # endif // defined(BOOST_ASIO_IO_CONTEXT_HPP) #endif // !defined(BOOST_ASIO_NO_EXTENSIONS) #endif // BOOST_ASIO_STRAND_HPP
hpp
asio
data/projects/asio/include/boost/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 BOOST_ASIO_ASSOCIATED_EXECUTOR_HPP #define BOOST_ASIO_ASSOCIATED_EXECUTOR_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <boost/asio/detail/config.hpp> #include <boost/asio/associator.hpp> #include <boost/asio/detail/functional.hpp> #include <boost/asio/detail/type_traits.hpp> #include <boost/asio/execution/executor.hpp> #include <boost/asio/is_executor.hpp> #include <boost/asio/system_executor.hpp> #include <boost/asio/detail/push_options.hpp> namespace boost { 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> BOOST_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> BOOST_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> BOOST_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 } // namespace boost #include <boost/asio/detail/pop_options.hpp> #endif // BOOST_ASIO_ASSOCIATED_EXECUTOR_HPP
hpp
asio
data/projects/asio/include/boost/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 BOOST_ASIO_IS_READ_BUFFERED_HPP #define BOOST_ASIO_IS_READ_BUFFERED_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <boost/asio/detail/config.hpp> #include <boost/asio/buffered_read_stream_fwd.hpp> #include <boost/asio/buffered_stream_fwd.hpp> #include <boost/asio/detail/push_options.hpp> namespace boost { 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 BOOST_ASIO_STATIC_CONSTANT(bool, value = sizeof(detail::is_read_buffered_helper((Stream*)0)) == 1); #endif }; } // namespace asio } // namespace boost #include <boost/asio/detail/pop_options.hpp> #endif // BOOST_ASIO_IS_READ_BUFFERED_HPP
hpp
asio
data/projects/asio/include/boost/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 BOOST_ASIO_DISPATCH_HPP #define BOOST_ASIO_DISPATCH_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <boost/asio/detail/config.hpp> #include <boost/asio/async_result.hpp> #include <boost/asio/detail/initiate_dispatch.hpp> #include <boost/asio/detail/type_traits.hpp> #include <boost/asio/execution_context.hpp> #include <boost/asio/execution/executor.hpp> #include <boost/asio/is_executor.hpp> #include <boost/asio/detail/push_options.hpp> namespace boost { 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 <BOOST_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, BOOST_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, BOOST_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 } // namespace boost #include <boost/asio/detail/pop_options.hpp> #endif // BOOST_ASIO_DISPATCH_HPP
hpp
asio
data/projects/asio/include/boost/asio/buffers_iterator.hpp
// // buffers_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 BOOST_ASIO_BUFFERS_ITERATOR_HPP #define BOOST_ASIO_BUFFERS_ITERATOR_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <boost/asio/detail/config.hpp> #include <cstddef> #include <iterator> #include <boost/asio/buffer.hpp> #include <boost/asio/detail/assert.hpp> #include <boost/asio/detail/type_traits.hpp> #include <boost/asio/detail/push_options.hpp> namespace boost { namespace asio { namespace detail { template <bool IsMutable> struct buffers_iterator_types_helper; template <> struct buffers_iterator_types_helper<false> { typedef const_buffer buffer_type; template <typename ByteType> struct byte_type { typedef add_const_t<ByteType> type; }; }; template <> struct buffers_iterator_types_helper<true> { typedef mutable_buffer buffer_type; template <typename ByteType> struct byte_type { typedef ByteType type; }; }; template <typename BufferSequence, typename ByteType> struct buffers_iterator_types { enum { is_mutable = is_convertible< typename BufferSequence::value_type, mutable_buffer>::value }; typedef buffers_iterator_types_helper<is_mutable> helper; typedef typename helper::buffer_type buffer_type; typedef typename helper::template byte_type<ByteType>::type byte_type; typedef typename BufferSequence::const_iterator const_iterator; }; template <typename ByteType> struct buffers_iterator_types<mutable_buffer, ByteType> { typedef mutable_buffer buffer_type; typedef ByteType byte_type; typedef const mutable_buffer* const_iterator; }; template <typename ByteType> struct buffers_iterator_types<const_buffer, ByteType> { typedef const_buffer buffer_type; typedef add_const_t<ByteType> byte_type; typedef const const_buffer* const_iterator; }; #if !defined(BOOST_ASIO_NO_DEPRECATED) template <typename ByteType> struct buffers_iterator_types<mutable_buffers_1, ByteType> { typedef mutable_buffer buffer_type; typedef ByteType byte_type; typedef const mutable_buffer* const_iterator; }; template <typename ByteType> struct buffers_iterator_types<const_buffers_1, ByteType> { typedef const_buffer buffer_type; typedef add_const_t<ByteType> byte_type; typedef const const_buffer* const_iterator; }; #endif // !defined(BOOST_ASIO_NO_DEPRECATED) } /// A random access iterator over the bytes in a buffer sequence. template <typename BufferSequence, typename ByteType = char> class buffers_iterator { private: typedef typename detail::buffers_iterator_types< BufferSequence, ByteType>::buffer_type buffer_type; typedef typename detail::buffers_iterator_types<BufferSequence, ByteType>::const_iterator buffer_sequence_iterator_type; public: /// The type used for the distance between two iterators. typedef std::ptrdiff_t difference_type; /// The type of the value pointed to by the iterator. typedef ByteType value_type; #if defined(GENERATING_DOCUMENTATION) /// The type of the result of applying operator->() to the iterator. /** * If the buffer sequence stores buffer objects that are convertible to * mutable_buffer, this is a pointer to a non-const ByteType. Otherwise, a * pointer to a const ByteType. */ typedef const_or_non_const_ByteType* pointer; #else // defined(GENERATING_DOCUMENTATION) typedef typename detail::buffers_iterator_types< BufferSequence, ByteType>::byte_type* pointer; #endif // defined(GENERATING_DOCUMENTATION) #if defined(GENERATING_DOCUMENTATION) /// The type of the result of applying operator*() to the iterator. /** * If the buffer sequence stores buffer objects that are convertible to * mutable_buffer, this is a reference to a non-const ByteType. Otherwise, a * reference to a const ByteType. */ typedef const_or_non_const_ByteType& reference; #else // defined(GENERATING_DOCUMENTATION) typedef typename detail::buffers_iterator_types< BufferSequence, ByteType>::byte_type& reference; #endif // defined(GENERATING_DOCUMENTATION) /// The iterator category. typedef std::random_access_iterator_tag iterator_category; /// Default constructor. Creates an iterator in an undefined state. buffers_iterator() : current_buffer_(), current_buffer_position_(0), begin_(), current_(), end_(), position_(0) { } /// Construct an iterator representing the beginning of the buffers' data. static buffers_iterator begin(const BufferSequence& buffers) #if defined(__GNUC__) && (__GNUC__ == 4) && (__GNUC_MINOR__ == 3) __attribute__ ((__noinline__)) #endif // defined(__GNUC__) && (__GNUC__ == 4) && (__GNUC_MINOR__ == 3) { buffers_iterator new_iter; new_iter.begin_ = boost::asio::buffer_sequence_begin(buffers); new_iter.current_ = boost::asio::buffer_sequence_begin(buffers); new_iter.end_ = boost::asio::buffer_sequence_end(buffers); while (new_iter.current_ != new_iter.end_) { new_iter.current_buffer_ = *new_iter.current_; if (new_iter.current_buffer_.size() > 0) break; ++new_iter.current_; } return new_iter; } /// Construct an iterator representing the end of the buffers' data. static buffers_iterator end(const BufferSequence& buffers) #if defined(__GNUC__) && (__GNUC__ == 4) && (__GNUC_MINOR__ == 3) __attribute__ ((__noinline__)) #endif // defined(__GNUC__) && (__GNUC__ == 4) && (__GNUC_MINOR__ == 3) { buffers_iterator new_iter; new_iter.begin_ = boost::asio::buffer_sequence_begin(buffers); new_iter.current_ = boost::asio::buffer_sequence_begin(buffers); new_iter.end_ = boost::asio::buffer_sequence_end(buffers); while (new_iter.current_ != new_iter.end_) { buffer_type buffer = *new_iter.current_; new_iter.position_ += buffer.size(); ++new_iter.current_; } return new_iter; } /// Dereference an iterator. reference operator*() const { return dereference(); } /// Dereference an iterator. pointer operator->() const { return &dereference(); } /// Access an individual element. reference operator[](std::ptrdiff_t difference) const { buffers_iterator tmp(*this); tmp.advance(difference); return *tmp; } /// Increment operator (prefix). buffers_iterator& operator++() { increment(); return *this; } /// Increment operator (postfix). buffers_iterator operator++(int) { buffers_iterator tmp(*this); ++*this; return tmp; } /// Decrement operator (prefix). buffers_iterator& operator--() { decrement(); return *this; } /// Decrement operator (postfix). buffers_iterator operator--(int) { buffers_iterator tmp(*this); --*this; return tmp; } /// Addition operator. buffers_iterator& operator+=(std::ptrdiff_t difference) { advance(difference); return *this; } /// Subtraction operator. buffers_iterator& operator-=(std::ptrdiff_t difference) { advance(-difference); return *this; } /// Addition operator. friend buffers_iterator operator+(const buffers_iterator& iter, std::ptrdiff_t difference) { buffers_iterator tmp(iter); tmp.advance(difference); return tmp; } /// Addition operator. friend buffers_iterator operator+(std::ptrdiff_t difference, const buffers_iterator& iter) { buffers_iterator tmp(iter); tmp.advance(difference); return tmp; } /// Subtraction operator. friend buffers_iterator operator-(const buffers_iterator& iter, std::ptrdiff_t difference) { buffers_iterator tmp(iter); tmp.advance(-difference); return tmp; } /// Subtraction operator. friend std::ptrdiff_t operator-(const buffers_iterator& a, const buffers_iterator& b) { return b.distance_to(a); } /// Test two iterators for equality. friend bool operator==(const buffers_iterator& a, const buffers_iterator& b) { return a.equal(b); } /// Test two iterators for inequality. friend bool operator!=(const buffers_iterator& a, const buffers_iterator& b) { return !a.equal(b); } /// Compare two iterators. friend bool operator<(const buffers_iterator& a, const buffers_iterator& b) { return a.distance_to(b) > 0; } /// Compare two iterators. friend bool operator<=(const buffers_iterator& a, const buffers_iterator& b) { return !(b < a); } /// Compare two iterators. friend bool operator>(const buffers_iterator& a, const buffers_iterator& b) { return b < a; } /// Compare two iterators. friend bool operator>=(const buffers_iterator& a, const buffers_iterator& b) { return !(a < b); } private: // Dereference the iterator. reference dereference() const { return static_cast<pointer>( current_buffer_.data())[current_buffer_position_]; } // Compare two iterators for equality. bool equal(const buffers_iterator& other) const { return position_ == other.position_; } // Increment the iterator. void increment() { BOOST_ASIO_ASSERT(current_ != end_ && "iterator out of bounds"); ++position_; // Check if the increment can be satisfied by the current buffer. ++current_buffer_position_; if (current_buffer_position_ != current_buffer_.size()) return; // Find the next non-empty buffer. ++current_; current_buffer_position_ = 0; while (current_ != end_) { current_buffer_ = *current_; if (current_buffer_.size() > 0) return; ++current_; } } // Decrement the iterator. void decrement() { BOOST_ASIO_ASSERT(position_ > 0 && "iterator out of bounds"); --position_; // Check if the decrement can be satisfied by the current buffer. if (current_buffer_position_ != 0) { --current_buffer_position_; return; } // Find the previous non-empty buffer. buffer_sequence_iterator_type iter = current_; while (iter != begin_) { --iter; buffer_type buffer = *iter; std::size_t buffer_size = buffer.size(); if (buffer_size > 0) { current_ = iter; current_buffer_ = buffer; current_buffer_position_ = buffer_size - 1; return; } } } // Advance the iterator by the specified distance. void advance(std::ptrdiff_t n) { if (n > 0) { BOOST_ASIO_ASSERT(current_ != end_ && "iterator out of bounds"); for (;;) { std::ptrdiff_t current_buffer_balance = current_buffer_.size() - current_buffer_position_; // Check if the advance can be satisfied by the current buffer. if (current_buffer_balance > n) { position_ += n; current_buffer_position_ += n; return; } // Update position. n -= current_buffer_balance; position_ += current_buffer_balance; // Move to next buffer. If it is empty then it will be skipped on the // next iteration of this loop. if (++current_ == end_) { BOOST_ASIO_ASSERT(n == 0 && "iterator out of bounds"); current_buffer_ = buffer_type(); current_buffer_position_ = 0; return; } current_buffer_ = *current_; current_buffer_position_ = 0; } } else if (n < 0) { std::size_t abs_n = -n; BOOST_ASIO_ASSERT(position_ >= abs_n && "iterator out of bounds"); for (;;) { // Check if the advance can be satisfied by the current buffer. if (current_buffer_position_ >= abs_n) { position_ -= abs_n; current_buffer_position_ -= abs_n; return; } // Update position. abs_n -= current_buffer_position_; position_ -= current_buffer_position_; // Check if we've reached the beginning of the buffers. if (current_ == begin_) { BOOST_ASIO_ASSERT(abs_n == 0 && "iterator out of bounds"); current_buffer_position_ = 0; return; } // Find the previous non-empty buffer. buffer_sequence_iterator_type iter = current_; while (iter != begin_) { --iter; buffer_type buffer = *iter; std::size_t buffer_size = buffer.size(); if (buffer_size > 0) { current_ = iter; current_buffer_ = buffer; current_buffer_position_ = buffer_size; break; } } } } } // Determine the distance between two iterators. std::ptrdiff_t distance_to(const buffers_iterator& other) const { return other.position_ - position_; } buffer_type current_buffer_; std::size_t current_buffer_position_; buffer_sequence_iterator_type begin_; buffer_sequence_iterator_type current_; buffer_sequence_iterator_type end_; std::size_t position_; }; /// Construct an iterator representing the beginning of the buffers' data. template <typename BufferSequence> inline buffers_iterator<BufferSequence> buffers_begin( const BufferSequence& buffers) { return buffers_iterator<BufferSequence>::begin(buffers); } /// Construct an iterator representing the end of the buffers' data. template <typename BufferSequence> inline buffers_iterator<BufferSequence> buffers_end( const BufferSequence& buffers) { return buffers_iterator<BufferSequence>::end(buffers); } } // namespace asio } // namespace boost #include <boost/asio/detail/pop_options.hpp> #endif // BOOST_ASIO_BUFFERS_ITERATOR_HPP
hpp
asio
data/projects/asio/include/boost/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 BOOST_ASIO_BASIC_DEADLINE_TIMER_HPP #define BOOST_ASIO_BASIC_DEADLINE_TIMER_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <boost/asio/detail/config.hpp> #if defined(BOOST_ASIO_HAS_BOOST_DATE_TIME) \ || defined(GENERATING_DOCUMENTATION) #include <cstddef> #include <boost/asio/any_io_executor.hpp> #include <boost/asio/detail/deadline_timer_service.hpp> #include <boost/asio/detail/handler_type_requirements.hpp> #include <boost/asio/detail/io_object_impl.hpp> #include <boost/asio/detail/non_const_lvalue.hpp> #include <boost/asio/detail/throw_error.hpp> #include <boost/asio/error.hpp> #include <boost/asio/execution_context.hpp> #include <boost/asio/time_traits.hpp> #include <boost/asio/detail/push_options.hpp> namespace boost { 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 boost::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. * boost::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 boost::system::error_code& error) * { * if (!error) * { * // Timer expired. * } * } * * ... * * // Construct a timer with an absolute expiry time. * boost::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 boost::system::error_code& e) * { * if (e != boost::asio::error::operation_aborted) * { * // Timer was not cancelled, take necessary action. * } * } * @endcode * * @li The boost::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 boost::system::error_code passed to * it contains the value boost::asio::error::operation_aborted. */ template <typename Time, typename TimeTraits = boost::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) { boost::system::error_code ec; impl_.get_service().expires_at(impl_.get_implementation(), expiry_time, ec); boost::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) { boost::system::error_code ec; impl_.get_service().expires_at(impl_.get_implementation(), expiry_time, ec); boost::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) { boost::system::error_code ec; impl_.get_service().expires_from_now( impl_.get_implementation(), expiry_time, ec); boost::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) { boost::system::error_code ec; impl_.get_service().expires_from_now( impl_.get_implementation(), expiry_time, ec); boost::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 boost::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 boost::system::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() { boost::system::error_code ec; std::size_t s = impl_.get_service().cancel(impl_.get_implementation(), ec); boost::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 boost::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(boost::system::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 * boost::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 boost::system::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() { boost::system::error_code ec; std::size_t s = impl_.get_service().cancel_one( impl_.get_implementation(), ec); boost::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 * boost::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(boost::system::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 boost::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 boost::system::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) { boost::system::error_code ec; std::size_t s = impl_.get_service().expires_at( impl_.get_implementation(), expiry_time, ec); boost::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 boost::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, boost::system::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 boost::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 boost::system::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) { boost::system::error_code ec; std::size_t s = impl_.get_service().expires_from_now( impl_.get_implementation(), expiry_time, ec); boost::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 boost::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, boost::system::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 boost::system::system_error Thrown on failure. */ void wait() { boost::system::error_code ec; impl_.get_service().wait(impl_.get_implementation(), ec); boost::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(boost::system::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 boost::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 boost::system::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 boost::asio::post(). * * @par Completion Signature * @code void(boost::system::error_code) @endcode * * @par Per-Operation Cancellation * This asynchronous operation supports cancellation for the following * boost::asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * @li @c cancellation_type::total */ template < BOOST_ASIO_COMPLETION_TOKEN_FOR(void (boost::system::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 (boost::system::error_code)>( declval<initiate_async_wait>(), token)) { return async_initiate<WaitToken, void (boost::system::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. BOOST_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 } // namespace boost #include <boost/asio/detail/pop_options.hpp> #endif // defined(BOOST_ASIO_HAS_BOOST_DATE_TIME) // || defined(GENERATING_DOCUMENTATION) #endif // BOOST_ASIO_BASIC_DEADLINE_TIMER_HPP
hpp
asio
data/projects/asio/include/boost/asio/executor.hpp
// // 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 BOOST_ASIO_EXECUTOR_HPP #define BOOST_ASIO_EXECUTOR_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <boost/asio/detail/config.hpp> #if !defined(BOOST_ASIO_NO_TS_EXECUTORS) #include <new> #include <typeinfo> #include <boost/asio/detail/cstddef.hpp> #include <boost/asio/detail/executor_function.hpp> #include <boost/asio/detail/memory.hpp> #include <boost/asio/detail/throw_exception.hpp> #include <boost/asio/execution_context.hpp> #include <boost/asio/detail/push_options.hpp> namespace boost { namespace asio { /// Exception thrown when trying to access an empty polymorphic executor. class bad_executor : public std::exception { public: /// Constructor. BOOST_ASIO_DECL bad_executor() noexcept; /// Obtain message associated with exception. BOOST_ASIO_DECL virtual const char* what() const noexcept; }; /// Polymorphic wrapper for executors. class executor { public: /// Default constructor. executor() noexcept : impl_(0) { } /// Construct from nullptr. executor(nullptr_t) noexcept : impl_(0) { } /// Copy constructor. executor(const executor& other) noexcept : impl_(other.clone()) { } /// Move constructor. executor(executor&& other) noexcept : impl_(other.impl_) { other.impl_ = 0; } /// Construct a polymorphic wrapper for the specified executor. template <typename Executor> executor(Executor e); /// Construct a polymorphic executor that points to the same target as /// another polymorphic executor. executor(std::nothrow_t, const executor& other) noexcept : impl_(other.clone()) { } /// Construct a polymorphic executor that moves the target from another /// polymorphic executor. executor(std::nothrow_t, executor&& other) noexcept : impl_(other.impl_) { other.impl_ = 0; } /// Construct a polymorphic wrapper for the specified executor. template <typename Executor> executor(std::nothrow_t, Executor e) noexcept; /// Allocator-aware constructor to create a polymorphic wrapper for the /// specified executor. template <typename Executor, typename Allocator> executor(allocator_arg_t, const Allocator& a, Executor e); /// Destructor. ~executor() { destroy(); } /// Assignment operator. executor& operator=(const executor& other) noexcept { destroy(); impl_ = other.clone(); return *this; } // Move assignment operator. executor& operator=(executor&& other) noexcept { destroy(); impl_ = other.impl_; other.impl_ = 0; return *this; } /// Assignment operator for nullptr_t. executor& operator=(nullptr_t) noexcept { destroy(); impl_ = 0; return *this; } /// Assignment operator to create a polymorphic wrapper for the specified /// executor. template <typename Executor> executor& operator=(Executor&& e) noexcept { executor tmp(static_cast<Executor&&>(e)); destroy(); impl_ = tmp.impl_; tmp.impl_ = 0; return *this; } /// Obtain the underlying execution context. execution_context& context() const noexcept { return get_impl()->context(); } /// Inform the executor that it has some outstanding work to do. void on_work_started() const noexcept { get_impl()->on_work_started(); } /// Inform the executor that some work is no longer outstanding. void on_work_finished() const noexcept { get_impl()->on_work_finished(); } /// Request the executor to invoke the given function object. /** * This function is used to ask the executor to execute the given function * object. The function object is executed according to the rules of the * target executor object. * * @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 Allocator> void dispatch(Function&& f, const Allocator& a) const; /// Request the executor to invoke the given function object. /** * This function is used to ask the executor to execute the given function * object. The function object is executed according to the rules of the * target executor object. * * @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 Allocator> void post(Function&& f, const Allocator& a) const; /// Request the executor to invoke the given function object. /** * This function is used to ask the executor to execute the given function * object. The function object is executed according to the rules of the * target executor object. * * @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 Allocator> void defer(Function&& f, const Allocator& a) const; struct unspecified_bool_type_t {}; typedef void (*unspecified_bool_type)(unspecified_bool_type_t); static void unspecified_bool_true(unspecified_bool_type_t) {} /// Operator to test if the executor contains a valid target. operator unspecified_bool_type() const noexcept { return impl_ ? &executor::unspecified_bool_true : 0; } /// Obtain type information for the target executor object. /** * @returns If @c *this has a target type of type @c T, <tt>typeid(T)</tt>; * otherwise, <tt>typeid(void)</tt>. */ #if !defined(BOOST_ASIO_NO_TYPEID) || defined(GENERATING_DOCUMENTATION) const std::type_info& target_type() const noexcept { return impl_ ? impl_->target_type() : typeid(void); } #else // !defined(BOOST_ASIO_NO_TYPEID) || defined(GENERATING_DOCUMENTATION) const void* target_type() const noexcept { return impl_ ? impl_->target_type() : 0; } #endif // !defined(BOOST_ASIO_NO_TYPEID) || defined(GENERATING_DOCUMENTATION) /// Obtain a pointer to the target executor object. /** * @returns If <tt>target_type() == typeid(T)</tt>, a pointer to the stored * executor target; otherwise, a null pointer. */ template <typename Executor> Executor* target() noexcept; /// Obtain a pointer to the target executor object. /** * @returns If <tt>target_type() == typeid(T)</tt>, a pointer to the stored * executor target; otherwise, a null pointer. */ template <typename Executor> const Executor* target() const noexcept; /// Compare two executors for equality. friend bool operator==(const executor& a, const executor& b) noexcept { if (a.impl_ == b.impl_) return true; if (!a.impl_ || !b.impl_) return false; return a.impl_->equals(b.impl_); } /// Compare two executors for inequality. friend bool operator!=(const executor& a, const executor& b) noexcept { return !(a == b); } private: #if !defined(GENERATING_DOCUMENTATION) typedef detail::executor_function function; template <typename, typename> class impl; #if !defined(BOOST_ASIO_NO_TYPEID) typedef const std::type_info& type_id_result_type; #else // !defined(BOOST_ASIO_NO_TYPEID) typedef const void* type_id_result_type; #endif // !defined(BOOST_ASIO_NO_TYPEID) template <typename T> static type_id_result_type type_id() { #if !defined(BOOST_ASIO_NO_TYPEID) return typeid(T); #else // !defined(BOOST_ASIO_NO_TYPEID) static int unique_id; return &unique_id; #endif // !defined(BOOST_ASIO_NO_TYPEID) } // Base class for all polymorphic executor implementations. class impl_base { public: virtual impl_base* clone() const noexcept = 0; virtual void destroy() noexcept = 0; virtual execution_context& context() noexcept = 0; virtual void on_work_started() noexcept = 0; virtual void on_work_finished() noexcept = 0; virtual void dispatch(function&&) = 0; virtual void post(function&&) = 0; virtual void defer(function&&) = 0; virtual type_id_result_type target_type() const noexcept = 0; virtual void* target() noexcept = 0; virtual const void* target() const noexcept = 0; virtual bool equals(const impl_base* e) const noexcept = 0; protected: impl_base(bool fast_dispatch) : fast_dispatch_(fast_dispatch) {} virtual ~impl_base() {} private: friend class executor; const bool fast_dispatch_; }; // Helper function to check and return the implementation pointer. impl_base* get_impl() const { if (!impl_) { bad_executor ex; boost::asio::detail::throw_exception(ex); } return impl_; } // Helper function to clone another implementation. impl_base* clone() const noexcept { return impl_ ? impl_->clone() : 0; } // Helper function to destroy an implementation. void destroy() noexcept { if (impl_) impl_->destroy(); } impl_base* impl_; #endif // !defined(GENERATING_DOCUMENTATION) }; } // namespace asio } // namespace boost BOOST_ASIO_USES_ALLOCATOR(boost::asio::executor) #include <boost/asio/detail/pop_options.hpp> #include <boost/asio/impl/executor.hpp> #if defined(BOOST_ASIO_HEADER_ONLY) # include <boost/asio/impl/executor.ipp> #endif // defined(BOOST_ASIO_HEADER_ONLY) #endif // !defined(BOOST_ASIO_NO_TS_EXECUTORS) #endif // BOOST_ASIO_EXECUTOR_HPP
hpp
asio
data/projects/asio/include/boost/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 BOOST_ASIO_CONNECT_PIPE_HPP #define BOOST_ASIO_CONNECT_PIPE_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <boost/asio/detail/config.hpp> #if defined(BOOST_ASIO_HAS_PIPE) \ || defined(GENERATING_DOCUMENTATION) #include <boost/asio/basic_readable_pipe.hpp> #include <boost/asio/basic_writable_pipe.hpp> #include <boost/asio/error.hpp> #include <boost/asio/detail/push_options.hpp> namespace boost { namespace asio { namespace detail { #if defined(BOOST_ASIO_HAS_IOCP) typedef HANDLE native_pipe_handle; #else // defined(BOOST_ASIO_HAS_IOCP) typedef int native_pipe_handle; #endif // defined(BOOST_ASIO_HAS_IOCP) BOOST_ASIO_DECL void create_pipe(native_pipe_handle p[2], boost::system::error_code& ec); BOOST_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 boost::system::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 boost::system::system_error Thrown on failure. * * @param ec Set to indicate what error occurred, if any. */ template <typename Executor1, typename Executor2> BOOST_ASIO_SYNC_OP_VOID connect_pipe(basic_readable_pipe<Executor1>& read_end, basic_writable_pipe<Executor2>& write_end, boost::system::error_code& ec); } // namespace asio } // namespace boost #include <boost/asio/detail/pop_options.hpp> #include <boost/asio/impl/connect_pipe.hpp> #if defined(BOOST_ASIO_HEADER_ONLY) # include <boost/asio/impl/connect_pipe.ipp> #endif // defined(BOOST_ASIO_HEADER_ONLY) #endif // defined(BOOST_ASIO_HAS_PIPE) // || defined(GENERATING_DOCUMENTATION) #endif // BOOST_ASIO_CONNECT_PIPE_HPP
hpp
asio
data/projects/asio/include/boost/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 BOOST_ASIO_ERROR_HPP #define BOOST_ASIO_ERROR_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <boost/asio/detail/config.hpp> #include <boost/cerrno.hpp> #include <boost/system/error_code.hpp> #include <boost/system/system_error.hpp> #if defined(BOOST_ASIO_WINDOWS) \ || defined(__CYGWIN__) \ || defined(BOOST_ASIO_WINDOWS_RUNTIME) # include <winerror.h> #else # include <cerrno> # include <netdb.h> #endif #if defined(GENERATING_DOCUMENTATION) /// INTERNAL ONLY. # define BOOST_ASIO_NATIVE_ERROR(e) implementation_defined /// INTERNAL ONLY. # define BOOST_ASIO_SOCKET_ERROR(e) implementation_defined /// INTERNAL ONLY. # define BOOST_ASIO_NETDB_ERROR(e) implementation_defined /// INTERNAL ONLY. # define BOOST_ASIO_GETADDRINFO_ERROR(e) implementation_defined /// INTERNAL ONLY. # define BOOST_ASIO_WIN_OR_POSIX(e_win, e_posix) implementation_defined #elif defined(BOOST_ASIO_WINDOWS_RUNTIME) # define BOOST_ASIO_NATIVE_ERROR(e) __HRESULT_FROM_WIN32(e) # define BOOST_ASIO_SOCKET_ERROR(e) __HRESULT_FROM_WIN32(WSA ## e) # define BOOST_ASIO_NETDB_ERROR(e) __HRESULT_FROM_WIN32(WSA ## e) # define BOOST_ASIO_GETADDRINFO_ERROR(e) __HRESULT_FROM_WIN32(WSA ## e) # define BOOST_ASIO_WIN_OR_POSIX(e_win, e_posix) e_win #elif defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__) # define BOOST_ASIO_NATIVE_ERROR(e) e # define BOOST_ASIO_SOCKET_ERROR(e) WSA ## e # define BOOST_ASIO_NETDB_ERROR(e) WSA ## e # define BOOST_ASIO_GETADDRINFO_ERROR(e) WSA ## e # define BOOST_ASIO_WIN_OR_POSIX(e_win, e_posix) e_win #else # define BOOST_ASIO_NATIVE_ERROR(e) e # define BOOST_ASIO_SOCKET_ERROR(e) e # define BOOST_ASIO_NETDB_ERROR(e) e # define BOOST_ASIO_GETADDRINFO_ERROR(e) e # define BOOST_ASIO_WIN_OR_POSIX(e_win, e_posix) e_posix #endif #include <boost/asio/detail/push_options.hpp> namespace boost { namespace asio { namespace error { enum basic_errors { /// Permission denied. access_denied = BOOST_ASIO_SOCKET_ERROR(EACCES), /// Address family not supported by protocol. address_family_not_supported = BOOST_ASIO_SOCKET_ERROR(EAFNOSUPPORT), /// Address already in use. address_in_use = BOOST_ASIO_SOCKET_ERROR(EADDRINUSE), /// Transport endpoint is already connected. already_connected = BOOST_ASIO_SOCKET_ERROR(EISCONN), /// Operation already in progress. already_started = BOOST_ASIO_SOCKET_ERROR(EALREADY), /// Broken pipe. broken_pipe = BOOST_ASIO_WIN_OR_POSIX( BOOST_ASIO_NATIVE_ERROR(ERROR_BROKEN_PIPE), BOOST_ASIO_NATIVE_ERROR(EPIPE)), /// A connection has been aborted. connection_aborted = BOOST_ASIO_SOCKET_ERROR(ECONNABORTED), /// Connection refused. connection_refused = BOOST_ASIO_SOCKET_ERROR(ECONNREFUSED), /// Connection reset by peer. connection_reset = BOOST_ASIO_SOCKET_ERROR(ECONNRESET), /// Bad file descriptor. bad_descriptor = BOOST_ASIO_SOCKET_ERROR(EBADF), /// Bad address. fault = BOOST_ASIO_SOCKET_ERROR(EFAULT), /// No route to host. host_unreachable = BOOST_ASIO_SOCKET_ERROR(EHOSTUNREACH), /// Operation now in progress. in_progress = BOOST_ASIO_SOCKET_ERROR(EINPROGRESS), /// Interrupted system call. interrupted = BOOST_ASIO_SOCKET_ERROR(EINTR), /// Invalid argument. invalid_argument = BOOST_ASIO_SOCKET_ERROR(EINVAL), /// Message too long. message_size = BOOST_ASIO_SOCKET_ERROR(EMSGSIZE), /// The name was too long. name_too_long = BOOST_ASIO_SOCKET_ERROR(ENAMETOOLONG), /// Network is down. network_down = BOOST_ASIO_SOCKET_ERROR(ENETDOWN), /// Network dropped connection on reset. network_reset = BOOST_ASIO_SOCKET_ERROR(ENETRESET), /// Network is unreachable. network_unreachable = BOOST_ASIO_SOCKET_ERROR(ENETUNREACH), /// Too many open files. no_descriptors = BOOST_ASIO_SOCKET_ERROR(EMFILE), /// No buffer space available. no_buffer_space = BOOST_ASIO_SOCKET_ERROR(ENOBUFS), /// Cannot allocate memory. no_memory = BOOST_ASIO_WIN_OR_POSIX( BOOST_ASIO_NATIVE_ERROR(ERROR_OUTOFMEMORY), BOOST_ASIO_NATIVE_ERROR(ENOMEM)), /// Operation not permitted. no_permission = BOOST_ASIO_WIN_OR_POSIX( BOOST_ASIO_NATIVE_ERROR(ERROR_ACCESS_DENIED), BOOST_ASIO_NATIVE_ERROR(EPERM)), /// Protocol not available. no_protocol_option = BOOST_ASIO_SOCKET_ERROR(ENOPROTOOPT), /// No such device. no_such_device = BOOST_ASIO_WIN_OR_POSIX( BOOST_ASIO_NATIVE_ERROR(ERROR_BAD_UNIT), BOOST_ASIO_NATIVE_ERROR(ENODEV)), /// Transport endpoint is not connected. not_connected = BOOST_ASIO_SOCKET_ERROR(ENOTCONN), /// Socket operation on non-socket. not_socket = BOOST_ASIO_SOCKET_ERROR(ENOTSOCK), /// Operation cancelled. operation_aborted = BOOST_ASIO_WIN_OR_POSIX( BOOST_ASIO_NATIVE_ERROR(ERROR_OPERATION_ABORTED), BOOST_ASIO_NATIVE_ERROR(ECANCELED)), /// Operation not supported. operation_not_supported = BOOST_ASIO_SOCKET_ERROR(EOPNOTSUPP), /// Cannot send after transport endpoint shutdown. shut_down = BOOST_ASIO_SOCKET_ERROR(ESHUTDOWN), /// Connection timed out. timed_out = BOOST_ASIO_SOCKET_ERROR(ETIMEDOUT), /// Resource temporarily unavailable. try_again = BOOST_ASIO_WIN_OR_POSIX( BOOST_ASIO_NATIVE_ERROR(ERROR_RETRY), BOOST_ASIO_NATIVE_ERROR(EAGAIN)), /// The socket is marked non-blocking and the requested operation would block. would_block = BOOST_ASIO_SOCKET_ERROR(EWOULDBLOCK) }; enum netdb_errors { /// Host not found (authoritative). host_not_found = BOOST_ASIO_NETDB_ERROR(HOST_NOT_FOUND), /// Host not found (non-authoritative). host_not_found_try_again = BOOST_ASIO_NETDB_ERROR(TRY_AGAIN), /// The query is valid but does not have associated address data. no_data = BOOST_ASIO_NETDB_ERROR(NO_DATA), /// A non-recoverable error occurred. no_recovery = BOOST_ASIO_NETDB_ERROR(NO_RECOVERY) }; enum addrinfo_errors { /// The service is not supported for the given socket type. service_not_found = BOOST_ASIO_WIN_OR_POSIX( BOOST_ASIO_NATIVE_ERROR(WSATYPE_NOT_FOUND), BOOST_ASIO_GETADDRINFO_ERROR(EAI_SERVICE)), /// The socket type is not supported. socket_type_not_supported = BOOST_ASIO_WIN_OR_POSIX( BOOST_ASIO_NATIVE_ERROR(WSAESOCKTNOSUPPORT), BOOST_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 }; #if !defined(BOOST_ASIO_ERROR_LOCATION) \ && !defined(BOOST_ASIO_DISABLE_ERROR_LOCATION) \ && defined(BOOST_ASIO_HAS_BOOST_CONFIG) \ && (BOOST_VERSION >= 107900) # define BOOST_ASIO_ERROR_LOCATION(e) \ do { \ BOOST_STATIC_CONSTEXPR boost::source_location loc \ = BOOST_CURRENT_LOCATION; \ (e).assign((e), &loc); \ } while (false) #else // !defined(BOOST_ASIO_ERROR_LOCATION) // && !defined(BOOST_ASIO_DISABLE_ERROR_LOCATION) // && defined(BOOST_ASIO_HAS_BOOST_CONFIG) // && (BOOST_VERSION >= 107900) # define BOOST_ASIO_ERROR_LOCATION(e) (void)0 #endif // !defined(BOOST_ASIO_ERROR_LOCATION) // && !defined(BOOST_ASIO_DISABLE_ERROR_LOCATION) // && defined(BOOST_ASIO_HAS_BOOST_CONFIG) // && (BOOST_VERSION >= 107900) inline void clear(boost::system::error_code& ec) { ec = boost::system::error_code(); } inline const boost::system::error_category& get_system_category() { return boost::system::system_category(); } #if !defined(BOOST_ASIO_WINDOWS) && !defined(__CYGWIN__) extern BOOST_ASIO_DECL const boost::system::error_category& get_netdb_category(); extern BOOST_ASIO_DECL const boost::system::error_category& get_addrinfo_category(); #else // !defined(BOOST_ASIO_WINDOWS) && !defined(__CYGWIN__) inline const boost::system::error_category& get_netdb_category() { return get_system_category(); } inline const boost::system::error_category& get_addrinfo_category() { return get_system_category(); } #endif // !defined(BOOST_ASIO_WINDOWS) && !defined(__CYGWIN__) extern BOOST_ASIO_DECL const boost::system::error_category& get_misc_category(); static const boost::system::error_category& system_category BOOST_ASIO_UNUSED_VARIABLE = boost::asio::error::get_system_category(); static const boost::system::error_category& netdb_category BOOST_ASIO_UNUSED_VARIABLE = boost::asio::error::get_netdb_category(); static const boost::system::error_category& addrinfo_category BOOST_ASIO_UNUSED_VARIABLE = boost::asio::error::get_addrinfo_category(); static const boost::system::error_category& misc_category BOOST_ASIO_UNUSED_VARIABLE = boost::asio::error::get_misc_category(); } // namespace error } // namespace asio } // namespace boost namespace boost { namespace system { template<> struct is_error_code_enum<boost::asio::error::basic_errors> { static const bool value = true; }; template<> struct is_error_code_enum<boost::asio::error::netdb_errors> { static const bool value = true; }; template<> struct is_error_code_enum<boost::asio::error::addrinfo_errors> { static const bool value = true; }; template<> struct is_error_code_enum<boost::asio::error::misc_errors> { static const bool value = true; }; } // namespace system } // namespace boost namespace boost { namespace asio { namespace error { inline boost::system::error_code make_error_code(basic_errors e) { return boost::system::error_code( static_cast<int>(e), get_system_category()); } inline boost::system::error_code make_error_code(netdb_errors e) { return boost::system::error_code( static_cast<int>(e), get_netdb_category()); } inline boost::system::error_code make_error_code(addrinfo_errors e) { return boost::system::error_code( static_cast<int>(e), get_addrinfo_category()); } inline boost::system::error_code make_error_code(misc_errors e) { return boost::system::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 } // namespace boost #include <boost/asio/detail/pop_options.hpp> #undef BOOST_ASIO_NATIVE_ERROR #undef BOOST_ASIO_SOCKET_ERROR #undef BOOST_ASIO_NETDB_ERROR #undef BOOST_ASIO_GETADDRINFO_ERROR #undef BOOST_ASIO_WIN_OR_POSIX #if defined(BOOST_ASIO_HEADER_ONLY) # include <boost/asio/impl/error.ipp> #endif // defined(BOOST_ASIO_HEADER_ONLY) #endif // BOOST_ASIO_ERROR_HPP
hpp
asio
data/projects/asio/include/boost/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 BOOST_ASIO_BASIC_STREAMBUF_HPP #define BOOST_ASIO_BASIC_STREAMBUF_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <boost/asio/detail/config.hpp> #if !defined(BOOST_ASIO_NO_IOSTREAM) #include <algorithm> #include <cstring> #include <stdexcept> #include <streambuf> #include <vector> #include <boost/asio/basic_streambuf_fwd.hpp> #include <boost/asio/buffer.hpp> #include <boost/asio/detail/limits.hpp> #include <boost/asio/detail/noncopyable.hpp> #include <boost/asio/detail/throw_exception.hpp> #include <boost/asio/detail/push_options.hpp> namespace boost { 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 * boost::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 * boost::asio::streambuf b; * * // reserve 512 bytes in output sequence * boost::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 BOOST_ASIO_CONST_BUFFER const_buffers_type; typedef BOOST_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 boost::asio::buffer(boost::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 boost::asio::buffer(boost::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("boost::asio::streambuf too long"); boost::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 } // namespace boost #include <boost/asio/detail/pop_options.hpp> #endif // !defined(BOOST_ASIO_NO_IOSTREAM) #endif // BOOST_ASIO_BASIC_STREAMBUF_HPP
hpp
asio
data/projects/asio/include/boost/asio/io_context_strand.hpp
// // io_context_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 BOOST_ASIO_IO_CONTEXT_STRAND_HPP #define BOOST_ASIO_IO_CONTEXT_STRAND_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <boost/asio/detail/config.hpp> #if !defined(BOOST_ASIO_NO_EXTENSIONS) \ && !defined(BOOST_ASIO_NO_TS_EXECUTORS) #include <boost/asio/async_result.hpp> #include <boost/asio/detail/handler_type_requirements.hpp> #include <boost/asio/detail/strand_service.hpp> #include <boost/asio/detail/wrapped_handler.hpp> #include <boost/asio/io_context.hpp> #include <boost/asio/detail/push_options.hpp> namespace boost { namespace asio { /// Provides serialised handler execution. /** * The io_context::strand class provides the ability to post and dispatch * handlers with the guarantee that none of those handlers will execute * concurrently. * * @par Order of handler invocation * Given: * * @li a strand object @c s * * @li an object @c a meeting completion handler requirements * * @li an object @c a1 which is an arbitrary copy of @c a made by the * implementation * * @li an object @c b meeting completion handler requirements * * @li an object @c b1 which is an arbitrary copy of @c b made by the * implementation * * if any of the following conditions are true: * * @li @c s.post(a) happens-before @c s.post(b) * * @li @c s.post(a) happens-before @c s.dispatch(b), where the latter is * performed outside the strand * * @li @c s.dispatch(a) happens-before @c s.post(b), where the former is * performed outside the strand * * @li @c s.dispatch(a) happens-before @c s.dispatch(b), where both are * performed outside the strand * * then @c a() happens-before @c b() * * Note that in the following case: * @code async_op_1(..., s.wrap(a)); * async_op_2(..., s.wrap(b)); @endcode * the completion of the first async operation will perform @c s.dispatch(a), * and the second will perform @c s.dispatch(b), but the order in which those * are performed is unspecified. That is, you cannot state whether one * happens-before the other. Therefore none of the above conditions are met and * no ordering guarantee is made. * * @note The implementation makes no guarantee that handlers posted or * dispatched through different @c strand objects will be invoked concurrently. * * @par Thread Safety * @e Distinct @e objects: Safe.@n * @e Shared @e objects: Safe. * * @par Concepts: * Dispatcher. */ class io_context::strand { private: #if !defined(BOOST_ASIO_NO_DEPRECATED) struct initiate_dispatch; struct initiate_post; #endif // !defined(BOOST_ASIO_NO_DEPRECATED) public: /// Constructor. /** * Constructs the strand. * * @param io_context The io_context object that the strand will use to * dispatch handlers that are ready to be run. */ explicit strand(boost::asio::io_context& io_context) : service_(boost::asio::use_service< boost::asio::detail::strand_service>(io_context)) { service_.construct(impl_); } /// Copy constructor. /** * Creates a copy such that both strand objects share the same underlying * state. */ strand(const strand& other) noexcept : service_(other.service_), impl_(other.impl_) { } /// Destructor. /** * Destroys a strand. * * Handlers posted through the strand that have not yet been invoked will * still be dispatched in a way that meets the guarantee of non-concurrency. */ ~strand() { } /// Obtain the underlying execution context. boost::asio::io_context& context() const noexcept { return service_.get_io_context(); } /// Inform the strand that it has some outstanding work to do. /** * The strand delegates this call to its underlying io_context. */ void on_work_started() const noexcept { context().get_executor().on_work_started(); } /// Inform the strand that some work is no longer outstanding. /** * The strand delegates this call to its underlying io_context. */ void on_work_finished() const noexcept { context().get_executor().on_work_finished(); } /// Request the strand to invoke the given function object. /** * This function is used to ask the strand to execute the given function * object on its underlying io_context. The function object will be executed * inside this function if the strand is not otherwise busy and if the * underlying io_context's executor's @c dispatch() function is also able to * execute the function before returning. * * @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 Allocator> void dispatch(Function&& f, const Allocator& a) const { decay_t<Function> tmp(static_cast<Function&&>(f)); service_.dispatch(impl_, tmp); (void)a; } #if !defined(BOOST_ASIO_NO_DEPRECATED) /// (Deprecated: Use boost::asio::dispatch().) Request the strand to invoke /// the given handler. /** * This function is used to ask the strand to execute the given handler. * * The strand object guarantees that handlers posted or dispatched through * the strand will not be executed concurrently. The handler may be executed * inside this function if the guarantee can be met. If this function is * called from within a handler that was posted or dispatched through the same * strand, then the new handler will be executed immediately. * * The strand's guarantee is in addition to the guarantee provided by the * underlying io_context. The io_context guarantees that the handler will only * be called in a thread in which the io_context's run member function is * currently being invoked. * * @param handler The handler to be called. The strand will make a copy of the * handler object as required. The function signature of the handler must be: * @code void handler(); @endcode */ template <typename LegacyCompletionHandler> auto dispatch(LegacyCompletionHandler&& handler) -> decltype( async_initiate<LegacyCompletionHandler, void ()>( declval<initiate_dispatch>(), handler, this)) { return async_initiate<LegacyCompletionHandler, void ()>( initiate_dispatch(), handler, this); } #endif // !defined(BOOST_ASIO_NO_DEPRECATED) /// Request the strand 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 by the underlying 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 Allocator> void post(Function&& f, const Allocator& a) const { decay_t<Function> tmp(static_cast<Function&&>(f)); service_.post(impl_, tmp); (void)a; } #if !defined(BOOST_ASIO_NO_DEPRECATED) /// (Deprecated: Use boost::asio::post().) Request the strand to invoke the /// given handler and return immediately. /** * This function is used to ask the strand to execute the given handler, but * without allowing the strand to call the handler from inside this function. * * The strand object guarantees that handlers posted or dispatched through * the strand will not be executed concurrently. The strand's guarantee is in * addition to the guarantee provided by the underlying io_context. The * io_context guarantees that the handler will only be called in a thread in * which the io_context's run member function is currently being invoked. * * @param handler The handler to be called. The strand will make a copy of the * handler object as required. The function signature of the handler must be: * @code void handler(); @endcode */ template <typename LegacyCompletionHandler> auto post(LegacyCompletionHandler&& handler) -> decltype( async_initiate<LegacyCompletionHandler, void ()>( declval<initiate_post>(), handler, this)) { return async_initiate<LegacyCompletionHandler, void ()>( initiate_post(), handler, this); } #endif // !defined(BOOST_ASIO_NO_DEPRECATED) /// Request the strand 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 by the underlying 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 Allocator> void defer(Function&& f, const Allocator& a) const { decay_t<Function> tmp(static_cast<Function&&>(f)); service_.post(impl_, tmp); (void)a; } #if !defined(BOOST_ASIO_NO_DEPRECATED) /// (Deprecated: Use boost::asio::bind_executor().) Create a new handler that /// automatically dispatches the wrapped handler on the strand. /** * This function is used to create a new handler function object that, when * invoked, will automatically pass the wrapped handler to the strand's * dispatch function. * * @param handler The handler to be wrapped. The strand 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 strand'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 strand.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 strand.dispatch(boost::bind(f, a1, ... an)); @endcode */ template <typename Handler> #if defined(GENERATING_DOCUMENTATION) unspecified #else detail::wrapped_handler<strand, Handler, detail::is_continuation_if_running> #endif wrap(Handler handler) { return detail::wrapped_handler<io_context::strand, Handler, detail::is_continuation_if_running>(*this, handler); } #endif // !defined(BOOST_ASIO_NO_DEPRECATED) /// Determine whether the strand is running in the current thread. /** * @return @c true if the current thread is executing a handler that was * submitted to the strand using post(), dispatch() or wrap(). Otherwise * returns @c false. */ bool running_in_this_thread() const noexcept { return service_.running_in_this_thread(impl_); } /// Compare two strands for equality. /** * Two strands are equal if they refer to the same ordered, non-concurrent * state. */ friend bool operator==(const strand& a, const strand& b) noexcept { return a.impl_ == b.impl_; } /// Compare two strands for inequality. /** * Two strands are equal if they refer to the same ordered, non-concurrent * state. */ friend bool operator!=(const strand& a, const strand& b) noexcept { return a.impl_ != b.impl_; } private: #if !defined(BOOST_ASIO_NO_DEPRECATED) struct initiate_dispatch { template <typename LegacyCompletionHandler> void operator()(LegacyCompletionHandler&& handler, strand* self) const { // If you get an error on the following line it means that your // handler does not meet the documented type requirements for a // LegacyCompletionHandler. BOOST_ASIO_LEGACY_COMPLETION_HANDLER_CHECK( LegacyCompletionHandler, handler) type_check; detail::non_const_lvalue<LegacyCompletionHandler> handler2(handler); self->service_.dispatch(self->impl_, handler2.value); } }; struct initiate_post { template <typename LegacyCompletionHandler> void operator()(LegacyCompletionHandler&& handler, strand* self) const { // If you get an error on the following line it means that your // handler does not meet the documented type requirements for a // LegacyCompletionHandler. BOOST_ASIO_LEGACY_COMPLETION_HANDLER_CHECK( LegacyCompletionHandler, handler) type_check; detail::non_const_lvalue<LegacyCompletionHandler> handler2(handler); self->service_.post(self->impl_, handler2.value); } }; #endif // !defined(BOOST_ASIO_NO_DEPRECATED) boost::asio::detail::strand_service& service_; mutable boost::asio::detail::strand_service::implementation_type impl_; }; } // namespace asio } // namespace boost #include <boost/asio/detail/pop_options.hpp> #endif // !defined(BOOST_ASIO_NO_EXTENSIONS) // && !defined(BOOST_ASIO_NO_TS_EXECUTORS) #endif // BOOST_ASIO_IO_CONTEXT_STRAND_HPP
hpp
asio
data/projects/asio/include/boost/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 BOOST_ASIO_IS_WRITE_BUFFERED_HPP #define BOOST_ASIO_IS_WRITE_BUFFERED_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <boost/asio/detail/config.hpp> #include <boost/asio/buffered_stream_fwd.hpp> #include <boost/asio/buffered_write_stream_fwd.hpp> #include <boost/asio/detail/push_options.hpp> namespace boost { 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 BOOST_ASIO_STATIC_CONSTANT(bool, value = sizeof(detail::is_write_buffered_helper((Stream*)0)) == 1); #endif }; } // namespace asio } // namespace boost #include <boost/asio/detail/pop_options.hpp> #endif // BOOST_ASIO_IS_WRITE_BUFFERED_HPP
hpp
asio
data/projects/asio/include/boost/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 BOOST_ASIO_BIND_ALLOCATOR_HPP #define BOOST_ASIO_BIND_ALLOCATOR_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <boost/asio/detail/config.hpp> #include <boost/asio/detail/type_traits.hpp> #include <boost/asio/associated_allocator.hpp> #include <boost/asio/associator.hpp> #include <boost/asio/async_result.hpp> #include <boost/asio/detail/push_options.hpp> namespace boost { 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_; }; /// Associate an object of type @c T with an allocator of type /// @c Allocator. template <typename Allocator, typename T> BOOST_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 { template <typename Init> init_wrapper(const Allocator& allocator, Init&& init) : allocator_(allocator), initiation_(static_cast<Init&&>(init)) { } template <typename Handler, typename... Args> void operator()(Handler&& handler, Args&&... args) { static_cast<Initiation&&>(initiation_)( allocator_binder<decay_t<Handler>, Allocator>( allocator_, static_cast<Handler&&>(handler)), static_cast<Args&&>(args)...); } template <typename Handler, typename... Args> void operator()(Handler&& handler, Args&&... args) const { initiation_( allocator_binder<decay_t<Handler>, Allocator>( allocator_, static_cast<Handler&&>(handler)), static_cast<Args&&>(args)...); } Allocator allocator_; Initiation initiation_; }; template <typename Initiation, typename RawCompletionToken, typename... Args> static auto initiate(Initiation&& initiation, RawCompletionToken&& token, Args&&... args) -> decltype( async_initiate<T, Signature>( declval<init_wrapper<decay_t<Initiation>>>(), token.get(), static_cast<Args&&>(args)...)) { return async_initiate<T, Signature>( init_wrapper<decay_t<Initiation>>(token.get_allocator(), static_cast<Initiation&&>(initiation)), token.get(), static_cast<Args&&>(args)...); } private: async_result(const async_result&) = delete; async_result& operator=(const async_result&) = delete; async_result<T, Signature> target_; }; 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 } // namespace boost #include <boost/asio/detail/pop_options.hpp> #endif // BOOST_ASIO_BIND_ALLOCATOR_HPP
hpp
asio
data/projects/asio/include/boost/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 BOOST_ASIO_POST_HPP #define BOOST_ASIO_POST_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <boost/asio/detail/config.hpp> #include <boost/asio/async_result.hpp> #include <boost/asio/detail/initiate_post.hpp> #include <boost/asio/detail/type_traits.hpp> #include <boost/asio/execution_context.hpp> #include <boost/asio/execution/blocking.hpp> #include <boost/asio/execution/executor.hpp> #include <boost/asio/is_executor.hpp> #include <boost/asio/require.hpp> #include <boost/asio/detail/push_options.hpp> namespace boost { 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 <BOOST_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, BOOST_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, BOOST_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 } // namespace boost #include <boost/asio/detail/pop_options.hpp> #endif // BOOST_ASIO_POST_HPP
hpp
asio
data/projects/asio/include/boost/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 BOOST_ASIO_BUFFER_REGISTRATION_HPP #define BOOST_ASIO_BUFFER_REGISTRATION_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <boost/asio/detail/config.hpp> #include <iterator> #include <utility> #include <vector> #include <boost/asio/detail/memory.hpp> #include <boost/asio/execution/context.hpp> #include <boost/asio/execution/executor.hpp> #include <boost/asio/execution_context.hpp> #include <boost/asio/is_executor.hpp> #include <boost/asio/query.hpp> #include <boost/asio/registered_buffer.hpp> #if defined(BOOST_ASIO_HAS_IO_URING) # include <boost/asio/detail/scheduler.hpp> # include <boost/asio/detail/io_uring_service.hpp> #endif // defined(BOOST_ASIO_HAS_IO_URING) #include <boost/asio/detail/push_options.hpp> namespace boost { 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_( BOOST_ASIO_REBIND_ALLOC(allocator_type, mutable_registered_buffer)(alloc)) { init_buffers(buffer_registration::get_context(ex), boost::asio::buffer_sequence_begin(buffer_sequence_), boost::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_( BOOST_ASIO_REBIND_ALLOC(allocator_type, mutable_registered_buffer)(alloc)) { init_buffers(ctx, boost::asio::buffer_sequence_begin(buffer_sequence_), boost::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(BOOST_ASIO_HAS_IO_URING) service_ = other.service_; other.service_ = 0; #endif // defined(BOOST_ASIO_HAS_IO_URING) } /// Unregisters the buffers. ~buffer_registration() { #if defined(BOOST_ASIO_HAS_IO_URING) if (service_) service_->unregister_buffers(); #endif // defined(BOOST_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(BOOST_ASIO_HAS_IO_URING) if (service_) service_->unregister_buffers(); service_ = other.service_; other.service_ = 0; #endif // defined(BOOST_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 boost::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(BOOST_ASIO_HAS_IO_URING) service_ = &use_service<detail::io_uring_service>(ctx); std::vector<iovec, BOOST_ASIO_REBIND_ALLOC(allocator_type, iovec)> iovecs(n, BOOST_ASIO_REBIND_ALLOC(allocator_type, iovec)( buffers_.get_allocator())); #endif // defined(BOOST_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(BOOST_ASIO_HAS_IO_URING) iovecs[i].iov_base = buffers_[i].data(); iovecs[i].iov_len = buffers_[i].size(); #endif // defined(BOOST_ASIO_HAS_IO_URING) } #if defined(BOOST_ASIO_HAS_IO_URING) if (n > 0) { service_->register_buffers(&iovecs[0], static_cast<unsigned>(iovecs.size())); } #endif // defined(BOOST_ASIO_HAS_IO_URING) } MutableBufferSequence buffer_sequence_; std::vector<mutable_registered_buffer, BOOST_ASIO_REBIND_ALLOC(allocator_type, mutable_registered_buffer)> buffers_; #if defined(BOOST_ASIO_HAS_IO_URING) detail::io_uring_service* service_; #endif // defined(BOOST_ASIO_HAS_IO_URING) }; /// Register buffers with an execution context. template <typename Executor, typename MutableBufferSequence> BOOST_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> BOOST_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> BOOST_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> BOOST_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 } // namespace boost #include <boost/asio/detail/pop_options.hpp> #endif // BOOST_ASIO_BUFFER_REGISTRATION_HPP
hpp
asio
data/projects/asio/include/boost/asio/detached.hpp
// // detached.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 BOOST_ASIO_DETACHED_HPP #define BOOST_ASIO_DETACHED_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <boost/asio/detail/config.hpp> #include <memory> #include <boost/asio/detail/type_traits.hpp> #include <boost/asio/detail/push_options.hpp> namespace boost { namespace asio { /// A @ref completion_token type used to specify that an asynchronous operation /// is detached. /** * The detached_t class is used to indicate that an asynchronous operation is * detached. That is, there is no completion handler waiting for the * operation's result. A detached_t object may be passed as a handler to an * asynchronous operation, typically using the special value * @c boost::asio::detached. For example: * * @code my_socket.async_send(my_buffer, boost::asio::detached); * @endcode */ class detached_t { public: /// Constructor. constexpr detached_t() { } /// Adapts an executor to add the @c detached_t completion token as the /// default. template <typename InnerExecutor> struct executor_with_default : InnerExecutor { /// Specify @c detached_t as the default completion token type. typedef detached_t default_completion_token_type; /// Construct the adapted executor from the inner executor type. executor_with_default(const InnerExecutor& ex) noexcept : InnerExecutor(ex) { } /// Convert the specified executor to the inner executor type, then use /// that to construct the adapted executor. template <typename OtherExecutor> executor_with_default(const OtherExecutor& ex, constraint_t< is_convertible<OtherExecutor, InnerExecutor>::value > = 0) noexcept : InnerExecutor(ex) { } }; /// Type alias to adapt an I/O object to use @c detached_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 detached_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)); } }; /// A @ref completion_token object used to specify that an asynchronous /// operation is detached. /** * See the documentation for boost::asio::detached_t for a usage example. */ constexpr detached_t detached; } // namespace asio } // namespace boost #include <boost/asio/detail/pop_options.hpp> #include <boost/asio/impl/detached.hpp> #endif // BOOST_ASIO_DETACHED_HPP
hpp
asio
data/projects/asio/include/boost/asio/system_context.hpp
// // system_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 BOOST_ASIO_SYSTEM_CONTEXT_HPP #define BOOST_ASIO_SYSTEM_CONTEXT_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <boost/asio/detail/config.hpp> #include <boost/asio/detail/scheduler.hpp> #include <boost/asio/detail/thread_group.hpp> #include <boost/asio/execution.hpp> #include <boost/asio/execution_context.hpp> #include <boost/asio/detail/push_options.hpp> namespace boost { namespace asio { template <typename Blocking, typename Relationship, typename Allocator> class basic_system_executor; /// The executor context for the system executor. class system_context : public execution_context { public: /// The executor type associated with the context. typedef basic_system_executor< execution::blocking_t::possibly_t, execution::relationship_t::fork_t, std::allocator<void> > executor_type; /// Destructor shuts down all threads in the system thread pool. BOOST_ASIO_DECL ~system_context(); /// Obtain an executor for the context. executor_type get_executor() noexcept; /// Signal all threads in the system thread pool to stop. BOOST_ASIO_DECL void stop(); /// Determine whether the system thread pool has been stopped. BOOST_ASIO_DECL bool stopped() const noexcept; /// Join all threads in the system thread pool. BOOST_ASIO_DECL void join(); #if defined(GENERATING_DOCUMENTATION) private: #endif // defined(GENERATING_DOCUMENTATION) // Constructor creates all threads in the system thread pool. BOOST_ASIO_DECL system_context(); private: template <typename, typename, typename> friend class basic_system_executor; struct thread_function; // Helper function to create the underlying scheduler. BOOST_ASIO_DECL detail::scheduler& add_scheduler(detail::scheduler* s); // The underlying scheduler. detail::scheduler& scheduler_; // The threads in the system thread pool. detail::thread_group threads_; // The number of threads in the pool. std::size_t num_threads_; }; } // namespace asio } // namespace boost #include <boost/asio/detail/pop_options.hpp> #include <boost/asio/impl/system_context.hpp> #if defined(BOOST_ASIO_HEADER_ONLY) # include <boost/asio/impl/system_context.ipp> #endif // defined(BOOST_ASIO_HEADER_ONLY) #endif // BOOST_ASIO_SYSTEM_CONTEXT_HPP
hpp
asio
data/projects/asio/include/boost/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 BOOST_ASIO_SSL_HPP #define BOOST_ASIO_SSL_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <boost/asio/ssl/context.hpp> #include <boost/asio/ssl/context_base.hpp> #include <boost/asio/ssl/error.hpp> #include <boost/asio/ssl/rfc2818_verification.hpp> #include <boost/asio/ssl/host_name_verification.hpp> #include <boost/asio/ssl/stream.hpp> #include <boost/asio/ssl/stream_base.hpp> #include <boost/asio/ssl/verify_context.hpp> #include <boost/asio/ssl/verify_mode.hpp> #endif // BOOST_ASIO_SSL_HPP
hpp
asio
data/projects/asio/include/boost/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 BOOST_ASIO_HANDLER_CONTINUATION_HOOK_HPP #define BOOST_ASIO_HANDLER_CONTINUATION_HOOK_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <boost/asio/detail/config.hpp> #include <boost/asio/detail/push_options.hpp> namespace boost { 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 } // namespace boost #include <boost/asio/detail/pop_options.hpp> #endif // BOOST_ASIO_HANDLER_CONTINUATION_HOOK_HPP
hpp
asio
data/projects/asio/include/boost/asio/placeholders.hpp
// // placeholders.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 BOOST_ASIO_PLACEHOLDERS_HPP #define BOOST_ASIO_PLACEHOLDERS_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <boost/asio/detail/config.hpp> #include <boost/asio/detail/functional.hpp> #include <boost/asio/detail/push_options.hpp> namespace boost { namespace asio { namespace placeholders { #if defined(GENERATING_DOCUMENTATION) /// An argument placeholder, for use with std::bind() or boost::bind(), that /// corresponds to the error argument of a handler for any of the asynchronous /// functions. unspecified error; /// An argument placeholder, for use with std::bind() or boost::bind(), that /// corresponds to the bytes_transferred argument of a handler for asynchronous /// functions such as boost::asio::basic_stream_socket::async_write_some or /// boost::asio::async_write. unspecified bytes_transferred; /// An argument placeholder, for use with std::bind() or boost::bind(), that /// corresponds to the iterator argument of a handler for asynchronous functions /// such as boost::asio::async_connect. unspecified iterator; /// An argument placeholder, for use with std::bind() or boost::bind(), that /// corresponds to the results argument of a handler for asynchronous functions /// such as boost::asio::basic_resolver::async_resolve. unspecified results; /// An argument placeholder, for use with std::bind() or boost::bind(), that /// corresponds to the results argument of a handler for asynchronous functions /// such as boost::asio::async_connect. unspecified endpoint; /// An argument placeholder, for use with std::bind() or boost::bind(), that /// corresponds to the signal_number argument of a handler for asynchronous /// functions such as boost::asio::signal_set::async_wait. unspecified signal_number; #else static constexpr auto& error = std::placeholders::_1; static constexpr auto& bytes_transferred = std::placeholders::_2; static constexpr auto& iterator = std::placeholders::_2; static constexpr auto& results = std::placeholders::_2; static constexpr auto& endpoint = std::placeholders::_2; static constexpr auto& signal_number = std::placeholders::_2; #endif } // namespace placeholders } // namespace asio } // namespace boost #include <boost/asio/detail/pop_options.hpp> #endif // BOOST_ASIO_PLACEHOLDERS_HPP
hpp
asio
data/projects/asio/include/boost/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 BOOST_ASIO_CANCELLATION_TYPE_HPP #define BOOST_ASIO_CANCELLATION_TYPE_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <boost/asio/detail/config.hpp> #include <boost/asio/detail/push_options.hpp> namespace boost { 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 } // namespace boost #include <boost/asio/detail/pop_options.hpp> #endif // BOOST_ASIO_CANCELLATION_TYPE_HPP
hpp
asio
data/projects/asio/include/boost/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 BOOST_ASIO_PREPEND_HPP #define BOOST_ASIO_PREPEND_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <boost/asio/detail/config.hpp> #include <tuple> #include <boost/asio/detail/type_traits.hpp> #include <boost/asio/detail/push_options.hpp> namespace boost { 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> BOOST_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 } // namespace boost #include <boost/asio/detail/pop_options.hpp> #include <boost/asio/impl/prepend.hpp> #endif // BOOST_ASIO_PREPEND_HPP
hpp
asio
data/projects/asio/include/boost/asio/basic_socket.hpp
// // basic_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 BOOST_ASIO_BASIC_SOCKET_HPP #define BOOST_ASIO_BASIC_SOCKET_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <utility> #include <boost/asio/any_io_executor.hpp> #include <boost/asio/detail/config.hpp> #include <boost/asio/async_result.hpp> #include <boost/asio/detail/handler_type_requirements.hpp> #include <boost/asio/detail/io_object_impl.hpp> #include <boost/asio/detail/non_const_lvalue.hpp> #include <boost/asio/detail/throw_error.hpp> #include <boost/asio/detail/type_traits.hpp> #include <boost/asio/error.hpp> #include <boost/asio/execution_context.hpp> #include <boost/asio/post.hpp> #include <boost/asio/socket_base.hpp> #if defined(BOOST_ASIO_WINDOWS_RUNTIME) # include <boost/asio/detail/null_socket_service.hpp> #elif defined(BOOST_ASIO_HAS_IOCP) # include <boost/asio/detail/win_iocp_socket_service.hpp> #elif defined(BOOST_ASIO_HAS_IO_URING_AS_DEFAULT) # include <boost/asio/detail/io_uring_socket_service.hpp> #else # include <boost/asio/detail/reactive_socket_service.hpp> #endif #include <boost/asio/detail/push_options.hpp> namespace boost { namespace asio { #if !defined(BOOST_ASIO_BASIC_SOCKET_FWD_DECL) #define BOOST_ASIO_BASIC_SOCKET_FWD_DECL // Forward declaration with defaulted arguments. template <typename Protocol, typename Executor = any_io_executor> class basic_socket; #endif // !defined(BOOST_ASIO_BASIC_SOCKET_FWD_DECL) /// Provides socket functionality. /** * The basic_socket class template provides functionality that is common to both * stream-oriented and datagram-oriented sockets. * * @par Thread Safety * @e Distinct @e objects: Safe.@n * @e Shared @e objects: Unsafe. */ template <typename Protocol, typename Executor> class basic_socket : public socket_base { private: class initiate_async_connect; class initiate_async_wait; 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_socket<Protocol, Executor1> other; }; /// The native representation of a socket. #if defined(GENERATING_DOCUMENTATION) typedef implementation_defined native_handle_type; #elif defined(BOOST_ASIO_WINDOWS_RUNTIME) typedef typename detail::null_socket_service< Protocol>::native_handle_type native_handle_type; #elif defined(BOOST_ASIO_HAS_IOCP) typedef typename detail::win_iocp_socket_service< Protocol>::native_handle_type native_handle_type; #elif defined(BOOST_ASIO_HAS_IO_URING_AS_DEFAULT) typedef typename detail::io_uring_socket_service< Protocol>::native_handle_type native_handle_type; #else typedef typename detail::reactive_socket_service< Protocol>::native_handle_type native_handle_type; #endif /// The protocol type. typedef Protocol protocol_type; /// The endpoint type. typedef typename Protocol::endpoint endpoint_type; #if !defined(BOOST_ASIO_NO_EXTENSIONS) /// A basic_socket is always the lowest layer. typedef basic_socket<Protocol, Executor> lowest_layer_type; #endif // !defined(BOOST_ASIO_NO_EXTENSIONS) /// Construct a basic_socket without opening it. /** * This constructor creates a socket without opening 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_socket(const executor_type& ex) : impl_(0, ex) { } /// Construct a basic_socket without opening it. /** * This constructor creates a socket without opening 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_socket(ExecutionContext& context, constraint_t< is_convertible<ExecutionContext&, execution_context&>::value > = 0) : impl_(0, 0, context) { } /// Construct and open a basic_socket. /** * This constructor creates and opens a 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 boost::system::system_error Thrown on failure. */ basic_socket(const executor_type& ex, const protocol_type& protocol) : impl_(0, ex) { boost::system::error_code ec; impl_.get_service().open(impl_.get_implementation(), protocol, ec); boost::asio::detail::throw_error(ec, "open"); } /// Construct and open a basic_socket. /** * This constructor creates and opens a 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 boost::system::system_error Thrown on failure. */ template <typename ExecutionContext> basic_socket(ExecutionContext& context, const protocol_type& protocol, constraint_t< is_convertible<ExecutionContext&, execution_context&>::value, defaulted_constraint > = defaulted_constraint()) : impl_(0, 0, context) { boost::system::error_code ec; impl_.get_service().open(impl_.get_implementation(), protocol, ec); boost::asio::detail::throw_error(ec, "open"); } /// Construct a basic_socket, opening it and binding it to the given local /// endpoint. /** * This constructor creates a 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 socket will * be bound. * * @throws boost::system::system_error Thrown on failure. */ basic_socket(const executor_type& ex, const endpoint_type& endpoint) : impl_(0, ex) { boost::system::error_code ec; const protocol_type protocol = endpoint.protocol(); impl_.get_service().open(impl_.get_implementation(), protocol, ec); boost::asio::detail::throw_error(ec, "open"); impl_.get_service().bind(impl_.get_implementation(), endpoint, ec); boost::asio::detail::throw_error(ec, "bind"); } /// Construct a basic_socket, opening it and binding it to the given local /// endpoint. /** * This constructor creates a 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 socket will * be bound. * * @throws boost::system::system_error Thrown on failure. */ template <typename ExecutionContext> basic_socket(ExecutionContext& context, const endpoint_type& endpoint, constraint_t< is_convertible<ExecutionContext&, execution_context&>::value > = 0) : impl_(0, 0, context) { boost::system::error_code ec; const protocol_type protocol = endpoint.protocol(); impl_.get_service().open(impl_.get_implementation(), protocol, ec); boost::asio::detail::throw_error(ec, "open"); impl_.get_service().bind(impl_.get_implementation(), endpoint, ec); boost::asio::detail::throw_error(ec, "bind"); } /// Construct a basic_socket on an existing native socket. /** * This constructor creates a 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 A native socket. * * @throws boost::system::system_error Thrown on failure. */ basic_socket(const executor_type& ex, const protocol_type& protocol, const native_handle_type& native_socket) : impl_(0, ex) { boost::system::error_code ec; impl_.get_service().assign(impl_.get_implementation(), protocol, native_socket, ec); boost::asio::detail::throw_error(ec, "assign"); } /// Construct a basic_socket on an existing native socket. /** * This constructor creates a 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 A native socket. * * @throws boost::system::system_error Thrown on failure. */ template <typename ExecutionContext> basic_socket(ExecutionContext& context, const protocol_type& protocol, const native_handle_type& native_socket, constraint_t< is_convertible<ExecutionContext&, execution_context&>::value > = 0) : impl_(0, 0, context) { boost::system::error_code ec; impl_.get_service().assign(impl_.get_implementation(), protocol, native_socket, ec); boost::asio::detail::throw_error(ec, "assign"); } /// Move-construct a basic_socket from another. /** * This constructor moves a socket from one object to another. * * @param other The other basic_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_socket(const executor_type&) constructor. */ basic_socket(basic_socket&& other) noexcept : impl_(std::move(other.impl_)) { } /// Move-assign a basic_socket from another. /** * This assignment operator moves a socket from one object to another. * * @param other The other basic_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_socket(const executor_type&) constructor. */ basic_socket& operator=(basic_socket&& other) { impl_ = std::move(other.impl_); return *this; } // All sockets have access to each other's implementations. template <typename Protocol1, typename Executor1> friend class basic_socket; /// Move-construct a basic_socket from a socket of another protocol type. /** * This constructor moves a socket from one object to another. * * @param other The other basic_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_socket(const executor_type&) constructor. */ template <typename Protocol1, typename Executor1> basic_socket(basic_socket<Protocol1, Executor1>&& other, constraint_t< is_convertible<Protocol1, Protocol>::value && is_convertible<Executor1, Executor>::value > = 0) : impl_(std::move(other.impl_)) { } /// Move-assign a basic_socket from a socket of another protocol type. /** * This assignment operator moves a socket from one object to another. * * @param other The other basic_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_socket(const executor_type&) constructor. */ template <typename Protocol1, typename Executor1> constraint_t< is_convertible<Protocol1, Protocol>::value && is_convertible<Executor1, Executor>::value, basic_socket& > operator=(basic_socket<Protocol1, Executor1>&& other) { basic_socket tmp(std::move(other)); impl_ = std::move(tmp.impl_); return *this; } /// Get the executor associated with the object. const executor_type& get_executor() noexcept { return impl_.get_executor(); } #if !defined(BOOST_ASIO_NO_EXTENSIONS) /// Get a reference to the lowest layer. /** * This function returns a reference to the lowest layer in a stack of * layers. Since a basic_socket 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_socket 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; } #endif // !defined(BOOST_ASIO_NO_EXTENSIONS) /// Open the socket using the specified protocol. /** * This function opens the socket so that it will use the specified protocol. * * @param protocol An object specifying protocol parameters to be used. * * @throws boost::system::system_error Thrown on failure. * * @par Example * @code * boost::asio::ip::tcp::socket socket(my_context); * socket.open(boost::asio::ip::tcp::v4()); * @endcode */ void open(const protocol_type& protocol = protocol_type()) { boost::system::error_code ec; impl_.get_service().open(impl_.get_implementation(), protocol, ec); boost::asio::detail::throw_error(ec, "open"); } /// Open the socket using the specified protocol. /** * This function opens the socket so that it will use the specified protocol. * * @param protocol An object specifying which protocol is to be used. * * @param ec Set to indicate what error occurred, if any. * * @par Example * @code * boost::asio::ip::tcp::socket socket(my_context); * boost::system::error_code ec; * socket.open(boost::asio::ip::tcp::v4(), ec); * if (ec) * { * // An error occurred. * } * @endcode */ BOOST_ASIO_SYNC_OP_VOID open(const protocol_type& protocol, boost::system::error_code& ec) { impl_.get_service().open(impl_.get_implementation(), protocol, ec); BOOST_ASIO_SYNC_OP_VOID_RETURN(ec); } /// Assign an existing native socket to the socket. /* * This function opens the socket to hold an existing native socket. * * @param protocol An object specifying which protocol is to be used. * * @param native_socket A native socket. * * @throws boost::system::system_error Thrown on failure. */ void assign(const protocol_type& protocol, const native_handle_type& native_socket) { boost::system::error_code ec; impl_.get_service().assign(impl_.get_implementation(), protocol, native_socket, ec); boost::asio::detail::throw_error(ec, "assign"); } /// Assign an existing native socket to the socket. /* * This function opens the socket to hold an existing native socket. * * @param protocol An object specifying which protocol is to be used. * * @param native_socket A native socket. * * @param ec Set to indicate what error occurred, if any. */ BOOST_ASIO_SYNC_OP_VOID assign(const protocol_type& protocol, const native_handle_type& native_socket, boost::system::error_code& ec) { impl_.get_service().assign(impl_.get_implementation(), protocol, native_socket, ec); BOOST_ASIO_SYNC_OP_VOID_RETURN(ec); } /// Determine whether the socket is open. bool is_open() const { return impl_.get_service().is_open(impl_.get_implementation()); } /// Close the socket. /** * This function is used to close the socket. Any asynchronous send, receive * or connect operations will be cancelled immediately, and will complete * with the boost::asio::error::operation_aborted error. * * @throws boost::system::system_error Thrown on failure. Note that, even if * the function indicates an error, the underlying descriptor is closed. * * @note For portable behaviour with respect to graceful closure of a * connected socket, call shutdown() before closing the socket. */ void close() { boost::system::error_code ec; impl_.get_service().close(impl_.get_implementation(), ec); boost::asio::detail::throw_error(ec, "close"); } /// Close the socket. /** * This function is used to close the socket. Any asynchronous send, receive * or connect operations will be cancelled immediately, and will complete * with the boost::asio::error::operation_aborted error. * * @param ec Set to indicate what error occurred, if any. Note that, even if * the function indicates an error, the underlying descriptor is closed. * * @par Example * @code * boost::asio::ip::tcp::socket socket(my_context); * ... * boost::system::error_code ec; * socket.close(ec); * if (ec) * { * // An error occurred. * } * @endcode * * @note For portable behaviour with respect to graceful closure of a * connected socket, call shutdown() before closing the socket. */ BOOST_ASIO_SYNC_OP_VOID close(boost::system::error_code& ec) { impl_.get_service().close(impl_.get_implementation(), ec); BOOST_ASIO_SYNC_OP_VOID_RETURN(ec); } /// Release ownership of the underlying native socket. /** * This function causes all outstanding asynchronous connect, send and receive * operations to finish immediately, and the handlers for cancelled operations * will be passed the boost::asio::error::operation_aborted error. Ownership * of the native socket is then transferred to the caller. * * @throws boost::system::system_error Thrown on failure. * * @note This function is unsupported on Windows versions prior to Windows * 8.1, and will fail with boost::asio::error::operation_not_supported on * these platforms. */ #if defined(BOOST_ASIO_MSVC) && (BOOST_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() { boost::system::error_code ec; native_handle_type s = impl_.get_service().release( impl_.get_implementation(), ec); boost::asio::detail::throw_error(ec, "release"); return s; } /// Release ownership of the underlying native socket. /** * This function causes all outstanding asynchronous connect, send and receive * operations to finish immediately, and the handlers for cancelled operations * will be passed the boost::asio::error::operation_aborted error. Ownership * of the native socket 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 boost::asio::error::operation_not_supported on * these platforms. */ #if defined(BOOST_ASIO_MSVC) && (BOOST_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(boost::system::error_code& ec) { return impl_.get_service().release(impl_.get_implementation(), ec); } /// Get the native socket representation. /** * This function may be used to obtain the underlying representation of the * socket. This is intended to allow access to native socket 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 socket. /** * This function causes all outstanding asynchronous connect, send and receive * operations to finish immediately, and the handlers for cancelled operations * will be passed the boost::asio::error::operation_aborted error. * * @throws boost::system::system_error Thrown on failure. * * @note Calls to cancel() will always fail with * boost::asio::error::operation_not_supported when run on Windows XP, Windows * Server 2003, and earlier versions of Windows, unless * BOOST_ASIO_ENABLE_CANCELIO is defined. However, the CancelIo function has * two issues that should be considered before enabling its use: * * @li It will only cancel asynchronous operations that were initiated in the * current thread. * * @li It can appear to complete without error, but the request to cancel the * unfinished operations may be silently ignored by the operating system. * Whether it works or not seems to depend on the drivers that are installed. * * For portable cancellation, consider using one of the following * alternatives: * * @li Disable asio's I/O completion port backend by defining * BOOST_ASIO_DISABLE_IOCP. * * @li Use the close() function to simultaneously cancel the outstanding * operations and close the socket. * * When running on Windows Vista, Windows Server 2008, and later, the * CancelIoEx function is always used. This function does not have the * problems described above. */ #if defined(BOOST_ASIO_MSVC) && (BOOST_ASIO_MSVC >= 1400) \ && (!defined(_WIN32_WINNT) || _WIN32_WINNT < 0x0600) \ && !defined(BOOST_ASIO_ENABLE_CANCELIO) __declspec(deprecated("By default, this function always fails with " "operation_not_supported when used on Windows XP, Windows Server 2003, " "or earlier. Consult documentation for details.")) #endif void cancel() { boost::system::error_code ec; impl_.get_service().cancel(impl_.get_implementation(), ec); boost::asio::detail::throw_error(ec, "cancel"); } /// Cancel all asynchronous operations associated with the socket. /** * This function causes all outstanding asynchronous connect, send and receive * operations to finish immediately, and the handlers for cancelled operations * will be passed the boost::asio::error::operation_aborted error. * * @param ec Set to indicate what error occurred, if any. * * @note Calls to cancel() will always fail with * boost::asio::error::operation_not_supported when run on Windows XP, Windows * Server 2003, and earlier versions of Windows, unless * BOOST_ASIO_ENABLE_CANCELIO is defined. However, the CancelIo function has * two issues that should be considered before enabling its use: * * @li It will only cancel asynchronous operations that were initiated in the * current thread. * * @li It can appear to complete without error, but the request to cancel the * unfinished operations may be silently ignored by the operating system. * Whether it works or not seems to depend on the drivers that are installed. * * For portable cancellation, consider using one of the following * alternatives: * * @li Disable asio's I/O completion port backend by defining * BOOST_ASIO_DISABLE_IOCP. * * @li Use the close() function to simultaneously cancel the outstanding * operations and close the socket. * * When running on Windows Vista, Windows Server 2008, and later, the * CancelIoEx function is always used. This function does not have the * problems described above. */ #if defined(BOOST_ASIO_MSVC) && (BOOST_ASIO_MSVC >= 1400) \ && (!defined(_WIN32_WINNT) || _WIN32_WINNT < 0x0600) \ && !defined(BOOST_ASIO_ENABLE_CANCELIO) __declspec(deprecated("By default, this function always fails with " "operation_not_supported when used on Windows XP, Windows Server 2003, " "or earlier. Consult documentation for details.")) #endif BOOST_ASIO_SYNC_OP_VOID cancel(boost::system::error_code& ec) { impl_.get_service().cancel(impl_.get_implementation(), ec); BOOST_ASIO_SYNC_OP_VOID_RETURN(ec); } /// Determine whether the socket is at the out-of-band data mark. /** * This function is used to check whether the socket input is currently * positioned at the out-of-band data mark. * * @return A bool indicating whether the socket is at the out-of-band data * mark. * * @throws boost::system::system_error Thrown on failure. */ bool at_mark() const { boost::system::error_code ec; bool b = impl_.get_service().at_mark(impl_.get_implementation(), ec); boost::asio::detail::throw_error(ec, "at_mark"); return b; } /// Determine whether the socket is at the out-of-band data mark. /** * This function is used to check whether the socket input is currently * positioned at the out-of-band data mark. * * @param ec Set to indicate what error occurred, if any. * * @return A bool indicating whether the socket is at the out-of-band data * mark. */ bool at_mark(boost::system::error_code& ec) const { return impl_.get_service().at_mark(impl_.get_implementation(), ec); } /// Determine the number of bytes available for reading. /** * This function is used to determine the number of bytes that may be read * without blocking. * * @return The number of bytes that may be read without blocking, or 0 if an * error occurs. * * @throws boost::system::system_error Thrown on failure. */ std::size_t available() const { boost::system::error_code ec; std::size_t s = impl_.get_service().available( impl_.get_implementation(), ec); boost::asio::detail::throw_error(ec, "available"); return s; } /// Determine the number of bytes available for reading. /** * This function is used to determine the number of bytes that may be read * without blocking. * * @param ec Set to indicate what error occurred, if any. * * @return The number of bytes that may be read without blocking, or 0 if an * error occurs. */ std::size_t available(boost::system::error_code& ec) const { return impl_.get_service().available(impl_.get_implementation(), ec); } /// Bind the socket to the given local endpoint. /** * This function binds the socket to the specified endpoint on the local * machine. * * @param endpoint An endpoint on the local machine to which the socket will * be bound. * * @throws boost::system::system_error Thrown on failure. * * @par Example * @code * boost::asio::ip::tcp::socket socket(my_context); * socket.open(boost::asio::ip::tcp::v4()); * socket.bind(boost::asio::ip::tcp::endpoint( * boost::asio::ip::tcp::v4(), 12345)); * @endcode */ void bind(const endpoint_type& endpoint) { boost::system::error_code ec; impl_.get_service().bind(impl_.get_implementation(), endpoint, ec); boost::asio::detail::throw_error(ec, "bind"); } /// Bind the socket to the given local endpoint. /** * This function binds the socket to the specified endpoint on the local * machine. * * @param endpoint An endpoint on the local machine to which the socket will * be bound. * * @param ec Set to indicate what error occurred, if any. * * @par Example * @code * boost::asio::ip::tcp::socket socket(my_context); * socket.open(boost::asio::ip::tcp::v4()); * boost::system::error_code ec; * socket.bind(boost::asio::ip::tcp::endpoint( * boost::asio::ip::tcp::v4(), 12345), ec); * if (ec) * { * // An error occurred. * } * @endcode */ BOOST_ASIO_SYNC_OP_VOID bind(const endpoint_type& endpoint, boost::system::error_code& ec) { impl_.get_service().bind(impl_.get_implementation(), endpoint, ec); BOOST_ASIO_SYNC_OP_VOID_RETURN(ec); } /// Connect the socket to the specified endpoint. /** * This function is used to connect a socket to the specified remote endpoint. * The function call will block until the connection is successfully made or * an error occurs. * * The socket is automatically opened if it is not already open. If the * connect fails, and the socket was automatically opened, the socket is * not returned to the closed state. * * @param peer_endpoint The remote endpoint to which the socket will be * connected. * * @throws boost::system::system_error Thrown on failure. * * @par Example * @code * boost::asio::ip::tcp::socket socket(my_context); * boost::asio::ip::tcp::endpoint endpoint( * boost::asio::ip::address::from_string("1.2.3.4"), 12345); * socket.connect(endpoint); * @endcode */ void connect(const endpoint_type& peer_endpoint) { boost::system::error_code ec; if (!is_open()) { impl_.get_service().open(impl_.get_implementation(), peer_endpoint.protocol(), ec); boost::asio::detail::throw_error(ec, "connect"); } impl_.get_service().connect(impl_.get_implementation(), peer_endpoint, ec); boost::asio::detail::throw_error(ec, "connect"); } /// Connect the socket to the specified endpoint. /** * This function is used to connect a socket to the specified remote endpoint. * The function call will block until the connection is successfully made or * an error occurs. * * The socket is automatically opened if it is not already open. If the * connect fails, and the socket was automatically opened, the socket is * not returned to the closed state. * * @param peer_endpoint The remote endpoint to which the socket will be * connected. * * @param ec Set to indicate what error occurred, if any. * * @par Example * @code * boost::asio::ip::tcp::socket socket(my_context); * boost::asio::ip::tcp::endpoint endpoint( * boost::asio::ip::address::from_string("1.2.3.4"), 12345); * boost::system::error_code ec; * socket.connect(endpoint, ec); * if (ec) * { * // An error occurred. * } * @endcode */ BOOST_ASIO_SYNC_OP_VOID connect(const endpoint_type& peer_endpoint, boost::system::error_code& ec) { if (!is_open()) { impl_.get_service().open(impl_.get_implementation(), peer_endpoint.protocol(), ec); if (ec) { BOOST_ASIO_SYNC_OP_VOID_RETURN(ec); } } impl_.get_service().connect(impl_.get_implementation(), peer_endpoint, ec); BOOST_ASIO_SYNC_OP_VOID_RETURN(ec); } /// Start an asynchronous connect. /** * This function is used to asynchronously connect a socket to the specified * remote endpoint. It is an initiating function for an @ref * asynchronous_operation, and always returns immediately. * * The socket is automatically opened if it is not already open. If the * connect fails, and the socket was automatically opened, the socket is * not returned to the closed state. * * @param peer_endpoint The remote endpoint to which the socket will be * connected. Copies will be made of the endpoint object as required. * * @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( * const boost::system::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 boost::asio::post(). * * @par Completion Signature * @code void(boost::system::error_code) @endcode * * @par Example * @code * void connect_handler(const boost::system::error_code& error) * { * if (!error) * { * // Connect succeeded. * } * } * * ... * * boost::asio::ip::tcp::socket socket(my_context); * boost::asio::ip::tcp::endpoint endpoint( * boost::asio::ip::address::from_string("1.2.3.4"), 12345); * socket.async_connect(endpoint, connect_handler); * @endcode * * @par Per-Operation Cancellation * On POSIX or Windows operating systems, this asynchronous operation supports * cancellation for the following boost::asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * @li @c cancellation_type::total */ template < BOOST_ASIO_COMPLETION_TOKEN_FOR(void (boost::system::error_code)) ConnectToken = default_completion_token_t<executor_type>> auto async_connect(const endpoint_type& peer_endpoint, ConnectToken&& token = default_completion_token_t<executor_type>()) -> decltype( async_initiate<ConnectToken, void (boost::system::error_code)>( declval<initiate_async_connect>(), token, peer_endpoint, declval<boost::system::error_code&>())) { boost::system::error_code open_ec; if (!is_open()) { const protocol_type protocol = peer_endpoint.protocol(); impl_.get_service().open(impl_.get_implementation(), protocol, open_ec); } return async_initiate<ConnectToken, void (boost::system::error_code)>( initiate_async_connect(this), token, peer_endpoint, open_ec); } /// Set an option on the socket. /** * This function is used to set an option on the socket. * * @param option The new option value to be set on the socket. * * @throws boost::system::system_error Thrown on failure. * * @sa SettableSocketOption @n * boost::asio::socket_base::broadcast @n * boost::asio::socket_base::do_not_route @n * boost::asio::socket_base::keep_alive @n * boost::asio::socket_base::linger @n * boost::asio::socket_base::receive_buffer_size @n * boost::asio::socket_base::receive_low_watermark @n * boost::asio::socket_base::reuse_address @n * boost::asio::socket_base::send_buffer_size @n * boost::asio::socket_base::send_low_watermark @n * boost::asio::ip::multicast::join_group @n * boost::asio::ip::multicast::leave_group @n * boost::asio::ip::multicast::enable_loopback @n * boost::asio::ip::multicast::outbound_interface @n * boost::asio::ip::multicast::hops @n * boost::asio::ip::tcp::no_delay * * @par Example * Setting the IPPROTO_TCP/TCP_NODELAY option: * @code * boost::asio::ip::tcp::socket socket(my_context); * ... * boost::asio::ip::tcp::no_delay option(true); * socket.set_option(option); * @endcode */ template <typename SettableSocketOption> void set_option(const SettableSocketOption& option) { boost::system::error_code ec; impl_.get_service().set_option(impl_.get_implementation(), option, ec); boost::asio::detail::throw_error(ec, "set_option"); } /// Set an option on the socket. /** * This function is used to set an option on the socket. * * @param option The new option value to be set on the socket. * * @param ec Set to indicate what error occurred, if any. * * @sa SettableSocketOption @n * boost::asio::socket_base::broadcast @n * boost::asio::socket_base::do_not_route @n * boost::asio::socket_base::keep_alive @n * boost::asio::socket_base::linger @n * boost::asio::socket_base::receive_buffer_size @n * boost::asio::socket_base::receive_low_watermark @n * boost::asio::socket_base::reuse_address @n * boost::asio::socket_base::send_buffer_size @n * boost::asio::socket_base::send_low_watermark @n * boost::asio::ip::multicast::join_group @n * boost::asio::ip::multicast::leave_group @n * boost::asio::ip::multicast::enable_loopback @n * boost::asio::ip::multicast::outbound_interface @n * boost::asio::ip::multicast::hops @n * boost::asio::ip::tcp::no_delay * * @par Example * Setting the IPPROTO_TCP/TCP_NODELAY option: * @code * boost::asio::ip::tcp::socket socket(my_context); * ... * boost::asio::ip::tcp::no_delay option(true); * boost::system::error_code ec; * socket.set_option(option, ec); * if (ec) * { * // An error occurred. * } * @endcode */ template <typename SettableSocketOption> BOOST_ASIO_SYNC_OP_VOID set_option(const SettableSocketOption& option, boost::system::error_code& ec) { impl_.get_service().set_option(impl_.get_implementation(), option, ec); BOOST_ASIO_SYNC_OP_VOID_RETURN(ec); } /// Get an option from the socket. /** * This function is used to get the current value of an option on the socket. * * @param option The option value to be obtained from the socket. * * @throws boost::system::system_error Thrown on failure. * * @sa GettableSocketOption @n * boost::asio::socket_base::broadcast @n * boost::asio::socket_base::do_not_route @n * boost::asio::socket_base::keep_alive @n * boost::asio::socket_base::linger @n * boost::asio::socket_base::receive_buffer_size @n * boost::asio::socket_base::receive_low_watermark @n * boost::asio::socket_base::reuse_address @n * boost::asio::socket_base::send_buffer_size @n * boost::asio::socket_base::send_low_watermark @n * boost::asio::ip::multicast::join_group @n * boost::asio::ip::multicast::leave_group @n * boost::asio::ip::multicast::enable_loopback @n * boost::asio::ip::multicast::outbound_interface @n * boost::asio::ip::multicast::hops @n * boost::asio::ip::tcp::no_delay * * @par Example * Getting the value of the SOL_SOCKET/SO_KEEPALIVE option: * @code * boost::asio::ip::tcp::socket socket(my_context); * ... * boost::asio::ip::tcp::socket::keep_alive option; * socket.get_option(option); * bool is_set = option.value(); * @endcode */ template <typename GettableSocketOption> void get_option(GettableSocketOption& option) const { boost::system::error_code ec; impl_.get_service().get_option(impl_.get_implementation(), option, ec); boost::asio::detail::throw_error(ec, "get_option"); } /// Get an option from the socket. /** * This function is used to get the current value of an option on the socket. * * @param option The option value to be obtained from the socket. * * @param ec Set to indicate what error occurred, if any. * * @sa GettableSocketOption @n * boost::asio::socket_base::broadcast @n * boost::asio::socket_base::do_not_route @n * boost::asio::socket_base::keep_alive @n * boost::asio::socket_base::linger @n * boost::asio::socket_base::receive_buffer_size @n * boost::asio::socket_base::receive_low_watermark @n * boost::asio::socket_base::reuse_address @n * boost::asio::socket_base::send_buffer_size @n * boost::asio::socket_base::send_low_watermark @n * boost::asio::ip::multicast::join_group @n * boost::asio::ip::multicast::leave_group @n * boost::asio::ip::multicast::enable_loopback @n * boost::asio::ip::multicast::outbound_interface @n * boost::asio::ip::multicast::hops @n * boost::asio::ip::tcp::no_delay * * @par Example * Getting the value of the SOL_SOCKET/SO_KEEPALIVE option: * @code * boost::asio::ip::tcp::socket socket(my_context); * ... * boost::asio::ip::tcp::socket::keep_alive option; * boost::system::error_code ec; * socket.get_option(option, ec); * if (ec) * { * // An error occurred. * } * bool is_set = option.value(); * @endcode */ template <typename GettableSocketOption> BOOST_ASIO_SYNC_OP_VOID get_option(GettableSocketOption& option, boost::system::error_code& ec) const { impl_.get_service().get_option(impl_.get_implementation(), option, ec); BOOST_ASIO_SYNC_OP_VOID_RETURN(ec); } /// Perform an IO control command on the socket. /** * This function is used to execute an IO control command on the socket. * * @param command The IO control command to be performed on the socket. * * @throws boost::system::system_error Thrown on failure. * * @sa IoControlCommand @n * boost::asio::socket_base::bytes_readable @n * boost::asio::socket_base::non_blocking_io * * @par Example * Getting the number of bytes ready to read: * @code * boost::asio::ip::tcp::socket socket(my_context); * ... * boost::asio::ip::tcp::socket::bytes_readable command; * socket.io_control(command); * std::size_t bytes_readable = command.get(); * @endcode */ template <typename IoControlCommand> void io_control(IoControlCommand& command) { boost::system::error_code ec; impl_.get_service().io_control(impl_.get_implementation(), command, ec); boost::asio::detail::throw_error(ec, "io_control"); } /// Perform an IO control command on the socket. /** * This function is used to execute an IO control command on the socket. * * @param command The IO control command to be performed on the socket. * * @param ec Set to indicate what error occurred, if any. * * @sa IoControlCommand @n * boost::asio::socket_base::bytes_readable @n * boost::asio::socket_base::non_blocking_io * * @par Example * Getting the number of bytes ready to read: * @code * boost::asio::ip::tcp::socket socket(my_context); * ... * boost::asio::ip::tcp::socket::bytes_readable command; * boost::system::error_code ec; * socket.io_control(command, ec); * if (ec) * { * // An error occurred. * } * std::size_t bytes_readable = command.get(); * @endcode */ template <typename IoControlCommand> BOOST_ASIO_SYNC_OP_VOID io_control(IoControlCommand& command, boost::system::error_code& ec) { impl_.get_service().io_control(impl_.get_implementation(), command, ec); BOOST_ASIO_SYNC_OP_VOID_RETURN(ec); } /// Gets the non-blocking mode of the socket. /** * @returns @c true if the socket's synchronous operations will fail with * boost::asio::error::would_block if they are unable to perform the requested * operation immediately. If @c false, synchronous operations will block * until complete. * * @note The non-blocking mode has no effect on the behaviour of asynchronous * operations. Asynchronous operations will never fail with the error * boost::asio::error::would_block. */ bool non_blocking() const { return impl_.get_service().non_blocking(impl_.get_implementation()); } /// Sets the non-blocking mode of the socket. /** * @param mode If @c true, the socket's synchronous operations will fail with * boost::asio::error::would_block if they are unable to perform the requested * operation immediately. If @c false, synchronous operations will block * until complete. * * @throws boost::system::system_error Thrown on failure. * * @note The non-blocking mode has no effect on the behaviour of asynchronous * operations. Asynchronous operations will never fail with the error * boost::asio::error::would_block. */ void non_blocking(bool mode) { boost::system::error_code ec; impl_.get_service().non_blocking(impl_.get_implementation(), mode, ec); boost::asio::detail::throw_error(ec, "non_blocking"); } /// Sets the non-blocking mode of the socket. /** * @param mode If @c true, the socket's synchronous operations will fail with * boost::asio::error::would_block if they are unable to perform the requested * operation immediately. If @c false, synchronous operations will block * until complete. * * @param ec Set to indicate what error occurred, if any. * * @note The non-blocking mode has no effect on the behaviour of asynchronous * operations. Asynchronous operations will never fail with the error * boost::asio::error::would_block. */ BOOST_ASIO_SYNC_OP_VOID non_blocking( bool mode, boost::system::error_code& ec) { impl_.get_service().non_blocking(impl_.get_implementation(), mode, ec); BOOST_ASIO_SYNC_OP_VOID_RETURN(ec); } /// Gets the non-blocking mode of the native socket implementation. /** * This function is used to retrieve the non-blocking mode of the underlying * native socket. This mode has no effect on the behaviour of the socket * object's synchronous operations. * * @returns @c true if the underlying socket is in non-blocking mode and * direct system calls may fail with boost::asio::error::would_block (or the * equivalent system error). * * @note The current non-blocking mode is cached by the socket object. * Consequently, the return value may be incorrect if the non-blocking mode * was set directly on the native socket. * * @par Example * This function is intended to allow the encapsulation of arbitrary * non-blocking system calls as asynchronous operations, in a way that is * transparent to the user of the socket object. The following example * illustrates how Linux's @c sendfile system call might be encapsulated: * @code template <typename Handler> * struct sendfile_op * { * tcp::socket& sock_; * int fd_; * Handler handler_; * off_t offset_; * std::size_t total_bytes_transferred_; * * // Function call operator meeting WriteHandler requirements. * // Used as the handler for the async_write_some operation. * void operator()(boost::system::error_code ec, std::size_t) * { * // Put the underlying socket into non-blocking mode. * if (!ec) * if (!sock_.native_non_blocking()) * sock_.native_non_blocking(true, ec); * * if (!ec) * { * for (;;) * { * // Try the system call. * errno = 0; * int n = ::sendfile(sock_.native_handle(), fd_, &offset_, 65536); * ec = boost::system::error_code(n < 0 ? errno : 0, * boost::asio::error::get_system_category()); * total_bytes_transferred_ += ec ? 0 : n; * * // Retry operation immediately if interrupted by signal. * if (ec == boost::asio::error::interrupted) * continue; * * // Check if we need to run the operation again. * if (ec == boost::asio::error::would_block * || ec == boost::asio::error::try_again) * { * // We have to wait for the socket to become ready again. * sock_.async_wait(tcp::socket::wait_write, *this); * return; * } * * if (ec || n == 0) * { * // An error occurred, or we have reached the end of the file. * // Either way we must exit the loop so we can call the handler. * break; * } * * // Loop around to try calling sendfile again. * } * } * * // Pass result back to user's handler. * handler_(ec, total_bytes_transferred_); * } * }; * * template <typename Handler> * void async_sendfile(tcp::socket& sock, int fd, Handler h) * { * sendfile_op<Handler> op = { sock, fd, h, 0, 0 }; * sock.async_wait(tcp::socket::wait_write, op); * } @endcode */ bool native_non_blocking() const { return impl_.get_service().native_non_blocking(impl_.get_implementation()); } /// Sets the non-blocking mode of the native socket implementation. /** * This function is used to modify the non-blocking mode of the underlying * native socket. It has no effect on the behaviour of the socket object's * synchronous operations. * * @param mode If @c true, the underlying socket is put into non-blocking * mode and direct system calls may fail with boost::asio::error::would_block * (or the equivalent system error). * * @throws boost::system::system_error Thrown on failure. If the @c mode is * @c false, but the current value of @c non_blocking() is @c true, this * function fails with boost::asio::error::invalid_argument, as the * combination does not make sense. * * @par Example * This function is intended to allow the encapsulation of arbitrary * non-blocking system calls as asynchronous operations, in a way that is * transparent to the user of the socket object. The following example * illustrates how Linux's @c sendfile system call might be encapsulated: * @code template <typename Handler> * struct sendfile_op * { * tcp::socket& sock_; * int fd_; * Handler handler_; * off_t offset_; * std::size_t total_bytes_transferred_; * * // Function call operator meeting WriteHandler requirements. * // Used as the handler for the async_write_some operation. * void operator()(boost::system::error_code ec, std::size_t) * { * // Put the underlying socket into non-blocking mode. * if (!ec) * if (!sock_.native_non_blocking()) * sock_.native_non_blocking(true, ec); * * if (!ec) * { * for (;;) * { * // Try the system call. * errno = 0; * int n = ::sendfile(sock_.native_handle(), fd_, &offset_, 65536); * ec = boost::system::error_code(n < 0 ? errno : 0, * boost::asio::error::get_system_category()); * total_bytes_transferred_ += ec ? 0 : n; * * // Retry operation immediately if interrupted by signal. * if (ec == boost::asio::error::interrupted) * continue; * * // Check if we need to run the operation again. * if (ec == boost::asio::error::would_block * || ec == boost::asio::error::try_again) * { * // We have to wait for the socket to become ready again. * sock_.async_wait(tcp::socket::wait_write, *this); * return; * } * * if (ec || n == 0) * { * // An error occurred, or we have reached the end of the file. * // Either way we must exit the loop so we can call the handler. * break; * } * * // Loop around to try calling sendfile again. * } * } * * // Pass result back to user's handler. * handler_(ec, total_bytes_transferred_); * } * }; * * template <typename Handler> * void async_sendfile(tcp::socket& sock, int fd, Handler h) * { * sendfile_op<Handler> op = { sock, fd, h, 0, 0 }; * sock.async_wait(tcp::socket::wait_write, op); * } @endcode */ void native_non_blocking(bool mode) { boost::system::error_code ec; impl_.get_service().native_non_blocking( impl_.get_implementation(), mode, ec); boost::asio::detail::throw_error(ec, "native_non_blocking"); } /// Sets the non-blocking mode of the native socket implementation. /** * This function is used to modify the non-blocking mode of the underlying * native socket. It has no effect on the behaviour of the socket object's * synchronous operations. * * @param mode If @c true, the underlying socket is put into non-blocking * mode and direct system calls may fail with boost::asio::error::would_block * (or the equivalent system error). * * @param ec Set to indicate what error occurred, if any. If the @c mode is * @c false, but the current value of @c non_blocking() is @c true, this * function fails with boost::asio::error::invalid_argument, as the * combination does not make sense. * * @par Example * This function is intended to allow the encapsulation of arbitrary * non-blocking system calls as asynchronous operations, in a way that is * transparent to the user of the socket object. The following example * illustrates how Linux's @c sendfile system call might be encapsulated: * @code template <typename Handler> * struct sendfile_op * { * tcp::socket& sock_; * int fd_; * Handler handler_; * off_t offset_; * std::size_t total_bytes_transferred_; * * // Function call operator meeting WriteHandler requirements. * // Used as the handler for the async_write_some operation. * void operator()(boost::system::error_code ec, std::size_t) * { * // Put the underlying socket into non-blocking mode. * if (!ec) * if (!sock_.native_non_blocking()) * sock_.native_non_blocking(true, ec); * * if (!ec) * { * for (;;) * { * // Try the system call. * errno = 0; * int n = ::sendfile(sock_.native_handle(), fd_, &offset_, 65536); * ec = boost::system::error_code(n < 0 ? errno : 0, * boost::asio::error::get_system_category()); * total_bytes_transferred_ += ec ? 0 : n; * * // Retry operation immediately if interrupted by signal. * if (ec == boost::asio::error::interrupted) * continue; * * // Check if we need to run the operation again. * if (ec == boost::asio::error::would_block * || ec == boost::asio::error::try_again) * { * // We have to wait for the socket to become ready again. * sock_.async_wait(tcp::socket::wait_write, *this); * return; * } * * if (ec || n == 0) * { * // An error occurred, or we have reached the end of the file. * // Either way we must exit the loop so we can call the handler. * break; * } * * // Loop around to try calling sendfile again. * } * } * * // Pass result back to user's handler. * handler_(ec, total_bytes_transferred_); * } * }; * * template <typename Handler> * void async_sendfile(tcp::socket& sock, int fd, Handler h) * { * sendfile_op<Handler> op = { sock, fd, h, 0, 0 }; * sock.async_wait(tcp::socket::wait_write, op); * } @endcode */ BOOST_ASIO_SYNC_OP_VOID native_non_blocking( bool mode, boost::system::error_code& ec) { impl_.get_service().native_non_blocking( impl_.get_implementation(), mode, ec); BOOST_ASIO_SYNC_OP_VOID_RETURN(ec); } /// Get the local endpoint of the socket. /** * This function is used to obtain the locally bound endpoint of the socket. * * @returns An object that represents the local endpoint of the socket. * * @throws boost::system::system_error Thrown on failure. * * @par Example * @code * boost::asio::ip::tcp::socket socket(my_context); * ... * boost::asio::ip::tcp::endpoint endpoint = socket.local_endpoint(); * @endcode */ endpoint_type local_endpoint() const { boost::system::error_code ec; endpoint_type ep = impl_.get_service().local_endpoint( impl_.get_implementation(), ec); boost::asio::detail::throw_error(ec, "local_endpoint"); return ep; } /// Get the local endpoint of the socket. /** * This function is used to obtain the locally bound endpoint of the socket. * * @param ec Set to indicate what error occurred, if any. * * @returns An object that represents the local endpoint of the socket. * Returns a default-constructed endpoint object if an error occurred. * * @par Example * @code * boost::asio::ip::tcp::socket socket(my_context); * ... * boost::system::error_code ec; * boost::asio::ip::tcp::endpoint endpoint = socket.local_endpoint(ec); * if (ec) * { * // An error occurred. * } * @endcode */ endpoint_type local_endpoint(boost::system::error_code& ec) const { return impl_.get_service().local_endpoint(impl_.get_implementation(), ec); } /// Get the remote endpoint of the socket. /** * This function is used to obtain the remote endpoint of the socket. * * @returns An object that represents the remote endpoint of the socket. * * @throws boost::system::system_error Thrown on failure. * * @par Example * @code * boost::asio::ip::tcp::socket socket(my_context); * ... * boost::asio::ip::tcp::endpoint endpoint = socket.remote_endpoint(); * @endcode */ endpoint_type remote_endpoint() const { boost::system::error_code ec; endpoint_type ep = impl_.get_service().remote_endpoint( impl_.get_implementation(), ec); boost::asio::detail::throw_error(ec, "remote_endpoint"); return ep; } /// Get the remote endpoint of the socket. /** * This function is used to obtain the remote endpoint of the socket. * * @param ec Set to indicate what error occurred, if any. * * @returns An object that represents the remote endpoint of the socket. * Returns a default-constructed endpoint object if an error occurred. * * @par Example * @code * boost::asio::ip::tcp::socket socket(my_context); * ... * boost::system::error_code ec; * boost::asio::ip::tcp::endpoint endpoint = socket.remote_endpoint(ec); * if (ec) * { * // An error occurred. * } * @endcode */ endpoint_type remote_endpoint(boost::system::error_code& ec) const { return impl_.get_service().remote_endpoint(impl_.get_implementation(), ec); } /// Disable sends or receives on the socket. /** * This function is used to disable send operations, receive operations, or * both. * * @param what Determines what types of operation will no longer be allowed. * * @throws boost::system::system_error Thrown on failure. * * @par Example * Shutting down the send side of the socket: * @code * boost::asio::ip::tcp::socket socket(my_context); * ... * socket.shutdown(boost::asio::ip::tcp::socket::shutdown_send); * @endcode */ void shutdown(shutdown_type what) { boost::system::error_code ec; impl_.get_service().shutdown(impl_.get_implementation(), what, ec); boost::asio::detail::throw_error(ec, "shutdown"); } /// Disable sends or receives on the socket. /** * This function is used to disable send operations, receive operations, or * both. * * @param what Determines what types of operation will no longer be allowed. * * @param ec Set to indicate what error occurred, if any. * * @par Example * Shutting down the send side of the socket: * @code * boost::asio::ip::tcp::socket socket(my_context); * ... * boost::system::error_code ec; * socket.shutdown(boost::asio::ip::tcp::socket::shutdown_send, ec); * if (ec) * { * // An error occurred. * } * @endcode */ BOOST_ASIO_SYNC_OP_VOID shutdown(shutdown_type what, boost::system::error_code& ec) { impl_.get_service().shutdown(impl_.get_implementation(), what, ec); BOOST_ASIO_SYNC_OP_VOID_RETURN(ec); } /// Wait for the socket to become ready to read, ready to write, or to have /// pending error conditions. /** * This function is used to perform a blocking wait for a socket to enter * a ready to read, write or error condition state. * * @param w Specifies the desired socket state. * * @par Example * Waiting for a socket to become readable. * @code * boost::asio::ip::tcp::socket socket(my_context); * ... * socket.wait(boost::asio::ip::tcp::socket::wait_read); * @endcode */ void wait(wait_type w) { boost::system::error_code ec; impl_.get_service().wait(impl_.get_implementation(), w, ec); boost::asio::detail::throw_error(ec, "wait"); } /// Wait for the socket to become ready to read, ready to write, or to have /// pending error conditions. /** * This function is used to perform a blocking wait for a socket to enter * a ready to read, write or error condition state. * * @param w Specifies the desired socket state. * * @param ec Set to indicate what error occurred, if any. * * @par Example * Waiting for a socket to become readable. * @code * boost::asio::ip::tcp::socket socket(my_context); * ... * boost::system::error_code ec; * socket.wait(boost::asio::ip::tcp::socket::wait_read, ec); * @endcode */ BOOST_ASIO_SYNC_OP_VOID wait(wait_type w, boost::system::error_code& ec) { impl_.get_service().wait(impl_.get_implementation(), w, ec); BOOST_ASIO_SYNC_OP_VOID_RETURN(ec); } /// Asynchronously wait for the socket to become ready to read, ready to /// write, or to have pending error conditions. /** * This function is used to perform an asynchronous wait for a socket to enter * a ready to read, write or error condition state. It is an initiating * function for an @ref asynchronous_operation, and always returns * immediately. * * @param w Specifies the desired socket state. * * @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 boost::system::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 boost::asio::post(). * * @par Completion Signature * @code void(boost::system::error_code) @endcode * * @par Example * @code * void wait_handler(const boost::system::error_code& error) * { * if (!error) * { * // Wait succeeded. * } * } * * ... * * boost::asio::ip::tcp::socket socket(my_context); * ... * socket.async_wait(boost::asio::ip::tcp::socket::wait_read, wait_handler); * @endcode * * @par Per-Operation Cancellation * On POSIX or Windows operating systems, this asynchronous operation supports * cancellation for the following boost::asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * @li @c cancellation_type::total */ template < BOOST_ASIO_COMPLETION_TOKEN_FOR(void (boost::system::error_code)) WaitToken = default_completion_token_t<executor_type>> auto async_wait(wait_type w, WaitToken&& token = default_completion_token_t<executor_type>()) -> decltype( async_initiate<WaitToken, void (boost::system::error_code)>( declval<initiate_async_wait>(), token, w)) { return async_initiate<WaitToken, void (boost::system::error_code)>( initiate_async_wait(this), token, w); } protected: /// Protected destructor to prevent deletion through this type. /** * This function destroys the socket, cancelling any outstanding asynchronous * operations associated with the socket as if by calling @c cancel. */ ~basic_socket() { } #if defined(BOOST_ASIO_WINDOWS_RUNTIME) detail::io_object_impl< detail::null_socket_service<Protocol>, Executor> impl_; #elif defined(BOOST_ASIO_HAS_IOCP) detail::io_object_impl< detail::win_iocp_socket_service<Protocol>, Executor> impl_; #elif defined(BOOST_ASIO_HAS_IO_URING_AS_DEFAULT) detail::io_object_impl< detail::io_uring_socket_service<Protocol>, Executor> impl_; #else detail::io_object_impl< detail::reactive_socket_service<Protocol>, Executor> impl_; #endif private: // Disallow copying and assignment. basic_socket(const basic_socket&) = delete; basic_socket& operator=(const basic_socket&) = delete; class initiate_async_connect { public: typedef Executor executor_type; explicit initiate_async_connect(basic_socket* self) : self_(self) { } const executor_type& get_executor() const noexcept { return self_->get_executor(); } template <typename ConnectHandler> void operator()(ConnectHandler&& handler, const endpoint_type& peer_endpoint, const boost::system::error_code& open_ec) const { // If you get an error on the following line it means that your handler // does not meet the documented type requirements for a ConnectHandler. BOOST_ASIO_CONNECT_HANDLER_CHECK(ConnectHandler, handler) type_check; if (open_ec) { boost::asio::post(self_->impl_.get_executor(), boost::asio::detail::bind_handler( static_cast<ConnectHandler&&>(handler), open_ec)); } else { detail::non_const_lvalue<ConnectHandler> handler2(handler); self_->impl_.get_service().async_connect( self_->impl_.get_implementation(), peer_endpoint, handler2.value, self_->impl_.get_executor()); } } private: basic_socket* self_; }; class initiate_async_wait { public: typedef Executor executor_type; explicit initiate_async_wait(basic_socket* self) : self_(self) { } const executor_type& get_executor() const noexcept { return self_->get_executor(); } template <typename WaitHandler> void operator()(WaitHandler&& handler, wait_type w) 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. BOOST_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(), w, handler2.value, self_->impl_.get_executor()); } private: basic_socket* self_; }; }; } // namespace asio } // namespace boost #include <boost/asio/detail/pop_options.hpp> #endif // BOOST_ASIO_BASIC_SOCKET_HPP
hpp
asio
data/projects/asio/include/boost/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 BOOST_ASIO_CANCELLATION_SIGNAL_HPP #define BOOST_ASIO_CANCELLATION_SIGNAL_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <boost/asio/detail/config.hpp> #include <cassert> #include <new> #include <utility> #include <boost/asio/cancellation_type.hpp> #include <boost/asio/detail/cstddef.hpp> #include <boost/asio/detail/type_traits.hpp> #include <boost/asio/detail/push_options.hpp> namespace boost { 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) { } BOOST_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(boost::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(boost::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. */ BOOST_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) { } BOOST_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; BOOST_ASIO_DECL ~auto_delete_helper(); }; detail::cancellation_handler_base** handler_; }; inline cancellation_slot cancellation_signal::slot() noexcept { return cancellation_slot(0, &handler_); } } // namespace asio } // namespace boost #include <boost/asio/detail/pop_options.hpp> #if defined(BOOST_ASIO_HEADER_ONLY) # include <boost/asio/impl/cancellation_signal.ipp> #endif // defined(BOOST_ASIO_HEADER_ONLY) #endif // BOOST_ASIO_CANCELLATION_SIGNAL_HPP
hpp
asio
data/projects/asio/include/boost/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 BOOST_ASIO_RECYCLING_ALLOCATOR_HPP #define BOOST_ASIO_RECYCLING_ALLOCATOR_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <boost/asio/detail/config.hpp> #include <boost/asio/detail/recycling_allocator.hpp> #include <boost/asio/detail/push_options.hpp> namespace boost { 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 } // namespace boost #include <boost/asio/detail/pop_options.hpp> #endif // BOOST_ASIO_RECYCLING_ALLOCATOR_HPP
hpp
asio
data/projects/asio/include/boost/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 BOOST_ASIO_WRITE_AT_HPP #define BOOST_ASIO_WRITE_AT_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <boost/asio/detail/config.hpp> #include <cstddef> #include <boost/asio/async_result.hpp> #include <boost/asio/completion_condition.hpp> #include <boost/asio/detail/cstdint.hpp> #include <boost/asio/error.hpp> #if !defined(BOOST_ASIO_NO_EXTENSIONS) # include <boost/asio/basic_streambuf_fwd.hpp> #endif // !defined(BOOST_ASIO_NO_EXTENSIONS) #include <boost/asio/detail/push_options.hpp> namespace boost { namespace asio { namespace detail { template <typename> class initiate_async_write_at; #if !defined(BOOST_ASIO_NO_IOSTREAM) template <typename> class initiate_async_write_at_streambuf; #endif // !defined(BOOST_ASIO_NO_IOSTREAM) } // namespace detail /** * @defgroup write_at boost::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 boost::system::system_error Thrown on failure. * * @par Example * To write a single data buffer use the @ref buffer function as follows: * @code boost::asio::write_at(d, 42, boost::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 boost::asio::write_at( * d, offset, buffers, * boost::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 boost::asio::write_at(d, 42, * boost::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 boost::asio::write_at( * d, offset, buffers, * boost::asio::transfer_all(), ec); @endcode */ template <typename SyncRandomAccessWriteDevice, typename ConstBufferSequence> std::size_t write_at(SyncRandomAccessWriteDevice& d, uint64_t offset, const ConstBufferSequence& buffers, boost::system::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 boost::system::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 boost::system::system_error Thrown on failure. * * @par Example * To write a single data buffer use the @ref buffer function as follows: * @code boost::asio::write_at(d, 42, boost::asio::buffer(data, size), * boost::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); /// 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 boost::system::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, boost::system::error_code& ec); #if !defined(BOOST_ASIO_NO_EXTENSIONS) #if !defined(BOOST_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 boost::system::system_error Thrown on failure. * * @note This overload is equivalent to calling: * @code boost::asio::write_at( * d, 42, b, * boost::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 boost::asio::write_at( * d, 42, b, * boost::asio::transfer_all(), ec); @endcode */ template <typename SyncRandomAccessWriteDevice, typename Allocator> std::size_t write_at(SyncRandomAccessWriteDevice& d, uint64_t offset, basic_streambuf<Allocator>& b, boost::system::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 boost::system::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 boost::system::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); /// 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 boost::system::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, boost::system::error_code& ec); #endif // !defined(BOOST_ASIO_NO_IOSTREAM) #endif // !defined(BOOST_ASIO_NO_EXTENSIONS) /*@}*/ /** * @defgroup async_write_at boost::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 boost::system::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 boost::asio::post(). * * @par Completion Signature * @code void(boost::system::error_code, std::size_t) @endcode * * @par Example * To write a single data buffer use the @ref buffer function as follows: * @code * boost::asio::async_write_at(d, 42, boost::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 * boost::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, BOOST_ASIO_COMPLETION_TOKEN_FOR(void (boost::system::error_code, std::size_t)) WriteToken = default_completion_token_t< typename AsyncRandomAccessWriteDevice::executor_type>> auto async_write_at(AsyncRandomAccessWriteDevice& d, uint64_t offset, const ConstBufferSequence& buffers, WriteToken&& token = default_completion_token_t< typename AsyncRandomAccessWriteDevice::executor_type>()) -> decltype( async_initiate<WriteToken, void (boost::system::error_code, std::size_t)>( declval<detail::initiate_async_write_at< AsyncRandomAccessWriteDevice>>(), 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 boost::system::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 boost::system::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 boost::asio::post(). * * @par Completion Signature * @code void(boost::system::error_code, std::size_t) @endcode * * @par Example * To write a single data buffer use the @ref buffer function as follows: * @code boost::asio::async_write_at(d, 42, * boost::asio::buffer(data, size), * boost::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 * boost::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, BOOST_ASIO_COMPLETION_TOKEN_FOR(void (boost::system::error_code, std::size_t)) WriteToken = default_completion_token_t< typename AsyncRandomAccessWriteDevice::executor_type>> 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>()) -> decltype( async_initiate<WriteToken, void (boost::system::error_code, std::size_t)>( declval<detail::initiate_async_write_at< AsyncRandomAccessWriteDevice>>(), token, offset, buffers, static_cast<CompletionCondition&&>(completion_condition))); #if !defined(BOOST_ASIO_NO_EXTENSIONS) #if !defined(BOOST_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 boost::system::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 boost::asio::post(). * * @par Completion Signature * @code void(boost::system::error_code, std::size_t) @endcode * * @par Per-Operation Cancellation * This asynchronous operation supports cancellation for the following * boost::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, BOOST_ASIO_COMPLETION_TOKEN_FOR(void (boost::system::error_code, std::size_t)) WriteToken = default_completion_token_t< typename AsyncRandomAccessWriteDevice::executor_type>> auto async_write_at(AsyncRandomAccessWriteDevice& d, uint64_t offset, basic_streambuf<Allocator>& b, WriteToken&& token = default_completion_token_t< typename AsyncRandomAccessWriteDevice::executor_type>()) -> decltype( async_initiate<WriteToken, void (boost::system::error_code, std::size_t)>( declval<detail::initiate_async_write_at_streambuf< AsyncRandomAccessWriteDevice>>(), 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 boost::system::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 boost::system::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 boost::asio::post(). * * @par Completion Signature * @code void(boost::system::error_code, std::size_t) @endcode * * @par Per-Operation Cancellation * This asynchronous operation supports cancellation for the following * boost::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, BOOST_ASIO_COMPLETION_TOKEN_FOR(void (boost::system::error_code, std::size_t)) WriteToken = default_completion_token_t< typename AsyncRandomAccessWriteDevice::executor_type>> 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>()) -> decltype( async_initiate<WriteToken, void (boost::system::error_code, std::size_t)>( declval<detail::initiate_async_write_at_streambuf< AsyncRandomAccessWriteDevice>>(), token, offset, &b, static_cast<CompletionCondition&&>(completion_condition))); #endif // !defined(BOOST_ASIO_NO_IOSTREAM) #endif // !defined(BOOST_ASIO_NO_EXTENSIONS) /*@}*/ } // namespace asio } // namespace boost #include <boost/asio/detail/pop_options.hpp> #include <boost/asio/impl/write_at.hpp> #endif // BOOST_ASIO_WRITE_AT_HPP
hpp
asio
data/projects/asio/include/boost/asio/basic_file.hpp
// // basic_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 BOOST_ASIO_BASIC_FILE_HPP #define BOOST_ASIO_BASIC_FILE_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <boost/asio/detail/config.hpp> #if defined(BOOST_ASIO_HAS_FILE) \ || defined(GENERATING_DOCUMENTATION) #include <string> #include <utility> #include <boost/asio/any_io_executor.hpp> #include <boost/asio/async_result.hpp> #include <boost/asio/detail/cstdint.hpp> #include <boost/asio/detail/handler_type_requirements.hpp> #include <boost/asio/detail/io_object_impl.hpp> #include <boost/asio/detail/non_const_lvalue.hpp> #include <boost/asio/detail/throw_error.hpp> #include <boost/asio/detail/type_traits.hpp> #include <boost/asio/error.hpp> #include <boost/asio/execution_context.hpp> #include <boost/asio/post.hpp> #include <boost/asio/file_base.hpp> #if defined(BOOST_ASIO_HAS_IOCP) # include <boost/asio/detail/win_iocp_file_service.hpp> #elif defined(BOOST_ASIO_HAS_IO_URING) # include <boost/asio/detail/io_uring_file_service.hpp> #endif #include <boost/asio/detail/push_options.hpp> namespace boost { namespace asio { #if !defined(BOOST_ASIO_BASIC_FILE_FWD_DECL) #define BOOST_ASIO_BASIC_FILE_FWD_DECL // Forward declaration with defaulted arguments. template <typename Executor = any_io_executor> class basic_file; #endif // !defined(BOOST_ASIO_BASIC_FILE_FWD_DECL) /// Provides file functionality. /** * The basic_file class template provides functionality that is common to both * stream-oriented and random-access files. * * @par Thread Safety * @e Distinct @e objects: Safe.@n * @e Shared @e objects: Unsafe. */ template <typename Executor> class basic_file : public file_base { 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_file<Executor1> other; }; /// The native representation of a file. #if defined(GENERATING_DOCUMENTATION) typedef implementation_defined native_handle_type; #elif defined(BOOST_ASIO_HAS_IOCP) typedef detail::win_iocp_file_service::native_handle_type native_handle_type; #elif defined(BOOST_ASIO_HAS_IO_URING) typedef detail::io_uring_file_service::native_handle_type native_handle_type; #endif /// Construct a basic_file without opening it. /** * This constructor initialises a file without opening 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_file(const executor_type& ex) : impl_(0, ex) { } /// Construct a basic_file without opening it. /** * This constructor initialises a file without opening 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_file(ExecutionContext& context, constraint_t< is_convertible<ExecutionContext&, execution_context&>::value, defaulted_constraint > = defaulted_constraint()) : impl_(0, 0, context) { } /// Construct and open a basic_file. /** * This constructor initialises a file and opens 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. * * @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. */ explicit basic_file(const executor_type& ex, const char* path, file_base::flags open_flags) : impl_(0, ex) { boost::system::error_code ec; impl_.get_service().open(impl_.get_implementation(), path, open_flags, ec); boost::asio::detail::throw_error(ec, "open"); } /// Construct a basic_file without opening it. /** * This constructor initialises a file and opens 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. * * @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. */ template <typename ExecutionContext> explicit basic_file(ExecutionContext& context, const char* path, file_base::flags open_flags, constraint_t< is_convertible<ExecutionContext&, execution_context&>::value, defaulted_constraint > = defaulted_constraint()) : impl_(0, 0, context) { boost::system::error_code ec; impl_.get_service().open(impl_.get_implementation(), path, open_flags, ec); boost::asio::detail::throw_error(ec, "open"); } /// Construct and open a basic_file. /** * This constructor initialises a file and opens 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. * * @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. */ explicit basic_file(const executor_type& ex, const std::string& path, file_base::flags open_flags) : impl_(0, ex) { boost::system::error_code ec; impl_.get_service().open(impl_.get_implementation(), path.c_str(), open_flags, ec); boost::asio::detail::throw_error(ec, "open"); } /// Construct a basic_file without opening it. /** * This constructor initialises a file and opens 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. * * @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. */ template <typename ExecutionContext> explicit basic_file(ExecutionContext& context, const std::string& path, file_base::flags open_flags, constraint_t< is_convertible<ExecutionContext&, execution_context&>::value, defaulted_constraint > = defaulted_constraint()) : impl_(0, 0, context) { boost::system::error_code ec; impl_.get_service().open(impl_.get_implementation(), path.c_str(), open_flags, ec); boost::asio::detail::throw_error(ec, "open"); } /// Construct a basic_file on an existing native file handle. /** * This constructor initialises a 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 A native file handle. * * @throws boost::system::system_error Thrown on failure. */ basic_file(const executor_type& ex, const native_handle_type& native_file) : impl_(0, ex) { boost::system::error_code ec; impl_.get_service().assign( impl_.get_implementation(), native_file, ec); boost::asio::detail::throw_error(ec, "assign"); } /// Construct a basic_file on an existing native file. /** * This constructor initialises a 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 A native file. * * @throws boost::system::system_error Thrown on failure. */ template <typename ExecutionContext> basic_file(ExecutionContext& context, const native_handle_type& native_file, constraint_t< is_convertible<ExecutionContext&, execution_context&>::value, defaulted_constraint > = defaulted_constraint()) : impl_(0, 0, context) { boost::system::error_code ec; impl_.get_service().assign( impl_.get_implementation(), native_file, ec); boost::asio::detail::throw_error(ec, "assign"); } /// Move-construct a basic_file from another. /** * This constructor moves a file from one object to another. * * @param other The other basic_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_file(const executor_type&) constructor. */ basic_file(basic_file&& other) noexcept : impl_(std::move(other.impl_)) { } /// Move-assign a basic_file from another. /** * This assignment operator moves a file from one object to another. * * @param other The other basic_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_file(const executor_type&) constructor. */ basic_file& operator=(basic_file&& other) { impl_ = std::move(other.impl_); return *this; } // All files have access to each other's implementations. template <typename Executor1> friend class basic_file; /// Move-construct a basic_file from a file of another executor type. /** * This constructor moves a file from one object to another. * * @param other The other basic_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_file(const executor_type&) constructor. */ template <typename Executor1> basic_file(basic_file<Executor1>&& other, constraint_t< is_convertible<Executor1, Executor>::value, defaulted_constraint > = defaulted_constraint()) : impl_(std::move(other.impl_)) { } /// Move-assign a basic_file from a file of another executor type. /** * This assignment operator moves a file from one object to another. * * @param other The other basic_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_file(const executor_type&) constructor. */ template <typename Executor1> constraint_t< is_convertible<Executor1, Executor>::value, basic_file& > operator=(basic_file<Executor1>&& other) { basic_file tmp(std::move(other)); impl_ = std::move(tmp.impl_); return *this; } /// Get the executor associated with the object. const executor_type& get_executor() noexcept { return impl_.get_executor(); } /// Open the file using the specified path. /** * This function opens the file so that it will use the specified path. * * @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 boost::system::system_error Thrown on failure. * * @par Example * @code * boost::asio::stream_file file(my_context); * file.open("/path/to/my/file", boost::asio::stream_file::read_only); * @endcode */ void open(const char* path, file_base::flags open_flags) { boost::system::error_code ec; impl_.get_service().open(impl_.get_implementation(), path, open_flags, ec); boost::asio::detail::throw_error(ec, "open"); } /// Open the file using the specified path. /** * This function opens the file so that it will use the specified path. * * @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. * * @param ec Set to indicate what error occurred, if any. * * @par Example * @code * boost::asio::stream_file file(my_context); * boost::system::error_code ec; * file.open("/path/to/my/file", boost::asio::stream_file::read_only, ec); * if (ec) * { * // An error occurred. * } * @endcode */ BOOST_ASIO_SYNC_OP_VOID open(const char* path, file_base::flags open_flags, boost::system::error_code& ec) { impl_.get_service().open(impl_.get_implementation(), path, open_flags, ec); BOOST_ASIO_SYNC_OP_VOID_RETURN(ec); } /// Open the file using the specified path. /** * This function opens the file so that it will use the specified path. * * @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 boost::system::system_error Thrown on failure. * * @par Example * @code * boost::asio::stream_file file(my_context); * file.open("/path/to/my/file", boost::asio::stream_file::read_only); * @endcode */ void open(const std::string& path, file_base::flags open_flags) { boost::system::error_code ec; impl_.get_service().open(impl_.get_implementation(), path.c_str(), open_flags, ec); boost::asio::detail::throw_error(ec, "open"); } /// Open the file using the specified path. /** * This function opens the file so that it will use the specified path. * * @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. * * @param ec Set to indicate what error occurred, if any. * * @par Example * @code * boost::asio::stream_file file(my_context); * boost::system::error_code ec; * file.open("/path/to/my/file", boost::asio::stream_file::read_only, ec); * if (ec) * { * // An error occurred. * } * @endcode */ BOOST_ASIO_SYNC_OP_VOID open(const std::string& path, file_base::flags open_flags, boost::system::error_code& ec) { impl_.get_service().open(impl_.get_implementation(), path.c_str(), open_flags, ec); BOOST_ASIO_SYNC_OP_VOID_RETURN(ec); } /// Assign an existing native file to the file. /* * This function opens the file to hold an existing native file. * * @param native_file A native file. * * @throws boost::system::system_error Thrown on failure. */ void assign(const native_handle_type& native_file) { boost::system::error_code ec; impl_.get_service().assign( impl_.get_implementation(), native_file, ec); boost::asio::detail::throw_error(ec, "assign"); } /// Assign an existing native file to the file. /* * This function opens the file to hold an existing native file. * * @param native_file A native file. * * @param ec Set to indicate what error occurred, if any. */ BOOST_ASIO_SYNC_OP_VOID assign(const native_handle_type& native_file, boost::system::error_code& ec) { impl_.get_service().assign( impl_.get_implementation(), native_file, ec); BOOST_ASIO_SYNC_OP_VOID_RETURN(ec); } /// Determine whether the file is open. bool is_open() const { return impl_.get_service().is_open(impl_.get_implementation()); } /// Close the file. /** * This function is used to close the file. Any asynchronous read or write * operations will be cancelled immediately, and will complete with the * boost::asio::error::operation_aborted error. * * @throws boost::system::system_error Thrown on failure. Note that, even if * the function indicates an error, the underlying descriptor is closed. */ void close() { boost::system::error_code ec; impl_.get_service().close(impl_.get_implementation(), ec); boost::asio::detail::throw_error(ec, "close"); } /// Close the file. /** * This function is used to close the file. Any asynchronous read or write * operations will be cancelled immediately, and will complete with the * boost::asio::error::operation_aborted error. * * @param ec Set to indicate what error occurred, if any. Note that, even if * the function indicates an error, the underlying descriptor is closed. * * @par Example * @code * boost::asio::stream_file file(my_context); * ... * boost::system::error_code ec; * file.close(ec); * if (ec) * { * // An error occurred. * } * @endcode */ BOOST_ASIO_SYNC_OP_VOID close(boost::system::error_code& ec) { impl_.get_service().close(impl_.get_implementation(), ec); BOOST_ASIO_SYNC_OP_VOID_RETURN(ec); } /// Release ownership of the underlying native file. /** * This function causes all outstanding asynchronous read and write * operations to finish immediately, and the handlers for cancelled * operations will be passed the boost::asio::error::operation_aborted error. * Ownership of the native file is then transferred to the caller. * * @throws boost::system::system_error Thrown on failure. * * @note This function is unsupported on Windows versions prior to Windows * 8.1, and will fail with boost::asio::error::operation_not_supported on * these platforms. */ #if defined(BOOST_ASIO_MSVC) && (BOOST_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() { boost::system::error_code ec; native_handle_type s = impl_.get_service().release( impl_.get_implementation(), ec); boost::asio::detail::throw_error(ec, "release"); return s; } /// Release ownership of the underlying native file. /** * This function causes all outstanding asynchronous read and write * operations to finish immediately, and the handlers for cancelled * operations will be passed the boost::asio::error::operation_aborted error. * Ownership of the native file 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 boost::asio::error::operation_not_supported on * these platforms. */ #if defined(BOOST_ASIO_MSVC) && (BOOST_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(boost::system::error_code& ec) { return impl_.get_service().release(impl_.get_implementation(), ec); } /// Get the native file representation. /** * This function may be used to obtain the underlying representation of the * file. This is intended to allow access to native file 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 file. /** * This function causes all outstanding asynchronous read and write * operations to finish immediately, and the handlers for cancelled * operations will be passed the boost::asio::error::operation_aborted error. * * @throws boost::system::system_error Thrown on failure. * * @note Calls to cancel() will always fail with * boost::asio::error::operation_not_supported when run on Windows XP, Windows * Server 2003, and earlier versions of Windows, unless * BOOST_ASIO_ENABLE_CANCELIO is defined. However, the CancelIo function has * two issues that should be considered before enabling its use: * * @li It will only cancel asynchronous operations that were initiated in the * current thread. * * @li It can appear to complete without error, but the request to cancel the * unfinished operations may be silently ignored by the operating system. * Whether it works or not seems to depend on the drivers that are installed. * * For portable cancellation, consider using the close() function to * simultaneously cancel the outstanding operations and close the file. * * When running on Windows Vista, Windows Server 2008, and later, the * CancelIoEx function is always used. This function does not have the * problems described above. */ #if defined(BOOST_ASIO_MSVC) && (BOOST_ASIO_MSVC >= 1400) \ && (!defined(_WIN32_WINNT) || _WIN32_WINNT < 0x0600) \ && !defined(BOOST_ASIO_ENABLE_CANCELIO) __declspec(deprecated("By default, this function always fails with " "operation_not_supported when used on Windows XP, Windows Server 2003, " "or earlier. Consult documentation for details.")) #endif void cancel() { boost::system::error_code ec; impl_.get_service().cancel(impl_.get_implementation(), ec); boost::asio::detail::throw_error(ec, "cancel"); } /// Cancel all asynchronous operations associated with the file. /** * This function causes all outstanding asynchronous read and write * operations to finish immediately, and the handlers for cancelled * operations will be passed the boost::asio::error::operation_aborted error. * * @param ec Set to indicate what error occurred, if any. * * @note Calls to cancel() will always fail with * boost::asio::error::operation_not_supported when run on Windows XP, Windows * Server 2003, and earlier versions of Windows, unless * BOOST_ASIO_ENABLE_CANCELIO is defined. However, the CancelIo function has * two issues that should be considered before enabling its use: * * @li It will only cancel asynchronous operations that were initiated in the * current thread. * * @li It can appear to complete without error, but the request to cancel the * unfinished operations may be silently ignored by the operating system. * Whether it works or not seems to depend on the drivers that are installed. * * For portable cancellation, consider using the close() function to * simultaneously cancel the outstanding operations and close the file. * * When running on Windows Vista, Windows Server 2008, and later, the * CancelIoEx function is always used. This function does not have the * problems described above. */ #if defined(BOOST_ASIO_MSVC) && (BOOST_ASIO_MSVC >= 1400) \ && (!defined(_WIN32_WINNT) || _WIN32_WINNT < 0x0600) \ && !defined(BOOST_ASIO_ENABLE_CANCELIO) __declspec(deprecated("By default, this function always fails with " "operation_not_supported when used on Windows XP, Windows Server 2003, " "or earlier. Consult documentation for details.")) #endif BOOST_ASIO_SYNC_OP_VOID cancel(boost::system::error_code& ec) { impl_.get_service().cancel(impl_.get_implementation(), ec); BOOST_ASIO_SYNC_OP_VOID_RETURN(ec); } /// Get the size of the file. /** * This function determines the size of the file, in bytes. * * @throws boost::system::system_error Thrown on failure. */ uint64_t size() const { boost::system::error_code ec; uint64_t s = impl_.get_service().size(impl_.get_implementation(), ec); boost::asio::detail::throw_error(ec, "size"); return s; } /// Get the size of the file. /** * This function determines the size of the file, in bytes. * * @param ec Set to indicate what error occurred, if any. */ uint64_t size(boost::system::error_code& ec) const { return impl_.get_service().size(impl_.get_implementation(), ec); } /// Alter the size of the file. /** * This function resizes the file to the specified size, in bytes. If the * current file size exceeds @c n then any extra data is discarded. If the * current size is less than @c n then the file is extended and filled with * zeroes. * * @param n The new size for the file. * * @throws boost::system::system_error Thrown on failure. */ void resize(uint64_t n) { boost::system::error_code ec; impl_.get_service().resize(impl_.get_implementation(), n, ec); boost::asio::detail::throw_error(ec, "resize"); } /// Alter the size of the file. /** * This function resizes the file to the specified size, in bytes. If the * current file size exceeds @c n then any extra data is discarded. If the * current size is less than @c n then the file is extended and filled with * zeroes. * * @param n The new size for the file. * * @param ec Set to indicate what error occurred, if any. */ BOOST_ASIO_SYNC_OP_VOID resize(uint64_t n, boost::system::error_code& ec) { impl_.get_service().resize(impl_.get_implementation(), n, ec); BOOST_ASIO_SYNC_OP_VOID_RETURN(ec); } /// Synchronise the file to disk. /** * This function synchronises the file data and metadata to disk. Note that * the semantics of this synchronisation vary between operation systems. * * @throws boost::system::system_error Thrown on failure. */ void sync_all() { boost::system::error_code ec; impl_.get_service().sync_all(impl_.get_implementation(), ec); boost::asio::detail::throw_error(ec, "sync_all"); } /// Synchronise the file to disk. /** * This function synchronises the file data and metadata to disk. Note that * the semantics of this synchronisation vary between operation systems. * * @param ec Set to indicate what error occurred, if any. */ BOOST_ASIO_SYNC_OP_VOID sync_all(boost::system::error_code& ec) { impl_.get_service().sync_all(impl_.get_implementation(), ec); BOOST_ASIO_SYNC_OP_VOID_RETURN(ec); } /// Synchronise the file data to disk. /** * This function synchronises the file data to disk. Note that the semantics * of this synchronisation vary between operation systems. * * @throws boost::system::system_error Thrown on failure. */ void sync_data() { boost::system::error_code ec; impl_.get_service().sync_data(impl_.get_implementation(), ec); boost::asio::detail::throw_error(ec, "sync_data"); } /// Synchronise the file data to disk. /** * This function synchronises the file data to disk. Note that the semantics * of this synchronisation vary between operation systems. * * @param ec Set to indicate what error occurred, if any. */ BOOST_ASIO_SYNC_OP_VOID sync_data(boost::system::error_code& ec) { impl_.get_service().sync_data(impl_.get_implementation(), ec); BOOST_ASIO_SYNC_OP_VOID_RETURN(ec); } protected: /// Protected destructor to prevent deletion through this type. /** * This function destroys the file, cancelling any outstanding asynchronous * operations associated with the file as if by calling @c cancel. */ ~basic_file() { } #if defined(BOOST_ASIO_HAS_IOCP) detail::io_object_impl<detail::win_iocp_file_service, Executor> impl_; #elif defined(BOOST_ASIO_HAS_IO_URING) detail::io_object_impl<detail::io_uring_file_service, Executor> impl_; #endif private: // Disallow copying and assignment. basic_file(const basic_file&) = delete; basic_file& operator=(const basic_file&) = delete; }; } // namespace asio } // namespace boost #include <boost/asio/detail/pop_options.hpp> #endif // defined(BOOST_ASIO_HAS_FILE) // || defined(GENERATING_DOCUMENTATION) #endif // BOOST_ASIO_BASIC_FILE_HPP
hpp
asio
data/projects/asio/include/boost/asio/cancellation_state.hpp
// // cancellation_state.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 BOOST_ASIO_CANCELLATION_STATE_HPP #define BOOST_ASIO_CANCELLATION_STATE_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <boost/asio/detail/config.hpp> #include <cassert> #include <new> #include <utility> #include <boost/asio/cancellation_signal.hpp> #include <boost/asio/detail/cstddef.hpp> #include <boost/asio/detail/push_options.hpp> namespace boost { namespace asio { /// A simple cancellation signal propagation filter. template <cancellation_type_t Mask> struct cancellation_filter { /// Returns <tt>type & Mask</tt>. cancellation_type_t operator()( cancellation_type_t type) const noexcept { return type & Mask; } }; /// A cancellation filter that disables cancellation. typedef cancellation_filter<cancellation_type::none> disable_cancellation; /// A cancellation filter that enables terminal cancellation only. typedef cancellation_filter<cancellation_type::terminal> enable_terminal_cancellation; #if defined(GENERATING_DOCUMENTATION) /// A cancellation filter that enables terminal and partial cancellation. typedef cancellation_filter< cancellation_type::terminal | cancellation_type::partial> enable_partial_cancellation; /// A cancellation filter that enables terminal, partial and total cancellation. typedef cancellation_filter<cancellation_type::terminal | cancellation_type::partial | cancellation_type::total> enable_total_cancellation; #else // defined(GENERATING_DOCUMENTATION) typedef cancellation_filter< static_cast<cancellation_type_t>( static_cast<unsigned int>(cancellation_type::terminal) | static_cast<unsigned int>(cancellation_type::partial))> enable_partial_cancellation; typedef cancellation_filter< static_cast<cancellation_type_t>( static_cast<unsigned int>(cancellation_type::terminal) | static_cast<unsigned int>(cancellation_type::partial) | static_cast<unsigned int>(cancellation_type::total))> enable_total_cancellation; #endif // defined(GENERATING_DOCUMENTATION) /// A cancellation state is used for chaining signals and slots in compositions. class cancellation_state { public: /// Construct a disconnected cancellation state. constexpr cancellation_state() noexcept : impl_(0) { } /// Construct and attach to a parent slot to create a new child slot. /** * Initialises the cancellation state so that it allows terminal cancellation * only. Equivalent to <tt>cancellation_state(slot, * enable_terminal_cancellation())</tt>. * * @param slot The parent cancellation slot to which the state will be * attached. */ template <typename CancellationSlot> constexpr explicit cancellation_state(CancellationSlot slot) : impl_(slot.is_connected() ? &slot.template emplace<impl<>>() : 0) { } /// Construct and attach to a parent slot to create a new child slot. /** * @param slot The parent cancellation slot to which the state will be * attached. * * @param filter A function object that is used to transform incoming * cancellation signals as they are received from the parent slot. This * function object must have the signature: * @code boost::asio::cancellation_type_t filter( * boost::asio::cancellation_type_t); @endcode * * The library provides the following pre-defined cancellation filters: * * @li boost::asio::disable_cancellation * @li boost::asio::enable_terminal_cancellation * @li boost::asio::enable_partial_cancellation * @li boost::asio::enable_total_cancellation */ template <typename CancellationSlot, typename Filter> constexpr cancellation_state(CancellationSlot slot, Filter filter) : impl_(slot.is_connected() ? &slot.template emplace<impl<Filter, Filter>>(filter, filter) : 0) { } /// Construct and attach to a parent slot to create a new child slot. /** * @param slot The parent cancellation slot to which the state will be * attached. * * @param in_filter A function object that is used to transform incoming * cancellation signals as they are received from the parent slot. This * function object must have the signature: * @code boost::asio::cancellation_type_t in_filter( * boost::asio::cancellation_type_t); @endcode * * @param out_filter A function object that is used to transform outcoming * cancellation signals as they are relayed to the child slot. This function * object must have the signature: * @code boost::asio::cancellation_type_t out_filter( * boost::asio::cancellation_type_t); @endcode * * The library provides the following pre-defined cancellation filters: * * @li boost::asio::disable_cancellation * @li boost::asio::enable_terminal_cancellation * @li boost::asio::enable_partial_cancellation * @li boost::asio::enable_total_cancellation */ template <typename CancellationSlot, typename InFilter, typename OutFilter> constexpr cancellation_state(CancellationSlot slot, InFilter in_filter, OutFilter out_filter) : impl_(slot.is_connected() ? &slot.template emplace<impl<InFilter, OutFilter>>( static_cast<InFilter&&>(in_filter), static_cast<OutFilter&&>(out_filter)) : 0) { } /// Returns the single child slot associated with the state. /** * This sub-slot is used with the operations that are being composed. */ constexpr cancellation_slot slot() const noexcept { return impl_ ? impl_->signal_.slot() : cancellation_slot(); } /// Returns the cancellation types that have been triggered. cancellation_type_t cancelled() const noexcept { return impl_ ? impl_->cancelled_ : cancellation_type_t(); } /// Clears the specified cancellation types, if they have been triggered. void clear(cancellation_type_t mask = cancellation_type::all) noexcept { if (impl_) impl_->cancelled_ &= ~mask; } private: struct impl_base { impl_base() : cancelled_() { } cancellation_signal signal_; cancellation_type_t cancelled_; }; template < typename InFilter = enable_terminal_cancellation, typename OutFilter = InFilter> struct impl : impl_base { impl() : in_filter_(), out_filter_() { } impl(InFilter in_filter, OutFilter out_filter) : in_filter_(static_cast<InFilter&&>(in_filter)), out_filter_(static_cast<OutFilter&&>(out_filter)) { } void operator()(cancellation_type_t in) { this->cancelled_ = in_filter_(in); cancellation_type_t out = out_filter_(this->cancelled_); if (out != cancellation_type::none) this->signal_.emit(out); } InFilter in_filter_; OutFilter out_filter_; }; impl_base* impl_; }; } // namespace asio } // namespace boost #include <boost/asio/detail/pop_options.hpp> #endif // BOOST_ASIO_CANCELLATION_STATE_HPP
hpp
asio
data/projects/asio/include/boost/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 BOOST_ASIO_AS_TUPLE_HPP #define BOOST_ASIO_AS_TUPLE_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <boost/asio/detail/config.hpp> #include <boost/asio/detail/type_traits.hpp> #include <boost/asio/detail/push_options.hpp> namespace boost { 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_; }; /// Adapt a @ref completion_token to specify that the completion handler /// arguments should be combined into a single tuple argument. template <typename CompletionToken> BOOST_ASIO_NODISCARD inline constexpr as_tuple_t<decay_t<CompletionToken>> as_tuple(CompletionToken&& completion_token) { return as_tuple_t<decay_t<CompletionToken>>( static_cast<CompletionToken&&>(completion_token)); } } // namespace asio } // namespace boost #include <boost/asio/detail/pop_options.hpp> #include <boost/asio/impl/as_tuple.hpp> #endif // BOOST_ASIO_AS_TUPLE_HPP
hpp
asio
data/projects/asio/include/boost/asio/registered_buffer.hpp
// // registered_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 BOOST_ASIO_REGISTERED_BUFFER_HPP #define BOOST_ASIO_REGISTERED_BUFFER_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <boost/asio/detail/config.hpp> #include <boost/asio/buffer.hpp> #include <boost/asio/detail/push_options.hpp> namespace boost { namespace asio { namespace detail { class buffer_registration_base; } // namespace detail class const_registered_buffer; /// Type used to identify a registered buffer. class registered_buffer_id { public: /// The native buffer identifier type. typedef int native_handle_type; /// Default constructor creates an invalid registered buffer identifier. registered_buffer_id() noexcept : scope_(0), index_(-1) { } /// Get the native buffer identifier type. native_handle_type native_handle() const noexcept { return index_; } /// Compare two IDs for equality. friend bool operator==(const registered_buffer_id& lhs, const registered_buffer_id& rhs) noexcept { return lhs.scope_ == rhs.scope_ && lhs.index_ == rhs.index_; } /// Compare two IDs for equality. friend bool operator!=(const registered_buffer_id& lhs, const registered_buffer_id& rhs) noexcept { return lhs.scope_ != rhs.scope_ || lhs.index_ != rhs.index_; } private: friend class detail::buffer_registration_base; // Hidden constructor used by buffer registration. registered_buffer_id(const void* scope, int index) noexcept : scope_(scope), index_(index) { } const void* scope_; int index_; }; /// Holds a registered buffer over modifiable data. /** * Satisfies the @c MutableBufferSequence type requirements. */ class mutable_registered_buffer { public: /// Default constructor creates an invalid registered buffer. mutable_registered_buffer() noexcept : buffer_(), id_() { } /// Get the underlying mutable buffer. const mutable_buffer& buffer() const noexcept { return buffer_; } /// Get a pointer to the beginning of the memory range. /** * @returns <tt>buffer().data()</tt>. */ void* data() const noexcept { return buffer_.data(); } /// Get the size of the memory range. /** * @returns <tt>buffer().size()</tt>. */ std::size_t size() const noexcept { return buffer_.size(); } /// Get the registered buffer identifier. const registered_buffer_id& id() const noexcept { return id_; } /// Move the start of the buffer by the specified number of bytes. mutable_registered_buffer& operator+=(std::size_t n) noexcept { buffer_ += n; return *this; } private: friend class detail::buffer_registration_base; // Hidden constructor used by buffer registration and operators. mutable_registered_buffer(const mutable_buffer& b, const registered_buffer_id& i) noexcept : buffer_(b), id_(i) { } #if !defined(GENERATING_DOCUMENTATION) friend mutable_registered_buffer buffer( const mutable_registered_buffer& b, std::size_t n) noexcept; #endif // !defined(GENERATING_DOCUMENTATION) mutable_buffer buffer_; registered_buffer_id id_; }; /// Holds a registered buffer over non-modifiable data. /** * Satisfies the @c ConstBufferSequence type requirements. */ class const_registered_buffer { public: /// Default constructor creates an invalid registered buffer. const_registered_buffer() noexcept : buffer_(), id_() { } /// Construct a non-modifiable buffer from a modifiable one. const_registered_buffer( const mutable_registered_buffer& b) noexcept : buffer_(b.buffer()), id_(b.id()) { } /// Get the underlying constant buffer. const const_buffer& buffer() const noexcept { return buffer_; } /// Get a pointer to the beginning of the memory range. /** * @returns <tt>buffer().data()</tt>. */ const void* data() const noexcept { return buffer_.data(); } /// Get the size of the memory range. /** * @returns <tt>buffer().size()</tt>. */ std::size_t size() const noexcept { return buffer_.size(); } /// Get the registered buffer identifier. const registered_buffer_id& id() const noexcept { return id_; } /// Move the start of the buffer by the specified number of bytes. const_registered_buffer& operator+=(std::size_t n) noexcept { buffer_ += n; return *this; } private: // Hidden constructor used by operators. const_registered_buffer(const const_buffer& b, const registered_buffer_id& i) noexcept : buffer_(b), id_(i) { } #if !defined(GENERATING_DOCUMENTATION) friend const_registered_buffer buffer( const const_registered_buffer& b, std::size_t n) noexcept; #endif // !defined(GENERATING_DOCUMENTATION) const_buffer buffer_; registered_buffer_id id_; }; /** @addtogroup buffer_sequence_begin */ /// Get an iterator to the first element in a buffer sequence. inline const mutable_buffer* buffer_sequence_begin( const mutable_registered_buffer& b) noexcept { return &b.buffer(); } /// Get an iterator to the first element in a buffer sequence. inline const const_buffer* buffer_sequence_begin( const const_registered_buffer& b) noexcept { return &b.buffer(); } /** @} */ /** @addtogroup buffer_sequence_end */ /// Get an iterator to one past the end element in a buffer sequence. inline const mutable_buffer* buffer_sequence_end( const mutable_registered_buffer& b) noexcept { return &b.buffer() + 1; } /// Get an iterator to one past the end element in a buffer sequence. inline const const_buffer* buffer_sequence_end( const const_registered_buffer& b) noexcept { return &b.buffer() + 1; } /** @} */ /** @addtogroup buffer */ /// Obtain a buffer representing the entire registered buffer. inline mutable_registered_buffer buffer( const mutable_registered_buffer& b) noexcept { return b; } /// Obtain a buffer representing the entire registered buffer. inline const_registered_buffer buffer( const const_registered_buffer& b) noexcept { return b; } /// Obtain a buffer representing part of a registered buffer. inline mutable_registered_buffer buffer( const mutable_registered_buffer& b, std::size_t n) noexcept { return mutable_registered_buffer(buffer(b.buffer_, n), b.id_); } /// Obtain a buffer representing part of a registered buffer. inline const_registered_buffer buffer( const const_registered_buffer& b, std::size_t n) noexcept { return const_registered_buffer(buffer(b.buffer_, n), b.id_); } /** @} */ /// Create a new modifiable registered buffer that is offset from the start of /// another. /** * @relates mutable_registered_buffer */ inline mutable_registered_buffer operator+( const mutable_registered_buffer& b, std::size_t n) noexcept { mutable_registered_buffer tmp(b); tmp += n; return tmp; } /// Create a new modifiable buffer that is offset from the start of another. /** * @relates mutable_registered_buffer */ inline mutable_registered_buffer operator+(std::size_t n, const mutable_registered_buffer& b) noexcept { return b + n; } /// Create a new non-modifiable registered buffer that is offset from the start /// of another. /** * @relates const_registered_buffer */ inline const_registered_buffer operator+(const const_registered_buffer& b, std::size_t n) noexcept { const_registered_buffer tmp(b); tmp += n; return tmp; } /// Create a new non-modifiable buffer that is offset from the start of another. /** * @relates const_registered_buffer */ inline const_registered_buffer operator+(std::size_t n, const const_registered_buffer& b) noexcept { return b + n; } } // namespace asio } // namespace boost #include <boost/asio/detail/pop_options.hpp> #endif // BOOST_ASIO_REGISTERED_BUFFER_HPP
hpp
asio
data/projects/asio/include/boost/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 BOOST_ASIO_COMPOSE_HPP #define BOOST_ASIO_COMPOSE_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <boost/asio/detail/config.hpp> #include <boost/asio/associated_executor.hpp> #include <boost/asio/async_result.hpp> #include <boost/asio/detail/base_from_cancellation_state.hpp> #include <boost/asio/detail/composed_work.hpp> #include <boost/asio/detail/handler_cont_helpers.hpp> #include <boost/asio/detail/type_traits.hpp> #include <boost/asio/detail/push_options.hpp> namespace boost { namespace asio { namespace detail { template <typename Impl, typename Work, typename Handler, typename Signature> class composed_op; template <typename Impl, typename Work, typename Handler, typename R, typename... Args> class composed_op<Impl, Work, Handler, R(Args...)> : 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)...); } void complete(Args... args) { this->work_.reset(); 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 Signature> inline bool asio_handler_is_continuation( composed_op<Impl, Work, Handler, Signature>* this_handler) { return this_handler->invocations_ > 1 ? true : boost_asio_handler_cont_helpers::is_continuation( this_handler->handler_); } template <typename Signature, typename Executors> class initiate_composed_op { public: typedef typename composed_io_executors<Executors>::head_type executor_type; template <typename T> explicit initiate_composed_op(int, T&& executors) : executors_(static_cast<T&&>(executors)) { } executor_type get_executor() const noexcept { return executors_.head_; } template <typename Handler, typename Impl> void operator()(Handler&& handler, Impl&& impl) const { composed_op<decay_t<Impl>, composed_work<Executors>, decay_t<Handler>, Signature>( static_cast<Impl&&>(impl), composed_work<Executors>(executors_), static_cast<Handler&&>(handler))(); } private: composed_io_executors<Executors> executors_; }; template <typename Signature, typename Executors> inline initiate_composed_op<Signature, Executors> make_initiate_composed_op( composed_io_executors<Executors>&& executors) { return initiate_composed_op<Signature, Executors>(0, 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) /// 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_; * boost::asio::mutable_buffer buffer_; * enum { starting, reading, writing } state_; * * template <typename Self> * void operator()(Self& self, * boost::system::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; * boost::asio::async_write(socket_, buffer_, * boost::asio::transfer_exactly(n), * std::move(self)); * } * break; * case writing: * self.complete(error, n); * break; * } * } * }; * * template <typename CompletionToken> * auto async_echo(tcp::socket& socket, * boost::asio::mutable_buffer buffer, * CompletionToken&& token) -> * decltype( * boost::asio::async_compose<CompletionToken, * void(boost::system::error_code, std::size_t)>( * std::declval<async_echo_implementation>(), * token, socket)) * { * return boost::asio::async_compose<CompletionToken, * void(boost::system::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> auto async_compose(Implementation&& implementation, type_identity_t<CompletionToken>& token, IoObjectsOrExecutors&&... io_objects_or_executors) -> decltype( async_initiate<CompletionToken, Signature>( detail::make_initiate_composed_op<Signature>( detail::make_composed_io_executors( detail::get_composed_io_executor( static_cast<IoObjectsOrExecutors&&>( io_objects_or_executors))...)), token, static_cast<Implementation&&>(implementation))) { return async_initiate<CompletionToken, Signature>( detail::make_initiate_composed_op<Signature>( detail::make_composed_io_executors( detail::get_composed_io_executor( static_cast<IoObjectsOrExecutors&&>( io_objects_or_executors))...)), token, static_cast<Implementation&&>(implementation)); } } // namespace asio } // namespace boost #include <boost/asio/detail/pop_options.hpp> #endif // BOOST_ASIO_COMPOSE_HPP
hpp
asio
data/projects/asio/include/boost/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 BOOST_ASIO_IS_EXECUTOR_HPP #define BOOST_ASIO_IS_EXECUTOR_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <boost/asio/detail/config.hpp> #include <boost/asio/detail/is_executor.hpp> #include <boost/asio/detail/push_options.hpp> namespace boost { 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) : boost::asio::detail::is_executor<T> #endif // defined(GENERATING_DOCUMENTATION) { }; } // namespace asio } // namespace boost #include <boost/asio/detail/pop_options.hpp> #endif // BOOST_ASIO_IS_EXECUTOR_HPP
hpp
asio
data/projects/asio/include/boost/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 BOOST_ASIO_REQUIRE_CONCEPT_HPP #define BOOST_ASIO_REQUIRE_CONCEPT_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <boost/asio/detail/config.hpp> #include <boost/asio/detail/type_traits.hpp> #include <boost/asio/is_applicable_property.hpp> #include <boost/asio/traits/require_concept_member.hpp> #include <boost/asio/traits/require_concept_free.hpp> #include <boost/asio/traits/static_require_concept.hpp> #include <boost/asio/detail/push_options.hpp> #if defined(GENERATING_DOCUMENTATION) namespace boost { 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>boost::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>boost::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>boost::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>boost::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>boost::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>boost::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 } // namespace boost #else // defined(GENERATING_DOCUMENTATION) namespace boost_asio_require_concept_fn { using boost::asio::conditional_t; using boost::asio::decay_t; using boost::asio::declval; using boost::asio::enable_if_t; using boost::asio::is_applicable_property; using boost::asio::traits::require_concept_free; using boost::asio::traits::require_concept_member; using boost::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(BOOST_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(BOOST_ASIO_HAS_DEDUCED_REQUIRE_CONCEPT_MEMBER_TRAIT) typedef T type; #endif // defined(BOOST_ASIO_HAS_DEDUCED_REQUIRE_CONCEPT_MEMBER_TRAIT) }; template <typename T, typename Property> BOOST_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> BOOST_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> BOOST_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 boost_asio_require_concept_fn namespace boost { namespace asio { namespace { static constexpr const boost_asio_require_concept_fn::impl& require_concept = boost_asio_require_concept_fn::static_instance<>::instance; } // namespace typedef boost_asio_require_concept_fn::impl require_concept_t; template <typename T, typename Property> struct can_require_concept : integral_constant<bool, boost_asio_require_concept_fn::call_traits< require_concept_t, T, void(Property)>::overload != boost_asio_require_concept_fn::ill_formed> { }; #if defined(BOOST_ASIO_HAS_VARIABLE_TEMPLATES) template <typename T, typename Property> constexpr bool can_require_concept_v = can_require_concept<T, Property>::value; #endif // defined(BOOST_ASIO_HAS_VARIABLE_TEMPLATES) template <typename T, typename Property> struct is_nothrow_require_concept : integral_constant<bool, boost_asio_require_concept_fn::call_traits< require_concept_t, T, void(Property)>::is_noexcept> { }; #if defined(BOOST_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(BOOST_ASIO_HAS_VARIABLE_TEMPLATES) template <typename T, typename Property> struct require_concept_result { typedef typename boost_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 } // namespace boost #endif // defined(GENERATING_DOCUMENTATION) #include <boost/asio/detail/pop_options.hpp> #endif // BOOST_ASIO_REQUIRE_CONCEPT_HPP
hpp
asio
data/projects/asio/include/boost/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 BOOST_ASIO_BASIC_IO_OBJECT_HPP #define BOOST_ASIO_BASIC_IO_OBJECT_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <boost/asio/detail/config.hpp> #include <boost/asio/io_context.hpp> #include <boost/asio/detail/push_options.hpp> namespace boost { 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(BOOST_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. */ boost::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. */ boost::asio::io_context& get_io_service() { return service_.get_io_context(); } #endif // !defined(BOOST_ASIO_NO_DEPRECATED) /// The type of the executor associated with the object. typedef boost::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(boost::asio::io_context& io_context) : service_(boost::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(BOOST_ASIO_NO_DEPRECATED) boost::asio::io_context& get_io_context() { return service_->get_io_context(); } boost::asio::io_context& get_io_service() { return service_->get_io_context(); } #endif // !defined(BOOST_ASIO_NO_DEPRECATED) typedef boost::asio::io_context::executor_type executor_type; executor_type get_executor() noexcept { return service_->get_io_context().get_executor(); } protected: explicit basic_io_object(boost::asio::io_context& io_context) : service_(&boost::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_(&boost::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 } // namespace boost #include <boost/asio/detail/pop_options.hpp> #endif // BOOST_ASIO_BASIC_IO_OBJECT_HPP
hpp
asio
data/projects/asio/include/boost/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 BOOST_ASIO_SOCKET_BASE_HPP #define BOOST_ASIO_SOCKET_BASE_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <boost/asio/detail/config.hpp> #include <boost/asio/detail/io_control.hpp> #include <boost/asio/detail/socket_option.hpp> #include <boost/asio/detail/socket_types.hpp> #include <boost/asio/detail/push_options.hpp> namespace boost { 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 = BOOST_ASIO_OS_DEF(SHUT_RD), shutdown_send = BOOST_ASIO_OS_DEF(SHUT_WR), shutdown_both = BOOST_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 BOOST_ASIO_STATIC_CONSTANT(int, message_peek = BOOST_ASIO_OS_DEF(MSG_PEEK)); BOOST_ASIO_STATIC_CONSTANT(int, message_out_of_band = BOOST_ASIO_OS_DEF(MSG_OOB)); BOOST_ASIO_STATIC_CONSTANT(int, message_do_not_route = BOOST_ASIO_OS_DEF(MSG_DONTROUTE)); BOOST_ASIO_STATIC_CONSTANT(int, message_end_of_record = BOOST_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 * boost::asio::ip::udp::socket socket(my_context); * ... * boost::asio::socket_base::broadcast option(true); * socket.set_option(option); * @endcode * * @par * Getting the current option value: * @code * boost::asio::ip::udp::socket socket(my_context); * ... * boost::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 boost::asio::detail::socket_option::boolean< BOOST_ASIO_OS_DEF(SOL_SOCKET), BOOST_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 * boost::asio::ip::tcp::socket socket(my_context); * ... * boost::asio::socket_base::debug option(true); * socket.set_option(option); * @endcode * * @par * Getting the current option value: * @code * boost::asio::ip::tcp::socket socket(my_context); * ... * boost::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 boost::asio::detail::socket_option::boolean< BOOST_ASIO_OS_DEF(SOL_SOCKET), BOOST_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 * boost::asio::ip::udp::socket socket(my_context); * ... * boost::asio::socket_base::do_not_route option(true); * socket.set_option(option); * @endcode * * @par * Getting the current option value: * @code * boost::asio::ip::udp::socket socket(my_context); * ... * boost::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 boost::asio::detail::socket_option::boolean< BOOST_ASIO_OS_DEF(SOL_SOCKET), BOOST_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 * boost::asio::ip::tcp::socket socket(my_context); * ... * boost::asio::socket_base::keep_alive option(true); * socket.set_option(option); * @endcode * * @par * Getting the current option value: * @code * boost::asio::ip::tcp::socket socket(my_context); * ... * boost::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 boost::asio::detail::socket_option::boolean< BOOST_ASIO_OS_DEF(SOL_SOCKET), BOOST_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 * boost::asio::ip::tcp::socket socket(my_context); * ... * boost::asio::socket_base::send_buffer_size option(8192); * socket.set_option(option); * @endcode * * @par * Getting the current option value: * @code * boost::asio::ip::tcp::socket socket(my_context); * ... * boost::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 boost::asio::detail::socket_option::integer< BOOST_ASIO_OS_DEF(SOL_SOCKET), BOOST_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 * boost::asio::ip::tcp::socket socket(my_context); * ... * boost::asio::socket_base::send_low_watermark option(1024); * socket.set_option(option); * @endcode * * @par * Getting the current option value: * @code * boost::asio::ip::tcp::socket socket(my_context); * ... * boost::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 boost::asio::detail::socket_option::integer< BOOST_ASIO_OS_DEF(SOL_SOCKET), BOOST_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 * boost::asio::ip::tcp::socket socket(my_context); * ... * boost::asio::socket_base::receive_buffer_size option(8192); * socket.set_option(option); * @endcode * * @par * Getting the current option value: * @code * boost::asio::ip::tcp::socket socket(my_context); * ... * boost::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 boost::asio::detail::socket_option::integer< BOOST_ASIO_OS_DEF(SOL_SOCKET), BOOST_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 * boost::asio::ip::tcp::socket socket(my_context); * ... * boost::asio::socket_base::receive_low_watermark option(1024); * socket.set_option(option); * @endcode * * @par * Getting the current option value: * @code * boost::asio::ip::tcp::socket socket(my_context); * ... * boost::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 boost::asio::detail::socket_option::integer< BOOST_ASIO_OS_DEF(SOL_SOCKET), BOOST_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 * boost::asio::ip::tcp::acceptor acceptor(my_context); * ... * boost::asio::socket_base::reuse_address option(true); * acceptor.set_option(option); * @endcode * * @par * Getting the current option value: * @code * boost::asio::ip::tcp::acceptor acceptor(my_context); * ... * boost::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 boost::asio::detail::socket_option::boolean< BOOST_ASIO_OS_DEF(SOL_SOCKET), BOOST_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 * boost::asio::ip::tcp::socket socket(my_context); * ... * boost::asio::socket_base::linger option(true, 30); * socket.set_option(option); * @endcode * * @par * Getting the current option value: * @code * boost::asio::ip::tcp::socket socket(my_context); * ... * boost::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 boost::asio::detail::socket_option::linger< BOOST_ASIO_OS_DEF(SOL_SOCKET), BOOST_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 * boost::asio::ip::tcp::socket socket(my_context); * ... * boost::asio::socket_base::out_of_band_inline option(true); * socket.set_option(option); * @endcode * * @par * Getting the current option value: * @code * boost::asio::ip::tcp::socket socket(my_context); * ... * boost::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 boost::asio::detail::socket_option::boolean< BOOST_ASIO_OS_DEF(SOL_SOCKET), BOOST_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 boost::asio::error::connection_aborted. * By default the option is false. * * @par Examples * Setting the option: * @code * boost::asio::ip::tcp::acceptor acceptor(my_context); * ... * boost::asio::socket_base::enable_connection_aborted option(true); * acceptor.set_option(option); * @endcode * * @par * Getting the current option value: * @code * boost::asio::ip::tcp::acceptor acceptor(my_context); * ... * boost::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 boost::asio::detail::socket_option::boolean< boost::asio::detail::custom_socket_option_level, boost::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 * boost::asio::ip::tcp::socket socket(my_context); * ... * boost::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 boost::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 BOOST_ASIO_STATIC_CONSTANT(int, max_listen_connections = BOOST_ASIO_OS_DEF(SOMAXCONN)); #endif #if !defined(BOOST_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 BOOST_ASIO_STATIC_CONSTANT(int, max_connections = BOOST_ASIO_OS_DEF(SOMAXCONN)); #endif #endif // !defined(BOOST_ASIO_NO_DEPRECATED) protected: /// Protected destructor to prevent deletion through this type. ~socket_base() { } }; } // namespace asio } // namespace boost #include <boost/asio/detail/pop_options.hpp> #endif // BOOST_ASIO_SOCKET_BASE_HPP
hpp
asio
data/projects/asio/include/boost/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 BOOST_ASIO_WRITE_HPP #define BOOST_ASIO_WRITE_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <boost/asio/detail/config.hpp> #include <cstddef> #include <boost/asio/async_result.hpp> #include <boost/asio/buffer.hpp> #include <boost/asio/completion_condition.hpp> #include <boost/asio/error.hpp> #if !defined(BOOST_ASIO_NO_EXTENSIONS) # include <boost/asio/basic_streambuf_fwd.hpp> #endif // !defined(BOOST_ASIO_NO_EXTENSIONS) #include <boost/asio/detail/push_options.hpp> namespace boost { namespace asio { namespace detail { template <typename> class initiate_async_write; #if !defined(BOOST_ASIO_NO_DYNAMIC_BUFFER_V1) template <typename> class initiate_async_write_dynbuf_v1; #endif // !defined(BOOST_ASIO_NO_DYNAMIC_BUFFER_V1) template <typename> class initiate_async_write_dynbuf_v2; } // namespace detail /** * @defgroup write boost::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 boost::system::system_error Thrown on failure. * * @par Example * To write a single data buffer use the @ref buffer function as follows: * @code boost::asio::write(s, boost::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 boost::asio::write( * s, buffers, * boost::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 boost::asio::write(s, boost::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 boost::asio::write( * s, buffers, * boost::asio::transfer_all(), ec); @endcode */ template <typename SyncWriteStream, typename ConstBufferSequence> std::size_t write(SyncWriteStream& s, const ConstBufferSequence& buffers, boost::system::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 boost::system::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 boost::system::system_error Thrown on failure. * * @par Example * To write a single data buffer use the @ref buffer function as follows: * @code boost::asio::write(s, boost::asio::buffer(data, size), * boost::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); /// 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 boost::system::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, boost::system::error_code& ec, constraint_t< is_const_buffer_sequence<ConstBufferSequence>::value > = 0); #if !defined(BOOST_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 boost::system::system_error Thrown on failure. * * @note This overload is equivalent to calling: * @code boost::asio::write( * s, buffers, * boost::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 boost::asio::write( * s, buffers, * boost::asio::transfer_all(), ec); @endcode */ template <typename SyncWriteStream, typename DynamicBuffer_v1> std::size_t write(SyncWriteStream& s, DynamicBuffer_v1&& buffers, boost::system::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 boost::system::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 boost::system::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); /// 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 boost::system::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, boost::system::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(BOOST_ASIO_NO_EXTENSIONS) #if !defined(BOOST_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 boost::system::system_error Thrown on failure. * * @note This overload is equivalent to calling: * @code boost::asio::write( * s, b, * boost::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 boost::asio::write( * s, b, * boost::asio::transfer_all(), ec); @endcode */ template <typename SyncWriteStream, typename Allocator> std::size_t write(SyncWriteStream& s, basic_streambuf<Allocator>& b, boost::system::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 boost::system::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 boost::system::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); /// 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 boost::system::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, boost::system::error_code& ec); #endif // !defined(BOOST_ASIO_NO_IOSTREAM) #endif // !defined(BOOST_ASIO_NO_EXTENSIONS) #endif // !defined(BOOST_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 boost::system::system_error Thrown on failure. * * @note This overload is equivalent to calling: * @code boost::asio::write( * s, buffers, * boost::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 boost::asio::write( * s, buffers, * boost::asio::transfer_all(), ec); @endcode */ template <typename SyncWriteStream, typename DynamicBuffer_v2> std::size_t write(SyncWriteStream& s, DynamicBuffer_v2 buffers, boost::system::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 boost::system::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 boost::system::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); /// 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 boost::system::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, boost::system::error_code& ec, constraint_t< is_dynamic_buffer_v2<DynamicBuffer_v2>::value > = 0); /*@}*/ /** * @defgroup async_write boost::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 boost::system::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 boost::asio::post(). * * @par Completion Signature * @code void(boost::system::error_code, std::size_t) @endcode * * @par Example * To write a single data buffer use the @ref buffer function as follows: * @code * boost::asio::async_write(s, boost::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 * boost::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, BOOST_ASIO_COMPLETION_TOKEN_FOR(void (boost::system::error_code, std::size_t)) WriteToken = default_completion_token_t<typename AsyncWriteStream::executor_type>> 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) -> decltype( async_initiate<WriteToken, void (boost::system::error_code, std::size_t)>( declval<detail::initiate_async_write<AsyncWriteStream>>(), 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 boost::system::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 boost::system::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 boost::asio::post(). * * @par Completion Signature * @code void(boost::system::error_code, std::size_t) @endcode * * @par Example * To write a single data buffer use the @ref buffer function as follows: * @code boost::asio::async_write(s, * boost::asio::buffer(data, size), * boost::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 * boost::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, BOOST_ASIO_COMPLETION_TOKEN_FOR(void (boost::system::error_code, std::size_t)) WriteToken> auto async_write(AsyncWriteStream& s, const ConstBufferSequence& buffers, CompletionCondition completion_condition, WriteToken&& token, constraint_t< is_const_buffer_sequence<ConstBufferSequence>::value > = 0) -> decltype( async_initiate<WriteToken, void (boost::system::error_code, std::size_t)>( declval<detail::initiate_async_write<AsyncWriteStream>>(), token, buffers, static_cast<CompletionCondition&&>(completion_condition))); #if !defined(BOOST_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 boost::system::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 boost::asio::post(). * * @par Completion Signature * @code void(boost::system::error_code, std::size_t) @endcode * * @par Per-Operation Cancellation * This asynchronous operation supports cancellation for the following * boost::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, BOOST_ASIO_COMPLETION_TOKEN_FOR(void (boost::system::error_code, std::size_t)) WriteToken = default_completion_token_t<typename AsyncWriteStream::executor_type>> 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) -> decltype( async_initiate<WriteToken, void (boost::system::error_code, std::size_t)>( declval<detail::initiate_async_write_dynbuf_v1<AsyncWriteStream>>(), 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 boost::system::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 boost::system::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 boost::asio::post(). * * @par Completion Signature * @code void(boost::system::error_code, std::size_t) @endcode * * @par Per-Operation Cancellation * This asynchronous operation supports cancellation for the following * boost::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, BOOST_ASIO_COMPLETION_TOKEN_FOR(void (boost::system::error_code, std::size_t)) WriteToken> auto async_write(AsyncWriteStream& s, DynamicBuffer_v1&& buffers, CompletionCondition completion_condition, WriteToken&& token, 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<WriteToken, void (boost::system::error_code, std::size_t)>( declval<detail::initiate_async_write_dynbuf_v1<AsyncWriteStream>>(), token, static_cast<DynamicBuffer_v1&&>(buffers), static_cast<CompletionCondition&&>(completion_condition))); #if !defined(BOOST_ASIO_NO_EXTENSIONS) #if !defined(BOOST_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 boost::system::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 boost::asio::post(). * * @par Completion Signature * @code void(boost::system::error_code, std::size_t) @endcode * * @par Per-Operation Cancellation * This asynchronous operation supports cancellation for the following * boost::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, BOOST_ASIO_COMPLETION_TOKEN_FOR(void (boost::system::error_code, std::size_t)) WriteToken = default_completion_token_t<typename AsyncWriteStream::executor_type>> auto async_write(AsyncWriteStream& s, basic_streambuf<Allocator>& b, WriteToken&& token = default_completion_token_t<typename AsyncWriteStream::executor_type>()) -> decltype( async_initiate<WriteToken, void (boost::system::error_code, std::size_t)>( declval<detail::initiate_async_write_dynbuf_v1<AsyncWriteStream>>(), 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 boost::system::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 boost::system::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 boost::asio::post(). * * @par Completion Signature * @code void(boost::system::error_code, std::size_t) @endcode * * @par Per-Operation Cancellation * This asynchronous operation supports cancellation for the following * boost::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, BOOST_ASIO_COMPLETION_TOKEN_FOR(void (boost::system::error_code, std::size_t)) WriteToken> auto async_write(AsyncWriteStream& s, basic_streambuf<Allocator>& b, CompletionCondition completion_condition, WriteToken&& token) -> decltype( async_initiate<WriteToken, void (boost::system::error_code, std::size_t)>( declval<detail::initiate_async_write_dynbuf_v1<AsyncWriteStream>>(), token, basic_streambuf_ref<Allocator>(b), static_cast<CompletionCondition&&>(completion_condition))); #endif // !defined(BOOST_ASIO_NO_IOSTREAM) #endif // !defined(BOOST_ASIO_NO_EXTENSIONS) #endif // !defined(BOOST_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 boost::system::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 boost::asio::post(). * * @par Completion Signature * @code void(boost::system::error_code, std::size_t) @endcode * * @par Per-Operation Cancellation * This asynchronous operation supports cancellation for the following * boost::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, BOOST_ASIO_COMPLETION_TOKEN_FOR(void (boost::system::error_code, std::size_t)) WriteToken = default_completion_token_t<typename AsyncWriteStream::executor_type>> 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) -> decltype( async_initiate<WriteToken, void (boost::system::error_code, std::size_t)>( declval<detail::initiate_async_write_dynbuf_v2<AsyncWriteStream>>(), 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 boost::system::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 boost::system::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 boost::asio::post(). * * @par Completion Signature * @code void(boost::system::error_code, std::size_t) @endcode * * @par Per-Operation Cancellation * This asynchronous operation supports cancellation for the following * boost::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, BOOST_ASIO_COMPLETION_TOKEN_FOR(void (boost::system::error_code, std::size_t)) WriteToken> auto async_write(AsyncWriteStream& s, DynamicBuffer_v2 buffers, CompletionCondition completion_condition, WriteToken&& token, constraint_t< is_dynamic_buffer_v2<DynamicBuffer_v2>::value > = 0) -> decltype( async_initiate<WriteToken, void (boost::system::error_code, std::size_t)>( declval<detail::initiate_async_write_dynbuf_v2<AsyncWriteStream>>(), token, static_cast<DynamicBuffer_v2&&>(buffers), static_cast<CompletionCondition&&>(completion_condition))); /*@}*/ } // namespace asio } // namespace boost #include <boost/asio/detail/pop_options.hpp> #include <boost/asio/impl/write.hpp> #endif // BOOST_ASIO_WRITE_HPP
hpp
asio
data/projects/asio/include/boost/asio/yield.hpp
// // yield.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) // #include "coroutine.hpp" #ifndef reenter # define reenter(c) BOOST_ASIO_CORO_REENTER(c) #endif #ifndef yield # define yield BOOST_ASIO_CORO_YIELD #endif #ifndef fork # define fork BOOST_ASIO_CORO_FORK #endif
hpp
asio
data/projects/asio/include/boost/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 BOOST_ASIO_BASIC_STREAMBUF_FWD_HPP #define BOOST_ASIO_BASIC_STREAMBUF_FWD_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <boost/asio/detail/config.hpp> #if !defined(BOOST_ASIO_NO_IOSTREAM) #include <memory> namespace boost { namespace asio { template <typename Allocator = std::allocator<char>> class basic_streambuf; template <typename Allocator = std::allocator<char>> class basic_streambuf_ref; } // namespace asio } // namespace boost #endif // !defined(BOOST_ASIO_NO_IOSTREAM) #endif // BOOST_ASIO_BASIC_STREAMBUF_FWD_HPP
hpp
asio
data/projects/asio/include/boost/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 BOOST_ASIO_BUFFERED_STREAM_FWD_HPP #define BOOST_ASIO_BUFFERED_STREAM_FWD_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) namespace boost { namespace asio { template <typename Stream> class buffered_stream; } // namespace asio } // namespace boost #endif // BOOST_ASIO_BUFFERED_STREAM_FWD_HPP
hpp
asio
data/projects/asio/include/boost/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 BOOST_ASIO_IS_CONTIGUOUS_ITERATOR_HPP #define BOOST_ASIO_IS_CONTIGUOUS_ITERATOR_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <boost/asio/detail/config.hpp> #include <iterator> #include <boost/asio/detail/type_traits.hpp> #include <boost/asio/detail/push_options.hpp> namespace boost { 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(BOOST_ASIO_HAS_STD_CONCEPTS) \ || defined(GENERATING_DOCUMENTATION) integral_constant<bool, std::contiguous_iterator<T>> #else // defined(BOOST_ASIO_HAS_STD_CONCEPTS) // || defined(GENERATING_DOCUMENTATION) is_pointer<T> #endif // defined(BOOST_ASIO_HAS_STD_CONCEPTS) // || defined(GENERATING_DOCUMENTATION) { }; } // namespace asio } // namespace boost #include <boost/asio/detail/pop_options.hpp> #endif // BOOST_ASIO_IS_CONTIGUOUS_ITERATOR_HPP
hpp
asio
data/projects/asio/include/boost/asio/basic_readable_pipe.hpp
// // basic_readable_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 BOOST_ASIO_BASIC_READABLE_PIPE_HPP #define BOOST_ASIO_BASIC_READABLE_PIPE_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <boost/asio/detail/config.hpp> #if defined(BOOST_ASIO_HAS_PIPE) \ || defined(GENERATING_DOCUMENTATION) #include <string> #include <utility> #include <boost/asio/any_io_executor.hpp> #include <boost/asio/async_result.hpp> #include <boost/asio/detail/handler_type_requirements.hpp> #include <boost/asio/detail/io_object_impl.hpp> #include <boost/asio/detail/non_const_lvalue.hpp> #include <boost/asio/detail/throw_error.hpp> #include <boost/asio/detail/type_traits.hpp> #include <boost/asio/error.hpp> #include <boost/asio/execution_context.hpp> #if defined(BOOST_ASIO_HAS_IOCP) # include <boost/asio/detail/win_iocp_handle_service.hpp> #elif defined(BOOST_ASIO_HAS_IO_URING_AS_DEFAULT) # include <boost/asio/detail/io_uring_descriptor_service.hpp> #else # include <boost/asio/detail/reactive_descriptor_service.hpp> #endif #include <boost/asio/detail/push_options.hpp> namespace boost { namespace asio { /// Provides pipe functionality. /** * The basic_readable_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_readable_pipe { private: class initiate_async_read_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_readable_pipe<Executor1> other; }; /// The native representation of a pipe. #if defined(GENERATING_DOCUMENTATION) typedef implementation_defined native_handle_type; #elif defined(BOOST_ASIO_HAS_IOCP) typedef detail::win_iocp_handle_service::native_handle_type native_handle_type; #elif defined(BOOST_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_readable_pipe is always the lowest layer. typedef basic_readable_pipe lowest_layer_type; /// Construct a basic_readable_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_readable_pipe(const executor_type& ex) : impl_(0, ex) { } /// Construct a basic_readable_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_readable_pipe(ExecutionContext& context, constraint_t< is_convertible<ExecutionContext&, execution_context&>::value, defaulted_constraint > = defaulted_constraint()) : impl_(0, 0, context) { } /// Construct a basic_readable_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 boost::system::system_error Thrown on failure. */ basic_readable_pipe(const executor_type& ex, const native_handle_type& native_pipe) : impl_(0, ex) { boost::system::error_code ec; impl_.get_service().assign(impl_.get_implementation(), native_pipe, ec); boost::asio::detail::throw_error(ec, "assign"); } /// Construct a basic_readable_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 boost::system::system_error Thrown on failure. */ template <typename ExecutionContext> basic_readable_pipe(ExecutionContext& context, const native_handle_type& native_pipe, constraint_t< is_convertible<ExecutionContext&, execution_context&>::value > = 0) : impl_(0, 0, context) { boost::system::error_code ec; impl_.get_service().assign(impl_.get_implementation(), native_pipe, ec); boost::asio::detail::throw_error(ec, "assign"); } /// Move-construct a basic_readable_pipe from another. /** * This constructor moves a pipe from one object to another. * * @param other The other basic_readable_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_readable_pipe(const executor_type&) * constructor. */ basic_readable_pipe(basic_readable_pipe&& other) : impl_(std::move(other.impl_)) { } /// Move-assign a basic_readable_pipe from another. /** * This assignment operator moves a pipe from one object to another. * * @param other The other basic_readable_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_readable_pipe(const executor_type&) * constructor. */ basic_readable_pipe& operator=(basic_readable_pipe&& other) { impl_ = std::move(other.impl_); return *this; } // All pipes have access to each other's implementations. template <typename Executor1> friend class basic_readable_pipe; /// Move-construct a basic_readable_pipe from a pipe of another executor type. /** * This constructor moves a pipe from one object to another. * * @param other The other basic_readable_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_readable_pipe(const executor_type&) * constructor. */ template <typename Executor1> basic_readable_pipe(basic_readable_pipe<Executor1>&& other, constraint_t< is_convertible<Executor1, Executor>::value, defaulted_constraint > = defaulted_constraint()) : impl_(std::move(other.impl_)) { } /// Move-assign a basic_readable_pipe from a pipe of another executor type. /** * This assignment operator moves a pipe from one object to another. * * @param other The other basic_readable_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_readable_pipe(const executor_type&) * constructor. */ template <typename Executor1> constraint_t< is_convertible<Executor1, Executor>::value, basic_readable_pipe& > operator=(basic_readable_pipe<Executor1>&& other) { basic_readable_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_readable_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_readable_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_readable_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 boost::system::system_error Thrown on failure. */ void assign(const native_handle_type& native_pipe) { boost::system::error_code ec; impl_.get_service().assign(impl_.get_implementation(), native_pipe, ec); boost::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. */ BOOST_ASIO_SYNC_OP_VOID assign(const native_handle_type& native_pipe, boost::system::error_code& ec) { impl_.get_service().assign(impl_.get_implementation(), native_pipe, ec); BOOST_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 read operations * will be cancelled immediately, and will complete with the * boost::asio::error::operation_aborted error. * * @throws boost::system::system_error Thrown on failure. */ void close() { boost::system::error_code ec; impl_.get_service().close(impl_.get_implementation(), ec); boost::asio::detail::throw_error(ec, "close"); } /// Close the pipe. /** * This function is used to close the pipe. Any asynchronous read operations * will be cancelled immediately, and will complete with the * boost::asio::error::operation_aborted error. * * @param ec Set to indicate what error occurred, if any. */ BOOST_ASIO_SYNC_OP_VOID close(boost::system::error_code& ec) { impl_.get_service().close(impl_.get_implementation(), ec); BOOST_ASIO_SYNC_OP_VOID_RETURN(ec); } /// Release ownership of the underlying native pipe. /** * This function causes all outstanding asynchronous read operations to * finish immediately, and the handlers for cancelled operations will be * passed the boost::asio::error::operation_aborted error. Ownership of the * native pipe is then transferred to the caller. * * @throws boost::system::system_error Thrown on failure. * * @note This function is unsupported on Windows versions prior to Windows * 8.1, and will fail with boost::asio::error::operation_not_supported on * these platforms. */ #if defined(BOOST_ASIO_MSVC) && (BOOST_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() { boost::system::error_code ec; native_handle_type s = impl_.get_service().release( impl_.get_implementation(), ec); boost::asio::detail::throw_error(ec, "release"); return s; } /// Release ownership of the underlying native pipe. /** * This function causes all outstanding asynchronous read operations to * finish immediately, and the handlers for cancelled operations will be * passed the boost::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 boost::asio::error::operation_not_supported on * these platforms. */ #if defined(BOOST_ASIO_MSVC) && (BOOST_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(boost::system::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 read operations to finish * immediately, and the handlers for cancelled operations will be passed the * boost::asio::error::operation_aborted error. * * @throws boost::system::system_error Thrown on failure. */ void cancel() { boost::system::error_code ec; impl_.get_service().cancel(impl_.get_implementation(), ec); boost::asio::detail::throw_error(ec, "cancel"); } /// Cancel all asynchronous operations associated with the pipe. /** * This function causes all outstanding asynchronous read operations to finish * immediately, and the handlers for cancelled operations will be passed the * boost::asio::error::operation_aborted error. * * @param ec Set to indicate what error occurred, if any. */ BOOST_ASIO_SYNC_OP_VOID cancel(boost::system::error_code& ec) { impl_.get_service().cancel(impl_.get_implementation(), ec); BOOST_ASIO_SYNC_OP_VOID_RETURN(ec); } /// Read some data from the pipe. /** * This function is used to read data from the pipe. 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 boost::system::system_error Thrown on failure. An error code of * boost::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_readable_pipe.read_some(boost::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) { boost::system::error_code ec; std::size_t s = impl_.get_service().read_some( impl_.get_implementation(), buffers, ec); boost::asio::detail::throw_error(ec, "read_some"); return s; } /// Read some data from the pipe. /** * This function is used to read data from the pipe. 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, boost::system::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 pipe. 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 boost::system::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 boost::asio::post(). * * @par Completion Signature * @code void(boost::system::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_readable_pipe.async_read_some( * boost::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. */ template <typename MutableBufferSequence, BOOST_ASIO_COMPLETION_TOKEN_FOR(void (boost::system::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 (boost::system::error_code, std::size_t)>( declval<initiate_async_read_some>(), token, buffers)) { return async_initiate<ReadToken, void (boost::system::error_code, std::size_t)>( initiate_async_read_some(this), token, buffers); } private: // Disallow copying and assignment. basic_readable_pipe(const basic_readable_pipe&) = delete; basic_readable_pipe& operator=(const basic_readable_pipe&) = delete; class initiate_async_read_some { public: typedef Executor executor_type; explicit initiate_async_read_some(basic_readable_pipe* 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. BOOST_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_readable_pipe* self_; }; #if defined(BOOST_ASIO_HAS_IOCP) detail::io_object_impl<detail::win_iocp_handle_service, Executor> impl_; #elif defined(BOOST_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 } // namespace boost #include <boost/asio/detail/pop_options.hpp> #endif // defined(BOOST_ASIO_HAS_PIPE) // || defined(GENERATING_DOCUMENTATION) #endif // BOOST_ASIO_BASIC_READABLE_PIPE_HPP
hpp
asio
data/projects/asio/include/boost/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 BOOST_ASIO_BASIC_STREAM_SOCKET_HPP #define BOOST_ASIO_BASIC_STREAM_SOCKET_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <boost/asio/detail/config.hpp> #include <cstddef> #include <boost/asio/async_result.hpp> #include <boost/asio/basic_socket.hpp> #include <boost/asio/detail/handler_type_requirements.hpp> #include <boost/asio/detail/non_const_lvalue.hpp> #include <boost/asio/detail/throw_error.hpp> #include <boost/asio/error.hpp> #include <boost/asio/detail/push_options.hpp> namespace boost { namespace asio { #if !defined(BOOST_ASIO_BASIC_STREAM_SOCKET_FWD_DECL) #define BOOST_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(BOOST_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 boost::system::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 boost::system::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 boost::system::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 boost::system::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 boost::system::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 boost::system::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 boost::system::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(boost::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) { boost::system::error_code ec; std::size_t s = this->impl_.get_service().send( this->impl_.get_implementation(), buffers, 0, ec); boost::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 boost::system::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(boost::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) { boost::system::error_code ec; std::size_t s = this->impl_.get_service().send( this->impl_.get_implementation(), buffers, flags, ec); boost::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, boost::system::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 boost::system::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 boost::asio::post(). * * @par Completion Signature * @code void(boost::system::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(boost::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 boost::asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * @li @c cancellation_type::total */ template <typename ConstBufferSequence, BOOST_ASIO_COMPLETION_TOKEN_FOR(void (boost::system::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 (boost::system::error_code, std::size_t)>( declval<initiate_async_send>(), token, buffers, socket_base::message_flags(0))) { return async_initiate<WriteToken, void (boost::system::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 boost::system::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 boost::asio::post(). * * @par Completion Signature * @code void(boost::system::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(boost::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 boost::asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * @li @c cancellation_type::total */ template <typename ConstBufferSequence, BOOST_ASIO_COMPLETION_TOKEN_FOR(void (boost::system::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 (boost::system::error_code, std::size_t)>( declval<initiate_async_send>(), token, buffers, flags)) { return async_initiate<WriteToken, void (boost::system::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 boost::system::system_error Thrown on failure. An error code of * boost::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(boost::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) { boost::system::error_code ec; std::size_t s = this->impl_.get_service().receive( this->impl_.get_implementation(), buffers, 0, ec); boost::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 boost::system::system_error Thrown on failure. An error code of * boost::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(boost::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) { boost::system::error_code ec; std::size_t s = this->impl_.get_service().receive( this->impl_.get_implementation(), buffers, flags, ec); boost::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, boost::system::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 boost::system::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 boost::asio::post(). * * @par Completion Signature * @code void(boost::system::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(boost::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 boost::asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * @li @c cancellation_type::total */ template <typename MutableBufferSequence, BOOST_ASIO_COMPLETION_TOKEN_FOR(void (boost::system::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 (boost::system::error_code, std::size_t)>( declval<initiate_async_receive>(), token, buffers, socket_base::message_flags(0))) { return async_initiate<ReadToken, void (boost::system::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 boost::system::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 boost::asio::post(). * * @par Completion Signature * @code void(boost::system::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(boost::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 boost::asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * @li @c cancellation_type::total */ template <typename MutableBufferSequence, BOOST_ASIO_COMPLETION_TOKEN_FOR(void (boost::system::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 (boost::system::error_code, std::size_t)>( declval<initiate_async_receive>(), token, buffers, flags)) { return async_initiate<ReadToken, void (boost::system::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 boost::system::system_error Thrown on failure. An error code of * boost::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(boost::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) { boost::system::error_code ec; std::size_t s = this->impl_.get_service().send( this->impl_.get_implementation(), buffers, 0, ec); boost::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, boost::system::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 boost::system::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 boost::asio::post(). * * @par Completion Signature * @code void(boost::system::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(boost::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 boost::asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * @li @c cancellation_type::total */ template <typename ConstBufferSequence, BOOST_ASIO_COMPLETION_TOKEN_FOR(void (boost::system::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 (boost::system::error_code, std::size_t)>( declval<initiate_async_send>(), token, buffers, socket_base::message_flags(0))) { return async_initiate<WriteToken, void (boost::system::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 boost::system::system_error Thrown on failure. An error code of * boost::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(boost::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) { boost::system::error_code ec; std::size_t s = this->impl_.get_service().receive( this->impl_.get_implementation(), buffers, 0, ec); boost::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, boost::system::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 boost::system::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 boost::asio::post(). * * @par Completion Signature * @code void(boost::system::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(boost::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 boost::asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * @li @c cancellation_type::total */ template <typename MutableBufferSequence, BOOST_ASIO_COMPLETION_TOKEN_FOR(void (boost::system::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 (boost::system::error_code, std::size_t)>( declval<initiate_async_receive>(), token, buffers, socket_base::message_flags(0))) { return async_initiate<ReadToken, void (boost::system::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. BOOST_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. BOOST_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 } // namespace boost #include <boost/asio/detail/pop_options.hpp> #endif // BOOST_ASIO_BASIC_STREAM_SOCKET_HPP
hpp
asio
data/projects/asio/include/boost/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 BOOST_ASIO_BASIC_SIGNAL_SET_HPP #define BOOST_ASIO_BASIC_SIGNAL_SET_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <boost/asio/detail/config.hpp> #include <boost/asio/any_io_executor.hpp> #include <boost/asio/async_result.hpp> #include <boost/asio/detail/handler_type_requirements.hpp> #include <boost/asio/detail/io_object_impl.hpp> #include <boost/asio/detail/non_const_lvalue.hpp> #include <boost/asio/detail/signal_set_service.hpp> #include <boost/asio/detail/throw_error.hpp> #include <boost/asio/detail/type_traits.hpp> #include <boost/asio/error.hpp> #include <boost/asio/execution_context.hpp> #include <boost/asio/signal_set_base.hpp> #include <boost/asio/detail/push_options.hpp> namespace boost { 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 boost::system::error_code& error, * int signal_number) * { * if (!error) * { * // A signal occurred. * } * } * * ... * * // Construct a signal set registered for process termination. * boost::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 boost::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) { boost::system::error_code ec; impl_.get_service().add(impl_.get_implementation(), signal_number_1, ec); boost::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 boost::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) { boost::system::error_code ec; impl_.get_service().add(impl_.get_implementation(), signal_number_1, ec); boost::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 boost::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) { boost::system::error_code ec; impl_.get_service().add(impl_.get_implementation(), signal_number_1, ec); boost::asio::detail::throw_error(ec, "add"); impl_.get_service().add(impl_.get_implementation(), signal_number_2, ec); boost::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 boost::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) { boost::system::error_code ec; impl_.get_service().add(impl_.get_implementation(), signal_number_1, ec); boost::asio::detail::throw_error(ec, "add"); impl_.get_service().add(impl_.get_implementation(), signal_number_2, ec); boost::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 boost::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) { boost::system::error_code ec; impl_.get_service().add(impl_.get_implementation(), signal_number_1, ec); boost::asio::detail::throw_error(ec, "add"); impl_.get_service().add(impl_.get_implementation(), signal_number_2, ec); boost::asio::detail::throw_error(ec, "add"); impl_.get_service().add(impl_.get_implementation(), signal_number_3, ec); boost::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 boost::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) { boost::system::error_code ec; impl_.get_service().add(impl_.get_implementation(), signal_number_1, ec); boost::asio::detail::throw_error(ec, "add"); impl_.get_service().add(impl_.get_implementation(), signal_number_2, ec); boost::asio::detail::throw_error(ec, "add"); impl_.get_service().add(impl_.get_implementation(), signal_number_3, ec); boost::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 boost::system::system_error Thrown on failure. */ void add(int signal_number) { boost::system::error_code ec; impl_.get_service().add(impl_.get_implementation(), signal_number, ec); boost::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. */ BOOST_ASIO_SYNC_OP_VOID add(int signal_number, boost::system::error_code& ec) { impl_.get_service().add(impl_.get_implementation(), signal_number, ec); BOOST_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 boost::system::system_error Thrown on failure. */ void add(int signal_number, flags_t f) { boost::system::error_code ec; impl_.get_service().add(impl_.get_implementation(), signal_number, f, ec); boost::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. */ BOOST_ASIO_SYNC_OP_VOID add(int signal_number, flags_t f, boost::system::error_code& ec) { impl_.get_service().add(impl_.get_implementation(), signal_number, f, ec); BOOST_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 boost::system::system_error Thrown on failure. * * @note Removes any notifications that have been queued for the specified * signal number. */ void remove(int signal_number) { boost::system::error_code ec; impl_.get_service().remove(impl_.get_implementation(), signal_number, ec); boost::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. */ BOOST_ASIO_SYNC_OP_VOID remove(int signal_number, boost::system::error_code& ec) { impl_.get_service().remove(impl_.get_implementation(), signal_number, ec); BOOST_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 boost::system::system_error Thrown on failure. * * @note Removes all queued notifications. */ void clear() { boost::system::error_code ec; impl_.get_service().clear(impl_.get_implementation(), ec); boost::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. */ BOOST_ASIO_SYNC_OP_VOID clear(boost::system::error_code& ec) { impl_.get_service().clear(impl_.get_implementation(), ec); BOOST_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 boost::asio::error::operation_aborted * error code. * * Cancellation does not alter the set of registered signals. * * @throws boost::system::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() { boost::system::error_code ec; impl_.get_service().cancel(impl_.get_implementation(), ec); boost::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 boost::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. */ BOOST_ASIO_SYNC_OP_VOID cancel(boost::system::error_code& ec) { impl_.get_service().cancel(impl_.get_implementation(), ec); BOOST_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 boost::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 boost::system::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 boost::asio::post(). * * @par Completion Signature * @code void(boost::system::error_code, int) @endcode * * @par Per-Operation Cancellation * This asynchronous operation supports cancellation for the following * boost::asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * @li @c cancellation_type::total */ template < BOOST_ASIO_COMPLETION_TOKEN_FOR(void (boost::system::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 (boost::system::error_code, int)>( declval<initiate_async_wait>(), token)) { return async_initiate<SignalToken, void (boost::system::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. BOOST_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 } // namespace boost #include <boost/asio/detail/pop_options.hpp> #endif // BOOST_ASIO_BASIC_SIGNAL_SET_HPP
hpp
asio
data/projects/asio/include/boost/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 BOOST_ASIO_DEFER_HPP #define BOOST_ASIO_DEFER_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <boost/asio/detail/config.hpp> #include <boost/asio/async_result.hpp> #include <boost/asio/detail/initiate_defer.hpp> #include <boost/asio/detail/type_traits.hpp> #include <boost/asio/execution_context.hpp> #include <boost/asio/execution/blocking.hpp> #include <boost/asio/execution/executor.hpp> #include <boost/asio/is_executor.hpp> #include <boost/asio/require.hpp> #include <boost/asio/detail/push_options.hpp> namespace boost { 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 <BOOST_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, BOOST_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, BOOST_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 } // namespace boost #include <boost/asio/detail/pop_options.hpp> #endif // BOOST_ASIO_DEFER_HPP
hpp
asio
data/projects/asio/include/boost/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 BOOST_ASIO_IO_SERVICE_STRAND_HPP #define BOOST_ASIO_IO_SERVICE_STRAND_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <boost/asio/io_context_strand.hpp> #endif // BOOST_ASIO_IO_SERVICE_STRAND_HPP
hpp
asio
data/projects/asio/include/boost/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 BOOST_ASIO_ANY_COMPLETION_HANDLER_HPP #define BOOST_ASIO_ANY_COMPLETION_HANDLER_HPP #include <boost/asio/detail/config.hpp> #include <cstring> #include <functional> #include <memory> #include <utility> #include <boost/asio/any_completion_executor.hpp> #include <boost/asio/any_io_executor.hpp> #include <boost/asio/associated_allocator.hpp> #include <boost/asio/associated_cancellation_slot.hpp> #include <boost/asio/associated_executor.hpp> #include <boost/asio/associated_immediate_executor.hpp> #include <boost/asio/cancellation_state.hpp> #include <boost/asio/recycling_allocator.hpp> #include <boost/asio/detail/push_options.hpp> namespace boost { 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, boost::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, boost::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, boost::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_, boost::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, boost::asio::recycling_allocator<void>>>::template rebind_alloc<unsigned char> alloc( (get_associated_allocator)(handler_, boost::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; boost::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, boost::asio::recycling_allocator<void>>>::template rebind_alloc<unsigned char> alloc( (get_associated_allocator)(handler_, boost::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_, boost::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; boost::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; boost::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 } // namespace boost #include <boost/asio/detail/pop_options.hpp> #endif // BOOST_ASIO_ANY_COMPLETION_HANDLER_HPP
hpp
asio
data/projects/asio/include/boost/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 BOOST_ASIO_WRITABLE_PIPE_HPP #define BOOST_ASIO_WRITABLE_PIPE_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <boost/asio/detail/config.hpp> #if defined(BOOST_ASIO_HAS_PIPE) \ || defined(GENERATING_DOCUMENTATION) #include <boost/asio/basic_writable_pipe.hpp> namespace boost { namespace asio { /// Typedef for the typical usage of a writable pipe. typedef basic_writable_pipe<> writable_pipe; } // namespace asio } // namespace boost #endif // defined(BOOST_ASIO_HAS_PIPE) // || defined(GENERATING_DOCUMENTATION) #endif // BOOST_ASIO_WRITABLE_PIPE_HPP
hpp
asio
data/projects/asio/include/boost/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 BOOST_ASIO_USE_FUTURE_HPP #define BOOST_ASIO_USE_FUTURE_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <boost/asio/detail/config.hpp> #include <boost/asio/detail/future.hpp> #if defined(BOOST_ASIO_HAS_STD_FUTURE_CLASS) \ || defined(GENERATING_DOCUMENTATION) #include <memory> #include <boost/asio/detail/type_traits.hpp> #include <boost/asio/detail/push_options.hpp> namespace boost { 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 boost::asio::use_future. For * example: * * @code std::future<std::size_t> my_future * = my_socket.async_read_some(my_buffer, boost::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(BOOST_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(BOOST_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([](boost::system::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 boost::asio::use_future_t for a usage example. */ constexpr use_future_t<> use_future; } // namespace asio } // namespace boost #include <boost/asio/detail/pop_options.hpp> #include <boost/asio/impl/use_future.hpp> #endif // defined(BOOST_ASIO_HAS_STD_FUTURE_CLASS) // || defined(GENERATING_DOCUMENTATION) #endif // BOOST_ASIO_USE_FUTURE_HPP
hpp
asio
data/projects/asio/include/boost/asio/async_result.hpp
// // async_result.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 BOOST_ASIO_ASYNC_RESULT_HPP #define BOOST_ASIO_ASYNC_RESULT_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <boost/asio/detail/config.hpp> #include <boost/asio/detail/type_traits.hpp> #include <boost/asio/detail/push_options.hpp> namespace boost { namespace asio { #if defined(BOOST_ASIO_HAS_CONCEPTS) namespace detail { template <typename T> struct is_completion_signature : false_type { }; template <typename R, typename... Args> struct is_completion_signature<R(Args...)> : true_type { }; template <typename R, typename... Args> struct is_completion_signature<R(Args...) &> : true_type { }; template <typename R, typename... Args> struct is_completion_signature<R(Args...) &&> : true_type { }; # if defined(BOOST_ASIO_HAS_NOEXCEPT_FUNCTION_TYPE) template <typename R, typename... Args> struct is_completion_signature<R(Args...) noexcept> : true_type { }; template <typename R, typename... Args> struct is_completion_signature<R(Args...) & noexcept> : true_type { }; template <typename R, typename... Args> struct is_completion_signature<R(Args...) && noexcept> : true_type { }; # endif // defined(BOOST_ASIO_HAS_NOEXCEPT_FUNCTION_TYPE) template <typename... T> struct are_completion_signatures : false_type { }; template <typename T0> struct are_completion_signatures<T0> : is_completion_signature<T0> { }; template <typename T0, typename... TN> struct are_completion_signatures<T0, TN...> : integral_constant<bool, ( is_completion_signature<T0>::value && are_completion_signatures<TN...>::value)> { }; template <typename T, typename... Args> BOOST_ASIO_CONCEPT callable_with = requires(T&& t, Args&&... args) { static_cast<T&&>(t)(static_cast<Args&&>(args)...); }; template <typename T, typename... Signatures> struct is_completion_handler_for : false_type { }; template <typename T, typename R, typename... Args> struct is_completion_handler_for<T, R(Args...)> : integral_constant<bool, (callable_with<decay_t<T>, Args...>)> { }; template <typename T, typename R, typename... Args> struct is_completion_handler_for<T, R(Args...) &> : integral_constant<bool, (callable_with<decay_t<T>&, Args...>)> { }; template <typename T, typename R, typename... Args> struct is_completion_handler_for<T, R(Args...) &&> : integral_constant<bool, (callable_with<decay_t<T>&&, Args...>)> { }; # if defined(BOOST_ASIO_HAS_NOEXCEPT_FUNCTION_TYPE) template <typename T, typename R, typename... Args> struct is_completion_handler_for<T, R(Args...) noexcept> : integral_constant<bool, (callable_with<decay_t<T>, Args...>)> { }; template <typename T, typename R, typename... Args> struct is_completion_handler_for<T, R(Args...) & noexcept> : integral_constant<bool, (callable_with<decay_t<T>&, Args...>)> { }; template <typename T, typename R, typename... Args> struct is_completion_handler_for<T, R(Args...) && noexcept> : integral_constant<bool, (callable_with<decay_t<T>&&, Args...>)> { }; # endif // defined(BOOST_ASIO_HAS_NOEXCEPT_FUNCTION_TYPE) template <typename T, typename Signature0, typename... SignatureN> struct is_completion_handler_for<T, Signature0, SignatureN...> : integral_constant<bool, ( is_completion_handler_for<T, Signature0>::value && is_completion_handler_for<T, SignatureN...>::value)> { }; } // namespace detail template <typename T> BOOST_ASIO_CONCEPT completion_signature = detail::is_completion_signature<T>::value; #define BOOST_ASIO_COMPLETION_SIGNATURE \ ::boost::asio::completion_signature template <typename T, typename... Signatures> BOOST_ASIO_CONCEPT completion_handler_for = detail::are_completion_signatures<Signatures...>::value && detail::is_completion_handler_for<T, Signatures...>::value; #define BOOST_ASIO_COMPLETION_HANDLER_FOR(sig) \ ::boost::asio::completion_handler_for<sig> #define BOOST_ASIO_COMPLETION_HANDLER_FOR2(sig0, sig1) \ ::boost::asio::completion_handler_for<sig0, sig1> #define BOOST_ASIO_COMPLETION_HANDLER_FOR3(sig0, sig1, sig2) \ ::boost::asio::completion_handler_for<sig0, sig1, sig2> #else // defined(BOOST_ASIO_HAS_CONCEPTS) #define BOOST_ASIO_COMPLETION_SIGNATURE typename #define BOOST_ASIO_COMPLETION_HANDLER_FOR(sig) typename #define BOOST_ASIO_COMPLETION_HANDLER_FOR2(sig0, sig1) typename #define BOOST_ASIO_COMPLETION_HANDLER_FOR3(sig0, sig1, sig2) typename #endif // defined(BOOST_ASIO_HAS_CONCEPTS) namespace detail { template <typename T> struct is_lvalue_completion_signature : false_type { }; template <typename R, typename... Args> struct is_lvalue_completion_signature<R(Args...) &> : true_type { }; # if defined(BOOST_ASIO_HAS_NOEXCEPT_FUNCTION_TYPE) template <typename R, typename... Args> struct is_lvalue_completion_signature<R(Args...) & noexcept> : true_type { }; # endif // defined(BOOST_ASIO_HAS_NOEXCEPT_FUNCTION_TYPE) template <typename... Signatures> struct are_any_lvalue_completion_signatures : false_type { }; template <typename Sig0> struct are_any_lvalue_completion_signatures<Sig0> : is_lvalue_completion_signature<Sig0> { }; template <typename Sig0, typename... SigN> struct are_any_lvalue_completion_signatures<Sig0, SigN...> : integral_constant<bool, ( is_lvalue_completion_signature<Sig0>::value || are_any_lvalue_completion_signatures<SigN...>::value)> { }; template <typename T> struct is_rvalue_completion_signature : false_type { }; template <typename R, typename... Args> struct is_rvalue_completion_signature<R(Args...) &&> : true_type { }; # if defined(BOOST_ASIO_HAS_NOEXCEPT_FUNCTION_TYPE) template <typename R, typename... Args> struct is_rvalue_completion_signature<R(Args...) && noexcept> : true_type { }; # endif // defined(BOOST_ASIO_HAS_NOEXCEPT_FUNCTION_TYPE) template <typename... Signatures> struct are_any_rvalue_completion_signatures : false_type { }; template <typename Sig0> struct are_any_rvalue_completion_signatures<Sig0> : is_rvalue_completion_signature<Sig0> { }; template <typename Sig0, typename... SigN> struct are_any_rvalue_completion_signatures<Sig0, SigN...> : integral_constant<bool, ( is_rvalue_completion_signature<Sig0>::value || are_any_rvalue_completion_signatures<SigN...>::value)> { }; template <typename T> struct simple_completion_signature; template <typename R, typename... Args> struct simple_completion_signature<R(Args...)> { typedef R type(Args...); }; template <typename R, typename... Args> struct simple_completion_signature<R(Args...) &> { typedef R type(Args...); }; template <typename R, typename... Args> struct simple_completion_signature<R(Args...) &&> { typedef R type(Args...); }; # if defined(BOOST_ASIO_HAS_NOEXCEPT_FUNCTION_TYPE) template <typename R, typename... Args> struct simple_completion_signature<R(Args...) noexcept> { typedef R type(Args...); }; template <typename R, typename... Args> struct simple_completion_signature<R(Args...) & noexcept> { typedef R type(Args...); }; template <typename R, typename... Args> struct simple_completion_signature<R(Args...) && noexcept> { typedef R type(Args...); }; # endif // defined(BOOST_ASIO_HAS_NOEXCEPT_FUNCTION_TYPE) template <typename CompletionToken, BOOST_ASIO_COMPLETION_SIGNATURE... Signatures> class completion_handler_async_result { public: typedef CompletionToken completion_handler_type; typedef void return_type; explicit completion_handler_async_result(completion_handler_type&) { } return_type get() { } template <typename Initiation, BOOST_ASIO_COMPLETION_HANDLER_FOR(Signatures...) RawCompletionToken, typename... Args> static return_type initiate(Initiation&& initiation, RawCompletionToken&& token, Args&&... args) { static_cast<Initiation&&>(initiation)( static_cast<RawCompletionToken&&>(token), static_cast<Args&&>(args)...); } private: completion_handler_async_result( const completion_handler_async_result&) = delete; completion_handler_async_result& operator=( const completion_handler_async_result&) = delete; }; } // namespace detail #if defined(GENERATING_DOCUMENTATION) /// An interface for customising the behaviour of an initiating function. /** * The async_result traits class is used for determining: * * @li the concrete completion handler type to be called at the end of the * asynchronous operation; * * @li the initiating function return type; and * * @li how the return value of the initiating function is obtained. * * The trait allows the handler and return types to be determined at the point * where the specific completion handler signature is known. * * This template may be specialised for user-defined completion token types. * The primary template assumes that the CompletionToken is the completion * handler. */ template <typename CompletionToken, BOOST_ASIO_COMPLETION_SIGNATURE... Signatures> class async_result { public: /// The concrete completion handler type for the specific signature. typedef CompletionToken completion_handler_type; /// The return type of the initiating function. typedef void return_type; /// Construct an async result from a given handler. /** * When using a specalised async_result, the constructor has an opportunity * to initialise some state associated with the completion handler, which is * then returned from the initiating function. */ explicit async_result(completion_handler_type& h); /// Obtain the value to be returned from the initiating function. return_type get(); /// Initiate the asynchronous operation that will produce the result, and /// obtain the value to be returned from the initiating function. template <typename Initiation, typename RawCompletionToken, typename... Args> static return_type initiate( Initiation&& initiation, RawCompletionToken&& token, Args&&... args); private: async_result(const async_result&) = delete; async_result& operator=(const async_result&) = delete; }; #else // defined(GENERATING_DOCUMENTATION) template <typename CompletionToken, BOOST_ASIO_COMPLETION_SIGNATURE... Signatures> class async_result : public conditional_t< detail::are_any_lvalue_completion_signatures<Signatures...>::value || !detail::are_any_rvalue_completion_signatures<Signatures...>::value, detail::completion_handler_async_result<CompletionToken, Signatures...>, async_result<CompletionToken, typename detail::simple_completion_signature<Signatures>::type...> > { public: typedef conditional_t< detail::are_any_lvalue_completion_signatures<Signatures...>::value || !detail::are_any_rvalue_completion_signatures<Signatures...>::value, detail::completion_handler_async_result<CompletionToken, Signatures...>, async_result<CompletionToken, typename detail::simple_completion_signature<Signatures>::type...> > base_type; using base_type::base_type; private: async_result(const async_result&) = delete; async_result& operator=(const async_result&) = delete; }; template <BOOST_ASIO_COMPLETION_SIGNATURE... Signatures> class async_result<void, Signatures...> { // Empty. }; #endif // defined(GENERATING_DOCUMENTATION) /// Helper template to deduce the handler type from a CompletionToken, capture /// a local copy of the handler, and then create an async_result for the /// handler. template <typename CompletionToken, BOOST_ASIO_COMPLETION_SIGNATURE... Signatures> struct async_completion { /// The real handler type to be used for the asynchronous operation. typedef typename boost::asio::async_result< decay_t<CompletionToken>, Signatures...>::completion_handler_type completion_handler_type; /// Constructor. /** * The constructor creates the concrete completion handler and makes the link * between the handler and the asynchronous result. */ explicit async_completion(CompletionToken& token) : completion_handler(static_cast<conditional_t< is_same<CompletionToken, completion_handler_type>::value, completion_handler_type&, CompletionToken&&>>(token)), result(completion_handler) { } /// A copy of, or reference to, a real handler object. conditional_t< is_same<CompletionToken, completion_handler_type>::value, completion_handler_type&, completion_handler_type> completion_handler; /// The result of the asynchronous operation's initiating function. async_result<decay_t<CompletionToken>, Signatures...> result; }; namespace detail { struct async_result_memfns_base { void initiate(); }; template <typename T> struct async_result_memfns_derived : T, async_result_memfns_base { }; template <typename T, T> struct async_result_memfns_check { }; template <typename> char (&async_result_initiate_memfn_helper(...))[2]; template <typename T> char async_result_initiate_memfn_helper( async_result_memfns_check< void (async_result_memfns_base::*)(), &async_result_memfns_derived<T>::initiate>*); template <typename CompletionToken, BOOST_ASIO_COMPLETION_SIGNATURE... Signatures> struct async_result_has_initiate_memfn : integral_constant<bool, sizeof(async_result_initiate_memfn_helper< async_result<decay_t<CompletionToken>, Signatures...> >(0)) != 1> { }; } // namespace detail #if defined(GENERATING_DOCUMENTATION) # define BOOST_ASIO_INITFN_RESULT_TYPE(ct, sig) \ void_or_deduced # define BOOST_ASIO_INITFN_RESULT_TYPE2(ct, sig0, sig1) \ void_or_deduced # define BOOST_ASIO_INITFN_RESULT_TYPE3(ct, sig0, sig1, sig2) \ void_or_deduced #else # define BOOST_ASIO_INITFN_RESULT_TYPE(ct, sig) \ typename ::boost::asio::async_result< \ typename ::boost::asio::decay<ct>::type, sig>::return_type # define BOOST_ASIO_INITFN_RESULT_TYPE2(ct, sig0, sig1) \ typename ::boost::asio::async_result< \ typename ::boost::asio::decay<ct>::type, sig0, sig1>::return_type # define BOOST_ASIO_INITFN_RESULT_TYPE3(ct, sig0, sig1, sig2) \ typename ::boost::asio::async_result< \ typename ::boost::asio::decay<ct>::type, sig0, sig1, sig2>::return_type #define BOOST_ASIO_HANDLER_TYPE(ct, sig) \ typename ::boost::asio::async_result< \ typename ::boost::asio::decay<ct>::type, sig>::completion_handler_type #define BOOST_ASIO_HANDLER_TYPE2(ct, sig0, sig1) \ typename ::boost::asio::async_result< \ typename ::boost::asio::decay<ct>::type, \ sig0, sig1>::completion_handler_type #define BOOST_ASIO_HANDLER_TYPE3(ct, sig0, sig1, sig2) \ typename ::boost::asio::async_result< \ typename ::boost::asio::decay<ct>::type, \ sig0, sig1, sig2>::completion_handler_type #endif #if defined(GENERATING_DOCUMENTATION) # define BOOST_ASIO_INITFN_AUTO_RESULT_TYPE(ct, sig) \ auto # define BOOST_ASIO_INITFN_AUTO_RESULT_TYPE2(ct, sig0, sig1) \ auto # define BOOST_ASIO_INITFN_AUTO_RESULT_TYPE3(ct, sig0, sig1, sig2) \ auto #elif defined(BOOST_ASIO_HAS_RETURN_TYPE_DEDUCTION) # define BOOST_ASIO_INITFN_AUTO_RESULT_TYPE(ct, sig) \ auto # define BOOST_ASIO_INITFN_AUTO_RESULT_TYPE2(ct, sig0, sig1) \ auto # define BOOST_ASIO_INITFN_AUTO_RESULT_TYPE3(ct, sig0, sig1, sig2) \ auto #else # define BOOST_ASIO_INITFN_AUTO_RESULT_TYPE(ct, sig) \ BOOST_ASIO_INITFN_RESULT_TYPE(ct, sig) # define BOOST_ASIO_INITFN_AUTO_RESULT_TYPE2(ct, sig0, sig1) \ BOOST_ASIO_INITFN_RESULT_TYPE2(ct, sig0, sig1) # define BOOST_ASIO_INITFN_AUTO_RESULT_TYPE3(ct, sig0, sig1, sig2) \ BOOST_ASIO_INITFN_RESULT_TYPE3(ct, sig0, sig1, sig2) #endif #if defined(GENERATING_DOCUMENTATION) # define BOOST_ASIO_INITFN_AUTO_RESULT_TYPE_PREFIX(ct, sig) \ auto # define BOOST_ASIO_INITFN_AUTO_RESULT_TYPE_PREFIX2(ct, sig0, sig1) \ auto # define BOOST_ASIO_INITFN_AUTO_RESULT_TYPE_PREFIX3(ct, sig0, sig1, sig2) \ auto # define BOOST_ASIO_INITFN_AUTO_RESULT_TYPE_SUFFIX(expr) #elif defined(BOOST_ASIO_HAS_RETURN_TYPE_DEDUCTION) # define BOOST_ASIO_INITFN_AUTO_RESULT_TYPE_PREFIX(ct, sig) \ auto # define BOOST_ASIO_INITFN_AUTO_RESULT_TYPE_PREFIX2(ct, sig0, sig1) \ auto # define BOOST_ASIO_INITFN_AUTO_RESULT_TYPE_PREFIX3(ct, sig0, sig1, sig2) \ auto # define BOOST_ASIO_INITFN_AUTO_RESULT_TYPE_SUFFIX(expr) #else # define BOOST_ASIO_INITFN_AUTO_RESULT_TYPE_PREFIX(ct, sig) \ auto # define BOOST_ASIO_INITFN_AUTO_RESULT_TYPE_PREFIX2(ct, sig0, sig1) \ auto # define BOOST_ASIO_INITFN_AUTO_RESULT_TYPE_PREFIX3(ct, sig0, sig1, sig2) \ auto # define BOOST_ASIO_INITFN_AUTO_RESULT_TYPE_SUFFIX(expr) -> decltype expr #endif #if defined(GENERATING_DOCUMENTATION) # define BOOST_ASIO_INITFN_DEDUCED_RESULT_TYPE(ct, sig, expr) \ void_or_deduced # define BOOST_ASIO_INITFN_DEDUCED_RESULT_TYPE2(ct, sig0, sig1, expr) \ void_or_deduced # define BOOST_ASIO_INITFN_DEDUCED_RESULT_TYPE3(ct, sig0, sig1, sig2, expr) \ void_or_deduced #else # define BOOST_ASIO_INITFN_DEDUCED_RESULT_TYPE(ct, sig, expr) \ decltype expr # define BOOST_ASIO_INITFN_DEDUCED_RESULT_TYPE2(ct, sig0, sig1, expr) \ decltype expr # define BOOST_ASIO_INITFN_DEDUCED_RESULT_TYPE3(ct, sig0, sig1, sig2, expr) \ decltype expr #endif #if defined(GENERATING_DOCUMENTATION) template <typename CompletionToken, completion_signature... Signatures, typename Initiation, typename... Args> void_or_deduced async_initiate( Initiation&& initiation, type_identity_t<CompletionToken>& token, Args&&... args); #else // defined(GENERATING_DOCUMENTATION) template <typename CompletionToken, BOOST_ASIO_COMPLETION_SIGNATURE... Signatures, typename Initiation, typename... Args> inline auto async_initiate(Initiation&& initiation, type_identity_t<CompletionToken>& token, Args&&... args) -> constraint_t< detail::async_result_has_initiate_memfn< CompletionToken, Signatures...>::value, decltype( async_result<decay_t<CompletionToken>, Signatures...>::initiate( static_cast<Initiation&&>(initiation), static_cast<CompletionToken&&>(token), static_cast<Args&&>(args)...))> { return async_result<decay_t<CompletionToken>, Signatures...>::initiate( static_cast<Initiation&&>(initiation), static_cast<CompletionToken&&>(token), static_cast<Args&&>(args)...); } template <typename CompletionToken, BOOST_ASIO_COMPLETION_SIGNATURE... Signatures, typename Initiation, typename... Args> inline constraint_t< !detail::async_result_has_initiate_memfn< CompletionToken, Signatures...>::value, typename async_result<decay_t<CompletionToken>, Signatures...>::return_type> async_initiate(Initiation&& initiation, type_identity_t<CompletionToken>& token, Args&&... args) { async_completion<CompletionToken, Signatures...> completion(token); static_cast<Initiation&&>(initiation)( static_cast< typename async_result<decay_t<CompletionToken>, Signatures...>::completion_handler_type&&>( completion.completion_handler), static_cast<Args&&>(args)...); return completion.result.get(); } #endif // defined(GENERATING_DOCUMENTATION) #if defined(BOOST_ASIO_HAS_CONCEPTS) namespace detail { template <typename... Signatures> struct initiation_archetype { template <completion_handler_for<Signatures...> CompletionHandler> void operator()(CompletionHandler&&) const { } }; } // namespace detail template <typename T, typename... Signatures> BOOST_ASIO_CONCEPT completion_token_for = detail::are_completion_signatures<Signatures...>::value && requires(T&& t) { async_initiate<T, Signatures...>( detail::initiation_archetype<Signatures...>{}, t); }; #define BOOST_ASIO_COMPLETION_TOKEN_FOR(sig) \ ::boost::asio::completion_token_for<sig> #define BOOST_ASIO_COMPLETION_TOKEN_FOR2(sig0, sig1) \ ::boost::asio::completion_token_for<sig0, sig1> #define BOOST_ASIO_COMPLETION_TOKEN_FOR3(sig0, sig1, sig2) \ ::boost::asio::completion_token_for<sig0, sig1, sig2> #else // defined(BOOST_ASIO_HAS_CONCEPTS) #define BOOST_ASIO_COMPLETION_TOKEN_FOR(sig) typename #define BOOST_ASIO_COMPLETION_TOKEN_FOR2(sig0, sig1) typename #define BOOST_ASIO_COMPLETION_TOKEN_FOR3(sig0, sig1, sig2) typename #endif // defined(BOOST_ASIO_HAS_CONCEPTS) namespace detail { struct async_operation_probe {}; struct async_operation_probe_result {}; template <typename Call, typename = void> struct is_async_operation_call : false_type { }; template <typename Call> struct is_async_operation_call<Call, void_t< enable_if_t< is_same< result_of_t<Call>, async_operation_probe_result >::value > > > : true_type { }; } // namespace detail #if !defined(GENERATING_DOCUMENTATION) template <typename... Signatures> class async_result<detail::async_operation_probe, Signatures...> { public: typedef detail::async_operation_probe_result return_type; template <typename Initiation, typename... InitArgs> static return_type initiate(Initiation&&, detail::async_operation_probe, InitArgs&&...) { return return_type(); } }; #endif // !defined(GENERATING_DOCUMENTATION) #if defined(GENERATING_DOCUMENTATION) /// The is_async_operation trait detects whether a type @c T and arguments /// @c Args... may be used to initiate an asynchronous operation. /** * Class template @c is_async_operation is a trait is derived from @c true_type * if the expression <tt>T(Args..., token)</tt> initiates an asynchronous * operation, where @c token is an unspecified completion token type. Otherwise, * @c is_async_operation is derived from @c false_type. */ template <typename T, typename... Args> struct is_async_operation : integral_constant<bool, automatically_determined> { }; #else // defined(GENERATING_DOCUMENTATION) template <typename T, typename... Args> struct is_async_operation : detail::is_async_operation_call< T(Args..., detail::async_operation_probe)> { }; #endif // defined(GENERATING_DOCUMENTATION) #if defined(BOOST_ASIO_HAS_CONCEPTS) template <typename T, typename... Args> BOOST_ASIO_CONCEPT async_operation = is_async_operation<T, Args...>::value; #define BOOST_ASIO_ASYNC_OPERATION(t) \ ::boost::asio::async_operation<t> #define BOOST_ASIO_ASYNC_OPERATION1(t, a0) \ ::boost::asio::async_operation<t, a0> #define BOOST_ASIO_ASYNC_OPERATION2(t, a0, a1) \ ::boost::asio::async_operation<t, a0, a1> #define BOOST_ASIO_ASYNC_OPERATION3(t, a0, a1, a2) \ ::boost::asio::async_operation<t, a0, a1, a2> #else // defined(BOOST_ASIO_HAS_CONCEPTS) #define BOOST_ASIO_ASYNC_OPERATION(t) typename #define BOOST_ASIO_ASYNC_OPERATION1(t, a0) typename #define BOOST_ASIO_ASYNC_OPERATION2(t, a0, a1) typename #define BOOST_ASIO_ASYNC_OPERATION3(t, a0, a1, a2) typename #endif // defined(BOOST_ASIO_HAS_CONCEPTS) namespace detail { struct completion_signature_probe {}; template <typename... T> struct completion_signature_probe_result { template <template <typename...> class Op> struct apply { typedef Op<T...> type; }; }; template <typename T> struct completion_signature_probe_result<T> { typedef T type; template <template <typename...> class Op> struct apply { typedef Op<T> type; }; }; template <> struct completion_signature_probe_result<void> { template <template <typename...> class Op> struct apply { typedef Op<> type; }; }; } // namespace detail #if !defined(GENERATING_DOCUMENTATION) template <typename... Signatures> class async_result<detail::completion_signature_probe, Signatures...> { public: typedef detail::completion_signature_probe_result<Signatures...> return_type; template <typename Initiation, typename... InitArgs> static return_type initiate(Initiation&&, detail::completion_signature_probe, InitArgs&&...) { return return_type(); } }; template <typename Signature> class async_result<detail::completion_signature_probe, Signature> { public: typedef detail::completion_signature_probe_result<Signature> return_type; template <typename Initiation, typename... InitArgs> static return_type initiate(Initiation&&, detail::completion_signature_probe, InitArgs&&...) { return return_type(); } }; #endif // !defined(GENERATING_DOCUMENTATION) #if defined(GENERATING_DOCUMENTATION) /// The completion_signature_of trait determines the completion signature /// of an asynchronous operation. /** * Class template @c completion_signature_of is a trait with a member type * alias @c type that denotes the completion signature of the asynchronous * operation initiated by the expression <tt>T(Args..., token)</tt> operation, * where @c token is an unspecified completion token type. If the asynchronous * operation does not have exactly one completion signature, the instantion of * the trait is well-formed but the member type alias @c type is omitted. If * the expression <tt>T(Args..., token)</tt> is not an asynchronous operation * then use of the trait is ill-formed. */ template <typename T, typename... Args> struct completion_signature_of { typedef automatically_determined type; }; #else // defined(GENERATING_DOCUMENTATION) template <typename T, typename... Args> struct completion_signature_of : result_of_t<T(Args..., detail::completion_signature_probe)> { }; #endif // defined(GENERATING_DOCUMENTATION) template <typename T, typename... Args> using completion_signature_of_t = typename completion_signature_of<T, Args...>::type; namespace detail { template <typename T, typename = void> struct default_completion_token_impl { typedef void 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. */ 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 not defined. 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 BOOST_ASIO_DEFAULT_COMPLETION_TOKEN_TYPE(e) \ = typename ::boost::asio::default_completion_token<e>::type #define BOOST_ASIO_DEFAULT_COMPLETION_TOKEN(e) \ = typename ::boost::asio::default_completion_token<e>::type() } // namespace asio } // namespace boost #include <boost/asio/detail/pop_options.hpp> #endif // BOOST_ASIO_ASYNC_RESULT_HPP
hpp
asio
data/projects/asio/include/boost/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 BOOST_ASIO_BUFFERED_WRITE_STREAM_FWD_HPP #define BOOST_ASIO_BUFFERED_WRITE_STREAM_FWD_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) namespace boost { namespace asio { template <typename Stream> class buffered_write_stream; } // namespace asio } // namespace boost #endif // BOOST_ASIO_BUFFERED_WRITE_STREAM_FWD_HPP
hpp
asio
data/projects/asio/include/boost/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 BOOST_ASIO_BASIC_SEQ_PACKET_SOCKET_HPP #define BOOST_ASIO_BASIC_SEQ_PACKET_SOCKET_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <boost/asio/detail/config.hpp> #include <cstddef> #include <boost/asio/basic_socket.hpp> #include <boost/asio/detail/handler_type_requirements.hpp> #include <boost/asio/detail/throw_error.hpp> #include <boost/asio/error.hpp> #include <boost/asio/detail/push_options.hpp> namespace boost { namespace asio { #if !defined(BOOST_ASIO_BASIC_SEQ_PACKET_SOCKET_FWD_DECL) #define BOOST_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(BOOST_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 boost::system::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 boost::system::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 boost::system::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 boost::system::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 boost::system::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 boost::system::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 boost::system::system_error Thrown on failure. * * @par Example * To send a single data buffer use the @ref buffer function as follows: * @code * socket.send(boost::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) { boost::system::error_code ec; std::size_t s = this->impl_.get_service().send( this->impl_.get_implementation(), buffers, flags, ec); boost::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, boost::system::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 boost::system::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 boost::asio::post(). * * @par Completion Signature * @code void(boost::system::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(boost::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 boost::asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * @li @c cancellation_type::total */ template <typename ConstBufferSequence, BOOST_ASIO_COMPLETION_TOKEN_FOR(void (boost::system::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 (boost::system::error_code, std::size_t)>( declval<initiate_async_send>(), token, buffers, flags)) { return async_initiate<WriteToken, void (boost::system::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 boost::system::system_error Thrown on failure. An error code of * boost::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(boost::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) { boost::system::error_code ec; std::size_t s = this->impl_.get_service().receive_with_flags( this->impl_.get_implementation(), buffers, 0, out_flags, ec); boost::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 boost::system::system_error Thrown on failure. An error code of * boost::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(boost::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) { boost::system::error_code ec; std::size_t s = this->impl_.get_service().receive_with_flags( this->impl_.get_implementation(), buffers, in_flags, out_flags, ec); boost::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, boost::system::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 boost::system::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 boost::asio::post(). * * @par Completion Signature * @code void(boost::system::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(boost::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 boost::asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * @li @c cancellation_type::total */ template <typename MutableBufferSequence, BOOST_ASIO_COMPLETION_TOKEN_FOR(void (boost::system::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 (boost::system::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 (boost::system::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 boost::system::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 boost::asio::post(). * * @par Completion Signature * @code void(boost::system::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( * boost::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 boost::asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * @li @c cancellation_type::total */ template <typename MutableBufferSequence, BOOST_ASIO_COMPLETION_TOKEN_FOR(void (boost::system::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 (boost::system::error_code, std::size_t)>( declval<initiate_async_receive_with_flags>(), token, buffers, in_flags, &out_flags)) { return async_initiate<ReadToken, void (boost::system::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. BOOST_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. BOOST_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 } // namespace boost #include <boost/asio/detail/pop_options.hpp> #endif // BOOST_ASIO_BASIC_SEQ_PACKET_SOCKET_HPP
hpp
asio
data/projects/asio/include/boost/asio/readable_pipe.hpp
// // readable_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 BOOST_ASIO_READABLE_PIPE_HPP #define BOOST_ASIO_READABLE_PIPE_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <boost/asio/detail/config.hpp> #if defined(BOOST_ASIO_HAS_PIPE) \ || defined(GENERATING_DOCUMENTATION) #include <boost/asio/basic_readable_pipe.hpp> namespace boost { namespace asio { /// Typedef for the typical usage of a readable pipe. typedef basic_readable_pipe<> readable_pipe; } // namespace asio } // namespace boost #endif // defined(BOOST_ASIO_HAS_PIPE) // || defined(GENERATING_DOCUMENTATION) #endif // BOOST_ASIO_READABLE_PIPE_HPP
hpp
asio
data/projects/asio/include/boost/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 BOOST_ASIO_ANY_COMPLETION_EXECUTOR_HPP #define BOOST_ASIO_ANY_COMPLETION_EXECUTOR_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <boost/asio/detail/config.hpp> #if defined(BOOST_ASIO_USE_TS_EXECUTOR_AS_DEFAULT) # include <boost/asio/executor.hpp> #else // defined(BOOST_ASIO_USE_TS_EXECUTOR_AS_DEFAULT) # include <boost/asio/execution.hpp> #endif // defined(BOOST_ASIO_USE_TS_EXECUTOR_AS_DEFAULT) #include <boost/asio/detail/push_options.hpp> namespace boost { namespace asio { #if defined(BOOST_ASIO_USE_TS_EXECUTOR_AS_DEFAULT) typedef executor any_completion_executor; #else // defined(BOOST_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. BOOST_ASIO_DECL any_completion_executor() noexcept; /// Construct in an empty state. Equivalent effects to default constructor. BOOST_ASIO_DECL any_completion_executor(nullptr_t) noexcept; /// Copy constructor. BOOST_ASIO_DECL any_completion_executor( const any_completion_executor& e) noexcept; /// Move constructor. BOOST_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. BOOST_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. BOOST_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 <BOOST_ASIO_EXECUTION_EXECUTOR Executor> any_completion_executor(Executor e); #else // defined(GENERATING_DOCUMENTATION) template <BOOST_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 <BOOST_ASIO_EXECUTION_EXECUTOR Executor> any_completion_executor(std::nothrow_t, Executor e); #else // defined(GENERATING_DOCUMENTATION) template <BOOST_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. BOOST_ASIO_DECL any_completion_executor& operator=( const any_completion_executor& e) noexcept; /// Move assignment operator. BOOST_ASIO_DECL any_completion_executor& operator=( any_completion_executor&& e) noexcept; /// Assignment operator that sets the polymorphic wrapper to the empty state. BOOST_ASIO_DECL any_completion_executor& operator=(nullptr_t); /// Destructor. BOOST_ASIO_DECL ~any_completion_executor(); /// Swap targets with another polymorphic wrapper. BOOST_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 * boost::asio::require and boost::asio::prefer customisation points. * * For example: * @code any_completion_executor ex = ...; * auto ex2 = boost::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 * boost::asio::prefer customisation point. * * For example: * @code any_completion_executor ex = ...; * auto ex2 = boost::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 <> BOOST_ASIO_DECL any_completion_executor any_completion_executor::prefer( const execution::outstanding_work_t::tracked_t&, int) const; template <> BOOST_ASIO_DECL any_completion_executor any_completion_executor::prefer( const execution::outstanding_work_t::untracked_t&, int) const; template <> BOOST_ASIO_DECL any_completion_executor any_completion_executor::prefer( const execution::relationship_t::fork_t&, int) const; template <> BOOST_ASIO_DECL any_completion_executor any_completion_executor::prefer( const execution::relationship_t::continuation_t&, int) const; namespace traits { #if !defined(BOOST_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(BOOST_ASIO_HAS_DEDUCED_EQUALITY_COMPARABLE_TRAIT) #if !defined(BOOST_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(BOOST_ASIO_HAS_DEDUCED_EXECUTE_MEMBER_TRAIT) #if !defined(BOOST_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(BOOST_ASIO_HAS_DEDUCED_QUERY_MEMBER_TRAIT) #if !defined(BOOST_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(BOOST_ASIO_HAS_DEDUCED_REQUIRE_MEMBER_TRAIT) #if !defined(BOOST_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(BOOST_ASIO_HAS_DEDUCED_PREFER_MEMBER_TRAIT) } // namespace traits #endif // !defined(GENERATING_DOCUMENTATION) #endif // defined(BOOST_ASIO_USE_TS_EXECUTOR_AS_DEFAULT) } // namespace asio } // namespace boost #include <boost/asio/detail/pop_options.hpp> #if defined(BOOST_ASIO_HEADER_ONLY) \ && !defined(BOOST_ASIO_USE_TS_EXECUTOR_AS_DEFAULT) # include <boost/asio/impl/any_completion_executor.ipp> #endif // defined(BOOST_ASIO_HEADER_ONLY) // && !defined(BOOST_ASIO_USE_TS_EXECUTOR_AS_DEFAULT) #endif // BOOST_ASIO_ANY_COMPLETION_EXECUTOR_HPP
hpp
asio
data/projects/asio/include/boost/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 BOOST_ASIO_STEADY_TIMER_HPP #define BOOST_ASIO_STEADY_TIMER_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <boost/asio/detail/config.hpp> #include <boost/asio/basic_waitable_timer.hpp> #include <boost/asio/detail/chrono.hpp> namespace boost { 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 } // namespace boost #endif // BOOST_ASIO_STEADY_TIMER_HPP
hpp
asio
data/projects/asio/include/boost/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 BOOST_ASIO_CONNECT_HPP #define BOOST_ASIO_CONNECT_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <boost/asio/detail/config.hpp> #include <boost/asio/async_result.hpp> #include <boost/asio/basic_socket.hpp> #include <boost/asio/detail/type_traits.hpp> #include <boost/asio/error.hpp> #include <boost/asio/detail/push_options.hpp> namespace boost { namespace asio { namespace detail { struct default_connect_condition; template <typename, typename> class initiate_async_range_connect; template <typename, typename> class initiate_async_iterator_connect; char (&has_iterator_helper(...))[2]; template <typename T> char has_iterator_helper(T*, typename T::iterator* = 0); template <typename T> struct has_iterator_typedef { enum { value = (sizeof((has_iterator_helper)((T*)(0))) == 1) }; }; } // namespace detail /// 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 { #if defined(GENERATING_DOCUMENTATION) /// The value member is true if the type may be used as an endpoint sequence. static const bool value; #else enum { value = detail::has_iterator_typedef<T>::value }; #endif }; /** * @defgroup connect boost::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 boost::system::system_error Thrown on failure. If the sequence is * empty, the associated @c error_code is boost::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); * boost::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 boost::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); * boost::system::error_code ec; * boost::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, boost::system::error_code& ec, constraint_t<is_endpoint_sequence<EndpointSequence>::value> = 0); #if !defined(BOOST_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 boost::system::system_error Thrown on failure. If the sequence is * empty, the associated @c error_code is boost::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 boost::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 boost::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 boost::asio::ip::tcp::resolver::iterator. */ template <typename Protocol, typename Executor, typename Iterator> Iterator connect(basic_socket<Protocol, Executor>& s, Iterator begin, boost::system::error_code& ec, constraint_t<!is_endpoint_sequence<Iterator>::value> = 0); #endif // !defined(BOOST_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 boost::system::system_error Thrown on failure. If the sequence is * empty, the associated @c error_code is boost::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); * boost::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 boost::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); * boost::system::error_code ec; * boost::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, boost::system::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 boost::system::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 boost::system::system_error Thrown on failure. If the sequence is * empty, the associated @c error_code is boost::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 boost::system::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 boost::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 = boost::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); /// 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 boost::system::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 boost::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 boost::system::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 boost::asio::connect function as follows: * @code tcp::resolver r(my_context); * tcp::resolver::query q("host", "service"); * tcp::socket s(my_context); * boost::system::error_code ec; * tcp::endpoint e = boost::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, boost::system::error_code& ec, constraint_t<is_endpoint_sequence<EndpointSequence>::value> = 0); #if !defined(BOOST_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 boost::system::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 boost::system::system_error Thrown on failure. If the sequence is * empty, the associated @c error_code is boost::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 boost::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); /// (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 boost::system::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 boost::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 boost::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, boost::system::error_code& ec, constraint_t<!is_endpoint_sequence<Iterator>::value> = 0); #endif // !defined(BOOST_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 boost::system::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 boost::system::system_error Thrown on failure. If the sequence is * empty, the associated @c error_code is boost::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 boost::system::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 boost::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 = boost::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); /// 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 boost::system::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 boost::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 boost::system::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 boost::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); * boost::system::error_code ec; * tcp::resolver::results_type::iterator i = boost::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, boost::system::error_code& ec); /*@}*/ /** * @defgroup async_connect boost::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 * // boost::asio::error::not_found. Otherwise, contains the * // error from the last connection attempt. * const boost::system::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 boost::asio::post(). * * @par Completion Signature * @code void(boost::system::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 boost::system::error_code& ec, * tcp::resolver::results_type results) * { * if (!ec) * { * boost::asio::async_connect(s, results, connect_handler); * } * } * * // ... * * void connect_handler( * const boost::system::error_code& ec, * const tcp::endpoint& endpoint) * { * // ... * } @endcode * * @par Per-Operation Cancellation * This asynchronous operation supports cancellation for the following * boost::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, BOOST_ASIO_COMPLETION_TOKEN_FOR(void (boost::system::error_code, typename Protocol::endpoint)) RangeConnectToken = default_completion_token_t<Executor>> 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) -> decltype( async_initiate<RangeConnectToken, void (boost::system::error_code, typename Protocol::endpoint)>( declval<detail::initiate_async_range_connect<Protocol, Executor>>(), token, endpoints, declval<detail::default_connect_condition>())); #if !defined(BOOST_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 * // boost::asio::error::not_found. Otherwise, contains the * // error from the last connection attempt. * const boost::system::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 boost::asio::post(). * * @par Completion Signature * @code void(boost::system::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 boost::asio::ip::tcp::resolver::iterator. * * @par Per-Operation Cancellation * This asynchronous operation supports cancellation for the following * boost::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, BOOST_ASIO_COMPLETION_TOKEN_FOR(void (boost::system::error_code, Iterator)) IteratorConnectToken = default_completion_token_t<Executor>> 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) -> decltype( async_initiate<IteratorConnectToken, void (boost::system::error_code, Iterator)>( declval<detail::initiate_async_iterator_connect<Protocol, Executor>>(), token, begin, Iterator(), declval<detail::default_connect_condition>())); #endif // !defined(BOOST_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 * // boost::asio::error::not_found. Otherwise, contains the * // error from the last connection attempt. * const boost::system::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 boost::asio::post(). * * @par Completion Signature * @code void(boost::system::error_code, Iterator) @endcode * * @par Example * @code std::vector<tcp::endpoint> endpoints = ...; * tcp::socket s(my_context); * boost::asio::async_connect(s, * endpoints.begin(), endpoints.end(), * connect_handler); * * // ... * * void connect_handler( * const boost::system::error_code& ec, * std::vector<tcp::endpoint>::iterator i) * { * // ... * } @endcode * * @par Per-Operation Cancellation * This asynchronous operation supports cancellation for the following * boost::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, BOOST_ASIO_COMPLETION_TOKEN_FOR(void (boost::system::error_code, Iterator)) IteratorConnectToken = default_completion_token_t<Executor>> auto async_connect( basic_socket<Protocol, Executor>& s, Iterator begin, Iterator end, IteratorConnectToken&& token = default_completion_token_t<Executor>()) -> decltype( async_initiate<IteratorConnectToken, void (boost::system::error_code, Iterator)>( declval<detail::initiate_async_iterator_connect<Protocol, Executor>>(), token, begin, end, declval<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 boost::system::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 * // boost::asio::error::not_found. Otherwise, contains the * // error from the last connection attempt. * const boost::system::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 boost::asio::post(). * * @par Completion Signature * @code void(boost::system::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 boost::system::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 boost::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 boost::system::error_code& ec, * tcp::resolver::results_type results) * { * if (!ec) * { * boost::asio::async_connect(s, results, * my_connect_condition(), * connect_handler); * } * } * * // ... * * void connect_handler( * const boost::system::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 * boost::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, BOOST_ASIO_COMPLETION_TOKEN_FOR(void (boost::system::error_code, typename Protocol::endpoint)) RangeConnectToken = default_completion_token_t<Executor>> 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) -> decltype( async_initiate<RangeConnectToken, void (boost::system::error_code, typename Protocol::endpoint)>( declval<detail::initiate_async_range_connect<Protocol, Executor>>(), token, endpoints, connect_condition)); #if !defined(BOOST_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 boost::system::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 * // boost::asio::error::not_found. Otherwise, contains the * // error from the last connection attempt. * const boost::system::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 boost::asio::post(). * * @par Completion Signature * @code void(boost::system::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 boost::asio::ip::tcp::resolver::iterator. * * @par Per-Operation Cancellation * This asynchronous operation supports cancellation for the following * boost::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, BOOST_ASIO_COMPLETION_TOKEN_FOR(void (boost::system::error_code, Iterator)) IteratorConnectToken = default_completion_token_t<Executor>> 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) -> decltype( async_initiate<IteratorConnectToken, void (boost::system::error_code, Iterator)>( declval<detail::initiate_async_iterator_connect<Protocol, Executor>>(), token, begin, Iterator(), connect_condition)); #endif // !defined(BOOST_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 boost::system::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 * // boost::asio::error::not_found. Otherwise, contains the * // error from the last connection attempt. * const boost::system::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 boost::asio::post(). * * @par Completion Signature * @code void(boost::system::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 boost::system::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 boost::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 boost::system::error_code& ec, * tcp::resolver::iterator i) * { * if (!ec) * { * tcp::resolver::iterator end; * boost::asio::async_connect(s, i, end, * my_connect_condition(), * connect_handler); * } * } * * // ... * * void connect_handler( * const boost::system::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 * boost::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, BOOST_ASIO_COMPLETION_TOKEN_FOR(void (boost::system::error_code, Iterator)) IteratorConnectToken = default_completion_token_t<Executor>> auto async_connect(basic_socket<Protocol, Executor>& s, Iterator begin, Iterator end, ConnectCondition connect_condition, IteratorConnectToken&& token = default_completion_token_t<Executor>()) -> decltype( async_initiate<IteratorConnectToken, void (boost::system::error_code, Iterator)>( declval<detail::initiate_async_iterator_connect<Protocol, Executor>>(), token, begin, end, connect_condition)); /*@}*/ } // namespace asio } // namespace boost #include <boost/asio/detail/pop_options.hpp> #include <boost/asio/impl/connect.hpp> #endif
hpp
asio
data/projects/asio/include/boost/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 BOOST_ASIO_THIS_CORO_HPP #define BOOST_ASIO_THIS_CORO_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <boost/asio/detail/config.hpp> #include <boost/asio/detail/type_traits.hpp> #include <boost/asio/detail/push_options.hpp> namespace boost { 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. 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 boost::asio::awaitable<void> my_coroutine() * { * boost::asio::cancellation_state cs * = co_await boost::asio::this_coro::cancellation_state; * * // ... * * if (cs.cancelled() != boost::asio::cancellation_type::none) * // ... * } @endcode */ 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 * boost::asio::cancellation_state object <tt>S</tt>, constructed as * <tt>S(P)</tt>, into the current coroutine's cancellation state object. * * @par Example * @code boost::asio::awaitable<void> my_coroutine() * { * co_await boost::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 boost::asio::co_spawn. */ BOOST_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 * boost::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 boost::asio::awaitable<void> my_coroutine() * { * co_await boost::asio::this_coro::reset_cancellation_state( * boost::asio::enable_partial_cancellation()); * * // ... * } @endcode * * @note The cancellation state is shared by all coroutines in the same "thread * of execution" that was created using boost::asio::co_spawn. */ template <typename Filter> BOOST_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 * boost::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 boost::asio::awaitable<void> my_coroutine() * { * co_await boost::asio::this_coro::reset_cancellation_state( * boost::asio::enable_partial_cancellation(), * boost::asio::disable_cancellation()); * * // ... * } @endcode * * @note The cancellation state is shared by all coroutines in the same "thread * of execution" that was created using boost::asio::co_spawn. */ template <typename InFilter, typename OutFilter> BOOST_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 boost::asio::awaitable<void> my_coroutine() * { * if (co_await boost::asio::this_coro::throw_if_cancelled) * // ... * * // ... * } @endcode */ BOOST_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 boost::asio::awaitable<void> my_coroutine() * { * co_await boost::asio::this_coro::throw_if_cancelled(false); * * // ... * } @endcode */ BOOST_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() { } }; BOOST_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> BOOST_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> BOOST_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() { } }; BOOST_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; }; BOOST_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 } // namespace boost #include <boost/asio/detail/pop_options.hpp> #endif // BOOST_ASIO_THIS_CORO_HPP
hpp
asio
data/projects/asio/include/boost/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 BOOST_ASIO_DEADLINE_TIMER_HPP #define BOOST_ASIO_DEADLINE_TIMER_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <boost/asio/detail/config.hpp> #if defined(BOOST_ASIO_HAS_BOOST_DATE_TIME) \ || defined(GENERATING_DOCUMENTATION) #include <boost/asio/detail/socket_types.hpp> // Must come before posix_time. #include <boost/asio/basic_deadline_timer.hpp> #include <boost/date_time/posix_time/posix_time_types.hpp> namespace boost { 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 } // namespace boost #endif // defined(BOOST_ASIO_HAS_BOOST_DATE_TIME) // || defined(GENERATING_DOCUMENTATION) #endif // BOOST_ASIO_DEADLINE_TIMER_HPP
hpp
asio
data/projects/asio/include/boost/asio/basic_socket_streambuf.hpp
// // basic_socket_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 BOOST_ASIO_BASIC_SOCKET_STREAMBUF_HPP #define BOOST_ASIO_BASIC_SOCKET_STREAMBUF_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <boost/asio/detail/config.hpp> #if !defined(BOOST_ASIO_NO_IOSTREAM) #include <streambuf> #include <vector> #include <boost/asio/basic_socket.hpp> #include <boost/asio/basic_stream_socket.hpp> #include <boost/asio/detail/buffer_sequence_adapter.hpp> #include <boost/asio/detail/memory.hpp> #include <boost/asio/detail/throw_error.hpp> #include <boost/asio/io_context.hpp> #if defined(BOOST_ASIO_HAS_BOOST_DATE_TIME) \ && defined(BOOST_ASIO_USE_BOOST_DATE_TIME_FOR_SOCKET_IOSTREAM) # include <boost/asio/detail/deadline_timer_service.hpp> #else // defined(BOOST_ASIO_HAS_BOOST_DATE_TIME) // && defined(BOOST_ASIO_USE_BOOST_DATE_TIME_FOR_SOCKET_IOSTREAM) # include <boost/asio/steady_timer.hpp> #endif // defined(BOOST_ASIO_HAS_BOOST_DATE_TIME) // && defined(BOOST_ASIO_USE_BOOST_DATE_TIME_FOR_SOCKET_IOSTREAM) #include <boost/asio/detail/push_options.hpp> namespace boost { namespace asio { namespace detail { // A separate base class is used to ensure that the io_context member is // initialised prior to the basic_socket_streambuf's basic_socket base class. class socket_streambuf_io_context { protected: socket_streambuf_io_context(io_context* ctx) : default_io_context_(ctx) { } shared_ptr<io_context> default_io_context_; }; // A separate base class is used to ensure that the dynamically allocated // buffers are constructed prior to the basic_socket_streambuf's basic_socket // base class. This makes moving the socket is the last potentially throwing // step in the streambuf's move constructor, giving the constructor a strong // exception safety guarantee. class socket_streambuf_buffers { protected: socket_streambuf_buffers() : get_buffer_(buffer_size), put_buffer_(buffer_size) { } enum { buffer_size = 512 }; std::vector<char> get_buffer_; std::vector<char> put_buffer_; }; } // namespace detail #if !defined(BOOST_ASIO_BASIC_SOCKET_STREAMBUF_FWD_DECL) #define BOOST_ASIO_BASIC_SOCKET_STREAMBUF_FWD_DECL // Forward declaration with defaulted arguments. template <typename Protocol, #if defined(BOOST_ASIO_HAS_BOOST_DATE_TIME) \ && defined(BOOST_ASIO_USE_BOOST_DATE_TIME_FOR_SOCKET_IOSTREAM) typename Clock = boost::posix_time::ptime, typename WaitTraits = time_traits<Clock>> #else // defined(BOOST_ASIO_HAS_BOOST_DATE_TIME) // && defined(BOOST_ASIO_USE_BOOST_DATE_TIME_FOR_SOCKET_IOSTREAM) typename Clock = chrono::steady_clock, typename WaitTraits = wait_traits<Clock>> #endif // defined(BOOST_ASIO_HAS_BOOST_DATE_TIME) // && defined(BOOST_ASIO_USE_BOOST_DATE_TIME_FOR_SOCKET_IOSTREAM) class basic_socket_streambuf; #endif // !defined(BOOST_ASIO_BASIC_SOCKET_STREAMBUF_FWD_DECL) /// Iostream streambuf for a socket. #if defined(GENERATING_DOCUMENTATION) template <typename Protocol, typename Clock = chrono::steady_clock, typename WaitTraits = wait_traits<Clock>> #else // defined(GENERATING_DOCUMENTATION) template <typename Protocol, typename Clock, typename WaitTraits> #endif // defined(GENERATING_DOCUMENTATION) class basic_socket_streambuf : public std::streambuf, private detail::socket_streambuf_io_context, private detail::socket_streambuf_buffers, #if defined(BOOST_ASIO_NO_DEPRECATED) || defined(GENERATING_DOCUMENTATION) private basic_socket<Protocol> #else // defined(BOOST_ASIO_NO_DEPRECATED) || defined(GENERATING_DOCUMENTATION) public basic_socket<Protocol> #endif // defined(BOOST_ASIO_NO_DEPRECATED) || defined(GENERATING_DOCUMENTATION) { private: // These typedefs are intended keep this class's implementation independent // of whether it's using Boost.DateClock, Boost.Chrono or std::chrono. #if defined(BOOST_ASIO_HAS_BOOST_DATE_TIME) \ && defined(BOOST_ASIO_USE_BOOST_DATE_TIME_FOR_SOCKET_IOSTREAM) typedef WaitTraits traits_helper; #else // defined(BOOST_ASIO_HAS_BOOST_DATE_TIME) // && defined(BOOST_ASIO_USE_BOOST_DATE_TIME_FOR_SOCKET_IOSTREAM) typedef detail::chrono_time_traits<Clock, WaitTraits> traits_helper; #endif // defined(BOOST_ASIO_HAS_BOOST_DATE_TIME) // && defined(BOOST_ASIO_USE_BOOST_DATE_TIME_FOR_SOCKET_IOSTREAM) public: /// The protocol type. typedef Protocol protocol_type; /// The endpoint type. typedef typename Protocol::endpoint endpoint_type; /// The clock type. typedef Clock clock_type; #if defined(GENERATING_DOCUMENTATION) /// (Deprecated: Use time_point.) The time type. typedef typename WaitTraits::time_type time_type; /// The time type. typedef typename WaitTraits::time_point time_point; /// (Deprecated: Use duration.) The duration type. typedef typename WaitTraits::duration_type duration_type; /// The duration type. typedef typename WaitTraits::duration duration; #else # if !defined(BOOST_ASIO_NO_DEPRECATED) typedef typename traits_helper::time_type time_type; typedef typename traits_helper::duration_type duration_type; # endif // !defined(BOOST_ASIO_NO_DEPRECATED) typedef typename traits_helper::time_type time_point; typedef typename traits_helper::duration_type duration; #endif /// Construct a basic_socket_streambuf without establishing a connection. basic_socket_streambuf() : detail::socket_streambuf_io_context(new io_context), basic_socket<Protocol>(*default_io_context_), expiry_time_(max_expiry_time()) { init_buffers(); } /// Construct a basic_socket_streambuf from the supplied socket. explicit basic_socket_streambuf(basic_stream_socket<protocol_type> s) : detail::socket_streambuf_io_context(0), basic_socket<Protocol>(std::move(s)), expiry_time_(max_expiry_time()) { init_buffers(); } /// Move-construct a basic_socket_streambuf from another. basic_socket_streambuf(basic_socket_streambuf&& other) : detail::socket_streambuf_io_context(other), basic_socket<Protocol>(std::move(other.socket())), ec_(other.ec_), expiry_time_(other.expiry_time_) { get_buffer_.swap(other.get_buffer_); put_buffer_.swap(other.put_buffer_); setg(other.eback(), other.gptr(), other.egptr()); setp(other.pptr(), other.epptr()); other.ec_ = boost::system::error_code(); other.expiry_time_ = max_expiry_time(); other.init_buffers(); } /// Move-assign a basic_socket_streambuf from another. basic_socket_streambuf& operator=(basic_socket_streambuf&& other) { this->close(); socket() = std::move(other.socket()); detail::socket_streambuf_io_context::operator=(other); ec_ = other.ec_; expiry_time_ = other.expiry_time_; get_buffer_.swap(other.get_buffer_); put_buffer_.swap(other.put_buffer_); setg(other.eback(), other.gptr(), other.egptr()); setp(other.pptr(), other.epptr()); other.ec_ = boost::system::error_code(); other.expiry_time_ = max_expiry_time(); other.put_buffer_.resize(buffer_size); other.init_buffers(); return *this; } /// Destructor flushes buffered data. virtual ~basic_socket_streambuf() { if (pptr() != pbase()) overflow(traits_type::eof()); } /// Establish a connection. /** * This function establishes a connection to the specified endpoint. * * @return \c this if a connection was successfully established, a null * pointer otherwise. */ basic_socket_streambuf* connect(const endpoint_type& endpoint) { init_buffers(); ec_ = boost::system::error_code(); this->connect_to_endpoints(&endpoint, &endpoint + 1); return !ec_ ? this : 0; } /// Establish a connection. /** * This function automatically establishes a connection based on the supplied * resolver query parameters. The arguments are used to construct a resolver * query object. * * @return \c this if a connection was successfully established, a null * pointer otherwise. */ template <typename... T> basic_socket_streambuf* connect(T... x) { init_buffers(); typedef typename Protocol::resolver resolver_type; resolver_type resolver(socket().get_executor()); connect_to_endpoints(resolver.resolve(x..., ec_)); return !ec_ ? this : 0; } /// Close the connection. /** * @return \c this if a connection was successfully established, a null * pointer otherwise. */ basic_socket_streambuf* close() { sync(); socket().close(ec_); if (!ec_) init_buffers(); return !ec_ ? this : 0; } /// Get a reference to the underlying socket. basic_socket<Protocol>& socket() { return *this; } /// Get the last error associated with the stream buffer. /** * @return An \c error_code corresponding to the last error from the stream * buffer. */ const boost::system::error_code& error() const { return ec_; } #if !defined(BOOST_ASIO_NO_DEPRECATED) /// (Deprecated: Use error().) Get the last error associated with the stream /// buffer. /** * @return An \c error_code corresponding to the last error from the stream * buffer. */ const boost::system::error_code& puberror() const { return error(); } /// (Deprecated: Use expiry().) Get the stream buffer's expiry time as an /// absolute time. /** * @return An absolute time value representing the stream buffer's expiry * time. */ time_point expires_at() const { return expiry_time_; } #endif // !defined(BOOST_ASIO_NO_DEPRECATED) /// Get the stream buffer's expiry time as an absolute time. /** * @return An absolute time value representing the stream buffer's expiry * time. */ time_point expiry() const { return expiry_time_; } /// Set the stream buffer's expiry time as an absolute time. /** * This function sets the expiry time associated with the stream. Stream * operations performed after this time (where the operations cannot be * completed using the internal buffers) will fail with the error * boost::asio::error::operation_aborted. * * @param expiry_time The expiry time to be used for the stream. */ void expires_at(const time_point& expiry_time) { expiry_time_ = expiry_time; } /// Set the stream buffer's expiry time relative to now. /** * This function sets the expiry time associated with the stream. Stream * operations performed after this time (where the operations cannot be * completed using the internal buffers) will fail with the error * boost::asio::error::operation_aborted. * * @param expiry_time The expiry time to be used for the timer. */ void expires_after(const duration& expiry_time) { expiry_time_ = traits_helper::add(traits_helper::now(), expiry_time); } #if !defined(BOOST_ASIO_NO_DEPRECATED) /// (Deprecated: Use expiry().) Get the stream buffer's expiry time relative /// to now. /** * @return A relative time value representing the stream buffer's expiry time. */ duration expires_from_now() const { return traits_helper::subtract(expires_at(), traits_helper::now()); } /// (Deprecated: Use expires_after().) Set the stream buffer's expiry time /// relative to now. /** * This function sets the expiry time associated with the stream. Stream * operations performed after this time (where the operations cannot be * completed using the internal buffers) will fail with the error * boost::asio::error::operation_aborted. * * @param expiry_time The expiry time to be used for the timer. */ void expires_from_now(const duration& expiry_time) { expiry_time_ = traits_helper::add(traits_helper::now(), expiry_time); } #endif // !defined(BOOST_ASIO_NO_DEPRECATED) protected: int_type underflow() { #if defined(BOOST_ASIO_WINDOWS_RUNTIME) ec_ = boost::asio::error::operation_not_supported; return traits_type::eof(); #else // defined(BOOST_ASIO_WINDOWS_RUNTIME) if (gptr() != egptr()) return traits_type::eof(); for (;;) { // Check if we are past the expiry time. if (traits_helper::less_than(expiry_time_, traits_helper::now())) { ec_ = boost::asio::error::timed_out; return traits_type::eof(); } // Try to complete the operation without blocking. if (!socket().native_non_blocking()) socket().native_non_blocking(true, ec_); detail::buffer_sequence_adapter<mutable_buffer, mutable_buffer> bufs(boost::asio::buffer(get_buffer_) + putback_max); detail::signed_size_type bytes = detail::socket_ops::recv( socket().native_handle(), bufs.buffers(), bufs.count(), 0, ec_); // Check if operation succeeded. if (bytes > 0) { setg(&get_buffer_[0], &get_buffer_[0] + putback_max, &get_buffer_[0] + putback_max + bytes); return traits_type::to_int_type(*gptr()); } // Check for EOF. if (bytes == 0) { ec_ = boost::asio::error::eof; return traits_type::eof(); } // Operation failed. if (ec_ != boost::asio::error::would_block && ec_ != boost::asio::error::try_again) return traits_type::eof(); // Wait for socket to become ready. if (detail::socket_ops::poll_read( socket().native_handle(), 0, timeout(), ec_) < 0) return traits_type::eof(); } #endif // defined(BOOST_ASIO_WINDOWS_RUNTIME) } int_type overflow(int_type c) { #if defined(BOOST_ASIO_WINDOWS_RUNTIME) ec_ = boost::asio::error::operation_not_supported; return traits_type::eof(); #else // defined(BOOST_ASIO_WINDOWS_RUNTIME) char_type ch = traits_type::to_char_type(c); // Determine what needs to be sent. const_buffer output_buffer; if (put_buffer_.empty()) { if (traits_type::eq_int_type(c, traits_type::eof())) return traits_type::not_eof(c); // Nothing to do. output_buffer = boost::asio::buffer(&ch, sizeof(char_type)); } else { output_buffer = boost::asio::buffer(pbase(), (pptr() - pbase()) * sizeof(char_type)); } while (output_buffer.size() > 0) { // Check if we are past the expiry time. if (traits_helper::less_than(expiry_time_, traits_helper::now())) { ec_ = boost::asio::error::timed_out; return traits_type::eof(); } // Try to complete the operation without blocking. if (!socket().native_non_blocking()) socket().native_non_blocking(true, ec_); detail::buffer_sequence_adapter< const_buffer, const_buffer> bufs(output_buffer); detail::signed_size_type bytes = detail::socket_ops::send( socket().native_handle(), bufs.buffers(), bufs.count(), 0, ec_); // Check if operation succeeded. if (bytes > 0) { output_buffer += static_cast<std::size_t>(bytes); continue; } // Operation failed. if (ec_ != boost::asio::error::would_block && ec_ != boost::asio::error::try_again) return traits_type::eof(); // Wait for socket to become ready. if (detail::socket_ops::poll_write( socket().native_handle(), 0, timeout(), ec_) < 0) return traits_type::eof(); } if (!put_buffer_.empty()) { setp(&put_buffer_[0], &put_buffer_[0] + put_buffer_.size()); // If the new character is eof then our work here is done. if (traits_type::eq_int_type(c, traits_type::eof())) return traits_type::not_eof(c); // Add the new character to the output buffer. *pptr() = ch; pbump(1); } return c; #endif // defined(BOOST_ASIO_WINDOWS_RUNTIME) } int sync() { return overflow(traits_type::eof()); } std::streambuf* setbuf(char_type* s, std::streamsize n) { if (pptr() == pbase() && s == 0 && n == 0) { put_buffer_.clear(); setp(0, 0); sync(); return this; } return 0; } private: // Disallow copying and assignment. basic_socket_streambuf(const basic_socket_streambuf&) = delete; basic_socket_streambuf& operator=( const basic_socket_streambuf&) = delete; void init_buffers() { setg(&get_buffer_[0], &get_buffer_[0] + putback_max, &get_buffer_[0] + putback_max); if (put_buffer_.empty()) setp(0, 0); else setp(&put_buffer_[0], &put_buffer_[0] + put_buffer_.size()); } int timeout() const { int64_t msec = traits_helper::to_posix_duration( traits_helper::subtract(expiry_time_, traits_helper::now())).total_milliseconds(); if (msec > (std::numeric_limits<int>::max)()) msec = (std::numeric_limits<int>::max)(); else if (msec < 0) msec = 0; return static_cast<int>(msec); } template <typename EndpointSequence> void connect_to_endpoints(const EndpointSequence& endpoints) { this->connect_to_endpoints(endpoints.begin(), endpoints.end()); } template <typename EndpointIterator> void connect_to_endpoints(EndpointIterator begin, EndpointIterator end) { #if defined(BOOST_ASIO_WINDOWS_RUNTIME) ec_ = boost::asio::error::operation_not_supported; #else // defined(BOOST_ASIO_WINDOWS_RUNTIME) if (ec_) return; ec_ = boost::asio::error::not_found; for (EndpointIterator i = begin; i != end; ++i) { // Check if we are past the expiry time. if (traits_helper::less_than(expiry_time_, traits_helper::now())) { ec_ = boost::asio::error::timed_out; return; } // Close and reopen the socket. typename Protocol::endpoint ep(*i); socket().close(ec_); socket().open(ep.protocol(), ec_); if (ec_) continue; // Try to complete the operation without blocking. if (!socket().native_non_blocking()) socket().native_non_blocking(true, ec_); detail::socket_ops::connect(socket().native_handle(), ep.data(), ep.size(), ec_); // Check if operation succeeded. if (!ec_) return; // Operation failed. if (ec_ != boost::asio::error::in_progress && ec_ != boost::asio::error::would_block) continue; // Wait for socket to become ready. if (detail::socket_ops::poll_connect( socket().native_handle(), timeout(), ec_) < 0) continue; // Get the error code from the connect operation. int connect_error = 0; size_t connect_error_len = sizeof(connect_error); if (detail::socket_ops::getsockopt(socket().native_handle(), 0, SOL_SOCKET, SO_ERROR, &connect_error, &connect_error_len, ec_) == detail::socket_error_retval) return; // Check the result of the connect operation. ec_ = boost::system::error_code(connect_error, boost::asio::error::get_system_category()); if (!ec_) return; } #endif // defined(BOOST_ASIO_WINDOWS_RUNTIME) } // Helper function to get the maximum expiry time. static time_point max_expiry_time() { #if defined(BOOST_ASIO_HAS_BOOST_DATE_TIME) \ && defined(BOOST_ASIO_USE_BOOST_DATE_TIME_FOR_SOCKET_IOSTREAM) return boost::posix_time::pos_infin; #else // defined(BOOST_ASIO_HAS_BOOST_DATE_TIME) // && defined(BOOST_ASIO_USE_BOOST_DATE_TIME_FOR_SOCKET_IOSTREAM) return (time_point::max)(); #endif // defined(BOOST_ASIO_HAS_BOOST_DATE_TIME) // && defined(BOOST_ASIO_USE_BOOST_DATE_TIME_FOR_SOCKET_IOSTREAM) } enum { putback_max = 8 }; boost::system::error_code ec_; time_point expiry_time_; }; } // namespace asio } // namespace boost #include <boost/asio/detail/pop_options.hpp> #endif // !defined(BOOST_ASIO_NO_IOSTREAM) #endif // BOOST_ASIO_BASIC_SOCKET_STREAMBUF_HPP
hpp
asio
data/projects/asio/include/boost/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 BOOST_ASIO_BUFFERED_WRITE_STREAM_HPP #define BOOST_ASIO_BUFFERED_WRITE_STREAM_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <boost/asio/detail/config.hpp> #include <cstddef> #include <boost/asio/buffered_write_stream_fwd.hpp> #include <boost/asio/buffer.hpp> #include <boost/asio/completion_condition.hpp> #include <boost/asio/detail/bind_handler.hpp> #include <boost/asio/detail/buffered_stream_storage.hpp> #include <boost/asio/detail/noncopyable.hpp> #include <boost/asio/detail/type_traits.hpp> #include <boost/asio/error.hpp> #include <boost/asio/write.hpp> #include <boost/asio/detail/push_options.hpp> namespace boost { 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 BOOST_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. BOOST_ASIO_SYNC_OP_VOID close(boost::system::error_code& ec) { next_layer_.close(ec); BOOST_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(boost::system::error_code& ec); /// Start an asynchronous flush. /** * @par Completion Signature * @code void(boost::system::error_code, std::size_t) @endcode */ template < BOOST_ASIO_COMPLETION_TOKEN_FOR(void (boost::system::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 (boost::system::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, boost::system::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(boost::system::error_code, std::size_t) @endcode */ template <typename ConstBufferSequence, BOOST_ASIO_COMPLETION_TOKEN_FOR(void (boost::system::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 (boost::system::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, boost::system::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(boost::system::error_code, std::size_t) @endcode */ template <typename MutableBufferSequence, BOOST_ASIO_COMPLETION_TOKEN_FOR(void (boost::system::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, boost::system::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(boost::system::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 } // namespace boost #include <boost/asio/detail/pop_options.hpp> #include <boost/asio/impl/buffered_write_stream.hpp> #endif // BOOST_ASIO_BUFFERED_WRITE_STREAM_HPP
hpp
asio
data/projects/asio/include/boost/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 BOOST_ASIO_CONSIGN_HPP #define BOOST_ASIO_CONSIGN_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <boost/asio/detail/config.hpp> #include <tuple> #include <boost/asio/detail/type_traits.hpp> #include <boost/asio/detail/push_options.hpp> namespace boost { 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> BOOST_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 } // namespace boost #include <boost/asio/detail/pop_options.hpp> #include <boost/asio/impl/consign.hpp> #endif // BOOST_ASIO_CONSIGN_HPP
hpp
asio
data/projects/asio/include/boost/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 BOOST_ASIO_COROUTINE_HPP #define BOOST_ASIO_COROUTINE_HPP namespace boost { 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 <boost/asio/yield.hpp>@endcode * * and may conversely be undefined as follows: * * @code #include <boost/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 boost::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 BOOST_ASIO_CORO_REENTER instead of @c reenter * @li @c BOOST_ASIO_CORO_YIELD instead of @c yield * @li @c BOOST_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 } // namespace boost #define BOOST_ASIO_CORO_REENTER(c) \ switch (::boost::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 BOOST_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 BOOST_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 BOOST_ASIO_CORO_YIELD BOOST_ASIO_CORO_YIELD_IMPL(__COUNTER__ + 1) # define BOOST_ASIO_CORO_FORK BOOST_ASIO_CORO_FORK_IMPL(__COUNTER__ + 1) #else // defined(_MSC_VER) # define BOOST_ASIO_CORO_YIELD BOOST_ASIO_CORO_YIELD_IMPL(__LINE__) # define BOOST_ASIO_CORO_FORK BOOST_ASIO_CORO_FORK_IMPL(__LINE__) #endif // defined(_MSC_VER) #endif // BOOST_ASIO_COROUTINE_HPP
hpp
asio
data/projects/asio/include/boost/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 BOOST_ASIO_SYSTEM_EXECUTOR_HPP #define BOOST_ASIO_SYSTEM_EXECUTOR_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <boost/asio/detail/config.hpp> #include <boost/asio/detail/memory.hpp> #include <boost/asio/execution.hpp> #include <boost/asio/detail/push_options.hpp> namespace boost { 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 boost_asio_require_fn::impl; friend struct boost_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 * boost::asio::require customisation point. * * For example: * @code boost::asio::system_executor ex1; * auto ex2 = boost::asio::require(ex1, * boost::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 * boost::asio::require customisation point. * * For example: * @code boost::asio::system_executor ex1; * auto ex2 = boost::asio::require(ex1, * boost::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 * boost::asio::require customisation point. * * For example: * @code boost::asio::system_executor ex1; * auto ex2 = boost::asio::require(ex1, * boost::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 * boost::asio::require customisation point. * * For example: * @code boost::asio::system_executor ex1; * auto ex2 = boost::asio::require(ex1, * boost::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 * boost::asio::require customisation point. * * For example: * @code boost::asio::system_executor ex1; * auto ex2 = boost::asio::require(ex1, * boost::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 * boost::asio::require customisation point. * * For example: * @code boost::asio::system_executor ex1; * auto ex2 = boost::asio::require(ex1, * boost::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 * boost::asio::require customisation point. * * For example: * @code boost::asio::system_executor ex1; * auto ex2 = boost::asio::require(ex1, * boost::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 boost_asio_query_fn::impl; friend struct boost::asio::execution::detail::blocking_t<0>; friend struct boost::asio::execution::detail::mapping_t<0>; friend struct boost::asio::execution::detail::outstanding_work_t<0>; friend struct boost::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 * boost::asio::query customisation point. * * For example: * @code boost::asio::system_executor ex; * if (boost::asio::query(ex, boost::asio::execution::mapping) * == boost::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 * boost::asio::query customisation point. * * For example: * @code boost::asio::system_executor ex; * boost::asio::system_context& pool = boost::asio::query( * ex, boost::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 * boost::asio::query customisation point. * * For example: * @code boost::asio::system_executor ex; * if (boost::asio::query(ex, boost::asio::execution::blocking) * == boost::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 * boost::asio::query customisation point. * * For example: * @code boost::asio::system_executor ex; * if (boost::asio::query(ex, boost::asio::execution::relationship) * == boost::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 * boost::asio::query customisation point. * * For example: * @code boost::asio::system_executor ex; * auto alloc = boost::asio::query(ex, * boost::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 * boost::asio::query customisation point. * * For example: * @code boost::asio::system_executor ex; * auto alloc = boost::asio::query(ex, * boost::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 * boost::asio::query customisation point. * * For example: * @code boost::asio::system_executor ex; * std::size_t occupancy = boost::asio::query( * ex, boost::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(BOOST_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(BOOST_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(BOOST_ASIO_HAS_DEDUCED_EQUALITY_COMPARABLE_TRAIT) template <typename Blocking, typename Relationship, typename Allocator> struct equality_comparable< boost::asio::basic_system_executor<Blocking, Relationship, Allocator> > { static constexpr bool is_valid = true; static constexpr bool is_noexcept = true; }; #endif // !defined(BOOST_ASIO_HAS_DEDUCED_EQUALITY_COMPARABLE_TRAIT) #if !defined(BOOST_ASIO_HAS_DEDUCED_EXECUTE_MEMBER_TRAIT) template <typename Blocking, typename Relationship, typename Allocator, typename Function> struct execute_member< boost::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(BOOST_ASIO_HAS_DEDUCED_EXECUTE_MEMBER_TRAIT) #if !defined(BOOST_ASIO_HAS_DEDUCED_REQUIRE_MEMBER_TRAIT) template <typename Blocking, typename Relationship, typename Allocator> struct require_member< boost::asio::basic_system_executor<Blocking, Relationship, Allocator>, boost::asio::execution::blocking_t::possibly_t > { static constexpr bool is_valid = true; static constexpr bool is_noexcept = false; typedef boost::asio::basic_system_executor< boost::asio::execution::blocking_t::possibly_t, Relationship, Allocator> result_type; }; template <typename Blocking, typename Relationship, typename Allocator> struct require_member< boost::asio::basic_system_executor<Blocking, Relationship, Allocator>, boost::asio::execution::blocking_t::always_t > { static constexpr bool is_valid = true; static constexpr bool is_noexcept = false; typedef boost::asio::basic_system_executor< boost::asio::execution::blocking_t::always_t, Relationship, Allocator> result_type; }; template <typename Blocking, typename Relationship, typename Allocator> struct require_member< boost::asio::basic_system_executor<Blocking, Relationship, Allocator>, boost::asio::execution::blocking_t::never_t > { static constexpr bool is_valid = true; static constexpr bool is_noexcept = false; typedef boost::asio::basic_system_executor< boost::asio::execution::blocking_t::never_t, Relationship, Allocator> result_type; }; template <typename Blocking, typename Relationship, typename Allocator> struct require_member< boost::asio::basic_system_executor<Blocking, Relationship, Allocator>, boost::asio::execution::relationship_t::fork_t > { static constexpr bool is_valid = true; static constexpr bool is_noexcept = false; typedef boost::asio::basic_system_executor<Blocking, boost::asio::execution::relationship_t::fork_t, Allocator> result_type; }; template <typename Blocking, typename Relationship, typename Allocator> struct require_member< boost::asio::basic_system_executor<Blocking, Relationship, Allocator>, boost::asio::execution::relationship_t::continuation_t > { static constexpr bool is_valid = true; static constexpr bool is_noexcept = false; typedef boost::asio::basic_system_executor<Blocking, boost::asio::execution::relationship_t::continuation_t, Allocator> result_type; }; template <typename Blocking, typename Relationship, typename Allocator> struct require_member< boost::asio::basic_system_executor<Blocking, Relationship, Allocator>, boost::asio::execution::allocator_t<void> > { static constexpr bool is_valid = true; static constexpr bool is_noexcept = false; typedef boost::asio::basic_system_executor<Blocking, Relationship, std::allocator<void>> result_type; }; template <typename Blocking, typename Relationship, typename Allocator, typename OtherAllocator> struct require_member< boost::asio::basic_system_executor<Blocking, Relationship, Allocator>, boost::asio::execution::allocator_t<OtherAllocator> > { static constexpr bool is_valid = true; static constexpr bool is_noexcept = false; typedef boost::asio::basic_system_executor<Blocking, Relationship, OtherAllocator> result_type; }; #endif // !defined(BOOST_ASIO_HAS_DEDUCED_REQUIRE_MEMBER_TRAIT) #if !defined(BOOST_ASIO_HAS_DEDUCED_QUERY_STATIC_CONSTEXPR_MEMBER_TRAIT) template <typename Blocking, typename Relationship, typename Allocator, typename Property> struct query_static_constexpr_member< boost::asio::basic_system_executor<Blocking, Relationship, Allocator>, Property, typename boost::asio::enable_if< boost::asio::is_convertible< Property, boost::asio::execution::mapping_t >::value >::type > { static constexpr bool is_valid = true; static constexpr bool is_noexcept = true; typedef boost::asio::execution::mapping_t::thread_t result_type; static constexpr result_type value() noexcept { return result_type(); } }; #endif // !defined(BOOST_ASIO_HAS_DEDUCED_QUERY_STATIC_CONSTEXPR_MEMBER_TRAIT) #if !defined(BOOST_ASIO_HAS_DEDUCED_QUERY_MEMBER_TRAIT) template <typename Blocking, typename Relationship, typename Allocator, typename Property> struct query_member< boost::asio::basic_system_executor<Blocking, Relationship, Allocator>, Property, typename boost::asio::enable_if< boost::asio::is_convertible< Property, boost::asio::execution::blocking_t >::value >::type > { static constexpr bool is_valid = true; static constexpr bool is_noexcept = true; typedef boost::asio::execution::blocking_t result_type; }; template <typename Blocking, typename Relationship, typename Allocator, typename Property> struct query_member< boost::asio::basic_system_executor<Blocking, Relationship, Allocator>, Property, typename boost::asio::enable_if< boost::asio::is_convertible< Property, boost::asio::execution::relationship_t >::value >::type > { static constexpr bool is_valid = true; static constexpr bool is_noexcept = true; typedef boost::asio::execution::relationship_t result_type; }; template <typename Blocking, typename Relationship, typename Allocator> struct query_member< boost::asio::basic_system_executor<Blocking, Relationship, Allocator>, boost::asio::execution::context_t > { static constexpr bool is_valid = true; static constexpr bool is_noexcept = true; typedef boost::asio::system_context& result_type; }; template <typename Blocking, typename Relationship, typename Allocator> struct query_member< boost::asio::basic_system_executor<Blocking, Relationship, Allocator>, boost::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< boost::asio::basic_system_executor<Blocking, Relationship, Allocator>, boost::asio::execution::allocator_t<Allocator> > { static constexpr bool is_valid = true; static constexpr bool is_noexcept = true; typedef Allocator result_type; }; #endif // !defined(BOOST_ASIO_HAS_DEDUCED_QUERY_MEMBER_TRAIT) } // namespace traits #endif // !defined(GENERATING_DOCUMENTATION) } // namespace asio } // namespace boost #include <boost/asio/detail/pop_options.hpp> #include <boost/asio/impl/system_executor.hpp> #endif // BOOST_ASIO_SYSTEM_EXECUTOR_HPP
hpp
asio
data/projects/asio/include/boost/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 BOOST_ASIO_VERSION_HPP #define BOOST_ASIO_VERSION_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) // BOOST_ASIO_VERSION % 100 is the sub-minor version // BOOST_ASIO_VERSION / 100 % 1000 is the minor version // BOOST_ASIO_VERSION / 100000 is the major version #define BOOST_ASIO_VERSION 103001 // 1.30.1 #endif // BOOST_ASIO_VERSION_HPP
hpp
asio
data/projects/asio/include/boost/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 BOOST_ASIO_FILE_BASE_HPP #define BOOST_ASIO_FILE_BASE_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <boost/asio/detail/config.hpp> #if defined(BOOST_ASIO_HAS_FILE) \ || defined(GENERATING_DOCUMENTATION) #if !defined(BOOST_ASIO_WINDOWS) # include <fcntl.h> #endif // !defined(BOOST_ASIO_WINDOWS) #include <boost/asio/detail/push_options.hpp> namespace boost { 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(BOOST_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(BOOST_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(BOOST_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 } // namespace boost #include <boost/asio/detail/pop_options.hpp> #endif // defined(BOOST_ASIO_HAS_FILE) // || defined(GENERATING_DOCUMENTATION) #endif // BOOST_ASIO_FILE_BASE_HPP
hpp
asio
data/projects/asio/include/boost/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 BOOST_ASIO_BUFFER_HPP #define BOOST_ASIO_BUFFER_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <boost/asio/detail/config.hpp> #include <cstddef> #include <cstring> #include <limits> #include <stdexcept> #include <string> #include <vector> #include <boost/asio/detail/array_fwd.hpp> #include <boost/asio/detail/memory.hpp> #include <boost/asio/detail/string_view.hpp> #include <boost/asio/detail/throw_exception.hpp> #include <boost/asio/detail/type_traits.hpp> #include <boost/asio/is_contiguous_iterator.hpp> #if defined(BOOST_ASIO_MSVC) && (BOOST_ASIO_MSVC >= 1700) # if defined(_HAS_ITERATOR_DEBUGGING) && (_HAS_ITERATOR_DEBUGGING != 0) # if !defined(BOOST_ASIO_DISABLE_BUFFER_DEBUGGING) # define BOOST_ASIO_ENABLE_BUFFER_DEBUGGING # endif // !defined(BOOST_ASIO_DISABLE_BUFFER_DEBUGGING) # endif // defined(_HAS_ITERATOR_DEBUGGING) #endif // defined(BOOST_ASIO_MSVC) && (BOOST_ASIO_MSVC >= 1700) #if defined(__GNUC__) # if defined(_GLIBCXX_DEBUG) # if !defined(BOOST_ASIO_DISABLE_BUFFER_DEBUGGING) # define BOOST_ASIO_ENABLE_BUFFER_DEBUGGING # endif // !defined(BOOST_ASIO_DISABLE_BUFFER_DEBUGGING) # endif // defined(_GLIBCXX_DEBUG) #endif // defined(__GNUC__) #if defined(BOOST_ASIO_ENABLE_BUFFER_DEBUGGING) # include <boost/asio/detail/functional.hpp> #endif // BOOST_ASIO_ENABLE_BUFFER_DEBUGGING #include <boost/asio/detail/push_options.hpp> namespace boost { 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 boost::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(BOOST_ASIO_ENABLE_BUFFER_DEBUGGING) mutable_buffer(void* data, std::size_t size, boost::asio::detail::function<void()> debug_check) : data_(data), size_(size), debug_check_(debug_check) { } const boost::asio::detail::function<void()>& get_debug_check() const { return debug_check_; } #endif // BOOST_ASIO_ENABLE_BUFFER_DEBUGGING /// Get a pointer to the beginning of the memory range. void* data() const noexcept { #if defined(BOOST_ASIO_ENABLE_BUFFER_DEBUGGING) if (size_ && debug_check_) debug_check_(); #endif // BOOST_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(BOOST_ASIO_ENABLE_BUFFER_DEBUGGING) boost::asio::detail::function<void()> debug_check_; #endif // BOOST_ASIO_ENABLE_BUFFER_DEBUGGING }; #if !defined(BOOST_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(BOOST_ASIO_ENABLE_BUFFER_DEBUGGING) mutable_buffers_1(void* data, std::size_t size, boost::asio::detail::function<void()> debug_check) : mutable_buffer(data, size, debug_check) { } #endif // BOOST_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(BOOST_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 boost::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(BOOST_ASIO_ENABLE_BUFFER_DEBUGGING) , debug_check_(b.get_debug_check()) #endif // BOOST_ASIO_ENABLE_BUFFER_DEBUGGING { } #if defined(BOOST_ASIO_ENABLE_BUFFER_DEBUGGING) const_buffer(const void* data, std::size_t size, boost::asio::detail::function<void()> debug_check) : data_(data), size_(size), debug_check_(debug_check) { } const boost::asio::detail::function<void()>& get_debug_check() const { return debug_check_; } #endif // BOOST_ASIO_ENABLE_BUFFER_DEBUGGING /// Get a pointer to the beginning of the memory range. const void* data() const noexcept { #if defined(BOOST_ASIO_ENABLE_BUFFER_DEBUGGING) if (size_ && debug_check_) debug_check_(); #endif // BOOST_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(BOOST_ASIO_ENABLE_BUFFER_DEBUGGING) boost::asio::detail::function<void()> debug_check_; #endif // BOOST_ASIO_ENABLE_BUFFER_DEBUGGING }; #if !defined(BOOST_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(BOOST_ASIO_ENABLE_BUFFER_DEBUGGING) const_buffers_1(const void* data, std::size_t size, boost::asio::detail::function<void()> debug_check) : const_buffer(data, size, debug_check) { } #endif // BOOST_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(BOOST_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 boost::asio::buffer_sequence_begin * * @brief The boost::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 boost::asio::buffer_sequence_end * * @brief The boost::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(BOOST_ASIO_NO_DEPRECATED) || is_same<BufferSequence, mutable_buffers_1>::value || is_same<BufferSequence, const_buffers_1>::value #endif // !defined(BOOST_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 = boost::asio::buffer_sequence_begin(buffers); * auto end = boost::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>(), boost::asio::buffer_sequence_begin(b), boost::asio::buffer_sequence_end(b)); } #if !defined(BOOST_ASIO_NO_DEPRECATED) /** @defgroup buffer_cast boost::asio::buffer_cast * * @brief (Deprecated: Use the @c data() member function.) The * boost::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 boost::asio::const_buffer b1 = ...; * const unsigned char* p1 = boost::asio::buffer_cast<const unsigned char*>(b1); * @endcode * * To access the memory of a modifiable buffer, use: * @code boost::asio::mutable_buffer b2 = ...; * unsigned char* p2 = boost::asio::buffer_cast<unsigned char*>(b2); * @endcode * * The boost::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(BOOST_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(BOOST_ASIO_ENABLE_BUFFER_DEBUGGING) , b.get_debug_check() #endif // BOOST_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(BOOST_ASIO_ENABLE_BUFFER_DEBUGGING) , b.get_debug_check() #endif // BOOST_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(BOOST_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(BOOST_ASIO_MSVC) && (BOOST_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(BOOST_ASIO_MSVC) && (BOOST_ASIO_MSVC == 1400) } void operator()() { (void)*iter_; } private: Iterator iter_; }; } // namespace detail #endif // BOOST_ASIO_ENABLE_BUFFER_DEBUGGING /** @defgroup buffer boost::asio::buffer * * @brief The boost::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(boost::asio::buffer(data, size)); @endcode * * In the above example, the return value of boost::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(boost::asio::buffer(d1)); * * std::vector<char> d2(128); * bytes_transferred = sock.receive(boost::asio::buffer(d2)); * * std::array<char, 128> d3; * bytes_transferred = sock.receive(boost::asio::buffer(d3)); * * boost::array<char, 128> d4; * bytes_transferred = sock.receive(boost::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 boost::asio::mutable_buffer b1 = ...; * std::size_t s1 = b1.size(); * unsigned char* p1 = static_cast<unsigned char*>(b1.data()); * * boost::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(boost::asio::buffer_size(buffers)); * boost::asio::buffer_copy(boost::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 boost::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 boost::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 = boost::asio::buffer(a); @endcode * * represents the entire array, <tt>{ 'a', 'b', 'c', 'd', 'e' }</tt>. An * optional second argument to the boost::asio::buffer function may be used to * limit the size, in bytes, of the buffer: * * @code b2 = boost::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 = boost::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 = { * boost::asio::buffer(d1), * boost::asio::buffer(d2), * boost::asio::buffer(d3) }; * bytes_transferred = sock.receive(bufs1); * * std::vector<const_buffer> bufs2; * bufs2.push_back(boost::asio::buffer(d1)); * bufs2.push_back(boost::asio::buffer(d2)); * bufs2.push_back(boost::asio::buffer(d3)); * bytes_transferred = sock.send(bufs2); @endcode * * @par Buffer Literals * * The `_buf` literal suffix, defined in namespace * <tt>boost::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 boost::asio::buffer_literals; * * boost::asio::const_buffer b1 = "hello"_buf; * boost::asio::const_buffer b2 = 0xdeadbeef_buf; * boost::asio::const_buffer b3 = 0x0123456789abcdef0123456789abcdef_buf; * boost::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(BOOST_ASIO_NO_DEPRECATED) || defined(GENERATING_DOCUMENTATION) # define BOOST_ASIO_MUTABLE_BUFFER mutable_buffer # define BOOST_ASIO_CONST_BUFFER const_buffer #else // defined(BOOST_ASIO_NO_DEPRECATED) || defined(GENERATING_DOCUMENTATION) # define BOOST_ASIO_MUTABLE_BUFFER mutable_buffers_1 # define BOOST_ASIO_CONST_BUFFER const_buffers_1 #endif // defined(BOOST_ASIO_NO_DEPRECATED) || defined(GENERATING_DOCUMENTATION) /// Create a new modifiable buffer from an existing buffer. /** * @returns <tt>mutable_buffer(b)</tt>. */ BOOST_ASIO_NODISCARD inline BOOST_ASIO_MUTABLE_BUFFER buffer( const mutable_buffer& b) noexcept { return BOOST_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 */ BOOST_ASIO_NODISCARD inline BOOST_ASIO_MUTABLE_BUFFER buffer( const mutable_buffer& b, std::size_t max_size_in_bytes) noexcept { return BOOST_ASIO_MUTABLE_BUFFER( mutable_buffer(b.data(), b.size() < max_size_in_bytes ? b.size() : max_size_in_bytes #if defined(BOOST_ASIO_ENABLE_BUFFER_DEBUGGING) , b.get_debug_check() #endif // BOOST_ASIO_ENABLE_BUFFER_DEBUGGING )); } /// Create a new non-modifiable buffer from an existing buffer. /** * @returns <tt>const_buffer(b)</tt>. */ BOOST_ASIO_NODISCARD inline BOOST_ASIO_CONST_BUFFER buffer( const const_buffer& b) noexcept { return BOOST_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 */ BOOST_ASIO_NODISCARD inline BOOST_ASIO_CONST_BUFFER buffer( const const_buffer& b, std::size_t max_size_in_bytes) noexcept { return BOOST_ASIO_CONST_BUFFER(b.data(), b.size() < max_size_in_bytes ? b.size() : max_size_in_bytes #if defined(BOOST_ASIO_ENABLE_BUFFER_DEBUGGING) , b.get_debug_check() #endif // BOOST_ASIO_ENABLE_BUFFER_DEBUGGING ); } /// Create a new modifiable buffer that represents the given memory range. /** * @returns <tt>mutable_buffer(data, size_in_bytes)</tt>. */ BOOST_ASIO_NODISCARD inline BOOST_ASIO_MUTABLE_BUFFER buffer( void* data, std::size_t size_in_bytes) noexcept { return BOOST_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>. */ BOOST_ASIO_NODISCARD inline BOOST_ASIO_CONST_BUFFER buffer( const void* data, std::size_t size_in_bytes) noexcept { return BOOST_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> BOOST_ASIO_NODISCARD inline BOOST_ASIO_MUTABLE_BUFFER buffer( PodType (&data)[N]) noexcept { return BOOST_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> BOOST_ASIO_NODISCARD inline BOOST_ASIO_MUTABLE_BUFFER buffer( PodType (&data)[N], std::size_t max_size_in_bytes) noexcept { return BOOST_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> BOOST_ASIO_NODISCARD inline BOOST_ASIO_CONST_BUFFER buffer( const PodType (&data)[N]) noexcept { return BOOST_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> BOOST_ASIO_NODISCARD inline BOOST_ASIO_CONST_BUFFER buffer( const PodType (&data)[N], std::size_t max_size_in_bytes) noexcept { return BOOST_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> BOOST_ASIO_NODISCARD inline BOOST_ASIO_MUTABLE_BUFFER buffer( boost::array<PodType, N>& data) noexcept { return BOOST_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> BOOST_ASIO_NODISCARD inline BOOST_ASIO_MUTABLE_BUFFER buffer( boost::array<PodType, N>& data, std::size_t max_size_in_bytes) noexcept { return BOOST_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> BOOST_ASIO_NODISCARD inline BOOST_ASIO_CONST_BUFFER buffer( boost::array<const PodType, N>& data) noexcept { return BOOST_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> BOOST_ASIO_NODISCARD inline BOOST_ASIO_CONST_BUFFER buffer( boost::array<const PodType, N>& data, std::size_t max_size_in_bytes) noexcept { return BOOST_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> BOOST_ASIO_NODISCARD inline BOOST_ASIO_CONST_BUFFER buffer( const boost::array<PodType, N>& data) noexcept { return BOOST_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> BOOST_ASIO_NODISCARD inline BOOST_ASIO_CONST_BUFFER buffer( const boost::array<PodType, N>& data, std::size_t max_size_in_bytes) noexcept { return BOOST_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> BOOST_ASIO_NODISCARD inline BOOST_ASIO_MUTABLE_BUFFER buffer( std::array<PodType, N>& data) noexcept { return BOOST_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> BOOST_ASIO_NODISCARD inline BOOST_ASIO_MUTABLE_BUFFER buffer( std::array<PodType, N>& data, std::size_t max_size_in_bytes) noexcept { return BOOST_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> BOOST_ASIO_NODISCARD inline BOOST_ASIO_CONST_BUFFER buffer( std::array<const PodType, N>& data) noexcept { return BOOST_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> BOOST_ASIO_NODISCARD inline BOOST_ASIO_CONST_BUFFER buffer( std::array<const PodType, N>& data, std::size_t max_size_in_bytes) noexcept { return BOOST_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> BOOST_ASIO_NODISCARD inline BOOST_ASIO_CONST_BUFFER buffer( const std::array<PodType, N>& data) noexcept { return BOOST_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> BOOST_ASIO_NODISCARD inline BOOST_ASIO_CONST_BUFFER buffer( const std::array<PodType, N>& data, std::size_t max_size_in_bytes) noexcept { return BOOST_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> BOOST_ASIO_NODISCARD inline BOOST_ASIO_MUTABLE_BUFFER buffer( std::vector<PodType, Allocator>& data) noexcept { return BOOST_ASIO_MUTABLE_BUFFER( data.size() ? &data[0] : 0, data.size() * sizeof(PodType) #if defined(BOOST_ASIO_ENABLE_BUFFER_DEBUGGING) , detail::buffer_debug_check< typename std::vector<PodType, Allocator>::iterator >(data.begin()) #endif // BOOST_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> BOOST_ASIO_NODISCARD inline BOOST_ASIO_MUTABLE_BUFFER buffer( std::vector<PodType, Allocator>& data, std::size_t max_size_in_bytes) noexcept { return BOOST_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(BOOST_ASIO_ENABLE_BUFFER_DEBUGGING) , detail::buffer_debug_check< typename std::vector<PodType, Allocator>::iterator >(data.begin()) #endif // BOOST_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> BOOST_ASIO_NODISCARD inline BOOST_ASIO_CONST_BUFFER buffer( const std::vector<PodType, Allocator>& data) noexcept { return BOOST_ASIO_CONST_BUFFER( data.size() ? &data[0] : 0, data.size() * sizeof(PodType) #if defined(BOOST_ASIO_ENABLE_BUFFER_DEBUGGING) , detail::buffer_debug_check< typename std::vector<PodType, Allocator>::const_iterator >(data.begin()) #endif // BOOST_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> BOOST_ASIO_NODISCARD inline BOOST_ASIO_CONST_BUFFER buffer( const std::vector<PodType, Allocator>& data, std::size_t max_size_in_bytes) noexcept { return BOOST_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(BOOST_ASIO_ENABLE_BUFFER_DEBUGGING) , detail::buffer_debug_check< typename std::vector<PodType, Allocator>::const_iterator >(data.begin()) #endif // BOOST_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> BOOST_ASIO_NODISCARD inline BOOST_ASIO_MUTABLE_BUFFER buffer( std::basic_string<Elem, Traits, Allocator>& data) noexcept { return BOOST_ASIO_MUTABLE_BUFFER(data.size() ? &data[0] : 0, data.size() * sizeof(Elem) #if defined(BOOST_ASIO_ENABLE_BUFFER_DEBUGGING) , detail::buffer_debug_check< typename std::basic_string<Elem, Traits, Allocator>::iterator >(data.begin()) #endif // BOOST_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> BOOST_ASIO_NODISCARD inline BOOST_ASIO_MUTABLE_BUFFER buffer( std::basic_string<Elem, Traits, Allocator>& data, std::size_t max_size_in_bytes) noexcept { return BOOST_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(BOOST_ASIO_ENABLE_BUFFER_DEBUGGING) , detail::buffer_debug_check< typename std::basic_string<Elem, Traits, Allocator>::iterator >(data.begin()) #endif // BOOST_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> BOOST_ASIO_NODISCARD inline BOOST_ASIO_CONST_BUFFER buffer( const std::basic_string<Elem, Traits, Allocator>& data) noexcept { return BOOST_ASIO_CONST_BUFFER(data.data(), data.size() * sizeof(Elem) #if defined(BOOST_ASIO_ENABLE_BUFFER_DEBUGGING) , detail::buffer_debug_check< typename std::basic_string<Elem, Traits, Allocator>::const_iterator >(data.begin()) #endif // BOOST_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> BOOST_ASIO_NODISCARD inline BOOST_ASIO_CONST_BUFFER buffer( const std::basic_string<Elem, Traits, Allocator>& data, std::size_t max_size_in_bytes) noexcept { return BOOST_ASIO_CONST_BUFFER(data.data(), data.size() * sizeof(Elem) < max_size_in_bytes ? data.size() * sizeof(Elem) : max_size_in_bytes #if defined(BOOST_ASIO_ENABLE_BUFFER_DEBUGGING) , detail::buffer_debug_check< typename std::basic_string<Elem, Traits, Allocator>::const_iterator >(data.begin()) #endif // BOOST_ASIO_ENABLE_BUFFER_DEBUGGING ); } #if defined(BOOST_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> BOOST_ASIO_NODISCARD inline BOOST_ASIO_CONST_BUFFER buffer( basic_string_view<Elem, Traits> data) noexcept { return BOOST_ASIO_CONST_BUFFER(data.size() ? &data[0] : 0, data.size() * sizeof(Elem) #if defined(BOOST_ASIO_ENABLE_BUFFER_DEBUGGING) , detail::buffer_debug_check< typename basic_string_view<Elem, Traits>::iterator >(data.begin()) #endif // BOOST_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> BOOST_ASIO_NODISCARD inline BOOST_ASIO_CONST_BUFFER buffer( basic_string_view<Elem, Traits> data, std::size_t max_size_in_bytes) noexcept { return BOOST_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(BOOST_ASIO_ENABLE_BUFFER_DEBUGGING) , detail::buffer_debug_check< typename basic_string_view<Elem, Traits>::iterator >(data.begin()) #endif // BOOST_ASIO_ENABLE_BUFFER_DEBUGGING ); } #endif // defined(BOOST_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> BOOST_ASIO_NODISCARD inline BOOST_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 BOOST_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> BOOST_ASIO_NODISCARD inline BOOST_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 BOOST_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> BOOST_ASIO_NODISCARD inline BOOST_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 BOOST_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> BOOST_ASIO_NODISCARD inline BOOST_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 BOOST_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> BOOST_ASIO_NODISCARD inline BOOST_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 BOOST_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> BOOST_ASIO_NODISCARD inline BOOST_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 BOOST_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 BOOST_ASIO_CONST_BUFFER const_buffers_type; /// The type used to represent a sequence of mutable buffers that refers to /// the underlying memory. typedef BOOST_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(BOOST_ASIO_NO_DYNAMIC_BUFFER_V1) size_((std::numeric_limits<std::size_t>::max)()), #endif // !defined(BOOST_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(BOOST_ASIO_NO_DYNAMIC_BUFFER_V1) size_(other.size_), #endif // !defined(BOOST_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(BOOST_ASIO_NO_DYNAMIC_BUFFER_V1) size_(other.size_), #endif // !defined(BOOST_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(BOOST_ASIO_NO_DYNAMIC_BUFFER_V1) if (size_ != (std::numeric_limits<std::size_t>::max)()) return size_; #endif // !defined(BOOST_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(BOOST_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(boost::asio::buffer(string_, size_)); } #endif // !defined(BOOST_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(boost::asio::buffer( boost::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(boost::asio::buffer( boost::asio::buffer(string_, max_size_) + pos, n)); } #if !defined(BOOST_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"); boost::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 boost::asio::buffer(boost::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(BOOST_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"); boost::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(BOOST_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(BOOST_ASIO_NO_DYNAMIC_BUFFER_V1) string_.erase(0, n); } private: std::basic_string<Elem, Traits, Allocator>& string_; #if !defined(BOOST_ASIO_NO_DYNAMIC_BUFFER_V1) std::size_t size_; #endif // !defined(BOOST_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 BOOST_ASIO_CONST_BUFFER const_buffers_type; /// The type used to represent a sequence of mutable buffers that refers to /// the underlying memory. typedef BOOST_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(BOOST_ASIO_NO_DYNAMIC_BUFFER_V1) size_((std::numeric_limits<std::size_t>::max)()), #endif // !defined(BOOST_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(BOOST_ASIO_NO_DYNAMIC_BUFFER_V1) size_(other.size_), #endif // !defined(BOOST_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(BOOST_ASIO_NO_DYNAMIC_BUFFER_V1) size_(other.size_), #endif // !defined(BOOST_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(BOOST_ASIO_NO_DYNAMIC_BUFFER_V1) if (size_ != (std::numeric_limits<std::size_t>::max)()) return size_; #endif // !defined(BOOST_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(BOOST_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(boost::asio::buffer(vector_, size_)); } #endif // !defined(BOOST_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(boost::asio::buffer( boost::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(boost::asio::buffer( boost::asio::buffer(vector_, max_size_) + pos, n)); } #if !defined(BOOST_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"); boost::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 boost::asio::buffer(boost::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(BOOST_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"); boost::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(BOOST_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(BOOST_ASIO_NO_DYNAMIC_BUFFER_V1) vector_.erase(vector_.begin(), vector_.begin() + (std::min)(size(), n)); } private: std::vector<Elem, Allocator>& vector_; #if !defined(BOOST_ASIO_NO_DYNAMIC_BUFFER_V1) std::size_t size_; #endif // !defined(BOOST_ASIO_NO_DYNAMIC_BUFFER_V1) const std::size_t max_size_; }; /** @defgroup dynamic_buffer boost::asio::dynamic_buffer * * @brief The boost::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> BOOST_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> BOOST_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> BOOST_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> BOOST_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 boost::asio::buffer_copy * * @brief The boost::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, boost::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( boost::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( boost::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, boost::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>(), boost::asio::buffer_sequence_begin(target), boost::asio::buffer_sequence_end(target), boost::asio::buffer_sequence_begin(source), boost::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>(), boost::asio::buffer_sequence_begin(target), boost::asio::buffer_sequence_end(target), boost::asio::buffer_sequence_begin(source), boost::asio::buffer_sequence_end(source), max_bytes_to_copy); } /*@}*/ } // namespace asio } // namespace boost #include <boost/asio/detail/pop_options.hpp> #include <boost/asio/detail/is_buffer_sequence.hpp> #include <boost/asio/detail/push_options.hpp> namespace boost { 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) : boost::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) : boost::asio::detail::is_buffer_sequence<T, const_buffer> #endif // defined(GENERATING_DOCUMENTATION) { }; #if !defined(BOOST_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) : boost::asio::detail::is_dynamic_buffer_v1<T> #endif // defined(GENERATING_DOCUMENTATION) { }; #endif // !defined(BOOST_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) : boost::asio::detail::is_dynamic_buffer_v2<T> #endif // defined(GENERATING_DOCUMENTATION) { }; /// Trait to determine whether a type satisfies the DynamicBuffer requirements. /** * If @c BOOST_ASIO_NO_DYNAMIC_BUFFER_V1 is not defined, determines whether the * type satisfies the DynamicBuffer_v1 requirements. Otherwise, if @c * BOOST_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(BOOST_ASIO_NO_DYNAMIC_BUFFER_V1) : boost::asio::is_dynamic_buffer_v2<T> #else // defined(BOOST_ASIO_NO_DYNAMIC_BUFFER_V1) : boost::asio::is_dynamic_buffer_v1<T> #endif // defined(BOOST_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 BOOST_ASIO_CONST_BUFFER operator ""_buf(const char* data, std::size_t n) { return BOOST_ASIO_CONST_BUFFER(data, n); } /// Literal operator for creating const_buffer objects from unbounded binary or /// hexadecimal integer literals. template <char... Chars> inline BOOST_ASIO_CONST_BUFFER operator ""_buf() { return BOOST_ASIO_CONST_BUFFER( +detail::literal<Chars...>::data, detail::literal<Chars...>::size); } } // namespace buffer_literals } // namespace asio } // namespace boost #include <boost/asio/detail/pop_options.hpp> #endif // BOOST_ASIO_BUFFER_HPP
hpp
asio
data/projects/asio/include/boost/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 BOOST_ASIO_BASIC_SERIAL_PORT_HPP #define BOOST_ASIO_BASIC_SERIAL_PORT_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <boost/asio/detail/config.hpp> #if defined(BOOST_ASIO_HAS_SERIAL_PORT) \ || defined(GENERATING_DOCUMENTATION) #include <string> #include <utility> #include <boost/asio/any_io_executor.hpp> #include <boost/asio/async_result.hpp> #include <boost/asio/detail/handler_type_requirements.hpp> #include <boost/asio/detail/io_object_impl.hpp> #include <boost/asio/detail/non_const_lvalue.hpp> #include <boost/asio/detail/throw_error.hpp> #include <boost/asio/detail/type_traits.hpp> #include <boost/asio/error.hpp> #include <boost/asio/execution_context.hpp> #include <boost/asio/serial_port_base.hpp> #if defined(BOOST_ASIO_HAS_IOCP) # include <boost/asio/detail/win_iocp_serial_port_service.hpp> #else # include <boost/asio/detail/posix_serial_port_service.hpp> #endif #include <boost/asio/detail/push_options.hpp> namespace boost { 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(BOOST_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) { boost::system::error_code ec; impl_.get_service().open(impl_.get_implementation(), device, ec); boost::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) { boost::system::error_code ec; impl_.get_service().open(impl_.get_implementation(), device, ec); boost::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) { boost::system::error_code ec; impl_.get_service().open(impl_.get_implementation(), device, ec); boost::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) { boost::system::error_code ec; impl_.get_service().open(impl_.get_implementation(), device, ec); boost::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 boost::system::system_error Thrown on failure. */ basic_serial_port(const executor_type& ex, const native_handle_type& native_serial_port) : impl_(0, ex) { boost::system::error_code ec; impl_.get_service().assign(impl_.get_implementation(), native_serial_port, ec); boost::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 boost::system::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) { boost::system::error_code ec; impl_.get_service().assign(impl_.get_implementation(), native_serial_port, ec); boost::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 boost::system::system_error Thrown on failure. */ void open(const std::string& device) { boost::system::error_code ec; impl_.get_service().open(impl_.get_implementation(), device, ec); boost::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. */ BOOST_ASIO_SYNC_OP_VOID open(const std::string& device, boost::system::error_code& ec) { impl_.get_service().open(impl_.get_implementation(), device, ec); BOOST_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 boost::system::system_error Thrown on failure. */ void assign(const native_handle_type& native_serial_port) { boost::system::error_code ec; impl_.get_service().assign(impl_.get_implementation(), native_serial_port, ec); boost::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. */ BOOST_ASIO_SYNC_OP_VOID assign(const native_handle_type& native_serial_port, boost::system::error_code& ec) { impl_.get_service().assign(impl_.get_implementation(), native_serial_port, ec); BOOST_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 * boost::asio::error::operation_aborted error. * * @throws boost::system::system_error Thrown on failure. */ void close() { boost::system::error_code ec; impl_.get_service().close(impl_.get_implementation(), ec); boost::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 * boost::asio::error::operation_aborted error. * * @param ec Set to indicate what error occurred, if any. */ BOOST_ASIO_SYNC_OP_VOID close(boost::system::error_code& ec) { impl_.get_service().close(impl_.get_implementation(), ec); BOOST_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 boost::asio::error::operation_aborted error. * * @throws boost::system::system_error Thrown on failure. */ void cancel() { boost::system::error_code ec; impl_.get_service().cancel(impl_.get_implementation(), ec); boost::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 boost::asio::error::operation_aborted error. * * @param ec Set to indicate what error occurred, if any. */ BOOST_ASIO_SYNC_OP_VOID cancel(boost::system::error_code& ec) { impl_.get_service().cancel(impl_.get_implementation(), ec); BOOST_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 boost::system::system_error Thrown on failure. */ void send_break() { boost::system::error_code ec; impl_.get_service().send_break(impl_.get_implementation(), ec); boost::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. */ BOOST_ASIO_SYNC_OP_VOID send_break(boost::system::error_code& ec) { impl_.get_service().send_break(impl_.get_implementation(), ec); BOOST_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 boost::system::system_error Thrown on failure. * * @sa SettableSerialPortOption @n * boost::asio::serial_port_base::baud_rate @n * boost::asio::serial_port_base::flow_control @n * boost::asio::serial_port_base::parity @n * boost::asio::serial_port_base::stop_bits @n * boost::asio::serial_port_base::character_size */ template <typename SettableSerialPortOption> void set_option(const SettableSerialPortOption& option) { boost::system::error_code ec; impl_.get_service().set_option(impl_.get_implementation(), option, ec); boost::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 * boost::asio::serial_port_base::baud_rate @n * boost::asio::serial_port_base::flow_control @n * boost::asio::serial_port_base::parity @n * boost::asio::serial_port_base::stop_bits @n * boost::asio::serial_port_base::character_size */ template <typename SettableSerialPortOption> BOOST_ASIO_SYNC_OP_VOID set_option(const SettableSerialPortOption& option, boost::system::error_code& ec) { impl_.get_service().set_option(impl_.get_implementation(), option, ec); BOOST_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 boost::system::system_error Thrown on failure. * * @sa GettableSerialPortOption @n * boost::asio::serial_port_base::baud_rate @n * boost::asio::serial_port_base::flow_control @n * boost::asio::serial_port_base::parity @n * boost::asio::serial_port_base::stop_bits @n * boost::asio::serial_port_base::character_size */ template <typename GettableSerialPortOption> void get_option(GettableSerialPortOption& option) const { boost::system::error_code ec; impl_.get_service().get_option(impl_.get_implementation(), option, ec); boost::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 * boost::asio::serial_port_base::baud_rate @n * boost::asio::serial_port_base::flow_control @n * boost::asio::serial_port_base::parity @n * boost::asio::serial_port_base::stop_bits @n * boost::asio::serial_port_base::character_size */ template <typename GettableSerialPortOption> BOOST_ASIO_SYNC_OP_VOID get_option(GettableSerialPortOption& option, boost::system::error_code& ec) const { impl_.get_service().get_option(impl_.get_implementation(), option, ec); BOOST_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 boost::system::system_error Thrown on failure. An error code of * boost::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(boost::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) { boost::system::error_code ec; std::size_t s = impl_.get_service().write_some( impl_.get_implementation(), buffers, ec); boost::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, boost::system::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 boost::system::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 boost::asio::post(). * * @par Completion Signature * @code void(boost::system::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( * boost::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 boost::asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * @li @c cancellation_type::total */ template <typename ConstBufferSequence, BOOST_ASIO_COMPLETION_TOKEN_FOR(void (boost::system::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 (boost::system::error_code, std::size_t)>( declval<initiate_async_write_some>(), token, buffers)) { return async_initiate<WriteToken, void (boost::system::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 boost::system::system_error Thrown on failure. An error code of * boost::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(boost::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) { boost::system::error_code ec; std::size_t s = impl_.get_service().read_some( impl_.get_implementation(), buffers, ec); boost::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, boost::system::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 boost::system::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 boost::asio::post(). * * @par Completion Signature * @code void(boost::system::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( * boost::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 boost::asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * @li @c cancellation_type::total */ template <typename MutableBufferSequence, BOOST_ASIO_COMPLETION_TOKEN_FOR(void (boost::system::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 (boost::system::error_code, std::size_t)>( declval<initiate_async_read_some>(), token, buffers)) { return async_initiate<ReadToken, void (boost::system::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. BOOST_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. BOOST_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(BOOST_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 } // namespace boost #include <boost/asio/detail/pop_options.hpp> #endif // defined(BOOST_ASIO_HAS_SERIAL_PORT) // || defined(GENERATING_DOCUMENTATION) #endif // BOOST_ASIO_BASIC_SERIAL_PORT_HPP
hpp
asio
data/projects/asio/include/boost/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 BOOST_ASIO_USE_AWAITABLE_HPP #define BOOST_ASIO_USE_AWAITABLE_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <boost/asio/detail/config.hpp> #if defined(BOOST_ASIO_HAS_CO_AWAIT) || defined(GENERATING_DOCUMENTATION) #include <boost/asio/awaitable.hpp> #include <boost/asio/detail/handler_tracking.hpp> #if defined(BOOST_ASIO_ENABLE_HANDLER_TRACKING) # if defined(BOOST_ASIO_HAS_SOURCE_LOCATION) # include <boost/asio/detail/source_location.hpp> # endif // defined(BOOST_ASIO_HAS_SOURCE_LOCATION) #endif // defined(BOOST_ASIO_ENABLE_HANDLER_TRACKING) #include <boost/asio/detail/push_options.hpp> namespace boost { 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(BOOST_ASIO_ENABLE_HANDLER_TRACKING) # if defined(BOOST_ASIO_HAS_SOURCE_LOCATION) detail::source_location location = detail::source_location::current() # endif // defined(BOOST_ASIO_HAS_SOURCE_LOCATION) #endif // defined(BOOST_ASIO_ENABLE_HANDLER_TRACKING) ) #if defined(BOOST_ASIO_ENABLE_HANDLER_TRACKING) # if defined(BOOST_ASIO_HAS_SOURCE_LOCATION) : file_name_(location.file_name()), line_(location.line()), function_name_(location.function_name()) # else // defined(BOOST_ASIO_HAS_SOURCE_LOCATION) : file_name_(0), line_(0), function_name_(0) # endif // defined(BOOST_ASIO_HAS_SOURCE_LOCATION) #endif // defined(BOOST_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(BOOST_ASIO_ENABLE_HANDLER_TRACKING) : file_name_(file_name), line_(line), function_name_(function_name) #endif // defined(BOOST_ASIO_ENABLE_HANDLER_TRACKING) { #if !defined(BOOST_ASIO_ENABLE_HANDLER_TRACKING) (void)file_name; (void)line; (void)function_name; #endif // !defined(BOOST_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(BOOST_ASIO_ENABLE_HANDLER_TRACKING) const char* file_name_; int line_; const char* function_name_; #endif // defined(BOOST_ASIO_ENABLE_HANDLER_TRACKING) }; /// A @ref completion_token object that represents the currently executing /// coroutine. /** * See the documentation for boost::asio::use_awaitable_t for a usage example. */ #if defined(GENERATING_DOCUMENTATION) constexpr use_awaitable_t<> use_awaitable; #else constexpr use_awaitable_t<> use_awaitable(0, 0, 0); #endif } // namespace asio } // namespace boost #include <boost/asio/detail/pop_options.hpp> #include <boost/asio/impl/use_awaitable.hpp> #endif // defined(BOOST_ASIO_HAS_CO_AWAIT) || defined(GENERATING_DOCUMENTATION) #endif // BOOST_ASIO_USE_AWAITABLE_HPP
hpp
asio
data/projects/asio/include/boost/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 BOOST_ASIO_RANDOM_ACCESS_FILE_HPP #define BOOST_ASIO_RANDOM_ACCESS_FILE_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <boost/asio/detail/config.hpp> #if defined(BOOST_ASIO_HAS_FILE) \ || defined(GENERATING_DOCUMENTATION) #include <boost/asio/basic_random_access_file.hpp> namespace boost { namespace asio { /// Typedef for the typical usage of a random-access file. typedef basic_random_access_file<> random_access_file; } // namespace asio } // namespace boost #endif // defined(BOOST_ASIO_HAS_FILE) // || defined(GENERATING_DOCUMENTATION) #endif // BOOST_ASIO_RANDOM_ACCESS_FILE_HPP
hpp
asio
data/projects/asio/include/boost/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 BOOST_ASIO_SYSTEM_TIMER_HPP #define BOOST_ASIO_SYSTEM_TIMER_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <boost/asio/detail/config.hpp> #include <boost/asio/basic_waitable_timer.hpp> #include <boost/asio/detail/chrono.hpp> namespace boost { 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 } // namespace boost #endif // BOOST_ASIO_SYSTEM_TIMER_HPP
hpp
asio
data/projects/asio/include/boost/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 BOOST_ASIO_PREFER_HPP #define BOOST_ASIO_PREFER_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <boost/asio/detail/config.hpp> #include <boost/asio/detail/type_traits.hpp> #include <boost/asio/is_applicable_property.hpp> #include <boost/asio/traits/prefer_free.hpp> #include <boost/asio/traits/prefer_member.hpp> #include <boost/asio/traits/require_free.hpp> #include <boost/asio/traits/require_member.hpp> #include <boost/asio/traits/static_require.hpp> #include <boost/asio/detail/push_options.hpp> #if defined(GENERATING_DOCUMENTATION) namespace boost { 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>boost::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>boost::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>boost::asio::prefer(boost::asio::prefer(E, P0), Pn...)</tt> * if <tt>N > 0</tt> and the expression * <tt>boost::asio::prefer(boost::asio::prefer(E, P0), Pn...)</tt> * is a valid expression. * * @li Otherwise, <tt>boost::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>boost::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>boost::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>boost::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 } // namespace boost #else // defined(GENERATING_DOCUMENTATION) namespace boost_asio_prefer_fn { using boost::asio::conditional_t; using boost::asio::decay_t; using boost::asio::declval; using boost::asio::enable_if_t; using boost::asio::is_applicable_property; using boost::asio::traits::prefer_free; using boost::asio::traits::prefer_member; using boost::asio::traits::require_free; using boost::asio::traits::require_member; using boost::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(BOOST_ASIO_HAS_DEDUCED_REQUIRE_MEMBER_TRAIT) \ && defined(BOOST_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(BOOST_ASIO_HAS_DEDUCED_REQUIRE_MEMBER_TRAIT) // && defined(BOOST_ASIO_HAS_DEDUCED_PREFER_MEMBER_TRAIT) typedef T type; #endif // defined(BOOST_ASIO_HAS_DEDUCED_REQUIRE_MEMBER_TRAIT) // && defined(BOOST_ASIO_HAS_DEDUCED_PREFER_MEMBER_TRAIT) }; template <typename T, typename Property> BOOST_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> BOOST_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> BOOST_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> BOOST_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> BOOST_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> BOOST_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> BOOST_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 boost_asio_prefer_fn namespace boost { namespace asio { namespace { static constexpr const boost_asio_prefer_fn::impl& prefer = boost_asio_prefer_fn::static_instance<>::instance; } // namespace typedef boost_asio_prefer_fn::impl prefer_t; template <typename T, typename... Properties> struct can_prefer : integral_constant<bool, boost_asio_prefer_fn::call_traits< prefer_t, T, void(Properties...)>::overload != boost_asio_prefer_fn::ill_formed> { }; #if defined(BOOST_ASIO_HAS_VARIABLE_TEMPLATES) template <typename T, typename... Properties> constexpr bool can_prefer_v = can_prefer<T, Properties...>::value; #endif // defined(BOOST_ASIO_HAS_VARIABLE_TEMPLATES) template <typename T, typename... Properties> struct is_nothrow_prefer : integral_constant<bool, boost_asio_prefer_fn::call_traits< prefer_t, T, void(Properties...)>::is_noexcept> { }; #if defined(BOOST_ASIO_HAS_VARIABLE_TEMPLATES) template <typename T, typename... Properties> constexpr bool is_nothrow_prefer_v = is_nothrow_prefer<T, Properties...>::value; #endif // defined(BOOST_ASIO_HAS_VARIABLE_TEMPLATES) template <typename T, typename... Properties> struct prefer_result { typedef typename boost_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 } // namespace boost #endif // defined(GENERATING_DOCUMENTATION) #include <boost/asio/detail/pop_options.hpp> #endif // BOOST_ASIO_PREFER_HPP
hpp
asio
data/projects/asio/include/boost/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 BOOST_ASIO_TIME_TRAITS_HPP #define BOOST_ASIO_TIME_TRAITS_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <boost/asio/detail/socket_types.hpp> // Must come before posix_time. #if defined(BOOST_ASIO_HAS_BOOST_DATE_TIME) \ || defined(GENERATING_DOCUMENTATION) #include <boost/date_time/posix_time/posix_time_types.hpp> #include <boost/asio/detail/push_options.hpp> namespace boost { 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 } // namespace boost #include <boost/asio/detail/pop_options.hpp> #endif // defined(BOOST_ASIO_HAS_BOOST_DATE_TIME) // || defined(GENERATING_DOCUMENTATION) #endif // BOOST_ASIO_TIME_TRAITS_HPP
hpp
asio
data/projects/asio/include/boost/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 BOOST_ASIO_ASSOCIATOR_HPP #define BOOST_ASIO_ASSOCIATOR_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <boost/asio/detail/config.hpp> #include <boost/asio/detail/push_options.hpp> namespace boost { namespace asio { /// Used to generically specialise associators for a type. template <template <typename, typename> class Associator, typename T, typename DefaultCandidate> struct associator { }; } // namespace asio } // namespace boost #include <boost/asio/detail/pop_options.hpp> #endif // BOOST_ASIO_ASSOCIATOR_HPP
hpp
asio
data/projects/asio/include/boost/asio/buffered_read_stream_fwd.hpp
// // buffered_read_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 BOOST_ASIO_BUFFERED_READ_STREAM_FWD_HPP #define BOOST_ASIO_BUFFERED_READ_STREAM_FWD_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) namespace boost { namespace asio { template <typename Stream> class buffered_read_stream; } // namespace asio } // namespace boost #endif // BOOST_ASIO_BUFFERED_READ_STREAM_FWD_HPP
hpp
asio
data/projects/asio/include/boost/asio/basic_socket_iostream.hpp
// // basic_socket_iostream.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 BOOST_ASIO_BASIC_SOCKET_IOSTREAM_HPP #define BOOST_ASIO_BASIC_SOCKET_IOSTREAM_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <boost/asio/detail/config.hpp> #if !defined(BOOST_ASIO_NO_IOSTREAM) #include <istream> #include <ostream> #include <boost/asio/basic_socket_streambuf.hpp> #include <boost/asio/detail/push_options.hpp> namespace boost { namespace asio { namespace detail { // A separate base class is used to ensure that the streambuf is initialised // prior to the basic_socket_iostream's basic_iostream base class. template <typename Protocol, typename Clock, typename WaitTraits> class socket_iostream_base { protected: socket_iostream_base() { } socket_iostream_base(socket_iostream_base&& other) : streambuf_(std::move(other.streambuf_)) { } socket_iostream_base(basic_stream_socket<Protocol> s) : streambuf_(std::move(s)) { } socket_iostream_base& operator=(socket_iostream_base&& other) { streambuf_ = std::move(other.streambuf_); return *this; } basic_socket_streambuf<Protocol, Clock, WaitTraits> streambuf_; }; } // namespace detail #if !defined(BOOST_ASIO_BASIC_SOCKET_IOSTREAM_FWD_DECL) #define BOOST_ASIO_BASIC_SOCKET_IOSTREAM_FWD_DECL // Forward declaration with defaulted arguments. template <typename Protocol, #if defined(BOOST_ASIO_HAS_BOOST_DATE_TIME) \ && defined(BOOST_ASIO_USE_BOOST_DATE_TIME_FOR_SOCKET_IOSTREAM) typename Clock = boost::posix_time::ptime, typename WaitTraits = time_traits<Clock>> #else // defined(BOOST_ASIO_HAS_BOOST_DATE_TIME) // && defined(BOOST_ASIO_USE_BOOST_DATE_TIME_FOR_SOCKET_IOSTREAM) typename Clock = chrono::steady_clock, typename WaitTraits = wait_traits<Clock>> #endif // defined(BOOST_ASIO_HAS_BOOST_DATE_TIME) // && defined(BOOST_ASIO_USE_BOOST_DATE_TIME_FOR_SOCKET_IOSTREAM) class basic_socket_iostream; #endif // !defined(BOOST_ASIO_BASIC_SOCKET_IOSTREAM_FWD_DECL) /// Iostream interface for a socket. #if defined(GENERATING_DOCUMENTATION) template <typename Protocol, typename Clock = chrono::steady_clock, typename WaitTraits = wait_traits<Clock>> #else // defined(GENERATING_DOCUMENTATION) template <typename Protocol, typename Clock, typename WaitTraits> #endif // defined(GENERATING_DOCUMENTATION) class basic_socket_iostream : private detail::socket_iostream_base<Protocol, Clock, WaitTraits>, public std::basic_iostream<char> { private: // These typedefs are intended keep this class's implementation independent // of whether it's using Boost.DateClock, Boost.Chrono or std::chrono. #if defined(BOOST_ASIO_HAS_BOOST_DATE_TIME) \ && defined(BOOST_ASIO_USE_BOOST_DATE_TIME_FOR_SOCKET_IOSTREAM) typedef WaitTraits traits_helper; #else // defined(BOOST_ASIO_HAS_BOOST_DATE_TIME) // && defined(BOOST_ASIO_USE_BOOST_DATE_TIME_FOR_SOCKET_IOSTREAM) typedef detail::chrono_time_traits<Clock, WaitTraits> traits_helper; #endif // defined(BOOST_ASIO_HAS_BOOST_DATE_TIME) // && defined(BOOST_ASIO_USE_BOOST_DATE_TIME_FOR_SOCKET_IOSTREAM) public: /// The protocol type. typedef Protocol protocol_type; /// The endpoint type. typedef typename Protocol::endpoint endpoint_type; /// The clock type. typedef Clock clock_type; #if defined(GENERATING_DOCUMENTATION) /// (Deprecated: Use time_point.) The time type. typedef typename WaitTraits::time_type time_type; /// The time type. typedef typename WaitTraits::time_point time_point; /// (Deprecated: Use duration.) The duration type. typedef typename WaitTraits::duration_type duration_type; /// The duration type. typedef typename WaitTraits::duration duration; #else # if !defined(BOOST_ASIO_NO_DEPRECATED) typedef typename traits_helper::time_type time_type; typedef typename traits_helper::duration_type duration_type; # endif // !defined(BOOST_ASIO_NO_DEPRECATED) typedef typename traits_helper::time_type time_point; typedef typename traits_helper::duration_type duration; #endif /// Construct a basic_socket_iostream without establishing a connection. basic_socket_iostream() : std::basic_iostream<char>( &this->detail::socket_iostream_base< Protocol, Clock, WaitTraits>::streambuf_) { this->setf(std::ios_base::unitbuf); } /// Construct a basic_socket_iostream from the supplied socket. explicit basic_socket_iostream(basic_stream_socket<protocol_type> s) : detail::socket_iostream_base< Protocol, Clock, WaitTraits>(std::move(s)), std::basic_iostream<char>( &this->detail::socket_iostream_base< Protocol, Clock, WaitTraits>::streambuf_) { this->setf(std::ios_base::unitbuf); } /// Move-construct a basic_socket_iostream from another. basic_socket_iostream(basic_socket_iostream&& other) : detail::socket_iostream_base< Protocol, Clock, WaitTraits>(std::move(other)), std::basic_iostream<char>(std::move(other)) { this->set_rdbuf(&this->detail::socket_iostream_base< Protocol, Clock, WaitTraits>::streambuf_); } /// Move-assign a basic_socket_iostream from another. basic_socket_iostream& operator=(basic_socket_iostream&& other) { std::basic_iostream<char>::operator=(std::move(other)); detail::socket_iostream_base< Protocol, Clock, WaitTraits>::operator=(std::move(other)); return *this; } /// Establish a connection to an endpoint corresponding to a resolver query. /** * This constructor automatically establishes a connection based on the * supplied resolver query parameters. The arguments are used to construct * a resolver query object. */ template <typename... T> explicit basic_socket_iostream(T... x) : std::basic_iostream<char>( &this->detail::socket_iostream_base< Protocol, Clock, WaitTraits>::streambuf_) { this->setf(std::ios_base::unitbuf); if (rdbuf()->connect(x...) == 0) this->setstate(std::ios_base::failbit); } /// Establish a connection to an endpoint corresponding to a resolver query. /** * This function automatically establishes a connection based on the supplied * resolver query parameters. The arguments are used to construct a resolver * query object. */ template <typename... T> void connect(T... x) { if (rdbuf()->connect(x...) == 0) this->setstate(std::ios_base::failbit); } /// Close the connection. void close() { if (rdbuf()->close() == 0) this->setstate(std::ios_base::failbit); } /// Return a pointer to the underlying streambuf. basic_socket_streambuf<Protocol, Clock, WaitTraits>* rdbuf() const { return const_cast<basic_socket_streambuf<Protocol, Clock, WaitTraits>*>( &this->detail::socket_iostream_base< Protocol, Clock, WaitTraits>::streambuf_); } /// Get a reference to the underlying socket. basic_socket<Protocol>& socket() { return rdbuf()->socket(); } /// Get the last error associated with the stream. /** * @return An \c error_code corresponding to the last error from the stream. * * @par Example * To print the error associated with a failure to establish a connection: * @code tcp::iostream s("www.boost.org", "http"); * if (!s) * { * std::cout << "Error: " << s.error().message() << std::endl; * } @endcode */ const boost::system::error_code& error() const { return rdbuf()->error(); } #if !defined(BOOST_ASIO_NO_DEPRECATED) /// (Deprecated: Use expiry().) Get the stream's expiry time as an absolute /// time. /** * @return An absolute time value representing the stream's expiry time. */ time_point expires_at() const { return rdbuf()->expires_at(); } #endif // !defined(BOOST_ASIO_NO_DEPRECATED) /// Get the stream's expiry time as an absolute time. /** * @return An absolute time value representing the stream's expiry time. */ time_point expiry() const { return rdbuf()->expiry(); } /// Set the stream's expiry time as an absolute time. /** * This function sets the expiry time associated with the stream. Stream * operations performed after this time (where the operations cannot be * completed using the internal buffers) will fail with the error * boost::asio::error::operation_aborted. * * @param expiry_time The expiry time to be used for the stream. */ void expires_at(const time_point& expiry_time) { rdbuf()->expires_at(expiry_time); } /// Set the stream's expiry time relative to now. /** * This function sets the expiry time associated with the stream. Stream * operations performed after this time (where the operations cannot be * completed using the internal buffers) will fail with the error * boost::asio::error::operation_aborted. * * @param expiry_time The expiry time to be used for the timer. */ void expires_after(const duration& expiry_time) { rdbuf()->expires_after(expiry_time); } #if !defined(BOOST_ASIO_NO_DEPRECATED) /// (Deprecated: Use expiry().) Get the stream's expiry time relative to now. /** * @return A relative time value representing the stream's expiry time. */ duration expires_from_now() const { return rdbuf()->expires_from_now(); } /// (Deprecated: Use expires_after().) Set the stream's expiry time relative /// to now. /** * This function sets the expiry time associated with the stream. Stream * operations performed after this time (where the operations cannot be * completed using the internal buffers) will fail with the error * boost::asio::error::operation_aborted. * * @param expiry_time The expiry time to be used for the timer. */ void expires_from_now(const duration& expiry_time) { rdbuf()->expires_from_now(expiry_time); } #endif // !defined(BOOST_ASIO_NO_DEPRECATED) private: // Disallow copying and assignment. basic_socket_iostream(const basic_socket_iostream&) = delete; basic_socket_iostream& operator=( const basic_socket_iostream&) = delete; }; } // namespace asio } // namespace boost #include <boost/asio/detail/pop_options.hpp> #endif // !defined(BOOST_ASIO_NO_IOSTREAM) #endif // BOOST_ASIO_BASIC_SOCKET_IOSTREAM_HPP
hpp
asio
data/projects/asio/include/boost/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 BOOST_ASIO_QUERY_HPP #define BOOST_ASIO_QUERY_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <boost/asio/detail/config.hpp> #include <boost/asio/detail/type_traits.hpp> #include <boost/asio/is_applicable_property.hpp> #include <boost/asio/traits/query_member.hpp> #include <boost/asio/traits/query_free.hpp> #include <boost/asio/traits/static_query.hpp> #include <boost/asio/detail/push_options.hpp> #if defined(GENERATING_DOCUMENTATION) namespace boost { 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>boost::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>boost::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>boost::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>boost::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>boost::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>boost::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 } // namespace boost #else // defined(GENERATING_DOCUMENTATION) namespace boost_asio_query_fn { using boost::asio::conditional_t; using boost::asio::decay_t; using boost::asio::declval; using boost::asio::enable_if_t; using boost::asio::is_applicable_property; using boost::asio::traits::query_free; using boost::asio::traits::query_member; using boost::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(BOOST_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(BOOST_ASIO_HAS_DEDUCED_QUERY_MEMBER_TRAIT) typedef T type; #endif // defined(BOOST_ASIO_HAS_DEDUCED_QUERY_MEMBER_TRAIT) }; template <typename T, typename Property> BOOST_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> BOOST_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> BOOST_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 boost_asio_query_fn namespace boost { namespace asio { namespace { static constexpr const boost_asio_query_fn::impl& query = boost_asio_query_fn::static_instance<>::instance; } // namespace typedef boost_asio_query_fn::impl query_t; template <typename T, typename Property> struct can_query : integral_constant<bool, boost_asio_query_fn::call_traits<query_t, T, void(Property)>::overload != boost_asio_query_fn::ill_formed> { }; #if defined(BOOST_ASIO_HAS_VARIABLE_TEMPLATES) template <typename T, typename Property> constexpr bool can_query_v = can_query<T, Property>::value; #endif // defined(BOOST_ASIO_HAS_VARIABLE_TEMPLATES) template <typename T, typename Property> struct is_nothrow_query : integral_constant<bool, boost_asio_query_fn::call_traits<query_t, T, void(Property)>::is_noexcept> { }; #if defined(BOOST_ASIO_HAS_VARIABLE_TEMPLATES) template <typename T, typename Property> constexpr bool is_nothrow_query_v = is_nothrow_query<T, Property>::value; #endif // defined(BOOST_ASIO_HAS_VARIABLE_TEMPLATES) template <typename T, typename Property> struct query_result { typedef typename boost_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 } // namespace boost #endif // defined(GENERATING_DOCUMENTATION) #include <boost/asio/detail/pop_options.hpp> #endif // BOOST_ASIO_QUERY_HPP
hpp
asio
data/projects/asio/include/boost/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 BOOST_ASIO_SIGNAL_SET_HPP #define BOOST_ASIO_SIGNAL_SET_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <boost/asio/detail/config.hpp> #include <boost/asio/basic_signal_set.hpp> namespace boost { namespace asio { /// Typedef for the typical usage of a signal set. typedef basic_signal_set<> signal_set; } // namespace asio } // namespace boost #endif // BOOST_ASIO_SIGNAL_SET_HPP
hpp
asio
data/projects/asio/include/boost/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 BOOST_ASIO_THREAD_POOL_HPP #define BOOST_ASIO_THREAD_POOL_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <boost/asio/detail/config.hpp> #include <boost/asio/detail/atomic_count.hpp> #include <boost/asio/detail/scheduler.hpp> #include <boost/asio/detail/thread_group.hpp> #include <boost/asio/execution.hpp> #include <boost/asio/execution_context.hpp> #include <boost/asio/detail/push_options.hpp> namespace boost { 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 boost::asio::dispatch, * @ref boost::asio::post or @ref boost::asio::defer free functions. * * For example: * * @code void my_task() * { * ... * } * * ... * * // Launch the pool with four threads. * boost::asio::thread_pool pool(4); * * // Submit a function to the pool. * boost::asio::post(pool, my_task); * * // Submit a lambda object to the pool. * boost::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(BOOST_ASIO_NO_TS_EXECUTORS) /// Constructs a pool with an automatically determined number of threads. BOOST_ASIO_DECL thread_pool(); #endif // !defined(BOOST_ASIO_NO_TS_EXECUTORS) /// Constructs a pool with a specified number of threads. BOOST_ASIO_DECL thread_pool(std::size_t num_threads); /// Destructor. /** * Automatically stops and joins the pool, if not explicitly done beforehand. */ BOOST_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. */ BOOST_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. */ BOOST_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. */ BOOST_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. */ BOOST_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. BOOST_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 boost_asio_require_fn::impl; friend struct boost_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 * boost::asio::require customisation point. * * For example: * @code auto ex1 = my_thread_pool.executor(); * auto ex2 = boost::asio::require(ex1, * boost::asio::execution::blocking.possibly); @endcode */ constexpr basic_executor_type<Allocator, BOOST_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 * boost::asio::require customisation point. * * For example: * @code auto ex1 = my_thread_pool.executor(); * auto ex2 = boost::asio::require(ex1, * boost::asio::execution::blocking.always); @endcode */ constexpr basic_executor_type<Allocator, BOOST_ASIO_UNSPECIFIED((Bits & ~blocking_mask) | blocking_always)> require(execution::blocking_t::always_t) const { return basic_executor_type<Allocator, BOOST_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 * boost::asio::require customisation point. * * For example: * @code auto ex1 = my_thread_pool.executor(); * auto ex2 = boost::asio::require(ex1, * boost::asio::execution::blocking.never); @endcode */ constexpr basic_executor_type<Allocator, BOOST_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 * boost::asio::require customisation point. * * For example: * @code auto ex1 = my_thread_pool.executor(); * auto ex2 = boost::asio::require(ex1, * boost::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 * boost::asio::require customisation point. * * For example: * @code auto ex1 = my_thread_pool.executor(); * auto ex2 = boost::asio::require(ex1, * boost::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 * boost::asio::require customisation point. * * For example: * @code auto ex1 = my_thread_pool.executor(); * auto ex2 = boost::asio::require(ex1, * boost::asio::execution::outstanding_work.tracked); @endcode */ constexpr basic_executor_type<Allocator, BOOST_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 * boost::asio::require customisation point. * * For example: * @code auto ex1 = my_thread_pool.executor(); * auto ex2 = boost::asio::require(ex1, * boost::asio::execution::outstanding_work.untracked); @endcode */ constexpr basic_executor_type<Allocator, BOOST_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 * boost::asio::require customisation point. * * For example: * @code auto ex1 = my_thread_pool.executor(); * auto ex2 = boost::asio::require(ex1, * boost::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 * boost::asio::require customisation point. * * For example: * @code auto ex1 = my_thread_pool.executor(); * auto ex2 = boost::asio::require(ex1, * boost::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 boost_asio_query_fn::impl; friend struct boost::asio::execution::detail::mapping_t<0>; friend struct boost::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 * boost::asio::query customisation point. * * For example: * @code auto ex = my_thread_pool.executor(); * if (boost::asio::query(ex, boost::asio::execution::mapping) * == boost::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 * boost::asio::query customisation point. * * For example: * @code auto ex = my_thread_pool.executor(); * boost::asio::thread_pool& pool = boost::asio::query( * ex, boost::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 * boost::asio::query customisation point. * * For example: * @code auto ex = my_thread_pool.executor(); * if (boost::asio::query(ex, boost::asio::execution::blocking) * == boost::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 * boost::asio::query customisation point. * * For example: * @code auto ex = my_thread_pool.executor(); * if (boost::asio::query(ex, boost::asio::execution::relationship) * == boost::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 * boost::asio::query customisation point. * * For example: * @code auto ex = my_thread_pool.executor(); * if (boost::asio::query(ex, boost::asio::execution::outstanding_work) * == boost::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 * boost::asio::query customisation point. * * For example: * @code auto ex = my_thread_pool.executor(); * auto alloc = boost::asio::query(ex, * boost::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 * boost::asio::query customisation point. * * For example: * @code auto ex = my_thread_pool.executor(); * auto alloc = boost::asio::query(ex, * boost::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 * boost::asio::query customisation point. * * For example: * @code auto ex = my_thread_pool.executor(); * std::size_t occupancy = boost::asio::query( * ex, boost::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(BOOST_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(BOOST_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(BOOST_ASIO_HAS_DEDUCED_EQUALITY_COMPARABLE_TRAIT) template <typename Allocator, unsigned int Bits> struct equality_comparable< boost::asio::thread_pool::basic_executor_type<Allocator, Bits> > { static constexpr bool is_valid = true; static constexpr bool is_noexcept = true; }; #endif // !defined(BOOST_ASIO_HAS_DEDUCED_EQUALITY_COMPARABLE_TRAIT) #if !defined(BOOST_ASIO_HAS_DEDUCED_EXECUTE_MEMBER_TRAIT) template <typename Allocator, unsigned int Bits, typename Function> struct execute_member< boost::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(BOOST_ASIO_HAS_DEDUCED_EXECUTE_MEMBER_TRAIT) #if !defined(BOOST_ASIO_HAS_DEDUCED_REQUIRE_MEMBER_TRAIT) template <typename Allocator, unsigned int Bits> struct require_member< boost::asio::thread_pool::basic_executor_type<Allocator, Bits>, boost::asio::execution::blocking_t::possibly_t > : boost::asio::detail::thread_pool_bits { static constexpr bool is_valid = true; static constexpr bool is_noexcept = true; typedef boost::asio::thread_pool::basic_executor_type< Allocator, Bits & ~blocking_mask> result_type; }; template <typename Allocator, unsigned int Bits> struct require_member< boost::asio::thread_pool::basic_executor_type<Allocator, Bits>, boost::asio::execution::blocking_t::always_t > : boost::asio::detail::thread_pool_bits { static constexpr bool is_valid = true; static constexpr bool is_noexcept = false; typedef boost::asio::thread_pool::basic_executor_type<Allocator, (Bits & ~blocking_mask) | blocking_always> result_type; }; template <typename Allocator, unsigned int Bits> struct require_member< boost::asio::thread_pool::basic_executor_type<Allocator, Bits>, boost::asio::execution::blocking_t::never_t > : boost::asio::detail::thread_pool_bits { static constexpr bool is_valid = true; static constexpr bool is_noexcept = false; typedef boost::asio::thread_pool::basic_executor_type< Allocator, Bits & ~blocking_mask> result_type; }; template <typename Allocator, unsigned int Bits> struct require_member< boost::asio::thread_pool::basic_executor_type<Allocator, Bits>, boost::asio::execution::relationship_t::fork_t > { static constexpr bool is_valid = true; static constexpr bool is_noexcept = false; typedef boost::asio::thread_pool::basic_executor_type< Allocator, Bits> result_type; }; template <typename Allocator, unsigned int Bits> struct require_member< boost::asio::thread_pool::basic_executor_type<Allocator, Bits>, boost::asio::execution::relationship_t::continuation_t > { static constexpr bool is_valid = true; static constexpr bool is_noexcept = false; typedef boost::asio::thread_pool::basic_executor_type< Allocator, Bits> result_type; }; template <typename Allocator, unsigned int Bits> struct require_member< boost::asio::thread_pool::basic_executor_type<Allocator, Bits>, boost::asio::execution::outstanding_work_t::tracked_t > : boost::asio::detail::thread_pool_bits { static constexpr bool is_valid = true; static constexpr bool is_noexcept = false; typedef boost::asio::thread_pool::basic_executor_type< Allocator, Bits | outstanding_work_tracked> result_type; }; template <typename Allocator, unsigned int Bits> struct require_member< boost::asio::thread_pool::basic_executor_type<Allocator, Bits>, boost::asio::execution::outstanding_work_t::untracked_t > : boost::asio::detail::thread_pool_bits { static constexpr bool is_valid = true; static constexpr bool is_noexcept = false; typedef boost::asio::thread_pool::basic_executor_type< Allocator, Bits & ~outstanding_work_tracked> result_type; }; template <typename Allocator, unsigned int Bits> struct require_member< boost::asio::thread_pool::basic_executor_type<Allocator, Bits>, boost::asio::execution::allocator_t<void> > { static constexpr bool is_valid = true; static constexpr bool is_noexcept = false; typedef boost::asio::thread_pool::basic_executor_type< std::allocator<void>, Bits> result_type; }; template <unsigned int Bits, typename Allocator, typename OtherAllocator> struct require_member< boost::asio::thread_pool::basic_executor_type<Allocator, Bits>, boost::asio::execution::allocator_t<OtherAllocator> > { static constexpr bool is_valid = true; static constexpr bool is_noexcept = false; typedef boost::asio::thread_pool::basic_executor_type< OtherAllocator, Bits> result_type; }; #endif // !defined(BOOST_ASIO_HAS_DEDUCED_REQUIRE_MEMBER_TRAIT) #if !defined(BOOST_ASIO_HAS_DEDUCED_QUERY_STATIC_CONSTEXPR_MEMBER_TRAIT) template <typename Allocator, unsigned int Bits, typename Property> struct query_static_constexpr_member< boost::asio::thread_pool::basic_executor_type<Allocator, Bits>, Property, typename boost::asio::enable_if< boost::asio::is_convertible< Property, boost::asio::execution::outstanding_work_t >::value >::type > : boost::asio::detail::thread_pool_bits { static constexpr bool is_valid = true; static constexpr bool is_noexcept = true; typedef boost::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< boost::asio::thread_pool::basic_executor_type<Allocator, Bits>, Property, typename boost::asio::enable_if< boost::asio::is_convertible< Property, boost::asio::execution::mapping_t >::value >::type > { static constexpr bool is_valid = true; static constexpr bool is_noexcept = true; typedef boost::asio::execution::mapping_t::thread_t result_type; static constexpr result_type value() noexcept { return result_type(); } }; #endif // !defined(BOOST_ASIO_HAS_DEDUCED_QUERY_STATIC_CONSTEXPR_MEMBER_TRAIT) #if !defined(BOOST_ASIO_HAS_DEDUCED_QUERY_MEMBER_TRAIT) template <typename Allocator, unsigned int Bits, typename Property> struct query_member< boost::asio::thread_pool::basic_executor_type<Allocator, Bits>, Property, typename boost::asio::enable_if< boost::asio::is_convertible< Property, boost::asio::execution::blocking_t >::value >::type > { static constexpr bool is_valid = true; static constexpr bool is_noexcept = true; typedef boost::asio::execution::blocking_t result_type; }; template <typename Allocator, unsigned int Bits, typename Property> struct query_member< boost::asio::thread_pool::basic_executor_type<Allocator, Bits>, Property, typename boost::asio::enable_if< boost::asio::is_convertible< Property, boost::asio::execution::relationship_t >::value >::type > { static constexpr bool is_valid = true; static constexpr bool is_noexcept = true; typedef boost::asio::execution::relationship_t result_type; }; template <typename Allocator, unsigned int Bits> struct query_member< boost::asio::thread_pool::basic_executor_type<Allocator, Bits>, boost::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< boost::asio::thread_pool::basic_executor_type<Allocator, Bits>, boost::asio::execution::context_t > { static constexpr bool is_valid = true; static constexpr bool is_noexcept = true; typedef boost::asio::thread_pool& result_type; }; template <typename Allocator, unsigned int Bits> struct query_member< boost::asio::thread_pool::basic_executor_type<Allocator, Bits>, boost::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< boost::asio::thread_pool::basic_executor_type<Allocator, Bits>, boost::asio::execution::allocator_t<OtherAllocator> > { static constexpr bool is_valid = true; static constexpr bool is_noexcept = true; typedef Allocator result_type; }; #endif // !defined(BOOST_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 } // namespace boost #include <boost/asio/detail/pop_options.hpp> #include <boost/asio/impl/thread_pool.hpp> #if defined(BOOST_ASIO_HEADER_ONLY) # include <boost/asio/impl/thread_pool.ipp> #endif // defined(BOOST_ASIO_HEADER_ONLY) #endif // BOOST_ASIO_THREAD_POOL_HPP
hpp
asio
data/projects/asio/include/boost/asio/append.hpp
// // append.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 BOOST_ASIO_APPEND_HPP #define BOOST_ASIO_APPEND_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <boost/asio/detail/config.hpp> #include <tuple> #include <boost/asio/detail/type_traits.hpp> #include <boost/asio/detail/push_options.hpp> namespace boost { namespace asio { /// Completion token type used to specify that the completion handler /// arguments should be passed additional values after the results of the /// operation. template <typename CompletionToken, typename... Values> class append_t { public: /// Constructor. template <typename T, typename... V> constexpr explicit append_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 after the results of the /// operation. template <typename CompletionToken, typename... Values> BOOST_ASIO_NODISCARD inline constexpr append_t<decay_t<CompletionToken>, decay_t<Values>...> append(CompletionToken&& completion_token, Values&&... values) { return append_t<decay_t<CompletionToken>, decay_t<Values>...>( static_cast<CompletionToken&&>(completion_token), static_cast<Values&&>(values)...); } } // namespace asio } // namespace boost #include <boost/asio/detail/pop_options.hpp> #include <boost/asio/impl/append.hpp> #endif // BOOST_ASIO_APPEND_HPP
hpp
asio
data/projects/asio/include/boost/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 BOOST_ASIO_EXECUTOR_WORK_GUARD_HPP #define BOOST_ASIO_EXECUTOR_WORK_GUARD_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <boost/asio/detail/config.hpp> #include <boost/asio/associated_executor.hpp> #include <boost/asio/detail/type_traits.hpp> #include <boost/asio/execution.hpp> #include <boost/asio/is_executor.hpp> #include <boost/asio/detail/push_options.hpp> namespace boost { namespace asio { #if !defined(BOOST_ASIO_EXECUTOR_WORK_GUARD_DECL) #define BOOST_ASIO_EXECUTOR_WORK_GUARD_DECL template <typename Executor, typename = void, typename = void> class executor_work_guard; #endif // !defined(BOOST_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(BOOST_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(BOOST_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(boost::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(boost::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> BOOST_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> BOOST_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> BOOST_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> BOOST_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> BOOST_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 } // namespace boost #include <boost/asio/detail/pop_options.hpp> #endif // BOOST_ASIO_EXECUTOR_WORK_GUARD_HPP
hpp
asio
data/projects/asio/include/boost/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 BOOST_ASIO_BIND_CANCELLATION_SLOT_HPP #define BOOST_ASIO_BIND_CANCELLATION_SLOT_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <boost/asio/detail/config.hpp> #include <boost/asio/detail/type_traits.hpp> #include <boost/asio/associated_cancellation_slot.hpp> #include <boost/asio/associator.hpp> #include <boost/asio/async_result.hpp> #include <boost/asio/detail/push_options.hpp> namespace boost { 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_; }; /// Associate an object of type @c T with a cancellation slot of type /// @c CancellationSlot. template <typename CancellationSlot, typename T> BOOST_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 { template <typename Init> init_wrapper(const CancellationSlot& slot, Init&& init) : slot_(slot), initiation_(static_cast<Init&&>(init)) { } template <typename Handler, typename... Args> void operator()(Handler&& handler, Args&&... args) { static_cast<Initiation&&>(initiation_)( 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, Args&&... args) const { initiation_( cancellation_slot_binder<decay_t<Handler>, CancellationSlot>( slot_, static_cast<Handler&&>(handler)), static_cast<Args&&>(args)...); } CancellationSlot slot_; Initiation initiation_; }; template <typename Initiation, typename RawCompletionToken, typename... Args> static auto initiate(Initiation&& initiation, RawCompletionToken&& token, Args&&... args) -> decltype( async_initiate<T, Signature>( declval<init_wrapper<decay_t<Initiation>>>(), token.get(), static_cast<Args&&>(args)...)) { return async_initiate<T, Signature>( init_wrapper<decay_t<Initiation>>( token.get_cancellation_slot(), static_cast<Initiation&&>(initiation)), token.get(), static_cast<Args&&>(args)...); } private: async_result(const async_result&) = delete; async_result& operator=(const async_result&) = delete; async_result<T, Signature> target_; }; 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 } // namespace boost #include <boost/asio/detail/pop_options.hpp> #endif // BOOST_ASIO_BIND_CANCELLATION_SLOT_HPP
hpp
asio
data/projects/asio/include/boost/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 BOOST_ASIO_BASIC_WAITABLE_TIMER_HPP #define BOOST_ASIO_BASIC_WAITABLE_TIMER_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <boost/asio/detail/config.hpp> #include <cstddef> #include <utility> #include <boost/asio/any_io_executor.hpp> #include <boost/asio/detail/chrono_time_traits.hpp> #include <boost/asio/detail/deadline_timer_service.hpp> #include <boost/asio/detail/handler_type_requirements.hpp> #include <boost/asio/detail/io_object_impl.hpp> #include <boost/asio/detail/non_const_lvalue.hpp> #include <boost/asio/detail/throw_error.hpp> #include <boost/asio/error.hpp> #include <boost/asio/wait_traits.hpp> #include <boost/asio/detail/push_options.hpp> namespace boost { namespace asio { #if !defined(BOOST_ASIO_BASIC_WAITABLE_TIMER_FWD_DECL) #define BOOST_ASIO_BASIC_WAITABLE_TIMER_FWD_DECL // Forward declaration with defaulted arguments. template <typename Clock, typename WaitTraits = boost::asio::wait_traits<Clock>, typename Executor = any_io_executor> class basic_waitable_timer; #endif // !defined(BOOST_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 boost::asio::steady_timer, * boost::asio::system_timer or boost::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. * boost::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 boost::system::error_code& error) * { * if (!error) * { * // Timer expired. * } * } * * ... * * // Construct a timer with an absolute expiry time. * boost::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 boost::system::error_code& e) * { * if (e != boost::asio::error::operation_aborted) * { * // Timer was not cancelled, take necessary action. * } * } * @endcode * * @li The boost::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 boost::system::error_code passed to * it contains the value boost::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) { boost::system::error_code ec; impl_.get_service().expires_at(impl_.get_implementation(), expiry_time, ec); boost::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) { boost::system::error_code ec; impl_.get_service().expires_at(impl_.get_implementation(), expiry_time, ec); boost::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) { boost::system::error_code ec; impl_.get_service().expires_after( impl_.get_implementation(), expiry_time, ec); boost::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) { boost::system::error_code ec; impl_.get_service().expires_after( impl_.get_implementation(), expiry_time, ec); boost::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 boost::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 boost::system::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() { boost::system::error_code ec; std::size_t s = impl_.get_service().cancel(impl_.get_implementation(), ec); boost::asio::detail::throw_error(ec, "cancel"); return s; } #if !defined(BOOST_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 boost::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(boost::system::error_code& ec) { return impl_.get_service().cancel(impl_.get_implementation(), ec); } #endif // !defined(BOOST_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 * boost::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 boost::system::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() { boost::system::error_code ec; std::size_t s = impl_.get_service().cancel_one( impl_.get_implementation(), ec); boost::asio::detail::throw_error(ec, "cancel_one"); return s; } #if !defined(BOOST_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 * boost::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(boost::system::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(BOOST_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 boost::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 boost::system::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) { boost::system::error_code ec; std::size_t s = impl_.get_service().expires_at( impl_.get_implementation(), expiry_time, ec); boost::asio::detail::throw_error(ec, "expires_at"); return s; } #if !defined(BOOST_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 boost::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, boost::system::error_code& ec) { return impl_.get_service().expires_at( impl_.get_implementation(), expiry_time, ec); } #endif // !defined(BOOST_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 boost::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 boost::system::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) { boost::system::error_code ec; std::size_t s = impl_.get_service().expires_after( impl_.get_implementation(), expiry_time, ec); boost::asio::detail::throw_error(ec, "expires_after"); return s; } #if !defined(BOOST_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 boost::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 boost::system::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) { boost::system::error_code ec; std::size_t s = impl_.get_service().expires_from_now( impl_.get_implementation(), expiry_time, ec); boost::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 boost::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, boost::system::error_code& ec) { return impl_.get_service().expires_from_now( impl_.get_implementation(), expiry_time, ec); } #endif // !defined(BOOST_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 boost::system::system_error Thrown on failure. */ void wait() { boost::system::error_code ec; impl_.get_service().wait(impl_.get_implementation(), ec); boost::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(boost::system::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 boost::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 boost::system::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 boost::asio::post(). * * @par Completion Signature * @code void(boost::system::error_code) @endcode * * @par Per-Operation Cancellation * This asynchronous operation supports cancellation for the following * boost::asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * @li @c cancellation_type::total */ template < BOOST_ASIO_COMPLETION_TOKEN_FOR(void (boost::system::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 (boost::system::error_code)>( declval<initiate_async_wait>(), token)) { return async_initiate<WaitToken, void (boost::system::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. BOOST_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 } // namespace boost #include <boost/asio/detail/pop_options.hpp> #endif // BOOST_ASIO_BASIC_WAITABLE_TIMER_HPP
hpp
asio
data/projects/asio/include/boost/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 BOOST_ASIO_BASIC_RANDOM_ACCESS_FILE_HPP #define BOOST_ASIO_BASIC_RANDOM_ACCESS_FILE_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <boost/asio/detail/config.hpp> #if defined(BOOST_ASIO_HAS_FILE) \ || defined(GENERATING_DOCUMENTATION) #include <cstddef> #include <boost/asio/async_result.hpp> #include <boost/asio/basic_file.hpp> #include <boost/asio/detail/handler_type_requirements.hpp> #include <boost/asio/detail/non_const_lvalue.hpp> #include <boost/asio/detail/throw_error.hpp> #include <boost/asio/error.hpp> #include <boost/asio/detail/push_options.hpp> namespace boost { namespace asio { #if !defined(BOOST_ASIO_BASIC_RANDOM_ACCESS_FILE_FWD_DECL) #define BOOST_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(BOOST_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 boost::system::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 boost::system::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 boost::system::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 boost::system::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 boost::system::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 boost::system::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 boost::system::system_error Thrown on failure. An error code of * boost::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, boost::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) { boost::system::error_code ec; std::size_t s = this->impl_.get_service().write_some_at( this->impl_.get_implementation(), offset, buffers, ec); boost::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, boost::system::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 boost::system::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 boost::asio::post(). * * @par Completion Signature * @code void(boost::system::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, boost::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 * boost::asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * @li @c cancellation_type::total */ template <typename ConstBufferSequence, BOOST_ASIO_COMPLETION_TOKEN_FOR(void (boost::system::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 (boost::system::error_code, std::size_t)>( declval<initiate_async_write_some_at>(), token, offset, buffers)) { return async_initiate<WriteToken, void (boost::system::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 boost::system::system_error Thrown on failure. An error code of * boost::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, boost::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) { boost::system::error_code ec; std::size_t s = this->impl_.get_service().read_some_at( this->impl_.get_implementation(), offset, buffers, ec); boost::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, boost::system::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 boost::system::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 boost::asio::post(). * * @par Completion Signature * @code void(boost::system::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, boost::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 * boost::asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * @li @c cancellation_type::total */ template <typename MutableBufferSequence, BOOST_ASIO_COMPLETION_TOKEN_FOR(void (boost::system::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 (boost::system::error_code, std::size_t)>( declval<initiate_async_read_some_at>(), token, offset, buffers)) { return async_initiate<ReadToken, void (boost::system::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. BOOST_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. BOOST_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 } // namespace boost #include <boost/asio/detail/pop_options.hpp> #endif // defined(BOOST_ASIO_HAS_FILE) // || defined(GENERATING_DOCUMENTATION) #endif // BOOST_ASIO_BASIC_RANDOM_ACCESS_FILE_HPP
hpp
asio
data/projects/asio/include/boost/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 BOOST_ASIO_BUFFERED_STREAM_HPP #define BOOST_ASIO_BUFFERED_STREAM_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <boost/asio/detail/config.hpp> #include <cstddef> #include <boost/asio/async_result.hpp> #include <boost/asio/buffered_read_stream.hpp> #include <boost/asio/buffered_write_stream.hpp> #include <boost/asio/buffered_stream_fwd.hpp> #include <boost/asio/detail/noncopyable.hpp> #include <boost/asio/error.hpp> #include <boost/asio/detail/push_options.hpp> namespace boost { 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. BOOST_ASIO_SYNC_OP_VOID close(boost::system::error_code& ec) { stream_impl_.close(ec); BOOST_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(boost::system::error_code& ec) { return stream_impl_.next_layer().flush(ec); } /// Start an asynchronous flush. /** * @par Completion Signature * @code void(boost::system::error_code, std::size_t) @endcode */ template < BOOST_ASIO_COMPLETION_TOKEN_FOR(void (boost::system::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, boost::system::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(boost::system::error_code, std::size_t) @endcode */ template <typename ConstBufferSequence, BOOST_ASIO_COMPLETION_TOKEN_FOR(void (boost::system::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(boost::system::error_code& ec) { return stream_impl_.fill(ec); } /// Start an asynchronous fill. /** * @par Completion Signature * @code void(boost::system::error_code, std::size_t) @endcode */ template < BOOST_ASIO_COMPLETION_TOKEN_FOR(void (boost::system::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, boost::system::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(boost::system::error_code, std::size_t) @endcode */ template <typename MutableBufferSequence, BOOST_ASIO_COMPLETION_TOKEN_FOR(void (boost::system::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, boost::system::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(boost::system::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 } // namespace boost #include <boost/asio/detail/pop_options.hpp> #endif // BOOST_ASIO_BUFFERED_STREAM_HPP
hpp
asio
data/projects/asio/include/boost/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 BOOST_ASIO_IS_APPLICABLE_PROPERTY_HPP #define BOOST_ASIO_IS_APPLICABLE_PROPERTY_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <boost/asio/detail/config.hpp> #include <boost/asio/detail/type_traits.hpp> namespace boost { namespace asio { namespace detail { template <typename T, typename Property, typename = void> struct is_applicable_property_trait : false_type { }; #if defined(BOOST_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(BOOST_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(BOOST_ASIO_HAS_VARIABLE_TEMPLATES) template <typename T, typename Property> constexpr const bool is_applicable_property_v = is_applicable_property<T, Property>::value; #endif // defined(BOOST_ASIO_HAS_VARIABLE_TEMPLATES) } // namespace asio } // namespace boost #endif // BOOST_ASIO_IS_APPLICABLE_PROPERTY_HPP
hpp
asio
data/projects/asio/include/boost/asio/io_service.hpp
// // io_service.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 BOOST_ASIO_IO_SERVICE_HPP #define BOOST_ASIO_IO_SERVICE_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <boost/asio/io_context.hpp> #include <boost/asio/detail/push_options.hpp> namespace boost { namespace asio { #if !defined(BOOST_ASIO_NO_DEPRECATED) /// Typedef for backwards compatibility. typedef io_context io_service; #endif // !defined(BOOST_ASIO_NO_DEPRECATED) } // namespace asio } // namespace boost #include <boost/asio/detail/pop_options.hpp> #endif // BOOST_ASIO_IO_SERVICE_HPP
hpp
asio
data/projects/asio/include/boost/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 BOOST_ASIO_HIGH_RESOLUTION_TIMER_HPP #define BOOST_ASIO_HIGH_RESOLUTION_TIMER_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <boost/asio/detail/config.hpp> #include <boost/asio/basic_waitable_timer.hpp> #include <boost/asio/detail/chrono.hpp> namespace boost { 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 } // namespace boost #endif // BOOST_ASIO_HIGH_RESOLUTION_TIMER_HPP
hpp
asio
data/projects/asio/include/boost/asio/basic_socket_acceptor.hpp
// // basic_socket_acceptor.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 BOOST_ASIO_BASIC_SOCKET_ACCEPTOR_HPP #define BOOST_ASIO_BASIC_SOCKET_ACCEPTOR_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <utility> #include <boost/asio/detail/config.hpp> #include <boost/asio/any_io_executor.hpp> #include <boost/asio/basic_socket.hpp> #include <boost/asio/detail/handler_type_requirements.hpp> #include <boost/asio/detail/io_object_impl.hpp> #include <boost/asio/detail/non_const_lvalue.hpp> #include <boost/asio/detail/throw_error.hpp> #include <boost/asio/detail/type_traits.hpp> #include <boost/asio/error.hpp> #include <boost/asio/execution_context.hpp> #include <boost/asio/socket_base.hpp> #if defined(BOOST_ASIO_WINDOWS_RUNTIME) # include <boost/asio/detail/null_socket_service.hpp> #elif defined(BOOST_ASIO_HAS_IOCP) # include <boost/asio/detail/win_iocp_socket_service.hpp> #elif defined(BOOST_ASIO_HAS_IO_URING_AS_DEFAULT) # include <boost/asio/detail/io_uring_socket_service.hpp> #else # include <boost/asio/detail/reactive_socket_service.hpp> #endif #include <boost/asio/detail/push_options.hpp> namespace boost { namespace asio { #if !defined(BOOST_ASIO_BASIC_SOCKET_ACCEPTOR_FWD_DECL) #define BOOST_ASIO_BASIC_SOCKET_ACCEPTOR_FWD_DECL // Forward declaration with defaulted arguments. template <typename Protocol, typename Executor = any_io_executor> class basic_socket_acceptor; #endif // !defined(BOOST_ASIO_BASIC_SOCKET_ACCEPTOR_FWD_DECL) /// Provides the ability to accept new connections. /** * The basic_socket_acceptor class template is used for accepting new socket * connections. * * @par Thread Safety * @e Distinct @e objects: Safe.@n * @e Shared @e objects: Unsafe. * * Synchronous @c accept operations are thread safe, if the underlying * operating system calls are also thread safe. This means that it is permitted * to perform concurrent calls to synchronous @c accept operations on a single * socket object. Other synchronous operations, such as @c open or @c close, are * not thread safe. * * @par Example * Opening a socket acceptor with the SO_REUSEADDR option enabled: * @code * boost::asio::ip::tcp::acceptor acceptor(my_context); * boost::asio::ip::tcp::endpoint endpoint(boost::asio::ip::tcp::v4(), port); * acceptor.open(endpoint.protocol()); * acceptor.set_option(boost::asio::ip::tcp::acceptor::reuse_address(true)); * acceptor.bind(endpoint); * acceptor.listen(); * @endcode */ template <typename Protocol, typename Executor> class basic_socket_acceptor : public socket_base { private: class initiate_async_wait; class initiate_async_accept; class initiate_async_move_accept; public: /// The type of the executor associated with the object. typedef Executor executor_type; /// Rebinds the acceptor type to another executor. template <typename Executor1> struct rebind_executor { /// The socket type when rebound to the specified executor. typedef basic_socket_acceptor<Protocol, Executor1> other; }; /// The native representation of an acceptor. #if defined(GENERATING_DOCUMENTATION) typedef implementation_defined native_handle_type; #elif defined(BOOST_ASIO_WINDOWS_RUNTIME) typedef typename detail::null_socket_service< Protocol>::native_handle_type native_handle_type; #elif defined(BOOST_ASIO_HAS_IOCP) typedef typename detail::win_iocp_socket_service< Protocol>::native_handle_type native_handle_type; #elif defined(BOOST_ASIO_HAS_IO_URING_AS_DEFAULT) typedef typename detail::io_uring_socket_service< Protocol>::native_handle_type native_handle_type; #else typedef typename detail::reactive_socket_service< Protocol>::native_handle_type native_handle_type; #endif /// The protocol type. typedef Protocol protocol_type; /// The endpoint type. typedef typename Protocol::endpoint endpoint_type; /// Construct an acceptor without opening it. /** * This constructor creates an acceptor without opening it to listen for new * connections. The open() function must be called before the acceptor can * accept new socket connections. * * @param ex The I/O executor that the acceptor will use, by default, to * dispatch handlers for any asynchronous operations performed on the * acceptor. */ explicit basic_socket_acceptor(const executor_type& ex) : impl_(0, ex) { } /// Construct an acceptor without opening it. /** * This constructor creates an acceptor without opening it to listen for new * connections. The open() function must be called before the acceptor can * accept new socket connections. * * @param context An execution context which provides the I/O executor that * the acceptor will use, by default, to dispatch handlers for any * asynchronous operations performed on the acceptor. */ template <typename ExecutionContext> explicit basic_socket_acceptor(ExecutionContext& context, constraint_t< is_convertible<ExecutionContext&, execution_context&>::value > = 0) : impl_(0, 0, context) { } /// Construct an open acceptor. /** * This constructor creates an acceptor and automatically opens it. * * @param ex The I/O executor that the acceptor will use, by default, to * dispatch handlers for any asynchronous operations performed on the * acceptor. * * @param protocol An object specifying protocol parameters to be used. * * @throws boost::system::system_error Thrown on failure. */ basic_socket_acceptor(const executor_type& ex, const protocol_type& protocol) : impl_(0, ex) { boost::system::error_code ec; impl_.get_service().open(impl_.get_implementation(), protocol, ec); boost::asio::detail::throw_error(ec, "open"); } /// Construct an open acceptor. /** * This constructor creates an acceptor and automatically opens it. * * @param context An execution context which provides the I/O executor that * the acceptor will use, by default, to dispatch handlers for any * asynchronous operations performed on the acceptor. * * @param protocol An object specifying protocol parameters to be used. * * @throws boost::system::system_error Thrown on failure. */ template <typename ExecutionContext> basic_socket_acceptor(ExecutionContext& context, const protocol_type& protocol, constraint_t< is_convertible<ExecutionContext&, execution_context&>::value, defaulted_constraint > = defaulted_constraint()) : impl_(0, 0, context) { boost::system::error_code ec; impl_.get_service().open(impl_.get_implementation(), protocol, ec); boost::asio::detail::throw_error(ec, "open"); } /// Construct an acceptor opened on the given endpoint. /** * This constructor creates an acceptor and automatically opens it to listen * for new connections on the specified endpoint. * * @param ex The I/O executor that the acceptor will use, by default, to * dispatch handlers for any asynchronous operations performed on the * acceptor. * * @param endpoint An endpoint on the local machine on which the acceptor * will listen for new connections. * * @param reuse_addr Whether the constructor should set the socket option * socket_base::reuse_address. * * @throws boost::system::system_error Thrown on failure. * * @note This constructor is equivalent to the following code: * @code * basic_socket_acceptor<Protocol> acceptor(my_context); * acceptor.open(endpoint.protocol()); * if (reuse_addr) * acceptor.set_option(socket_base::reuse_address(true)); * acceptor.bind(endpoint); * acceptor.listen(); * @endcode */ basic_socket_acceptor(const executor_type& ex, const endpoint_type& endpoint, bool reuse_addr = true) : impl_(0, ex) { boost::system::error_code ec; const protocol_type protocol = endpoint.protocol(); impl_.get_service().open(impl_.get_implementation(), protocol, ec); boost::asio::detail::throw_error(ec, "open"); if (reuse_addr) { impl_.get_service().set_option(impl_.get_implementation(), socket_base::reuse_address(true), ec); boost::asio::detail::throw_error(ec, "set_option"); } impl_.get_service().bind(impl_.get_implementation(), endpoint, ec); boost::asio::detail::throw_error(ec, "bind"); impl_.get_service().listen(impl_.get_implementation(), socket_base::max_listen_connections, ec); boost::asio::detail::throw_error(ec, "listen"); } /// Construct an acceptor opened on the given endpoint. /** * This constructor creates an acceptor and automatically opens it to listen * for new connections on the specified endpoint. * * @param context An execution context which provides the I/O executor that * the acceptor will use, by default, to dispatch handlers for any * asynchronous operations performed on the acceptor. * * @param endpoint An endpoint on the local machine on which the acceptor * will listen for new connections. * * @param reuse_addr Whether the constructor should set the socket option * socket_base::reuse_address. * * @throws boost::system::system_error Thrown on failure. * * @note This constructor is equivalent to the following code: * @code * basic_socket_acceptor<Protocol> acceptor(my_context); * acceptor.open(endpoint.protocol()); * if (reuse_addr) * acceptor.set_option(socket_base::reuse_address(true)); * acceptor.bind(endpoint); * acceptor.listen(); * @endcode */ template <typename ExecutionContext> basic_socket_acceptor(ExecutionContext& context, const endpoint_type& endpoint, bool reuse_addr = true, constraint_t< is_convertible<ExecutionContext&, execution_context&>::value > = 0) : impl_(0, 0, context) { boost::system::error_code ec; const protocol_type protocol = endpoint.protocol(); impl_.get_service().open(impl_.get_implementation(), protocol, ec); boost::asio::detail::throw_error(ec, "open"); if (reuse_addr) { impl_.get_service().set_option(impl_.get_implementation(), socket_base::reuse_address(true), ec); boost::asio::detail::throw_error(ec, "set_option"); } impl_.get_service().bind(impl_.get_implementation(), endpoint, ec); boost::asio::detail::throw_error(ec, "bind"); impl_.get_service().listen(impl_.get_implementation(), socket_base::max_listen_connections, ec); boost::asio::detail::throw_error(ec, "listen"); } /// Construct a basic_socket_acceptor on an existing native acceptor. /** * This constructor creates an acceptor object to hold an existing native * acceptor. * * @param ex The I/O executor that the acceptor will use, by default, to * dispatch handlers for any asynchronous operations performed on the * acceptor. * * @param protocol An object specifying protocol parameters to be used. * * @param native_acceptor A native acceptor. * * @throws boost::system::system_error Thrown on failure. */ basic_socket_acceptor(const executor_type& ex, const protocol_type& protocol, const native_handle_type& native_acceptor) : impl_(0, ex) { boost::system::error_code ec; impl_.get_service().assign(impl_.get_implementation(), protocol, native_acceptor, ec); boost::asio::detail::throw_error(ec, "assign"); } /// Construct a basic_socket_acceptor on an existing native acceptor. /** * This constructor creates an acceptor object to hold an existing native * acceptor. * * @param context An execution context which provides the I/O executor that * the acceptor will use, by default, to dispatch handlers for any * asynchronous operations performed on the acceptor. * * @param protocol An object specifying protocol parameters to be used. * * @param native_acceptor A native acceptor. * * @throws boost::system::system_error Thrown on failure. */ template <typename ExecutionContext> basic_socket_acceptor(ExecutionContext& context, const protocol_type& protocol, const native_handle_type& native_acceptor, constraint_t< is_convertible<ExecutionContext&, execution_context&>::value > = 0) : impl_(0, 0, context) { boost::system::error_code ec; impl_.get_service().assign(impl_.get_implementation(), protocol, native_acceptor, ec); boost::asio::detail::throw_error(ec, "assign"); } /// Move-construct a basic_socket_acceptor from another. /** * This constructor moves an acceptor from one object to another. * * @param other The other basic_socket_acceptor 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_socket_acceptor(const executor_type&) * constructor. */ basic_socket_acceptor(basic_socket_acceptor&& other) noexcept : impl_(std::move(other.impl_)) { } /// Move-assign a basic_socket_acceptor from another. /** * This assignment operator moves an acceptor from one object to another. * * @param other The other basic_socket_acceptor 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_socket_acceptor(const executor_type&) * constructor. */ basic_socket_acceptor& operator=(basic_socket_acceptor&& other) { impl_ = std::move(other.impl_); return *this; } // All socket acceptors have access to each other's implementations. template <typename Protocol1, typename Executor1> friend class basic_socket_acceptor; /// Move-construct a basic_socket_acceptor from an acceptor of another /// protocol type. /** * This constructor moves an acceptor from one object to another. * * @param other The other basic_socket_acceptor 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_socket_acceptor(const executor_type&) * constructor. */ template <typename Protocol1, typename Executor1> basic_socket_acceptor(basic_socket_acceptor<Protocol1, Executor1>&& other, constraint_t< is_convertible<Protocol1, Protocol>::value && is_convertible<Executor1, Executor>::value > = 0) : impl_(std::move(other.impl_)) { } /// Move-assign a basic_socket_acceptor from an acceptor of another protocol /// type. /** * This assignment operator moves an acceptor from one object to another. * * @param other The other basic_socket_acceptor 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_socket_acceptor(const executor_type&) * constructor. */ template <typename Protocol1, typename Executor1> constraint_t< is_convertible<Protocol1, Protocol>::value && is_convertible<Executor1, Executor>::value, basic_socket_acceptor& > operator=(basic_socket_acceptor<Protocol1, Executor1>&& other) { basic_socket_acceptor tmp(std::move(other)); impl_ = std::move(tmp.impl_); return *this; } /// Destroys the acceptor. /** * This function destroys the acceptor, cancelling any outstanding * asynchronous operations associated with the acceptor as if by calling * @c cancel. */ ~basic_socket_acceptor() { } /// Get the executor associated with the object. const executor_type& get_executor() noexcept { return impl_.get_executor(); } /// Open the acceptor using the specified protocol. /** * This function opens the socket acceptor so that it will use the specified * protocol. * * @param protocol An object specifying which protocol is to be used. * * @throws boost::system::system_error Thrown on failure. * * @par Example * @code * boost::asio::ip::tcp::acceptor acceptor(my_context); * acceptor.open(boost::asio::ip::tcp::v4()); * @endcode */ void open(const protocol_type& protocol = protocol_type()) { boost::system::error_code ec; impl_.get_service().open(impl_.get_implementation(), protocol, ec); boost::asio::detail::throw_error(ec, "open"); } /// Open the acceptor using the specified protocol. /** * This function opens the socket acceptor so that it will use the specified * protocol. * * @param protocol An object specifying which protocol is to be used. * * @param ec Set to indicate what error occurred, if any. * * @par Example * @code * boost::asio::ip::tcp::acceptor acceptor(my_context); * boost::system::error_code ec; * acceptor.open(boost::asio::ip::tcp::v4(), ec); * if (ec) * { * // An error occurred. * } * @endcode */ BOOST_ASIO_SYNC_OP_VOID open(const protocol_type& protocol, boost::system::error_code& ec) { impl_.get_service().open(impl_.get_implementation(), protocol, ec); BOOST_ASIO_SYNC_OP_VOID_RETURN(ec); } /// Assigns an existing native acceptor to the acceptor. /* * This function opens the acceptor to hold an existing native acceptor. * * @param protocol An object specifying which protocol is to be used. * * @param native_acceptor A native acceptor. * * @throws boost::system::system_error Thrown on failure. */ void assign(const protocol_type& protocol, const native_handle_type& native_acceptor) { boost::system::error_code ec; impl_.get_service().assign(impl_.get_implementation(), protocol, native_acceptor, ec); boost::asio::detail::throw_error(ec, "assign"); } /// Assigns an existing native acceptor to the acceptor. /* * This function opens the acceptor to hold an existing native acceptor. * * @param protocol An object specifying which protocol is to be used. * * @param native_acceptor A native acceptor. * * @param ec Set to indicate what error occurred, if any. */ BOOST_ASIO_SYNC_OP_VOID assign(const protocol_type& protocol, const native_handle_type& native_acceptor, boost::system::error_code& ec) { impl_.get_service().assign(impl_.get_implementation(), protocol, native_acceptor, ec); BOOST_ASIO_SYNC_OP_VOID_RETURN(ec); } /// Determine whether the acceptor is open. bool is_open() const { return impl_.get_service().is_open(impl_.get_implementation()); } /// Bind the acceptor to the given local endpoint. /** * This function binds the socket acceptor to the specified endpoint on the * local machine. * * @param endpoint An endpoint on the local machine to which the socket * acceptor will be bound. * * @throws boost::system::system_error Thrown on failure. * * @par Example * @code * boost::asio::ip::tcp::acceptor acceptor(my_context); * boost::asio::ip::tcp::endpoint endpoint(boost::asio::ip::tcp::v4(), 12345); * acceptor.open(endpoint.protocol()); * acceptor.bind(endpoint); * @endcode */ void bind(const endpoint_type& endpoint) { boost::system::error_code ec; impl_.get_service().bind(impl_.get_implementation(), endpoint, ec); boost::asio::detail::throw_error(ec, "bind"); } /// Bind the acceptor to the given local endpoint. /** * This function binds the socket acceptor to the specified endpoint on the * local machine. * * @param endpoint An endpoint on the local machine to which the socket * acceptor will be bound. * * @param ec Set to indicate what error occurred, if any. * * @par Example * @code * boost::asio::ip::tcp::acceptor acceptor(my_context); * boost::asio::ip::tcp::endpoint endpoint(boost::asio::ip::tcp::v4(), 12345); * acceptor.open(endpoint.protocol()); * boost::system::error_code ec; * acceptor.bind(endpoint, ec); * if (ec) * { * // An error occurred. * } * @endcode */ BOOST_ASIO_SYNC_OP_VOID bind(const endpoint_type& endpoint, boost::system::error_code& ec) { impl_.get_service().bind(impl_.get_implementation(), endpoint, ec); BOOST_ASIO_SYNC_OP_VOID_RETURN(ec); } /// Place the acceptor into the state where it will listen for new /// connections. /** * This function puts the socket acceptor into the state where it may accept * new connections. * * @param backlog The maximum length of the queue of pending connections. * * @throws boost::system::system_error Thrown on failure. */ void listen(int backlog = socket_base::max_listen_connections) { boost::system::error_code ec; impl_.get_service().listen(impl_.get_implementation(), backlog, ec); boost::asio::detail::throw_error(ec, "listen"); } /// Place the acceptor into the state where it will listen for new /// connections. /** * This function puts the socket acceptor into the state where it may accept * new connections. * * @param backlog The maximum length of the queue of pending connections. * * @param ec Set to indicate what error occurred, if any. * * @par Example * @code * boost::asio::ip::tcp::acceptor acceptor(my_context); * ... * boost::system::error_code ec; * acceptor.listen(boost::asio::socket_base::max_listen_connections, ec); * if (ec) * { * // An error occurred. * } * @endcode */ BOOST_ASIO_SYNC_OP_VOID listen(int backlog, boost::system::error_code& ec) { impl_.get_service().listen(impl_.get_implementation(), backlog, ec); BOOST_ASIO_SYNC_OP_VOID_RETURN(ec); } /// Close the acceptor. /** * This function is used to close the acceptor. Any asynchronous accept * operations will be cancelled immediately. * * A subsequent call to open() is required before the acceptor can again be * used to again perform socket accept operations. * * @throws boost::system::system_error Thrown on failure. */ void close() { boost::system::error_code ec; impl_.get_service().close(impl_.get_implementation(), ec); boost::asio::detail::throw_error(ec, "close"); } /// Close the acceptor. /** * This function is used to close the acceptor. Any asynchronous accept * operations will be cancelled immediately. * * A subsequent call to open() is required before the acceptor can again be * used to again perform socket accept operations. * * @param ec Set to indicate what error occurred, if any. * * @par Example * @code * boost::asio::ip::tcp::acceptor acceptor(my_context); * ... * boost::system::error_code ec; * acceptor.close(ec); * if (ec) * { * // An error occurred. * } * @endcode */ BOOST_ASIO_SYNC_OP_VOID close(boost::system::error_code& ec) { impl_.get_service().close(impl_.get_implementation(), ec); BOOST_ASIO_SYNC_OP_VOID_RETURN(ec); } /// Release ownership of the underlying native acceptor. /** * This function causes all outstanding asynchronous accept operations to * finish immediately, and the handlers for cancelled operations will be * passed the boost::asio::error::operation_aborted error. Ownership of the * native acceptor is then transferred to the caller. * * @throws boost::system::system_error Thrown on failure. * * @note This function is unsupported on Windows versions prior to Windows * 8.1, and will fail with boost::asio::error::operation_not_supported on * these platforms. */ #if defined(BOOST_ASIO_MSVC) && (BOOST_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() { boost::system::error_code ec; native_handle_type s = impl_.get_service().release( impl_.get_implementation(), ec); boost::asio::detail::throw_error(ec, "release"); return s; } /// Release ownership of the underlying native acceptor. /** * This function causes all outstanding asynchronous accept operations to * finish immediately, and the handlers for cancelled operations will be * passed the boost::asio::error::operation_aborted error. Ownership of the * native acceptor 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 boost::asio::error::operation_not_supported on * these platforms. */ #if defined(BOOST_ASIO_MSVC) && (BOOST_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(boost::system::error_code& ec) { return impl_.get_service().release(impl_.get_implementation(), ec); } /// Get the native acceptor representation. /** * This function may be used to obtain the underlying representation of the * acceptor. This is intended to allow access to native acceptor 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 acceptor. /** * This function causes all outstanding asynchronous connect, send and receive * operations to finish immediately, and the handlers for cancelled operations * will be passed the boost::asio::error::operation_aborted error. * * @throws boost::system::system_error Thrown on failure. */ void cancel() { boost::system::error_code ec; impl_.get_service().cancel(impl_.get_implementation(), ec); boost::asio::detail::throw_error(ec, "cancel"); } /// Cancel all asynchronous operations associated with the acceptor. /** * This function causes all outstanding asynchronous connect, send and receive * operations to finish immediately, and the handlers for cancelled operations * will be passed the boost::asio::error::operation_aborted error. * * @param ec Set to indicate what error occurred, if any. */ BOOST_ASIO_SYNC_OP_VOID cancel(boost::system::error_code& ec) { impl_.get_service().cancel(impl_.get_implementation(), ec); BOOST_ASIO_SYNC_OP_VOID_RETURN(ec); } /// Set an option on the acceptor. /** * This function is used to set an option on the acceptor. * * @param option The new option value to be set on the acceptor. * * @throws boost::system::system_error Thrown on failure. * * @sa SettableSocketOption @n * boost::asio::socket_base::reuse_address * boost::asio::socket_base::enable_connection_aborted * * @par Example * Setting the SOL_SOCKET/SO_REUSEADDR option: * @code * boost::asio::ip::tcp::acceptor acceptor(my_context); * ... * boost::asio::ip::tcp::acceptor::reuse_address option(true); * acceptor.set_option(option); * @endcode */ template <typename SettableSocketOption> void set_option(const SettableSocketOption& option) { boost::system::error_code ec; impl_.get_service().set_option(impl_.get_implementation(), option, ec); boost::asio::detail::throw_error(ec, "set_option"); } /// Set an option on the acceptor. /** * This function is used to set an option on the acceptor. * * @param option The new option value to be set on the acceptor. * * @param ec Set to indicate what error occurred, if any. * * @sa SettableSocketOption @n * boost::asio::socket_base::reuse_address * boost::asio::socket_base::enable_connection_aborted * * @par Example * Setting the SOL_SOCKET/SO_REUSEADDR option: * @code * boost::asio::ip::tcp::acceptor acceptor(my_context); * ... * boost::asio::ip::tcp::acceptor::reuse_address option(true); * boost::system::error_code ec; * acceptor.set_option(option, ec); * if (ec) * { * // An error occurred. * } * @endcode */ template <typename SettableSocketOption> BOOST_ASIO_SYNC_OP_VOID set_option(const SettableSocketOption& option, boost::system::error_code& ec) { impl_.get_service().set_option(impl_.get_implementation(), option, ec); BOOST_ASIO_SYNC_OP_VOID_RETURN(ec); } /// Get an option from the acceptor. /** * This function is used to get the current value of an option on the * acceptor. * * @param option The option value to be obtained from the acceptor. * * @throws boost::system::system_error Thrown on failure. * * @sa GettableSocketOption @n * boost::asio::socket_base::reuse_address * * @par Example * Getting the value of the SOL_SOCKET/SO_REUSEADDR option: * @code * boost::asio::ip::tcp::acceptor acceptor(my_context); * ... * boost::asio::ip::tcp::acceptor::reuse_address option; * acceptor.get_option(option); * bool is_set = option.get(); * @endcode */ template <typename GettableSocketOption> void get_option(GettableSocketOption& option) const { boost::system::error_code ec; impl_.get_service().get_option(impl_.get_implementation(), option, ec); boost::asio::detail::throw_error(ec, "get_option"); } /// Get an option from the acceptor. /** * This function is used to get the current value of an option on the * acceptor. * * @param option The option value to be obtained from the acceptor. * * @param ec Set to indicate what error occurred, if any. * * @sa GettableSocketOption @n * boost::asio::socket_base::reuse_address * * @par Example * Getting the value of the SOL_SOCKET/SO_REUSEADDR option: * @code * boost::asio::ip::tcp::acceptor acceptor(my_context); * ... * boost::asio::ip::tcp::acceptor::reuse_address option; * boost::system::error_code ec; * acceptor.get_option(option, ec); * if (ec) * { * // An error occurred. * } * bool is_set = option.get(); * @endcode */ template <typename GettableSocketOption> BOOST_ASIO_SYNC_OP_VOID get_option(GettableSocketOption& option, boost::system::error_code& ec) const { impl_.get_service().get_option(impl_.get_implementation(), option, ec); BOOST_ASIO_SYNC_OP_VOID_RETURN(ec); } /// Perform an IO control command on the acceptor. /** * This function is used to execute an IO control command on the acceptor. * * @param command The IO control command to be performed on the acceptor. * * @throws boost::system::system_error Thrown on failure. * * @sa IoControlCommand @n * boost::asio::socket_base::non_blocking_io * * @par Example * Getting the number of bytes ready to read: * @code * boost::asio::ip::tcp::acceptor acceptor(my_context); * ... * boost::asio::ip::tcp::acceptor::non_blocking_io command(true); * socket.io_control(command); * @endcode */ template <typename IoControlCommand> void io_control(IoControlCommand& command) { boost::system::error_code ec; impl_.get_service().io_control(impl_.get_implementation(), command, ec); boost::asio::detail::throw_error(ec, "io_control"); } /// Perform an IO control command on the acceptor. /** * This function is used to execute an IO control command on the acceptor. * * @param command The IO control command to be performed on the acceptor. * * @param ec Set to indicate what error occurred, if any. * * @sa IoControlCommand @n * boost::asio::socket_base::non_blocking_io * * @par Example * Getting the number of bytes ready to read: * @code * boost::asio::ip::tcp::acceptor acceptor(my_context); * ... * boost::asio::ip::tcp::acceptor::non_blocking_io command(true); * boost::system::error_code ec; * socket.io_control(command, ec); * if (ec) * { * // An error occurred. * } * @endcode */ template <typename IoControlCommand> BOOST_ASIO_SYNC_OP_VOID io_control(IoControlCommand& command, boost::system::error_code& ec) { impl_.get_service().io_control(impl_.get_implementation(), command, ec); BOOST_ASIO_SYNC_OP_VOID_RETURN(ec); } /// Gets the non-blocking mode of the acceptor. /** * @returns @c true if the acceptor's synchronous operations will fail with * boost::asio::error::would_block if they are unable to perform the requested * operation immediately. If @c false, synchronous operations will block * until complete. * * @note The non-blocking mode has no effect on the behaviour of asynchronous * operations. Asynchronous operations will never fail with the error * boost::asio::error::would_block. */ bool non_blocking() const { return impl_.get_service().non_blocking(impl_.get_implementation()); } /// Sets the non-blocking mode of the acceptor. /** * @param mode If @c true, the acceptor's synchronous operations will fail * with boost::asio::error::would_block if they are unable to perform the * requested operation immediately. If @c false, synchronous operations will * block until complete. * * @throws boost::system::system_error Thrown on failure. * * @note The non-blocking mode has no effect on the behaviour of asynchronous * operations. Asynchronous operations will never fail with the error * boost::asio::error::would_block. */ void non_blocking(bool mode) { boost::system::error_code ec; impl_.get_service().non_blocking(impl_.get_implementation(), mode, ec); boost::asio::detail::throw_error(ec, "non_blocking"); } /// Sets the non-blocking mode of the acceptor. /** * @param mode If @c true, the acceptor's synchronous operations will fail * with boost::asio::error::would_block if they are unable to perform the * requested operation immediately. If @c false, synchronous operations will * block until complete. * * @param ec Set to indicate what error occurred, if any. * * @note The non-blocking mode has no effect on the behaviour of asynchronous * operations. Asynchronous operations will never fail with the error * boost::asio::error::would_block. */ BOOST_ASIO_SYNC_OP_VOID non_blocking( bool mode, boost::system::error_code& ec) { impl_.get_service().non_blocking(impl_.get_implementation(), mode, ec); BOOST_ASIO_SYNC_OP_VOID_RETURN(ec); } /// Gets the non-blocking mode of the native acceptor implementation. /** * This function is used to retrieve the non-blocking mode of the underlying * native acceptor. This mode has no effect on the behaviour of the acceptor * object's synchronous operations. * * @returns @c true if the underlying acceptor is in non-blocking mode and * direct system calls may fail with boost::asio::error::would_block (or the * equivalent system error). * * @note The current non-blocking mode is cached by the acceptor object. * Consequently, the return value may be incorrect if the non-blocking mode * was set directly on the native acceptor. */ bool native_non_blocking() const { return impl_.get_service().native_non_blocking(impl_.get_implementation()); } /// Sets the non-blocking mode of the native acceptor implementation. /** * This function is used to modify the non-blocking mode of the underlying * native acceptor. It has no effect on the behaviour of the acceptor object's * synchronous operations. * * @param mode If @c true, the underlying acceptor is put into non-blocking * mode and direct system calls may fail with boost::asio::error::would_block * (or the equivalent system error). * * @throws boost::system::system_error Thrown on failure. If the @c mode is * @c false, but the current value of @c non_blocking() is @c true, this * function fails with boost::asio::error::invalid_argument, as the * combination does not make sense. */ void native_non_blocking(bool mode) { boost::system::error_code ec; impl_.get_service().native_non_blocking( impl_.get_implementation(), mode, ec); boost::asio::detail::throw_error(ec, "native_non_blocking"); } /// Sets the non-blocking mode of the native acceptor implementation. /** * This function is used to modify the non-blocking mode of the underlying * native acceptor. It has no effect on the behaviour of the acceptor object's * synchronous operations. * * @param mode If @c true, the underlying acceptor is put into non-blocking * mode and direct system calls may fail with boost::asio::error::would_block * (or the equivalent system error). * * @param ec Set to indicate what error occurred, if any. If the @c mode is * @c false, but the current value of @c non_blocking() is @c true, this * function fails with boost::asio::error::invalid_argument, as the * combination does not make sense. */ BOOST_ASIO_SYNC_OP_VOID native_non_blocking( bool mode, boost::system::error_code& ec) { impl_.get_service().native_non_blocking( impl_.get_implementation(), mode, ec); BOOST_ASIO_SYNC_OP_VOID_RETURN(ec); } /// Get the local endpoint of the acceptor. /** * This function is used to obtain the locally bound endpoint of the acceptor. * * @returns An object that represents the local endpoint of the acceptor. * * @throws boost::system::system_error Thrown on failure. * * @par Example * @code * boost::asio::ip::tcp::acceptor acceptor(my_context); * ... * boost::asio::ip::tcp::endpoint endpoint = acceptor.local_endpoint(); * @endcode */ endpoint_type local_endpoint() const { boost::system::error_code ec; endpoint_type ep = impl_.get_service().local_endpoint( impl_.get_implementation(), ec); boost::asio::detail::throw_error(ec, "local_endpoint"); return ep; } /// Get the local endpoint of the acceptor. /** * This function is used to obtain the locally bound endpoint of the acceptor. * * @param ec Set to indicate what error occurred, if any. * * @returns An object that represents the local endpoint of the acceptor. * Returns a default-constructed endpoint object if an error occurred and the * error handler did not throw an exception. * * @par Example * @code * boost::asio::ip::tcp::acceptor acceptor(my_context); * ... * boost::system::error_code ec; * boost::asio::ip::tcp::endpoint endpoint = acceptor.local_endpoint(ec); * if (ec) * { * // An error occurred. * } * @endcode */ endpoint_type local_endpoint(boost::system::error_code& ec) const { return impl_.get_service().local_endpoint(impl_.get_implementation(), ec); } /// Wait for the acceptor to become ready to read, ready to write, or to have /// pending error conditions. /** * This function is used to perform a blocking wait for an acceptor to enter * a ready to read, write or error condition state. * * @param w Specifies the desired acceptor state. * * @par Example * Waiting for an acceptor to become readable. * @code * boost::asio::ip::tcp::acceptor acceptor(my_context); * ... * acceptor.wait(boost::asio::ip::tcp::acceptor::wait_read); * @endcode */ void wait(wait_type w) { boost::system::error_code ec; impl_.get_service().wait(impl_.get_implementation(), w, ec); boost::asio::detail::throw_error(ec, "wait"); } /// Wait for the acceptor to become ready to read, ready to write, or to have /// pending error conditions. /** * This function is used to perform a blocking wait for an acceptor to enter * a ready to read, write or error condition state. * * @param w Specifies the desired acceptor state. * * @param ec Set to indicate what error occurred, if any. * * @par Example * Waiting for an acceptor to become readable. * @code * boost::asio::ip::tcp::acceptor acceptor(my_context); * ... * boost::system::error_code ec; * acceptor.wait(boost::asio::ip::tcp::acceptor::wait_read, ec); * @endcode */ BOOST_ASIO_SYNC_OP_VOID wait(wait_type w, boost::system::error_code& ec) { impl_.get_service().wait(impl_.get_implementation(), w, ec); BOOST_ASIO_SYNC_OP_VOID_RETURN(ec); } /// Asynchronously wait for the acceptor to become ready to read, ready to /// write, or to have pending error conditions. /** * This function is used to perform an asynchronous wait for an acceptor to * enter a ready to read, write or error condition state. It is an initiating * function for an @ref asynchronous_operation, and always returns * immediately. * * @param w Specifies the desired acceptor state. * * @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 boost::system::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 boost::asio::post(). * * @par Completion Signature * @code void(boost::system::error_code) @endcode * * @par Example * @code * void wait_handler(const boost::system::error_code& error) * { * if (!error) * { * // Wait succeeded. * } * } * * ... * * boost::asio::ip::tcp::acceptor acceptor(my_context); * ... * acceptor.async_wait( * boost::asio::ip::tcp::acceptor::wait_read, * wait_handler); * @endcode * * @par Per-Operation Cancellation * On POSIX or Windows operating systems, this asynchronous operation supports * cancellation for the following boost::asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * @li @c cancellation_type::total */ template < BOOST_ASIO_COMPLETION_TOKEN_FOR(void (boost::system::error_code)) WaitToken = default_completion_token_t<executor_type>> auto async_wait(wait_type w, WaitToken&& token = default_completion_token_t<executor_type>()) -> decltype( async_initiate<WaitToken, void (boost::system::error_code)>( declval<initiate_async_wait>(), token, w)) { return async_initiate<WaitToken, void (boost::system::error_code)>( initiate_async_wait(this), token, w); } #if !defined(BOOST_ASIO_NO_EXTENSIONS) /// Accept a new connection. /** * This function is used to accept a new connection from a peer into the * given socket. The function call will block until a new connection has been * accepted successfully or an error occurs. * * @param peer The socket into which the new connection will be accepted. * * @throws boost::system::system_error Thrown on failure. * * @par Example * @code * boost::asio::ip::tcp::acceptor acceptor(my_context); * ... * boost::asio::ip::tcp::socket socket(my_context); * acceptor.accept(socket); * @endcode */ template <typename Protocol1, typename Executor1> void accept(basic_socket<Protocol1, Executor1>& peer, constraint_t< is_convertible<Protocol, Protocol1>::value > = 0) { boost::system::error_code ec; impl_.get_service().accept(impl_.get_implementation(), peer, static_cast<endpoint_type*>(0), ec); boost::asio::detail::throw_error(ec, "accept"); } /// Accept a new connection. /** * This function is used to accept a new connection from a peer into the * given socket. The function call will block until a new connection has been * accepted successfully or an error occurs. * * @param peer The socket into which the new connection will be accepted. * * @param ec Set to indicate what error occurred, if any. * * @par Example * @code * boost::asio::ip::tcp::acceptor acceptor(my_context); * ... * boost::asio::ip::tcp::socket socket(my_context); * boost::system::error_code ec; * acceptor.accept(socket, ec); * if (ec) * { * // An error occurred. * } * @endcode */ template <typename Protocol1, typename Executor1> BOOST_ASIO_SYNC_OP_VOID accept( basic_socket<Protocol1, Executor1>& peer, boost::system::error_code& ec, constraint_t< is_convertible<Protocol, Protocol1>::value > = 0) { impl_.get_service().accept(impl_.get_implementation(), peer, static_cast<endpoint_type*>(0), ec); BOOST_ASIO_SYNC_OP_VOID_RETURN(ec); } /// Start an asynchronous accept. /** * This function is used to asynchronously accept a new connection into a * socket, and additionally obtain the endpoint of the remote peer. It is an * initiating function for an @ref asynchronous_operation, and always returns * immediately. * * @param peer The socket into which the new connection will be accepted. * Ownership of the peer 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 accept 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 boost::system::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 boost::asio::post(). * * @par Completion Signature * @code void(boost::system::error_code) @endcode * * @par Example * @code * void accept_handler(const boost::system::error_code& error) * { * if (!error) * { * // Accept succeeded. * } * } * * ... * * boost::asio::ip::tcp::acceptor acceptor(my_context); * ... * boost::asio::ip::tcp::socket socket(my_context); * acceptor.async_accept(socket, accept_handler); * @endcode * * @par Per-Operation Cancellation * On POSIX or Windows operating systems, this asynchronous operation supports * cancellation for the following boost::asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * @li @c cancellation_type::total */ template <typename Protocol1, typename Executor1, BOOST_ASIO_COMPLETION_TOKEN_FOR(void (boost::system::error_code)) AcceptToken = default_completion_token_t<executor_type>> auto async_accept(basic_socket<Protocol1, Executor1>& peer, AcceptToken&& token = default_completion_token_t<executor_type>(), constraint_t< is_convertible<Protocol, Protocol1>::value > = 0) -> decltype( async_initiate<AcceptToken, void (boost::system::error_code)>( declval<initiate_async_accept>(), token, &peer, static_cast<endpoint_type*>(0))) { return async_initiate<AcceptToken, void (boost::system::error_code)>( initiate_async_accept(this), token, &peer, static_cast<endpoint_type*>(0)); } /// Accept a new connection and obtain the endpoint of the peer /** * This function is used to accept a new connection from a peer into the * given socket, and additionally provide the endpoint of the remote peer. * The function call will block until a new connection has been accepted * successfully or an error occurs. * * @param peer The socket into which the new connection will be accepted. * * @param peer_endpoint An endpoint object which will receive the endpoint of * the remote peer. * * @throws boost::system::system_error Thrown on failure. * * @par Example * @code * boost::asio::ip::tcp::acceptor acceptor(my_context); * ... * boost::asio::ip::tcp::socket socket(my_context); * boost::asio::ip::tcp::endpoint endpoint; * acceptor.accept(socket, endpoint); * @endcode */ template <typename Executor1> void accept(basic_socket<protocol_type, Executor1>& peer, endpoint_type& peer_endpoint) { boost::system::error_code ec; impl_.get_service().accept(impl_.get_implementation(), peer, &peer_endpoint, ec); boost::asio::detail::throw_error(ec, "accept"); } /// Accept a new connection and obtain the endpoint of the peer /** * This function is used to accept a new connection from a peer into the * given socket, and additionally provide the endpoint of the remote peer. * The function call will block until a new connection has been accepted * successfully or an error occurs. * * @param peer The socket into which the new connection will be accepted. * * @param peer_endpoint An endpoint object which will receive the endpoint of * the remote peer. * * @param ec Set to indicate what error occurred, if any. * * @par Example * @code * boost::asio::ip::tcp::acceptor acceptor(my_context); * ... * boost::asio::ip::tcp::socket socket(my_context); * boost::asio::ip::tcp::endpoint endpoint; * boost::system::error_code ec; * acceptor.accept(socket, endpoint, ec); * if (ec) * { * // An error occurred. * } * @endcode */ template <typename Executor1> BOOST_ASIO_SYNC_OP_VOID accept(basic_socket<protocol_type, Executor1>& peer, endpoint_type& peer_endpoint, boost::system::error_code& ec) { impl_.get_service().accept( impl_.get_implementation(), peer, &peer_endpoint, ec); BOOST_ASIO_SYNC_OP_VOID_RETURN(ec); } /// Start an asynchronous accept. /** * This function is used to asynchronously accept a new connection into a * socket, and additionally obtain the endpoint of the remote peer. It is an * initiating function for an @ref asynchronous_operation, and always returns * immediately. * * @param peer The socket into which the new connection will be accepted. * Ownership of the peer object is retained by the caller, which must * guarantee that it is valid until the completion handler is called. * * @param peer_endpoint An endpoint object into which the endpoint of the * remote peer will be written. Ownership of the peer_endpoint object is * retained by the caller, which must guarantee that it is valid until the * handler is called. * * @param token The @ref completion_token that will be used to produce a * completion handler, which will be called when the accept 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 boost::system::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 boost::asio::post(). * * @par Completion Signature * @code void(boost::system::error_code) @endcode * * @par Per-Operation Cancellation * On POSIX or Windows operating systems, this asynchronous operation supports * cancellation for the following boost::asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * @li @c cancellation_type::total */ template <typename Executor1, BOOST_ASIO_COMPLETION_TOKEN_FOR(void (boost::system::error_code)) AcceptToken = default_completion_token_t<executor_type>> auto async_accept(basic_socket<protocol_type, Executor1>& peer, endpoint_type& peer_endpoint, AcceptToken&& token = default_completion_token_t<executor_type>()) -> decltype( async_initiate<AcceptToken, void (boost::system::error_code)>( declval<initiate_async_accept>(), token, &peer, &peer_endpoint)) { return async_initiate<AcceptToken, void (boost::system::error_code)>( initiate_async_accept(this), token, &peer, &peer_endpoint); } #endif // !defined(BOOST_ASIO_NO_EXTENSIONS) /// Accept a new connection. /** * This function is used to accept a new connection from a peer. The function * call will block until a new connection has been accepted successfully or * an error occurs. * * This overload requires that the Protocol template parameter satisfy the * AcceptableProtocol type requirements. * * @returns A socket object representing the newly accepted connection. * * @throws boost::system::system_error Thrown on failure. * * @par Example * @code * boost::asio::ip::tcp::acceptor acceptor(my_context); * ... * boost::asio::ip::tcp::socket socket(acceptor.accept()); * @endcode */ typename Protocol::socket::template rebind_executor<executor_type>::other accept() { boost::system::error_code ec; typename Protocol::socket::template rebind_executor< executor_type>::other peer(impl_.get_executor()); impl_.get_service().accept(impl_.get_implementation(), peer, 0, ec); boost::asio::detail::throw_error(ec, "accept"); return peer; } /// Accept a new connection. /** * This function is used to accept a new connection from a peer. The function * call will block until a new connection has been accepted successfully or * an error occurs. * * This overload requires that the Protocol template parameter satisfy the * AcceptableProtocol type requirements. * * @param ec Set to indicate what error occurred, if any. * * @returns On success, a socket object representing the newly accepted * connection. On error, a socket object where is_open() is false. * * @par Example * @code * boost::asio::ip::tcp::acceptor acceptor(my_context); * ... * boost::asio::ip::tcp::socket socket(acceptor.accept(ec)); * if (ec) * { * // An error occurred. * } * @endcode */ typename Protocol::socket::template rebind_executor<executor_type>::other accept(boost::system::error_code& ec) { typename Protocol::socket::template rebind_executor< executor_type>::other peer(impl_.get_executor()); impl_.get_service().accept(impl_.get_implementation(), peer, 0, ec); return peer; } /// Start an asynchronous accept. /** * This function is used to asynchronously accept a new connection. It is an * initiating function for an @ref asynchronous_operation, and always returns * immediately. * * This overload requires that the Protocol template parameter satisfy the * AcceptableProtocol type requirements. * * @param token The @ref completion_token that will be used to produce a * completion handler, which will be called when the accept 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 boost::system::error_code& error, * * // On success, the newly accepted socket. * typename Protocol::socket::template * rebind_executor<executor_type>::other peer * ); @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 boost::asio::post(). * * @par Completion Signature * @code void(boost::system::error_code, * typename Protocol::socket::template * rebind_executor<executor_type>::other)) @endcode * * @par Example * @code * void accept_handler(const boost::system::error_code& error, * boost::asio::ip::tcp::socket peer) * { * if (!error) * { * // Accept succeeded. * } * } * * ... * * boost::asio::ip::tcp::acceptor acceptor(my_context); * ... * acceptor.async_accept(accept_handler); * @endcode * * @par Per-Operation Cancellation * On POSIX or Windows operating systems, this asynchronous operation supports * cancellation for the following boost::asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * @li @c cancellation_type::total */ template < BOOST_ASIO_COMPLETION_TOKEN_FOR(void (boost::system::error_code, typename Protocol::socket::template rebind_executor< executor_type>::other)) MoveAcceptToken = default_completion_token_t<executor_type>> auto async_accept( MoveAcceptToken&& token = default_completion_token_t<executor_type>()) -> decltype( async_initiate<MoveAcceptToken, void (boost::system::error_code, typename Protocol::socket::template rebind_executor<executor_type>::other)>( declval<initiate_async_move_accept>(), token, declval<const executor_type&>(), static_cast<endpoint_type*>(0), static_cast<typename Protocol::socket::template rebind_executor<executor_type>::other*>(0))) { return async_initiate<MoveAcceptToken, void (boost::system::error_code, typename Protocol::socket::template rebind_executor<executor_type>::other)>( initiate_async_move_accept(this), token, impl_.get_executor(), static_cast<endpoint_type*>(0), static_cast<typename Protocol::socket::template rebind_executor<executor_type>::other*>(0)); } /// Accept a new connection. /** * This function is used to accept a new connection from a peer. The function * call will block until a new connection has been accepted successfully or * an error occurs. * * This overload requires that the Protocol template parameter satisfy the * AcceptableProtocol type requirements. * * @param ex The I/O executor object to be used for the newly * accepted socket. * * @returns A socket object representing the newly accepted connection. * * @throws boost::system::system_error Thrown on failure. * * @par Example * @code * boost::asio::ip::tcp::acceptor acceptor(my_context); * ... * boost::asio::ip::tcp::socket socket(acceptor.accept()); * @endcode */ template <typename Executor1> typename Protocol::socket::template rebind_executor<Executor1>::other accept(const Executor1& ex, constraint_t< is_executor<Executor1>::value || execution::is_executor<Executor1>::value > = 0) { boost::system::error_code ec; typename Protocol::socket::template rebind_executor<Executor1>::other peer(ex); impl_.get_service().accept(impl_.get_implementation(), peer, 0, ec); boost::asio::detail::throw_error(ec, "accept"); return peer; } /// Accept a new connection. /** * This function is used to accept a new connection from a peer. The function * call will block until a new connection has been accepted successfully or * an error occurs. * * This overload requires that the Protocol template parameter satisfy the * AcceptableProtocol type requirements. * * @param context The I/O execution context object to be used for the newly * accepted socket. * * @returns A socket object representing the newly accepted connection. * * @throws boost::system::system_error Thrown on failure. * * @par Example * @code * boost::asio::ip::tcp::acceptor acceptor(my_context); * ... * boost::asio::ip::tcp::socket socket(acceptor.accept()); * @endcode */ template <typename ExecutionContext> typename Protocol::socket::template rebind_executor< typename ExecutionContext::executor_type>::other accept(ExecutionContext& context, constraint_t< is_convertible<ExecutionContext&, execution_context&>::value > = 0) { boost::system::error_code ec; typename Protocol::socket::template rebind_executor< typename ExecutionContext::executor_type>::other peer(context); impl_.get_service().accept(impl_.get_implementation(), peer, 0, ec); boost::asio::detail::throw_error(ec, "accept"); return peer; } /// Accept a new connection. /** * This function is used to accept a new connection from a peer. The function * call will block until a new connection has been accepted successfully or * an error occurs. * * This overload requires that the Protocol template parameter satisfy the * AcceptableProtocol type requirements. * * @param ex The I/O executor object to be used for the newly accepted * socket. * * @param ec Set to indicate what error occurred, if any. * * @returns On success, a socket object representing the newly accepted * connection. On error, a socket object where is_open() is false. * * @par Example * @code * boost::asio::ip::tcp::acceptor acceptor(my_context); * ... * boost::asio::ip::tcp::socket socket(acceptor.accept(my_context2, ec)); * if (ec) * { * // An error occurred. * } * @endcode */ template <typename Executor1> typename Protocol::socket::template rebind_executor<Executor1>::other accept(const Executor1& ex, boost::system::error_code& ec, constraint_t< is_executor<Executor1>::value || execution::is_executor<Executor1>::value > = 0) { typename Protocol::socket::template rebind_executor<Executor1>::other peer(ex); impl_.get_service().accept(impl_.get_implementation(), peer, 0, ec); return peer; } /// Accept a new connection. /** * This function is used to accept a new connection from a peer. The function * call will block until a new connection has been accepted successfully or * an error occurs. * * This overload requires that the Protocol template parameter satisfy the * AcceptableProtocol type requirements. * * @param context The I/O execution context object to be used for the newly * accepted socket. * * @param ec Set to indicate what error occurred, if any. * * @returns On success, a socket object representing the newly accepted * connection. On error, a socket object where is_open() is false. * * @par Example * @code * boost::asio::ip::tcp::acceptor acceptor(my_context); * ... * boost::asio::ip::tcp::socket socket(acceptor.accept(my_context2, ec)); * if (ec) * { * // An error occurred. * } * @endcode */ template <typename ExecutionContext> typename Protocol::socket::template rebind_executor< typename ExecutionContext::executor_type>::other accept(ExecutionContext& context, boost::system::error_code& ec, constraint_t< is_convertible<ExecutionContext&, execution_context&>::value > = 0) { typename Protocol::socket::template rebind_executor< typename ExecutionContext::executor_type>::other peer(context); impl_.get_service().accept(impl_.get_implementation(), peer, 0, ec); return peer; } /// Start an asynchronous accept. /** * This function is used to asynchronously accept a new connection. It is an * initiating function for an @ref asynchronous_operation, and always returns * immediately. * * This overload requires that the Protocol template parameter satisfy the * AcceptableProtocol type requirements. * * @param ex The I/O executor object to be used for the newly accepted * socket. * * @param token The @ref completion_token that will be used to produce a * completion handler, which will be called when the accept 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 boost::system::error_code& error, * * // On success, the newly accepted socket. * typename Protocol::socket::template rebind_executor< * Executor1>::other peer * ); @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 boost::asio::post(). * * @par Completion Signature * @code void(boost::system::error_code, * typename Protocol::socket::template rebind_executor< * Executor1>::other)) @endcode * * @par Example * @code * void accept_handler(const boost::system::error_code& error, * boost::asio::ip::tcp::socket peer) * { * if (!error) * { * // Accept succeeded. * } * } * * ... * * boost::asio::ip::tcp::acceptor acceptor(my_context); * ... * acceptor.async_accept(my_context2, accept_handler); * @endcode * * @par Per-Operation Cancellation * On POSIX or Windows operating systems, this asynchronous operation supports * cancellation for the following boost::asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * @li @c cancellation_type::total */ template <typename Executor1, BOOST_ASIO_COMPLETION_TOKEN_FOR(void (boost::system::error_code, typename Protocol::socket::template rebind_executor< constraint_t<is_executor<Executor1>::value || execution::is_executor<Executor1>::value, Executor1>>::other)) MoveAcceptToken = default_completion_token_t<executor_type>> auto async_accept(const Executor1& ex, MoveAcceptToken&& token = default_completion_token_t<executor_type>(), constraint_t< is_executor<Executor1>::value || execution::is_executor<Executor1>::value > = 0) -> decltype( async_initiate<MoveAcceptToken, void (boost::system::error_code, typename Protocol::socket::template rebind_executor< Executor1>::other)>( declval<initiate_async_move_accept>(), token, ex, static_cast<endpoint_type*>(0), static_cast<typename Protocol::socket::template rebind_executor<Executor1>::other*>(0))) { return async_initiate<MoveAcceptToken, void (boost::system::error_code, typename Protocol::socket::template rebind_executor< Executor1>::other)>( initiate_async_move_accept(this), token, ex, static_cast<endpoint_type*>(0), static_cast<typename Protocol::socket::template rebind_executor<Executor1>::other*>(0)); } /// Start an asynchronous accept. /** * This function is used to asynchronously accept a new connection. It is an * initiating function for an @ref asynchronous_operation, and always returns * immediately. * * This overload requires that the Protocol template parameter satisfy the * AcceptableProtocol type requirements. * * @param context The I/O execution context object to be used for the newly * accepted socket. * * @param token The @ref completion_token that will be used to produce a * completion handler, which will be called when the accept 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 boost::system::error_code& error, * * // On success, the newly accepted socket. * typename Protocol::socket::template rebind_executor< * typename ExecutionContext::executor_type>::other peer * ); @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 boost::asio::post(). * * @par Completion Signature * @code void(boost::system::error_code, * typename Protocol::socket::template rebind_executor< * typename ExecutionContext::executor_type>::other)) @endcode * * @par Example * @code * void accept_handler(const boost::system::error_code& error, * boost::asio::ip::tcp::socket peer) * { * if (!error) * { * // Accept succeeded. * } * } * * ... * * boost::asio::ip::tcp::acceptor acceptor(my_context); * ... * acceptor.async_accept(my_context2, accept_handler); * @endcode * * @par Per-Operation Cancellation * On POSIX or Windows operating systems, this asynchronous operation supports * cancellation for the following boost::asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * @li @c cancellation_type::total */ template <typename ExecutionContext, BOOST_ASIO_COMPLETION_TOKEN_FOR(void (boost::system::error_code, typename Protocol::socket::template rebind_executor< typename ExecutionContext::executor_type>::other)) MoveAcceptToken = default_completion_token_t<executor_type>> auto async_accept(ExecutionContext& context, MoveAcceptToken&& token = default_completion_token_t<executor_type>(), constraint_t< is_convertible<ExecutionContext&, execution_context&>::value > = 0) -> decltype( async_initiate<MoveAcceptToken, void (boost::system::error_code, typename Protocol::socket::template rebind_executor< typename ExecutionContext::executor_type>::other)>( declval<initiate_async_move_accept>(), token, context.get_executor(), static_cast<endpoint_type*>(0), static_cast<typename Protocol::socket::template rebind_executor< typename ExecutionContext::executor_type>::other*>(0))) { return async_initiate<MoveAcceptToken, void (boost::system::error_code, typename Protocol::socket::template rebind_executor< typename ExecutionContext::executor_type>::other)>( initiate_async_move_accept(this), token, context.get_executor(), static_cast<endpoint_type*>(0), static_cast<typename Protocol::socket::template rebind_executor< typename ExecutionContext::executor_type>::other*>(0)); } /// Accept a new connection. /** * This function is used to accept a new connection from a peer. The function * call will block until a new connection has been accepted successfully or * an error occurs. * * This overload requires that the Protocol template parameter satisfy the * AcceptableProtocol type requirements. * * @param peer_endpoint An endpoint object into which the endpoint of the * remote peer will be written. * * @returns A socket object representing the newly accepted connection. * * @throws boost::system::system_error Thrown on failure. * * @par Example * @code * boost::asio::ip::tcp::acceptor acceptor(my_context); * ... * boost::asio::ip::tcp::endpoint endpoint; * boost::asio::ip::tcp::socket socket(acceptor.accept(endpoint)); * @endcode */ typename Protocol::socket::template rebind_executor<executor_type>::other accept(endpoint_type& peer_endpoint) { boost::system::error_code ec; typename Protocol::socket::template rebind_executor< executor_type>::other peer(impl_.get_executor()); impl_.get_service().accept(impl_.get_implementation(), peer, &peer_endpoint, ec); boost::asio::detail::throw_error(ec, "accept"); return peer; } /// Accept a new connection. /** * This function is used to accept a new connection from a peer. The function * call will block until a new connection has been accepted successfully or * an error occurs. * * This overload requires that the Protocol template parameter satisfy the * AcceptableProtocol type requirements. * * @param peer_endpoint An endpoint object into which the endpoint of the * remote peer will be written. * * @param ec Set to indicate what error occurred, if any. * * @returns On success, a socket object representing the newly accepted * connection. On error, a socket object where is_open() is false. * * @par Example * @code * boost::asio::ip::tcp::acceptor acceptor(my_context); * ... * boost::asio::ip::tcp::endpoint endpoint; * boost::asio::ip::tcp::socket socket(acceptor.accept(endpoint, ec)); * if (ec) * { * // An error occurred. * } * @endcode */ typename Protocol::socket::template rebind_executor<executor_type>::other accept(endpoint_type& peer_endpoint, boost::system::error_code& ec) { typename Protocol::socket::template rebind_executor< executor_type>::other peer(impl_.get_executor()); impl_.get_service().accept(impl_.get_implementation(), peer, &peer_endpoint, ec); return peer; } /// Start an asynchronous accept. /** * This function is used to asynchronously accept a new connection. It is an * initiating function for an @ref asynchronous_operation, and always returns * immediately. * * This overload requires that the Protocol template parameter satisfy the * AcceptableProtocol type requirements. * * @param peer_endpoint An endpoint object into which the endpoint of the * remote peer will be written. Ownership of the peer_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 accept 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 boost::system::error_code& error, * * // On success, the newly accepted socket. * typename Protocol::socket::template * rebind_executor<executor_type>::other peer * ); @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 boost::asio::post(). * * @par Completion Signature * @code void(boost::system::error_code, * typename Protocol::socket::template * rebind_executor<executor_type>::other)) @endcode * * @par Example * @code * void accept_handler(const boost::system::error_code& error, * boost::asio::ip::tcp::socket peer) * { * if (!error) * { * // Accept succeeded. * } * } * * ... * * boost::asio::ip::tcp::acceptor acceptor(my_context); * ... * boost::asio::ip::tcp::endpoint endpoint; * acceptor.async_accept(endpoint, accept_handler); * @endcode * * @par Per-Operation Cancellation * On POSIX or Windows operating systems, this asynchronous operation supports * cancellation for the following boost::asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * @li @c cancellation_type::total */ template < BOOST_ASIO_COMPLETION_TOKEN_FOR(void (boost::system::error_code, typename Protocol::socket::template rebind_executor< executor_type>::other)) MoveAcceptToken = default_completion_token_t<executor_type>> auto async_accept(endpoint_type& peer_endpoint, MoveAcceptToken&& token = default_completion_token_t<executor_type>()) -> decltype( async_initiate<MoveAcceptToken, void (boost::system::error_code, typename Protocol::socket::template rebind_executor<executor_type>::other)>( declval<initiate_async_move_accept>(), token, declval<const executor_type&>(), &peer_endpoint, static_cast<typename Protocol::socket::template rebind_executor<executor_type>::other*>(0))) { return async_initiate<MoveAcceptToken, void (boost::system::error_code, typename Protocol::socket::template rebind_executor<executor_type>::other)>( initiate_async_move_accept(this), token, impl_.get_executor(), &peer_endpoint, static_cast<typename Protocol::socket::template rebind_executor<executor_type>::other*>(0)); } /// Accept a new connection. /** * This function is used to accept a new connection from a peer. The function * call will block until a new connection has been accepted successfully or * an error occurs. * * This overload requires that the Protocol template parameter satisfy the * AcceptableProtocol type requirements. * * @param ex The I/O executor object to be used for the newly accepted * socket. * * @param peer_endpoint An endpoint object into which the endpoint of the * remote peer will be written. * * @returns A socket object representing the newly accepted connection. * * @throws boost::system::system_error Thrown on failure. * * @par Example * @code * boost::asio::ip::tcp::acceptor acceptor(my_context); * ... * boost::asio::ip::tcp::endpoint endpoint; * boost::asio::ip::tcp::socket socket( * acceptor.accept(my_context2, endpoint)); * @endcode */ template <typename Executor1> typename Protocol::socket::template rebind_executor<Executor1>::other accept(const Executor1& ex, endpoint_type& peer_endpoint, constraint_t< is_executor<Executor1>::value || execution::is_executor<Executor1>::value > = 0) { boost::system::error_code ec; typename Protocol::socket::template rebind_executor<Executor1>::other peer(ex); impl_.get_service().accept(impl_.get_implementation(), peer, &peer_endpoint, ec); boost::asio::detail::throw_error(ec, "accept"); return peer; } /// Accept a new connection. /** * This function is used to accept a new connection from a peer. The function * call will block until a new connection has been accepted successfully or * an error occurs. * * This overload requires that the Protocol template parameter satisfy the * AcceptableProtocol type requirements. * * @param context The I/O execution context object to be used for the newly * accepted socket. * * @param peer_endpoint An endpoint object into which the endpoint of the * remote peer will be written. * * @returns A socket object representing the newly accepted connection. * * @throws boost::system::system_error Thrown on failure. * * @par Example * @code * boost::asio::ip::tcp::acceptor acceptor(my_context); * ... * boost::asio::ip::tcp::endpoint endpoint; * boost::asio::ip::tcp::socket socket( * acceptor.accept(my_context2, endpoint)); * @endcode */ template <typename ExecutionContext> typename Protocol::socket::template rebind_executor< typename ExecutionContext::executor_type>::other accept(ExecutionContext& context, endpoint_type& peer_endpoint, constraint_t< is_convertible<ExecutionContext&, execution_context&>::value > = 0) { boost::system::error_code ec; typename Protocol::socket::template rebind_executor< typename ExecutionContext::executor_type>::other peer(context); impl_.get_service().accept(impl_.get_implementation(), peer, &peer_endpoint, ec); boost::asio::detail::throw_error(ec, "accept"); return peer; } /// Accept a new connection. /** * This function is used to accept a new connection from a peer. The function * call will block until a new connection has been accepted successfully or * an error occurs. * * This overload requires that the Protocol template parameter satisfy the * AcceptableProtocol type requirements. * * @param ex The I/O executor object to be used for the newly accepted * socket. * * @param peer_endpoint An endpoint object into which the endpoint of the * remote peer will be written. * * @param ec Set to indicate what error occurred, if any. * * @returns On success, a socket object representing the newly accepted * connection. On error, a socket object where is_open() is false. * * @par Example * @code * boost::asio::ip::tcp::acceptor acceptor(my_context); * ... * boost::asio::ip::tcp::endpoint endpoint; * boost::asio::ip::tcp::socket socket( * acceptor.accept(my_context2, endpoint, ec)); * if (ec) * { * // An error occurred. * } * @endcode */ template <typename Executor1> typename Protocol::socket::template rebind_executor<Executor1>::other accept(const executor_type& ex, endpoint_type& peer_endpoint, boost::system::error_code& ec, constraint_t< is_executor<Executor1>::value || execution::is_executor<Executor1>::value > = 0) { typename Protocol::socket::template rebind_executor<Executor1>::other peer(ex); impl_.get_service().accept(impl_.get_implementation(), peer, &peer_endpoint, ec); return peer; } /// Accept a new connection. /** * This function is used to accept a new connection from a peer. The function * call will block until a new connection has been accepted successfully or * an error occurs. * * This overload requires that the Protocol template parameter satisfy the * AcceptableProtocol type requirements. * * @param context The I/O execution context object to be used for the newly * accepted socket. * * @param peer_endpoint An endpoint object into which the endpoint of the * remote peer will be written. * * @param ec Set to indicate what error occurred, if any. * * @returns On success, a socket object representing the newly accepted * connection. On error, a socket object where is_open() is false. * * @par Example * @code * boost::asio::ip::tcp::acceptor acceptor(my_context); * ... * boost::asio::ip::tcp::endpoint endpoint; * boost::asio::ip::tcp::socket socket( * acceptor.accept(my_context2, endpoint, ec)); * if (ec) * { * // An error occurred. * } * @endcode */ template <typename ExecutionContext> typename Protocol::socket::template rebind_executor< typename ExecutionContext::executor_type>::other accept(ExecutionContext& context, endpoint_type& peer_endpoint, boost::system::error_code& ec, constraint_t< is_convertible<ExecutionContext&, execution_context&>::value > = 0) { typename Protocol::socket::template rebind_executor< typename ExecutionContext::executor_type>::other peer(context); impl_.get_service().accept(impl_.get_implementation(), peer, &peer_endpoint, ec); return peer; } /// Start an asynchronous accept. /** * This function is used to asynchronously accept a new connection. It is an * initiating function for an @ref asynchronous_operation, and always returns * immediately. * * This overload requires that the Protocol template parameter satisfy the * AcceptableProtocol type requirements. * * @param ex The I/O executor object to be used for the newly accepted * socket. * * @param peer_endpoint An endpoint object into which the endpoint of the * remote peer will be written. Ownership of the peer_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 accept 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 boost::system::error_code& error, * * // On success, the newly accepted socket. * typename Protocol::socket::template rebind_executor< * Executor1>::other peer * ); @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 boost::asio::post(). * * @par Completion Signature * @code void(boost::system::error_code, * typename Protocol::socket::template rebind_executor< * Executor1>::other)) @endcode * * @par Example * @code * void accept_handler(const boost::system::error_code& error, * boost::asio::ip::tcp::socket peer) * { * if (!error) * { * // Accept succeeded. * } * } * * ... * * boost::asio::ip::tcp::acceptor acceptor(my_context); * ... * boost::asio::ip::tcp::endpoint endpoint; * acceptor.async_accept(my_context2, endpoint, accept_handler); * @endcode * * @par Per-Operation Cancellation * On POSIX or Windows operating systems, this asynchronous operation supports * cancellation for the following boost::asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * @li @c cancellation_type::total */ template <typename Executor1, BOOST_ASIO_COMPLETION_TOKEN_FOR(void (boost::system::error_code, typename Protocol::socket::template rebind_executor< constraint_t<is_executor<Executor1>::value || execution::is_executor<Executor1>::value, Executor1>>::other)) MoveAcceptToken = default_completion_token_t<executor_type>> auto async_accept(const Executor1& ex, endpoint_type& peer_endpoint, MoveAcceptToken&& token = default_completion_token_t<executor_type>(), constraint_t< is_executor<Executor1>::value || execution::is_executor<Executor1>::value > = 0) -> decltype( async_initiate<MoveAcceptToken, void (boost::system::error_code, typename Protocol::socket::template rebind_executor< Executor1>::other)>( declval<initiate_async_move_accept>(), token, ex, &peer_endpoint, static_cast<typename Protocol::socket::template rebind_executor<Executor1>::other*>(0))) { return async_initiate<MoveAcceptToken, void (boost::system::error_code, typename Protocol::socket::template rebind_executor< Executor1>::other)>( initiate_async_move_accept(this), token, ex, &peer_endpoint, static_cast<typename Protocol::socket::template rebind_executor<Executor1>::other*>(0)); } /// Start an asynchronous accept. /** * This function is used to asynchronously accept a new connection. It is an * initiating function for an @ref asynchronous_operation, and always returns * immediately. * * This overload requires that the Protocol template parameter satisfy the * AcceptableProtocol type requirements. * * @param context The I/O execution context object to be used for the newly * accepted socket. * * @param peer_endpoint An endpoint object into which the endpoint of the * remote peer will be written. Ownership of the peer_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 accept 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 boost::system::error_code& error, * * // On success, the newly accepted socket. * typename Protocol::socket::template rebind_executor< * typename ExecutionContext::executor_type>::other peer * ); @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 boost::asio::post(). * * @par Completion Signature * @code void(boost::system::error_code, * typename Protocol::socket::template rebind_executor< * typename ExecutionContext::executor_type>::other)) @endcode * * @par Example * @code * void accept_handler(const boost::system::error_code& error, * boost::asio::ip::tcp::socket peer) * { * if (!error) * { * // Accept succeeded. * } * } * * ... * * boost::asio::ip::tcp::acceptor acceptor(my_context); * ... * boost::asio::ip::tcp::endpoint endpoint; * acceptor.async_accept(my_context2, endpoint, accept_handler); * @endcode * * @par Per-Operation Cancellation * On POSIX or Windows operating systems, this asynchronous operation supports * cancellation for the following boost::asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * @li @c cancellation_type::total */ template <typename ExecutionContext, BOOST_ASIO_COMPLETION_TOKEN_FOR(void (boost::system::error_code, typename Protocol::socket::template rebind_executor< typename ExecutionContext::executor_type>::other)) MoveAcceptToken = default_completion_token_t<executor_type>> auto async_accept(ExecutionContext& context, endpoint_type& peer_endpoint, MoveAcceptToken&& token = default_completion_token_t<executor_type>(), constraint_t< is_convertible<ExecutionContext&, execution_context&>::value > = 0) -> decltype( async_initiate<MoveAcceptToken, void (boost::system::error_code, typename Protocol::socket::template rebind_executor< typename ExecutionContext::executor_type>::other)>( declval<initiate_async_move_accept>(), token, context.get_executor(), &peer_endpoint, static_cast<typename Protocol::socket::template rebind_executor< typename ExecutionContext::executor_type>::other*>(0))) { return async_initiate<MoveAcceptToken, void (boost::system::error_code, typename Protocol::socket::template rebind_executor< typename ExecutionContext::executor_type>::other)>( initiate_async_move_accept(this), token, context.get_executor(), &peer_endpoint, static_cast<typename Protocol::socket::template rebind_executor< typename ExecutionContext::executor_type>::other*>(0)); } private: // Disallow copying and assignment. basic_socket_acceptor(const basic_socket_acceptor&) = delete; basic_socket_acceptor& operator=( const basic_socket_acceptor&) = delete; class initiate_async_wait { public: typedef Executor executor_type; explicit initiate_async_wait(basic_socket_acceptor* self) : self_(self) { } const executor_type& get_executor() const noexcept { return self_->get_executor(); } template <typename WaitHandler> void operator()(WaitHandler&& handler, wait_type w) 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. BOOST_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(), w, handler2.value, self_->impl_.get_executor()); } private: basic_socket_acceptor* self_; }; class initiate_async_accept { public: typedef Executor executor_type; explicit initiate_async_accept(basic_socket_acceptor* self) : self_(self) { } const executor_type& get_executor() const noexcept { return self_->get_executor(); } template <typename AcceptHandler, typename Protocol1, typename Executor1> void operator()(AcceptHandler&& handler, basic_socket<Protocol1, Executor1>* peer, endpoint_type* peer_endpoint) const { // If you get an error on the following line it means that your handler // does not meet the documented type requirements for a AcceptHandler. BOOST_ASIO_ACCEPT_HANDLER_CHECK(AcceptHandler, handler) type_check; detail::non_const_lvalue<AcceptHandler> handler2(handler); self_->impl_.get_service().async_accept( self_->impl_.get_implementation(), *peer, peer_endpoint, handler2.value, self_->impl_.get_executor()); } private: basic_socket_acceptor* self_; }; class initiate_async_move_accept { public: typedef Executor executor_type; explicit initiate_async_move_accept(basic_socket_acceptor* self) : self_(self) { } const executor_type& get_executor() const noexcept { return self_->get_executor(); } template <typename MoveAcceptHandler, typename Executor1, typename Socket> void operator()(MoveAcceptHandler&& handler, const Executor1& peer_ex, endpoint_type* peer_endpoint, Socket*) const { // If you get an error on the following line it means that your handler // does not meet the documented type requirements for a MoveAcceptHandler. BOOST_ASIO_MOVE_ACCEPT_HANDLER_CHECK( MoveAcceptHandler, handler, Socket) type_check; detail::non_const_lvalue<MoveAcceptHandler> handler2(handler); self_->impl_.get_service().async_move_accept( self_->impl_.get_implementation(), peer_ex, peer_endpoint, handler2.value, self_->impl_.get_executor()); } private: basic_socket_acceptor* self_; }; #if defined(BOOST_ASIO_WINDOWS_RUNTIME) detail::io_object_impl< detail::null_socket_service<Protocol>, Executor> impl_; #elif defined(BOOST_ASIO_HAS_IOCP) detail::io_object_impl< detail::win_iocp_socket_service<Protocol>, Executor> impl_; #elif defined(BOOST_ASIO_HAS_IO_URING_AS_DEFAULT) detail::io_object_impl< detail::io_uring_socket_service<Protocol>, Executor> impl_; #else detail::io_object_impl< detail::reactive_socket_service<Protocol>, Executor> impl_; #endif }; } // namespace asio } // namespace boost #include <boost/asio/detail/pop_options.hpp> #endif // BOOST_ASIO_BASIC_SOCKET_ACCEPTOR_HPP
hpp
asio
data/projects/asio/include/boost/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 BOOST_ASIO_READ_AT_HPP #define BOOST_ASIO_READ_AT_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <boost/asio/detail/config.hpp> #include <cstddef> #include <boost/asio/async_result.hpp> #include <boost/asio/completion_condition.hpp> #include <boost/asio/detail/cstdint.hpp> #include <boost/asio/error.hpp> #if !defined(BOOST_ASIO_NO_EXTENSIONS) # include <boost/asio/basic_streambuf_fwd.hpp> #endif // !defined(BOOST_ASIO_NO_EXTENSIONS) #include <boost/asio/detail/push_options.hpp> namespace boost { namespace asio { namespace detail { template <typename> class initiate_async_read_at; #if !defined(BOOST_ASIO_NO_IOSTREAM) template <typename> class initiate_async_read_at_streambuf; #endif // !defined(BOOST_ASIO_NO_IOSTREAM) } // namespace detail /** * @defgroup read_at boost::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 boost::system::system_error Thrown on failure. * * @par Example * To read into a single data buffer use the @ref buffer function as follows: * @code boost::asio::read_at(d, 42, boost::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 boost::asio::read_at( * d, 42, buffers, * boost::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 boost::asio::read_at(d, 42, * boost::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 boost::asio::read_at( * d, 42, buffers, * boost::asio::transfer_all(), ec); @endcode */ template <typename SyncRandomAccessReadDevice, typename MutableBufferSequence> std::size_t read_at(SyncRandomAccessReadDevice& d, uint64_t offset, const MutableBufferSequence& buffers, boost::system::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 boost::system::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 boost::system::system_error Thrown on failure. * * @par Example * To read into a single data buffer use the @ref buffer function as follows: * @code boost::asio::read_at(d, 42, boost::asio::buffer(data, size), * boost::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); /// 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 boost::system::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, boost::system::error_code& ec); #if !defined(BOOST_ASIO_NO_EXTENSIONS) #if !defined(BOOST_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 boost::system::system_error Thrown on failure. * * @note This overload is equivalent to calling: * @code boost::asio::read_at( * d, 42, b, * boost::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 boost::asio::read_at( * d, 42, b, * boost::asio::transfer_all(), ec); @endcode */ template <typename SyncRandomAccessReadDevice, typename Allocator> std::size_t read_at(SyncRandomAccessReadDevice& d, uint64_t offset, basic_streambuf<Allocator>& b, boost::system::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 boost::system::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 boost::system::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); /// 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 boost::system::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, boost::system::error_code& ec); #endif // !defined(BOOST_ASIO_NO_IOSTREAM) #endif // !defined(BOOST_ASIO_NO_EXTENSIONS) /*@}*/ /** * @defgroup async_read_at boost::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 boost::system::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 boost::asio::post(). * * @par Completion Signature * @code void(boost::system::error_code, std::size_t) @endcode * * @par Example * To read into a single data buffer use the @ref buffer function as follows: * @code * boost::asio::async_read_at(d, 42, boost::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 boost::asio::async_read_at( * d, 42, buffers, * boost::asio::transfer_all(), * handler); @endcode * * @par Per-Operation Cancellation * This asynchronous operation supports cancellation for the following * boost::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, BOOST_ASIO_COMPLETION_TOKEN_FOR(void (boost::system::error_code, std::size_t)) ReadToken = default_completion_token_t< typename AsyncRandomAccessReadDevice::executor_type>> auto async_read_at(AsyncRandomAccessReadDevice& d, uint64_t offset, const MutableBufferSequence& buffers, ReadToken&& token = default_completion_token_t< typename AsyncRandomAccessReadDevice::executor_type>()) -> decltype( async_initiate<ReadToken, void (boost::system::error_code, std::size_t)>( declval<detail::initiate_async_read_at<AsyncRandomAccessReadDevice>>(), 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 boost::system::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 boost::system::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 boost::asio::post(). * * @par Completion Signature * @code void(boost::system::error_code, std::size_t) @endcode * * @par Example * To read into a single data buffer use the @ref buffer function as follows: * @code boost::asio::async_read_at(d, 42, * boost::asio::buffer(data, size), * boost::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 * boost::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, BOOST_ASIO_COMPLETION_TOKEN_FOR(void (boost::system::error_code, std::size_t)) ReadToken = default_completion_token_t< typename AsyncRandomAccessReadDevice::executor_type>> 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>()) -> decltype( async_initiate<ReadToken, void (boost::system::error_code, std::size_t)>( declval<detail::initiate_async_read_at<AsyncRandomAccessReadDevice>>(), token, offset, buffers, static_cast<CompletionCondition&&>(completion_condition))); #if !defined(BOOST_ASIO_NO_EXTENSIONS) #if !defined(BOOST_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 boost::system::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 boost::asio::post(). * * @par Completion Signature * @code void(boost::system::error_code, std::size_t) @endcode * * @note This overload is equivalent to calling: * @code boost::asio::async_read_at( * d, 42, b, * boost::asio::transfer_all(), * handler); @endcode * * @par Per-Operation Cancellation * This asynchronous operation supports cancellation for the following * boost::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, BOOST_ASIO_COMPLETION_TOKEN_FOR(void (boost::system::error_code, std::size_t)) ReadToken = default_completion_token_t< typename AsyncRandomAccessReadDevice::executor_type>> auto async_read_at(AsyncRandomAccessReadDevice& d, uint64_t offset, basic_streambuf<Allocator>& b, ReadToken&& token = default_completion_token_t< typename AsyncRandomAccessReadDevice::executor_type>()) -> decltype( async_initiate<ReadToken, void (boost::system::error_code, std::size_t)>( declval<detail::initiate_async_read_at_streambuf< AsyncRandomAccessReadDevice>>(), 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 boost::system::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 boost::system::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 boost::asio::post(). * * @par Completion Signature * @code void(boost::system::error_code, std::size_t) @endcode * * @par Per-Operation Cancellation * This asynchronous operation supports cancellation for the following * boost::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, BOOST_ASIO_COMPLETION_TOKEN_FOR(void (boost::system::error_code, std::size_t)) ReadToken = default_completion_token_t< typename AsyncRandomAccessReadDevice::executor_type>> 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>()) -> decltype( async_initiate<ReadToken, void (boost::system::error_code, std::size_t)>( declval<detail::initiate_async_read_at_streambuf< AsyncRandomAccessReadDevice>>(), token, offset, &b, static_cast<CompletionCondition&&>(completion_condition))); #endif // !defined(BOOST_ASIO_NO_IOSTREAM) #endif // !defined(BOOST_ASIO_NO_EXTENSIONS) /*@}*/ } // namespace asio } // namespace boost #include <boost/asio/detail/pop_options.hpp> #include <boost/asio/impl/read_at.hpp> #endif // BOOST_ASIO_READ_AT_HPP
hpp