Unnamed: 0
int64 0
0
| repo_id
stringlengths 5
186
| file_path
stringlengths 15
223
| content
stringlengths 1
32.8M
⌀ |
---|---|---|---|
0 | repos/asio/asio/include/asio/ip/detail | repos/asio/asio/include/asio/ip/detail/impl/endpoint.ipp | //
// ip/detail/impl/endpoint.ipp
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef ASIO_IP_DETAIL_IMPL_ENDPOINT_IPP
#define ASIO_IP_DETAIL_IMPL_ENDPOINT_IPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include "asio/detail/config.hpp"
#include <cstring>
#if !defined(ASIO_NO_IOSTREAM)
# include <sstream>
#endif // !defined(ASIO_NO_IOSTREAM)
#include "asio/detail/socket_ops.hpp"
#include "asio/detail/throw_error.hpp"
#include "asio/error.hpp"
#include "asio/ip/detail/endpoint.hpp"
#include "asio/detail/push_options.hpp"
namespace asio {
namespace ip {
namespace detail {
endpoint::endpoint() noexcept
: data_()
{
data_.v4.sin_family = ASIO_OS_DEF(AF_INET);
data_.v4.sin_port = 0;
data_.v4.sin_addr.s_addr = ASIO_OS_DEF(INADDR_ANY);
}
endpoint::endpoint(int family, unsigned short port_num) noexcept
: data_()
{
using namespace std; // For memcpy.
if (family == ASIO_OS_DEF(AF_INET))
{
data_.v4.sin_family = ASIO_OS_DEF(AF_INET);
data_.v4.sin_port =
asio::detail::socket_ops::host_to_network_short(port_num);
data_.v4.sin_addr.s_addr = ASIO_OS_DEF(INADDR_ANY);
}
else
{
data_.v6.sin6_family = ASIO_OS_DEF(AF_INET6);
data_.v6.sin6_port =
asio::detail::socket_ops::host_to_network_short(port_num);
data_.v6.sin6_flowinfo = 0;
data_.v6.sin6_addr.s6_addr[0] = 0; data_.v6.sin6_addr.s6_addr[1] = 0;
data_.v6.sin6_addr.s6_addr[2] = 0; data_.v6.sin6_addr.s6_addr[3] = 0;
data_.v6.sin6_addr.s6_addr[4] = 0; data_.v6.sin6_addr.s6_addr[5] = 0;
data_.v6.sin6_addr.s6_addr[6] = 0; data_.v6.sin6_addr.s6_addr[7] = 0;
data_.v6.sin6_addr.s6_addr[8] = 0; data_.v6.sin6_addr.s6_addr[9] = 0;
data_.v6.sin6_addr.s6_addr[10] = 0; data_.v6.sin6_addr.s6_addr[11] = 0;
data_.v6.sin6_addr.s6_addr[12] = 0; data_.v6.sin6_addr.s6_addr[13] = 0;
data_.v6.sin6_addr.s6_addr[14] = 0; data_.v6.sin6_addr.s6_addr[15] = 0;
data_.v6.sin6_scope_id = 0;
}
}
endpoint::endpoint(const asio::ip::address& addr,
unsigned short port_num) noexcept
: data_()
{
using namespace std; // For memcpy.
if (addr.is_v4())
{
data_.v4.sin_family = ASIO_OS_DEF(AF_INET);
data_.v4.sin_port =
asio::detail::socket_ops::host_to_network_short(port_num);
data_.v4.sin_addr.s_addr =
asio::detail::socket_ops::host_to_network_long(
addr.to_v4().to_uint());
}
else
{
data_.v6.sin6_family = ASIO_OS_DEF(AF_INET6);
data_.v6.sin6_port =
asio::detail::socket_ops::host_to_network_short(port_num);
data_.v6.sin6_flowinfo = 0;
asio::ip::address_v6 v6_addr = addr.to_v6();
asio::ip::address_v6::bytes_type bytes = v6_addr.to_bytes();
memcpy(data_.v6.sin6_addr.s6_addr, bytes.data(), 16);
data_.v6.sin6_scope_id =
static_cast<asio::detail::u_long_type>(
v6_addr.scope_id());
}
}
void endpoint::resize(std::size_t new_size)
{
if (new_size > sizeof(asio::detail::sockaddr_storage_type))
{
asio::error_code ec(asio::error::invalid_argument);
asio::detail::throw_error(ec);
}
}
unsigned short endpoint::port() const noexcept
{
if (is_v4())
{
return asio::detail::socket_ops::network_to_host_short(
data_.v4.sin_port);
}
else
{
return asio::detail::socket_ops::network_to_host_short(
data_.v6.sin6_port);
}
}
void endpoint::port(unsigned short port_num) noexcept
{
if (is_v4())
{
data_.v4.sin_port
= asio::detail::socket_ops::host_to_network_short(port_num);
}
else
{
data_.v6.sin6_port
= asio::detail::socket_ops::host_to_network_short(port_num);
}
}
asio::ip::address endpoint::address() const noexcept
{
using namespace std; // For memcpy.
if (is_v4())
{
return asio::ip::address_v4(
asio::detail::socket_ops::network_to_host_long(
data_.v4.sin_addr.s_addr));
}
else
{
asio::ip::address_v6::bytes_type bytes;
memcpy(bytes.data(), data_.v6.sin6_addr.s6_addr, 16);
return asio::ip::address_v6(bytes, data_.v6.sin6_scope_id);
}
}
void endpoint::address(const asio::ip::address& addr) noexcept
{
endpoint tmp_endpoint(addr, port());
data_ = tmp_endpoint.data_;
}
bool operator==(const endpoint& e1, const endpoint& e2) noexcept
{
return e1.address() == e2.address() && e1.port() == e2.port();
}
bool operator<(const endpoint& e1, const endpoint& e2) noexcept
{
if (e1.address() < e2.address())
return true;
if (e1.address() != e2.address())
return false;
return e1.port() < e2.port();
}
#if !defined(ASIO_NO_IOSTREAM)
std::string endpoint::to_string() const
{
std::ostringstream tmp_os;
tmp_os.imbue(std::locale::classic());
if (is_v4())
tmp_os << address();
else
tmp_os << '[' << address() << ']';
tmp_os << ':' << port();
return tmp_os.str();
}
#endif // !defined(ASIO_NO_IOSTREAM)
} // namespace detail
} // namespace ip
} // namespace asio
#include "asio/detail/pop_options.hpp"
#endif // ASIO_IP_DETAIL_IMPL_ENDPOINT_IPP
|
0 | repos/asio/asio/include/asio/ip | repos/asio/asio/include/asio/ip/impl/address.hpp | //
// ip/impl/address.hpp
// ~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef ASIO_IP_IMPL_ADDRESS_HPP
#define ASIO_IP_IMPL_ADDRESS_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#if !defined(ASIO_NO_IOSTREAM)
#include "asio/detail/throw_error.hpp"
#include "asio/detail/push_options.hpp"
namespace asio {
namespace ip {
#if !defined(ASIO_NO_DEPRECATED)
inline address address::from_string(const char* str)
{
return asio::ip::make_address(str);
}
inline address address::from_string(
const char* str, asio::error_code& ec)
{
return asio::ip::make_address(str, ec);
}
inline address address::from_string(const std::string& str)
{
return asio::ip::make_address(str);
}
inline address address::from_string(
const std::string& str, asio::error_code& ec)
{
return asio::ip::make_address(str, ec);
}
#endif // !defined(ASIO_NO_DEPRECATED)
template <typename Elem, typename Traits>
std::basic_ostream<Elem, Traits>& operator<<(
std::basic_ostream<Elem, Traits>& os, const address& addr)
{
return os << addr.to_string().c_str();
}
} // namespace ip
} // namespace asio
#include "asio/detail/pop_options.hpp"
#endif // !defined(ASIO_NO_IOSTREAM)
#endif // ASIO_IP_IMPL_ADDRESS_HPP
|
0 | repos/asio/asio/include/asio/ip | repos/asio/asio/include/asio/ip/impl/address_v4.hpp | //
// ip/impl/address_v4.hpp
// ~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef ASIO_IP_IMPL_ADDRESS_V4_HPP
#define ASIO_IP_IMPL_ADDRESS_V4_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#if !defined(ASIO_NO_IOSTREAM)
#include "asio/detail/throw_error.hpp"
#include "asio/detail/push_options.hpp"
namespace asio {
namespace ip {
#if !defined(ASIO_NO_DEPRECATED)
inline address_v4 address_v4::from_string(const char* str)
{
return asio::ip::make_address_v4(str);
}
inline address_v4 address_v4::from_string(
const char* str, asio::error_code& ec)
{
return asio::ip::make_address_v4(str, ec);
}
inline address_v4 address_v4::from_string(const std::string& str)
{
return asio::ip::make_address_v4(str);
}
inline address_v4 address_v4::from_string(
const std::string& str, asio::error_code& ec)
{
return asio::ip::make_address_v4(str, ec);
}
#endif // !defined(ASIO_NO_DEPRECATED)
template <typename Elem, typename Traits>
std::basic_ostream<Elem, Traits>& operator<<(
std::basic_ostream<Elem, Traits>& os, const address_v4& addr)
{
return os << addr.to_string().c_str();
}
} // namespace ip
} // namespace asio
#include "asio/detail/pop_options.hpp"
#endif // !defined(ASIO_NO_IOSTREAM)
#endif // ASIO_IP_IMPL_ADDRESS_V4_HPP
|
0 | repos/asio/asio/include/asio/ip | repos/asio/asio/include/asio/ip/impl/address_v6.hpp | //
// ip/impl/address_v6.hpp
// ~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef ASIO_IP_IMPL_ADDRESS_V6_HPP
#define ASIO_IP_IMPL_ADDRESS_V6_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#if !defined(ASIO_NO_IOSTREAM)
#include "asio/detail/throw_error.hpp"
#include "asio/detail/push_options.hpp"
namespace asio {
namespace ip {
#if !defined(ASIO_NO_DEPRECATED)
inline address_v6 address_v6::from_string(const char* str)
{
return asio::ip::make_address_v6(str);
}
inline address_v6 address_v6::from_string(
const char* str, asio::error_code& ec)
{
return asio::ip::make_address_v6(str, ec);
}
inline address_v6 address_v6::from_string(const std::string& str)
{
return asio::ip::make_address_v6(str);
}
inline address_v6 address_v6::from_string(
const std::string& str, asio::error_code& ec)
{
return asio::ip::make_address_v6(str, ec);
}
#endif // !defined(ASIO_NO_DEPRECATED)
template <typename Elem, typename Traits>
std::basic_ostream<Elem, Traits>& operator<<(
std::basic_ostream<Elem, Traits>& os, const address_v6& addr)
{
return os << addr.to_string().c_str();
}
} // namespace ip
} // namespace asio
#include "asio/detail/pop_options.hpp"
#endif // !defined(ASIO_NO_IOSTREAM)
#endif // ASIO_IP_IMPL_ADDRESS_V6_HPP
|
0 | repos/asio/asio/include/asio/ip | repos/asio/asio/include/asio/ip/impl/network_v4.hpp | //
// ip/impl/network_v4.hpp
// ~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com)
// Copyright (c) 2014 Oliver Kowalke (oliver dot kowalke at gmail dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef ASIO_IP_IMPL_NETWORK_V4_HPP
#define ASIO_IP_IMPL_NETWORK_V4_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#if !defined(ASIO_NO_IOSTREAM)
#include "asio/detail/throw_error.hpp"
#include "asio/detail/push_options.hpp"
namespace asio {
namespace ip {
template <typename Elem, typename Traits>
std::basic_ostream<Elem, Traits>& operator<<(
std::basic_ostream<Elem, Traits>& os, const network_v4& addr)
{
asio::error_code ec;
std::string s = addr.to_string(ec);
if (ec)
{
if (os.exceptions() & std::basic_ostream<Elem, Traits>::failbit)
asio::detail::throw_error(ec);
else
os.setstate(std::basic_ostream<Elem, Traits>::failbit);
}
else
for (std::string::iterator i = s.begin(); i != s.end(); ++i)
os << os.widen(*i);
return os;
}
} // namespace ip
} // namespace asio
#include "asio/detail/pop_options.hpp"
#endif // !defined(ASIO_NO_IOSTREAM)
#endif // ASIO_IP_IMPL_NETWORK_V4_HPP
|
0 | repos/asio/asio/include/asio/ip | repos/asio/asio/include/asio/ip/impl/network_v6.ipp | //
// ip/impl/network_v6.ipp
// ~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com)
// Copyright (c) 2014 Oliver Kowalke (oliver dot kowalke at gmail dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef ASIO_IP_IMPL_NETWORK_V6_IPP
#define ASIO_IP_IMPL_NETWORK_V6_IPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include "asio/detail/config.hpp"
#include <climits>
#include <cstdio>
#include <cstdlib>
#include <stdexcept>
#include "asio/error.hpp"
#include "asio/detail/throw_error.hpp"
#include "asio/detail/throw_exception.hpp"
#include "asio/ip/network_v6.hpp"
#include "asio/detail/push_options.hpp"
namespace asio {
namespace ip {
network_v6::network_v6(const address_v6& addr, unsigned short prefix_len)
: address_(addr),
prefix_length_(prefix_len)
{
if (prefix_len > 128)
{
std::out_of_range ex("prefix length too large");
asio::detail::throw_exception(ex);
}
}
ASIO_DECL address_v6 network_v6::network() const noexcept
{
address_v6::bytes_type bytes(address_.to_bytes());
for (std::size_t i = 0; i < 16; ++i)
{
if (prefix_length_ <= i * 8)
bytes[i] = 0;
else if (prefix_length_ < (i + 1) * 8)
bytes[i] &= 0xFF00 >> (prefix_length_ % 8);
}
return address_v6(bytes, address_.scope_id());
}
address_v6_range network_v6::hosts() const noexcept
{
address_v6::bytes_type begin_bytes(address_.to_bytes());
address_v6::bytes_type end_bytes(address_.to_bytes());
for (std::size_t i = 0; i < 16; ++i)
{
if (prefix_length_ <= i * 8)
{
begin_bytes[i] = 0;
end_bytes[i] = 0xFF;
}
else if (prefix_length_ < (i + 1) * 8)
{
begin_bytes[i] &= 0xFF00 >> (prefix_length_ % 8);
end_bytes[i] |= 0xFF >> (prefix_length_ % 8);
}
}
return address_v6_range(
address_v6_iterator(address_v6(begin_bytes, address_.scope_id())),
++address_v6_iterator(address_v6(end_bytes, address_.scope_id())));
}
bool network_v6::is_subnet_of(const network_v6& other) const
{
if (other.prefix_length_ >= prefix_length_)
return false; // Only real subsets are allowed.
const network_v6 me(address_, other.prefix_length_);
return other.canonical() == me.canonical();
}
std::string network_v6::to_string() const
{
asio::error_code ec;
std::string addr = to_string(ec);
asio::detail::throw_error(ec);
return addr;
}
std::string network_v6::to_string(asio::error_code& ec) const
{
using namespace std; // For sprintf.
ec = asio::error_code();
char prefix_len[16];
#if defined(ASIO_HAS_SNPRINTF)
snprintf(prefix_len, sizeof(prefix_len), "/%u", prefix_length_);
#elif defined(ASIO_HAS_SECURE_RTL)
sprintf_s(prefix_len, sizeof(prefix_len), "/%u", prefix_length_);
#else // defined(ASIO_HAS_SECURE_RTL)
sprintf(prefix_len, "/%u", prefix_length_);
#endif // defined(ASIO_HAS_SECURE_RTL)
return address_.to_string() + prefix_len;
}
network_v6 make_network_v6(const char* str)
{
return make_network_v6(std::string(str));
}
network_v6 make_network_v6(const char* str, asio::error_code& ec)
{
return make_network_v6(std::string(str), ec);
}
network_v6 make_network_v6(const std::string& str)
{
asio::error_code ec;
network_v6 net = make_network_v6(str, ec);
asio::detail::throw_error(ec);
return net;
}
network_v6 make_network_v6(const std::string& str,
asio::error_code& ec)
{
std::string::size_type pos = str.find_first_of("/");
if (pos == std::string::npos)
{
ec = asio::error::invalid_argument;
return network_v6();
}
if (pos == str.size() - 1)
{
ec = asio::error::invalid_argument;
return network_v6();
}
std::string::size_type end = str.find_first_not_of("0123456789", pos + 1);
if (end != std::string::npos)
{
ec = asio::error::invalid_argument;
return network_v6();
}
const address_v6 addr = make_address_v6(str.substr(0, pos), ec);
if (ec)
return network_v6();
const int prefix_len = std::atoi(str.substr(pos + 1).c_str());
if (prefix_len < 0 || prefix_len > 128)
{
ec = asio::error::invalid_argument;
return network_v6();
}
return network_v6(addr, static_cast<unsigned short>(prefix_len));
}
#if defined(ASIO_HAS_STRING_VIEW)
network_v6 make_network_v6(string_view str)
{
return make_network_v6(static_cast<std::string>(str));
}
network_v6 make_network_v6(string_view str,
asio::error_code& ec)
{
return make_network_v6(static_cast<std::string>(str), ec);
}
#endif // defined(ASIO_HAS_STRING_VIEW)
} // namespace ip
} // namespace asio
#include "asio/detail/pop_options.hpp"
#endif // ASIO_IP_IMPL_NETWORK_V6_IPP
|
0 | repos/asio/asio/include/asio/ip | repos/asio/asio/include/asio/ip/impl/address.ipp | //
// ip/impl/address.ipp
// ~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef ASIO_IP_IMPL_ADDRESS_IPP
#define ASIO_IP_IMPL_ADDRESS_IPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include "asio/detail/config.hpp"
#include <typeinfo>
#include "asio/detail/throw_error.hpp"
#include "asio/detail/throw_exception.hpp"
#include "asio/error.hpp"
#include "asio/ip/address.hpp"
#include "asio/ip/bad_address_cast.hpp"
#include "asio/system_error.hpp"
#include "asio/detail/push_options.hpp"
namespace asio {
namespace ip {
address::address() noexcept
: type_(ipv4),
ipv4_address_(),
ipv6_address_()
{
}
address::address(
const asio::ip::address_v4& ipv4_address) noexcept
: type_(ipv4),
ipv4_address_(ipv4_address),
ipv6_address_()
{
}
address::address(
const asio::ip::address_v6& ipv6_address) noexcept
: type_(ipv6),
ipv4_address_(),
ipv6_address_(ipv6_address)
{
}
address::address(const address& other) noexcept
: type_(other.type_),
ipv4_address_(other.ipv4_address_),
ipv6_address_(other.ipv6_address_)
{
}
address::address(address&& other) noexcept
: type_(other.type_),
ipv4_address_(other.ipv4_address_),
ipv6_address_(other.ipv6_address_)
{
}
address& address::operator=(const address& other) noexcept
{
type_ = other.type_;
ipv4_address_ = other.ipv4_address_;
ipv6_address_ = other.ipv6_address_;
return *this;
}
address& address::operator=(address&& other) noexcept
{
type_ = other.type_;
ipv4_address_ = other.ipv4_address_;
ipv6_address_ = other.ipv6_address_;
return *this;
}
address& address::operator=(
const asio::ip::address_v4& ipv4_address) noexcept
{
type_ = ipv4;
ipv4_address_ = ipv4_address;
ipv6_address_ = asio::ip::address_v6();
return *this;
}
address& address::operator=(
const asio::ip::address_v6& ipv6_address) noexcept
{
type_ = ipv6;
ipv4_address_ = asio::ip::address_v4();
ipv6_address_ = ipv6_address;
return *this;
}
address make_address(const char* str)
{
asio::error_code ec;
address addr = make_address(str, ec);
asio::detail::throw_error(ec);
return addr;
}
address make_address(const char* str,
asio::error_code& ec) noexcept
{
asio::ip::address_v6 ipv6_address =
asio::ip::make_address_v6(str, ec);
if (!ec)
return address(ipv6_address);
asio::ip::address_v4 ipv4_address =
asio::ip::make_address_v4(str, ec);
if (!ec)
return address(ipv4_address);
return address();
}
address make_address(const std::string& str)
{
return make_address(str.c_str());
}
address make_address(const std::string& str,
asio::error_code& ec) noexcept
{
return make_address(str.c_str(), ec);
}
#if defined(ASIO_HAS_STRING_VIEW)
address make_address(string_view str)
{
return make_address(static_cast<std::string>(str));
}
address make_address(string_view str,
asio::error_code& ec) noexcept
{
return make_address(static_cast<std::string>(str), ec);
}
#endif // defined(ASIO_HAS_STRING_VIEW)
asio::ip::address_v4 address::to_v4() const
{
if (type_ != ipv4)
{
bad_address_cast ex;
asio::detail::throw_exception(ex);
}
return ipv4_address_;
}
asio::ip::address_v6 address::to_v6() const
{
if (type_ != ipv6)
{
bad_address_cast ex;
asio::detail::throw_exception(ex);
}
return ipv6_address_;
}
std::string address::to_string() const
{
if (type_ == ipv6)
return ipv6_address_.to_string();
return ipv4_address_.to_string();
}
#if !defined(ASIO_NO_DEPRECATED)
std::string address::to_string(asio::error_code& ec) const
{
if (type_ == ipv6)
return ipv6_address_.to_string(ec);
return ipv4_address_.to_string(ec);
}
#endif // !defined(ASIO_NO_DEPRECATED)
bool address::is_loopback() const noexcept
{
return (type_ == ipv4)
? ipv4_address_.is_loopback()
: ipv6_address_.is_loopback();
}
bool address::is_unspecified() const noexcept
{
return (type_ == ipv4)
? ipv4_address_.is_unspecified()
: ipv6_address_.is_unspecified();
}
bool address::is_multicast() const noexcept
{
return (type_ == ipv4)
? ipv4_address_.is_multicast()
: ipv6_address_.is_multicast();
}
bool operator==(const address& a1, const address& a2) noexcept
{
if (a1.type_ != a2.type_)
return false;
if (a1.type_ == address::ipv6)
return a1.ipv6_address_ == a2.ipv6_address_;
return a1.ipv4_address_ == a2.ipv4_address_;
}
bool operator<(const address& a1, const address& a2) noexcept
{
if (a1.type_ < a2.type_)
return true;
if (a1.type_ > a2.type_)
return false;
if (a1.type_ == address::ipv6)
return a1.ipv6_address_ < a2.ipv6_address_;
return a1.ipv4_address_ < a2.ipv4_address_;
}
} // namespace ip
} // namespace asio
#include "asio/detail/pop_options.hpp"
#endif // ASIO_IP_IMPL_ADDRESS_IPP
|
0 | repos/asio/asio/include/asio/ip | repos/asio/asio/include/asio/ip/impl/basic_endpoint.hpp | //
// ip/impl/basic_endpoint.hpp
// ~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef ASIO_IP_IMPL_BASIC_ENDPOINT_HPP
#define ASIO_IP_IMPL_BASIC_ENDPOINT_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#if !defined(ASIO_NO_IOSTREAM)
#include "asio/detail/throw_error.hpp"
#include "asio/detail/push_options.hpp"
namespace asio {
namespace ip {
template <typename Elem, typename Traits, typename InternetProtocol>
std::basic_ostream<Elem, Traits>& operator<<(
std::basic_ostream<Elem, Traits>& os,
const basic_endpoint<InternetProtocol>& endpoint)
{
asio::ip::detail::endpoint tmp_ep(endpoint.address(), endpoint.port());
return os << tmp_ep.to_string().c_str();
}
} // namespace ip
} // namespace asio
#include "asio/detail/pop_options.hpp"
#endif // !defined(ASIO_NO_IOSTREAM)
#endif // ASIO_IP_IMPL_BASIC_ENDPOINT_HPP
|
0 | repos/asio/asio/include/asio/ip | repos/asio/asio/include/asio/ip/impl/host_name.ipp | //
// ip/impl/host_name.ipp
// ~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef ASIO_IP_IMPL_HOST_NAME_IPP
#define ASIO_IP_IMPL_HOST_NAME_IPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include "asio/detail/config.hpp"
#include "asio/detail/socket_ops.hpp"
#include "asio/detail/throw_error.hpp"
#include "asio/detail/winsock_init.hpp"
#include "asio/ip/host_name.hpp"
#include "asio/detail/push_options.hpp"
namespace asio {
namespace ip {
std::string host_name()
{
char name[1024];
asio::error_code ec;
if (asio::detail::socket_ops::gethostname(name, sizeof(name), ec) != 0)
{
asio::detail::throw_error(ec);
return std::string();
}
return std::string(name);
}
std::string host_name(asio::error_code& ec)
{
char name[1024];
if (asio::detail::socket_ops::gethostname(name, sizeof(name), ec) != 0)
return std::string();
return std::string(name);
}
} // namespace ip
} // namespace asio
#include "asio/detail/pop_options.hpp"
#endif // ASIO_IP_IMPL_HOST_NAME_IPP
|
0 | repos/asio/asio/include/asio/ip | repos/asio/asio/include/asio/ip/impl/address_v6.ipp | //
// ip/impl/address_v6.ipp
// ~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef ASIO_IP_IMPL_ADDRESS_V6_IPP
#define ASIO_IP_IMPL_ADDRESS_V6_IPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include "asio/detail/config.hpp"
#include <cstring>
#include <stdexcept>
#include <typeinfo>
#include "asio/detail/socket_ops.hpp"
#include "asio/detail/throw_error.hpp"
#include "asio/detail/throw_exception.hpp"
#include "asio/error.hpp"
#include "asio/ip/address_v6.hpp"
#include "asio/ip/bad_address_cast.hpp"
#include "asio/detail/push_options.hpp"
namespace asio {
namespace ip {
address_v6::address_v6() noexcept
: addr_(),
scope_id_(0)
{
}
address_v6::address_v6(const address_v6::bytes_type& bytes,
scope_id_type scope)
: scope_id_(scope)
{
#if UCHAR_MAX > 0xFF
for (std::size_t i = 0; i < bytes.size(); ++i)
{
if (bytes[i] > 0xFF)
{
std::out_of_range ex("address_v6 from bytes_type");
asio::detail::throw_exception(ex);
}
}
#endif // UCHAR_MAX > 0xFF
using namespace std; // For memcpy.
memcpy(addr_.s6_addr, bytes.data(), 16);
}
address_v6::address_v6(const address_v6& other) noexcept
: addr_(other.addr_),
scope_id_(other.scope_id_)
{
}
address_v6::address_v6(address_v6&& other) noexcept
: addr_(other.addr_),
scope_id_(other.scope_id_)
{
}
address_v6& address_v6::operator=(const address_v6& other) noexcept
{
addr_ = other.addr_;
scope_id_ = other.scope_id_;
return *this;
}
address_v6& address_v6::operator=(address_v6&& other) noexcept
{
addr_ = other.addr_;
scope_id_ = other.scope_id_;
return *this;
}
address_v6::bytes_type address_v6::to_bytes() const noexcept
{
using namespace std; // For memcpy.
bytes_type bytes;
memcpy(bytes.data(), addr_.s6_addr, 16);
return bytes;
}
std::string address_v6::to_string() const
{
asio::error_code ec;
char addr_str[asio::detail::max_addr_v6_str_len];
const char* addr =
asio::detail::socket_ops::inet_ntop(
ASIO_OS_DEF(AF_INET6), &addr_, addr_str,
asio::detail::max_addr_v6_str_len, scope_id_, ec);
if (addr == 0)
asio::detail::throw_error(ec);
return addr;
}
#if !defined(ASIO_NO_DEPRECATED)
std::string address_v6::to_string(asio::error_code& ec) const
{
char addr_str[asio::detail::max_addr_v6_str_len];
const char* addr =
asio::detail::socket_ops::inet_ntop(
ASIO_OS_DEF(AF_INET6), &addr_, addr_str,
asio::detail::max_addr_v6_str_len, scope_id_, ec);
if (addr == 0)
return std::string();
return addr;
}
address_v4 address_v6::to_v4() const
{
if (!is_v4_mapped() && !is_v4_compatible())
{
bad_address_cast ex;
asio::detail::throw_exception(ex);
}
address_v4::bytes_type v4_bytes = { { addr_.s6_addr[12],
addr_.s6_addr[13], addr_.s6_addr[14], addr_.s6_addr[15] } };
return address_v4(v4_bytes);
}
#endif // !defined(ASIO_NO_DEPRECATED)
bool address_v6::is_loopback() const noexcept
{
return ((addr_.s6_addr[0] == 0) && (addr_.s6_addr[1] == 0)
&& (addr_.s6_addr[2] == 0) && (addr_.s6_addr[3] == 0)
&& (addr_.s6_addr[4] == 0) && (addr_.s6_addr[5] == 0)
&& (addr_.s6_addr[6] == 0) && (addr_.s6_addr[7] == 0)
&& (addr_.s6_addr[8] == 0) && (addr_.s6_addr[9] == 0)
&& (addr_.s6_addr[10] == 0) && (addr_.s6_addr[11] == 0)
&& (addr_.s6_addr[12] == 0) && (addr_.s6_addr[13] == 0)
&& (addr_.s6_addr[14] == 0) && (addr_.s6_addr[15] == 1));
}
bool address_v6::is_unspecified() const noexcept
{
return ((addr_.s6_addr[0] == 0) && (addr_.s6_addr[1] == 0)
&& (addr_.s6_addr[2] == 0) && (addr_.s6_addr[3] == 0)
&& (addr_.s6_addr[4] == 0) && (addr_.s6_addr[5] == 0)
&& (addr_.s6_addr[6] == 0) && (addr_.s6_addr[7] == 0)
&& (addr_.s6_addr[8] == 0) && (addr_.s6_addr[9] == 0)
&& (addr_.s6_addr[10] == 0) && (addr_.s6_addr[11] == 0)
&& (addr_.s6_addr[12] == 0) && (addr_.s6_addr[13] == 0)
&& (addr_.s6_addr[14] == 0) && (addr_.s6_addr[15] == 0));
}
bool address_v6::is_link_local() const noexcept
{
return ((addr_.s6_addr[0] == 0xfe) && ((addr_.s6_addr[1] & 0xc0) == 0x80));
}
bool address_v6::is_site_local() const noexcept
{
return ((addr_.s6_addr[0] == 0xfe) && ((addr_.s6_addr[1] & 0xc0) == 0xc0));
}
bool address_v6::is_v4_mapped() const noexcept
{
return ((addr_.s6_addr[0] == 0) && (addr_.s6_addr[1] == 0)
&& (addr_.s6_addr[2] == 0) && (addr_.s6_addr[3] == 0)
&& (addr_.s6_addr[4] == 0) && (addr_.s6_addr[5] == 0)
&& (addr_.s6_addr[6] == 0) && (addr_.s6_addr[7] == 0)
&& (addr_.s6_addr[8] == 0) && (addr_.s6_addr[9] == 0)
&& (addr_.s6_addr[10] == 0xff) && (addr_.s6_addr[11] == 0xff));
}
#if !defined(ASIO_NO_DEPRECATED)
bool address_v6::is_v4_compatible() const
{
return ((addr_.s6_addr[0] == 0) && (addr_.s6_addr[1] == 0)
&& (addr_.s6_addr[2] == 0) && (addr_.s6_addr[3] == 0)
&& (addr_.s6_addr[4] == 0) && (addr_.s6_addr[5] == 0)
&& (addr_.s6_addr[6] == 0) && (addr_.s6_addr[7] == 0)
&& (addr_.s6_addr[8] == 0) && (addr_.s6_addr[9] == 0)
&& (addr_.s6_addr[10] == 0) && (addr_.s6_addr[11] == 0)
&& !((addr_.s6_addr[12] == 0)
&& (addr_.s6_addr[13] == 0)
&& (addr_.s6_addr[14] == 0)
&& ((addr_.s6_addr[15] == 0) || (addr_.s6_addr[15] == 1))));
}
#endif // !defined(ASIO_NO_DEPRECATED)
bool address_v6::is_multicast() const noexcept
{
return (addr_.s6_addr[0] == 0xff);
}
bool address_v6::is_multicast_global() const noexcept
{
return ((addr_.s6_addr[0] == 0xff) && ((addr_.s6_addr[1] & 0x0f) == 0x0e));
}
bool address_v6::is_multicast_link_local() const noexcept
{
return ((addr_.s6_addr[0] == 0xff) && ((addr_.s6_addr[1] & 0x0f) == 0x02));
}
bool address_v6::is_multicast_node_local() const noexcept
{
return ((addr_.s6_addr[0] == 0xff) && ((addr_.s6_addr[1] & 0x0f) == 0x01));
}
bool address_v6::is_multicast_org_local() const noexcept
{
return ((addr_.s6_addr[0] == 0xff) && ((addr_.s6_addr[1] & 0x0f) == 0x08));
}
bool address_v6::is_multicast_site_local() const noexcept
{
return ((addr_.s6_addr[0] == 0xff) && ((addr_.s6_addr[1] & 0x0f) == 0x05));
}
bool operator==(const address_v6& a1, const address_v6& a2) noexcept
{
using namespace std; // For memcmp.
return memcmp(&a1.addr_, &a2.addr_,
sizeof(asio::detail::in6_addr_type)) == 0
&& a1.scope_id_ == a2.scope_id_;
}
bool operator<(const address_v6& a1, const address_v6& a2) noexcept
{
using namespace std; // For memcmp.
int memcmp_result = memcmp(&a1.addr_, &a2.addr_,
sizeof(asio::detail::in6_addr_type));
if (memcmp_result < 0)
return true;
if (memcmp_result > 0)
return false;
return a1.scope_id_ < a2.scope_id_;
}
address_v6 address_v6::loopback() noexcept
{
address_v6 tmp;
tmp.addr_.s6_addr[15] = 1;
return tmp;
}
#if !defined(ASIO_NO_DEPRECATED)
address_v6 address_v6::v4_mapped(const address_v4& addr)
{
address_v4::bytes_type v4_bytes = addr.to_bytes();
bytes_type v6_bytes = { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF,
v4_bytes[0], v4_bytes[1], v4_bytes[2], v4_bytes[3] } };
return address_v6(v6_bytes);
}
address_v6 address_v6::v4_compatible(const address_v4& addr)
{
address_v4::bytes_type v4_bytes = addr.to_bytes();
bytes_type v6_bytes = { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
v4_bytes[0], v4_bytes[1], v4_bytes[2], v4_bytes[3] } };
return address_v6(v6_bytes);
}
#endif // !defined(ASIO_NO_DEPRECATED)
address_v6 make_address_v6(const char* str)
{
asio::error_code ec;
address_v6 addr = make_address_v6(str, ec);
asio::detail::throw_error(ec);
return addr;
}
address_v6 make_address_v6(const char* str,
asio::error_code& ec) noexcept
{
address_v6::bytes_type bytes;
unsigned long scope_id = 0;
if (asio::detail::socket_ops::inet_pton(
ASIO_OS_DEF(AF_INET6), str, &bytes[0], &scope_id, ec) <= 0)
return address_v6();
return address_v6(bytes, static_cast<scope_id_type>(scope_id));
}
address_v6 make_address_v6(const std::string& str)
{
return make_address_v6(str.c_str());
}
address_v6 make_address_v6(const std::string& str,
asio::error_code& ec) noexcept
{
return make_address_v6(str.c_str(), ec);
}
#if defined(ASIO_HAS_STRING_VIEW)
address_v6 make_address_v6(string_view str)
{
return make_address_v6(static_cast<std::string>(str));
}
address_v6 make_address_v6(string_view str,
asio::error_code& ec) noexcept
{
return make_address_v6(static_cast<std::string>(str), ec);
}
#endif // defined(ASIO_HAS_STRING_VIEW)
address_v4 make_address_v4(
v4_mapped_t, const address_v6& v6_addr)
{
if (!v6_addr.is_v4_mapped())
{
bad_address_cast ex;
asio::detail::throw_exception(ex);
}
address_v6::bytes_type v6_bytes = v6_addr.to_bytes();
address_v4::bytes_type v4_bytes = { { v6_bytes[12],
v6_bytes[13], v6_bytes[14], v6_bytes[15] } };
return address_v4(v4_bytes);
}
address_v6 make_address_v6(
v4_mapped_t, const address_v4& v4_addr)
{
address_v4::bytes_type v4_bytes = v4_addr.to_bytes();
address_v6::bytes_type v6_bytes = { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0xFF, 0xFF, v4_bytes[0], v4_bytes[1], v4_bytes[2], v4_bytes[3] } };
return address_v6(v6_bytes);
}
} // namespace ip
} // namespace asio
#include "asio/detail/pop_options.hpp"
#endif // ASIO_IP_IMPL_ADDRESS_V6_IPP
|
0 | repos/asio/asio/include/asio/ip | repos/asio/asio/include/asio/ip/impl/network_v6.hpp | //
// ip/impl/network_v6.hpp
// ~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef ASIO_IP_IMPL_NETWORK_V6_HPP
#define ASIO_IP_IMPL_NETWORK_V6_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#if !defined(ASIO_NO_IOSTREAM)
#include "asio/detail/throw_error.hpp"
#include "asio/detail/push_options.hpp"
namespace asio {
namespace ip {
template <typename Elem, typename Traits>
std::basic_ostream<Elem, Traits>& operator<<(
std::basic_ostream<Elem, Traits>& os, const network_v6& addr)
{
asio::error_code ec;
std::string s = addr.to_string(ec);
if (ec)
{
if (os.exceptions() & std::basic_ostream<Elem, Traits>::failbit)
asio::detail::throw_error(ec);
else
os.setstate(std::basic_ostream<Elem, Traits>::failbit);
}
else
for (std::string::iterator i = s.begin(); i != s.end(); ++i)
os << os.widen(*i);
return os;
}
} // namespace ip
} // namespace asio
#include "asio/detail/pop_options.hpp"
#endif // !defined(ASIO_NO_IOSTREAM)
#endif // ASIO_IP_IMPL_NETWORK_V6_HPP
|
0 | repos/asio/asio/include/asio/ip | repos/asio/asio/include/asio/ip/impl/network_v4.ipp | //
// ip/impl/network_v4.ipp
// ~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com)
// Copyright (c) 2014 Oliver Kowalke (oliver dot kowalke at gmail dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef ASIO_IP_IMPL_NETWORK_V4_IPP
#define ASIO_IP_IMPL_NETWORK_V4_IPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include "asio/detail/config.hpp"
#include <climits>
#include <cstdio>
#include <cstdlib>
#include <stdexcept>
#include "asio/error.hpp"
#include "asio/detail/throw_error.hpp"
#include "asio/detail/throw_exception.hpp"
#include "asio/ip/network_v4.hpp"
#include "asio/detail/push_options.hpp"
namespace asio {
namespace ip {
network_v4::network_v4(const address_v4& addr, unsigned short prefix_len)
: address_(addr),
prefix_length_(prefix_len)
{
if (prefix_len > 32)
{
std::out_of_range ex("prefix length too large");
asio::detail::throw_exception(ex);
}
}
network_v4::network_v4(const address_v4& addr, const address_v4& mask)
: address_(addr),
prefix_length_(0)
{
address_v4::bytes_type mask_bytes = mask.to_bytes();
bool finished = false;
for (std::size_t i = 0; i < mask_bytes.size(); ++i)
{
if (finished)
{
if (mask_bytes[i])
{
std::invalid_argument ex("non-contiguous netmask");
asio::detail::throw_exception(ex);
}
continue;
}
else
{
switch (mask_bytes[i])
{
case 255:
prefix_length_ += 8;
break;
case 254: // prefix_length_ += 7
prefix_length_ += 1;
case 252: // prefix_length_ += 6
prefix_length_ += 1;
case 248: // prefix_length_ += 5
prefix_length_ += 1;
case 240: // prefix_length_ += 4
prefix_length_ += 1;
case 224: // prefix_length_ += 3
prefix_length_ += 1;
case 192: // prefix_length_ += 2
prefix_length_ += 1;
case 128: // prefix_length_ += 1
prefix_length_ += 1;
case 0: // nbits += 0
finished = true;
break;
default:
std::out_of_range ex("non-contiguous netmask");
asio::detail::throw_exception(ex);
}
}
}
}
address_v4 network_v4::netmask() const noexcept
{
uint32_t nmbits = 0xffffffff;
if (prefix_length_ == 0)
nmbits = 0;
else
nmbits = nmbits << (32 - prefix_length_);
return address_v4(nmbits);
}
address_v4_range network_v4::hosts() const noexcept
{
return is_host()
? address_v4_range(address_, address_v4(address_.to_uint() + 1))
: address_v4_range(address_v4(network().to_uint() + 1), broadcast());
}
bool network_v4::is_subnet_of(const network_v4& other) const
{
if (other.prefix_length_ >= prefix_length_)
return false; // Only real subsets are allowed.
const network_v4 me(address_, other.prefix_length_);
return other.canonical() == me.canonical();
}
std::string network_v4::to_string() const
{
asio::error_code ec;
std::string addr = to_string(ec);
asio::detail::throw_error(ec);
return addr;
}
std::string network_v4::to_string(asio::error_code& ec) const
{
using namespace std; // For sprintf.
ec = asio::error_code();
char prefix_len[16];
#if defined(ASIO_HAS_SNPRINTF)
snprintf(prefix_len, sizeof(prefix_len), "/%u", prefix_length_);
#elif defined(ASIO_HAS_SECURE_RTL)
sprintf_s(prefix_len, sizeof(prefix_len), "/%u", prefix_length_);
#else // defined(ASIO_HAS_SECURE_RTL)
sprintf(prefix_len, "/%u", prefix_length_);
#endif // defined(ASIO_HAS_SECURE_RTL)
return address_.to_string() + prefix_len;
}
network_v4 make_network_v4(const char* str)
{
return make_network_v4(std::string(str));
}
network_v4 make_network_v4(const char* str, asio::error_code& ec)
{
return make_network_v4(std::string(str), ec);
}
network_v4 make_network_v4(const std::string& str)
{
asio::error_code ec;
network_v4 net = make_network_v4(str, ec);
asio::detail::throw_error(ec);
return net;
}
network_v4 make_network_v4(const std::string& str,
asio::error_code& ec)
{
std::string::size_type pos = str.find_first_of("/");
if (pos == std::string::npos)
{
ec = asio::error::invalid_argument;
return network_v4();
}
if (pos == str.size() - 1)
{
ec = asio::error::invalid_argument;
return network_v4();
}
std::string::size_type end = str.find_first_not_of("0123456789", pos + 1);
if (end != std::string::npos)
{
ec = asio::error::invalid_argument;
return network_v4();
}
const address_v4 addr = make_address_v4(str.substr(0, pos), ec);
if (ec)
return network_v4();
const int prefix_len = std::atoi(str.substr(pos + 1).c_str());
if (prefix_len < 0 || prefix_len > 32)
{
ec = asio::error::invalid_argument;
return network_v4();
}
return network_v4(addr, static_cast<unsigned short>(prefix_len));
}
#if defined(ASIO_HAS_STRING_VIEW)
network_v4 make_network_v4(string_view str)
{
return make_network_v4(static_cast<std::string>(str));
}
network_v4 make_network_v4(string_view str,
asio::error_code& ec)
{
return make_network_v4(static_cast<std::string>(str), ec);
}
#endif // defined(ASIO_HAS_STRING_VIEW)
} // namespace ip
} // namespace asio
#include "asio/detail/pop_options.hpp"
#endif // ASIO_IP_IMPL_NETWORK_V4_IPP
|
0 | repos/asio/asio/include/asio/ip | repos/asio/asio/include/asio/ip/impl/address_v4.ipp | //
// ip/impl/address_v4.ipp
// ~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef ASIO_IP_IMPL_ADDRESS_V4_IPP
#define ASIO_IP_IMPL_ADDRESS_V4_IPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include "asio/detail/config.hpp"
#include <climits>
#include <limits>
#include <stdexcept>
#include "asio/error.hpp"
#include "asio/detail/socket_ops.hpp"
#include "asio/detail/throw_error.hpp"
#include "asio/detail/throw_exception.hpp"
#include "asio/ip/address_v4.hpp"
#include "asio/detail/push_options.hpp"
namespace asio {
namespace ip {
address_v4::address_v4(const address_v4::bytes_type& bytes)
{
#if UCHAR_MAX > 0xFF
if (bytes[0] > 0xFF || bytes[1] > 0xFF
|| bytes[2] > 0xFF || bytes[3] > 0xFF)
{
std::out_of_range ex("address_v4 from bytes_type");
asio::detail::throw_exception(ex);
}
#endif // UCHAR_MAX > 0xFF
using namespace std; // For memcpy.
memcpy(&addr_.s_addr, bytes.data(), 4);
}
address_v4::address_v4(address_v4::uint_type addr)
{
if ((std::numeric_limits<uint_type>::max)() > 0xFFFFFFFF)
{
std::out_of_range ex("address_v4 from unsigned integer");
asio::detail::throw_exception(ex);
}
addr_.s_addr = asio::detail::socket_ops::host_to_network_long(
static_cast<asio::detail::u_long_type>(addr));
}
address_v4::bytes_type address_v4::to_bytes() const noexcept
{
using namespace std; // For memcpy.
bytes_type bytes;
memcpy(bytes.data(), &addr_.s_addr, 4);
return bytes;
}
address_v4::uint_type address_v4::to_uint() const noexcept
{
return asio::detail::socket_ops::network_to_host_long(addr_.s_addr);
}
#if !defined(ASIO_NO_DEPRECATED)
unsigned long address_v4::to_ulong() const
{
return asio::detail::socket_ops::network_to_host_long(addr_.s_addr);
}
#endif // !defined(ASIO_NO_DEPRECATED)
std::string address_v4::to_string() const
{
asio::error_code ec;
char addr_str[asio::detail::max_addr_v4_str_len];
const char* addr =
asio::detail::socket_ops::inet_ntop(
ASIO_OS_DEF(AF_INET), &addr_, addr_str,
asio::detail::max_addr_v4_str_len, 0, ec);
if (addr == 0)
asio::detail::throw_error(ec);
return addr;
}
#if !defined(ASIO_NO_DEPRECATED)
std::string address_v4::to_string(asio::error_code& ec) const
{
char addr_str[asio::detail::max_addr_v4_str_len];
const char* addr =
asio::detail::socket_ops::inet_ntop(
ASIO_OS_DEF(AF_INET), &addr_, addr_str,
asio::detail::max_addr_v4_str_len, 0, ec);
if (addr == 0)
return std::string();
return addr;
}
#endif // !defined(ASIO_NO_DEPRECATED)
bool address_v4::is_loopback() const noexcept
{
return (to_uint() & 0xFF000000) == 0x7F000000;
}
bool address_v4::is_unspecified() const noexcept
{
return to_uint() == 0;
}
#if !defined(ASIO_NO_DEPRECATED)
bool address_v4::is_class_a() const
{
return (to_uint() & 0x80000000) == 0;
}
bool address_v4::is_class_b() const
{
return (to_uint() & 0xC0000000) == 0x80000000;
}
bool address_v4::is_class_c() const
{
return (to_uint() & 0xE0000000) == 0xC0000000;
}
#endif // !defined(ASIO_NO_DEPRECATED)
bool address_v4::is_multicast() const noexcept
{
return (to_uint() & 0xF0000000) == 0xE0000000;
}
#if !defined(ASIO_NO_DEPRECATED)
address_v4 address_v4::broadcast(const address_v4& addr, const address_v4& mask)
{
return address_v4(addr.to_uint() | (mask.to_uint() ^ 0xFFFFFFFF));
}
address_v4 address_v4::netmask(const address_v4& addr)
{
if (addr.is_class_a())
return address_v4(0xFF000000);
if (addr.is_class_b())
return address_v4(0xFFFF0000);
if (addr.is_class_c())
return address_v4(0xFFFFFF00);
return address_v4(0xFFFFFFFF);
}
#endif // !defined(ASIO_NO_DEPRECATED)
address_v4 make_address_v4(const char* str)
{
asio::error_code ec;
address_v4 addr = make_address_v4(str, ec);
asio::detail::throw_error(ec);
return addr;
}
address_v4 make_address_v4(const char* str,
asio::error_code& ec) noexcept
{
address_v4::bytes_type bytes;
if (asio::detail::socket_ops::inet_pton(
ASIO_OS_DEF(AF_INET), str, &bytes, 0, ec) <= 0)
return address_v4();
return address_v4(bytes);
}
address_v4 make_address_v4(const std::string& str)
{
return make_address_v4(str.c_str());
}
address_v4 make_address_v4(const std::string& str,
asio::error_code& ec) noexcept
{
return make_address_v4(str.c_str(), ec);
}
#if defined(ASIO_HAS_STRING_VIEW)
address_v4 make_address_v4(string_view str)
{
return make_address_v4(static_cast<std::string>(str));
}
address_v4 make_address_v4(string_view str,
asio::error_code& ec) noexcept
{
return make_address_v4(static_cast<std::string>(str), ec);
}
#endif // defined(ASIO_HAS_STRING_VIEW)
} // namespace ip
} // namespace asio
#include "asio/detail/pop_options.hpp"
#endif // ASIO_IP_IMPL_ADDRESS_V4_IPP
|
0 | repos/asio/asio/include/asio | repos/asio/asio/include/asio/impl/buffered_read_stream.hpp | //
// impl/buffered_read_stream.hpp
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef ASIO_IMPL_BUFFERED_READ_STREAM_HPP
#define ASIO_IMPL_BUFFERED_READ_STREAM_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include "asio/associator.hpp"
#include "asio/detail/handler_cont_helpers.hpp"
#include "asio/detail/handler_type_requirements.hpp"
#include "asio/detail/non_const_lvalue.hpp"
#include "asio/detail/type_traits.hpp"
#include "asio/detail/push_options.hpp"
namespace asio {
template <typename Stream>
std::size_t buffered_read_stream<Stream>::fill()
{
detail::buffer_resize_guard<detail::buffered_stream_storage>
resize_guard(storage_);
std::size_t previous_size = storage_.size();
storage_.resize(storage_.capacity());
storage_.resize(previous_size + next_layer_.read_some(buffer(
storage_.data() + previous_size,
storage_.size() - previous_size)));
resize_guard.commit();
return storage_.size() - previous_size;
}
template <typename Stream>
std::size_t buffered_read_stream<Stream>::fill(asio::error_code& ec)
{
detail::buffer_resize_guard<detail::buffered_stream_storage>
resize_guard(storage_);
std::size_t previous_size = storage_.size();
storage_.resize(storage_.capacity());
storage_.resize(previous_size + next_layer_.read_some(buffer(
storage_.data() + previous_size,
storage_.size() - previous_size),
ec));
resize_guard.commit();
return storage_.size() - previous_size;
}
namespace detail
{
template <typename ReadHandler>
class buffered_fill_handler
{
public:
buffered_fill_handler(detail::buffered_stream_storage& storage,
std::size_t previous_size, ReadHandler& handler)
: storage_(storage),
previous_size_(previous_size),
handler_(static_cast<ReadHandler&&>(handler))
{
}
buffered_fill_handler(const buffered_fill_handler& other)
: storage_(other.storage_),
previous_size_(other.previous_size_),
handler_(other.handler_)
{
}
buffered_fill_handler(buffered_fill_handler&& other)
: storage_(other.storage_),
previous_size_(other.previous_size_),
handler_(static_cast<ReadHandler&&>(other.handler_))
{
}
void operator()(const asio::error_code& ec,
const std::size_t bytes_transferred)
{
storage_.resize(previous_size_ + bytes_transferred);
static_cast<ReadHandler&&>(handler_)(ec, bytes_transferred);
}
//private:
detail::buffered_stream_storage& storage_;
std::size_t previous_size_;
ReadHandler handler_;
};
template <typename ReadHandler>
inline bool asio_handler_is_continuation(
buffered_fill_handler<ReadHandler>* this_handler)
{
return asio_handler_cont_helpers::is_continuation(
this_handler->handler_);
}
template <typename Stream>
class initiate_async_buffered_fill
{
public:
typedef typename remove_reference_t<
Stream>::lowest_layer_type::executor_type executor_type;
explicit initiate_async_buffered_fill(
remove_reference_t<Stream>& next_layer)
: next_layer_(next_layer)
{
}
executor_type get_executor() const noexcept
{
return next_layer_.lowest_layer().get_executor();
}
template <typename ReadHandler>
void operator()(ReadHandler&& handler,
buffered_stream_storage* storage) const
{
// If you get an error on the following line it means that your handler
// does not meet the documented type requirements for a ReadHandler.
ASIO_READ_HANDLER_CHECK(ReadHandler, handler) type_check;
non_const_lvalue<ReadHandler> handler2(handler);
std::size_t previous_size = storage->size();
storage->resize(storage->capacity());
next_layer_.async_read_some(
buffer(
storage->data() + previous_size,
storage->size() - previous_size),
buffered_fill_handler<decay_t<ReadHandler>>(
*storage, previous_size, handler2.value));
}
private:
remove_reference_t<Stream>& next_layer_;
};
} // namespace detail
#if !defined(GENERATING_DOCUMENTATION)
template <template <typename, typename> class Associator,
typename ReadHandler, typename DefaultCandidate>
struct associator<Associator,
detail::buffered_fill_handler<ReadHandler>,
DefaultCandidate>
: Associator<ReadHandler, DefaultCandidate>
{
static typename Associator<ReadHandler, DefaultCandidate>::type get(
const detail::buffered_fill_handler<ReadHandler>& h) noexcept
{
return Associator<ReadHandler, DefaultCandidate>::get(h.handler_);
}
static auto get(const detail::buffered_fill_handler<ReadHandler>& h,
const DefaultCandidate& c) noexcept
-> decltype(Associator<ReadHandler, DefaultCandidate>::get(h.handler_, c))
{
return Associator<ReadHandler, DefaultCandidate>::get(h.handler_, c);
}
};
#endif // !defined(GENERATING_DOCUMENTATION)
template <typename Stream>
template <
ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code,
std::size_t)) ReadHandler>
inline auto buffered_read_stream<Stream>::async_fill(ReadHandler&& handler)
-> decltype(
async_initiate<ReadHandler,
void (asio::error_code, std::size_t)>(
declval<detail::initiate_async_buffered_fill<Stream>>(),
handler, declval<detail::buffered_stream_storage*>()))
{
return async_initiate<ReadHandler,
void (asio::error_code, std::size_t)>(
detail::initiate_async_buffered_fill<Stream>(next_layer_),
handler, &storage_);
}
template <typename Stream>
template <typename MutableBufferSequence>
std::size_t buffered_read_stream<Stream>::read_some(
const MutableBufferSequence& buffers)
{
using asio::buffer_size;
if (buffer_size(buffers) == 0)
return 0;
if (storage_.empty())
this->fill();
return this->copy(buffers);
}
template <typename Stream>
template <typename MutableBufferSequence>
std::size_t buffered_read_stream<Stream>::read_some(
const MutableBufferSequence& buffers, asio::error_code& ec)
{
ec = asio::error_code();
using asio::buffer_size;
if (buffer_size(buffers) == 0)
return 0;
if (storage_.empty() && !this->fill(ec))
return 0;
return this->copy(buffers);
}
namespace detail
{
template <typename MutableBufferSequence, typename ReadHandler>
class buffered_read_some_handler
{
public:
buffered_read_some_handler(detail::buffered_stream_storage& storage,
const MutableBufferSequence& buffers, ReadHandler& handler)
: storage_(storage),
buffers_(buffers),
handler_(static_cast<ReadHandler&&>(handler))
{
}
buffered_read_some_handler(const buffered_read_some_handler& other)
: storage_(other.storage_),
buffers_(other.buffers_),
handler_(other.handler_)
{
}
buffered_read_some_handler(buffered_read_some_handler&& other)
: storage_(other.storage_),
buffers_(other.buffers_),
handler_(static_cast<ReadHandler&&>(other.handler_))
{
}
void operator()(const asio::error_code& ec, std::size_t)
{
if (ec || storage_.empty())
{
const std::size_t length = 0;
static_cast<ReadHandler&&>(handler_)(ec, length);
}
else
{
const std::size_t bytes_copied = asio::buffer_copy(
buffers_, storage_.data(), storage_.size());
storage_.consume(bytes_copied);
static_cast<ReadHandler&&>(handler_)(ec, bytes_copied);
}
}
//private:
detail::buffered_stream_storage& storage_;
MutableBufferSequence buffers_;
ReadHandler handler_;
};
template <typename MutableBufferSequence, typename ReadHandler>
inline bool asio_handler_is_continuation(
buffered_read_some_handler<
MutableBufferSequence, ReadHandler>* this_handler)
{
return asio_handler_cont_helpers::is_continuation(
this_handler->handler_);
}
template <typename Stream>
class initiate_async_buffered_read_some
{
public:
typedef typename remove_reference_t<
Stream>::lowest_layer_type::executor_type executor_type;
explicit initiate_async_buffered_read_some(
remove_reference_t<Stream>& next_layer)
: next_layer_(next_layer)
{
}
executor_type get_executor() const noexcept
{
return next_layer_.lowest_layer().get_executor();
}
template <typename ReadHandler, typename MutableBufferSequence>
void operator()(ReadHandler&& handler,
buffered_stream_storage* storage,
const MutableBufferSequence& buffers) const
{
// If you get an error on the following line it means that your handler
// does not meet the documented type requirements for a ReadHandler.
ASIO_READ_HANDLER_CHECK(ReadHandler, handler) type_check;
using asio::buffer_size;
non_const_lvalue<ReadHandler> handler2(handler);
if (buffer_size(buffers) == 0 || !storage->empty())
{
next_layer_.async_read_some(ASIO_MUTABLE_BUFFER(0, 0),
buffered_read_some_handler<MutableBufferSequence,
decay_t<ReadHandler>>(
*storage, buffers, handler2.value));
}
else
{
initiate_async_buffered_fill<Stream>(this->next_layer_)(
buffered_read_some_handler<MutableBufferSequence,
decay_t<ReadHandler>>(
*storage, buffers, handler2.value),
storage);
}
}
private:
remove_reference_t<Stream>& next_layer_;
};
} // namespace detail
#if !defined(GENERATING_DOCUMENTATION)
template <template <typename, typename> class Associator,
typename MutableBufferSequence, typename ReadHandler,
typename DefaultCandidate>
struct associator<Associator,
detail::buffered_read_some_handler<MutableBufferSequence, ReadHandler>,
DefaultCandidate>
: Associator<ReadHandler, DefaultCandidate>
{
static typename Associator<ReadHandler, DefaultCandidate>::type get(
const detail::buffered_read_some_handler<
MutableBufferSequence, ReadHandler>& h) noexcept
{
return Associator<ReadHandler, DefaultCandidate>::get(h.handler_);
}
static auto get(
const detail::buffered_read_some_handler<
MutableBufferSequence, ReadHandler>& h,
const DefaultCandidate& c) noexcept
-> decltype(Associator<ReadHandler, DefaultCandidate>::get(h.handler_, c))
{
return Associator<ReadHandler, DefaultCandidate>::get(h.handler_, c);
}
};
#endif // !defined(GENERATING_DOCUMENTATION)
template <typename Stream>
template <typename MutableBufferSequence,
ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code,
std::size_t)) ReadHandler>
inline auto buffered_read_stream<Stream>::async_read_some(
const MutableBufferSequence& buffers, ReadHandler&& handler)
-> decltype(
async_initiate<ReadHandler,
void (asio::error_code, std::size_t)>(
declval<detail::initiate_async_buffered_read_some<Stream>>(),
handler, declval<detail::buffered_stream_storage*>(), buffers))
{
return async_initiate<ReadHandler,
void (asio::error_code, std::size_t)>(
detail::initiate_async_buffered_read_some<Stream>(next_layer_),
handler, &storage_, buffers);
}
template <typename Stream>
template <typename MutableBufferSequence>
std::size_t buffered_read_stream<Stream>::peek(
const MutableBufferSequence& buffers)
{
if (storage_.empty())
this->fill();
return this->peek_copy(buffers);
}
template <typename Stream>
template <typename MutableBufferSequence>
std::size_t buffered_read_stream<Stream>::peek(
const MutableBufferSequence& buffers, asio::error_code& ec)
{
ec = asio::error_code();
if (storage_.empty() && !this->fill(ec))
return 0;
return this->peek_copy(buffers);
}
} // namespace asio
#include "asio/detail/pop_options.hpp"
#endif // ASIO_IMPL_BUFFERED_READ_STREAM_HPP
|
0 | repos/asio/asio/include/asio | repos/asio/asio/include/asio/impl/connect.hpp | //
// impl/connect.hpp
// ~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef ASIO_IMPL_CONNECT_HPP
#define ASIO_IMPL_CONNECT_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <algorithm>
#include "asio/associator.hpp"
#include "asio/detail/base_from_cancellation_state.hpp"
#include "asio/detail/bind_handler.hpp"
#include "asio/detail/handler_cont_helpers.hpp"
#include "asio/detail/handler_tracking.hpp"
#include "asio/detail/handler_type_requirements.hpp"
#include "asio/detail/non_const_lvalue.hpp"
#include "asio/detail/throw_error.hpp"
#include "asio/detail/type_traits.hpp"
#include "asio/error.hpp"
#include "asio/post.hpp"
#include "asio/detail/push_options.hpp"
namespace asio {
namespace detail
{
template <typename Protocol, typename Iterator>
inline typename Protocol::endpoint deref_connect_result(
Iterator iter, asio::error_code& ec)
{
return ec ? typename Protocol::endpoint() : *iter;
}
template <typename ConnectCondition, typename Iterator>
inline Iterator call_connect_condition(ConnectCondition& connect_condition,
const asio::error_code& ec, Iterator next, Iterator end,
constraint_t<
is_same<
result_of_t<ConnectCondition(asio::error_code, Iterator)>,
Iterator
>::value
> = 0)
{
if (next != end)
return connect_condition(ec, next);
return end;
}
template <typename ConnectCondition, typename Iterator>
inline Iterator call_connect_condition(ConnectCondition& connect_condition,
const asio::error_code& ec, Iterator next, Iterator end,
constraint_t<
is_same<
result_of_t<ConnectCondition(asio::error_code,
decltype(*declval<Iterator>()))>,
bool
>::value
> = 0)
{
for (;next != end; ++next)
if (connect_condition(ec, *next))
return next;
return end;
}
} // namespace detail
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
>)
{
asio::error_code ec;
typename Protocol::endpoint result = connect(s, endpoints, ec);
asio::detail::throw_error(ec, "connect");
return result;
}
template <typename Protocol, typename Executor, typename EndpointSequence>
typename Protocol::endpoint connect(basic_socket<Protocol, Executor>& s,
const EndpointSequence& endpoints, asio::error_code& ec,
constraint_t<
is_endpoint_sequence<EndpointSequence>::value
>)
{
return detail::deref_connect_result<Protocol>(
connect(s, endpoints.begin(), endpoints.end(),
detail::default_connect_condition(), ec), ec);
}
#if !defined(ASIO_NO_DEPRECATED)
template <typename Protocol, typename Executor, typename Iterator>
Iterator connect(basic_socket<Protocol, Executor>& s, Iterator begin,
constraint_t<
!is_endpoint_sequence<Iterator>::value
>)
{
asio::error_code ec;
Iterator result = connect(s, begin, ec);
asio::detail::throw_error(ec, "connect");
return result;
}
template <typename Protocol, typename Executor, typename Iterator>
inline Iterator connect(basic_socket<Protocol, Executor>& s,
Iterator begin, asio::error_code& ec,
constraint_t<
!is_endpoint_sequence<Iterator>::value
>)
{
return connect(s, begin, Iterator(), detail::default_connect_condition(), ec);
}
#endif // !defined(ASIO_NO_DEPRECATED)
template <typename Protocol, typename Executor, typename Iterator>
Iterator connect(basic_socket<Protocol, Executor>& s,
Iterator begin, Iterator end)
{
asio::error_code ec;
Iterator result = connect(s, begin, end, ec);
asio::detail::throw_error(ec, "connect");
return result;
}
template <typename Protocol, typename Executor, typename Iterator>
inline Iterator connect(basic_socket<Protocol, Executor>& s,
Iterator begin, Iterator end, asio::error_code& ec)
{
return connect(s, begin, end, detail::default_connect_condition(), ec);
}
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
>,
constraint_t<
is_connect_condition<ConnectCondition,
decltype(declval<const EndpointSequence&>().begin())>::value
>)
{
asio::error_code ec;
typename Protocol::endpoint result = connect(
s, endpoints, connect_condition, ec);
asio::detail::throw_error(ec, "connect");
return result;
}
template <typename Protocol, typename Executor,
typename EndpointSequence, typename ConnectCondition>
typename Protocol::endpoint connect(basic_socket<Protocol, Executor>& s,
const EndpointSequence& endpoints, ConnectCondition connect_condition,
asio::error_code& ec,
constraint_t<
is_endpoint_sequence<EndpointSequence>::value
>,
constraint_t<
is_connect_condition<ConnectCondition,
decltype(declval<const EndpointSequence&>().begin())>::value
>)
{
return detail::deref_connect_result<Protocol>(
connect(s, endpoints.begin(), endpoints.end(),
connect_condition, ec), ec);
}
#if !defined(ASIO_NO_DEPRECATED)
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
>,
constraint_t<
is_connect_condition<ConnectCondition, Iterator>::value
>)
{
asio::error_code ec;
Iterator result = connect(s, begin, connect_condition, ec);
asio::detail::throw_error(ec, "connect");
return result;
}
template <typename Protocol, typename Executor,
typename Iterator, typename ConnectCondition>
inline Iterator connect(basic_socket<Protocol, Executor>& s,
Iterator begin, ConnectCondition connect_condition,
asio::error_code& ec,
constraint_t<
!is_endpoint_sequence<Iterator>::value
>,
constraint_t<
is_connect_condition<ConnectCondition, Iterator>::value
>)
{
return connect(s, begin, Iterator(), connect_condition, ec);
}
#endif // !defined(ASIO_NO_DEPRECATED)
template <typename Protocol, typename Executor,
typename Iterator, typename ConnectCondition>
Iterator connect(basic_socket<Protocol, Executor>& s, Iterator begin,
Iterator end, ConnectCondition connect_condition,
constraint_t<
is_connect_condition<ConnectCondition, Iterator>::value
>)
{
asio::error_code ec;
Iterator result = connect(s, begin, end, connect_condition, ec);
asio::detail::throw_error(ec, "connect");
return result;
}
template <typename Protocol, typename Executor,
typename Iterator, typename ConnectCondition>
Iterator connect(basic_socket<Protocol, Executor>& s, Iterator begin,
Iterator end, ConnectCondition connect_condition,
asio::error_code& ec,
constraint_t<
is_connect_condition<ConnectCondition, Iterator>::value
>)
{
ec = asio::error_code();
for (Iterator iter = begin; iter != end; ++iter)
{
iter = (detail::call_connect_condition(connect_condition, ec, iter, end));
if (iter != end)
{
s.close(ec);
s.connect(*iter, ec);
if (!ec)
return iter;
}
else
break;
}
if (!ec)
ec = asio::error::not_found;
return end;
}
namespace detail
{
// Enable the empty base class optimisation for the connect condition.
template <typename ConnectCondition>
class base_from_connect_condition
{
protected:
explicit base_from_connect_condition(
const ConnectCondition& connect_condition)
: connect_condition_(connect_condition)
{
}
template <typename Iterator>
void check_condition(const asio::error_code& ec,
Iterator& iter, Iterator& end)
{
iter = detail::call_connect_condition(connect_condition_, ec, iter, end);
}
private:
ConnectCondition connect_condition_;
};
// The default_connect_condition implementation is essentially a no-op. This
// template specialisation lets us eliminate all costs associated with it.
template <>
class base_from_connect_condition<default_connect_condition>
{
protected:
explicit base_from_connect_condition(const default_connect_condition&)
{
}
template <typename Iterator>
void check_condition(const asio::error_code&, Iterator&, Iterator&)
{
}
};
template <typename Protocol, typename Executor, typename EndpointSequence,
typename ConnectCondition, typename RangeConnectHandler>
class range_connect_op
: public base_from_cancellation_state<RangeConnectHandler>,
base_from_connect_condition<ConnectCondition>
{
public:
range_connect_op(basic_socket<Protocol, Executor>& sock,
const EndpointSequence& endpoints,
const ConnectCondition& connect_condition,
RangeConnectHandler& handler)
: base_from_cancellation_state<RangeConnectHandler>(
handler, enable_partial_cancellation()),
base_from_connect_condition<ConnectCondition>(connect_condition),
socket_(sock),
endpoints_(endpoints),
index_(0),
start_(0),
handler_(static_cast<RangeConnectHandler&&>(handler))
{
}
range_connect_op(const range_connect_op& other)
: base_from_cancellation_state<RangeConnectHandler>(other),
base_from_connect_condition<ConnectCondition>(other),
socket_(other.socket_),
endpoints_(other.endpoints_),
index_(other.index_),
start_(other.start_),
handler_(other.handler_)
{
}
range_connect_op(range_connect_op&& other)
: base_from_cancellation_state<RangeConnectHandler>(
static_cast<base_from_cancellation_state<RangeConnectHandler>&&>(
other)),
base_from_connect_condition<ConnectCondition>(other),
socket_(other.socket_),
endpoints_(other.endpoints_),
index_(other.index_),
start_(other.start_),
handler_(static_cast<RangeConnectHandler&&>(other.handler_))
{
}
void operator()(asio::error_code ec, int start = 0)
{
this->process(ec, start,
const_cast<const EndpointSequence&>(endpoints_).begin(),
const_cast<const EndpointSequence&>(endpoints_).end());
}
//private:
template <typename Iterator>
void process(asio::error_code ec,
int start, Iterator begin, Iterator end)
{
Iterator iter = begin;
std::advance(iter, index_);
switch (start_ = start)
{
case 1:
for (;;)
{
this->check_condition(ec, iter, end);
index_ = std::distance(begin, iter);
if (iter != end)
{
socket_.close(ec);
ASIO_HANDLER_LOCATION((__FILE__, __LINE__, "async_connect"));
socket_.async_connect(*iter,
static_cast<range_connect_op&&>(*this));
return;
}
if (start)
{
ec = asio::error::not_found;
ASIO_HANDLER_LOCATION((__FILE__, __LINE__, "async_connect"));
asio::post(socket_.get_executor(),
detail::bind_handler(
static_cast<range_connect_op&&>(*this), ec));
return;
}
/* fall-through */ default:
if (iter == end)
break;
if (!socket_.is_open())
{
ec = asio::error::operation_aborted;
break;
}
if (!ec)
break;
if (this->cancelled() != cancellation_type::none)
{
ec = asio::error::operation_aborted;
break;
}
++iter;
++index_;
}
static_cast<RangeConnectHandler&&>(handler_)(
static_cast<const asio::error_code&>(ec),
static_cast<const typename Protocol::endpoint&>(
ec || iter == end ? typename Protocol::endpoint() : *iter));
}
}
basic_socket<Protocol, Executor>& socket_;
EndpointSequence endpoints_;
std::size_t index_;
int start_;
RangeConnectHandler handler_;
};
template <typename Protocol, typename Executor, typename EndpointSequence,
typename ConnectCondition, typename RangeConnectHandler>
inline bool asio_handler_is_continuation(
range_connect_op<Protocol, Executor, EndpointSequence,
ConnectCondition, RangeConnectHandler>* this_handler)
{
return asio_handler_cont_helpers::is_continuation(
this_handler->handler_);
}
template <typename Protocol, typename Executor>
class initiate_async_range_connect
{
public:
typedef Executor executor_type;
explicit initiate_async_range_connect(basic_socket<Protocol, Executor>& s)
: socket_(s)
{
}
executor_type get_executor() const noexcept
{
return socket_.get_executor();
}
template <typename RangeConnectHandler,
typename EndpointSequence, typename ConnectCondition>
void operator()(RangeConnectHandler&& handler,
const EndpointSequence& endpoints,
const ConnectCondition& connect_condition) const
{
// If you get an error on the following line it means that your
// handler does not meet the documented type requirements for an
// RangeConnectHandler.
ASIO_RANGE_CONNECT_HANDLER_CHECK(RangeConnectHandler,
handler, typename Protocol::endpoint) type_check;
non_const_lvalue<RangeConnectHandler> handler2(handler);
range_connect_op<Protocol, Executor, EndpointSequence, ConnectCondition,
decay_t<RangeConnectHandler>>(socket_, endpoints,
connect_condition, handler2.value)(asio::error_code(), 1);
}
private:
basic_socket<Protocol, Executor>& socket_;
};
template <typename Protocol, typename Executor, typename Iterator,
typename ConnectCondition, typename IteratorConnectHandler>
class iterator_connect_op
: public base_from_cancellation_state<IteratorConnectHandler>,
base_from_connect_condition<ConnectCondition>
{
public:
iterator_connect_op(basic_socket<Protocol, Executor>& sock,
const Iterator& begin, const Iterator& end,
const ConnectCondition& connect_condition,
IteratorConnectHandler& handler)
: base_from_cancellation_state<IteratorConnectHandler>(
handler, enable_partial_cancellation()),
base_from_connect_condition<ConnectCondition>(connect_condition),
socket_(sock),
iter_(begin),
end_(end),
start_(0),
handler_(static_cast<IteratorConnectHandler&&>(handler))
{
}
iterator_connect_op(const iterator_connect_op& other)
: base_from_cancellation_state<IteratorConnectHandler>(other),
base_from_connect_condition<ConnectCondition>(other),
socket_(other.socket_),
iter_(other.iter_),
end_(other.end_),
start_(other.start_),
handler_(other.handler_)
{
}
iterator_connect_op(iterator_connect_op&& other)
: base_from_cancellation_state<IteratorConnectHandler>(
static_cast<base_from_cancellation_state<IteratorConnectHandler>&&>(
other)),
base_from_connect_condition<ConnectCondition>(other),
socket_(other.socket_),
iter_(other.iter_),
end_(other.end_),
start_(other.start_),
handler_(static_cast<IteratorConnectHandler&&>(other.handler_))
{
}
void operator()(asio::error_code ec, int start = 0)
{
switch (start_ = start)
{
case 1:
for (;;)
{
this->check_condition(ec, iter_, end_);
if (iter_ != end_)
{
socket_.close(ec);
ASIO_HANDLER_LOCATION((__FILE__, __LINE__, "async_connect"));
socket_.async_connect(*iter_,
static_cast<iterator_connect_op&&>(*this));
return;
}
if (start)
{
ec = asio::error::not_found;
ASIO_HANDLER_LOCATION((__FILE__, __LINE__, "async_connect"));
asio::post(socket_.get_executor(),
detail::bind_handler(
static_cast<iterator_connect_op&&>(*this), ec));
return;
}
/* fall-through */ default:
if (iter_ == end_)
break;
if (!socket_.is_open())
{
ec = asio::error::operation_aborted;
break;
}
if (!ec)
break;
if (this->cancelled() != cancellation_type::none)
{
ec = asio::error::operation_aborted;
break;
}
++iter_;
}
static_cast<IteratorConnectHandler&&>(handler_)(
static_cast<const asio::error_code&>(ec),
static_cast<const Iterator&>(iter_));
}
}
//private:
basic_socket<Protocol, Executor>& socket_;
Iterator iter_;
Iterator end_;
int start_;
IteratorConnectHandler handler_;
};
template <typename Protocol, typename Executor, typename Iterator,
typename ConnectCondition, typename IteratorConnectHandler>
inline bool asio_handler_is_continuation(
iterator_connect_op<Protocol, Executor, Iterator,
ConnectCondition, IteratorConnectHandler>* this_handler)
{
return asio_handler_cont_helpers::is_continuation(
this_handler->handler_);
}
template <typename Protocol, typename Executor>
class initiate_async_iterator_connect
{
public:
typedef Executor executor_type;
explicit initiate_async_iterator_connect(
basic_socket<Protocol, Executor>& s)
: socket_(s)
{
}
executor_type get_executor() const noexcept
{
return socket_.get_executor();
}
template <typename IteratorConnectHandler,
typename Iterator, typename ConnectCondition>
void operator()(IteratorConnectHandler&& handler,
Iterator begin, Iterator end,
const ConnectCondition& connect_condition) const
{
// If you get an error on the following line it means that your
// handler does not meet the documented type requirements for an
// IteratorConnectHandler.
ASIO_ITERATOR_CONNECT_HANDLER_CHECK(
IteratorConnectHandler, handler, Iterator) type_check;
non_const_lvalue<IteratorConnectHandler> handler2(handler);
iterator_connect_op<Protocol, Executor, Iterator, ConnectCondition,
decay_t<IteratorConnectHandler>>(socket_, begin, end,
connect_condition, handler2.value)(asio::error_code(), 1);
}
private:
basic_socket<Protocol, Executor>& socket_;
};
} // namespace detail
#if !defined(GENERATING_DOCUMENTATION)
template <template <typename, typename> class Associator,
typename Protocol, typename Executor, typename EndpointSequence,
typename ConnectCondition, typename RangeConnectHandler,
typename DefaultCandidate>
struct associator<Associator,
detail::range_connect_op<Protocol, Executor,
EndpointSequence, ConnectCondition, RangeConnectHandler>,
DefaultCandidate>
: Associator<RangeConnectHandler, DefaultCandidate>
{
static typename Associator<RangeConnectHandler, DefaultCandidate>::type get(
const detail::range_connect_op<Protocol, Executor, EndpointSequence,
ConnectCondition, RangeConnectHandler>& h) noexcept
{
return Associator<RangeConnectHandler, DefaultCandidate>::get(h.handler_);
}
static auto get(
const detail::range_connect_op<Protocol, Executor,
EndpointSequence, ConnectCondition, RangeConnectHandler>& h,
const DefaultCandidate& c) noexcept
-> decltype(
Associator<RangeConnectHandler, DefaultCandidate>::get(
h.handler_, c))
{
return Associator<RangeConnectHandler, DefaultCandidate>::get(
h.handler_, c);
}
};
template <template <typename, typename> class Associator,
typename Protocol, typename Executor, typename Iterator,
typename ConnectCondition, typename IteratorConnectHandler,
typename DefaultCandidate>
struct associator<Associator,
detail::iterator_connect_op<Protocol, Executor,
Iterator, ConnectCondition, IteratorConnectHandler>,
DefaultCandidate>
: Associator<IteratorConnectHandler, DefaultCandidate>
{
static typename Associator<IteratorConnectHandler, DefaultCandidate>::type
get(const detail::iterator_connect_op<Protocol, Executor, Iterator,
ConnectCondition, IteratorConnectHandler>& h) noexcept
{
return Associator<IteratorConnectHandler, DefaultCandidate>::get(
h.handler_);
}
static auto get(
const detail::iterator_connect_op<Protocol, Executor,
Iterator, ConnectCondition, IteratorConnectHandler>& h,
const DefaultCandidate& c) noexcept
-> decltype(
Associator<IteratorConnectHandler, DefaultCandidate>::get(
h.handler_, c))
{
return Associator<IteratorConnectHandler, DefaultCandidate>::get(
h.handler_, c);
}
};
#endif // !defined(GENERATING_DOCUMENTATION)
} // namespace asio
#include "asio/detail/pop_options.hpp"
#endif // ASIO_IMPL_CONNECT_HPP
|
0 | repos/asio/asio/include/asio | repos/asio/asio/include/asio/impl/buffered_write_stream.hpp | //
// impl/buffered_write_stream.hpp
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef ASIO_IMPL_BUFFERED_WRITE_STREAM_HPP
#define ASIO_IMPL_BUFFERED_WRITE_STREAM_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include "asio/associator.hpp"
#include "asio/detail/handler_cont_helpers.hpp"
#include "asio/detail/handler_type_requirements.hpp"
#include "asio/detail/non_const_lvalue.hpp"
#include "asio/detail/push_options.hpp"
namespace asio {
template <typename Stream>
std::size_t buffered_write_stream<Stream>::flush()
{
std::size_t bytes_written = write(next_layer_,
buffer(storage_.data(), storage_.size()));
storage_.consume(bytes_written);
return bytes_written;
}
template <typename Stream>
std::size_t buffered_write_stream<Stream>::flush(asio::error_code& ec)
{
std::size_t bytes_written = write(next_layer_,
buffer(storage_.data(), storage_.size()),
transfer_all(), ec);
storage_.consume(bytes_written);
return bytes_written;
}
namespace detail
{
template <typename WriteHandler>
class buffered_flush_handler
{
public:
buffered_flush_handler(detail::buffered_stream_storage& storage,
WriteHandler& handler)
: storage_(storage),
handler_(static_cast<WriteHandler&&>(handler))
{
}
buffered_flush_handler(const buffered_flush_handler& other)
: storage_(other.storage_),
handler_(other.handler_)
{
}
buffered_flush_handler(buffered_flush_handler&& other)
: storage_(other.storage_),
handler_(static_cast<WriteHandler&&>(other.handler_))
{
}
void operator()(const asio::error_code& ec,
const std::size_t bytes_written)
{
storage_.consume(bytes_written);
static_cast<WriteHandler&&>(handler_)(ec, bytes_written);
}
//private:
detail::buffered_stream_storage& storage_;
WriteHandler handler_;
};
template <typename WriteHandler>
inline bool asio_handler_is_continuation(
buffered_flush_handler<WriteHandler>* this_handler)
{
return asio_handler_cont_helpers::is_continuation(
this_handler->handler_);
}
template <typename Stream>
class initiate_async_buffered_flush
{
public:
typedef typename remove_reference_t<
Stream>::lowest_layer_type::executor_type executor_type;
explicit initiate_async_buffered_flush(
remove_reference_t<Stream>& next_layer)
: next_layer_(next_layer)
{
}
executor_type get_executor() const noexcept
{
return next_layer_.lowest_layer().get_executor();
}
template <typename WriteHandler>
void operator()(WriteHandler&& handler,
buffered_stream_storage* storage) const
{
// If you get an error on the following line it means that your handler
// does not meet the documented type requirements for a WriteHandler.
ASIO_WRITE_HANDLER_CHECK(WriteHandler, handler) type_check;
non_const_lvalue<WriteHandler> handler2(handler);
async_write(next_layer_, buffer(storage->data(), storage->size()),
buffered_flush_handler<decay_t<WriteHandler>>(
*storage, handler2.value));
}
private:
remove_reference_t<Stream>& next_layer_;
};
} // namespace detail
#if !defined(GENERATING_DOCUMENTATION)
template <template <typename, typename> class Associator,
typename WriteHandler, typename DefaultCandidate>
struct associator<Associator,
detail::buffered_flush_handler<WriteHandler>,
DefaultCandidate>
: Associator<WriteHandler, DefaultCandidate>
{
static typename Associator<WriteHandler, DefaultCandidate>::type get(
const detail::buffered_flush_handler<WriteHandler>& h) noexcept
{
return Associator<WriteHandler, DefaultCandidate>::get(h.handler_);
}
static auto get(const detail::buffered_flush_handler<WriteHandler>& h,
const DefaultCandidate& c) noexcept
-> decltype(Associator<WriteHandler, DefaultCandidate>::get(h.handler_, c))
{
return Associator<WriteHandler, DefaultCandidate>::get(h.handler_, c);
}
};
#endif // !defined(GENERATING_DOCUMENTATION)
template <typename Stream>
template <
ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code,
std::size_t)) WriteHandler>
inline auto buffered_write_stream<Stream>::async_flush(WriteHandler&& handler)
-> decltype(
async_initiate<WriteHandler,
void (asio::error_code, std::size_t)>(
declval<detail::initiate_async_buffered_flush<Stream>>(),
handler, declval<detail::buffered_stream_storage*>()))
{
return async_initiate<WriteHandler,
void (asio::error_code, std::size_t)>(
detail::initiate_async_buffered_flush<Stream>(next_layer_),
handler, &storage_);
}
template <typename Stream>
template <typename ConstBufferSequence>
std::size_t buffered_write_stream<Stream>::write_some(
const ConstBufferSequence& buffers)
{
using asio::buffer_size;
if (buffer_size(buffers) == 0)
return 0;
if (storage_.size() == storage_.capacity())
this->flush();
return this->copy(buffers);
}
template <typename Stream>
template <typename ConstBufferSequence>
std::size_t buffered_write_stream<Stream>::write_some(
const ConstBufferSequence& buffers, asio::error_code& ec)
{
ec = asio::error_code();
using asio::buffer_size;
if (buffer_size(buffers) == 0)
return 0;
if (storage_.size() == storage_.capacity() && !flush(ec))
return 0;
return this->copy(buffers);
}
namespace detail
{
template <typename ConstBufferSequence, typename WriteHandler>
class buffered_write_some_handler
{
public:
buffered_write_some_handler(detail::buffered_stream_storage& storage,
const ConstBufferSequence& buffers, WriteHandler& handler)
: storage_(storage),
buffers_(buffers),
handler_(static_cast<WriteHandler&&>(handler))
{
}
buffered_write_some_handler(const buffered_write_some_handler& other)
: storage_(other.storage_),
buffers_(other.buffers_),
handler_(other.handler_)
{
}
buffered_write_some_handler(buffered_write_some_handler&& other)
: storage_(other.storage_),
buffers_(other.buffers_),
handler_(static_cast<WriteHandler&&>(other.handler_))
{
}
void operator()(const asio::error_code& ec, std::size_t)
{
if (ec)
{
const std::size_t length = 0;
static_cast<WriteHandler&&>(handler_)(ec, length);
}
else
{
using asio::buffer_size;
std::size_t orig_size = storage_.size();
std::size_t space_avail = storage_.capacity() - orig_size;
std::size_t bytes_avail = buffer_size(buffers_);
std::size_t length = bytes_avail < space_avail
? bytes_avail : space_avail;
storage_.resize(orig_size + length);
const std::size_t bytes_copied = asio::buffer_copy(
storage_.data() + orig_size, buffers_, length);
static_cast<WriteHandler&&>(handler_)(ec, bytes_copied);
}
}
//private:
detail::buffered_stream_storage& storage_;
ConstBufferSequence buffers_;
WriteHandler handler_;
};
template <typename ConstBufferSequence, typename WriteHandler>
inline bool asio_handler_is_continuation(
buffered_write_some_handler<
ConstBufferSequence, WriteHandler>* this_handler)
{
return asio_handler_cont_helpers::is_continuation(
this_handler->handler_);
}
template <typename Stream>
class initiate_async_buffered_write_some
{
public:
typedef typename remove_reference_t<
Stream>::lowest_layer_type::executor_type executor_type;
explicit initiate_async_buffered_write_some(
remove_reference_t<Stream>& next_layer)
: next_layer_(next_layer)
{
}
executor_type get_executor() const noexcept
{
return next_layer_.lowest_layer().get_executor();
}
template <typename WriteHandler, typename ConstBufferSequence>
void operator()(WriteHandler&& handler,
buffered_stream_storage* storage,
const ConstBufferSequence& buffers) const
{
// If you get an error on the following line it means that your handler
// does not meet the documented type requirements for a WriteHandler.
ASIO_WRITE_HANDLER_CHECK(WriteHandler, handler) type_check;
using asio::buffer_size;
non_const_lvalue<WriteHandler> handler2(handler);
if (buffer_size(buffers) == 0 || storage->size() < storage->capacity())
{
next_layer_.async_write_some(ASIO_CONST_BUFFER(0, 0),
buffered_write_some_handler<ConstBufferSequence,
decay_t<WriteHandler>>(
*storage, buffers, handler2.value));
}
else
{
initiate_async_buffered_flush<Stream>(this->next_layer_)(
buffered_write_some_handler<ConstBufferSequence,
decay_t<WriteHandler>>(
*storage, buffers, handler2.value),
storage);
}
}
private:
remove_reference_t<Stream>& next_layer_;
};
} // namespace detail
#if !defined(GENERATING_DOCUMENTATION)
template <template <typename, typename> class Associator,
typename ConstBufferSequence, typename WriteHandler,
typename DefaultCandidate>
struct associator<Associator,
detail::buffered_write_some_handler<ConstBufferSequence, WriteHandler>,
DefaultCandidate>
: Associator<WriteHandler, DefaultCandidate>
{
static typename Associator<WriteHandler, DefaultCandidate>::type get(
const detail::buffered_write_some_handler<
ConstBufferSequence, WriteHandler>& h) noexcept
{
return Associator<WriteHandler, DefaultCandidate>::get(h.handler_);
}
static auto get(
const detail::buffered_write_some_handler<
ConstBufferSequence, WriteHandler>& h,
const DefaultCandidate& c) noexcept
-> decltype(Associator<WriteHandler, DefaultCandidate>::get(h.handler_, c))
{
return Associator<WriteHandler, DefaultCandidate>::get(h.handler_, c);
}
};
#endif // !defined(GENERATING_DOCUMENTATION)
template <typename Stream>
template <typename ConstBufferSequence,
ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code,
std::size_t)) WriteHandler>
inline auto buffered_write_stream<Stream>::async_write_some(
const ConstBufferSequence& buffers, WriteHandler&& handler)
-> decltype(
async_initiate<WriteHandler,
void (asio::error_code, std::size_t)>(
declval<detail::initiate_async_buffered_write_some<Stream>>(),
handler, declval<detail::buffered_stream_storage*>(), buffers))
{
return async_initiate<WriteHandler,
void (asio::error_code, std::size_t)>(
detail::initiate_async_buffered_write_some<Stream>(next_layer_),
handler, &storage_, buffers);
}
template <typename Stream>
template <typename ConstBufferSequence>
std::size_t buffered_write_stream<Stream>::copy(
const ConstBufferSequence& buffers)
{
using asio::buffer_size;
std::size_t orig_size = storage_.size();
std::size_t space_avail = storage_.capacity() - orig_size;
std::size_t bytes_avail = buffer_size(buffers);
std::size_t length = bytes_avail < space_avail ? bytes_avail : space_avail;
storage_.resize(orig_size + length);
return asio::buffer_copy(
storage_.data() + orig_size, buffers, length);
}
} // namespace asio
#include "asio/detail/pop_options.hpp"
#endif // ASIO_IMPL_BUFFERED_WRITE_STREAM_HPP
|
0 | repos/asio/asio/include/asio | repos/asio/asio/include/asio/impl/write_at.hpp | //
// impl/write_at.hpp
// ~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef ASIO_IMPL_WRITE_AT_HPP
#define ASIO_IMPL_WRITE_AT_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include "asio/associator.hpp"
#include "asio/buffer.hpp"
#include "asio/detail/array_fwd.hpp"
#include "asio/detail/base_from_cancellation_state.hpp"
#include "asio/detail/base_from_completion_cond.hpp"
#include "asio/detail/bind_handler.hpp"
#include "asio/detail/consuming_buffers.hpp"
#include "asio/detail/dependent_type.hpp"
#include "asio/detail/handler_cont_helpers.hpp"
#include "asio/detail/handler_tracking.hpp"
#include "asio/detail/handler_type_requirements.hpp"
#include "asio/detail/non_const_lvalue.hpp"
#include "asio/detail/throw_error.hpp"
#include "asio/detail/push_options.hpp"
namespace asio {
namespace detail
{
template <typename SyncRandomAccessWriteDevice, typename ConstBufferSequence,
typename ConstBufferIterator, typename CompletionCondition>
std::size_t write_at_buffer_sequence(SyncRandomAccessWriteDevice& d,
uint64_t offset, const ConstBufferSequence& buffers,
const ConstBufferIterator&, CompletionCondition completion_condition,
asio::error_code& ec)
{
ec = asio::error_code();
asio::detail::consuming_buffers<const_buffer,
ConstBufferSequence, ConstBufferIterator> tmp(buffers);
while (!tmp.empty())
{
if (std::size_t max_size = detail::adapt_completion_condition_result(
completion_condition(ec, tmp.total_consumed())))
{
tmp.consume(d.write_some_at(offset + tmp.total_consumed(),
tmp.prepare(max_size), ec));
}
else
break;
}
return tmp.total_consumed();
}
} // namespace detail
template <typename SyncRandomAccessWriteDevice, typename ConstBufferSequence,
typename CompletionCondition>
std::size_t write_at(SyncRandomAccessWriteDevice& d,
uint64_t offset, const ConstBufferSequence& buffers,
CompletionCondition completion_condition, asio::error_code& ec,
constraint_t<
is_completion_condition<CompletionCondition>::value
>)
{
return detail::write_at_buffer_sequence(d, offset, buffers,
asio::buffer_sequence_begin(buffers),
static_cast<CompletionCondition&&>(completion_condition), ec);
}
template <typename SyncRandomAccessWriteDevice, typename ConstBufferSequence>
inline std::size_t write_at(SyncRandomAccessWriteDevice& d,
uint64_t offset, const ConstBufferSequence& buffers)
{
asio::error_code ec;
std::size_t bytes_transferred = write_at(
d, offset, buffers, transfer_all(), ec);
asio::detail::throw_error(ec, "write_at");
return bytes_transferred;
}
template <typename SyncRandomAccessWriteDevice, typename ConstBufferSequence>
inline std::size_t write_at(SyncRandomAccessWriteDevice& d,
uint64_t offset, const ConstBufferSequence& buffers,
asio::error_code& ec)
{
return write_at(d, offset, buffers, transfer_all(), ec);
}
template <typename SyncRandomAccessWriteDevice, typename ConstBufferSequence,
typename CompletionCondition>
inline std::size_t write_at(SyncRandomAccessWriteDevice& d,
uint64_t offset, const ConstBufferSequence& buffers,
CompletionCondition completion_condition,
constraint_t<
is_completion_condition<CompletionCondition>::value
>)
{
asio::error_code ec;
std::size_t bytes_transferred = write_at(d, offset, buffers,
static_cast<CompletionCondition&&>(completion_condition), ec);
asio::detail::throw_error(ec, "write_at");
return bytes_transferred;
}
#if !defined(ASIO_NO_EXTENSIONS)
#if !defined(ASIO_NO_IOSTREAM)
template <typename SyncRandomAccessWriteDevice, typename Allocator,
typename CompletionCondition>
std::size_t write_at(SyncRandomAccessWriteDevice& d,
uint64_t offset, asio::basic_streambuf<Allocator>& b,
CompletionCondition completion_condition, asio::error_code& ec,
constraint_t<
is_completion_condition<CompletionCondition>::value
>)
{
std::size_t bytes_transferred = write_at(d, offset, b.data(),
static_cast<CompletionCondition&&>(completion_condition), ec);
b.consume(bytes_transferred);
return bytes_transferred;
}
template <typename SyncRandomAccessWriteDevice, typename Allocator>
inline std::size_t write_at(SyncRandomAccessWriteDevice& d,
uint64_t offset, asio::basic_streambuf<Allocator>& b)
{
asio::error_code ec;
std::size_t bytes_transferred = write_at(d, offset, b, transfer_all(), ec);
asio::detail::throw_error(ec, "write_at");
return bytes_transferred;
}
template <typename SyncRandomAccessWriteDevice, typename Allocator>
inline std::size_t write_at(SyncRandomAccessWriteDevice& d,
uint64_t offset, asio::basic_streambuf<Allocator>& b,
asio::error_code& ec)
{
return write_at(d, offset, b, transfer_all(), ec);
}
template <typename SyncRandomAccessWriteDevice, typename Allocator,
typename CompletionCondition>
inline std::size_t write_at(SyncRandomAccessWriteDevice& d,
uint64_t offset, asio::basic_streambuf<Allocator>& b,
CompletionCondition completion_condition,
constraint_t<
is_completion_condition<CompletionCondition>::value
>)
{
asio::error_code ec;
std::size_t bytes_transferred = write_at(d, offset, b,
static_cast<CompletionCondition&&>(completion_condition), ec);
asio::detail::throw_error(ec, "write_at");
return bytes_transferred;
}
#endif // !defined(ASIO_NO_IOSTREAM)
#endif // !defined(ASIO_NO_EXTENSIONS)
namespace detail
{
template <typename AsyncRandomAccessWriteDevice,
typename ConstBufferSequence, typename ConstBufferIterator,
typename CompletionCondition, typename WriteHandler>
class write_at_op
: public base_from_cancellation_state<WriteHandler>,
base_from_completion_cond<CompletionCondition>
{
public:
write_at_op(AsyncRandomAccessWriteDevice& device,
uint64_t offset, const ConstBufferSequence& buffers,
CompletionCondition& completion_condition, WriteHandler& handler)
: base_from_cancellation_state<WriteHandler>(
handler, enable_partial_cancellation()),
base_from_completion_cond<CompletionCondition>(completion_condition),
device_(device),
offset_(offset),
buffers_(buffers),
start_(0),
handler_(static_cast<WriteHandler&&>(handler))
{
}
write_at_op(const write_at_op& other)
: base_from_cancellation_state<WriteHandler>(other),
base_from_completion_cond<CompletionCondition>(other),
device_(other.device_),
offset_(other.offset_),
buffers_(other.buffers_),
start_(other.start_),
handler_(other.handler_)
{
}
write_at_op(write_at_op&& other)
: base_from_cancellation_state<WriteHandler>(
static_cast<base_from_cancellation_state<WriteHandler>&&>(other)),
base_from_completion_cond<CompletionCondition>(
static_cast<base_from_completion_cond<CompletionCondition>&&>(other)),
device_(other.device_),
offset_(other.offset_),
buffers_(static_cast<buffers_type&&>(other.buffers_)),
start_(other.start_),
handler_(static_cast<WriteHandler&&>(other.handler_))
{
}
void operator()(asio::error_code ec,
std::size_t bytes_transferred, int start = 0)
{
std::size_t max_size;
switch (start_ = start)
{
case 1:
max_size = this->check_for_completion(ec, buffers_.total_consumed());
for (;;)
{
{
ASIO_HANDLER_LOCATION((__FILE__, __LINE__, "async_write_at"));
device_.async_write_some_at(
offset_ + buffers_.total_consumed(), buffers_.prepare(max_size),
static_cast<write_at_op&&>(*this));
}
return; default:
buffers_.consume(bytes_transferred);
if ((!ec && bytes_transferred == 0) || buffers_.empty())
break;
max_size = this->check_for_completion(ec, buffers_.total_consumed());
if (max_size == 0)
break;
if (this->cancelled() != cancellation_type::none)
{
ec = asio::error::operation_aborted;
break;
}
}
static_cast<WriteHandler&&>(handler_)(
static_cast<const asio::error_code&>(ec),
static_cast<const std::size_t&>(buffers_.total_consumed()));
}
}
//private:
typedef asio::detail::consuming_buffers<const_buffer,
ConstBufferSequence, ConstBufferIterator> buffers_type;
AsyncRandomAccessWriteDevice& device_;
uint64_t offset_;
buffers_type buffers_;
int start_;
WriteHandler handler_;
};
template <typename AsyncRandomAccessWriteDevice,
typename ConstBufferSequence, typename ConstBufferIterator,
typename CompletionCondition, typename WriteHandler>
inline bool asio_handler_is_continuation(
write_at_op<AsyncRandomAccessWriteDevice, ConstBufferSequence,
ConstBufferIterator, CompletionCondition, WriteHandler>* this_handler)
{
return this_handler->start_ == 0 ? true
: asio_handler_cont_helpers::is_continuation(
this_handler->handler_);
}
template <typename AsyncRandomAccessWriteDevice,
typename ConstBufferSequence, typename ConstBufferIterator,
typename CompletionCondition, typename WriteHandler>
inline void start_write_at_op(AsyncRandomAccessWriteDevice& d,
uint64_t offset, const ConstBufferSequence& buffers,
const ConstBufferIterator&, CompletionCondition& completion_condition,
WriteHandler& handler)
{
detail::write_at_op<AsyncRandomAccessWriteDevice, ConstBufferSequence,
ConstBufferIterator, CompletionCondition, WriteHandler>(
d, offset, buffers, completion_condition, handler)(
asio::error_code(), 0, 1);
}
template <typename AsyncRandomAccessWriteDevice>
class initiate_async_write_at
{
public:
typedef typename AsyncRandomAccessWriteDevice::executor_type executor_type;
explicit initiate_async_write_at(AsyncRandomAccessWriteDevice& device)
: device_(device)
{
}
executor_type get_executor() const noexcept
{
return device_.get_executor();
}
template <typename WriteHandler, typename ConstBufferSequence,
typename CompletionCondition>
void operator()(WriteHandler&& handler,
uint64_t offset, const ConstBufferSequence& buffers,
CompletionCondition&& completion_cond) const
{
// If you get an error on the following line it means that your handler
// does not meet the documented type requirements for a WriteHandler.
ASIO_WRITE_HANDLER_CHECK(WriteHandler, handler) type_check;
non_const_lvalue<WriteHandler> handler2(handler);
non_const_lvalue<CompletionCondition> completion_cond2(completion_cond);
start_write_at_op(device_, offset, buffers,
asio::buffer_sequence_begin(buffers),
completion_cond2.value, handler2.value);
}
private:
AsyncRandomAccessWriteDevice& device_;
};
} // namespace detail
#if !defined(GENERATING_DOCUMENTATION)
template <template <typename, typename> class Associator,
typename AsyncRandomAccessWriteDevice, typename ConstBufferSequence,
typename ConstBufferIterator, typename CompletionCondition,
typename WriteHandler, typename DefaultCandidate>
struct associator<Associator,
detail::write_at_op<AsyncRandomAccessWriteDevice, ConstBufferSequence,
ConstBufferIterator, CompletionCondition, WriteHandler>,
DefaultCandidate>
: Associator<WriteHandler, DefaultCandidate>
{
static typename Associator<WriteHandler, DefaultCandidate>::type get(
const detail::write_at_op<AsyncRandomAccessWriteDevice,
ConstBufferSequence, ConstBufferIterator,
CompletionCondition, WriteHandler>& h) noexcept
{
return Associator<WriteHandler, DefaultCandidate>::get(h.handler_);
}
static auto get(
const detail::write_at_op<AsyncRandomAccessWriteDevice,
ConstBufferSequence, ConstBufferIterator,
CompletionCondition, WriteHandler>& h,
const DefaultCandidate& c) noexcept
-> decltype(Associator<WriteHandler, DefaultCandidate>::get(h.handler_, c))
{
return Associator<WriteHandler, DefaultCandidate>::get(h.handler_, c);
}
};
#endif // !defined(GENERATING_DOCUMENTATION)
#if !defined(ASIO_NO_EXTENSIONS)
#if !defined(ASIO_NO_IOSTREAM)
namespace detail
{
template <typename Allocator, typename WriteHandler>
class write_at_streambuf_op
{
public:
write_at_streambuf_op(
asio::basic_streambuf<Allocator>& streambuf,
WriteHandler& handler)
: streambuf_(streambuf),
handler_(static_cast<WriteHandler&&>(handler))
{
}
write_at_streambuf_op(const write_at_streambuf_op& other)
: streambuf_(other.streambuf_),
handler_(other.handler_)
{
}
write_at_streambuf_op(write_at_streambuf_op&& other)
: streambuf_(other.streambuf_),
handler_(static_cast<WriteHandler&&>(other.handler_))
{
}
void operator()(const asio::error_code& ec,
const std::size_t bytes_transferred)
{
streambuf_.consume(bytes_transferred);
static_cast<WriteHandler&&>(handler_)(ec, bytes_transferred);
}
//private:
asio::basic_streambuf<Allocator>& streambuf_;
WriteHandler handler_;
};
template <typename Allocator, typename WriteHandler>
inline bool asio_handler_is_continuation(
write_at_streambuf_op<Allocator, WriteHandler>* this_handler)
{
return asio_handler_cont_helpers::is_continuation(
this_handler->handler_);
}
template <typename AsyncRandomAccessWriteDevice>
class initiate_async_write_at_streambuf
{
public:
typedef typename AsyncRandomAccessWriteDevice::executor_type executor_type;
explicit initiate_async_write_at_streambuf(
AsyncRandomAccessWriteDevice& device)
: device_(device)
{
}
executor_type get_executor() const noexcept
{
return device_.get_executor();
}
template <typename WriteHandler,
typename Allocator, typename CompletionCondition>
void operator()(WriteHandler&& handler,
uint64_t offset, basic_streambuf<Allocator>* b,
CompletionCondition&& completion_condition) const
{
// If you get an error on the following line it means that your handler
// does not meet the documented type requirements for a WriteHandler.
ASIO_WRITE_HANDLER_CHECK(WriteHandler, handler) type_check;
non_const_lvalue<WriteHandler> handler2(handler);
async_write_at(device_, offset, b->data(),
static_cast<CompletionCondition&&>(completion_condition),
write_at_streambuf_op<Allocator, decay_t<WriteHandler>>(
*b, handler2.value));
}
private:
AsyncRandomAccessWriteDevice& device_;
};
} // namespace detail
#if !defined(GENERATING_DOCUMENTATION)
template <template <typename, typename> class Associator,
typename Executor, typename WriteHandler, typename DefaultCandidate>
struct associator<Associator,
detail::write_at_streambuf_op<Executor, WriteHandler>,
DefaultCandidate>
: Associator<WriteHandler, DefaultCandidate>
{
static typename Associator<WriteHandler, DefaultCandidate>::type get(
const detail::write_at_streambuf_op<Executor, WriteHandler>& h) noexcept
{
return Associator<WriteHandler, DefaultCandidate>::get(h.handler_);
}
static auto get(
const detail::write_at_streambuf_op<Executor, WriteHandler>& h,
const DefaultCandidate& c) noexcept
-> decltype(Associator<WriteHandler, DefaultCandidate>::get(h.handler_, c))
{
return Associator<WriteHandler, DefaultCandidate>::get(h.handler_, c);
}
};
#endif // !defined(GENERATING_DOCUMENTATION)
#endif // !defined(ASIO_NO_IOSTREAM)
#endif // !defined(ASIO_NO_EXTENSIONS)
} // namespace asio
#include "asio/detail/pop_options.hpp"
#endif // ASIO_IMPL_WRITE_AT_HPP
|
0 | repos/asio/asio/include/asio | repos/asio/asio/include/asio/impl/use_future.hpp | //
// impl/use_future.hpp
// ~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef ASIO_IMPL_USE_FUTURE_HPP
#define ASIO_IMPL_USE_FUTURE_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include "asio/detail/config.hpp"
#include <tuple>
#include "asio/async_result.hpp"
#include "asio/detail/memory.hpp"
#include "asio/dispatch.hpp"
#include "asio/error_code.hpp"
#include "asio/execution.hpp"
#include "asio/packaged_task.hpp"
#include "asio/system_error.hpp"
#include "asio/system_executor.hpp"
#include "asio/detail/push_options.hpp"
namespace asio {
namespace detail {
template <typename T, typename F, typename... Args>
inline void promise_invoke_and_set(std::promise<T>& p,
F& f, Args&&... args)
{
#if !defined(ASIO_NO_EXCEPTIONS)
try
#endif // !defined(ASIO_NO_EXCEPTIONS)
{
p.set_value(f(static_cast<Args&&>(args)...));
}
#if !defined(ASIO_NO_EXCEPTIONS)
catch (...)
{
p.set_exception(std::current_exception());
}
#endif // !defined(ASIO_NO_EXCEPTIONS)
}
template <typename F, typename... Args>
inline void promise_invoke_and_set(std::promise<void>& p,
F& f, Args&&... args)
{
#if !defined(ASIO_NO_EXCEPTIONS)
try
#endif // !defined(ASIO_NO_EXCEPTIONS)
{
f(static_cast<Args&&>(args)...);
p.set_value();
}
#if !defined(ASIO_NO_EXCEPTIONS)
catch (...)
{
p.set_exception(std::current_exception());
}
#endif // !defined(ASIO_NO_EXCEPTIONS)
}
// A function object adapter to invoke a nullary function object and capture
// any exception thrown into a promise.
template <typename T, typename F>
class promise_invoker
{
public:
promise_invoker(const shared_ptr<std::promise<T>>& p,
F&& f)
: p_(p), f_(static_cast<F&&>(f))
{
}
void operator()()
{
#if !defined(ASIO_NO_EXCEPTIONS)
try
#endif // !defined(ASIO_NO_EXCEPTIONS)
{
f_();
}
#if !defined(ASIO_NO_EXCEPTIONS)
catch (...)
{
p_->set_exception(std::current_exception());
}
#endif // !defined(ASIO_NO_EXCEPTIONS)
}
private:
shared_ptr<std::promise<T>> p_;
decay_t<F> f_;
};
// An executor that adapts the system_executor to capture any exeption thrown
// by a submitted function object and save it into a promise.
template <typename T, typename Blocking = execution::blocking_t::possibly_t>
class promise_executor
{
public:
explicit promise_executor(const shared_ptr<std::promise<T>>& p)
: p_(p)
{
}
execution_context& query(execution::context_t) const noexcept
{
return asio::query(system_executor(), execution::context);
}
static constexpr Blocking query(execution::blocking_t)
{
return Blocking();
}
promise_executor<T, execution::blocking_t::possibly_t>
require(execution::blocking_t::possibly_t) const
{
return promise_executor<T, execution::blocking_t::possibly_t>(p_);
}
promise_executor<T, execution::blocking_t::never_t>
require(execution::blocking_t::never_t) const
{
return promise_executor<T, execution::blocking_t::never_t>(p_);
}
template <typename F>
void execute(F&& f) const
{
asio::require(system_executor(), Blocking()).execute(
promise_invoker<T, F>(p_, static_cast<F&&>(f)));
}
#if !defined(ASIO_NO_TS_EXECUTORS)
execution_context& context() const noexcept
{
return system_executor().context();
}
void on_work_started() const noexcept {}
void on_work_finished() const noexcept {}
template <typename F, typename A>
void dispatch(F&& f, const A&) const
{
promise_invoker<T, F>(p_, static_cast<F&&>(f))();
}
template <typename F, typename A>
void post(F&& f, const A& a) const
{
system_executor().post(
promise_invoker<T, F>(p_, static_cast<F&&>(f)), a);
}
template <typename F, typename A>
void defer(F&& f, const A& a) const
{
system_executor().defer(
promise_invoker<T, F>(p_, static_cast<F&&>(f)), a);
}
#endif // !defined(ASIO_NO_TS_EXECUTORS)
friend bool operator==(const promise_executor& a,
const promise_executor& b) noexcept
{
return a.p_ == b.p_;
}
friend bool operator!=(const promise_executor& a,
const promise_executor& b) noexcept
{
return a.p_ != b.p_;
}
private:
shared_ptr<std::promise<T>> p_;
};
// The base class for all completion handlers that create promises.
template <typename T>
class promise_creator
{
public:
typedef promise_executor<T> executor_type;
executor_type get_executor() const noexcept
{
return executor_type(p_);
}
typedef std::future<T> future_type;
future_type get_future()
{
return p_->get_future();
}
protected:
template <typename Allocator>
void create_promise(const Allocator& a)
{
ASIO_REBIND_ALLOC(Allocator, char) b(a);
p_ = std::allocate_shared<std::promise<T>>(b, std::allocator_arg, b);
}
shared_ptr<std::promise<T>> p_;
};
// For completion signature void().
class promise_handler_0
: public promise_creator<void>
{
public:
void operator()()
{
this->p_->set_value();
}
};
// For completion signature void(error_code).
class promise_handler_ec_0
: public promise_creator<void>
{
public:
void operator()(const asio::error_code& ec)
{
if (ec)
{
this->p_->set_exception(
std::make_exception_ptr(
asio::system_error(ec)));
}
else
{
this->p_->set_value();
}
}
};
// For completion signature void(exception_ptr).
class promise_handler_ex_0
: public promise_creator<void>
{
public:
void operator()(const std::exception_ptr& ex)
{
if (ex)
{
this->p_->set_exception(ex);
}
else
{
this->p_->set_value();
}
}
};
// For completion signature void(T).
template <typename T>
class promise_handler_1
: public promise_creator<T>
{
public:
template <typename Arg>
void operator()(Arg&& arg)
{
this->p_->set_value(static_cast<Arg&&>(arg));
}
};
// For completion signature void(error_code, T).
template <typename T>
class promise_handler_ec_1
: public promise_creator<T>
{
public:
template <typename Arg>
void operator()(const asio::error_code& ec,
Arg&& arg)
{
if (ec)
{
this->p_->set_exception(
std::make_exception_ptr(
asio::system_error(ec)));
}
else
this->p_->set_value(static_cast<Arg&&>(arg));
}
};
// For completion signature void(exception_ptr, T).
template <typename T>
class promise_handler_ex_1
: public promise_creator<T>
{
public:
template <typename Arg>
void operator()(const std::exception_ptr& ex,
Arg&& arg)
{
if (ex)
this->p_->set_exception(ex);
else
this->p_->set_value(static_cast<Arg&&>(arg));
}
};
// For completion signature void(T1, ..., Tn);
template <typename T>
class promise_handler_n
: public promise_creator<T>
{
public:
template <typename... Args>
void operator()(Args&&... args)
{
this->p_->set_value(
std::forward_as_tuple(
static_cast<Args&&>(args)...));
}
};
// For completion signature void(error_code, T1, ..., Tn);
template <typename T>
class promise_handler_ec_n
: public promise_creator<T>
{
public:
template <typename... Args>
void operator()(const asio::error_code& ec, Args&&... args)
{
if (ec)
{
this->p_->set_exception(
std::make_exception_ptr(
asio::system_error(ec)));
}
else
{
this->p_->set_value(
std::forward_as_tuple(
static_cast<Args&&>(args)...));
}
}
};
// For completion signature void(exception_ptr, T1, ..., Tn);
template <typename T>
class promise_handler_ex_n
: public promise_creator<T>
{
public:
template <typename... Args>
void operator()(const std::exception_ptr& ex,
Args&&... args)
{
if (ex)
this->p_->set_exception(ex);
else
{
this->p_->set_value(
std::forward_as_tuple(
static_cast<Args&&>(args)...));
}
}
};
// Helper template to choose the appropriate concrete promise handler
// implementation based on the supplied completion signature.
template <typename> class promise_handler_selector;
template <>
class promise_handler_selector<void()>
: public promise_handler_0 {};
template <>
class promise_handler_selector<void(asio::error_code)>
: public promise_handler_ec_0 {};
template <>
class promise_handler_selector<void(std::exception_ptr)>
: public promise_handler_ex_0 {};
template <typename Arg>
class promise_handler_selector<void(Arg)>
: public promise_handler_1<Arg> {};
template <typename Arg>
class promise_handler_selector<void(asio::error_code, Arg)>
: public promise_handler_ec_1<Arg> {};
template <typename Arg>
class promise_handler_selector<void(std::exception_ptr, Arg)>
: public promise_handler_ex_1<Arg> {};
template <typename... Arg>
class promise_handler_selector<void(Arg...)>
: public promise_handler_n<std::tuple<Arg...>> {};
template <typename... Arg>
class promise_handler_selector<void(asio::error_code, Arg...)>
: public promise_handler_ec_n<std::tuple<Arg...>> {};
template <typename... Arg>
class promise_handler_selector<void(std::exception_ptr, Arg...)>
: public promise_handler_ex_n<std::tuple<Arg...>> {};
// Completion handlers produced from the use_future completion token, when not
// using use_future::operator().
template <typename Signature, typename Allocator>
class promise_handler
: public promise_handler_selector<Signature>
{
public:
typedef Allocator allocator_type;
typedef void result_type;
promise_handler(use_future_t<Allocator> u)
: allocator_(u.get_allocator())
{
this->create_promise(allocator_);
}
allocator_type get_allocator() const noexcept
{
return allocator_;
}
private:
Allocator allocator_;
};
template <typename Function>
struct promise_function_wrapper
{
explicit promise_function_wrapper(Function& f)
: function_(static_cast<Function&&>(f))
{
}
explicit promise_function_wrapper(const Function& f)
: function_(f)
{
}
void operator()()
{
function_();
}
Function function_;
};
// Helper base class for async_result specialisation.
template <typename Signature, typename Allocator>
class promise_async_result
{
public:
typedef promise_handler<Signature, Allocator> completion_handler_type;
typedef typename completion_handler_type::future_type return_type;
explicit promise_async_result(completion_handler_type& h)
: future_(h.get_future())
{
}
return_type get()
{
return static_cast<return_type&&>(future_);
}
private:
return_type future_;
};
// Return value from use_future::operator().
template <typename Function, typename Allocator>
class packaged_token
{
public:
packaged_token(Function f, const Allocator& a)
: function_(static_cast<Function&&>(f)),
allocator_(a)
{
}
//private:
Function function_;
Allocator allocator_;
};
// Completion handlers produced from the use_future completion token, when
// using use_future::operator().
template <typename Function, typename Allocator, typename Result>
class packaged_handler
: public promise_creator<Result>
{
public:
typedef Allocator allocator_type;
typedef void result_type;
packaged_handler(packaged_token<Function, Allocator> t)
: function_(static_cast<Function&&>(t.function_)),
allocator_(t.allocator_)
{
this->create_promise(allocator_);
}
allocator_type get_allocator() const noexcept
{
return allocator_;
}
template <typename... Args>
void operator()(Args&&... args)
{
(promise_invoke_and_set)(*this->p_,
function_, static_cast<Args&&>(args)...);
}
private:
Function function_;
Allocator allocator_;
};
// Helper base class for async_result specialisation.
template <typename Function, typename Allocator, typename Result>
class packaged_async_result
{
public:
typedef packaged_handler<Function, Allocator, Result> completion_handler_type;
typedef typename completion_handler_type::future_type return_type;
explicit packaged_async_result(completion_handler_type& h)
: future_(h.get_future())
{
}
return_type get()
{
return static_cast<return_type&&>(future_);
}
private:
return_type future_;
};
} // namespace detail
template <typename Allocator> template <typename Function>
inline detail::packaged_token<decay_t<Function>, Allocator>
use_future_t<Allocator>::operator()(Function&& f) const
{
return detail::packaged_token<decay_t<Function>, Allocator>(
static_cast<Function&&>(f), allocator_);
}
#if !defined(GENERATING_DOCUMENTATION)
template <typename Allocator, typename Result, typename... Args>
class async_result<use_future_t<Allocator>, Result(Args...)>
: public detail::promise_async_result<
void(decay_t<Args>...), Allocator>
{
public:
explicit async_result(
typename detail::promise_async_result<void(decay_t<Args>...),
Allocator>::completion_handler_type& h)
: detail::promise_async_result<
void(decay_t<Args>...), Allocator>(h)
{
}
};
template <typename Function, typename Allocator,
typename Result, typename... Args>
class async_result<detail::packaged_token<Function, Allocator>, Result(Args...)>
: public detail::packaged_async_result<Function, Allocator,
result_of_t<Function(Args...)>>
{
public:
explicit async_result(
typename detail::packaged_async_result<Function, Allocator,
result_of_t<Function(Args...)>>::completion_handler_type& h)
: detail::packaged_async_result<Function, Allocator,
result_of_t<Function(Args...)>>(h)
{
}
};
namespace traits {
#if !defined(ASIO_HAS_DEDUCED_EQUALITY_COMPARABLE_TRAIT)
template <typename T, typename Blocking>
struct equality_comparable<
asio::detail::promise_executor<T, Blocking>>
{
static constexpr bool is_valid = true;
static constexpr bool is_noexcept = true;
};
#endif // !defined(ASIO_HAS_DEDUCED_EQUALITY_COMPARABLE_TRAIT)
#if !defined(ASIO_HAS_DEDUCED_EXECUTE_MEMBER_TRAIT)
template <typename T, typename Blocking, typename Function>
struct execute_member<
asio::detail::promise_executor<T, Blocking>, Function>
{
static constexpr bool is_valid = true;
static constexpr bool is_noexcept = false;
typedef void result_type;
};
#endif // !defined(ASIO_HAS_DEDUCED_EXECUTE_MEMBER_TRAIT)
#if !defined(ASIO_HAS_DEDUCED_QUERY_STATIC_CONSTEXPR_MEMBER_TRAIT)
template <typename T, typename Blocking, typename Property>
struct query_static_constexpr_member<
asio::detail::promise_executor<T, Blocking>,
Property,
typename asio::enable_if<
asio::is_convertible<
Property,
asio::execution::blocking_t
>::value
>::type
>
{
static constexpr bool is_valid = true;
static constexpr bool is_noexcept = true;
typedef Blocking result_type;
static constexpr result_type value() noexcept
{
return Blocking();
}
};
#endif // !defined(ASIO_HAS_DEDUCED_QUERY_STATIC_CONSTEXPR_MEMBER_TRAIT)
#if !defined(ASIO_HAS_DEDUCED_QUERY_MEMBER_TRAIT)
template <typename T, typename Blocking>
struct query_member<
asio::detail::promise_executor<T, Blocking>,
execution::context_t
>
{
static constexpr bool is_valid = true;
static constexpr bool is_noexcept = true;
typedef asio::system_context& result_type;
};
#endif // !defined(ASIO_HAS_DEDUCED_QUERY_MEMBER_TRAIT)
#if !defined(ASIO_HAS_DEDUCED_REQUIRE_MEMBER_TRAIT)
template <typename T, typename Blocking>
struct require_member<
asio::detail::promise_executor<T, Blocking>,
execution::blocking_t::possibly_t
>
{
static constexpr bool is_valid = true;
static constexpr bool is_noexcept = true;
typedef asio::detail::promise_executor<T,
execution::blocking_t::possibly_t> result_type;
};
template <typename T, typename Blocking>
struct require_member<
asio::detail::promise_executor<T, Blocking>,
execution::blocking_t::never_t
>
{
static constexpr bool is_valid = true;
static constexpr bool is_noexcept = true;
typedef asio::detail::promise_executor<T,
execution::blocking_t::never_t> result_type;
};
#endif // !defined(ASIO_HAS_DEDUCED_REQUIRE_MEMBER_TRAIT)
} // namespace traits
#endif // !defined(GENERATING_DOCUMENTATION)
} // namespace asio
#include "asio/detail/pop_options.hpp"
#endif // ASIO_IMPL_USE_FUTURE_HPP
|
0 | repos/asio/asio/include/asio | repos/asio/asio/include/asio/impl/serial_port_base.hpp | //
// impl/serial_port_base.hpp
// ~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com)
// Copyright (c) 2008 Rep Invariant Systems, Inc. ([email protected])
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef ASIO_IMPL_SERIAL_PORT_BASE_HPP
#define ASIO_IMPL_SERIAL_PORT_BASE_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include "asio/detail/push_options.hpp"
namespace asio {
inline serial_port_base::baud_rate::baud_rate(unsigned int rate)
: value_(rate)
{
}
inline unsigned int serial_port_base::baud_rate::value() const
{
return value_;
}
inline serial_port_base::flow_control::type
serial_port_base::flow_control::value() const
{
return value_;
}
inline serial_port_base::parity::type serial_port_base::parity::value() const
{
return value_;
}
inline serial_port_base::stop_bits::type
serial_port_base::stop_bits::value() const
{
return value_;
}
inline unsigned int serial_port_base::character_size::value() const
{
return value_;
}
} // namespace asio
#include "asio/detail/pop_options.hpp"
#endif // ASIO_IMPL_SERIAL_PORT_BASE_HPP
|
0 | repos/asio/asio/include/asio | repos/asio/asio/include/asio/impl/multiple_exceptions.ipp | //
// impl/multiple_exceptions.ipp
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef ASIO_IMPL_MULTIPLE_EXCEPTIONS_IPP
#define ASIO_IMPL_MULTIPLE_EXCEPTIONS_IPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include "asio/detail/config.hpp"
#include "asio/multiple_exceptions.hpp"
#include "asio/detail/push_options.hpp"
namespace asio {
multiple_exceptions::multiple_exceptions(
std::exception_ptr first) noexcept
: first_(static_cast<std::exception_ptr&&>(first))
{
}
const char* multiple_exceptions::what() const noexcept
{
return "multiple exceptions";
}
std::exception_ptr multiple_exceptions::first_exception() const
{
return first_;
}
} // namespace asio
#include "asio/detail/pop_options.hpp"
#endif // ASIO_IMPL_MULTIPLE_EXCEPTIONS_IPP
|
0 | repos/asio/asio/include/asio | repos/asio/asio/include/asio/impl/system_executor.hpp | //
// impl/system_executor.hpp
// ~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef ASIO_IMPL_SYSTEM_EXECUTOR_HPP
#define ASIO_IMPL_SYSTEM_EXECUTOR_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include "asio/detail/executor_op.hpp"
#include "asio/detail/global.hpp"
#include "asio/detail/type_traits.hpp"
#include "asio/system_context.hpp"
#include "asio/detail/push_options.hpp"
namespace asio {
template <typename Blocking, typename Relationship, typename Allocator>
inline system_context&
basic_system_executor<Blocking, Relationship, Allocator>::query(
execution::context_t) noexcept
{
return detail::global<system_context>();
}
template <typename Blocking, typename Relationship, typename Allocator>
inline std::size_t
basic_system_executor<Blocking, Relationship, Allocator>::query(
execution::occupancy_t) const noexcept
{
return detail::global<system_context>().num_threads_;
}
template <typename Blocking, typename Relationship, typename Allocator>
template <typename Function>
inline void
basic_system_executor<Blocking, Relationship, Allocator>::do_execute(
Function&& f, execution::blocking_t::possibly_t) const
{
// Obtain a non-const instance of the function.
detail::non_const_lvalue<Function> f2(f);
#if !defined(ASIO_NO_EXCEPTIONS)
try
{
#endif// !defined(ASIO_NO_EXCEPTIONS)
detail::fenced_block b(detail::fenced_block::full);
static_cast<decay_t<Function>&&>(f2.value)();
#if !defined(ASIO_NO_EXCEPTIONS)
}
catch (...)
{
std::terminate();
}
#endif// !defined(ASIO_NO_EXCEPTIONS)
}
template <typename Blocking, typename Relationship, typename Allocator>
template <typename Function>
inline void
basic_system_executor<Blocking, Relationship, Allocator>::do_execute(
Function&& f, execution::blocking_t::always_t) const
{
// Obtain a non-const instance of the function.
detail::non_const_lvalue<Function> f2(f);
#if !defined(ASIO_NO_EXCEPTIONS)
try
{
#endif// !defined(ASIO_NO_EXCEPTIONS)
detail::fenced_block b(detail::fenced_block::full);
static_cast<decay_t<Function>&&>(f2.value)();
#if !defined(ASIO_NO_EXCEPTIONS)
}
catch (...)
{
std::terminate();
}
#endif// !defined(ASIO_NO_EXCEPTIONS)
}
template <typename Blocking, typename Relationship, typename Allocator>
template <typename Function>
void basic_system_executor<Blocking, Relationship, Allocator>::do_execute(
Function&& f, execution::blocking_t::never_t) const
{
system_context& ctx = detail::global<system_context>();
// Allocate and construct an operation to wrap the function.
typedef detail::executor_op<decay_t<Function>, Allocator> op;
typename op::ptr p = { detail::addressof(allocator_),
op::ptr::allocate(allocator_), 0 };
p.p = new (p.v) op(static_cast<Function&&>(f), allocator_);
if (is_same<Relationship, execution::relationship_t::continuation_t>::value)
{
ASIO_HANDLER_CREATION((ctx, *p.p,
"system_executor", &ctx, 0, "execute(blk=never,rel=cont)"));
}
else
{
ASIO_HANDLER_CREATION((ctx, *p.p,
"system_executor", &ctx, 0, "execute(blk=never,rel=fork)"));
}
ctx.scheduler_.post_immediate_completion(p.p,
is_same<Relationship, execution::relationship_t::continuation_t>::value);
p.v = p.p = 0;
}
#if !defined(ASIO_NO_TS_EXECUTORS)
template <typename Blocking, typename Relationship, typename Allocator>
inline system_context& basic_system_executor<
Blocking, Relationship, Allocator>::context() const noexcept
{
return detail::global<system_context>();
}
template <typename Blocking, typename Relationship, typename Allocator>
template <typename Function, typename OtherAllocator>
void basic_system_executor<Blocking, Relationship, Allocator>::dispatch(
Function&& f, const OtherAllocator&) const
{
decay_t<Function>(static_cast<Function&&>(f))();
}
template <typename Blocking, typename Relationship, typename Allocator>
template <typename Function, typename OtherAllocator>
void basic_system_executor<Blocking, Relationship, Allocator>::post(
Function&& f, const OtherAllocator& a) const
{
system_context& ctx = detail::global<system_context>();
// Allocate and construct an operation to wrap the function.
typedef detail::executor_op<decay_t<Function>, OtherAllocator> op;
typename op::ptr p = { detail::addressof(a), op::ptr::allocate(a), 0 };
p.p = new (p.v) op(static_cast<Function&&>(f), a);
ASIO_HANDLER_CREATION((ctx, *p.p,
"system_executor", &this->context(), 0, "post"));
ctx.scheduler_.post_immediate_completion(p.p, false);
p.v = p.p = 0;
}
template <typename Blocking, typename Relationship, typename Allocator>
template <typename Function, typename OtherAllocator>
void basic_system_executor<Blocking, Relationship, Allocator>::defer(
Function&& f, const OtherAllocator& a) const
{
system_context& ctx = detail::global<system_context>();
// Allocate and construct an operation to wrap the function.
typedef detail::executor_op<decay_t<Function>, OtherAllocator> op;
typename op::ptr p = { detail::addressof(a), op::ptr::allocate(a), 0 };
p.p = new (p.v) op(static_cast<Function&&>(f), a);
ASIO_HANDLER_CREATION((ctx, *p.p,
"system_executor", &this->context(), 0, "defer"));
ctx.scheduler_.post_immediate_completion(p.p, true);
p.v = p.p = 0;
}
#endif // !defined(ASIO_NO_TS_EXECUTORS)
} // namespace asio
#include "asio/detail/pop_options.hpp"
#endif // ASIO_IMPL_SYSTEM_EXECUTOR_HPP
|
0 | repos/asio/asio/include/asio | repos/asio/asio/include/asio/impl/thread_pool.hpp | //
// impl/thread_pool.hpp
// ~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef ASIO_IMPL_THREAD_POOL_HPP
#define ASIO_IMPL_THREAD_POOL_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include "asio/detail/blocking_executor_op.hpp"
#include "asio/detail/executor_op.hpp"
#include "asio/detail/fenced_block.hpp"
#include "asio/detail/non_const_lvalue.hpp"
#include "asio/detail/type_traits.hpp"
#include "asio/execution_context.hpp"
#include "asio/detail/push_options.hpp"
namespace asio {
inline thread_pool::executor_type
thread_pool::get_executor() noexcept
{
return executor_type(*this);
}
inline thread_pool::executor_type
thread_pool::executor() noexcept
{
return executor_type(*this);
}
template <typename Allocator, unsigned int Bits>
thread_pool::basic_executor_type<Allocator, Bits>&
thread_pool::basic_executor_type<Allocator, Bits>::operator=(
const basic_executor_type& other) noexcept
{
if (this != &other)
{
thread_pool* old_thread_pool = pool_;
pool_ = other.pool_;
allocator_ = other.allocator_;
bits_ = other.bits_;
if (Bits & outstanding_work_tracked)
{
if (pool_)
pool_->scheduler_.work_started();
if (old_thread_pool)
old_thread_pool->scheduler_.work_finished();
}
}
return *this;
}
template <typename Allocator, unsigned int Bits>
thread_pool::basic_executor_type<Allocator, Bits>&
thread_pool::basic_executor_type<Allocator, Bits>::operator=(
basic_executor_type&& other) noexcept
{
if (this != &other)
{
thread_pool* old_thread_pool = pool_;
pool_ = other.pool_;
allocator_ = std::move(other.allocator_);
bits_ = other.bits_;
if (Bits & outstanding_work_tracked)
{
other.pool_ = 0;
if (old_thread_pool)
old_thread_pool->scheduler_.work_finished();
}
}
return *this;
}
template <typename Allocator, unsigned int Bits>
inline bool thread_pool::basic_executor_type<Allocator,
Bits>::running_in_this_thread() const noexcept
{
return pool_->scheduler_.can_dispatch();
}
template <typename Allocator, unsigned int Bits>
template <typename Function>
void thread_pool::basic_executor_type<Allocator,
Bits>::do_execute(Function&& f, false_type) const
{
typedef decay_t<Function> function_type;
// Invoke immediately if the blocking.possibly property is enabled and we are
// already inside the thread pool.
if ((bits_ & blocking_never) == 0 && pool_->scheduler_.can_dispatch())
{
// Make a local, non-const copy of the function.
function_type tmp(static_cast<Function&&>(f));
#if !defined(ASIO_NO_EXCEPTIONS)
try
{
#endif // !defined(ASIO_NO_EXCEPTIONS)
detail::fenced_block b(detail::fenced_block::full);
static_cast<function_type&&>(tmp)();
return;
#if !defined(ASIO_NO_EXCEPTIONS)
}
catch (...)
{
pool_->scheduler_.capture_current_exception();
return;
}
#endif // !defined(ASIO_NO_EXCEPTIONS)
}
// Allocate and construct an operation to wrap the function.
typedef detail::executor_op<function_type, Allocator> op;
typename op::ptr p = { detail::addressof(allocator_),
op::ptr::allocate(allocator_), 0 };
p.p = new (p.v) op(static_cast<Function&&>(f), allocator_);
if ((bits_ & relationship_continuation) != 0)
{
ASIO_HANDLER_CREATION((*pool_, *p.p,
"thread_pool", pool_, 0, "execute(blk=never,rel=cont)"));
}
else
{
ASIO_HANDLER_CREATION((*pool_, *p.p,
"thread_pool", pool_, 0, "execute(blk=never,rel=fork)"));
}
pool_->scheduler_.post_immediate_completion(p.p,
(bits_ & relationship_continuation) != 0);
p.v = p.p = 0;
}
template <typename Allocator, unsigned int Bits>
template <typename Function>
void thread_pool::basic_executor_type<Allocator,
Bits>::do_execute(Function&& f, true_type) const
{
// Obtain a non-const instance of the function.
detail::non_const_lvalue<Function> f2(f);
// Invoke immediately if we are already inside the thread pool.
if (pool_->scheduler_.can_dispatch())
{
#if !defined(ASIO_NO_EXCEPTIONS)
try
{
#endif // !defined(ASIO_NO_EXCEPTIONS)
detail::fenced_block b(detail::fenced_block::full);
static_cast<decay_t<Function>&&>(f2.value)();
return;
#if !defined(ASIO_NO_EXCEPTIONS)
}
catch (...)
{
std::terminate();
}
#endif // !defined(ASIO_NO_EXCEPTIONS)
}
// Construct an operation to wrap the function.
typedef decay_t<Function> function_type;
detail::blocking_executor_op<function_type> op(f2.value);
ASIO_HANDLER_CREATION((*pool_, op,
"thread_pool", pool_, 0, "execute(blk=always)"));
pool_->scheduler_.post_immediate_completion(&op, false);
op.wait();
}
#if !defined(ASIO_NO_TS_EXECUTORS)
template <typename Allocator, unsigned int Bits>
inline thread_pool& thread_pool::basic_executor_type<
Allocator, Bits>::context() const noexcept
{
return *pool_;
}
template <typename Allocator, unsigned int Bits>
inline void thread_pool::basic_executor_type<Allocator,
Bits>::on_work_started() const noexcept
{
pool_->scheduler_.work_started();
}
template <typename Allocator, unsigned int Bits>
inline void thread_pool::basic_executor_type<Allocator,
Bits>::on_work_finished() const noexcept
{
pool_->scheduler_.work_finished();
}
template <typename Allocator, unsigned int Bits>
template <typename Function, typename OtherAllocator>
void thread_pool::basic_executor_type<Allocator, Bits>::dispatch(
Function&& f, const OtherAllocator& a) const
{
typedef decay_t<Function> function_type;
// Invoke immediately if we are already inside the thread pool.
if (pool_->scheduler_.can_dispatch())
{
// Make a local, non-const copy of the function.
function_type tmp(static_cast<Function&&>(f));
detail::fenced_block b(detail::fenced_block::full);
static_cast<function_type&&>(tmp)();
return;
}
// Allocate and construct an operation to wrap the function.
typedef detail::executor_op<function_type, OtherAllocator> op;
typename op::ptr p = { detail::addressof(a), op::ptr::allocate(a), 0 };
p.p = new (p.v) op(static_cast<Function&&>(f), a);
ASIO_HANDLER_CREATION((*pool_, *p.p,
"thread_pool", pool_, 0, "dispatch"));
pool_->scheduler_.post_immediate_completion(p.p, false);
p.v = p.p = 0;
}
template <typename Allocator, unsigned int Bits>
template <typename Function, typename OtherAllocator>
void thread_pool::basic_executor_type<Allocator, Bits>::post(
Function&& f, const OtherAllocator& a) const
{
typedef decay_t<Function> function_type;
// Allocate and construct an operation to wrap the function.
typedef detail::executor_op<function_type, OtherAllocator> op;
typename op::ptr p = { detail::addressof(a), op::ptr::allocate(a), 0 };
p.p = new (p.v) op(static_cast<Function&&>(f), a);
ASIO_HANDLER_CREATION((*pool_, *p.p,
"thread_pool", pool_, 0, "post"));
pool_->scheduler_.post_immediate_completion(p.p, false);
p.v = p.p = 0;
}
template <typename Allocator, unsigned int Bits>
template <typename Function, typename OtherAllocator>
void thread_pool::basic_executor_type<Allocator, Bits>::defer(
Function&& f, const OtherAllocator& a) const
{
typedef decay_t<Function> function_type;
// Allocate and construct an operation to wrap the function.
typedef detail::executor_op<function_type, OtherAllocator> op;
typename op::ptr p = { detail::addressof(a), op::ptr::allocate(a), 0 };
p.p = new (p.v) op(static_cast<Function&&>(f), a);
ASIO_HANDLER_CREATION((*pool_, *p.p,
"thread_pool", pool_, 0, "defer"));
pool_->scheduler_.post_immediate_completion(p.p, true);
p.v = p.p = 0;
}
#endif // !defined(ASIO_NO_TS_EXECUTORS)
} // namespace asio
#include "asio/detail/pop_options.hpp"
#endif // ASIO_IMPL_THREAD_POOL_HPP
|
0 | repos/asio/asio/include/asio | repos/asio/asio/include/asio/impl/execution_context.ipp | //
// impl/execution_context.ipp
// ~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef ASIO_IMPL_EXECUTION_CONTEXT_IPP
#define ASIO_IMPL_EXECUTION_CONTEXT_IPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include "asio/detail/config.hpp"
#include "asio/execution_context.hpp"
#include "asio/detail/service_registry.hpp"
#include "asio/detail/push_options.hpp"
namespace asio {
execution_context::execution_context()
: service_registry_(new asio::detail::service_registry(*this))
{
}
execution_context::~execution_context()
{
shutdown();
destroy();
delete service_registry_;
}
void execution_context::shutdown()
{
service_registry_->shutdown_services();
}
void execution_context::destroy()
{
service_registry_->destroy_services();
}
void execution_context::notify_fork(
asio::execution_context::fork_event event)
{
service_registry_->notify_fork(event);
}
execution_context::service::service(execution_context& owner)
: owner_(owner),
next_(0)
{
}
execution_context::service::~service()
{
}
void execution_context::service::notify_fork(execution_context::fork_event)
{
}
service_already_exists::service_already_exists()
: std::logic_error("Service already exists.")
{
}
invalid_service_owner::invalid_service_owner()
: std::logic_error("Invalid service owner.")
{
}
} // namespace asio
#include "asio/detail/pop_options.hpp"
#endif // ASIO_IMPL_EXECUTION_CONTEXT_IPP
|
0 | repos/asio/asio/include/asio | repos/asio/asio/include/asio/impl/consign.hpp | //
// impl/consign.hpp
// ~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef ASIO_IMPL_CONSIGN_HPP
#define ASIO_IMPL_CONSIGN_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include "asio/detail/config.hpp"
#include "asio/associator.hpp"
#include "asio/async_result.hpp"
#include "asio/detail/handler_cont_helpers.hpp"
#include "asio/detail/initiation_base.hpp"
#include "asio/detail/type_traits.hpp"
#include "asio/detail/utility.hpp"
#include "asio/detail/push_options.hpp"
namespace asio {
namespace detail {
// Class to adapt a consign_t as a completion handler.
template <typename Handler, typename... Values>
class consign_handler
{
public:
typedef void result_type;
template <typename H>
consign_handler(H&& handler, std::tuple<Values...> values)
: handler_(static_cast<H&&>(handler)),
values_(static_cast<std::tuple<Values...>&&>(values))
{
}
template <typename... Args>
void operator()(Args&&... args)
{
static_cast<Handler&&>(handler_)(static_cast<Args&&>(args)...);
}
//private:
Handler handler_;
std::tuple<Values...> values_;
};
template <typename Handler>
inline bool asio_handler_is_continuation(
consign_handler<Handler>* this_handler)
{
return asio_handler_cont_helpers::is_continuation(
this_handler->handler_);
}
} // namespace detail
#if !defined(GENERATING_DOCUMENTATION)
template <typename CompletionToken, typename... Values, typename... Signatures>
struct async_result<consign_t<CompletionToken, Values...>, Signatures...>
: async_result<CompletionToken, Signatures...>
{
template <typename Initiation>
struct init_wrapper : detail::initiation_base<Initiation>
{
using detail::initiation_base<Initiation>::initiation_base;
template <typename Handler, typename... Args>
void operator()(Handler&& handler,
std::tuple<Values...> values, Args&&... args) &&
{
static_cast<Initiation&&>(*this)(
detail::consign_handler<decay_t<Handler>, Values...>(
static_cast<Handler&&>(handler),
static_cast<std::tuple<Values...>&&>(values)),
static_cast<Args&&>(args)...);
}
template <typename Handler, typename... Args>
void operator()(Handler&& handler,
std::tuple<Values...> values, Args&&... args) const &
{
static_cast<const Initiation&>(*this)(
detail::consign_handler<decay_t<Handler>, Values...>(
static_cast<Handler&&>(handler),
static_cast<std::tuple<Values...>&&>(values)),
static_cast<Args&&>(args)...);
}
};
template <typename Initiation, typename RawCompletionToken, typename... Args>
static auto initiate(Initiation&& initiation,
RawCompletionToken&& token, Args&&... args)
-> decltype(
async_initiate<CompletionToken, Signatures...>(
init_wrapper<decay_t<Initiation>>(
static_cast<Initiation&&>(initiation)),
token.token_, static_cast<std::tuple<Values...>&&>(token.values_),
static_cast<Args&&>(args)...))
{
return async_initiate<CompletionToken, Signatures...>(
init_wrapper<decay_t<Initiation>>(
static_cast<Initiation&&>(initiation)),
token.token_, static_cast<std::tuple<Values...>&&>(token.values_),
static_cast<Args&&>(args)...);
}
};
template <template <typename, typename> class Associator,
typename Handler, typename... Values, typename DefaultCandidate>
struct associator<Associator,
detail::consign_handler<Handler, Values...>, DefaultCandidate>
: Associator<Handler, DefaultCandidate>
{
static typename Associator<Handler, DefaultCandidate>::type get(
const detail::consign_handler<Handler, Values...>& h) noexcept
{
return Associator<Handler, DefaultCandidate>::get(h.handler_);
}
static auto get(const detail::consign_handler<Handler, Values...>& 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)
} // namespace asio
#include "asio/detail/pop_options.hpp"
#endif // ASIO_IMPL_CONSIGN_HPP
|
0 | repos/asio/asio/include/asio | repos/asio/asio/include/asio/impl/cancel_after.hpp | //
// impl/cancel_after.hpp
// ~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef ASIO_IMPL_CANCEL_AFTER_HPP
#define ASIO_IMPL_CANCEL_AFTER_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include "asio/detail/config.hpp"
#include "asio/associated_executor.hpp"
#include "asio/async_result.hpp"
#include "asio/detail/initiation_base.hpp"
#include "asio/detail/timed_cancel_op.hpp"
#include "asio/detail/push_options.hpp"
namespace asio {
namespace detail {
template <typename Initiation, typename Clock,
typename WaitTraits, typename... Signatures>
struct initiate_cancel_after : initiation_base<Initiation>
{
using initiation_base<Initiation>::initiation_base;
template <typename Handler, typename Rep, typename Period, typename... Args>
void operator()(Handler&& handler,
const chrono::duration<Rep, Period>& timeout,
cancellation_type_t cancel_type, Args&&... args) &&
{
using op = detail::timed_cancel_op<decay_t<Handler>,
basic_waitable_timer<Clock, WaitTraits>, Signatures...>;
non_const_lvalue<Handler> handler2(handler);
typename op::ptr p = { asio::detail::addressof(handler2.value),
op::ptr::allocate(handler2.value), 0 };
p.p = new (p.v) op(handler2.value,
basic_waitable_timer<Clock, WaitTraits,
typename Initiation::executor_type>(this->get_executor(), timeout),
cancel_type);
op* o = p.p;
p.v = p.p = 0;
o->start(static_cast<Initiation&&>(*this), static_cast<Args&&>(args)...);
}
template <typename Handler, typename Rep, typename Period, typename... Args>
void operator()(Handler&& handler,
const chrono::duration<Rep, Period>& timeout,
cancellation_type_t cancel_type, Args&&... args) const &
{
using op = detail::timed_cancel_op<decay_t<Handler>,
basic_waitable_timer<Clock, WaitTraits>, Signatures...>;
non_const_lvalue<Handler> handler2(handler);
typename op::ptr p = { asio::detail::addressof(handler2.value),
op::ptr::allocate(handler2.value), 0 };
p.p = new (p.v) op(handler2.value,
basic_waitable_timer<Clock, WaitTraits,
typename Initiation::executor_type>(this->get_executor(), timeout),
cancel_type);
op* o = p.p;
p.v = p.p = 0;
o->start(static_cast<const Initiation&>(*this),
static_cast<Args&&>(args)...);
}
};
template <typename Initiation, typename Clock,
typename WaitTraits, typename Executor, typename... Signatures>
struct initiate_cancel_after_timer : initiation_base<Initiation>
{
using initiation_base<Initiation>::initiation_base;
template <typename Handler, typename Rep, typename Period, typename... Args>
void operator()(Handler&& handler,
basic_waitable_timer<Clock, WaitTraits, Executor>* timer,
const chrono::duration<Rep, Period>& timeout,
cancellation_type_t cancel_type, Args&&... args) &&
{
using op = detail::timed_cancel_op<decay_t<Handler>,
basic_waitable_timer<Clock, WaitTraits, Executor>&, Signatures...>;
non_const_lvalue<Handler> handler2(handler);
typename op::ptr p = { asio::detail::addressof(handler2.value),
op::ptr::allocate(handler2.value), 0 };
timer->expires_after(timeout);
p.p = new (p.v) op(handler2.value, *timer, cancel_type);
op* o = p.p;
p.v = p.p = 0;
o->start(static_cast<Initiation&&>(*this), static_cast<Args&&>(args)...);
}
template <typename Handler, typename Rep, typename Period, typename... Args>
void operator()(Handler&& handler,
basic_waitable_timer<Clock, WaitTraits, Executor>* timer,
const chrono::duration<Rep, Period>& timeout,
cancellation_type_t cancel_type, Args&&... args) const &
{
using op = detail::timed_cancel_op<decay_t<Handler>,
basic_waitable_timer<Clock, WaitTraits, Executor>&, Signatures...>;
non_const_lvalue<Handler> handler2(handler);
typename op::ptr p = { asio::detail::addressof(handler2.value),
op::ptr::allocate(handler2.value), 0 };
timer->expires_after(timeout);
p.p = new (p.v) op(handler2.value, *timer, cancel_type);
op* o = p.p;
p.v = p.p = 0;
o->start(static_cast<const Initiation&>(*this),
static_cast<Args&&>(args)...);
}
};
} // namespace detail
#if !defined(GENERATING_DOCUMENTATION)
template <typename CompletionToken, typename Clock,
typename WaitTraits, typename... Signatures>
struct async_result<
cancel_after_t<CompletionToken, Clock, WaitTraits>, Signatures...>
: async_result<CompletionToken, Signatures...>
{
template <typename Initiation, typename RawCompletionToken, typename... Args>
static auto initiate(Initiation&& initiation,
RawCompletionToken&& token, Args&&... args)
-> decltype(
async_initiate<
conditional_t<
is_const<remove_reference_t<RawCompletionToken>>::value,
const CompletionToken, CompletionToken>,
Signatures...>(
declval<detail::initiate_cancel_after<
decay_t<Initiation>, Clock, WaitTraits, Signatures...>>(),
token.token_, token.timeout_, token.cancel_type_,
static_cast<Args&&>(args)...))
{
return async_initiate<
conditional_t<
is_const<remove_reference_t<RawCompletionToken>>::value,
const CompletionToken, CompletionToken>,
Signatures...>(
detail::initiate_cancel_after<
decay_t<Initiation>, Clock, WaitTraits, Signatures...>(
static_cast<Initiation&&>(initiation)),
token.token_, token.timeout_, token.cancel_type_,
static_cast<Args&&>(args)...);
}
};
template <typename CompletionToken, typename Clock,
typename WaitTraits, typename Executor, typename... Signatures>
struct async_result<
cancel_after_timer<CompletionToken, Clock, WaitTraits, Executor>,
Signatures...>
: async_result<CompletionToken, Signatures...>
{
template <typename Initiation, typename RawCompletionToken, typename... Args>
static auto initiate(Initiation&& initiation,
RawCompletionToken&& token, Args&&... args)
-> decltype(
async_initiate<
conditional_t<
is_const<remove_reference_t<RawCompletionToken>>::value,
const CompletionToken, CompletionToken>,
Signatures...>(
declval<detail::initiate_cancel_after_timer<
decay_t<Initiation>, Clock, WaitTraits, Executor, Signatures...>>(),
token.token_, &token.timer_, token.timeout_,
token.cancel_type_, static_cast<Args&&>(args)...))
{
return async_initiate<
conditional_t<
is_const<remove_reference_t<RawCompletionToken>>::value,
const CompletionToken, CompletionToken>,
Signatures...>(
detail::initiate_cancel_after_timer<
decay_t<Initiation>, Clock, WaitTraits, Executor, Signatures...>(
static_cast<Initiation&&>(initiation)),
token.token_, &token.timer_, token.timeout_,
token.cancel_type_, static_cast<Args&&>(args)...);
}
};
template <typename Clock, typename WaitTraits, typename... Signatures>
struct async_result<partial_cancel_after<Clock, WaitTraits>, Signatures...>
{
template <typename Initiation, typename RawCompletionToken, typename... Args>
static auto initiate(Initiation&& initiation,
RawCompletionToken&& token, Args&&... args)
-> decltype(
async_initiate<
const cancel_after_t<
default_completion_token_t<associated_executor_t<Initiation>>,
Clock, WaitTraits>&,
Signatures...>(
static_cast<Initiation&&>(initiation),
cancel_after_t<
default_completion_token_t<associated_executor_t<Initiation>>,
Clock, WaitTraits>(
default_completion_token_t<associated_executor_t<Initiation>>{},
token.timeout_, token.cancel_type_),
static_cast<Args&&>(args)...))
{
return async_initiate<
const cancel_after_t<
default_completion_token_t<associated_executor_t<Initiation>>,
Clock, WaitTraits>&,
Signatures...>(
static_cast<Initiation&&>(initiation),
cancel_after_t<
default_completion_token_t<associated_executor_t<Initiation>>,
Clock, WaitTraits>(
default_completion_token_t<associated_executor_t<Initiation>>{},
token.timeout_, token.cancel_type_),
static_cast<Args&&>(args)...);
}
};
template <typename Clock, typename WaitTraits,
typename Executor, typename... Signatures>
struct async_result<
partial_cancel_after_timer<Clock, WaitTraits, Executor>, Signatures...>
{
template <typename Initiation, typename RawCompletionToken, typename... Args>
static auto initiate(Initiation&& initiation,
RawCompletionToken&& token, Args&&... args)
-> decltype(
async_initiate<Signatures...>(
static_cast<Initiation&&>(initiation),
cancel_after_timer<
default_completion_token_t<associated_executor_t<Initiation>>,
Clock, WaitTraits, Executor>(
default_completion_token_t<associated_executor_t<Initiation>>{},
token.timer_, token.timeout_, token.cancel_type_),
static_cast<Args&&>(args)...))
{
return async_initiate<Signatures...>(
static_cast<Initiation&&>(initiation),
cancel_after_timer<
default_completion_token_t<associated_executor_t<Initiation>>,
Clock, WaitTraits, Executor>(
default_completion_token_t<associated_executor_t<Initiation>>{},
token.timer_, token.timeout_, token.cancel_type_),
static_cast<Args&&>(args)...);
}
};
#endif // !defined(GENERATING_DOCUMENTATION)
} // namespace asio
#include "asio/detail/pop_options.hpp"
#endif // ASIO_IMPL_CANCEL_AFTER_HPP
|
0 | repos/asio/asio/include/asio | repos/asio/asio/include/asio/impl/io_context.hpp | //
// impl/io_context.hpp
// ~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef ASIO_IMPL_IO_CONTEXT_HPP
#define ASIO_IMPL_IO_CONTEXT_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include "asio/detail/completion_handler.hpp"
#include "asio/detail/executor_op.hpp"
#include "asio/detail/fenced_block.hpp"
#include "asio/detail/handler_type_requirements.hpp"
#include "asio/detail/non_const_lvalue.hpp"
#include "asio/detail/service_registry.hpp"
#include "asio/detail/throw_error.hpp"
#include "asio/detail/type_traits.hpp"
#include "asio/detail/push_options.hpp"
namespace asio {
#if !defined(GENERATING_DOCUMENTATION)
template <typename Service>
inline Service& use_service(io_context& ioc)
{
// Check that Service meets the necessary type requirements.
(void)static_cast<execution_context::service*>(static_cast<Service*>(0));
(void)static_cast<const execution_context::id*>(&Service::id);
return ioc.service_registry_->template use_service<Service>(ioc);
}
template <>
inline detail::io_context_impl& use_service<detail::io_context_impl>(
io_context& ioc)
{
return ioc.impl_;
}
#endif // !defined(GENERATING_DOCUMENTATION)
inline io_context::executor_type
io_context::get_executor() noexcept
{
return executor_type(*this);
}
template <typename Rep, typename Period>
std::size_t io_context::run_for(
const chrono::duration<Rep, Period>& rel_time)
{
return this->run_until(chrono::steady_clock::now() + rel_time);
}
template <typename Clock, typename Duration>
std::size_t io_context::run_until(
const chrono::time_point<Clock, Duration>& abs_time)
{
std::size_t n = 0;
while (this->run_one_until(abs_time))
if (n != (std::numeric_limits<std::size_t>::max)())
++n;
return n;
}
template <typename Rep, typename Period>
std::size_t io_context::run_one_for(
const chrono::duration<Rep, Period>& rel_time)
{
return this->run_one_until(chrono::steady_clock::now() + rel_time);
}
template <typename Clock, typename Duration>
std::size_t io_context::run_one_until(
const chrono::time_point<Clock, Duration>& abs_time)
{
typename Clock::time_point now = Clock::now();
while (now < abs_time)
{
typename Clock::duration rel_time = abs_time - now;
if (rel_time > chrono::seconds(1))
rel_time = chrono::seconds(1);
asio::error_code ec;
std::size_t s = impl_.wait_one(
static_cast<long>(chrono::duration_cast<
chrono::microseconds>(rel_time).count()), ec);
asio::detail::throw_error(ec);
if (s || impl_.stopped())
return s;
now = Clock::now();
}
return 0;
}
#if !defined(ASIO_NO_DEPRECATED)
inline void io_context::reset()
{
restart();
}
struct io_context::initiate_dispatch
{
template <typename LegacyCompletionHandler>
void operator()(LegacyCompletionHandler&& handler,
io_context* 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.
ASIO_LEGACY_COMPLETION_HANDLER_CHECK(
LegacyCompletionHandler, handler) type_check;
detail::non_const_lvalue<LegacyCompletionHandler> handler2(handler);
if (self->impl_.can_dispatch())
{
detail::fenced_block b(detail::fenced_block::full);
static_cast<decay_t<LegacyCompletionHandler>&&>(handler2.value)();
}
else
{
// Allocate and construct an operation to wrap the handler.
typedef detail::completion_handler<
decay_t<LegacyCompletionHandler>, executor_type> op;
typename op::ptr p = { detail::addressof(handler2.value),
op::ptr::allocate(handler2.value), 0 };
p.p = new (p.v) op(handler2.value, self->get_executor());
ASIO_HANDLER_CREATION((*self, *p.p,
"io_context", self, 0, "dispatch"));
self->impl_.do_dispatch(p.p);
p.v = p.p = 0;
}
}
};
template <typename LegacyCompletionHandler>
auto io_context::dispatch(LegacyCompletionHandler&& handler)
-> decltype(
async_initiate<LegacyCompletionHandler, void ()>(
declval<initiate_dispatch>(), handler, this))
{
return async_initiate<LegacyCompletionHandler, void ()>(
initiate_dispatch(), handler, this);
}
struct io_context::initiate_post
{
template <typename LegacyCompletionHandler>
void operator()(LegacyCompletionHandler&& handler,
io_context* 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.
ASIO_LEGACY_COMPLETION_HANDLER_CHECK(
LegacyCompletionHandler, handler) type_check;
detail::non_const_lvalue<LegacyCompletionHandler> handler2(handler);
bool is_continuation =
asio_handler_cont_helpers::is_continuation(handler2.value);
// Allocate and construct an operation to wrap the handler.
typedef detail::completion_handler<
decay_t<LegacyCompletionHandler>, executor_type> op;
typename op::ptr p = { detail::addressof(handler2.value),
op::ptr::allocate(handler2.value), 0 };
p.p = new (p.v) op(handler2.value, self->get_executor());
ASIO_HANDLER_CREATION((*self, *p.p,
"io_context", self, 0, "post"));
self->impl_.post_immediate_completion(p.p, is_continuation);
p.v = p.p = 0;
}
};
template <typename LegacyCompletionHandler>
auto io_context::post(LegacyCompletionHandler&& handler)
-> decltype(
async_initiate<LegacyCompletionHandler, void ()>(
declval<initiate_post>(), handler, this))
{
return async_initiate<LegacyCompletionHandler, void ()>(
initiate_post(), handler, this);
}
template <typename Handler>
#if defined(GENERATING_DOCUMENTATION)
unspecified
#else
inline detail::wrapped_handler<io_context&, Handler>
#endif
io_context::wrap(Handler handler)
{
return detail::wrapped_handler<io_context&, Handler>(*this, handler);
}
#endif // !defined(ASIO_NO_DEPRECATED)
template <typename Allocator, uintptr_t Bits>
io_context::basic_executor_type<Allocator, Bits>&
io_context::basic_executor_type<Allocator, Bits>::operator=(
const basic_executor_type& other) noexcept
{
if (this != &other)
{
static_cast<Allocator&>(*this) = static_cast<const Allocator&>(other);
io_context* old_io_context = context_ptr();
target_ = other.target_;
if (Bits & outstanding_work_tracked)
{
if (context_ptr())
context_ptr()->impl_.work_started();
if (old_io_context)
old_io_context->impl_.work_finished();
}
}
return *this;
}
template <typename Allocator, uintptr_t Bits>
io_context::basic_executor_type<Allocator, Bits>&
io_context::basic_executor_type<Allocator, Bits>::operator=(
basic_executor_type&& other) noexcept
{
if (this != &other)
{
static_cast<Allocator&>(*this) = static_cast<Allocator&&>(other);
io_context* old_io_context = context_ptr();
target_ = other.target_;
if (Bits & outstanding_work_tracked)
{
other.target_ = 0;
if (old_io_context)
old_io_context->impl_.work_finished();
}
}
return *this;
}
template <typename Allocator, uintptr_t Bits>
inline bool io_context::basic_executor_type<Allocator,
Bits>::running_in_this_thread() const noexcept
{
return context_ptr()->impl_.can_dispatch();
}
template <typename Allocator, uintptr_t Bits>
template <typename Function>
void io_context::basic_executor_type<Allocator, Bits>::execute(
Function&& f) const
{
typedef decay_t<Function> function_type;
// Invoke immediately if the blocking.possibly property is enabled and we are
// already inside the thread pool.
if ((bits() & blocking_never) == 0 && context_ptr()->impl_.can_dispatch())
{
// Make a local, non-const copy of the function.
function_type tmp(static_cast<Function&&>(f));
#if !defined(ASIO_NO_EXCEPTIONS)
try
{
#endif // !defined(ASIO_NO_EXCEPTIONS)
detail::fenced_block b(detail::fenced_block::full);
static_cast<function_type&&>(tmp)();
return;
#if !defined(ASIO_NO_EXCEPTIONS)
}
catch (...)
{
context_ptr()->impl_.capture_current_exception();
return;
}
#endif // !defined(ASIO_NO_EXCEPTIONS)
}
// Allocate and construct an operation to wrap the function.
typedef detail::executor_op<function_type, Allocator, detail::operation> op;
typename op::ptr p = {
detail::addressof(static_cast<const Allocator&>(*this)),
op::ptr::allocate(static_cast<const Allocator&>(*this)), 0 };
p.p = new (p.v) op(static_cast<Function&&>(f),
static_cast<const Allocator&>(*this));
ASIO_HANDLER_CREATION((*context_ptr(), *p.p,
"io_context", context_ptr(), 0, "execute"));
context_ptr()->impl_.post_immediate_completion(p.p,
(bits() & relationship_continuation) != 0);
p.v = p.p = 0;
}
#if !defined(ASIO_NO_TS_EXECUTORS)
template <typename Allocator, uintptr_t Bits>
inline io_context& io_context::basic_executor_type<
Allocator, Bits>::context() const noexcept
{
return *context_ptr();
}
template <typename Allocator, uintptr_t Bits>
inline void io_context::basic_executor_type<Allocator,
Bits>::on_work_started() const noexcept
{
context_ptr()->impl_.work_started();
}
template <typename Allocator, uintptr_t Bits>
inline void io_context::basic_executor_type<Allocator,
Bits>::on_work_finished() const noexcept
{
context_ptr()->impl_.work_finished();
}
template <typename Allocator, uintptr_t Bits>
template <typename Function, typename OtherAllocator>
void io_context::basic_executor_type<Allocator, Bits>::dispatch(
Function&& f, const OtherAllocator& a) const
{
typedef decay_t<Function> function_type;
// Invoke immediately if we are already inside the thread pool.
if (context_ptr()->impl_.can_dispatch())
{
// Make a local, non-const copy of the function.
function_type tmp(static_cast<Function&&>(f));
detail::fenced_block b(detail::fenced_block::full);
static_cast<function_type&&>(tmp)();
return;
}
// Allocate and construct an operation to wrap the function.
typedef detail::executor_op<function_type,
OtherAllocator, detail::operation> op;
typename op::ptr p = { detail::addressof(a), op::ptr::allocate(a), 0 };
p.p = new (p.v) op(static_cast<Function&&>(f), a);
ASIO_HANDLER_CREATION((*context_ptr(), *p.p,
"io_context", context_ptr(), 0, "dispatch"));
context_ptr()->impl_.post_immediate_completion(p.p, false);
p.v = p.p = 0;
}
template <typename Allocator, uintptr_t Bits>
template <typename Function, typename OtherAllocator>
void io_context::basic_executor_type<Allocator, Bits>::post(
Function&& f, const OtherAllocator& a) const
{
// Allocate and construct an operation to wrap the function.
typedef detail::executor_op<decay_t<Function>,
OtherAllocator, detail::operation> op;
typename op::ptr p = { detail::addressof(a), op::ptr::allocate(a), 0 };
p.p = new (p.v) op(static_cast<Function&&>(f), a);
ASIO_HANDLER_CREATION((*context_ptr(), *p.p,
"io_context", context_ptr(), 0, "post"));
context_ptr()->impl_.post_immediate_completion(p.p, false);
p.v = p.p = 0;
}
template <typename Allocator, uintptr_t Bits>
template <typename Function, typename OtherAllocator>
void io_context::basic_executor_type<Allocator, Bits>::defer(
Function&& f, const OtherAllocator& a) const
{
// Allocate and construct an operation to wrap the function.
typedef detail::executor_op<decay_t<Function>,
OtherAllocator, detail::operation> op;
typename op::ptr p = { detail::addressof(a), op::ptr::allocate(a), 0 };
p.p = new (p.v) op(static_cast<Function&&>(f), a);
ASIO_HANDLER_CREATION((*context_ptr(), *p.p,
"io_context", context_ptr(), 0, "defer"));
context_ptr()->impl_.post_immediate_completion(p.p, true);
p.v = p.p = 0;
}
#endif // !defined(ASIO_NO_TS_EXECUTORS)
#if !defined(ASIO_NO_DEPRECATED)
inline io_context::work::work(asio::io_context& io_context)
: io_context_impl_(io_context.impl_)
{
io_context_impl_.work_started();
}
inline io_context::work::work(const work& other)
: io_context_impl_(other.io_context_impl_)
{
io_context_impl_.work_started();
}
inline io_context::work::~work()
{
io_context_impl_.work_finished();
}
inline asio::io_context& io_context::work::get_io_context()
{
return static_cast<asio::io_context&>(io_context_impl_.context());
}
#endif // !defined(ASIO_NO_DEPRECATED)
inline asio::io_context& io_context::service::get_io_context()
{
return static_cast<asio::io_context&>(context());
}
} // namespace asio
#include "asio/detail/pop_options.hpp"
#endif // ASIO_IMPL_IO_CONTEXT_HPP
|
0 | repos/asio/asio/include/asio | repos/asio/asio/include/asio/impl/connect_pipe.hpp | //
// impl/connect_pipe.hpp
// ~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef ASIO_IMPL_CONNECT_PIPE_HPP
#define ASIO_IMPL_CONNECT_PIPE_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include "asio/detail/config.hpp"
#if defined(ASIO_HAS_PIPE)
#include "asio/connect_pipe.hpp"
#include "asio/detail/throw_error.hpp"
#include "asio/detail/push_options.hpp"
namespace asio {
template <typename Executor1, typename Executor2>
void connect_pipe(basic_readable_pipe<Executor1>& read_end,
basic_writable_pipe<Executor2>& write_end)
{
asio::error_code ec;
asio::connect_pipe(read_end, write_end, ec);
asio::detail::throw_error(ec, "connect_pipe");
}
template <typename Executor1, typename Executor2>
ASIO_SYNC_OP_VOID connect_pipe(basic_readable_pipe<Executor1>& read_end,
basic_writable_pipe<Executor2>& write_end, asio::error_code& ec)
{
detail::native_pipe_handle p[2];
detail::create_pipe(p, ec);
if (ec)
ASIO_SYNC_OP_VOID_RETURN(ec);
read_end.assign(p[0], ec);
if (ec)
{
detail::close_pipe(p[0]);
detail::close_pipe(p[1]);
ASIO_SYNC_OP_VOID_RETURN(ec);
}
write_end.assign(p[1], ec);
if (ec)
{
asio::error_code temp_ec;
read_end.close(temp_ec);
detail::close_pipe(p[1]);
ASIO_SYNC_OP_VOID_RETURN(ec);
}
ASIO_SYNC_OP_VOID_RETURN(ec);
}
} // namespace asio
#include "asio/detail/pop_options.hpp"
#endif // defined(ASIO_HAS_PIPE)
#endif // ASIO_IMPL_CONNECT_PIPE_HPP
|
0 | repos/asio/asio/include/asio | repos/asio/asio/include/asio/impl/as_tuple.hpp | //
// impl/as_tuple.hpp
// ~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef ASIO_IMPL_AS_TUPLE_HPP
#define ASIO_IMPL_AS_TUPLE_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include "asio/detail/config.hpp"
#include <tuple>
#include "asio/associated_executor.hpp"
#include "asio/associator.hpp"
#include "asio/async_result.hpp"
#include "asio/detail/handler_cont_helpers.hpp"
#include "asio/detail/initiation_base.hpp"
#include "asio/detail/type_traits.hpp"
#include "asio/detail/push_options.hpp"
namespace asio {
namespace detail {
// Class to adapt a as_tuple_t as a completion handler.
template <typename Handler>
class as_tuple_handler
{
public:
typedef void result_type;
template <typename CompletionToken>
as_tuple_handler(as_tuple_t<CompletionToken> e)
: handler_(static_cast<CompletionToken&&>(e.token_))
{
}
template <typename RedirectedHandler>
as_tuple_handler(RedirectedHandler&& h)
: handler_(static_cast<RedirectedHandler&&>(h))
{
}
template <typename... Args>
void operator()(Args&&... args)
{
static_cast<Handler&&>(handler_)(
std::make_tuple(static_cast<Args&&>(args)...));
}
//private:
Handler handler_;
};
template <typename Handler>
inline bool asio_handler_is_continuation(
as_tuple_handler<Handler>* this_handler)
{
return asio_handler_cont_helpers::is_continuation(
this_handler->handler_);
}
template <typename Signature>
struct as_tuple_signature;
template <typename R, typename... Args>
struct as_tuple_signature<R(Args...)>
{
typedef R type(std::tuple<decay_t<Args>...>);
};
template <typename R, typename... Args>
struct as_tuple_signature<R(Args...) &>
{
typedef R type(std::tuple<decay_t<Args>...>) &;
};
template <typename R, typename... Args>
struct as_tuple_signature<R(Args...) &&>
{
typedef R type(std::tuple<decay_t<Args>...>) &&;
};
#if defined(ASIO_HAS_NOEXCEPT_FUNCTION_TYPE)
template <typename R, typename... Args>
struct as_tuple_signature<R(Args...) noexcept>
{
typedef R type(std::tuple<decay_t<Args>...>) noexcept;
};
template <typename R, typename... Args>
struct as_tuple_signature<R(Args...) & noexcept>
{
typedef R type(std::tuple<decay_t<Args>...>) & noexcept;
};
template <typename R, typename... Args>
struct as_tuple_signature<R(Args...) && noexcept>
{
typedef R type(std::tuple<decay_t<Args>...>) && noexcept;
};
#endif // defined(ASIO_HAS_NOEXCEPT_FUNCTION_TYPE)
} // namespace detail
#if !defined(GENERATING_DOCUMENTATION)
template <typename CompletionToken, typename... Signatures>
struct async_result<as_tuple_t<CompletionToken>, Signatures...>
: async_result<CompletionToken,
typename detail::as_tuple_signature<Signatures>::type...>
{
template <typename Initiation>
struct init_wrapper : detail::initiation_base<Initiation>
{
using detail::initiation_base<Initiation>::initiation_base;
template <typename Handler, typename... Args>
void operator()(Handler&& handler, Args&&... args) &&
{
static_cast<Initiation&&>(*this)(
detail::as_tuple_handler<decay_t<Handler>>(
static_cast<Handler&&>(handler)),
static_cast<Args&&>(args)...);
}
template <typename Handler, typename... Args>
void operator()(Handler&& handler, Args&&... args) const &
{
static_cast<const Initiation&>(*this)(
detail::as_tuple_handler<decay_t<Handler>>(
static_cast<Handler&&>(handler)),
static_cast<Args&&>(args)...);
}
};
template <typename Initiation, typename RawCompletionToken, typename... Args>
static auto initiate(Initiation&& initiation,
RawCompletionToken&& token, Args&&... args)
-> decltype(
async_initiate<
conditional_t<
is_const<remove_reference_t<RawCompletionToken>>::value,
const CompletionToken, CompletionToken>,
typename detail::as_tuple_signature<Signatures>::type...>(
init_wrapper<decay_t<Initiation>>(
static_cast<Initiation&&>(initiation)),
token.token_, static_cast<Args&&>(args)...))
{
return async_initiate<
conditional_t<
is_const<remove_reference_t<RawCompletionToken>>::value,
const CompletionToken, CompletionToken>,
typename detail::as_tuple_signature<Signatures>::type...>(
init_wrapper<decay_t<Initiation>>(
static_cast<Initiation&&>(initiation)),
token.token_, static_cast<Args&&>(args)...);
}
};
#if defined(ASIO_MSVC)
// Workaround for MSVC internal compiler error.
template <typename CompletionToken, typename Signature>
struct async_result<as_tuple_t<CompletionToken>, Signature>
: async_result<CompletionToken,
typename detail::as_tuple_signature<Signature>::type>
{
template <typename Initiation>
struct init_wrapper : detail::initiation_base<Initiation>
{
using detail::initiation_base<Initiation>::initiation_base;
template <typename Handler, typename... Args>
void operator()(Handler&& handler, Args&&... args) &&
{
static_cast<Initiation&&>(*this)(
detail::as_tuple_handler<decay_t<Handler>>(
static_cast<Handler&&>(handler)),
static_cast<Args&&>(args)...);
}
template <typename Handler, typename... Args>
void operator()(Handler&& handler, Args&&... args) const &
{
static_cast<const Initiation&>(*this)(
detail::as_tuple_handler<decay_t<Handler>>(
static_cast<Handler&&>(handler)),
static_cast<Args&&>(args)...);
}
};
template <typename Initiation, typename RawCompletionToken, typename... Args>
static auto initiate(Initiation&& initiation,
RawCompletionToken&& token, Args&&... args)
-> decltype(
async_initiate<
conditional_t<
is_const<remove_reference_t<RawCompletionToken>>::value,
const CompletionToken, CompletionToken>,
typename detail::as_tuple_signature<Signature>::type>(
init_wrapper<decay_t<Initiation>>(
static_cast<Initiation&&>(initiation)),
token.token_, static_cast<Args&&>(args)...))
{
return async_initiate<
conditional_t<
is_const<remove_reference_t<RawCompletionToken>>::value,
const CompletionToken, CompletionToken>,
typename detail::as_tuple_signature<Signature>::type>(
init_wrapper<decay_t<Initiation>>(
static_cast<Initiation&&>(initiation)),
token.token_, static_cast<Args&&>(args)...);
}
};
#endif // defined(ASIO_MSVC)
template <template <typename, typename> class Associator,
typename Handler, typename DefaultCandidate>
struct associator<Associator,
detail::as_tuple_handler<Handler>, DefaultCandidate>
: Associator<Handler, DefaultCandidate>
{
static typename Associator<Handler, DefaultCandidate>::type get(
const detail::as_tuple_handler<Handler>& h) noexcept
{
return Associator<Handler, DefaultCandidate>::get(h.handler_);
}
static auto get(const detail::as_tuple_handler<Handler>& h,
const DefaultCandidate& c) noexcept
-> decltype(Associator<Handler, DefaultCandidate>::get(h.handler_, c))
{
return Associator<Handler, DefaultCandidate>::get(h.handler_, c);
}
};
template <typename... Signatures>
struct async_result<partial_as_tuple, Signatures...>
{
template <typename Initiation, typename RawCompletionToken, typename... Args>
static auto initiate(Initiation&& initiation,
RawCompletionToken&&, Args&&... args)
-> decltype(
async_initiate<Signatures...>(
static_cast<Initiation&&>(initiation),
as_tuple_t<
default_completion_token_t<associated_executor_t<Initiation>>>{},
static_cast<Args&&>(args)...))
{
return async_initiate<Signatures...>(
static_cast<Initiation&&>(initiation),
as_tuple_t<
default_completion_token_t<associated_executor_t<Initiation>>>{},
static_cast<Args&&>(args)...);
}
};
#endif // !defined(GENERATING_DOCUMENTATION)
} // namespace asio
#include "asio/detail/pop_options.hpp"
#endif // ASIO_IMPL_AS_TUPLE_HPP
|
0 | repos/asio/asio/include/asio | repos/asio/asio/include/asio/impl/io_context.ipp | //
// impl/io_context.ipp
// ~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef ASIO_IMPL_IO_CONTEXT_IPP
#define ASIO_IMPL_IO_CONTEXT_IPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include "asio/detail/config.hpp"
#include "asio/io_context.hpp"
#include "asio/detail/concurrency_hint.hpp"
#include "asio/detail/limits.hpp"
#include "asio/detail/scoped_ptr.hpp"
#include "asio/detail/service_registry.hpp"
#include "asio/detail/throw_error.hpp"
#if defined(ASIO_HAS_IOCP)
# include "asio/detail/win_iocp_io_context.hpp"
#else
# include "asio/detail/scheduler.hpp"
#endif
#include "asio/detail/push_options.hpp"
namespace asio {
io_context::io_context()
: impl_(add_impl(new impl_type(*this,
ASIO_CONCURRENCY_HINT_DEFAULT, false)))
{
}
io_context::io_context(int concurrency_hint)
: impl_(add_impl(new impl_type(*this, concurrency_hint == 1
? ASIO_CONCURRENCY_HINT_1 : concurrency_hint, false)))
{
}
io_context::impl_type& io_context::add_impl(io_context::impl_type* impl)
{
asio::detail::scoped_ptr<impl_type> scoped_impl(impl);
asio::add_service<impl_type>(*this, scoped_impl.get());
return *scoped_impl.release();
}
io_context::~io_context()
{
shutdown();
}
io_context::count_type io_context::run()
{
asio::error_code ec;
count_type s = impl_.run(ec);
asio::detail::throw_error(ec);
return s;
}
#if !defined(ASIO_NO_DEPRECATED)
io_context::count_type io_context::run(asio::error_code& ec)
{
return impl_.run(ec);
}
#endif // !defined(ASIO_NO_DEPRECATED)
io_context::count_type io_context::run_one()
{
asio::error_code ec;
count_type s = impl_.run_one(ec);
asio::detail::throw_error(ec);
return s;
}
#if !defined(ASIO_NO_DEPRECATED)
io_context::count_type io_context::run_one(asio::error_code& ec)
{
return impl_.run_one(ec);
}
#endif // !defined(ASIO_NO_DEPRECATED)
io_context::count_type io_context::poll()
{
asio::error_code ec;
count_type s = impl_.poll(ec);
asio::detail::throw_error(ec);
return s;
}
#if !defined(ASIO_NO_DEPRECATED)
io_context::count_type io_context::poll(asio::error_code& ec)
{
return impl_.poll(ec);
}
#endif // !defined(ASIO_NO_DEPRECATED)
io_context::count_type io_context::poll_one()
{
asio::error_code ec;
count_type s = impl_.poll_one(ec);
asio::detail::throw_error(ec);
return s;
}
#if !defined(ASIO_NO_DEPRECATED)
io_context::count_type io_context::poll_one(asio::error_code& ec)
{
return impl_.poll_one(ec);
}
#endif // !defined(ASIO_NO_DEPRECATED)
void io_context::stop()
{
impl_.stop();
}
bool io_context::stopped() const
{
return impl_.stopped();
}
void io_context::restart()
{
impl_.restart();
}
io_context::service::service(asio::io_context& owner)
: execution_context::service(owner)
{
}
io_context::service::~service()
{
}
void io_context::service::shutdown()
{
#if !defined(ASIO_NO_DEPRECATED)
shutdown_service();
#endif // !defined(ASIO_NO_DEPRECATED)
}
#if !defined(ASIO_NO_DEPRECATED)
void io_context::service::shutdown_service()
{
}
#endif // !defined(ASIO_NO_DEPRECATED)
void io_context::service::notify_fork(io_context::fork_event ev)
{
#if !defined(ASIO_NO_DEPRECATED)
fork_service(ev);
#else // !defined(ASIO_NO_DEPRECATED)
(void)ev;
#endif // !defined(ASIO_NO_DEPRECATED)
}
#if !defined(ASIO_NO_DEPRECATED)
void io_context::service::fork_service(io_context::fork_event)
{
}
#endif // !defined(ASIO_NO_DEPRECATED)
} // namespace asio
#include "asio/detail/pop_options.hpp"
#endif // ASIO_IMPL_IO_CONTEXT_IPP
|
0 | repos/asio/asio/include/asio | repos/asio/asio/include/asio/impl/read_until.hpp | //
// impl/read_until.hpp
// ~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef ASIO_IMPL_READ_UNTIL_HPP
#define ASIO_IMPL_READ_UNTIL_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <algorithm>
#include <string>
#include <vector>
#include <utility>
#include "asio/associator.hpp"
#include "asio/buffer.hpp"
#include "asio/buffers_iterator.hpp"
#include "asio/detail/base_from_cancellation_state.hpp"
#include "asio/detail/bind_handler.hpp"
#include "asio/detail/handler_cont_helpers.hpp"
#include "asio/detail/handler_tracking.hpp"
#include "asio/detail/handler_type_requirements.hpp"
#include "asio/detail/limits.hpp"
#include "asio/detail/non_const_lvalue.hpp"
#include "asio/detail/throw_error.hpp"
#include "asio/detail/push_options.hpp"
namespace asio {
namespace detail
{
// Algorithm that finds a subsequence of equal values in a sequence. Returns
// (iterator,true) if a full match was found, in which case the iterator
// points to the beginning of the match. Returns (iterator,false) if a
// partial match was found at the end of the first sequence, in which case
// the iterator points to the beginning of the partial match. Returns
// (last1,false) if no full or partial match was found.
template <typename Iterator1, typename Iterator2>
std::pair<Iterator1, bool> partial_search(
Iterator1 first1, Iterator1 last1, Iterator2 first2, Iterator2 last2)
{
for (Iterator1 iter1 = first1; iter1 != last1; ++iter1)
{
Iterator1 test_iter1 = iter1;
Iterator2 test_iter2 = first2;
for (;; ++test_iter1, ++test_iter2)
{
if (test_iter2 == last2)
return std::make_pair(iter1, true);
if (test_iter1 == last1)
{
if (test_iter2 != first2)
return std::make_pair(iter1, false);
else
break;
}
if (*test_iter1 != *test_iter2)
break;
}
}
return std::make_pair(last1, false);
}
#if !defined(ASIO_NO_EXTENSIONS)
#if defined(ASIO_HAS_BOOST_REGEX)
struct regex_match_flags
{
template <typename T>
operator T() const
{
return T::match_default | T::match_partial;
}
};
#endif // !defined(ASIO_NO_EXTENSIONS)
#endif // defined(ASIO_HAS_BOOST_REGEX)
} // namespace detail
#if !defined(ASIO_NO_DYNAMIC_BUFFER_V1)
template <typename SyncReadStream, typename DynamicBuffer_v1>
inline std::size_t read_until(SyncReadStream& s,
DynamicBuffer_v1&& buffers, char delim,
constraint_t<
is_dynamic_buffer_v1<decay_t<DynamicBuffer_v1>>::value
>,
constraint_t<
!is_dynamic_buffer_v2<decay_t<DynamicBuffer_v1>>::value
>)
{
asio::error_code ec;
std::size_t bytes_transferred = read_until(s,
static_cast<DynamicBuffer_v1&&>(buffers), delim, ec);
asio::detail::throw_error(ec, "read_until");
return bytes_transferred;
}
template <typename SyncReadStream, typename DynamicBuffer_v1>
std::size_t read_until(SyncReadStream& s,
DynamicBuffer_v1&& buffers,
char delim, asio::error_code& ec,
constraint_t<
is_dynamic_buffer_v1<decay_t<DynamicBuffer_v1>>::value
>,
constraint_t<
!is_dynamic_buffer_v2<decay_t<DynamicBuffer_v1>>::value
>)
{
decay_t<DynamicBuffer_v1> b(
static_cast<DynamicBuffer_v1&&>(buffers));
std::size_t search_position = 0;
for (;;)
{
// Determine the range of the data to be searched.
typedef typename DynamicBuffer_v1::const_buffers_type buffers_type;
typedef buffers_iterator<buffers_type> iterator;
buffers_type data_buffers = b.data();
iterator begin = iterator::begin(data_buffers);
iterator start_pos = begin + search_position;
iterator end = iterator::end(data_buffers);
// Look for a match.
iterator iter = std::find(start_pos, end, delim);
if (iter != end)
{
// Found a match. We're done.
ec = asio::error_code();
return iter - begin + 1;
}
else
{
// No match. Next search can start with the new data.
search_position = end - begin;
}
// Check if buffer is full.
if (b.size() == b.max_size())
{
ec = error::not_found;
return 0;
}
// Need more data.
std::size_t bytes_to_read = std::min<std::size_t>(
std::max<std::size_t>(512, b.capacity() - b.size()),
std::min<std::size_t>(65536, b.max_size() - b.size()));
b.commit(s.read_some(b.prepare(bytes_to_read), ec));
if (ec)
return 0;
}
}
template <typename SyncReadStream, typename DynamicBuffer_v1>
inline std::size_t read_until(SyncReadStream& s,
DynamicBuffer_v1&& buffers,
ASIO_STRING_VIEW_PARAM delim,
constraint_t<
is_dynamic_buffer_v1<decay_t<DynamicBuffer_v1>>::value
>,
constraint_t<
!is_dynamic_buffer_v2<decay_t<DynamicBuffer_v1>>::value
>)
{
asio::error_code ec;
std::size_t bytes_transferred = read_until(s,
static_cast<DynamicBuffer_v1&&>(buffers), delim, ec);
asio::detail::throw_error(ec, "read_until");
return bytes_transferred;
}
template <typename SyncReadStream, typename DynamicBuffer_v1>
std::size_t read_until(SyncReadStream& s,
DynamicBuffer_v1&& buffers,
ASIO_STRING_VIEW_PARAM delim, asio::error_code& ec,
constraint_t<
is_dynamic_buffer_v1<decay_t<DynamicBuffer_v1>>::value
>,
constraint_t<
!is_dynamic_buffer_v2<decay_t<DynamicBuffer_v1>>::value
>)
{
decay_t<DynamicBuffer_v1> b(
static_cast<DynamicBuffer_v1&&>(buffers));
std::size_t search_position = 0;
for (;;)
{
// Determine the range of the data to be searched.
typedef typename DynamicBuffer_v1::const_buffers_type buffers_type;
typedef buffers_iterator<buffers_type> iterator;
buffers_type data_buffers = b.data();
iterator begin = iterator::begin(data_buffers);
iterator start_pos = begin + search_position;
iterator end = iterator::end(data_buffers);
// Look for a match.
std::pair<iterator, bool> result = detail::partial_search(
start_pos, end, delim.begin(), delim.end());
if (result.first != end)
{
if (result.second)
{
// Full match. We're done.
ec = asio::error_code();
return result.first - begin + delim.length();
}
else
{
// Partial match. Next search needs to start from beginning of match.
search_position = result.first - begin;
}
}
else
{
// No match. Next search can start with the new data.
search_position = end - begin;
}
// Check if buffer is full.
if (b.size() == b.max_size())
{
ec = error::not_found;
return 0;
}
// Need more data.
std::size_t bytes_to_read = std::min<std::size_t>(
std::max<std::size_t>(512, b.capacity() - b.size()),
std::min<std::size_t>(65536, b.max_size() - b.size()));
b.commit(s.read_some(b.prepare(bytes_to_read), ec));
if (ec)
return 0;
}
}
#if !defined(ASIO_NO_EXTENSIONS)
#if defined(ASIO_HAS_BOOST_REGEX)
template <typename SyncReadStream, typename DynamicBuffer_v1, typename Traits>
inline 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
>,
constraint_t<
!is_dynamic_buffer_v2<decay_t<DynamicBuffer_v1>>::value
>)
{
asio::error_code ec;
std::size_t bytes_transferred = read_until(s,
static_cast<DynamicBuffer_v1&&>(buffers), expr, ec);
asio::detail::throw_error(ec, "read_until");
return bytes_transferred;
}
template <typename SyncReadStream, typename DynamicBuffer_v1, typename Traits>
std::size_t read_until(SyncReadStream& s, DynamicBuffer_v1&& buffers,
const boost::basic_regex<char, Traits>& expr, asio::error_code& ec,
constraint_t<
is_dynamic_buffer_v1<decay_t<DynamicBuffer_v1>>::value
>,
constraint_t<
!is_dynamic_buffer_v2<decay_t<DynamicBuffer_v1>>::value
>)
{
decay_t<DynamicBuffer_v1> b(
static_cast<DynamicBuffer_v1&&>(buffers));
std::size_t search_position = 0;
for (;;)
{
// Determine the range of the data to be searched.
typedef typename DynamicBuffer_v1::const_buffers_type buffers_type;
typedef buffers_iterator<buffers_type> iterator;
buffers_type data_buffers = b.data();
iterator begin = iterator::begin(data_buffers);
iterator start_pos = begin + search_position;
iterator end = iterator::end(data_buffers);
// Look for a match.
boost::match_results<iterator,
typename std::vector<boost::sub_match<iterator>>::allocator_type>
match_results;
if (regex_search(start_pos, end, match_results,
expr, detail::regex_match_flags()))
{
if (match_results[0].matched)
{
// Full match. We're done.
ec = asio::error_code();
return match_results[0].second - begin;
}
else
{
// Partial match. Next search needs to start from beginning of match.
search_position = match_results[0].first - begin;
}
}
else
{
// No match. Next search can start with the new data.
search_position = end - begin;
}
// Check if buffer is full.
if (b.size() == b.max_size())
{
ec = error::not_found;
return 0;
}
// Need more data.
std::size_t bytes_to_read = std::min<std::size_t>(
std::max<std::size_t>(512, b.capacity() - b.size()),
std::min<std::size_t>(65536, b.max_size() - b.size()));
b.commit(s.read_some(b.prepare(bytes_to_read), ec));
if (ec)
return 0;
}
}
#endif // defined(ASIO_HAS_BOOST_REGEX)
template <typename SyncReadStream,
typename DynamicBuffer_v1, typename MatchCondition>
inline std::size_t read_until(SyncReadStream& s,
DynamicBuffer_v1&& buffers,
MatchCondition match_condition,
constraint_t<
is_match_condition<MatchCondition>::value
>,
constraint_t<
is_dynamic_buffer_v1<decay_t<DynamicBuffer_v1>>::value
>,
constraint_t<
!is_dynamic_buffer_v2<decay_t<DynamicBuffer_v1>>::value
>)
{
asio::error_code ec;
std::size_t bytes_transferred = read_until(s,
static_cast<DynamicBuffer_v1&&>(buffers),
match_condition, ec);
asio::detail::throw_error(ec, "read_until");
return bytes_transferred;
}
template <typename SyncReadStream,
typename DynamicBuffer_v1, typename MatchCondition>
std::size_t read_until(SyncReadStream& s,
DynamicBuffer_v1&& buffers,
MatchCondition match_condition, asio::error_code& ec,
constraint_t<
is_match_condition<MatchCondition>::value
>,
constraint_t<
is_dynamic_buffer_v1<decay_t<DynamicBuffer_v1>>::value
>,
constraint_t<
!is_dynamic_buffer_v2<decay_t<DynamicBuffer_v1>>::value
>)
{
decay_t<DynamicBuffer_v1> b(
static_cast<DynamicBuffer_v1&&>(buffers));
std::size_t search_position = 0;
for (;;)
{
// Determine the range of the data to be searched.
typedef typename DynamicBuffer_v1::const_buffers_type buffers_type;
typedef buffers_iterator<buffers_type> iterator;
buffers_type data_buffers = b.data();
iterator begin = iterator::begin(data_buffers);
iterator start_pos = begin + search_position;
iterator end = iterator::end(data_buffers);
// Look for a match.
std::pair<iterator, bool> result = match_condition(start_pos, end);
if (result.second)
{
// Full match. We're done.
ec = asio::error_code();
return result.first - begin;
}
else if (result.first != end)
{
// Partial match. Next search needs to start from beginning of match.
search_position = result.first - begin;
}
else
{
// No match. Next search can start with the new data.
search_position = end - begin;
}
// Check if buffer is full.
if (b.size() == b.max_size())
{
ec = error::not_found;
return 0;
}
// Need more data.
std::size_t bytes_to_read = std::min<std::size_t>(
std::max<std::size_t>(512, b.capacity() - b.size()),
std::min<std::size_t>(65536, b.max_size() - b.size()));
b.commit(s.read_some(b.prepare(bytes_to_read), ec));
if (ec)
return 0;
}
}
#if !defined(ASIO_NO_IOSTREAM)
template <typename SyncReadStream, typename Allocator>
inline std::size_t read_until(SyncReadStream& s,
asio::basic_streambuf<Allocator>& b, char delim)
{
return read_until(s, basic_streambuf_ref<Allocator>(b), delim);
}
template <typename SyncReadStream, typename Allocator>
inline std::size_t read_until(SyncReadStream& s,
asio::basic_streambuf<Allocator>& b, char delim,
asio::error_code& ec)
{
return read_until(s, basic_streambuf_ref<Allocator>(b), delim, ec);
}
template <typename SyncReadStream, typename Allocator>
inline std::size_t read_until(SyncReadStream& s,
asio::basic_streambuf<Allocator>& b,
ASIO_STRING_VIEW_PARAM delim)
{
return read_until(s, basic_streambuf_ref<Allocator>(b), delim);
}
template <typename SyncReadStream, typename Allocator>
inline std::size_t read_until(SyncReadStream& s,
asio::basic_streambuf<Allocator>& b,
ASIO_STRING_VIEW_PARAM delim, asio::error_code& ec)
{
return read_until(s, basic_streambuf_ref<Allocator>(b), delim, ec);
}
#if defined(ASIO_HAS_BOOST_REGEX)
template <typename SyncReadStream, typename Allocator, typename Traits>
inline std::size_t read_until(SyncReadStream& s,
asio::basic_streambuf<Allocator>& b,
const boost::basic_regex<char, Traits>& expr)
{
return read_until(s, basic_streambuf_ref<Allocator>(b), expr);
}
template <typename SyncReadStream, typename Allocator, typename Traits>
inline std::size_t read_until(SyncReadStream& s,
asio::basic_streambuf<Allocator>& b,
const boost::basic_regex<char, Traits>& expr,
asio::error_code& ec)
{
return read_until(s, basic_streambuf_ref<Allocator>(b), expr, ec);
}
#endif // defined(ASIO_HAS_BOOST_REGEX)
template <typename SyncReadStream, typename Allocator, typename MatchCondition>
inline std::size_t read_until(SyncReadStream& s,
asio::basic_streambuf<Allocator>& b, MatchCondition match_condition,
constraint_t<is_match_condition<MatchCondition>::value>)
{
return read_until(s, basic_streambuf_ref<Allocator>(b), match_condition);
}
template <typename SyncReadStream, typename Allocator, typename MatchCondition>
inline std::size_t read_until(SyncReadStream& s,
asio::basic_streambuf<Allocator>& b,
MatchCondition match_condition, asio::error_code& ec,
constraint_t<is_match_condition<MatchCondition>::value>)
{
return read_until(s, basic_streambuf_ref<Allocator>(b), match_condition, ec);
}
#endif // !defined(ASIO_NO_IOSTREAM)
#endif // !defined(ASIO_NO_EXTENSIONS)
#endif // !defined(ASIO_NO_DYNAMIC_BUFFER_V1)
template <typename SyncReadStream, typename DynamicBuffer_v2>
inline std::size_t read_until(SyncReadStream& s,
DynamicBuffer_v2 buffers, char delim,
constraint_t<
is_dynamic_buffer_v2<DynamicBuffer_v2>::value
>)
{
asio::error_code ec;
std::size_t bytes_transferred = read_until(s,
static_cast<DynamicBuffer_v2&&>(buffers), delim, ec);
asio::detail::throw_error(ec, "read_until");
return bytes_transferred;
}
template <typename SyncReadStream, typename DynamicBuffer_v2>
std::size_t read_until(SyncReadStream& s, DynamicBuffer_v2 buffers,
char delim, asio::error_code& ec,
constraint_t<
is_dynamic_buffer_v2<DynamicBuffer_v2>::value
>)
{
DynamicBuffer_v2& b = buffers;
std::size_t search_position = 0;
for (;;)
{
// Determine the range of the data to be searched.
typedef typename DynamicBuffer_v2::const_buffers_type buffers_type;
typedef buffers_iterator<buffers_type> iterator;
buffers_type data_buffers =
const_cast<const DynamicBuffer_v2&>(b).data(0, b.size());
iterator begin = iterator::begin(data_buffers);
iterator start_pos = begin + search_position;
iterator end = iterator::end(data_buffers);
// Look for a match.
iterator iter = std::find(start_pos, end, delim);
if (iter != end)
{
// Found a match. We're done.
ec = asio::error_code();
return iter - begin + 1;
}
else
{
// No match. Next search can start with the new data.
search_position = end - begin;
}
// Check if buffer is full.
if (b.size() == b.max_size())
{
ec = error::not_found;
return 0;
}
// Need more data.
std::size_t bytes_to_read = std::min<std::size_t>(
std::max<std::size_t>(512, b.capacity() - b.size()),
std::min<std::size_t>(65536, b.max_size() - b.size()));
std::size_t pos = b.size();
b.grow(bytes_to_read);
std::size_t bytes_transferred = s.read_some(b.data(pos, bytes_to_read), ec);
b.shrink(bytes_to_read - bytes_transferred);
if (ec)
return 0;
}
}
template <typename SyncReadStream, typename DynamicBuffer_v2>
inline std::size_t read_until(SyncReadStream& s,
DynamicBuffer_v2 buffers, ASIO_STRING_VIEW_PARAM delim,
constraint_t<
is_dynamic_buffer_v2<DynamicBuffer_v2>::value
>)
{
asio::error_code ec;
std::size_t bytes_transferred = read_until(s,
static_cast<DynamicBuffer_v2&&>(buffers), delim, ec);
asio::detail::throw_error(ec, "read_until");
return bytes_transferred;
}
template <typename SyncReadStream, typename DynamicBuffer_v2>
std::size_t read_until(SyncReadStream& s, DynamicBuffer_v2 buffers,
ASIO_STRING_VIEW_PARAM delim, asio::error_code& ec,
constraint_t<
is_dynamic_buffer_v2<DynamicBuffer_v2>::value
>)
{
DynamicBuffer_v2& b = buffers;
std::size_t search_position = 0;
for (;;)
{
// Determine the range of the data to be searched.
typedef typename DynamicBuffer_v2::const_buffers_type buffers_type;
typedef buffers_iterator<buffers_type> iterator;
buffers_type data_buffers =
const_cast<const DynamicBuffer_v2&>(b).data(0, b.size());
iterator begin = iterator::begin(data_buffers);
iterator start_pos = begin + search_position;
iterator end = iterator::end(data_buffers);
// Look for a match.
std::pair<iterator, bool> result = detail::partial_search(
start_pos, end, delim.begin(), delim.end());
if (result.first != end)
{
if (result.second)
{
// Full match. We're done.
ec = asio::error_code();
return result.first - begin + delim.length();
}
else
{
// Partial match. Next search needs to start from beginning of match.
search_position = result.first - begin;
}
}
else
{
// No match. Next search can start with the new data.
search_position = end - begin;
}
// Check if buffer is full.
if (b.size() == b.max_size())
{
ec = error::not_found;
return 0;
}
// Need more data.
std::size_t bytes_to_read = std::min<std::size_t>(
std::max<std::size_t>(512, b.capacity() - b.size()),
std::min<std::size_t>(65536, b.max_size() - b.size()));
std::size_t pos = b.size();
b.grow(bytes_to_read);
std::size_t bytes_transferred = s.read_some(b.data(pos, bytes_to_read), ec);
b.shrink(bytes_to_read - bytes_transferred);
if (ec)
return 0;
}
}
#if !defined(ASIO_NO_EXTENSIONS)
#if defined(ASIO_HAS_BOOST_REGEX)
template <typename SyncReadStream, typename DynamicBuffer_v2, typename Traits>
inline 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
>)
{
asio::error_code ec;
std::size_t bytes_transferred = read_until(s,
static_cast<DynamicBuffer_v2&&>(buffers), expr, ec);
asio::detail::throw_error(ec, "read_until");
return bytes_transferred;
}
template <typename SyncReadStream, typename DynamicBuffer_v2, typename Traits>
std::size_t read_until(SyncReadStream& s, DynamicBuffer_v2 buffers,
const boost::basic_regex<char, Traits>& expr, asio::error_code& ec,
constraint_t<
is_dynamic_buffer_v2<DynamicBuffer_v2>::value
>)
{
DynamicBuffer_v2& b = buffers;
std::size_t search_position = 0;
for (;;)
{
// Determine the range of the data to be searched.
typedef typename DynamicBuffer_v2::const_buffers_type buffers_type;
typedef buffers_iterator<buffers_type> iterator;
buffers_type data_buffers =
const_cast<const DynamicBuffer_v2&>(b).data(0, b.size());
iterator begin = iterator::begin(data_buffers);
iterator start_pos = begin + search_position;
iterator end = iterator::end(data_buffers);
// Look for a match.
boost::match_results<iterator,
typename std::vector<boost::sub_match<iterator>>::allocator_type>
match_results;
if (regex_search(start_pos, end, match_results,
expr, detail::regex_match_flags()))
{
if (match_results[0].matched)
{
// Full match. We're done.
ec = asio::error_code();
return match_results[0].second - begin;
}
else
{
// Partial match. Next search needs to start from beginning of match.
search_position = match_results[0].first - begin;
}
}
else
{
// No match. Next search can start with the new data.
search_position = end - begin;
}
// Check if buffer is full.
if (b.size() == b.max_size())
{
ec = error::not_found;
return 0;
}
// Need more data.
std::size_t bytes_to_read = std::min<std::size_t>(
std::max<std::size_t>(512, b.capacity() - b.size()),
std::min<std::size_t>(65536, b.max_size() - b.size()));
std::size_t pos = b.size();
b.grow(bytes_to_read);
std::size_t bytes_transferred = s.read_some(b.data(pos, bytes_to_read), ec);
b.shrink(bytes_to_read - bytes_transferred);
if (ec)
return 0;
}
}
#endif // defined(ASIO_HAS_BOOST_REGEX)
template <typename SyncReadStream,
typename DynamicBuffer_v2, typename MatchCondition>
inline std::size_t read_until(SyncReadStream& s,
DynamicBuffer_v2 buffers, MatchCondition match_condition,
constraint_t<
is_match_condition<MatchCondition>::value
>,
constraint_t<
is_dynamic_buffer_v2<DynamicBuffer_v2>::value
>)
{
asio::error_code ec;
std::size_t bytes_transferred = read_until(s,
static_cast<DynamicBuffer_v2&&>(buffers),
match_condition, ec);
asio::detail::throw_error(ec, "read_until");
return bytes_transferred;
}
template <typename SyncReadStream,
typename DynamicBuffer_v2, typename MatchCondition>
std::size_t read_until(SyncReadStream& s, DynamicBuffer_v2 buffers,
MatchCondition match_condition, asio::error_code& ec,
constraint_t<
is_match_condition<MatchCondition>::value
>,
constraint_t<
is_dynamic_buffer_v2<DynamicBuffer_v2>::value
>)
{
DynamicBuffer_v2& b = buffers;
std::size_t search_position = 0;
for (;;)
{
// Determine the range of the data to be searched.
typedef typename DynamicBuffer_v2::const_buffers_type buffers_type;
typedef buffers_iterator<buffers_type> iterator;
buffers_type data_buffers =
const_cast<const DynamicBuffer_v2&>(b).data(0, b.size());
iterator begin = iterator::begin(data_buffers);
iterator start_pos = begin + search_position;
iterator end = iterator::end(data_buffers);
// Look for a match.
std::pair<iterator, bool> result = match_condition(start_pos, end);
if (result.second)
{
// Full match. We're done.
ec = asio::error_code();
return result.first - begin;
}
else if (result.first != end)
{
// Partial match. Next search needs to start from beginning of match.
search_position = result.first - begin;
}
else
{
// No match. Next search can start with the new data.
search_position = end - begin;
}
// Check if buffer is full.
if (b.size() == b.max_size())
{
ec = error::not_found;
return 0;
}
// Need more data.
std::size_t bytes_to_read = std::min<std::size_t>(
std::max<std::size_t>(512, b.capacity() - b.size()),
std::min<std::size_t>(65536, b.max_size() - b.size()));
std::size_t pos = b.size();
b.grow(bytes_to_read);
std::size_t bytes_transferred = s.read_some(b.data(pos, bytes_to_read), ec);
b.shrink(bytes_to_read - bytes_transferred);
if (ec)
return 0;
}
}
#endif // !defined(ASIO_NO_EXTENSIONS)
#if !defined(ASIO_NO_DYNAMIC_BUFFER_V1)
namespace detail
{
template <typename AsyncReadStream,
typename DynamicBuffer_v1, typename ReadHandler>
class read_until_delim_op_v1
: public base_from_cancellation_state<ReadHandler>
{
public:
template <typename BufferSequence>
read_until_delim_op_v1(AsyncReadStream& stream,
BufferSequence&& buffers,
char delim, ReadHandler& handler)
: base_from_cancellation_state<ReadHandler>(
handler, enable_partial_cancellation()),
stream_(stream),
buffers_(static_cast<BufferSequence&&>(buffers)),
delim_(delim),
start_(0),
search_position_(0),
handler_(static_cast<ReadHandler&&>(handler))
{
}
read_until_delim_op_v1(const read_until_delim_op_v1& other)
: base_from_cancellation_state<ReadHandler>(other),
stream_(other.stream_),
buffers_(other.buffers_),
delim_(other.delim_),
start_(other.start_),
search_position_(other.search_position_),
handler_(other.handler_)
{
}
read_until_delim_op_v1(read_until_delim_op_v1&& other)
: base_from_cancellation_state<ReadHandler>(
static_cast<base_from_cancellation_state<ReadHandler>&&>(other)),
stream_(other.stream_),
buffers_(static_cast<DynamicBuffer_v1&&>(other.buffers_)),
delim_(other.delim_),
start_(other.start_),
search_position_(other.search_position_),
handler_(static_cast<ReadHandler&&>(other.handler_))
{
}
void operator()(asio::error_code ec,
std::size_t bytes_transferred, int start = 0)
{
const std::size_t not_found = (std::numeric_limits<std::size_t>::max)();
std::size_t bytes_to_read;
switch (start_ = start)
{
case 1:
for (;;)
{
{
// Determine the range of the data to be searched.
typedef typename DynamicBuffer_v1::const_buffers_type
buffers_type;
typedef buffers_iterator<buffers_type> iterator;
buffers_type data_buffers = buffers_.data();
iterator begin = iterator::begin(data_buffers);
iterator start_pos = begin + search_position_;
iterator end = iterator::end(data_buffers);
// Look for a match.
iterator iter = std::find(start_pos, end, delim_);
if (iter != end)
{
// Found a match. We're done.
search_position_ = iter - begin + 1;
bytes_to_read = 0;
}
// No match yet. Check if buffer is full.
else if (buffers_.size() == buffers_.max_size())
{
search_position_ = not_found;
bytes_to_read = 0;
}
// Need to read some more data.
else
{
// Next search can start with the new data.
search_position_ = end - begin;
bytes_to_read = std::min<std::size_t>(
std::max<std::size_t>(512,
buffers_.capacity() - buffers_.size()),
std::min<std::size_t>(65536,
buffers_.max_size() - buffers_.size()));
}
}
// Check if we're done.
if (!start && bytes_to_read == 0)
break;
// Start a new asynchronous read operation to obtain more data.
{
ASIO_HANDLER_LOCATION((
__FILE__, __LINE__, "async_read_until"));
stream_.async_read_some(buffers_.prepare(bytes_to_read),
static_cast<read_until_delim_op_v1&&>(*this));
}
return; default:
buffers_.commit(bytes_transferred);
if (ec || bytes_transferred == 0)
break;
if (this->cancelled() != cancellation_type::none)
{
ec = error::operation_aborted;
break;
}
}
const asio::error_code result_ec =
(search_position_ == not_found)
? error::not_found : ec;
const std::size_t result_n =
(ec || search_position_ == not_found)
? 0 : search_position_;
static_cast<ReadHandler&&>(handler_)(result_ec, result_n);
}
}
//private:
AsyncReadStream& stream_;
DynamicBuffer_v1 buffers_;
char delim_;
int start_;
std::size_t search_position_;
ReadHandler handler_;
};
template <typename AsyncReadStream,
typename DynamicBuffer_v1, typename ReadHandler>
inline bool asio_handler_is_continuation(
read_until_delim_op_v1<AsyncReadStream,
DynamicBuffer_v1, ReadHandler>* this_handler)
{
return this_handler->start_ == 0 ? true
: asio_handler_cont_helpers::is_continuation(
this_handler->handler_);
}
template <typename AsyncReadStream>
class initiate_async_read_until_delim_v1
{
public:
typedef typename AsyncReadStream::executor_type executor_type;
explicit initiate_async_read_until_delim_v1(AsyncReadStream& stream)
: stream_(stream)
{
}
executor_type get_executor() const noexcept
{
return stream_.get_executor();
}
template <typename ReadHandler, typename DynamicBuffer_v1>
void operator()(ReadHandler&& handler,
DynamicBuffer_v1&& buffers,
char delim) const
{
// If you get an error on the following line it means that your handler
// does not meet the documented type requirements for a ReadHandler.
ASIO_READ_HANDLER_CHECK(ReadHandler, handler) type_check;
non_const_lvalue<ReadHandler> handler2(handler);
read_until_delim_op_v1<AsyncReadStream,
decay_t<DynamicBuffer_v1>,
decay_t<ReadHandler>>(
stream_, static_cast<DynamicBuffer_v1&&>(buffers),
delim, handler2.value)(asio::error_code(), 0, 1);
}
private:
AsyncReadStream& stream_;
};
} // namespace detail
#if !defined(GENERATING_DOCUMENTATION)
template <template <typename, typename> class Associator,
typename AsyncReadStream, typename DynamicBuffer_v1,
typename ReadHandler, typename DefaultCandidate>
struct associator<Associator,
detail::read_until_delim_op_v1<AsyncReadStream,
DynamicBuffer_v1, ReadHandler>,
DefaultCandidate>
: Associator<ReadHandler, DefaultCandidate>
{
static typename Associator<ReadHandler, DefaultCandidate>::type get(
const detail::read_until_delim_op_v1<AsyncReadStream,
DynamicBuffer_v1, ReadHandler>& h) noexcept
{
return Associator<ReadHandler, DefaultCandidate>::get(h.handler_);
}
static auto get(
const detail::read_until_delim_op_v1<AsyncReadStream,
DynamicBuffer_v1, ReadHandler>& h,
const DefaultCandidate& c) noexcept
-> decltype(Associator<ReadHandler, DefaultCandidate>::get(h.handler_, c))
{
return Associator<ReadHandler, DefaultCandidate>::get(h.handler_, c);
}
};
#endif // !defined(GENERATING_DOCUMENTATION)
namespace detail
{
template <typename AsyncReadStream,
typename DynamicBuffer_v1, typename ReadHandler>
class read_until_delim_string_op_v1
: public base_from_cancellation_state<ReadHandler>
{
public:
template <typename BufferSequence>
read_until_delim_string_op_v1(AsyncReadStream& stream,
BufferSequence&& buffers,
const std::string& delim, ReadHandler& handler)
: base_from_cancellation_state<ReadHandler>(
handler, enable_partial_cancellation()),
stream_(stream),
buffers_(static_cast<BufferSequence&&>(buffers)),
delim_(delim),
start_(0),
search_position_(0),
handler_(static_cast<ReadHandler&&>(handler))
{
}
read_until_delim_string_op_v1(const read_until_delim_string_op_v1& other)
: base_from_cancellation_state<ReadHandler>(other),
stream_(other.stream_),
buffers_(other.buffers_),
delim_(other.delim_),
start_(other.start_),
search_position_(other.search_position_),
handler_(other.handler_)
{
}
read_until_delim_string_op_v1(read_until_delim_string_op_v1&& other)
: base_from_cancellation_state<ReadHandler>(
static_cast<base_from_cancellation_state<ReadHandler>&&>(other)),
stream_(other.stream_),
buffers_(static_cast<DynamicBuffer_v1&&>(other.buffers_)),
delim_(static_cast<std::string&&>(other.delim_)),
start_(other.start_),
search_position_(other.search_position_),
handler_(static_cast<ReadHandler&&>(other.handler_))
{
}
void operator()(asio::error_code ec,
std::size_t bytes_transferred, int start = 0)
{
const std::size_t not_found = (std::numeric_limits<std::size_t>::max)();
std::size_t bytes_to_read;
switch (start_ = start)
{
case 1:
for (;;)
{
{
// Determine the range of the data to be searched.
typedef typename DynamicBuffer_v1::const_buffers_type
buffers_type;
typedef buffers_iterator<buffers_type> iterator;
buffers_type data_buffers = buffers_.data();
iterator begin = iterator::begin(data_buffers);
iterator start_pos = begin + search_position_;
iterator end = iterator::end(data_buffers);
// Look for a match.
std::pair<iterator, bool> result = detail::partial_search(
start_pos, end, delim_.begin(), delim_.end());
if (result.first != end && result.second)
{
// Full match. We're done.
search_position_ = result.first - begin + delim_.length();
bytes_to_read = 0;
}
// No match yet. Check if buffer is full.
else if (buffers_.size() == buffers_.max_size())
{
search_position_ = not_found;
bytes_to_read = 0;
}
// Need to read some more data.
else
{
if (result.first != end)
{
// Partial match. Next search needs to start from beginning of
// match.
search_position_ = result.first - begin;
}
else
{
// Next search can start with the new data.
search_position_ = end - begin;
}
bytes_to_read = std::min<std::size_t>(
std::max<std::size_t>(512,
buffers_.capacity() - buffers_.size()),
std::min<std::size_t>(65536,
buffers_.max_size() - buffers_.size()));
}
}
// Check if we're done.
if (!start && bytes_to_read == 0)
break;
// Start a new asynchronous read operation to obtain more data.
{
ASIO_HANDLER_LOCATION((
__FILE__, __LINE__, "async_read_until"));
stream_.async_read_some(buffers_.prepare(bytes_to_read),
static_cast<read_until_delim_string_op_v1&&>(*this));
}
return; default:
buffers_.commit(bytes_transferred);
if (ec || bytes_transferred == 0)
break;
if (this->cancelled() != cancellation_type::none)
{
ec = error::operation_aborted;
break;
}
}
const asio::error_code result_ec =
(search_position_ == not_found)
? error::not_found : ec;
const std::size_t result_n =
(ec || search_position_ == not_found)
? 0 : search_position_;
static_cast<ReadHandler&&>(handler_)(result_ec, result_n);
}
}
//private:
AsyncReadStream& stream_;
DynamicBuffer_v1 buffers_;
std::string delim_;
int start_;
std::size_t search_position_;
ReadHandler handler_;
};
template <typename AsyncReadStream,
typename DynamicBuffer_v1, typename ReadHandler>
inline bool asio_handler_is_continuation(
read_until_delim_string_op_v1<AsyncReadStream,
DynamicBuffer_v1, ReadHandler>* this_handler)
{
return this_handler->start_ == 0 ? true
: asio_handler_cont_helpers::is_continuation(
this_handler->handler_);
}
template <typename AsyncReadStream>
class initiate_async_read_until_delim_string_v1
{
public:
typedef typename AsyncReadStream::executor_type executor_type;
explicit initiate_async_read_until_delim_string_v1(AsyncReadStream& stream)
: stream_(stream)
{
}
executor_type get_executor() const noexcept
{
return stream_.get_executor();
}
template <typename ReadHandler, typename DynamicBuffer_v1>
void operator()(ReadHandler&& handler,
DynamicBuffer_v1&& buffers,
const std::string& delim) const
{
// If you get an error on the following line it means that your handler
// does not meet the documented type requirements for a ReadHandler.
ASIO_READ_HANDLER_CHECK(ReadHandler, handler) type_check;
non_const_lvalue<ReadHandler> handler2(handler);
read_until_delim_string_op_v1<AsyncReadStream,
decay_t<DynamicBuffer_v1>,
decay_t<ReadHandler>>(
stream_, static_cast<DynamicBuffer_v1&&>(buffers),
delim, handler2.value)(asio::error_code(), 0, 1);
}
private:
AsyncReadStream& stream_;
};
} // namespace detail
#if !defined(GENERATING_DOCUMENTATION)
template <template <typename, typename> class Associator,
typename AsyncReadStream, typename DynamicBuffer_v1,
typename ReadHandler, typename DefaultCandidate>
struct associator<Associator,
detail::read_until_delim_string_op_v1<AsyncReadStream,
DynamicBuffer_v1, ReadHandler>,
DefaultCandidate>
: Associator<ReadHandler, DefaultCandidate>
{
static typename Associator<ReadHandler, DefaultCandidate>::type get(
const detail::read_until_delim_string_op_v1<
AsyncReadStream, DynamicBuffer_v1, ReadHandler>& h) noexcept
{
return Associator<ReadHandler, DefaultCandidate>::get(h.handler_);
}
static auto get(
const detail::read_until_delim_string_op_v1<
AsyncReadStream, DynamicBuffer_v1, ReadHandler>& h,
const DefaultCandidate& c) noexcept
-> decltype(Associator<ReadHandler, DefaultCandidate>::get(h.handler_, c))
{
return Associator<ReadHandler, DefaultCandidate>::get(h.handler_, c);
}
};
#endif // !defined(GENERATING_DOCUMENTATION)
#if !defined(ASIO_NO_EXTENSIONS)
#if defined(ASIO_HAS_BOOST_REGEX)
namespace detail
{
template <typename AsyncReadStream, typename DynamicBuffer_v1,
typename RegEx, typename ReadHandler>
class read_until_expr_op_v1
: public base_from_cancellation_state<ReadHandler>
{
public:
template <typename BufferSequence, typename Traits>
read_until_expr_op_v1(AsyncReadStream& stream, BufferSequence&& buffers,
const boost::basic_regex<char, Traits>& expr, ReadHandler& handler)
: base_from_cancellation_state<ReadHandler>(
handler, enable_partial_cancellation()),
stream_(stream),
buffers_(static_cast<BufferSequence&&>(buffers)),
expr_(expr),
start_(0),
search_position_(0),
handler_(static_cast<ReadHandler&&>(handler))
{
}
read_until_expr_op_v1(const read_until_expr_op_v1& other)
: base_from_cancellation_state<ReadHandler>(other),
stream_(other.stream_),
buffers_(other.buffers_),
expr_(other.expr_),
start_(other.start_),
search_position_(other.search_position_),
handler_(other.handler_)
{
}
read_until_expr_op_v1(read_until_expr_op_v1&& other)
: base_from_cancellation_state<ReadHandler>(
static_cast<base_from_cancellation_state<ReadHandler>&&>(other)),
stream_(other.stream_),
buffers_(static_cast<DynamicBuffer_v1&&>(other.buffers_)),
expr_(other.expr_),
start_(other.start_),
search_position_(other.search_position_),
handler_(static_cast<ReadHandler&&>(other.handler_))
{
}
void operator()(asio::error_code ec,
std::size_t bytes_transferred, int start = 0)
{
const std::size_t not_found = (std::numeric_limits<std::size_t>::max)();
std::size_t bytes_to_read;
switch (start_ = start)
{
case 1:
for (;;)
{
{
// Determine the range of the data to be searched.
typedef typename DynamicBuffer_v1::const_buffers_type
buffers_type;
typedef buffers_iterator<buffers_type> iterator;
buffers_type data_buffers = buffers_.data();
iterator begin = iterator::begin(data_buffers);
iterator start_pos = begin + search_position_;
iterator end = iterator::end(data_buffers);
// Look for a match.
boost::match_results<iterator,
typename std::vector<boost::sub_match<iterator>>::allocator_type>
match_results;
bool match = regex_search(start_pos, end,
match_results, expr_, regex_match_flags());
if (match && match_results[0].matched)
{
// Full match. We're done.
search_position_ = match_results[0].second - begin;
bytes_to_read = 0;
}
// No match yet. Check if buffer is full.
else if (buffers_.size() == buffers_.max_size())
{
search_position_ = not_found;
bytes_to_read = 0;
}
// Need to read some more data.
else
{
if (match)
{
// Partial match. Next search needs to start from beginning of
// match.
search_position_ = match_results[0].first - begin;
}
else
{
// Next search can start with the new data.
search_position_ = end - begin;
}
bytes_to_read = std::min<std::size_t>(
std::max<std::size_t>(512,
buffers_.capacity() - buffers_.size()),
std::min<std::size_t>(65536,
buffers_.max_size() - buffers_.size()));
}
}
// Check if we're done.
if (!start && bytes_to_read == 0)
break;
// Start a new asynchronous read operation to obtain more data.
{
ASIO_HANDLER_LOCATION((
__FILE__, __LINE__, "async_read_until"));
stream_.async_read_some(buffers_.prepare(bytes_to_read),
static_cast<read_until_expr_op_v1&&>(*this));
}
return; default:
buffers_.commit(bytes_transferred);
if (ec || bytes_transferred == 0)
break;
if (this->cancelled() != cancellation_type::none)
{
ec = error::operation_aborted;
break;
}
}
const asio::error_code result_ec =
(search_position_ == not_found)
? error::not_found : ec;
const std::size_t result_n =
(ec || search_position_ == not_found)
? 0 : search_position_;
static_cast<ReadHandler&&>(handler_)(result_ec, result_n);
}
}
//private:
AsyncReadStream& stream_;
DynamicBuffer_v1 buffers_;
RegEx expr_;
int start_;
std::size_t search_position_;
ReadHandler handler_;
};
template <typename AsyncReadStream, typename DynamicBuffer_v1,
typename RegEx, typename ReadHandler>
inline bool asio_handler_is_continuation(
read_until_expr_op_v1<AsyncReadStream,
DynamicBuffer_v1, RegEx, ReadHandler>* this_handler)
{
return this_handler->start_ == 0 ? true
: asio_handler_cont_helpers::is_continuation(
this_handler->handler_);
}
template <typename AsyncReadStream>
class initiate_async_read_until_expr_v1
{
public:
typedef typename AsyncReadStream::executor_type executor_type;
explicit initiate_async_read_until_expr_v1(AsyncReadStream& stream)
: stream_(stream)
{
}
executor_type get_executor() const noexcept
{
return stream_.get_executor();
}
template <typename ReadHandler, typename DynamicBuffer_v1, typename RegEx>
void operator()(ReadHandler&& handler,
DynamicBuffer_v1&& buffers, const RegEx& expr) const
{
// If you get an error on the following line it means that your handler
// does not meet the documented type requirements for a ReadHandler.
ASIO_READ_HANDLER_CHECK(ReadHandler, handler) type_check;
non_const_lvalue<ReadHandler> handler2(handler);
read_until_expr_op_v1<AsyncReadStream,
decay_t<DynamicBuffer_v1>,
RegEx, decay_t<ReadHandler>>(
stream_, static_cast<DynamicBuffer_v1&&>(buffers),
expr, handler2.value)(asio::error_code(), 0, 1);
}
private:
AsyncReadStream& stream_;
};
} // namespace detail
#if !defined(GENERATING_DOCUMENTATION)
template <template <typename, typename> class Associator,
typename AsyncReadStream, typename DynamicBuffer_v1,
typename RegEx, typename ReadHandler, typename DefaultCandidate>
struct associator<Associator,
detail::read_until_expr_op_v1<AsyncReadStream,
DynamicBuffer_v1, RegEx, ReadHandler>,
DefaultCandidate>
: Associator<ReadHandler, DefaultCandidate>
{
static typename Associator<ReadHandler, DefaultCandidate>::type get(
const detail::read_until_expr_op_v1<AsyncReadStream,
DynamicBuffer_v1, RegEx, ReadHandler>& h) noexcept
{
return Associator<ReadHandler, DefaultCandidate>::get(h.handler_);
}
static auto get(
const detail::read_until_expr_op_v1<AsyncReadStream,
DynamicBuffer_v1, RegEx, ReadHandler>& h,
const DefaultCandidate& c) noexcept
-> decltype(Associator<ReadHandler, DefaultCandidate>::get(h.handler_, c))
{
return Associator<ReadHandler, DefaultCandidate>::get(h.handler_, c);
}
};
#endif // !defined(GENERATING_DOCUMENTATION)
#endif // defined(ASIO_HAS_BOOST_REGEX)
namespace detail
{
template <typename AsyncReadStream, typename DynamicBuffer_v1,
typename MatchCondition, typename ReadHandler>
class read_until_match_op_v1
: public base_from_cancellation_state<ReadHandler>
{
public:
template <typename BufferSequence>
read_until_match_op_v1(AsyncReadStream& stream,
BufferSequence&& buffers,
MatchCondition match_condition, ReadHandler& handler)
: base_from_cancellation_state<ReadHandler>(
handler, enable_partial_cancellation()),
stream_(stream),
buffers_(static_cast<BufferSequence&&>(buffers)),
match_condition_(match_condition),
start_(0),
search_position_(0),
handler_(static_cast<ReadHandler&&>(handler))
{
}
read_until_match_op_v1(const read_until_match_op_v1& other)
: base_from_cancellation_state<ReadHandler>(other),
stream_(other.stream_),
buffers_(other.buffers_),
match_condition_(other.match_condition_),
start_(other.start_),
search_position_(other.search_position_),
handler_(other.handler_)
{
}
read_until_match_op_v1(read_until_match_op_v1&& other)
: base_from_cancellation_state<ReadHandler>(
static_cast<base_from_cancellation_state<ReadHandler>&&>(other)),
stream_(other.stream_),
buffers_(static_cast<DynamicBuffer_v1&&>(other.buffers_)),
match_condition_(other.match_condition_),
start_(other.start_),
search_position_(other.search_position_),
handler_(static_cast<ReadHandler&&>(other.handler_))
{
}
void operator()(asio::error_code ec,
std::size_t bytes_transferred, int start = 0)
{
const std::size_t not_found = (std::numeric_limits<std::size_t>::max)();
std::size_t bytes_to_read;
switch (start_ = start)
{
case 1:
for (;;)
{
{
// Determine the range of the data to be searched.
typedef typename DynamicBuffer_v1::const_buffers_type
buffers_type;
typedef buffers_iterator<buffers_type> iterator;
buffers_type data_buffers = buffers_.data();
iterator begin = iterator::begin(data_buffers);
iterator start_pos = begin + search_position_;
iterator end = iterator::end(data_buffers);
// Look for a match.
std::pair<iterator, bool> result = match_condition_(start_pos, end);
if (result.second)
{
// Full match. We're done.
search_position_ = result.first - begin;
bytes_to_read = 0;
}
// No match yet. Check if buffer is full.
else if (buffers_.size() == buffers_.max_size())
{
search_position_ = not_found;
bytes_to_read = 0;
}
// Need to read some more data.
else
{
if (result.first != end)
{
// Partial match. Next search needs to start from beginning of
// match.
search_position_ = result.first - begin;
}
else
{
// Next search can start with the new data.
search_position_ = end - begin;
}
bytes_to_read = std::min<std::size_t>(
std::max<std::size_t>(512,
buffers_.capacity() - buffers_.size()),
std::min<std::size_t>(65536,
buffers_.max_size() - buffers_.size()));
}
}
// Check if we're done.
if (!start && bytes_to_read == 0)
break;
// Start a new asynchronous read operation to obtain more data.
{
ASIO_HANDLER_LOCATION((
__FILE__, __LINE__, "async_read_until"));
stream_.async_read_some(buffers_.prepare(bytes_to_read),
static_cast<read_until_match_op_v1&&>(*this));
}
return; default:
buffers_.commit(bytes_transferred);
if (ec || bytes_transferred == 0)
break;
if (this->cancelled() != cancellation_type::none)
{
ec = error::operation_aborted;
break;
}
}
const asio::error_code result_ec =
(search_position_ == not_found)
? error::not_found : ec;
const std::size_t result_n =
(ec || search_position_ == not_found)
? 0 : search_position_;
static_cast<ReadHandler&&>(handler_)(result_ec, result_n);
}
}
//private:
AsyncReadStream& stream_;
DynamicBuffer_v1 buffers_;
MatchCondition match_condition_;
int start_;
std::size_t search_position_;
ReadHandler handler_;
};
template <typename AsyncReadStream, typename DynamicBuffer_v1,
typename MatchCondition, typename ReadHandler>
inline bool asio_handler_is_continuation(
read_until_match_op_v1<AsyncReadStream, DynamicBuffer_v1,
MatchCondition, ReadHandler>* this_handler)
{
return this_handler->start_ == 0 ? true
: asio_handler_cont_helpers::is_continuation(
this_handler->handler_);
}
template <typename AsyncReadStream>
class initiate_async_read_until_match_v1
{
public:
typedef typename AsyncReadStream::executor_type executor_type;
explicit initiate_async_read_until_match_v1(AsyncReadStream& stream)
: stream_(stream)
{
}
executor_type get_executor() const noexcept
{
return stream_.get_executor();
}
template <typename ReadHandler,
typename DynamicBuffer_v1, typename MatchCondition>
void operator()(ReadHandler&& handler,
DynamicBuffer_v1&& buffers,
MatchCondition match_condition) const
{
// If you get an error on the following line it means that your handler
// does not meet the documented type requirements for a ReadHandler.
ASIO_READ_HANDLER_CHECK(ReadHandler, handler) type_check;
non_const_lvalue<ReadHandler> handler2(handler);
read_until_match_op_v1<AsyncReadStream,
decay_t<DynamicBuffer_v1>,
MatchCondition, decay_t<ReadHandler>>(
stream_, static_cast<DynamicBuffer_v1&&>(buffers),
match_condition, handler2.value)(asio::error_code(), 0, 1);
}
private:
AsyncReadStream& stream_;
};
} // namespace detail
#if !defined(GENERATING_DOCUMENTATION)
template <template <typename, typename> class Associator,
typename AsyncReadStream, typename DynamicBuffer_v1,
typename MatchCondition, typename ReadHandler, typename DefaultCandidate>
struct associator<Associator,
detail::read_until_match_op_v1<AsyncReadStream,
DynamicBuffer_v1, MatchCondition, ReadHandler>,
DefaultCandidate>
: Associator<ReadHandler, DefaultCandidate>
{
static typename Associator<ReadHandler, DefaultCandidate>::type get(
const detail::read_until_match_op_v1<AsyncReadStream,
DynamicBuffer_v1, MatchCondition, ReadHandler>& h) noexcept
{
return Associator<ReadHandler, DefaultCandidate>::get(h.handler_);
}
static auto get(
const detail::read_until_match_op_v1<AsyncReadStream,
DynamicBuffer_v1, MatchCondition, ReadHandler>& h,
const DefaultCandidate& c) noexcept
-> decltype(Associator<ReadHandler, DefaultCandidate>::get(h.handler_, c))
{
return Associator<ReadHandler, DefaultCandidate>::get(h.handler_, c);
}
};
#endif // !defined(GENERATING_DOCUMENTATION)
#endif // !defined(ASIO_NO_EXTENSIONS)
#endif // !defined(ASIO_NO_DYNAMIC_BUFFER_V1)
namespace detail
{
template <typename AsyncReadStream,
typename DynamicBuffer_v2, typename ReadHandler>
class read_until_delim_op_v2
: public base_from_cancellation_state<ReadHandler>
{
public:
template <typename BufferSequence>
read_until_delim_op_v2(AsyncReadStream& stream,
BufferSequence&& buffers,
char delim, ReadHandler& handler)
: base_from_cancellation_state<ReadHandler>(
handler, enable_partial_cancellation()),
stream_(stream),
buffers_(static_cast<BufferSequence&&>(buffers)),
delim_(delim),
start_(0),
search_position_(0),
bytes_to_read_(0),
handler_(static_cast<ReadHandler&&>(handler))
{
}
read_until_delim_op_v2(const read_until_delim_op_v2& other)
: base_from_cancellation_state<ReadHandler>(other),
stream_(other.stream_),
buffers_(other.buffers_),
delim_(other.delim_),
start_(other.start_),
search_position_(other.search_position_),
bytes_to_read_(other.bytes_to_read_),
handler_(other.handler_)
{
}
read_until_delim_op_v2(read_until_delim_op_v2&& other)
: base_from_cancellation_state<ReadHandler>(
static_cast<base_from_cancellation_state<ReadHandler>&&>(other)),
stream_(other.stream_),
buffers_(static_cast<DynamicBuffer_v2&&>(other.buffers_)),
delim_(other.delim_),
start_(other.start_),
search_position_(other.search_position_),
bytes_to_read_(other.bytes_to_read_),
handler_(static_cast<ReadHandler&&>(other.handler_))
{
}
void operator()(asio::error_code ec,
std::size_t bytes_transferred, int start = 0)
{
const std::size_t not_found = (std::numeric_limits<std::size_t>::max)();
std::size_t pos;
switch (start_ = start)
{
case 1:
for (;;)
{
{
// Determine the range of the data to be searched.
typedef typename DynamicBuffer_v2::const_buffers_type
buffers_type;
typedef buffers_iterator<buffers_type> iterator;
buffers_type data_buffers =
const_cast<const DynamicBuffer_v2&>(buffers_).data(
0, buffers_.size());
iterator begin = iterator::begin(data_buffers);
iterator start_pos = begin + search_position_;
iterator end = iterator::end(data_buffers);
// Look for a match.
iterator iter = std::find(start_pos, end, delim_);
if (iter != end)
{
// Found a match. We're done.
search_position_ = iter - begin + 1;
bytes_to_read_ = 0;
}
// No match yet. Check if buffer is full.
else if (buffers_.size() == buffers_.max_size())
{
search_position_ = not_found;
bytes_to_read_ = 0;
}
// Need to read some more data.
else
{
// Next search can start with the new data.
search_position_ = end - begin;
bytes_to_read_ = std::min<std::size_t>(
std::max<std::size_t>(512,
buffers_.capacity() - buffers_.size()),
std::min<std::size_t>(65536,
buffers_.max_size() - buffers_.size()));
}
}
// Check if we're done.
if (!start && bytes_to_read_ == 0)
break;
// Start a new asynchronous read operation to obtain more data.
pos = buffers_.size();
buffers_.grow(bytes_to_read_);
{
ASIO_HANDLER_LOCATION((
__FILE__, __LINE__, "async_read_until"));
stream_.async_read_some(buffers_.data(pos, bytes_to_read_),
static_cast<read_until_delim_op_v2&&>(*this));
}
return; default:
buffers_.shrink(bytes_to_read_ - bytes_transferred);
if (ec || bytes_transferred == 0)
break;
if (this->cancelled() != cancellation_type::none)
{
ec = error::operation_aborted;
break;
}
}
const asio::error_code result_ec =
(search_position_ == not_found)
? error::not_found : ec;
const std::size_t result_n =
(ec || search_position_ == not_found)
? 0 : search_position_;
static_cast<ReadHandler&&>(handler_)(result_ec, result_n);
}
}
//private:
AsyncReadStream& stream_;
DynamicBuffer_v2 buffers_;
char delim_;
int start_;
std::size_t search_position_;
std::size_t bytes_to_read_;
ReadHandler handler_;
};
template <typename AsyncReadStream,
typename DynamicBuffer_v2, typename ReadHandler>
inline bool asio_handler_is_continuation(
read_until_delim_op_v2<AsyncReadStream,
DynamicBuffer_v2, ReadHandler>* this_handler)
{
return this_handler->start_ == 0 ? true
: asio_handler_cont_helpers::is_continuation(
this_handler->handler_);
}
template <typename AsyncReadStream>
class initiate_async_read_until_delim_v2
{
public:
typedef typename AsyncReadStream::executor_type executor_type;
explicit initiate_async_read_until_delim_v2(AsyncReadStream& stream)
: stream_(stream)
{
}
executor_type get_executor() const noexcept
{
return stream_.get_executor();
}
template <typename ReadHandler, typename DynamicBuffer_v2>
void operator()(ReadHandler&& handler,
DynamicBuffer_v2&& buffers, char delim) const
{
// If you get an error on the following line it means that your handler
// does not meet the documented type requirements for a ReadHandler.
ASIO_READ_HANDLER_CHECK(ReadHandler, handler) type_check;
non_const_lvalue<ReadHandler> handler2(handler);
read_until_delim_op_v2<AsyncReadStream,
decay_t<DynamicBuffer_v2>,
decay_t<ReadHandler>>(
stream_, static_cast<DynamicBuffer_v2&&>(buffers),
delim, handler2.value)(asio::error_code(), 0, 1);
}
private:
AsyncReadStream& stream_;
};
} // namespace detail
#if !defined(GENERATING_DOCUMENTATION)
template <template <typename, typename> class Associator,
typename AsyncReadStream, typename DynamicBuffer_v2,
typename ReadHandler, typename DefaultCandidate>
struct associator<Associator,
detail::read_until_delim_op_v2<AsyncReadStream,
DynamicBuffer_v2, ReadHandler>,
DefaultCandidate>
: Associator<ReadHandler, DefaultCandidate>
{
static typename Associator<ReadHandler, DefaultCandidate>::type get(
const detail::read_until_delim_op_v2<AsyncReadStream,
DynamicBuffer_v2, ReadHandler>& h) noexcept
{
return Associator<ReadHandler, DefaultCandidate>::get(h.handler_);
}
static auto get(
const detail::read_until_delim_op_v2<AsyncReadStream,
DynamicBuffer_v2, ReadHandler>& h,
const DefaultCandidate& c) noexcept
-> decltype(Associator<ReadHandler, DefaultCandidate>::get(h.handler_, c))
{
return Associator<ReadHandler, DefaultCandidate>::get(h.handler_, c);
}
};
#endif // !defined(GENERATING_DOCUMENTATION)
namespace detail
{
template <typename AsyncReadStream,
typename DynamicBuffer_v2, typename ReadHandler>
class read_until_delim_string_op_v2
: public base_from_cancellation_state<ReadHandler>
{
public:
template <typename BufferSequence>
read_until_delim_string_op_v2(AsyncReadStream& stream,
BufferSequence&& buffers,
const std::string& delim, ReadHandler& handler)
: base_from_cancellation_state<ReadHandler>(
handler, enable_partial_cancellation()),
stream_(stream),
buffers_(static_cast<BufferSequence&&>(buffers)),
delim_(delim),
start_(0),
search_position_(0),
bytes_to_read_(0),
handler_(static_cast<ReadHandler&&>(handler))
{
}
read_until_delim_string_op_v2(const read_until_delim_string_op_v2& other)
: base_from_cancellation_state<ReadHandler>(other),
stream_(other.stream_),
buffers_(other.buffers_),
delim_(other.delim_),
start_(other.start_),
search_position_(other.search_position_),
bytes_to_read_(other.bytes_to_read_),
handler_(other.handler_)
{
}
read_until_delim_string_op_v2(read_until_delim_string_op_v2&& other)
: base_from_cancellation_state<ReadHandler>(
static_cast<base_from_cancellation_state<ReadHandler>&&>(other)),
stream_(other.stream_),
buffers_(static_cast<DynamicBuffer_v2&&>(other.buffers_)),
delim_(static_cast<std::string&&>(other.delim_)),
start_(other.start_),
search_position_(other.search_position_),
bytes_to_read_(other.bytes_to_read_),
handler_(static_cast<ReadHandler&&>(other.handler_))
{
}
void operator()(asio::error_code ec,
std::size_t bytes_transferred, int start = 0)
{
const std::size_t not_found = (std::numeric_limits<std::size_t>::max)();
std::size_t pos;
switch (start_ = start)
{
case 1:
for (;;)
{
{
// Determine the range of the data to be searched.
typedef typename DynamicBuffer_v2::const_buffers_type
buffers_type;
typedef buffers_iterator<buffers_type> iterator;
buffers_type data_buffers =
const_cast<const DynamicBuffer_v2&>(buffers_).data(
0, buffers_.size());
iterator begin = iterator::begin(data_buffers);
iterator start_pos = begin + search_position_;
iterator end = iterator::end(data_buffers);
// Look for a match.
std::pair<iterator, bool> result = detail::partial_search(
start_pos, end, delim_.begin(), delim_.end());
if (result.first != end && result.second)
{
// Full match. We're done.
search_position_ = result.first - begin + delim_.length();
bytes_to_read_ = 0;
}
// No match yet. Check if buffer is full.
else if (buffers_.size() == buffers_.max_size())
{
search_position_ = not_found;
bytes_to_read_ = 0;
}
// Need to read some more data.
else
{
if (result.first != end)
{
// Partial match. Next search needs to start from beginning of
// match.
search_position_ = result.first - begin;
}
else
{
// Next search can start with the new data.
search_position_ = end - begin;
}
bytes_to_read_ = std::min<std::size_t>(
std::max<std::size_t>(512,
buffers_.capacity() - buffers_.size()),
std::min<std::size_t>(65536,
buffers_.max_size() - buffers_.size()));
}
}
// Check if we're done.
if (!start && bytes_to_read_ == 0)
break;
// Start a new asynchronous read operation to obtain more data.
pos = buffers_.size();
buffers_.grow(bytes_to_read_);
{
ASIO_HANDLER_LOCATION((
__FILE__, __LINE__, "async_read_until"));
stream_.async_read_some(buffers_.data(pos, bytes_to_read_),
static_cast<read_until_delim_string_op_v2&&>(*this));
}
return; default:
buffers_.shrink(bytes_to_read_ - bytes_transferred);
if (ec || bytes_transferred == 0)
break;
if (this->cancelled() != cancellation_type::none)
{
ec = error::operation_aborted;
break;
}
}
const asio::error_code result_ec =
(search_position_ == not_found)
? error::not_found : ec;
const std::size_t result_n =
(ec || search_position_ == not_found)
? 0 : search_position_;
static_cast<ReadHandler&&>(handler_)(result_ec, result_n);
}
}
//private:
AsyncReadStream& stream_;
DynamicBuffer_v2 buffers_;
std::string delim_;
int start_;
std::size_t search_position_;
std::size_t bytes_to_read_;
ReadHandler handler_;
};
template <typename AsyncReadStream,
typename DynamicBuffer_v2, typename ReadHandler>
inline bool asio_handler_is_continuation(
read_until_delim_string_op_v2<AsyncReadStream,
DynamicBuffer_v2, ReadHandler>* this_handler)
{
return this_handler->start_ == 0 ? true
: asio_handler_cont_helpers::is_continuation(
this_handler->handler_);
}
template <typename AsyncReadStream>
class initiate_async_read_until_delim_string_v2
{
public:
typedef typename AsyncReadStream::executor_type executor_type;
explicit initiate_async_read_until_delim_string_v2(AsyncReadStream& stream)
: stream_(stream)
{
}
executor_type get_executor() const noexcept
{
return stream_.get_executor();
}
template <typename ReadHandler, typename DynamicBuffer_v2>
void operator()(ReadHandler&& handler,
DynamicBuffer_v2&& buffers,
const std::string& delim) const
{
// If you get an error on the following line it means that your handler
// does not meet the documented type requirements for a ReadHandler.
ASIO_READ_HANDLER_CHECK(ReadHandler, handler) type_check;
non_const_lvalue<ReadHandler> handler2(handler);
read_until_delim_string_op_v2<AsyncReadStream,
decay_t<DynamicBuffer_v2>,
decay_t<ReadHandler>>(
stream_, static_cast<DynamicBuffer_v2&&>(buffers),
delim, handler2.value)(asio::error_code(), 0, 1);
}
private:
AsyncReadStream& stream_;
};
} // namespace detail
#if !defined(GENERATING_DOCUMENTATION)
template <template <typename, typename> class Associator,
typename AsyncReadStream, typename DynamicBuffer_v2,
typename ReadHandler, typename DefaultCandidate>
struct associator<Associator,
detail::read_until_delim_string_op_v2<AsyncReadStream,
DynamicBuffer_v2, ReadHandler>,
DefaultCandidate>
: Associator<ReadHandler, DefaultCandidate>
{
static typename Associator<ReadHandler, DefaultCandidate>::type get(
const detail::read_until_delim_string_op_v2<
AsyncReadStream, DynamicBuffer_v2, ReadHandler>& h) noexcept
{
return Associator<ReadHandler, DefaultCandidate>::get(h.handler_);
}
static auto get(
const detail::read_until_delim_string_op_v2<
AsyncReadStream, DynamicBuffer_v2, ReadHandler>& h,
const DefaultCandidate& c) noexcept
-> decltype(Associator<ReadHandler, DefaultCandidate>::get(h.handler_, c))
{
return Associator<ReadHandler, DefaultCandidate>::get(h.handler_, c);
}
};
#endif // !defined(GENERATING_DOCUMENTATION)
#if !defined(ASIO_NO_EXTENSIONS)
#if defined(ASIO_HAS_BOOST_REGEX)
namespace detail
{
template <typename AsyncReadStream, typename DynamicBuffer_v2,
typename RegEx, typename ReadHandler>
class read_until_expr_op_v2
: public base_from_cancellation_state<ReadHandler>
{
public:
template <typename BufferSequence, typename Traits>
read_until_expr_op_v2(AsyncReadStream& stream, BufferSequence&& buffers,
const boost::basic_regex<char, Traits>& expr, ReadHandler& handler)
: base_from_cancellation_state<ReadHandler>(
handler, enable_partial_cancellation()),
stream_(stream),
buffers_(static_cast<BufferSequence&&>(buffers)),
expr_(expr),
start_(0),
search_position_(0),
bytes_to_read_(0),
handler_(static_cast<ReadHandler&&>(handler))
{
}
read_until_expr_op_v2(const read_until_expr_op_v2& other)
: base_from_cancellation_state<ReadHandler>(other),
stream_(other.stream_),
buffers_(other.buffers_),
expr_(other.expr_),
start_(other.start_),
search_position_(other.search_position_),
bytes_to_read_(other.bytes_to_read_),
handler_(other.handler_)
{
}
read_until_expr_op_v2(read_until_expr_op_v2&& other)
: base_from_cancellation_state<ReadHandler>(
static_cast<base_from_cancellation_state<ReadHandler>&&>(other)),
stream_(other.stream_),
buffers_(static_cast<DynamicBuffer_v2&&>(other.buffers_)),
expr_(other.expr_),
start_(other.start_),
search_position_(other.search_position_),
bytes_to_read_(other.bytes_to_read_),
handler_(static_cast<ReadHandler&&>(other.handler_))
{
}
void operator()(asio::error_code ec,
std::size_t bytes_transferred, int start = 0)
{
const std::size_t not_found = (std::numeric_limits<std::size_t>::max)();
std::size_t pos;
switch (start_ = start)
{
case 1:
for (;;)
{
{
// Determine the range of the data to be searched.
typedef typename DynamicBuffer_v2::const_buffers_type
buffers_type;
typedef buffers_iterator<buffers_type> iterator;
buffers_type data_buffers =
const_cast<const DynamicBuffer_v2&>(buffers_).data(
0, buffers_.size());
iterator begin = iterator::begin(data_buffers);
iterator start_pos = begin + search_position_;
iterator end = iterator::end(data_buffers);
// Look for a match.
boost::match_results<iterator,
typename std::vector<boost::sub_match<iterator>>::allocator_type>
match_results;
bool match = regex_search(start_pos, end,
match_results, expr_, regex_match_flags());
if (match && match_results[0].matched)
{
// Full match. We're done.
search_position_ = match_results[0].second - begin;
bytes_to_read_ = 0;
}
// No match yet. Check if buffer is full.
else if (buffers_.size() == buffers_.max_size())
{
search_position_ = not_found;
bytes_to_read_ = 0;
}
// Need to read some more data.
else
{
if (match)
{
// Partial match. Next search needs to start from beginning of
// match.
search_position_ = match_results[0].first - begin;
}
else
{
// Next search can start with the new data.
search_position_ = end - begin;
}
bytes_to_read_ = std::min<std::size_t>(
std::max<std::size_t>(512,
buffers_.capacity() - buffers_.size()),
std::min<std::size_t>(65536,
buffers_.max_size() - buffers_.size()));
}
}
// Check if we're done.
if (!start && bytes_to_read_ == 0)
break;
// Start a new asynchronous read operation to obtain more data.
pos = buffers_.size();
buffers_.grow(bytes_to_read_);
{
ASIO_HANDLER_LOCATION((
__FILE__, __LINE__, "async_read_until"));
stream_.async_read_some(buffers_.data(pos, bytes_to_read_),
static_cast<read_until_expr_op_v2&&>(*this));
}
return; default:
buffers_.shrink(bytes_to_read_ - bytes_transferred);
if (ec || bytes_transferred == 0)
break;
if (this->cancelled() != cancellation_type::none)
{
ec = error::operation_aborted;
break;
}
}
const asio::error_code result_ec =
(search_position_ == not_found)
? error::not_found : ec;
const std::size_t result_n =
(ec || search_position_ == not_found)
? 0 : search_position_;
static_cast<ReadHandler&&>(handler_)(result_ec, result_n);
}
}
//private:
AsyncReadStream& stream_;
DynamicBuffer_v2 buffers_;
RegEx expr_;
int start_;
std::size_t search_position_;
std::size_t bytes_to_read_;
ReadHandler handler_;
};
template <typename AsyncReadStream, typename DynamicBuffer_v2,
typename RegEx, typename ReadHandler>
inline bool asio_handler_is_continuation(
read_until_expr_op_v2<AsyncReadStream,
DynamicBuffer_v2, RegEx, ReadHandler>* this_handler)
{
return this_handler->start_ == 0 ? true
: asio_handler_cont_helpers::is_continuation(
this_handler->handler_);
}
template <typename AsyncReadStream>
class initiate_async_read_until_expr_v2
{
public:
typedef typename AsyncReadStream::executor_type executor_type;
explicit initiate_async_read_until_expr_v2(AsyncReadStream& stream)
: stream_(stream)
{
}
executor_type get_executor() const noexcept
{
return stream_.get_executor();
}
template <typename ReadHandler, typename DynamicBuffer_v2, typename RegEx>
void operator()(ReadHandler&& handler,
DynamicBuffer_v2&& buffers,
const RegEx& expr) const
{
// If you get an error on the following line it means that your handler
// does not meet the documented type requirements for a ReadHandler.
ASIO_READ_HANDLER_CHECK(ReadHandler, handler) type_check;
non_const_lvalue<ReadHandler> handler2(handler);
read_until_expr_op_v2<AsyncReadStream,
decay_t<DynamicBuffer_v2>,
RegEx, decay_t<ReadHandler>>(
stream_, static_cast<DynamicBuffer_v2&&>(buffers),
expr, handler2.value)(asio::error_code(), 0, 1);
}
private:
AsyncReadStream& stream_;
};
} // namespace detail
#if !defined(GENERATING_DOCUMENTATION)
template <template <typename, typename> class Associator,
typename AsyncReadStream, typename DynamicBuffer_v2,
typename RegEx, typename ReadHandler, typename DefaultCandidate>
struct associator<Associator,
detail::read_until_expr_op_v2<AsyncReadStream,
DynamicBuffer_v2, RegEx, ReadHandler>,
DefaultCandidate>
: Associator<ReadHandler, DefaultCandidate>
{
static typename Associator<ReadHandler, DefaultCandidate>::type get(
const detail::read_until_expr_op_v2<AsyncReadStream,
DynamicBuffer_v2, RegEx, ReadHandler>& h) noexcept
{
return Associator<ReadHandler, DefaultCandidate>::get(h.handler_);
}
static auto get(
const detail::read_until_expr_op_v2<AsyncReadStream,
DynamicBuffer_v2, RegEx, ReadHandler>& h,
const DefaultCandidate& c) noexcept
-> decltype(Associator<ReadHandler, DefaultCandidate>::get(h.handler_, c))
{
return Associator<ReadHandler, DefaultCandidate>::get(h.handler_, c);
}
};
#endif // !defined(GENERATING_DOCUMENTATION)
#endif // defined(ASIO_HAS_BOOST_REGEX)
namespace detail
{
template <typename AsyncReadStream, typename DynamicBuffer_v2,
typename MatchCondition, typename ReadHandler>
class read_until_match_op_v2
: public base_from_cancellation_state<ReadHandler>
{
public:
template <typename BufferSequence>
read_until_match_op_v2(AsyncReadStream& stream,
BufferSequence&& buffers,
MatchCondition match_condition, ReadHandler& handler)
: base_from_cancellation_state<ReadHandler>(
handler, enable_partial_cancellation()),
stream_(stream),
buffers_(static_cast<BufferSequence&&>(buffers)),
match_condition_(match_condition),
start_(0),
search_position_(0),
bytes_to_read_(0),
handler_(static_cast<ReadHandler&&>(handler))
{
}
read_until_match_op_v2(const read_until_match_op_v2& other)
: base_from_cancellation_state<ReadHandler>(other),
stream_(other.stream_),
buffers_(other.buffers_),
match_condition_(other.match_condition_),
start_(other.start_),
search_position_(other.search_position_),
bytes_to_read_(other.bytes_to_read_),
handler_(other.handler_)
{
}
read_until_match_op_v2(read_until_match_op_v2&& other)
: base_from_cancellation_state<ReadHandler>(
static_cast<base_from_cancellation_state<ReadHandler>&&>(other)),
stream_(other.stream_),
buffers_(static_cast<DynamicBuffer_v2&&>(other.buffers_)),
match_condition_(other.match_condition_),
start_(other.start_),
search_position_(other.search_position_),
bytes_to_read_(other.bytes_to_read_),
handler_(static_cast<ReadHandler&&>(other.handler_))
{
}
void operator()(asio::error_code ec,
std::size_t bytes_transferred, int start = 0)
{
const std::size_t not_found = (std::numeric_limits<std::size_t>::max)();
std::size_t pos;
switch (start_ = start)
{
case 1:
for (;;)
{
{
// Determine the range of the data to be searched.
typedef typename DynamicBuffer_v2::const_buffers_type
buffers_type;
typedef buffers_iterator<buffers_type> iterator;
buffers_type data_buffers =
const_cast<const DynamicBuffer_v2&>(buffers_).data(
0, buffers_.size());
iterator begin = iterator::begin(data_buffers);
iterator start_pos = begin + search_position_;
iterator end = iterator::end(data_buffers);
// Look for a match.
std::pair<iterator, bool> result = match_condition_(start_pos, end);
if (result.second)
{
// Full match. We're done.
search_position_ = result.first - begin;
bytes_to_read_ = 0;
}
// No match yet. Check if buffer is full.
else if (buffers_.size() == buffers_.max_size())
{
search_position_ = not_found;
bytes_to_read_ = 0;
}
// Need to read some more data.
else
{
if (result.first != end)
{
// Partial match. Next search needs to start from beginning of
// match.
search_position_ = result.first - begin;
}
else
{
// Next search can start with the new data.
search_position_ = end - begin;
}
bytes_to_read_ = std::min<std::size_t>(
std::max<std::size_t>(512,
buffers_.capacity() - buffers_.size()),
std::min<std::size_t>(65536,
buffers_.max_size() - buffers_.size()));
}
}
// Check if we're done.
if (!start && bytes_to_read_ == 0)
break;
// Start a new asynchronous read operation to obtain more data.
pos = buffers_.size();
buffers_.grow(bytes_to_read_);
{
ASIO_HANDLER_LOCATION((
__FILE__, __LINE__, "async_read_until"));
stream_.async_read_some(buffers_.data(pos, bytes_to_read_),
static_cast<read_until_match_op_v2&&>(*this));
}
return; default:
buffers_.shrink(bytes_to_read_ - bytes_transferred);
if (ec || bytes_transferred == 0)
break;
if (this->cancelled() != cancellation_type::none)
{
ec = error::operation_aborted;
break;
}
}
const asio::error_code result_ec =
(search_position_ == not_found)
? error::not_found : ec;
const std::size_t result_n =
(ec || search_position_ == not_found)
? 0 : search_position_;
static_cast<ReadHandler&&>(handler_)(result_ec, result_n);
}
}
//private:
AsyncReadStream& stream_;
DynamicBuffer_v2 buffers_;
MatchCondition match_condition_;
int start_;
std::size_t search_position_;
std::size_t bytes_to_read_;
ReadHandler handler_;
};
template <typename AsyncReadStream, typename DynamicBuffer_v2,
typename MatchCondition, typename ReadHandler>
inline bool asio_handler_is_continuation(
read_until_match_op_v2<AsyncReadStream, DynamicBuffer_v2,
MatchCondition, ReadHandler>* this_handler)
{
return this_handler->start_ == 0 ? true
: asio_handler_cont_helpers::is_continuation(
this_handler->handler_);
}
template <typename AsyncReadStream>
class initiate_async_read_until_match_v2
{
public:
typedef typename AsyncReadStream::executor_type executor_type;
explicit initiate_async_read_until_match_v2(AsyncReadStream& stream)
: stream_(stream)
{
}
executor_type get_executor() const noexcept
{
return stream_.get_executor();
}
template <typename ReadHandler,
typename DynamicBuffer_v2, typename MatchCondition>
void operator()(ReadHandler&& handler,
DynamicBuffer_v2&& buffers,
MatchCondition match_condition) const
{
// If you get an error on the following line it means that your handler
// does not meet the documented type requirements for a ReadHandler.
ASIO_READ_HANDLER_CHECK(ReadHandler, handler) type_check;
non_const_lvalue<ReadHandler> handler2(handler);
read_until_match_op_v2<AsyncReadStream, decay_t<DynamicBuffer_v2>,
MatchCondition, decay_t<ReadHandler>>(
stream_, static_cast<DynamicBuffer_v2&&>(buffers),
match_condition, handler2.value)(asio::error_code(), 0, 1);
}
private:
AsyncReadStream& stream_;
};
} // namespace detail
#if !defined(GENERATING_DOCUMENTATION)
template <template <typename, typename> class Associator,
typename AsyncReadStream, typename DynamicBuffer_v2,
typename MatchCondition, typename ReadHandler, typename DefaultCandidate>
struct associator<Associator,
detail::read_until_match_op_v2<AsyncReadStream,
DynamicBuffer_v2, MatchCondition, ReadHandler>,
DefaultCandidate>
: Associator<ReadHandler, DefaultCandidate>
{
static typename Associator<ReadHandler, DefaultCandidate>::type get(
const detail::read_until_match_op_v2<AsyncReadStream,
DynamicBuffer_v2, MatchCondition, ReadHandler>& h) noexcept
{
return Associator<ReadHandler, DefaultCandidate>::get(h.handler_);
}
static auto get(
const detail::read_until_match_op_v2<AsyncReadStream,
DynamicBuffer_v2, MatchCondition, ReadHandler>& h,
const DefaultCandidate& c) noexcept
-> decltype(Associator<ReadHandler, DefaultCandidate>::get(h.handler_, c))
{
return Associator<ReadHandler, DefaultCandidate>::get(h.handler_, c);
}
};
#endif // !defined(GENERATING_DOCUMENTATION)
#endif // !defined(ASIO_NO_EXTENSIONS)
} // namespace asio
#include "asio/detail/pop_options.hpp"
#endif // ASIO_IMPL_READ_UNTIL_HPP
|
0 | repos/asio/asio/include/asio | repos/asio/asio/include/asio/impl/system_context.ipp | //
// impl/system_context.ipp
// ~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef ASIO_IMPL_SYSTEM_CONTEXT_IPP
#define ASIO_IMPL_SYSTEM_CONTEXT_IPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include "asio/detail/config.hpp"
#include "asio/system_context.hpp"
#include "asio/detail/push_options.hpp"
namespace asio {
struct system_context::thread_function
{
detail::scheduler* scheduler_;
void operator()()
{
#if !defined(ASIO_NO_EXCEPTIONS)
try
{
#endif// !defined(ASIO_NO_EXCEPTIONS)
asio::error_code ec;
scheduler_->run(ec);
#if !defined(ASIO_NO_EXCEPTIONS)
}
catch (...)
{
std::terminate();
}
#endif// !defined(ASIO_NO_EXCEPTIONS)
}
};
system_context::system_context()
: scheduler_(add_scheduler(new detail::scheduler(*this, 0, false)))
{
scheduler_.work_started();
thread_function f = { &scheduler_ };
num_threads_ = detail::thread::hardware_concurrency() * 2;
num_threads_ = num_threads_ ? num_threads_ : 2;
threads_.create_threads(f, num_threads_);
}
system_context::~system_context()
{
scheduler_.work_finished();
scheduler_.stop();
threads_.join();
}
void system_context::stop()
{
scheduler_.stop();
}
bool system_context::stopped() const noexcept
{
return scheduler_.stopped();
}
void system_context::join()
{
scheduler_.work_finished();
threads_.join();
}
detail::scheduler& system_context::add_scheduler(detail::scheduler* s)
{
detail::scoped_ptr<detail::scheduler> scoped_impl(s);
asio::add_service<detail::scheduler>(*this, scoped_impl.get());
return *scoped_impl.release();
}
} // namespace asio
#include "asio/detail/pop_options.hpp"
#endif // ASIO_IMPL_SYSTEM_CONTEXT_IPP
|
0 | repos/asio/asio/include/asio | repos/asio/asio/include/asio/impl/deferred.hpp | //
// impl/deferred.hpp
// ~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef ASIO_IMPL_DEFERRED_HPP
#define ASIO_IMPL_DEFERRED_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include "asio/detail/push_options.hpp"
namespace asio {
#if !defined(GENERATING_DOCUMENTATION)
template <typename Signature>
class async_result<deferred_t, Signature>
{
public:
template <typename Initiation, typename... InitArgs>
static deferred_async_operation<Signature, Initiation, InitArgs...>
initiate(Initiation&& initiation, deferred_t, InitArgs&&... args)
{
return deferred_async_operation<Signature, Initiation, InitArgs...>(
deferred_init_tag{},
static_cast<Initiation&&>(initiation),
static_cast<InitArgs&&>(args)...);
}
};
template <typename... Signatures>
class async_result<deferred_t, Signatures...>
{
public:
template <typename Initiation, typename... InitArgs>
static deferred_async_operation<
deferred_signatures<Signatures...>, Initiation, InitArgs...>
initiate(Initiation&& initiation, deferred_t, InitArgs&&... args)
{
return deferred_async_operation<
deferred_signatures<Signatures...>, Initiation, InitArgs...>(
deferred_init_tag{},
static_cast<Initiation&&>(initiation),
static_cast<InitArgs&&>(args)...);
}
};
template <typename Function, typename Signature>
class async_result<deferred_function<Function>, Signature>
{
public:
template <typename Initiation, typename... InitArgs>
static auto initiate(Initiation&& initiation,
deferred_function<Function> token, InitArgs&&... init_args)
-> decltype(
deferred_sequence<
deferred_async_operation<
Signature, Initiation, InitArgs...>,
Function>(deferred_init_tag{},
deferred_async_operation<
Signature, Initiation, InitArgs...>(
deferred_init_tag{},
static_cast<Initiation&&>(initiation),
static_cast<InitArgs&&>(init_args)...),
static_cast<Function&&>(token.function_)))
{
return deferred_sequence<
deferred_async_operation<
Signature, Initiation, InitArgs...>,
Function>(deferred_init_tag{},
deferred_async_operation<
Signature, Initiation, InitArgs...>(
deferred_init_tag{},
static_cast<Initiation&&>(initiation),
static_cast<InitArgs&&>(init_args)...),
static_cast<Function&&>(token.function_));
}
};
template <typename Function, typename... Signatures>
class async_result<deferred_function<Function>, Signatures...>
{
public:
template <typename Initiation, typename... InitArgs>
static auto initiate(Initiation&& initiation,
deferred_function<Function> token, InitArgs&&... init_args)
-> decltype(
deferred_sequence<
deferred_async_operation<
deferred_signatures<Signatures...>, Initiation, InitArgs...>,
Function>(deferred_init_tag{},
deferred_async_operation<
deferred_signatures<Signatures...>, Initiation, InitArgs...>(
deferred_init_tag{},
static_cast<Initiation&&>(initiation),
static_cast<InitArgs&&>(init_args)...),
static_cast<Function&&>(token.function_)))
{
return deferred_sequence<
deferred_async_operation<
deferred_signatures<Signatures...>, Initiation, InitArgs...>,
Function>(deferred_init_tag{},
deferred_async_operation<
deferred_signatures<Signatures...>, Initiation, InitArgs...>(
deferred_init_tag{},
static_cast<Initiation&&>(initiation),
static_cast<InitArgs&&>(init_args)...),
static_cast<Function&&>(token.function_));
}
};
template <template <typename, typename> class Associator,
typename Handler, typename Tail, typename DefaultCandidate>
struct associator<Associator,
detail::deferred_sequence_handler<Handler, Tail>,
DefaultCandidate>
: Associator<Handler, DefaultCandidate>
{
static typename Associator<Handler, DefaultCandidate>::type get(
const detail::deferred_sequence_handler<Handler, Tail>& h) noexcept
{
return Associator<Handler, DefaultCandidate>::get(h.handler_);
}
static auto get(const detail::deferred_sequence_handler<Handler, Tail>& 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)
} // namespace asio
#include "asio/detail/pop_options.hpp"
#endif // ASIO_IMPL_DEFERRED_HPP
|
0 | repos/asio/asio/include/asio | repos/asio/asio/include/asio/impl/awaitable.hpp | //
// impl/awaitable.hpp
// ~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef ASIO_IMPL_AWAITABLE_HPP
#define ASIO_IMPL_AWAITABLE_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include "asio/detail/config.hpp"
#include <exception>
#include <new>
#include <tuple>
#include "asio/cancellation_signal.hpp"
#include "asio/cancellation_state.hpp"
#include "asio/detail/thread_context.hpp"
#include "asio/detail/thread_info_base.hpp"
#include "asio/detail/throw_error.hpp"
#include "asio/detail/type_traits.hpp"
#include "asio/error.hpp"
#include "asio/post.hpp"
#include "asio/system_error.hpp"
#include "asio/this_coro.hpp"
#if defined(ASIO_ENABLE_HANDLER_TRACKING)
# if defined(ASIO_HAS_SOURCE_LOCATION)
# include "asio/detail/source_location.hpp"
# endif // defined(ASIO_HAS_SOURCE_LOCATION)
#endif // defined(ASIO_ENABLE_HANDLER_TRACKING)
#include "asio/detail/push_options.hpp"
namespace asio {
namespace detail {
struct awaitable_thread_has_context_switched {};
template <typename, typename> class awaitable_async_op_handler;
template <typename, typename, typename> class awaitable_async_op;
// An awaitable_thread represents a thread-of-execution that is composed of one
// or more "stack frames", with each frame represented by an awaitable_frame.
// All execution occurs in the context of the awaitable_thread's executor. An
// awaitable_thread continues to "pump" the stack frames by repeatedly resuming
// the top stack frame until the stack is empty, or until ownership of the
// stack is transferred to another awaitable_thread object.
//
// +------------------------------------+
// | top_of_stack_ |
// | V
// +--------------+---+ +-----------------+
// | | | |
// | awaitable_thread |<---------------------------+ awaitable_frame |
// | | attached_thread_ | |
// +--------------+---+ (Set only when +---+-------------+
// | frames are being |
// | actively pumped | caller_
// | by a thread, and |
// | then only for V
// | the top frame.) +-----------------+
// | | |
// | | awaitable_frame |
// | | |
// | +---+-------------+
// | |
// | | caller_
// | :
// | :
// | |
// | V
// | +-----------------+
// | bottom_of_stack_ | |
// +------------------------------->| awaitable_frame |
// | |
// +-----------------+
template <typename Executor>
class awaitable_frame_base
{
public:
#if !defined(ASIO_DISABLE_AWAITABLE_FRAME_RECYCLING)
void* operator new(std::size_t size)
{
return asio::detail::thread_info_base::allocate(
asio::detail::thread_info_base::awaitable_frame_tag(),
asio::detail::thread_context::top_of_thread_call_stack(),
size);
}
void operator delete(void* pointer, std::size_t size)
{
asio::detail::thread_info_base::deallocate(
asio::detail::thread_info_base::awaitable_frame_tag(),
asio::detail::thread_context::top_of_thread_call_stack(),
pointer, size);
}
#endif // !defined(ASIO_DISABLE_AWAITABLE_FRAME_RECYCLING)
// The frame starts in a suspended state until the awaitable_thread object
// pumps the stack.
auto initial_suspend() noexcept
{
return suspend_always();
}
// On final suspension the frame is popped from the top of the stack.
auto final_suspend() noexcept
{
struct result
{
awaitable_frame_base* this_;
bool await_ready() const noexcept
{
return false;
}
void await_suspend(coroutine_handle<void>) noexcept
{
this->this_->pop_frame();
}
void await_resume() const noexcept
{
}
};
return result{this};
}
void set_except(std::exception_ptr e) noexcept
{
pending_exception_ = e;
}
void set_error(const asio::error_code& ec)
{
this->set_except(std::make_exception_ptr(asio::system_error(ec)));
}
void unhandled_exception()
{
set_except(std::current_exception());
}
void rethrow_exception()
{
if (pending_exception_)
{
std::exception_ptr ex = std::exchange(pending_exception_, nullptr);
std::rethrow_exception(ex);
}
}
void clear_cancellation_slot()
{
this->attached_thread_->entry_point()->cancellation_state_.slot().clear();
}
template <typename T>
auto await_transform(awaitable<T, Executor> a) const
{
if (attached_thread_->entry_point()->throw_if_cancelled_)
if (!!attached_thread_->get_cancellation_state().cancelled())
throw_error(asio::error::operation_aborted, "co_await");
return a;
}
template <typename Op>
auto await_transform(Op&& op,
constraint_t<is_async_operation<Op>::value> = 0
#if defined(ASIO_ENABLE_HANDLER_TRACKING)
# if defined(ASIO_HAS_SOURCE_LOCATION)
, detail::source_location location = detail::source_location::current()
# endif // defined(ASIO_HAS_SOURCE_LOCATION)
#endif // defined(ASIO_ENABLE_HANDLER_TRACKING)
)
{
if (attached_thread_->entry_point()->throw_if_cancelled_)
if (!!attached_thread_->get_cancellation_state().cancelled())
throw_error(asio::error::operation_aborted, "co_await");
return awaitable_async_op<
completion_signature_of_t<Op>, decay_t<Op>, Executor>{
std::forward<Op>(op), this
#if defined(ASIO_ENABLE_HANDLER_TRACKING)
# if defined(ASIO_HAS_SOURCE_LOCATION)
, location
# endif // defined(ASIO_HAS_SOURCE_LOCATION)
#endif // defined(ASIO_ENABLE_HANDLER_TRACKING)
};
}
// This await transformation obtains the associated executor of the thread of
// execution.
auto await_transform(this_coro::executor_t) noexcept
{
struct result
{
awaitable_frame_base* this_;
bool await_ready() const noexcept
{
return true;
}
void await_suspend(coroutine_handle<void>) noexcept
{
}
auto await_resume() const noexcept
{
return this_->attached_thread_->get_executor();
}
};
return result{this};
}
// This await transformation obtains the associated cancellation state of the
// thread of execution.
auto await_transform(this_coro::cancellation_state_t) noexcept
{
struct result
{
awaitable_frame_base* this_;
bool await_ready() const noexcept
{
return true;
}
void await_suspend(coroutine_handle<void>) noexcept
{
}
auto await_resume() const noexcept
{
return this_->attached_thread_->get_cancellation_state();
}
};
return result{this};
}
// This await transformation resets the associated cancellation state.
auto await_transform(this_coro::reset_cancellation_state_0_t) noexcept
{
struct result
{
awaitable_frame_base* this_;
bool await_ready() const noexcept
{
return true;
}
void await_suspend(coroutine_handle<void>) noexcept
{
}
auto await_resume() const
{
return this_->attached_thread_->reset_cancellation_state();
}
};
return result{this};
}
// This await transformation resets the associated cancellation state.
template <typename Filter>
auto await_transform(
this_coro::reset_cancellation_state_1_t<Filter> reset) noexcept
{
struct result
{
awaitable_frame_base* this_;
Filter filter_;
bool await_ready() const noexcept
{
return true;
}
void await_suspend(coroutine_handle<void>) noexcept
{
}
auto await_resume()
{
return this_->attached_thread_->reset_cancellation_state(
static_cast<Filter&&>(filter_));
}
};
return result{this, static_cast<Filter&&>(reset.filter)};
}
// This await transformation resets the associated cancellation state.
template <typename InFilter, typename OutFilter>
auto await_transform(
this_coro::reset_cancellation_state_2_t<InFilter, OutFilter> reset)
noexcept
{
struct result
{
awaitable_frame_base* this_;
InFilter in_filter_;
OutFilter out_filter_;
bool await_ready() const noexcept
{
return true;
}
void await_suspend(coroutine_handle<void>) noexcept
{
}
auto await_resume()
{
return this_->attached_thread_->reset_cancellation_state(
static_cast<InFilter&&>(in_filter_),
static_cast<OutFilter&&>(out_filter_));
}
};
return result{this,
static_cast<InFilter&&>(reset.in_filter),
static_cast<OutFilter&&>(reset.out_filter)};
}
// This await transformation determines whether cancellation is propagated as
// an exception.
auto await_transform(this_coro::throw_if_cancelled_0_t)
noexcept
{
struct result
{
awaitable_frame_base* this_;
bool await_ready() const noexcept
{
return true;
}
void await_suspend(coroutine_handle<void>) noexcept
{
}
auto await_resume()
{
return this_->attached_thread_->throw_if_cancelled();
}
};
return result{this};
}
// This await transformation sets whether cancellation is propagated as an
// exception.
auto await_transform(this_coro::throw_if_cancelled_1_t throw_if_cancelled)
noexcept
{
struct result
{
awaitable_frame_base* this_;
bool value_;
bool await_ready() const noexcept
{
return true;
}
void await_suspend(coroutine_handle<void>) noexcept
{
}
auto await_resume()
{
this_->attached_thread_->throw_if_cancelled(value_);
}
};
return result{this, throw_if_cancelled.value};
}
// This await transformation is used to run an async operation's initiation
// function object after the coroutine has been suspended. This ensures that
// immediate resumption of the coroutine in another thread does not cause a
// race condition.
template <typename Function>
auto await_transform(Function f,
enable_if_t<
is_convertible<
result_of_t<Function(awaitable_frame_base*)>,
awaitable_thread<Executor>*
>::value
>* = nullptr)
{
struct result
{
Function function_;
awaitable_frame_base* this_;
bool await_ready() const noexcept
{
return false;
}
void await_suspend(coroutine_handle<void>) noexcept
{
this_->after_suspend(
[](void* arg)
{
result* r = static_cast<result*>(arg);
r->function_(r->this_);
}, this);
}
void await_resume() const noexcept
{
}
};
return result{std::move(f), this};
}
// Access the awaitable thread's has_context_switched_ flag.
auto await_transform(detail::awaitable_thread_has_context_switched) noexcept
{
struct result
{
awaitable_frame_base* this_;
bool await_ready() const noexcept
{
return true;
}
void await_suspend(coroutine_handle<void>) noexcept
{
}
bool& await_resume() const noexcept
{
return this_->attached_thread_->entry_point()->has_context_switched_;
}
};
return result{this};
}
void attach_thread(awaitable_thread<Executor>* handler) noexcept
{
attached_thread_ = handler;
}
awaitable_thread<Executor>* detach_thread() noexcept
{
attached_thread_->entry_point()->has_context_switched_ = true;
return std::exchange(attached_thread_, nullptr);
}
void push_frame(awaitable_frame_base<Executor>* caller) noexcept
{
caller_ = caller;
attached_thread_ = caller_->attached_thread_;
attached_thread_->entry_point()->top_of_stack_ = this;
caller_->attached_thread_ = nullptr;
}
void pop_frame() noexcept
{
if (caller_)
caller_->attached_thread_ = attached_thread_;
attached_thread_->entry_point()->top_of_stack_ = caller_;
attached_thread_ = nullptr;
caller_ = nullptr;
}
struct resume_context
{
void (*after_suspend_fn_)(void*) = nullptr;
void *after_suspend_arg_ = nullptr;
};
void resume()
{
resume_context context;
resume_context_ = &context;
coro_.resume();
if (context.after_suspend_fn_)
context.after_suspend_fn_(context.after_suspend_arg_);
}
void after_suspend(void (*fn)(void*), void* arg)
{
resume_context_->after_suspend_fn_ = fn;
resume_context_->after_suspend_arg_ = arg;
}
void destroy()
{
coro_.destroy();
}
protected:
coroutine_handle<void> coro_ = nullptr;
awaitable_thread<Executor>* attached_thread_ = nullptr;
awaitable_frame_base<Executor>* caller_ = nullptr;
std::exception_ptr pending_exception_ = nullptr;
resume_context* resume_context_ = nullptr;
};
template <typename T, typename Executor>
class awaitable_frame
: public awaitable_frame_base<Executor>
{
public:
awaitable_frame() noexcept
{
}
awaitable_frame(awaitable_frame&& other) noexcept
: awaitable_frame_base<Executor>(std::move(other))
{
}
~awaitable_frame()
{
if (has_result_)
std::launder(static_cast<T*>(static_cast<void*>(result_)))->~T();
}
awaitable<T, Executor> get_return_object() noexcept
{
this->coro_ = coroutine_handle<awaitable_frame>::from_promise(*this);
return awaitable<T, Executor>(this);
}
template <typename U>
void return_value(U&& u)
{
new (&result_) T(std::forward<U>(u));
has_result_ = true;
}
template <typename... Us>
void return_values(Us&&... us)
{
this->return_value(std::forward_as_tuple(std::forward<Us>(us)...));
}
T get()
{
this->caller_ = nullptr;
this->rethrow_exception();
return std::move(*std::launder(
static_cast<T*>(static_cast<void*>(result_))));
}
private:
alignas(T) unsigned char result_[sizeof(T)];
bool has_result_ = false;
};
template <typename Executor>
class awaitable_frame<void, Executor>
: public awaitable_frame_base<Executor>
{
public:
awaitable<void, Executor> get_return_object()
{
this->coro_ = coroutine_handle<awaitable_frame>::from_promise(*this);
return awaitable<void, Executor>(this);
}
void return_void()
{
}
void get()
{
this->caller_ = nullptr;
this->rethrow_exception();
}
};
struct awaitable_thread_entry_point {};
template <typename Executor>
class awaitable_frame<awaitable_thread_entry_point, Executor>
: public awaitable_frame_base<Executor>
{
public:
awaitable_frame()
: top_of_stack_(0),
has_executor_(false),
has_context_switched_(false),
throw_if_cancelled_(true)
{
}
~awaitable_frame()
{
if (has_executor_)
u_.executor_.~Executor();
}
awaitable<awaitable_thread_entry_point, Executor> get_return_object()
{
this->coro_ = coroutine_handle<awaitable_frame>::from_promise(*this);
return awaitable<awaitable_thread_entry_point, Executor>(this);
}
void return_void()
{
}
void get()
{
this->caller_ = nullptr;
this->rethrow_exception();
}
private:
template <typename> friend class awaitable_frame_base;
template <typename, typename> friend class awaitable_async_op_handler;
template <typename, typename> friend class awaitable_handler_base;
template <typename> friend class awaitable_thread;
union u
{
u() {}
~u() {}
char c_;
Executor executor_;
} u_;
awaitable_frame_base<Executor>* top_of_stack_;
asio::cancellation_slot parent_cancellation_slot_;
asio::cancellation_state cancellation_state_;
bool has_executor_;
bool has_context_switched_;
bool throw_if_cancelled_;
};
template <typename Executor>
class awaitable_thread
{
public:
typedef Executor executor_type;
typedef cancellation_slot cancellation_slot_type;
// Construct from the entry point of a new thread of execution.
awaitable_thread(awaitable<awaitable_thread_entry_point, Executor> p,
const Executor& ex, cancellation_slot parent_cancel_slot,
cancellation_state cancel_state)
: bottom_of_stack_(std::move(p))
{
bottom_of_stack_.frame_->top_of_stack_ = bottom_of_stack_.frame_;
new (&bottom_of_stack_.frame_->u_.executor_) Executor(ex);
bottom_of_stack_.frame_->has_executor_ = true;
bottom_of_stack_.frame_->parent_cancellation_slot_ = parent_cancel_slot;
bottom_of_stack_.frame_->cancellation_state_ = cancel_state;
}
// Transfer ownership from another awaitable_thread.
awaitable_thread(awaitable_thread&& other) noexcept
: bottom_of_stack_(std::move(other.bottom_of_stack_))
{
}
// Clean up with a last ditch effort to ensure the thread is unwound within
// the context of the executor.
~awaitable_thread()
{
if (bottom_of_stack_.valid())
{
// Coroutine "stack unwinding" must be performed through the executor.
auto* bottom_frame = bottom_of_stack_.frame_;
(post)(bottom_frame->u_.executor_,
[a = std::move(bottom_of_stack_)]() mutable
{
(void)awaitable<awaitable_thread_entry_point, Executor>(
std::move(a));
});
}
}
awaitable_frame<awaitable_thread_entry_point, Executor>* entry_point()
{
return bottom_of_stack_.frame_;
}
executor_type get_executor() const noexcept
{
return bottom_of_stack_.frame_->u_.executor_;
}
cancellation_state get_cancellation_state() const noexcept
{
return bottom_of_stack_.frame_->cancellation_state_;
}
void reset_cancellation_state()
{
bottom_of_stack_.frame_->cancellation_state_ =
cancellation_state(bottom_of_stack_.frame_->parent_cancellation_slot_);
}
template <typename Filter>
void reset_cancellation_state(Filter&& filter)
{
bottom_of_stack_.frame_->cancellation_state_ =
cancellation_state(bottom_of_stack_.frame_->parent_cancellation_slot_,
static_cast<Filter&&>(filter));
}
template <typename InFilter, typename OutFilter>
void reset_cancellation_state(InFilter&& in_filter,
OutFilter&& out_filter)
{
bottom_of_stack_.frame_->cancellation_state_ =
cancellation_state(bottom_of_stack_.frame_->parent_cancellation_slot_,
static_cast<InFilter&&>(in_filter),
static_cast<OutFilter&&>(out_filter));
}
bool throw_if_cancelled() const
{
return bottom_of_stack_.frame_->throw_if_cancelled_;
}
void throw_if_cancelled(bool value)
{
bottom_of_stack_.frame_->throw_if_cancelled_ = value;
}
cancellation_slot_type get_cancellation_slot() const noexcept
{
return bottom_of_stack_.frame_->cancellation_state_.slot();
}
// Launch a new thread of execution.
void launch()
{
bottom_of_stack_.frame_->top_of_stack_->attach_thread(this);
pump();
}
protected:
template <typename> friend class awaitable_frame_base;
// Repeatedly resume the top stack frame until the stack is empty or until it
// has been transferred to another resumable_thread object.
void pump()
{
do
bottom_of_stack_.frame_->top_of_stack_->resume();
while (bottom_of_stack_.frame_ && bottom_of_stack_.frame_->top_of_stack_);
if (bottom_of_stack_.frame_)
{
awaitable<awaitable_thread_entry_point, Executor> a(
std::move(bottom_of_stack_));
a.frame_->rethrow_exception();
}
}
awaitable<awaitable_thread_entry_point, Executor> bottom_of_stack_;
};
template <typename Signature, typename Executor>
class awaitable_async_op_handler;
template <typename R, typename Executor>
class awaitable_async_op_handler<R(), Executor>
: public awaitable_thread<Executor>
{
public:
struct result_type {};
awaitable_async_op_handler(
awaitable_thread<Executor>* h, result_type&)
: awaitable_thread<Executor>(std::move(*h))
{
}
void operator()()
{
this->entry_point()->top_of_stack_->attach_thread(this);
this->entry_point()->top_of_stack_->clear_cancellation_slot();
this->pump();
}
static void resume(result_type&)
{
}
};
template <typename R, typename Executor>
class awaitable_async_op_handler<R(asio::error_code), Executor>
: public awaitable_thread<Executor>
{
public:
typedef asio::error_code* result_type;
awaitable_async_op_handler(
awaitable_thread<Executor>* h, result_type& result)
: awaitable_thread<Executor>(std::move(*h)),
result_(result)
{
}
void operator()(asio::error_code ec)
{
result_ = &ec;
this->entry_point()->top_of_stack_->attach_thread(this);
this->entry_point()->top_of_stack_->clear_cancellation_slot();
this->pump();
}
static void resume(result_type& result)
{
throw_error(*result);
}
private:
result_type& result_;
};
template <typename R, typename Executor>
class awaitable_async_op_handler<R(std::exception_ptr), Executor>
: public awaitable_thread<Executor>
{
public:
typedef std::exception_ptr* result_type;
awaitable_async_op_handler(
awaitable_thread<Executor>* h, result_type& result)
: awaitable_thread<Executor>(std::move(*h)),
result_(result)
{
}
void operator()(std::exception_ptr ex)
{
result_ = &ex;
this->entry_point()->top_of_stack_->attach_thread(this);
this->entry_point()->top_of_stack_->clear_cancellation_slot();
this->pump();
}
static void resume(result_type& result)
{
if (*result)
{
std::exception_ptr ex = std::exchange(*result, nullptr);
std::rethrow_exception(ex);
}
}
private:
result_type& result_;
};
template <typename R, typename T, typename Executor>
class awaitable_async_op_handler<R(T), Executor>
: public awaitable_thread<Executor>
{
public:
typedef T* result_type;
awaitable_async_op_handler(
awaitable_thread<Executor>* h, result_type& result)
: awaitable_thread<Executor>(std::move(*h)),
result_(result)
{
}
void operator()(T result)
{
result_ = &result;
this->entry_point()->top_of_stack_->attach_thread(this);
this->entry_point()->top_of_stack_->clear_cancellation_slot();
this->pump();
}
static T resume(result_type& result)
{
return std::move(*result);
}
private:
result_type& result_;
};
template <typename R, typename T, typename Executor>
class awaitable_async_op_handler<R(asio::error_code, T), Executor>
: public awaitable_thread<Executor>
{
public:
struct result_type
{
asio::error_code* ec_;
T* value_;
};
awaitable_async_op_handler(
awaitable_thread<Executor>* h, result_type& result)
: awaitable_thread<Executor>(std::move(*h)),
result_(result)
{
}
void operator()(asio::error_code ec, T value)
{
result_.ec_ = &ec;
result_.value_ = &value;
this->entry_point()->top_of_stack_->attach_thread(this);
this->entry_point()->top_of_stack_->clear_cancellation_slot();
this->pump();
}
static T resume(result_type& result)
{
throw_error(*result.ec_);
return std::move(*result.value_);
}
private:
result_type& result_;
};
template <typename R, typename T, typename Executor>
class awaitable_async_op_handler<R(std::exception_ptr, T), Executor>
: public awaitable_thread<Executor>
{
public:
struct result_type
{
std::exception_ptr* ex_;
T* value_;
};
awaitable_async_op_handler(
awaitable_thread<Executor>* h, result_type& result)
: awaitable_thread<Executor>(std::move(*h)),
result_(result)
{
}
void operator()(std::exception_ptr ex, T value)
{
result_.ex_ = &ex;
result_.value_ = &value;
this->entry_point()->top_of_stack_->attach_thread(this);
this->entry_point()->top_of_stack_->clear_cancellation_slot();
this->pump();
}
static T resume(result_type& result)
{
if (*result.ex_)
{
std::exception_ptr ex = std::exchange(*result.ex_, nullptr);
std::rethrow_exception(ex);
}
return std::move(*result.value_);
}
private:
result_type& result_;
};
template <typename R, typename... Ts, typename Executor>
class awaitable_async_op_handler<R(Ts...), Executor>
: public awaitable_thread<Executor>
{
public:
typedef std::tuple<Ts...>* result_type;
awaitable_async_op_handler(
awaitable_thread<Executor>* h, result_type& result)
: awaitable_thread<Executor>(std::move(*h)),
result_(result)
{
}
template <typename... Args>
void operator()(Args&&... args)
{
std::tuple<Ts...> result(std::forward<Args>(args)...);
result_ = &result;
this->entry_point()->top_of_stack_->attach_thread(this);
this->entry_point()->top_of_stack_->clear_cancellation_slot();
this->pump();
}
static std::tuple<Ts...> resume(result_type& result)
{
return std::move(*result);
}
private:
result_type& result_;
};
template <typename R, typename... Ts, typename Executor>
class awaitable_async_op_handler<R(asio::error_code, Ts...), Executor>
: public awaitable_thread<Executor>
{
public:
struct result_type
{
asio::error_code* ec_;
std::tuple<Ts...>* value_;
};
awaitable_async_op_handler(
awaitable_thread<Executor>* h, result_type& result)
: awaitable_thread<Executor>(std::move(*h)),
result_(result)
{
}
template <typename... Args>
void operator()(asio::error_code ec, Args&&... args)
{
result_.ec_ = &ec;
std::tuple<Ts...> value(std::forward<Args>(args)...);
result_.value_ = &value;
this->entry_point()->top_of_stack_->attach_thread(this);
this->entry_point()->top_of_stack_->clear_cancellation_slot();
this->pump();
}
static std::tuple<Ts...> resume(result_type& result)
{
throw_error(*result.ec_);
return std::move(*result.value_);
}
private:
result_type& result_;
};
template <typename R, typename... Ts, typename Executor>
class awaitable_async_op_handler<R(std::exception_ptr, Ts...), Executor>
: public awaitable_thread<Executor>
{
public:
struct result_type
{
std::exception_ptr* ex_;
std::tuple<Ts...>* value_;
};
awaitable_async_op_handler(
awaitable_thread<Executor>* h, result_type& result)
: awaitable_thread<Executor>(std::move(*h)),
result_(result)
{
}
template <typename... Args>
void operator()(std::exception_ptr ex, Args&&... args)
{
result_.ex_ = &ex;
std::tuple<Ts...> value(std::forward<Args>(args)...);
result_.value_ = &value;
this->entry_point()->top_of_stack_->attach_thread(this);
this->entry_point()->top_of_stack_->clear_cancellation_slot();
this->pump();
}
static std::tuple<Ts...> resume(result_type& result)
{
if (*result.ex_)
{
std::exception_ptr ex = std::exchange(*result.ex_, nullptr);
std::rethrow_exception(ex);
}
return std::move(*result.value_);
}
private:
result_type& result_;
};
template <typename Signature, typename Op, typename Executor>
class awaitable_async_op
{
public:
typedef awaitable_async_op_handler<Signature, Executor> handler_type;
awaitable_async_op(Op&& o, awaitable_frame_base<Executor>* frame
#if defined(ASIO_ENABLE_HANDLER_TRACKING)
# if defined(ASIO_HAS_SOURCE_LOCATION)
, const detail::source_location& location
# endif // defined(ASIO_HAS_SOURCE_LOCATION)
#endif // defined(ASIO_ENABLE_HANDLER_TRACKING)
)
: op_(std::forward<Op>(o)),
frame_(frame),
result_()
#if defined(ASIO_ENABLE_HANDLER_TRACKING)
# if defined(ASIO_HAS_SOURCE_LOCATION)
, location_(location)
# endif // defined(ASIO_HAS_SOURCE_LOCATION)
#endif // defined(ASIO_ENABLE_HANDLER_TRACKING)
{
}
bool await_ready() const noexcept
{
return false;
}
void await_suspend(coroutine_handle<void>)
{
frame_->after_suspend(
[](void* arg)
{
awaitable_async_op* self = static_cast<awaitable_async_op*>(arg);
#if defined(ASIO_ENABLE_HANDLER_TRACKING)
# if defined(ASIO_HAS_SOURCE_LOCATION)
ASIO_HANDLER_LOCATION((self->location_.file_name(),
self->location_.line(), self->location_.function_name()));
# endif // defined(ASIO_HAS_SOURCE_LOCATION)
#endif // defined(ASIO_ENABLE_HANDLER_TRACKING)
std::forward<Op&&>(self->op_)(
handler_type(self->frame_->detach_thread(), self->result_));
}, this);
}
auto await_resume()
{
return handler_type::resume(result_);
}
private:
Op&& op_;
awaitable_frame_base<Executor>* frame_;
typename handler_type::result_type result_;
#if defined(ASIO_ENABLE_HANDLER_TRACKING)
# if defined(ASIO_HAS_SOURCE_LOCATION)
detail::source_location location_;
# endif // defined(ASIO_HAS_SOURCE_LOCATION)
#endif // defined(ASIO_ENABLE_HANDLER_TRACKING)
};
} // namespace detail
} // namespace asio
#if !defined(GENERATING_DOCUMENTATION)
# if defined(ASIO_HAS_STD_COROUTINE)
namespace std {
template <typename T, typename Executor, typename... Args>
struct coroutine_traits<asio::awaitable<T, Executor>, Args...>
{
typedef asio::detail::awaitable_frame<T, Executor> promise_type;
};
} // namespace std
# else // defined(ASIO_HAS_STD_COROUTINE)
namespace std { namespace experimental {
template <typename T, typename Executor, typename... Args>
struct coroutine_traits<asio::awaitable<T, Executor>, Args...>
{
typedef asio::detail::awaitable_frame<T, Executor> promise_type;
};
}} // namespace std::experimental
# endif // defined(ASIO_HAS_STD_COROUTINE)
#endif // !defined(GENERATING_DOCUMENTATION)
#include "asio/detail/pop_options.hpp"
#endif // ASIO_IMPL_AWAITABLE_HPP
|
0 | repos/asio/asio/include/asio | repos/asio/asio/include/asio/impl/redirect_error.hpp |
// impl/redirect_error.hpp
// ~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef ASIO_IMPL_REDIRECT_ERROR_HPP
#define ASIO_IMPL_REDIRECT_ERROR_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include "asio/detail/config.hpp"
#include "asio/associated_executor.hpp"
#include "asio/associator.hpp"
#include "asio/async_result.hpp"
#include "asio/detail/handler_cont_helpers.hpp"
#include "asio/detail/initiation_base.hpp"
#include "asio/detail/type_traits.hpp"
#include "asio/system_error.hpp"
#include "asio/detail/push_options.hpp"
namespace asio {
namespace detail {
// Class to adapt a redirect_error_t as a completion handler.
template <typename Handler>
class redirect_error_handler
{
public:
typedef void result_type;
template <typename CompletionToken>
redirect_error_handler(redirect_error_t<CompletionToken> e)
: ec_(e.ec_),
handler_(static_cast<CompletionToken&&>(e.token_))
{
}
template <typename RedirectedHandler>
redirect_error_handler(asio::error_code& ec,
RedirectedHandler&& h)
: ec_(ec),
handler_(static_cast<RedirectedHandler&&>(h))
{
}
void operator()()
{
static_cast<Handler&&>(handler_)();
}
template <typename Arg, typename... Args>
enable_if_t<
!is_same<decay_t<Arg>, asio::error_code>::value
>
operator()(Arg&& arg, Args&&... args)
{
static_cast<Handler&&>(handler_)(
static_cast<Arg&&>(arg),
static_cast<Args&&>(args)...);
}
template <typename... Args>
void operator()(const asio::error_code& ec, Args&&... args)
{
ec_ = ec;
static_cast<Handler&&>(handler_)(static_cast<Args&&>(args)...);
}
//private:
asio::error_code& ec_;
Handler handler_;
};
template <typename Handler>
inline bool asio_handler_is_continuation(
redirect_error_handler<Handler>* this_handler)
{
return asio_handler_cont_helpers::is_continuation(
this_handler->handler_);
}
template <typename Signature>
struct redirect_error_signature
{
typedef Signature type;
};
template <typename R, typename... Args>
struct redirect_error_signature<R(asio::error_code, Args...)>
{
typedef R type(Args...);
};
template <typename R, typename... Args>
struct redirect_error_signature<R(const asio::error_code&, Args...)>
{
typedef R type(Args...);
};
template <typename R, typename... Args>
struct redirect_error_signature<R(asio::error_code, Args...) &>
{
typedef R type(Args...) &;
};
template <typename R, typename... Args>
struct redirect_error_signature<R(const asio::error_code&, Args...) &>
{
typedef R type(Args...) &;
};
template <typename R, typename... Args>
struct redirect_error_signature<R(asio::error_code, Args...) &&>
{
typedef R type(Args...) &&;
};
template <typename R, typename... Args>
struct redirect_error_signature<R(const asio::error_code&, Args...) &&>
{
typedef R type(Args...) &&;
};
#if defined(ASIO_HAS_NOEXCEPT_FUNCTION_TYPE)
template <typename R, typename... Args>
struct redirect_error_signature<
R(asio::error_code, Args...) noexcept>
{
typedef R type(Args...) & noexcept;
};
template <typename R, typename... Args>
struct redirect_error_signature<
R(const asio::error_code&, Args...) noexcept>
{
typedef R type(Args...) & noexcept;
};
template <typename R, typename... Args>
struct redirect_error_signature<
R(asio::error_code, Args...) & noexcept>
{
typedef R type(Args...) & noexcept;
};
template <typename R, typename... Args>
struct redirect_error_signature<
R(const asio::error_code&, Args...) & noexcept>
{
typedef R type(Args...) & noexcept;
};
template <typename R, typename... Args>
struct redirect_error_signature<
R(asio::error_code, Args...) && noexcept>
{
typedef R type(Args...) && noexcept;
};
template <typename R, typename... Args>
struct redirect_error_signature<
R(const asio::error_code&, Args...) && noexcept>
{
typedef R type(Args...) && noexcept;
};
#endif // defined(ASIO_HAS_NOEXCEPT_FUNCTION_TYPE)
} // namespace detail
#if !defined(GENERATING_DOCUMENTATION)
template <typename CompletionToken, typename Signature>
struct async_result<redirect_error_t<CompletionToken>, Signature>
: async_result<CompletionToken,
typename detail::redirect_error_signature<Signature>::type>
{
template <typename Initiation>
struct init_wrapper : detail::initiation_base<Initiation>
{
using detail::initiation_base<Initiation>::initiation_base;
template <typename Handler, typename... Args>
void operator()(Handler&& handler,
asio::error_code* ec, Args&&... args) &&
{
static_cast<Initiation&&>(*this)(
detail::redirect_error_handler<decay_t<Handler>>(
*ec, static_cast<Handler&&>(handler)),
static_cast<Args&&>(args)...);
}
template <typename Handler, typename... Args>
void operator()(Handler&& handler,
asio::error_code* ec, Args&&... args) const &
{
static_cast<const Initiation&>(*this)(
detail::redirect_error_handler<decay_t<Handler>>(
*ec, static_cast<Handler&&>(handler)),
static_cast<Args&&>(args)...);
}
};
template <typename Initiation, typename RawCompletionToken, typename... Args>
static auto initiate(Initiation&& initiation,
RawCompletionToken&& token, Args&&... args)
-> decltype(
async_initiate<
conditional_t<
is_const<remove_reference_t<RawCompletionToken>>::value,
const CompletionToken, CompletionToken>,
typename detail::redirect_error_signature<Signature>::type>(
declval<init_wrapper<decay_t<Initiation>>>(),
token.token_, &token.ec_, static_cast<Args&&>(args)...))
{
return async_initiate<
conditional_t<
is_const<remove_reference_t<RawCompletionToken>>::value,
const CompletionToken, CompletionToken>,
typename detail::redirect_error_signature<Signature>::type>(
init_wrapper<decay_t<Initiation>>(
static_cast<Initiation&&>(initiation)),
token.token_, &token.ec_, static_cast<Args&&>(args)...);
}
};
template <template <typename, typename> class Associator,
typename Handler, typename DefaultCandidate>
struct associator<Associator,
detail::redirect_error_handler<Handler>, DefaultCandidate>
: Associator<Handler, DefaultCandidate>
{
static typename Associator<Handler, DefaultCandidate>::type get(
const detail::redirect_error_handler<Handler>& h) noexcept
{
return Associator<Handler, DefaultCandidate>::get(h.handler_);
}
static auto get(const detail::redirect_error_handler<Handler>& h,
const DefaultCandidate& c) noexcept
-> decltype(Associator<Handler, DefaultCandidate>::get(h.handler_, c))
{
return Associator<Handler, DefaultCandidate>::get(h.handler_, c);
}
};
template <typename... Signatures>
struct async_result<partial_redirect_error, Signatures...>
{
template <typename Initiation, typename RawCompletionToken, typename... Args>
static auto initiate(Initiation&& initiation,
RawCompletionToken&& token, Args&&... args)
-> decltype(
async_initiate<Signatures...>(
static_cast<Initiation&&>(initiation),
redirect_error_t<
default_completion_token_t<associated_executor_t<Initiation>>>(
default_completion_token_t<associated_executor_t<Initiation>>{},
token.ec_),
static_cast<Args&&>(args)...))
{
return async_initiate<Signatures...>(
static_cast<Initiation&&>(initiation),
redirect_error_t<
default_completion_token_t<associated_executor_t<Initiation>>>(
default_completion_token_t<associated_executor_t<Initiation>>{},
token.ec_),
static_cast<Args&&>(args)...);
}
};
#endif // !defined(GENERATING_DOCUMENTATION)
} // namespace asio
#include "asio/detail/pop_options.hpp"
#endif // ASIO_IMPL_REDIRECT_ERROR_HPP
|
0 | repos/asio/asio/include/asio | repos/asio/asio/include/asio/impl/error_code.ipp | //
// impl/error_code.ipp
// ~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef ASIO_IMPL_ERROR_CODE_IPP
#define ASIO_IMPL_ERROR_CODE_IPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include "asio/detail/config.hpp"
#if defined(ASIO_WINDOWS) || defined(__CYGWIN__)
# include <winerror.h>
#elif defined(ASIO_WINDOWS_RUNTIME)
# include <windows.h>
#else
# include <cerrno>
# include <cstring>
# include <string>
#endif
#include "asio/detail/local_free_on_block_exit.hpp"
#include "asio/detail/socket_types.hpp"
#include "asio/error_code.hpp"
#include "asio/detail/push_options.hpp"
namespace asio {
namespace detail {
class system_category : public error_category
{
public:
const char* name() const noexcept
{
return "asio.system";
}
std::string message(int value) const
{
#if defined(ASIO_WINDOWS_RUNTIME) || defined(ASIO_WINDOWS_APP)
std::wstring wmsg(128, wchar_t());
for (;;)
{
DWORD wlength = ::FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM
| FORMAT_MESSAGE_IGNORE_INSERTS, 0, value,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
&wmsg[0], static_cast<DWORD>(wmsg.size()), 0);
if (wlength == 0 && ::GetLastError() == ERROR_INSUFFICIENT_BUFFER)
{
wmsg.resize(wmsg.size() + wmsg.size() / 2);
continue;
}
if (wlength && wmsg[wlength - 1] == '\n')
--wlength;
if (wlength && wmsg[wlength - 1] == '\r')
--wlength;
if (wlength)
{
std::string msg(wlength * 2, char());
int length = ::WideCharToMultiByte(CP_ACP, 0,
wmsg.c_str(), static_cast<int>(wlength),
&msg[0], static_cast<int>(wlength * 2), 0, 0);
if (length <= 0)
return "asio.system error";
msg.resize(static_cast<std::size_t>(length));
return msg;
}
else
return "asio.system error";
}
#elif defined(ASIO_WINDOWS) || defined(__CYGWIN__)
char* msg = 0;
DWORD length = ::FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER
| FORMAT_MESSAGE_FROM_SYSTEM
| FORMAT_MESSAGE_IGNORE_INSERTS, 0, value,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (char*)&msg, 0, 0);
detail::local_free_on_block_exit local_free_obj(msg);
if (length && msg[length - 1] == '\n')
msg[--length] = '\0';
if (length && msg[length - 1] == '\r')
msg[--length] = '\0';
if (length)
return msg;
else
return "asio.system error";
#else // defined(ASIO_WINDOWS_DESKTOP) || defined(__CYGWIN__)
#if !defined(__sun)
if (value == ECANCELED)
return "Operation aborted.";
#endif // !defined(__sun)
#if defined(__sun) || defined(__QNX__) || defined(__SYMBIAN32__)
using namespace std;
return strerror(value);
#else
char buf[256] = "";
using namespace std;
return strerror_result(strerror_r(value, buf, sizeof(buf)), buf);
#endif
#endif // defined(ASIO_WINDOWS_DESKTOP) || defined(__CYGWIN__)
}
#if defined(ASIO_HAS_STD_ERROR_CODE)
std::error_condition default_error_condition(
int ev) const noexcept
{
switch (ev)
{
case access_denied:
return std::errc::permission_denied;
case address_family_not_supported:
return std::errc::address_family_not_supported;
case address_in_use:
return std::errc::address_in_use;
case already_connected:
return std::errc::already_connected;
case already_started:
return std::errc::connection_already_in_progress;
case broken_pipe:
return std::errc::broken_pipe;
case connection_aborted:
return std::errc::connection_aborted;
case connection_refused:
return std::errc::connection_refused;
case connection_reset:
return std::errc::connection_reset;
case bad_descriptor:
return std::errc::bad_file_descriptor;
case fault:
return std::errc::bad_address;
case host_unreachable:
return std::errc::host_unreachable;
case in_progress:
return std::errc::operation_in_progress;
case interrupted:
return std::errc::interrupted;
case invalid_argument:
return std::errc::invalid_argument;
case message_size:
return std::errc::message_size;
case name_too_long:
return std::errc::filename_too_long;
case network_down:
return std::errc::network_down;
case network_reset:
return std::errc::network_reset;
case network_unreachable:
return std::errc::network_unreachable;
case no_descriptors:
return std::errc::too_many_files_open;
case no_buffer_space:
return std::errc::no_buffer_space;
case no_memory:
return std::errc::not_enough_memory;
case no_permission:
return std::errc::operation_not_permitted;
case no_protocol_option:
return std::errc::no_protocol_option;
case no_such_device:
return std::errc::no_such_device;
case not_connected:
return std::errc::not_connected;
case not_socket:
return std::errc::not_a_socket;
case operation_aborted:
return std::errc::operation_canceled;
case operation_not_supported:
return std::errc::operation_not_supported;
case shut_down:
return std::make_error_condition(ev, *this);
case timed_out:
return std::errc::timed_out;
case try_again:
return std::errc::resource_unavailable_try_again;
case would_block:
return std::errc::operation_would_block;
default:
return std::make_error_condition(ev, *this);
}
#endif // defined(ASIO_HAS_STD_ERROR_CODE)
private:
// Helper function to adapt the result from glibc's variant of strerror_r.
static const char* strerror_result(int, const char* s) { return s; }
static const char* strerror_result(const char* s, const char*) { return s; }
};
} // namespace detail
const error_category& system_category()
{
static detail::system_category instance;
return instance;
}
} // namespace asio
#include "asio/detail/pop_options.hpp"
#endif // ASIO_IMPL_ERROR_CODE_IPP
|
0 | repos/asio/asio/include/asio | repos/asio/asio/include/asio/impl/thread_pool.ipp | //
// impl/thread_pool.ipp
// ~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef ASIO_IMPL_THREAD_POOL_IPP
#define ASIO_IMPL_THREAD_POOL_IPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include "asio/detail/config.hpp"
#include <stdexcept>
#include "asio/thread_pool.hpp"
#include "asio/detail/throw_exception.hpp"
#include "asio/detail/push_options.hpp"
namespace asio {
struct thread_pool::thread_function
{
detail::scheduler* scheduler_;
void operator()()
{
#if !defined(ASIO_NO_EXCEPTIONS)
try
{
#endif// !defined(ASIO_NO_EXCEPTIONS)
asio::error_code ec;
scheduler_->run(ec);
#if !defined(ASIO_NO_EXCEPTIONS)
}
catch (...)
{
std::terminate();
}
#endif// !defined(ASIO_NO_EXCEPTIONS)
}
};
#if !defined(ASIO_NO_TS_EXECUTORS)
namespace detail {
inline long default_thread_pool_size()
{
std::size_t num_threads = thread::hardware_concurrency() * 2;
num_threads = num_threads == 0 ? 2 : num_threads;
return static_cast<long>(num_threads);
}
} // namespace detail
thread_pool::thread_pool()
: scheduler_(add_scheduler(new detail::scheduler(*this, 0, false))),
num_threads_(detail::default_thread_pool_size())
{
scheduler_.work_started();
thread_function f = { &scheduler_ };
threads_.create_threads(f, static_cast<std::size_t>(num_threads_));
}
#endif // !defined(ASIO_NO_TS_EXECUTORS)
namespace detail {
inline long clamp_thread_pool_size(std::size_t n)
{
if (n > 0x7FFFFFFF)
{
std::out_of_range ex("thread pool size");
asio::detail::throw_exception(ex);
}
return static_cast<long>(n & 0x7FFFFFFF);
}
} // namespace detail
thread_pool::thread_pool(std::size_t num_threads)
: scheduler_(add_scheduler(new detail::scheduler(
*this, num_threads == 1 ? 1 : 0, false))),
num_threads_(detail::clamp_thread_pool_size(num_threads))
{
scheduler_.work_started();
thread_function f = { &scheduler_ };
threads_.create_threads(f, static_cast<std::size_t>(num_threads_));
}
thread_pool::~thread_pool()
{
stop();
join();
shutdown();
}
void thread_pool::stop()
{
scheduler_.stop();
}
void thread_pool::attach()
{
++num_threads_;
thread_function f = { &scheduler_ };
f();
}
void thread_pool::join()
{
if (num_threads_)
scheduler_.work_finished();
if (!threads_.empty())
threads_.join();
}
detail::scheduler& thread_pool::add_scheduler(detail::scheduler* s)
{
detail::scoped_ptr<detail::scheduler> scoped_impl(s);
asio::add_service<detail::scheduler>(*this, scoped_impl.get());
return *scoped_impl.release();
}
void thread_pool::wait()
{
scheduler_.work_finished();
threads_.join();
}
} // namespace asio
#include "asio/detail/pop_options.hpp"
#endif // ASIO_IMPL_THREAD_POOL_IPP
|
0 | repos/asio/asio/include/asio | repos/asio/asio/include/asio/impl/any_io_executor.ipp | //
// impl/any_io_executor.ipp
// ~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef ASIO_IMPL_ANY_IO_EXECUTOR_IPP
#define ASIO_IMPL_ANY_IO_EXECUTOR_IPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include "asio/detail/config.hpp"
#if !defined(ASIO_USE_TS_EXECUTOR_AS_DEFAULT)
#include "asio/any_io_executor.hpp"
#include "asio/detail/push_options.hpp"
namespace asio {
any_io_executor::any_io_executor() noexcept
: base_type()
{
}
any_io_executor::any_io_executor(nullptr_t) noexcept
: base_type(nullptr_t())
{
}
any_io_executor::any_io_executor(const any_io_executor& e) noexcept
: base_type(static_cast<const base_type&>(e))
{
}
any_io_executor::any_io_executor(std::nothrow_t,
const any_io_executor& e) noexcept
: base_type(static_cast<const base_type&>(e))
{
}
any_io_executor::any_io_executor(any_io_executor&& e) noexcept
: base_type(static_cast<base_type&&>(e))
{
}
any_io_executor::any_io_executor(std::nothrow_t, any_io_executor&& e) noexcept
: base_type(static_cast<base_type&&>(e))
{
}
any_io_executor& any_io_executor::operator=(const any_io_executor& e) noexcept
{
base_type::operator=(static_cast<const base_type&>(e));
return *this;
}
any_io_executor& any_io_executor::operator=(any_io_executor&& e) noexcept
{
base_type::operator=(static_cast<base_type&&>(e));
return *this;
}
any_io_executor& any_io_executor::operator=(nullptr_t)
{
base_type::operator=(nullptr_t());
return *this;
}
any_io_executor::~any_io_executor()
{
}
void any_io_executor::swap(any_io_executor& other) noexcept
{
static_cast<base_type&>(*this).swap(static_cast<base_type&>(other));
}
template <>
any_io_executor any_io_executor::require(
const execution::blocking_t::never_t& p, int) const
{
return static_cast<const base_type&>(*this).require(p);
}
template <>
any_io_executor any_io_executor::prefer(
const execution::blocking_t::possibly_t& p, int) const
{
return static_cast<const base_type&>(*this).prefer(p);
}
template <>
any_io_executor any_io_executor::prefer(
const execution::outstanding_work_t::tracked_t& p, int) const
{
return static_cast<const base_type&>(*this).prefer(p);
}
template <>
any_io_executor any_io_executor::prefer(
const execution::outstanding_work_t::untracked_t& p, int) const
{
return static_cast<const base_type&>(*this).prefer(p);
}
template <>
any_io_executor any_io_executor::prefer(
const execution::relationship_t::fork_t& p, int) const
{
return static_cast<const base_type&>(*this).prefer(p);
}
template <>
any_io_executor any_io_executor::prefer(
const execution::relationship_t::continuation_t& p, int) const
{
return static_cast<const base_type&>(*this).prefer(p);
}
} // namespace asio
#include "asio/detail/pop_options.hpp"
#endif // !defined(ASIO_USE_TS_EXECUTOR_AS_DEFAULT)
#endif // ASIO_IMPL_ANY_IO_EXECUTOR_IPP
|
0 | repos/asio/asio/include/asio | repos/asio/asio/include/asio/impl/read_at.hpp | //
// impl/read_at.hpp
// ~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef ASIO_IMPL_READ_AT_HPP
#define ASIO_IMPL_READ_AT_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <algorithm>
#include "asio/associator.hpp"
#include "asio/buffer.hpp"
#include "asio/detail/array_fwd.hpp"
#include "asio/detail/base_from_cancellation_state.hpp"
#include "asio/detail/base_from_completion_cond.hpp"
#include "asio/detail/bind_handler.hpp"
#include "asio/detail/consuming_buffers.hpp"
#include "asio/detail/dependent_type.hpp"
#include "asio/detail/handler_cont_helpers.hpp"
#include "asio/detail/handler_tracking.hpp"
#include "asio/detail/handler_type_requirements.hpp"
#include "asio/detail/non_const_lvalue.hpp"
#include "asio/detail/throw_error.hpp"
#include "asio/error.hpp"
#include "asio/detail/push_options.hpp"
namespace asio {
namespace detail
{
template <typename SyncRandomAccessReadDevice, typename MutableBufferSequence,
typename MutableBufferIterator, typename CompletionCondition>
std::size_t read_at_buffer_sequence(SyncRandomAccessReadDevice& d,
uint64_t offset, const MutableBufferSequence& buffers,
const MutableBufferIterator&, CompletionCondition completion_condition,
asio::error_code& ec)
{
ec = asio::error_code();
asio::detail::consuming_buffers<mutable_buffer,
MutableBufferSequence, MutableBufferIterator> tmp(buffers);
while (!tmp.empty())
{
if (std::size_t max_size = detail::adapt_completion_condition_result(
completion_condition(ec, tmp.total_consumed())))
{
tmp.consume(d.read_some_at(offset + tmp.total_consumed(),
tmp.prepare(max_size), ec));
}
else
break;
}
return tmp.total_consumed();
}
} // namespace detail
template <typename SyncRandomAccessReadDevice, typename MutableBufferSequence,
typename CompletionCondition>
std::size_t read_at(SyncRandomAccessReadDevice& d,
uint64_t offset, const MutableBufferSequence& buffers,
CompletionCondition completion_condition, asio::error_code& ec,
constraint_t<
is_completion_condition<CompletionCondition>::value
>)
{
return detail::read_at_buffer_sequence(d, offset, buffers,
asio::buffer_sequence_begin(buffers),
static_cast<CompletionCondition&&>(completion_condition), ec);
}
template <typename SyncRandomAccessReadDevice, typename MutableBufferSequence>
inline std::size_t read_at(SyncRandomAccessReadDevice& d,
uint64_t offset, const MutableBufferSequence& buffers)
{
asio::error_code ec;
std::size_t bytes_transferred = read_at(
d, offset, buffers, transfer_all(), ec);
asio::detail::throw_error(ec, "read_at");
return bytes_transferred;
}
template <typename SyncRandomAccessReadDevice, typename MutableBufferSequence>
inline std::size_t read_at(SyncRandomAccessReadDevice& d,
uint64_t offset, const MutableBufferSequence& buffers,
asio::error_code& ec)
{
return read_at(d, offset, buffers, transfer_all(), ec);
}
template <typename SyncRandomAccessReadDevice, typename MutableBufferSequence,
typename CompletionCondition>
inline std::size_t read_at(SyncRandomAccessReadDevice& d,
uint64_t offset, const MutableBufferSequence& buffers,
CompletionCondition completion_condition,
constraint_t<
is_completion_condition<CompletionCondition>::value
>)
{
asio::error_code ec;
std::size_t bytes_transferred = read_at(d, offset, buffers,
static_cast<CompletionCondition&&>(completion_condition), ec);
asio::detail::throw_error(ec, "read_at");
return bytes_transferred;
}
#if !defined(ASIO_NO_EXTENSIONS)
#if !defined(ASIO_NO_IOSTREAM)
template <typename SyncRandomAccessReadDevice, typename Allocator,
typename CompletionCondition>
std::size_t read_at(SyncRandomAccessReadDevice& d,
uint64_t offset, asio::basic_streambuf<Allocator>& b,
CompletionCondition completion_condition, asio::error_code& ec,
constraint_t<
is_completion_condition<CompletionCondition>::value
>)
{
ec = asio::error_code();
std::size_t total_transferred = 0;
std::size_t max_size = detail::adapt_completion_condition_result(
completion_condition(ec, total_transferred));
std::size_t bytes_available = read_size_helper(b, max_size);
while (bytes_available > 0)
{
std::size_t bytes_transferred = d.read_some_at(
offset + total_transferred, b.prepare(bytes_available), ec);
b.commit(bytes_transferred);
total_transferred += bytes_transferred;
max_size = detail::adapt_completion_condition_result(
completion_condition(ec, total_transferred));
bytes_available = read_size_helper(b, max_size);
}
return total_transferred;
}
template <typename SyncRandomAccessReadDevice, typename Allocator>
inline std::size_t read_at(SyncRandomAccessReadDevice& d,
uint64_t offset, asio::basic_streambuf<Allocator>& b)
{
asio::error_code ec;
std::size_t bytes_transferred = read_at(
d, offset, b, transfer_all(), ec);
asio::detail::throw_error(ec, "read_at");
return bytes_transferred;
}
template <typename SyncRandomAccessReadDevice, typename Allocator>
inline std::size_t read_at(SyncRandomAccessReadDevice& d,
uint64_t offset, asio::basic_streambuf<Allocator>& b,
asio::error_code& ec)
{
return read_at(d, offset, b, transfer_all(), ec);
}
template <typename SyncRandomAccessReadDevice, typename Allocator,
typename CompletionCondition>
inline std::size_t read_at(SyncRandomAccessReadDevice& d,
uint64_t offset, asio::basic_streambuf<Allocator>& b,
CompletionCondition completion_condition,
constraint_t<
is_completion_condition<CompletionCondition>::value
>)
{
asio::error_code ec;
std::size_t bytes_transferred = read_at(d, offset, b,
static_cast<CompletionCondition&&>(completion_condition), ec);
asio::detail::throw_error(ec, "read_at");
return bytes_transferred;
}
#endif // !defined(ASIO_NO_IOSTREAM)
#endif // !defined(ASIO_NO_EXTENSIONS)
namespace detail
{
template <typename AsyncRandomAccessReadDevice,
typename MutableBufferSequence, typename MutableBufferIterator,
typename CompletionCondition, typename ReadHandler>
class read_at_op
: public base_from_cancellation_state<ReadHandler>,
base_from_completion_cond<CompletionCondition>
{
public:
read_at_op(AsyncRandomAccessReadDevice& device,
uint64_t offset, const MutableBufferSequence& buffers,
CompletionCondition& completion_condition, ReadHandler& handler)
: base_from_cancellation_state<ReadHandler>(
handler, enable_partial_cancellation()),
base_from_completion_cond<CompletionCondition>(completion_condition),
device_(device),
offset_(offset),
buffers_(buffers),
start_(0),
handler_(static_cast<ReadHandler&&>(handler))
{
}
read_at_op(const read_at_op& other)
: base_from_cancellation_state<ReadHandler>(other),
base_from_completion_cond<CompletionCondition>(other),
device_(other.device_),
offset_(other.offset_),
buffers_(other.buffers_),
start_(other.start_),
handler_(other.handler_)
{
}
read_at_op(read_at_op&& other)
: base_from_cancellation_state<ReadHandler>(
static_cast<base_from_cancellation_state<ReadHandler>&&>(other)),
base_from_completion_cond<CompletionCondition>(
static_cast<base_from_completion_cond<CompletionCondition>&&>(other)),
device_(other.device_),
offset_(other.offset_),
buffers_(static_cast<buffers_type&&>(other.buffers_)),
start_(other.start_),
handler_(static_cast<ReadHandler&&>(other.handler_))
{
}
void operator()(asio::error_code ec,
std::size_t bytes_transferred, int start = 0)
{
std::size_t max_size;
switch (start_ = start)
{
case 1:
max_size = this->check_for_completion(ec, buffers_.total_consumed());
for (;;)
{
{
ASIO_HANDLER_LOCATION((__FILE__, __LINE__, "async_read_at"));
device_.async_read_some_at(
offset_ + buffers_.total_consumed(), buffers_.prepare(max_size),
static_cast<read_at_op&&>(*this));
}
return; default:
buffers_.consume(bytes_transferred);
if ((!ec && bytes_transferred == 0) || buffers_.empty())
break;
max_size = this->check_for_completion(ec, buffers_.total_consumed());
if (max_size == 0)
break;
if (this->cancelled() != cancellation_type::none)
{
ec = asio::error::operation_aborted;
break;
}
}
static_cast<ReadHandler&&>(handler_)(
static_cast<const asio::error_code&>(ec),
static_cast<const std::size_t&>(buffers_.total_consumed()));
}
}
//private:
typedef asio::detail::consuming_buffers<mutable_buffer,
MutableBufferSequence, MutableBufferIterator> buffers_type;
AsyncRandomAccessReadDevice& device_;
uint64_t offset_;
buffers_type buffers_;
int start_;
ReadHandler handler_;
};
template <typename AsyncRandomAccessReadDevice,
typename MutableBufferSequence, typename MutableBufferIterator,
typename CompletionCondition, typename ReadHandler>
inline bool asio_handler_is_continuation(
read_at_op<AsyncRandomAccessReadDevice, MutableBufferSequence,
MutableBufferIterator, CompletionCondition, ReadHandler>* this_handler)
{
return this_handler->start_ == 0 ? true
: asio_handler_cont_helpers::is_continuation(
this_handler->handler_);
}
template <typename AsyncRandomAccessReadDevice,
typename MutableBufferSequence, typename MutableBufferIterator,
typename CompletionCondition, typename ReadHandler>
inline void start_read_at_op(AsyncRandomAccessReadDevice& d,
uint64_t offset, const MutableBufferSequence& buffers,
const MutableBufferIterator&, CompletionCondition& completion_condition,
ReadHandler& handler)
{
detail::read_at_op<AsyncRandomAccessReadDevice, MutableBufferSequence,
MutableBufferIterator, CompletionCondition, ReadHandler>(
d, offset, buffers, completion_condition, handler)(
asio::error_code(), 0, 1);
}
template <typename AsyncRandomAccessReadDevice>
class initiate_async_read_at
{
public:
typedef typename AsyncRandomAccessReadDevice::executor_type executor_type;
explicit initiate_async_read_at(AsyncRandomAccessReadDevice& device)
: device_(device)
{
}
executor_type get_executor() const noexcept
{
return device_.get_executor();
}
template <typename ReadHandler, typename MutableBufferSequence,
typename CompletionCondition>
void operator()(ReadHandler&& handler,
uint64_t offset, const MutableBufferSequence& buffers,
CompletionCondition&& completion_cond) const
{
// If you get an error on the following line it means that your handler
// does not meet the documented type requirements for a ReadHandler.
ASIO_READ_HANDLER_CHECK(ReadHandler, handler) type_check;
non_const_lvalue<ReadHandler> handler2(handler);
non_const_lvalue<CompletionCondition> completion_cond2(completion_cond);
start_read_at_op(device_, offset, buffers,
asio::buffer_sequence_begin(buffers),
completion_cond2.value, handler2.value);
}
private:
AsyncRandomAccessReadDevice& device_;
};
} // namespace detail
#if !defined(GENERATING_DOCUMENTATION)
template <template <typename, typename> class Associator,
typename AsyncRandomAccessReadDevice, typename MutableBufferSequence,
typename MutableBufferIterator, typename CompletionCondition,
typename ReadHandler, typename DefaultCandidate>
struct associator<Associator,
detail::read_at_op<AsyncRandomAccessReadDevice, MutableBufferSequence,
MutableBufferIterator, CompletionCondition, ReadHandler>,
DefaultCandidate>
: Associator<ReadHandler, DefaultCandidate>
{
static typename Associator<ReadHandler, DefaultCandidate>::type get(
const detail::read_at_op<AsyncRandomAccessReadDevice,
MutableBufferSequence, MutableBufferIterator,
CompletionCondition, ReadHandler>& h) noexcept
{
return Associator<ReadHandler, DefaultCandidate>::get(h.handler_);
}
static auto get(
const detail::read_at_op<AsyncRandomAccessReadDevice,
MutableBufferSequence, MutableBufferIterator,
CompletionCondition, ReadHandler>& h,
const DefaultCandidate& c) noexcept
-> decltype(Associator<ReadHandler, DefaultCandidate>::get(h.handler_, c))
{
return Associator<ReadHandler, DefaultCandidate>::get(h.handler_, c);
}
};
#endif // !defined(GENERATING_DOCUMENTATION)
#if !defined(ASIO_NO_EXTENSIONS)
#if !defined(ASIO_NO_IOSTREAM)
namespace detail
{
template <typename AsyncRandomAccessReadDevice, typename Allocator,
typename CompletionCondition, typename ReadHandler>
class read_at_streambuf_op
: public base_from_cancellation_state<ReadHandler>,
base_from_completion_cond<CompletionCondition>
{
public:
read_at_streambuf_op(AsyncRandomAccessReadDevice& device,
uint64_t offset, basic_streambuf<Allocator>& streambuf,
CompletionCondition& completion_condition, ReadHandler& handler)
: base_from_cancellation_state<ReadHandler>(
handler, enable_partial_cancellation()),
base_from_completion_cond<CompletionCondition>(completion_condition),
device_(device),
offset_(offset),
streambuf_(streambuf),
start_(0),
total_transferred_(0),
handler_(static_cast<ReadHandler&&>(handler))
{
}
read_at_streambuf_op(const read_at_streambuf_op& other)
: base_from_cancellation_state<ReadHandler>(other),
base_from_completion_cond<CompletionCondition>(other),
device_(other.device_),
offset_(other.offset_),
streambuf_(other.streambuf_),
start_(other.start_),
total_transferred_(other.total_transferred_),
handler_(other.handler_)
{
}
read_at_streambuf_op(read_at_streambuf_op&& other)
: base_from_cancellation_state<ReadHandler>(
static_cast<base_from_cancellation_state<ReadHandler>&&>(other)),
base_from_completion_cond<CompletionCondition>(
static_cast<base_from_completion_cond<CompletionCondition>&&>(other)),
device_(other.device_),
offset_(other.offset_),
streambuf_(other.streambuf_),
start_(other.start_),
total_transferred_(other.total_transferred_),
handler_(static_cast<ReadHandler&&>(other.handler_))
{
}
void operator()(asio::error_code ec,
std::size_t bytes_transferred, int start = 0)
{
std::size_t max_size, bytes_available;
switch (start_ = start)
{
case 1:
max_size = this->check_for_completion(ec, total_transferred_);
bytes_available = read_size_helper(streambuf_, max_size);
for (;;)
{
{
ASIO_HANDLER_LOCATION((__FILE__, __LINE__, "async_read_at"));
device_.async_read_some_at(offset_ + total_transferred_,
streambuf_.prepare(bytes_available),
static_cast<read_at_streambuf_op&&>(*this));
}
return; default:
total_transferred_ += bytes_transferred;
streambuf_.commit(bytes_transferred);
max_size = this->check_for_completion(ec, total_transferred_);
bytes_available = read_size_helper(streambuf_, max_size);
if ((!ec && bytes_transferred == 0) || bytes_available == 0)
break;
if (this->cancelled() != cancellation_type::none)
{
ec = asio::error::operation_aborted;
break;
}
}
static_cast<ReadHandler&&>(handler_)(
static_cast<const asio::error_code&>(ec),
static_cast<const std::size_t&>(total_transferred_));
}
}
//private:
AsyncRandomAccessReadDevice& device_;
uint64_t offset_;
asio::basic_streambuf<Allocator>& streambuf_;
int start_;
std::size_t total_transferred_;
ReadHandler handler_;
};
template <typename AsyncRandomAccessReadDevice, typename Allocator,
typename CompletionCondition, typename ReadHandler>
inline bool asio_handler_is_continuation(
read_at_streambuf_op<AsyncRandomAccessReadDevice, Allocator,
CompletionCondition, ReadHandler>* this_handler)
{
return this_handler->start_ == 0 ? true
: asio_handler_cont_helpers::is_continuation(
this_handler->handler_);
}
template <typename AsyncRandomAccessReadDevice>
class initiate_async_read_at_streambuf
{
public:
typedef typename AsyncRandomAccessReadDevice::executor_type executor_type;
explicit initiate_async_read_at_streambuf(
AsyncRandomAccessReadDevice& device)
: device_(device)
{
}
executor_type get_executor() const noexcept
{
return device_.get_executor();
}
template <typename ReadHandler,
typename Allocator, typename CompletionCondition>
void operator()(ReadHandler&& handler,
uint64_t offset, basic_streambuf<Allocator>* b,
CompletionCondition&& completion_cond) const
{
// If you get an error on the following line it means that your handler
// does not meet the documented type requirements for a ReadHandler.
ASIO_READ_HANDLER_CHECK(ReadHandler, handler) type_check;
non_const_lvalue<ReadHandler> handler2(handler);
non_const_lvalue<CompletionCondition> completion_cond2(completion_cond);
read_at_streambuf_op<AsyncRandomAccessReadDevice, Allocator,
CompletionCondition, decay_t<ReadHandler>>(
device_, offset, *b, completion_cond2.value, handler2.value)(
asio::error_code(), 0, 1);
}
private:
AsyncRandomAccessReadDevice& device_;
};
} // namespace detail
#if !defined(GENERATING_DOCUMENTATION)
template <template <typename, typename> class Associator,
typename AsyncRandomAccessReadDevice, typename Executor,
typename CompletionCondition, typename ReadHandler,
typename DefaultCandidate>
struct associator<Associator,
detail::read_at_streambuf_op<AsyncRandomAccessReadDevice,
Executor, CompletionCondition, ReadHandler>,
DefaultCandidate>
: Associator<ReadHandler, DefaultCandidate>
{
static typename Associator<ReadHandler, DefaultCandidate>::type get(
const detail::read_at_streambuf_op<AsyncRandomAccessReadDevice,
Executor, CompletionCondition, ReadHandler>& h) noexcept
{
return Associator<ReadHandler, DefaultCandidate>::get(h.handler_);
}
static auto get(
const detail::read_at_streambuf_op<AsyncRandomAccessReadDevice,
Executor, CompletionCondition, ReadHandler>& h,
const DefaultCandidate& c) noexcept
-> decltype(Associator<ReadHandler, DefaultCandidate>::get(h.handler_, c))
{
return Associator<ReadHandler, DefaultCandidate>::get(h.handler_, c);
}
};
#endif // !defined(GENERATING_DOCUMENTATION)
#endif // !defined(ASIO_NO_IOSTREAM)
#endif // !defined(ASIO_NO_EXTENSIONS)
} // namespace asio
#include "asio/detail/pop_options.hpp"
#endif // ASIO_IMPL_READ_AT_HPP
|
0 | repos/asio/asio/include/asio | repos/asio/asio/include/asio/impl/cancellation_signal.ipp | //
// impl/cancellation_signal.ipp
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef ASIO_IMPL_CANCELLATION_SIGNAL_IPP
#define ASIO_IMPL_CANCELLATION_SIGNAL_IPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include "asio/detail/config.hpp"
#include "asio/cancellation_signal.hpp"
#include "asio/detail/thread_context.hpp"
#include "asio/detail/thread_info_base.hpp"
#include "asio/detail/push_options.hpp"
namespace asio {
cancellation_signal::~cancellation_signal()
{
if (handler_)
{
std::pair<void*, std::size_t> mem = handler_->destroy();
detail::thread_info_base::deallocate(
detail::thread_info_base::cancellation_signal_tag(),
detail::thread_context::top_of_thread_call_stack(),
mem.first, mem.second);
}
}
void cancellation_slot::clear()
{
if (handler_ != 0 && *handler_ != 0)
{
std::pair<void*, std::size_t> mem = (*handler_)->destroy();
detail::thread_info_base::deallocate(
detail::thread_info_base::cancellation_signal_tag(),
detail::thread_context::top_of_thread_call_stack(),
mem.first, mem.second);
*handler_ = 0;
}
}
std::pair<void*, std::size_t> cancellation_slot::prepare_memory(
std::size_t size, std::size_t align)
{
assert(handler_);
std::pair<void*, std::size_t> mem;
if (*handler_)
{
mem = (*handler_)->destroy();
*handler_ = 0;
}
if (size > mem.second
|| reinterpret_cast<std::size_t>(mem.first) % align != 0)
{
if (mem.first)
{
detail::thread_info_base::deallocate(
detail::thread_info_base::cancellation_signal_tag(),
detail::thread_context::top_of_thread_call_stack(),
mem.first, mem.second);
}
mem.first = detail::thread_info_base::allocate(
detail::thread_info_base::cancellation_signal_tag(),
detail::thread_context::top_of_thread_call_stack(),
size, align);
mem.second = size;
}
return mem;
}
cancellation_slot::auto_delete_helper::~auto_delete_helper()
{
if (mem.first)
{
detail::thread_info_base::deallocate(
detail::thread_info_base::cancellation_signal_tag(),
detail::thread_context::top_of_thread_call_stack(),
mem.first, mem.second);
}
}
} // namespace asio
#include "asio/detail/pop_options.hpp"
#endif // ASIO_IMPL_CANCELLATION_SIGNAL_IPP
|
0 | repos/asio/asio/include/asio | repos/asio/asio/include/asio/impl/co_spawn.hpp | //
// impl/co_spawn.hpp
// ~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef ASIO_IMPL_CO_SPAWN_HPP
#define ASIO_IMPL_CO_SPAWN_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include "asio/detail/config.hpp"
#include "asio/associated_cancellation_slot.hpp"
#include "asio/awaitable.hpp"
#include "asio/detail/memory.hpp"
#include "asio/detail/recycling_allocator.hpp"
#include "asio/dispatch.hpp"
#include "asio/execution/outstanding_work.hpp"
#include "asio/post.hpp"
#include "asio/prefer.hpp"
#include "asio/use_awaitable.hpp"
#include "asio/detail/push_options.hpp"
namespace asio {
namespace detail {
template <typename Executor, typename = void>
class co_spawn_work_guard
{
public:
typedef decay_t<
prefer_result_t<Executor,
execution::outstanding_work_t::tracked_t
>
> executor_type;
co_spawn_work_guard(const Executor& ex)
: executor_(asio::prefer(ex, execution::outstanding_work.tracked))
{
}
executor_type get_executor() const noexcept
{
return executor_;
}
private:
executor_type executor_;
};
#if !defined(ASIO_NO_TS_EXECUTORS)
template <typename Executor>
struct co_spawn_work_guard<Executor,
enable_if_t<
!execution::is_executor<Executor>::value
>> : executor_work_guard<Executor>
{
co_spawn_work_guard(const Executor& ex)
: executor_work_guard<Executor>(ex)
{
}
};
#endif // !defined(ASIO_NO_TS_EXECUTORS)
template <typename Handler, typename Executor,
typename Function, typename = void>
struct co_spawn_state
{
template <typename H, typename F>
co_spawn_state(H&& h, const Executor& ex, F&& f)
: handler(std::forward<H>(h)),
spawn_work(ex),
handler_work(asio::get_associated_executor(handler, ex)),
function(std::forward<F>(f))
{
}
Handler handler;
co_spawn_work_guard<Executor> spawn_work;
co_spawn_work_guard<associated_executor_t<Handler, Executor>> handler_work;
Function function;
};
template <typename Handler, typename Executor, typename Function>
struct co_spawn_state<Handler, Executor, Function,
enable_if_t<
is_same<
typename associated_executor<Handler,
Executor>::asio_associated_executor_is_unspecialised,
void
>::value
>>
{
template <typename H, typename F>
co_spawn_state(H&& h, const Executor& ex, F&& f)
: handler(std::forward<H>(h)),
handler_work(ex),
function(std::forward<F>(f))
{
}
Handler handler;
co_spawn_work_guard<Executor> handler_work;
Function function;
};
struct co_spawn_dispatch
{
template <typename CompletionToken>
auto operator()(CompletionToken&& token) const
-> decltype(asio::dispatch(std::forward<CompletionToken>(token)))
{
return asio::dispatch(std::forward<CompletionToken>(token));
}
};
struct co_spawn_post
{
template <typename CompletionToken>
auto operator()(CompletionToken&& token) const
-> decltype(asio::post(std::forward<CompletionToken>(token)))
{
return asio::post(std::forward<CompletionToken>(token));
}
};
template <typename T, typename Handler, typename Executor, typename Function>
awaitable<awaitable_thread_entry_point, Executor> co_spawn_entry_point(
awaitable<T, Executor>*, co_spawn_state<Handler, Executor, Function> s)
{
(void) co_await co_spawn_dispatch{};
(co_await awaitable_thread_has_context_switched{}) = false;
std::exception_ptr e = nullptr;
bool done = false;
#if !defined(ASIO_NO_EXCEPTIONS)
try
#endif // !defined(ASIO_NO_EXCEPTIONS)
{
T t = co_await s.function();
done = true;
bool switched = (co_await awaitable_thread_has_context_switched{});
if (!switched)
{
co_await this_coro::throw_if_cancelled(false);
(void) co_await co_spawn_post();
}
(dispatch)(s.handler_work.get_executor(),
[handler = std::move(s.handler), t = std::move(t)]() mutable
{
std::move(handler)(std::exception_ptr(), std::move(t));
});
co_return;
}
#if !defined(ASIO_NO_EXCEPTIONS)
catch (...)
{
if (done)
throw;
e = std::current_exception();
}
#endif // !defined(ASIO_NO_EXCEPTIONS)
bool switched = (co_await awaitable_thread_has_context_switched{});
if (!switched)
{
co_await this_coro::throw_if_cancelled(false);
(void) co_await co_spawn_post();
}
(dispatch)(s.handler_work.get_executor(),
[handler = std::move(s.handler), e]() mutable
{
std::move(handler)(e, T());
});
}
template <typename Handler, typename Executor, typename Function>
awaitable<awaitable_thread_entry_point, Executor> co_spawn_entry_point(
awaitable<void, Executor>*, co_spawn_state<Handler, Executor, Function> s)
{
(void) co_await co_spawn_dispatch{};
(co_await awaitable_thread_has_context_switched{}) = false;
std::exception_ptr e = nullptr;
#if !defined(ASIO_NO_EXCEPTIONS)
try
#endif // !defined(ASIO_NO_EXCEPTIONS)
{
co_await s.function();
}
#if !defined(ASIO_NO_EXCEPTIONS)
catch (...)
{
e = std::current_exception();
}
#endif // !defined(ASIO_NO_EXCEPTIONS)
bool switched = (co_await awaitable_thread_has_context_switched{});
if (!switched)
{
co_await this_coro::throw_if_cancelled(false);
(void) co_await co_spawn_post();
}
(dispatch)(s.handler_work.get_executor(),
[handler = std::move(s.handler), e]() mutable
{
std::move(handler)(e);
});
}
template <typename T, typename Executor>
class awaitable_as_function
{
public:
explicit awaitable_as_function(awaitable<T, Executor>&& a)
: awaitable_(std::move(a))
{
}
awaitable<T, Executor> operator()()
{
return std::move(awaitable_);
}
private:
awaitable<T, Executor> awaitable_;
};
template <typename Handler, typename Executor, typename = void>
class co_spawn_cancellation_handler
{
public:
co_spawn_cancellation_handler(const Handler&, const Executor& ex)
: signal_(detail::allocate_shared<cancellation_signal>(
detail::recycling_allocator<cancellation_signal,
detail::thread_info_base::cancellation_signal_tag>())),
ex_(ex)
{
}
cancellation_slot slot()
{
return signal_->slot();
}
void operator()(cancellation_type_t type)
{
shared_ptr<cancellation_signal> sig = signal_;
asio::dispatch(ex_, [sig, type]{ sig->emit(type); });
}
private:
shared_ptr<cancellation_signal> signal_;
Executor ex_;
};
template <typename Handler, typename Executor>
class co_spawn_cancellation_handler<Handler, Executor,
enable_if_t<
is_same<
typename associated_executor<Handler,
Executor>::asio_associated_executor_is_unspecialised,
void
>::value
>>
{
public:
co_spawn_cancellation_handler(const Handler&, const Executor&)
{
}
cancellation_slot slot()
{
return signal_.slot();
}
void operator()(cancellation_type_t type)
{
signal_.emit(type);
}
private:
cancellation_signal signal_;
};
template <typename Executor>
class initiate_co_spawn
{
public:
typedef Executor executor_type;
template <typename OtherExecutor>
explicit initiate_co_spawn(const OtherExecutor& ex)
: ex_(ex)
{
}
executor_type get_executor() const noexcept
{
return ex_;
}
template <typename Handler, typename F>
void operator()(Handler&& handler, F&& f) const
{
typedef result_of_t<F()> awaitable_type;
typedef decay_t<Handler> handler_type;
typedef decay_t<F> function_type;
typedef co_spawn_cancellation_handler<
handler_type, Executor> cancel_handler_type;
auto slot = asio::get_associated_cancellation_slot(handler);
cancel_handler_type* cancel_handler = slot.is_connected()
? &slot.template emplace<cancel_handler_type>(handler, ex_)
: nullptr;
cancellation_slot proxy_slot(
cancel_handler
? cancel_handler->slot()
: cancellation_slot());
cancellation_state cancel_state(proxy_slot);
auto a = (co_spawn_entry_point)(static_cast<awaitable_type*>(nullptr),
co_spawn_state<handler_type, Executor, function_type>(
std::forward<Handler>(handler), ex_, std::forward<F>(f)));
awaitable_handler<executor_type, void>(std::move(a),
ex_, proxy_slot, cancel_state).launch();
}
private:
Executor ex_;
};
} // namespace detail
template <typename Executor, typename T, typename AwaitableExecutor,
ASIO_COMPLETION_TOKEN_FOR(
void(std::exception_ptr, T)) CompletionToken>
inline ASIO_INITFN_AUTO_RESULT_TYPE(
CompletionToken, void(std::exception_ptr, T))
co_spawn(const Executor& ex,
awaitable<T, AwaitableExecutor> a, CompletionToken&& token,
constraint_t<
(is_executor<Executor>::value || execution::is_executor<Executor>::value)
&& is_convertible<Executor, AwaitableExecutor>::value
>)
{
return async_initiate<CompletionToken, void(std::exception_ptr, T)>(
detail::initiate_co_spawn<AwaitableExecutor>(AwaitableExecutor(ex)),
token, detail::awaitable_as_function<T, AwaitableExecutor>(std::move(a)));
}
template <typename Executor, typename AwaitableExecutor,
ASIO_COMPLETION_TOKEN_FOR(
void(std::exception_ptr)) CompletionToken>
inline ASIO_INITFN_AUTO_RESULT_TYPE(
CompletionToken, void(std::exception_ptr))
co_spawn(const Executor& ex,
awaitable<void, AwaitableExecutor> a, CompletionToken&& token,
constraint_t<
(is_executor<Executor>::value || execution::is_executor<Executor>::value)
&& is_convertible<Executor, AwaitableExecutor>::value
>)
{
return async_initiate<CompletionToken, void(std::exception_ptr)>(
detail::initiate_co_spawn<AwaitableExecutor>(AwaitableExecutor(ex)),
token, detail::awaitable_as_function<
void, AwaitableExecutor>(std::move(a)));
}
template <typename ExecutionContext, typename T, typename AwaitableExecutor,
ASIO_COMPLETION_TOKEN_FOR(
void(std::exception_ptr, T)) CompletionToken>
inline ASIO_INITFN_AUTO_RESULT_TYPE(
CompletionToken, void(std::exception_ptr, T))
co_spawn(ExecutionContext& ctx,
awaitable<T, AwaitableExecutor> a, CompletionToken&& token,
constraint_t<
is_convertible<ExecutionContext&, execution_context&>::value
&& is_convertible<typename ExecutionContext::executor_type,
AwaitableExecutor>::value
>)
{
return (co_spawn)(ctx.get_executor(), std::move(a),
std::forward<CompletionToken>(token));
}
template <typename ExecutionContext, typename AwaitableExecutor,
ASIO_COMPLETION_TOKEN_FOR(
void(std::exception_ptr)) CompletionToken>
inline ASIO_INITFN_AUTO_RESULT_TYPE(
CompletionToken, void(std::exception_ptr))
co_spawn(ExecutionContext& ctx,
awaitable<void, AwaitableExecutor> a, CompletionToken&& token,
constraint_t<
is_convertible<ExecutionContext&, execution_context&>::value
&& is_convertible<typename ExecutionContext::executor_type,
AwaitableExecutor>::value
>)
{
return (co_spawn)(ctx.get_executor(), std::move(a),
std::forward<CompletionToken>(token));
}
template <typename Executor, typename F,
ASIO_COMPLETION_TOKEN_FOR(typename detail::awaitable_signature<
result_of_t<F()>>::type) CompletionToken>
inline ASIO_INITFN_AUTO_RESULT_TYPE(CompletionToken,
typename detail::awaitable_signature<result_of_t<F()>>::type)
co_spawn(const Executor& ex, F&& f, CompletionToken&& token,
constraint_t<
is_executor<Executor>::value || execution::is_executor<Executor>::value
>)
{
return async_initiate<CompletionToken,
typename detail::awaitable_signature<result_of_t<F()>>::type>(
detail::initiate_co_spawn<
typename result_of_t<F()>::executor_type>(ex),
token, std::forward<F>(f));
}
template <typename ExecutionContext, typename F,
ASIO_COMPLETION_TOKEN_FOR(typename detail::awaitable_signature<
result_of_t<F()>>::type) CompletionToken>
inline ASIO_INITFN_AUTO_RESULT_TYPE(CompletionToken,
typename detail::awaitable_signature<result_of_t<F()>>::type)
co_spawn(ExecutionContext& ctx, F&& f, CompletionToken&& token,
constraint_t<
is_convertible<ExecutionContext&, execution_context&>::value
>)
{
return (co_spawn)(ctx.get_executor(), std::forward<F>(f),
std::forward<CompletionToken>(token));
}
} // namespace asio
#include "asio/detail/pop_options.hpp"
#endif // ASIO_IMPL_CO_SPAWN_HPP
|
0 | repos/asio/asio/include/asio | repos/asio/asio/include/asio/impl/write.hpp | //
// impl/write.hpp
// ~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef ASIO_IMPL_WRITE_HPP
#define ASIO_IMPL_WRITE_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include "asio/associator.hpp"
#include "asio/buffer.hpp"
#include "asio/detail/array_fwd.hpp"
#include "asio/detail/base_from_cancellation_state.hpp"
#include "asio/detail/base_from_completion_cond.hpp"
#include "asio/detail/bind_handler.hpp"
#include "asio/detail/consuming_buffers.hpp"
#include "asio/detail/dependent_type.hpp"
#include "asio/detail/handler_cont_helpers.hpp"
#include "asio/detail/handler_tracking.hpp"
#include "asio/detail/handler_type_requirements.hpp"
#include "asio/detail/non_const_lvalue.hpp"
#include "asio/detail/throw_error.hpp"
#include "asio/detail/push_options.hpp"
namespace asio {
namespace detail
{
template <typename SyncWriteStream, typename ConstBufferSequence,
typename ConstBufferIterator, typename CompletionCondition>
std::size_t write(SyncWriteStream& s,
const ConstBufferSequence& buffers, const ConstBufferIterator&,
CompletionCondition completion_condition, asio::error_code& ec)
{
ec = asio::error_code();
asio::detail::consuming_buffers<const_buffer,
ConstBufferSequence, ConstBufferIterator> tmp(buffers);
while (!tmp.empty())
{
if (std::size_t max_size = detail::adapt_completion_condition_result(
completion_condition(ec, tmp.total_consumed())))
tmp.consume(s.write_some(tmp.prepare(max_size), ec));
else
break;
}
return tmp.total_consumed();
}
} // namespace detail
template <typename SyncWriteStream, typename ConstBufferSequence,
typename CompletionCondition>
inline std::size_t write(SyncWriteStream& s, const ConstBufferSequence& buffers,
CompletionCondition completion_condition, asio::error_code& ec,
constraint_t<
is_const_buffer_sequence<ConstBufferSequence>::value
>,
constraint_t<
is_completion_condition<CompletionCondition>::value
>)
{
return detail::write(s, buffers,
asio::buffer_sequence_begin(buffers),
static_cast<CompletionCondition&&>(completion_condition), ec);
}
template <typename SyncWriteStream, typename ConstBufferSequence>
inline std::size_t write(SyncWriteStream& s, const ConstBufferSequence& buffers,
constraint_t<
is_const_buffer_sequence<ConstBufferSequence>::value
>)
{
asio::error_code ec;
std::size_t bytes_transferred = write(s, buffers, transfer_all(), ec);
asio::detail::throw_error(ec, "write");
return bytes_transferred;
}
template <typename SyncWriteStream, typename ConstBufferSequence>
inline std::size_t write(SyncWriteStream& s, const ConstBufferSequence& buffers,
asio::error_code& ec,
constraint_t<
is_const_buffer_sequence<ConstBufferSequence>::value
>)
{
return write(s, buffers, transfer_all(), ec);
}
template <typename SyncWriteStream, typename ConstBufferSequence,
typename CompletionCondition>
inline std::size_t write(SyncWriteStream& s, const ConstBufferSequence& buffers,
CompletionCondition completion_condition,
constraint_t<
is_const_buffer_sequence<ConstBufferSequence>::value
>,
constraint_t<
is_completion_condition<CompletionCondition>::value
>)
{
asio::error_code ec;
std::size_t bytes_transferred = write(s, buffers,
static_cast<CompletionCondition&&>(completion_condition), ec);
asio::detail::throw_error(ec, "write");
return bytes_transferred;
}
#if !defined(ASIO_NO_DYNAMIC_BUFFER_V1)
template <typename SyncWriteStream, typename DynamicBuffer_v1,
typename CompletionCondition>
std::size_t write(SyncWriteStream& s,
DynamicBuffer_v1&& buffers,
CompletionCondition completion_condition, asio::error_code& ec,
constraint_t<
is_dynamic_buffer_v1<decay_t<DynamicBuffer_v1>>::value
>,
constraint_t<
!is_dynamic_buffer_v2<decay_t<DynamicBuffer_v1>>::value
>,
constraint_t<
is_completion_condition<CompletionCondition>::value
>)
{
decay_t<DynamicBuffer_v1> b(
static_cast<DynamicBuffer_v1&&>(buffers));
std::size_t bytes_transferred = write(s, b.data(),
static_cast<CompletionCondition&&>(completion_condition), ec);
b.consume(bytes_transferred);
return bytes_transferred;
}
template <typename SyncWriteStream, typename DynamicBuffer_v1>
inline std::size_t write(SyncWriteStream& s,
DynamicBuffer_v1&& buffers,
constraint_t<
is_dynamic_buffer_v1<decay_t<DynamicBuffer_v1>>::value
>,
constraint_t<
!is_dynamic_buffer_v2<decay_t<DynamicBuffer_v1>>::value
>)
{
asio::error_code ec;
std::size_t bytes_transferred = write(s,
static_cast<DynamicBuffer_v1&&>(buffers),
transfer_all(), ec);
asio::detail::throw_error(ec, "write");
return bytes_transferred;
}
template <typename SyncWriteStream, typename DynamicBuffer_v1>
inline std::size_t write(SyncWriteStream& s,
DynamicBuffer_v1&& buffers,
asio::error_code& ec,
constraint_t<
is_dynamic_buffer_v1<decay_t<DynamicBuffer_v1>>::value
>,
constraint_t<
!is_dynamic_buffer_v2<decay_t<DynamicBuffer_v1>>::value
>)
{
return write(s, static_cast<DynamicBuffer_v1&&>(buffers),
transfer_all(), ec);
}
template <typename SyncWriteStream, typename DynamicBuffer_v1,
typename CompletionCondition>
inline std::size_t write(SyncWriteStream& s,
DynamicBuffer_v1&& buffers,
CompletionCondition completion_condition,
constraint_t<
is_dynamic_buffer_v1<decay_t<DynamicBuffer_v1>>::value
>,
constraint_t<
!is_dynamic_buffer_v2<decay_t<DynamicBuffer_v1>>::value
>,
constraint_t<
is_completion_condition<CompletionCondition>::value
>)
{
asio::error_code ec;
std::size_t bytes_transferred = write(s,
static_cast<DynamicBuffer_v1&&>(buffers),
static_cast<CompletionCondition&&>(completion_condition), ec);
asio::detail::throw_error(ec, "write");
return bytes_transferred;
}
#if !defined(ASIO_NO_EXTENSIONS)
#if !defined(ASIO_NO_IOSTREAM)
template <typename SyncWriteStream, typename Allocator,
typename CompletionCondition>
inline std::size_t write(SyncWriteStream& s,
asio::basic_streambuf<Allocator>& b,
CompletionCondition completion_condition, asio::error_code& ec,
constraint_t<
is_completion_condition<CompletionCondition>::value
>)
{
return write(s, basic_streambuf_ref<Allocator>(b),
static_cast<CompletionCondition&&>(completion_condition), ec);
}
template <typename SyncWriteStream, typename Allocator>
inline std::size_t write(SyncWriteStream& s,
asio::basic_streambuf<Allocator>& b)
{
return write(s, basic_streambuf_ref<Allocator>(b));
}
template <typename SyncWriteStream, typename Allocator>
inline std::size_t write(SyncWriteStream& s,
asio::basic_streambuf<Allocator>& b,
asio::error_code& ec)
{
return write(s, basic_streambuf_ref<Allocator>(b), ec);
}
template <typename SyncWriteStream, typename Allocator,
typename CompletionCondition>
inline std::size_t write(SyncWriteStream& s,
asio::basic_streambuf<Allocator>& b,
CompletionCondition completion_condition,
constraint_t<
is_completion_condition<CompletionCondition>::value
>)
{
return write(s, basic_streambuf_ref<Allocator>(b),
static_cast<CompletionCondition&&>(completion_condition));
}
#endif // !defined(ASIO_NO_IOSTREAM)
#endif // !defined(ASIO_NO_EXTENSIONS)
#endif // !defined(ASIO_NO_DYNAMIC_BUFFER_V1)
template <typename SyncWriteStream, typename DynamicBuffer_v2,
typename CompletionCondition>
std::size_t write(SyncWriteStream& s, DynamicBuffer_v2 buffers,
CompletionCondition completion_condition, asio::error_code& ec,
constraint_t<
is_dynamic_buffer_v2<DynamicBuffer_v2>::value
>,
constraint_t<
is_completion_condition<CompletionCondition>::value
>)
{
std::size_t bytes_transferred = write(s, buffers.data(0, buffers.size()),
static_cast<CompletionCondition&&>(completion_condition), ec);
buffers.consume(bytes_transferred);
return bytes_transferred;
}
template <typename SyncWriteStream, typename DynamicBuffer_v2>
inline std::size_t write(SyncWriteStream& s, DynamicBuffer_v2 buffers,
constraint_t<
is_dynamic_buffer_v2<DynamicBuffer_v2>::value
>)
{
asio::error_code ec;
std::size_t bytes_transferred = write(s,
static_cast<DynamicBuffer_v2&&>(buffers),
transfer_all(), ec);
asio::detail::throw_error(ec, "write");
return bytes_transferred;
}
template <typename SyncWriteStream, typename DynamicBuffer_v2>
inline std::size_t write(SyncWriteStream& s, DynamicBuffer_v2 buffers,
asio::error_code& ec,
constraint_t<
is_dynamic_buffer_v2<DynamicBuffer_v2>::value
>)
{
return write(s, static_cast<DynamicBuffer_v2&&>(buffers),
transfer_all(), ec);
}
template <typename SyncWriteStream, typename DynamicBuffer_v2,
typename CompletionCondition>
inline std::size_t write(SyncWriteStream& s, DynamicBuffer_v2 buffers,
CompletionCondition completion_condition,
constraint_t<
is_dynamic_buffer_v2<DynamicBuffer_v2>::value
>,
constraint_t<
is_completion_condition<CompletionCondition>::value
>)
{
asio::error_code ec;
std::size_t bytes_transferred = write(s,
static_cast<DynamicBuffer_v2&&>(buffers),
static_cast<CompletionCondition&&>(completion_condition), ec);
asio::detail::throw_error(ec, "write");
return bytes_transferred;
}
namespace detail
{
template <typename AsyncWriteStream, typename ConstBufferSequence,
typename ConstBufferIterator, typename CompletionCondition,
typename WriteHandler>
class write_op
: public base_from_cancellation_state<WriteHandler>,
base_from_completion_cond<CompletionCondition>
{
public:
write_op(AsyncWriteStream& stream, const ConstBufferSequence& buffers,
CompletionCondition& completion_condition, WriteHandler& handler)
: base_from_cancellation_state<WriteHandler>(
handler, enable_partial_cancellation()),
base_from_completion_cond<CompletionCondition>(completion_condition),
stream_(stream),
buffers_(buffers),
start_(0),
handler_(static_cast<WriteHandler&&>(handler))
{
}
write_op(const write_op& other)
: base_from_cancellation_state<WriteHandler>(other),
base_from_completion_cond<CompletionCondition>(other),
stream_(other.stream_),
buffers_(other.buffers_),
start_(other.start_),
handler_(other.handler_)
{
}
write_op(write_op&& other)
: base_from_cancellation_state<WriteHandler>(
static_cast<base_from_cancellation_state<WriteHandler>&&>(other)),
base_from_completion_cond<CompletionCondition>(
static_cast<base_from_completion_cond<CompletionCondition>&&>(other)),
stream_(other.stream_),
buffers_(static_cast<buffers_type&&>(other.buffers_)),
start_(other.start_),
handler_(static_cast<WriteHandler&&>(other.handler_))
{
}
void operator()(asio::error_code ec,
std::size_t bytes_transferred, int start = 0)
{
std::size_t max_size;
switch (start_ = start)
{
case 1:
max_size = this->check_for_completion(ec, buffers_.total_consumed());
for (;;)
{
{
ASIO_HANDLER_LOCATION((__FILE__, __LINE__, "async_write"));
stream_.async_write_some(buffers_.prepare(max_size),
static_cast<write_op&&>(*this));
}
return; default:
buffers_.consume(bytes_transferred);
if ((!ec && bytes_transferred == 0) || buffers_.empty())
break;
max_size = this->check_for_completion(ec, buffers_.total_consumed());
if (max_size == 0)
break;
if (this->cancelled() != cancellation_type::none)
{
ec = error::operation_aborted;
break;
}
}
static_cast<WriteHandler&&>(handler_)(
static_cast<const asio::error_code&>(ec),
static_cast<const std::size_t&>(buffers_.total_consumed()));
}
}
//private:
typedef asio::detail::consuming_buffers<const_buffer,
ConstBufferSequence, ConstBufferIterator> buffers_type;
AsyncWriteStream& stream_;
buffers_type buffers_;
int start_;
WriteHandler handler_;
};
template <typename AsyncWriteStream, typename ConstBufferSequence,
typename ConstBufferIterator, typename CompletionCondition,
typename WriteHandler>
inline bool asio_handler_is_continuation(
write_op<AsyncWriteStream, ConstBufferSequence, ConstBufferIterator,
CompletionCondition, WriteHandler>* this_handler)
{
return this_handler->start_ == 0 ? true
: asio_handler_cont_helpers::is_continuation(
this_handler->handler_);
}
template <typename AsyncWriteStream, typename ConstBufferSequence,
typename ConstBufferIterator, typename CompletionCondition,
typename WriteHandler>
inline void start_write_op(AsyncWriteStream& stream,
const ConstBufferSequence& buffers, const ConstBufferIterator&,
CompletionCondition& completion_condition, WriteHandler& handler)
{
detail::write_op<AsyncWriteStream, ConstBufferSequence,
ConstBufferIterator, CompletionCondition, WriteHandler>(
stream, buffers, completion_condition, handler)(
asio::error_code(), 0, 1);
}
template <typename AsyncWriteStream>
class initiate_async_write
{
public:
typedef typename AsyncWriteStream::executor_type executor_type;
explicit initiate_async_write(AsyncWriteStream& stream)
: stream_(stream)
{
}
executor_type get_executor() const noexcept
{
return stream_.get_executor();
}
template <typename WriteHandler, typename ConstBufferSequence,
typename CompletionCondition>
void operator()(WriteHandler&& handler,
const ConstBufferSequence& buffers,
CompletionCondition&& completion_cond) const
{
// If you get an error on the following line it means that your handler
// does not meet the documented type requirements for a WriteHandler.
ASIO_WRITE_HANDLER_CHECK(WriteHandler, handler) type_check;
non_const_lvalue<WriteHandler> handler2(handler);
non_const_lvalue<CompletionCondition> completion_cond2(completion_cond);
start_write_op(stream_, buffers,
asio::buffer_sequence_begin(buffers),
completion_cond2.value, handler2.value);
}
private:
AsyncWriteStream& stream_;
};
} // namespace detail
#if !defined(GENERATING_DOCUMENTATION)
template <template <typename, typename> class Associator,
typename AsyncWriteStream, typename ConstBufferSequence,
typename ConstBufferIterator, typename CompletionCondition,
typename WriteHandler, typename DefaultCandidate>
struct associator<Associator,
detail::write_op<AsyncWriteStream, ConstBufferSequence,
ConstBufferIterator, CompletionCondition, WriteHandler>,
DefaultCandidate>
: Associator<WriteHandler, DefaultCandidate>
{
static typename Associator<WriteHandler, DefaultCandidate>::type get(
const detail::write_op<AsyncWriteStream, ConstBufferSequence,
ConstBufferIterator, CompletionCondition, WriteHandler>& h) noexcept
{
return Associator<WriteHandler, DefaultCandidate>::get(h.handler_);
}
static auto get(
const detail::write_op<AsyncWriteStream, ConstBufferSequence,
ConstBufferIterator, CompletionCondition, WriteHandler>& h,
const DefaultCandidate& c) noexcept
-> decltype(Associator<WriteHandler, DefaultCandidate>::get(h.handler_, c))
{
return Associator<WriteHandler, DefaultCandidate>::get(h.handler_, c);
}
};
#endif // !defined(GENERATING_DOCUMENTATION)
#if !defined(ASIO_NO_DYNAMIC_BUFFER_V1)
namespace detail
{
template <typename AsyncWriteStream, typename DynamicBuffer_v1,
typename CompletionCondition, typename WriteHandler>
class write_dynbuf_v1_op
{
public:
template <typename BufferSequence>
write_dynbuf_v1_op(AsyncWriteStream& stream,
BufferSequence&& buffers,
CompletionCondition& completion_condition, WriteHandler& handler)
: stream_(stream),
buffers_(static_cast<BufferSequence&&>(buffers)),
completion_condition_(
static_cast<CompletionCondition&&>(completion_condition)),
handler_(static_cast<WriteHandler&&>(handler))
{
}
write_dynbuf_v1_op(const write_dynbuf_v1_op& other)
: stream_(other.stream_),
buffers_(other.buffers_),
completion_condition_(other.completion_condition_),
handler_(other.handler_)
{
}
write_dynbuf_v1_op(write_dynbuf_v1_op&& other)
: stream_(other.stream_),
buffers_(static_cast<DynamicBuffer_v1&&>(other.buffers_)),
completion_condition_(
static_cast<CompletionCondition&&>(
other.completion_condition_)),
handler_(static_cast<WriteHandler&&>(other.handler_))
{
}
void operator()(const asio::error_code& ec,
std::size_t bytes_transferred, int start = 0)
{
switch (start)
{
case 1:
async_write(stream_, buffers_.data(),
static_cast<CompletionCondition&&>(completion_condition_),
static_cast<write_dynbuf_v1_op&&>(*this));
return; default:
buffers_.consume(bytes_transferred);
static_cast<WriteHandler&&>(handler_)(ec,
static_cast<const std::size_t&>(bytes_transferred));
}
}
//private:
AsyncWriteStream& stream_;
DynamicBuffer_v1 buffers_;
CompletionCondition completion_condition_;
WriteHandler handler_;
};
template <typename AsyncWriteStream, typename DynamicBuffer_v1,
typename CompletionCondition, typename WriteHandler>
inline bool asio_handler_is_continuation(
write_dynbuf_v1_op<AsyncWriteStream, DynamicBuffer_v1,
CompletionCondition, WriteHandler>* this_handler)
{
return asio_handler_cont_helpers::is_continuation(
this_handler->handler_);
}
template <typename AsyncWriteStream>
class initiate_async_write_dynbuf_v1
{
public:
typedef typename AsyncWriteStream::executor_type executor_type;
explicit initiate_async_write_dynbuf_v1(AsyncWriteStream& stream)
: stream_(stream)
{
}
executor_type get_executor() const noexcept
{
return stream_.get_executor();
}
template <typename WriteHandler, typename DynamicBuffer_v1,
typename CompletionCondition>
void operator()(WriteHandler&& handler,
DynamicBuffer_v1&& buffers,
CompletionCondition&& completion_cond) const
{
// If you get an error on the following line it means that your handler
// does not meet the documented type requirements for a WriteHandler.
ASIO_WRITE_HANDLER_CHECK(WriteHandler, handler) type_check;
non_const_lvalue<WriteHandler> handler2(handler);
non_const_lvalue<CompletionCondition> completion_cond2(completion_cond);
write_dynbuf_v1_op<AsyncWriteStream,
decay_t<DynamicBuffer_v1>,
CompletionCondition, decay_t<WriteHandler>>(
stream_, static_cast<DynamicBuffer_v1&&>(buffers),
completion_cond2.value, handler2.value)(
asio::error_code(), 0, 1);
}
private:
AsyncWriteStream& stream_;
};
} // namespace detail
#if !defined(GENERATING_DOCUMENTATION)
template <template <typename, typename> class Associator,
typename AsyncWriteStream, typename DynamicBuffer_v1,
typename CompletionCondition, typename WriteHandler,
typename DefaultCandidate>
struct associator<Associator,
detail::write_dynbuf_v1_op<AsyncWriteStream,
DynamicBuffer_v1, CompletionCondition, WriteHandler>,
DefaultCandidate>
: Associator<WriteHandler, DefaultCandidate>
{
static typename Associator<WriteHandler, DefaultCandidate>::type get(
const detail::write_dynbuf_v1_op<AsyncWriteStream, DynamicBuffer_v1,
CompletionCondition, WriteHandler>& h) noexcept
{
return Associator<WriteHandler, DefaultCandidate>::get(h.handler_);
}
static auto get(
const detail::write_dynbuf_v1_op<AsyncWriteStream,
DynamicBuffer_v1, CompletionCondition, WriteHandler>& h,
const DefaultCandidate& c) noexcept
-> decltype(Associator<WriteHandler, DefaultCandidate>::get(h.handler_, c))
{
return Associator<WriteHandler, DefaultCandidate>::get(h.handler_, c);
}
};
#endif // !defined(GENERATING_DOCUMENTATION)
#endif // !defined(ASIO_NO_DYNAMIC_BUFFER_V1)
namespace detail
{
template <typename AsyncWriteStream, typename DynamicBuffer_v2,
typename CompletionCondition, typename WriteHandler>
class write_dynbuf_v2_op
{
public:
template <typename BufferSequence>
write_dynbuf_v2_op(AsyncWriteStream& stream,
BufferSequence&& buffers,
CompletionCondition& completion_condition, WriteHandler& handler)
: stream_(stream),
buffers_(static_cast<BufferSequence&&>(buffers)),
completion_condition_(
static_cast<CompletionCondition&&>(completion_condition)),
handler_(static_cast<WriteHandler&&>(handler))
{
}
write_dynbuf_v2_op(const write_dynbuf_v2_op& other)
: stream_(other.stream_),
buffers_(other.buffers_),
completion_condition_(other.completion_condition_),
handler_(other.handler_)
{
}
write_dynbuf_v2_op(write_dynbuf_v2_op&& other)
: stream_(other.stream_),
buffers_(static_cast<DynamicBuffer_v2&&>(other.buffers_)),
completion_condition_(
static_cast<CompletionCondition&&>(
other.completion_condition_)),
handler_(static_cast<WriteHandler&&>(other.handler_))
{
}
void operator()(const asio::error_code& ec,
std::size_t bytes_transferred, int start = 0)
{
switch (start)
{
case 1:
async_write(stream_, buffers_.data(0, buffers_.size()),
static_cast<CompletionCondition&&>(completion_condition_),
static_cast<write_dynbuf_v2_op&&>(*this));
return; default:
buffers_.consume(bytes_transferred);
static_cast<WriteHandler&&>(handler_)(ec,
static_cast<const std::size_t&>(bytes_transferred));
}
}
//private:
AsyncWriteStream& stream_;
DynamicBuffer_v2 buffers_;
CompletionCondition completion_condition_;
WriteHandler handler_;
};
template <typename AsyncWriteStream, typename DynamicBuffer_v2,
typename CompletionCondition, typename WriteHandler>
inline bool asio_handler_is_continuation(
write_dynbuf_v2_op<AsyncWriteStream, DynamicBuffer_v2,
CompletionCondition, WriteHandler>* this_handler)
{
return asio_handler_cont_helpers::is_continuation(
this_handler->handler_);
}
template <typename AsyncWriteStream>
class initiate_async_write_dynbuf_v2
{
public:
typedef typename AsyncWriteStream::executor_type executor_type;
explicit initiate_async_write_dynbuf_v2(AsyncWriteStream& stream)
: stream_(stream)
{
}
executor_type get_executor() const noexcept
{
return stream_.get_executor();
}
template <typename WriteHandler, typename DynamicBuffer_v2,
typename CompletionCondition>
void operator()(WriteHandler&& handler,
DynamicBuffer_v2&& buffers,
CompletionCondition&& completion_cond) const
{
// If you get an error on the following line it means that your handler
// does not meet the documented type requirements for a WriteHandler.
ASIO_WRITE_HANDLER_CHECK(WriteHandler, handler) type_check;
non_const_lvalue<WriteHandler> handler2(handler);
non_const_lvalue<CompletionCondition> completion_cond2(completion_cond);
write_dynbuf_v2_op<AsyncWriteStream, decay_t<DynamicBuffer_v2>,
CompletionCondition, decay_t<WriteHandler>>(
stream_, static_cast<DynamicBuffer_v2&&>(buffers),
completion_cond2.value, handler2.value)(
asio::error_code(), 0, 1);
}
private:
AsyncWriteStream& stream_;
};
} // namespace detail
#if !defined(GENERATING_DOCUMENTATION)
template <template <typename, typename> class Associator,
typename AsyncWriteStream, typename DynamicBuffer_v2,
typename CompletionCondition, typename WriteHandler,
typename DefaultCandidate>
struct associator<Associator,
detail::write_dynbuf_v2_op<AsyncWriteStream,
DynamicBuffer_v2, CompletionCondition, WriteHandler>,
DefaultCandidate>
: Associator<WriteHandler, DefaultCandidate>
{
static typename Associator<WriteHandler, DefaultCandidate>::type get(
const detail::write_dynbuf_v2_op<AsyncWriteStream, DynamicBuffer_v2,
CompletionCondition, WriteHandler>& h) noexcept
{
return Associator<WriteHandler, DefaultCandidate>::get(h.handler_);
}
static auto get(
const detail::write_dynbuf_v2_op<AsyncWriteStream,
DynamicBuffer_v2, CompletionCondition, WriteHandler>& h,
const DefaultCandidate& c) noexcept
-> decltype(Associator<WriteHandler, DefaultCandidate>::get(h.handler_, c))
{
return Associator<WriteHandler, DefaultCandidate>::get(h.handler_, c);
}
};
#endif // !defined(GENERATING_DOCUMENTATION)
} // namespace asio
#include "asio/detail/pop_options.hpp"
#endif // ASIO_IMPL_WRITE_HPP
|
0 | repos/asio/asio/include/asio | repos/asio/asio/include/asio/impl/use_awaitable.hpp | //
// impl/use_awaitable.hpp
// ~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef ASIO_IMPL_USE_AWAITABLE_HPP
#define ASIO_IMPL_USE_AWAITABLE_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include "asio/detail/config.hpp"
#include "asio/async_result.hpp"
#include "asio/cancellation_signal.hpp"
#include "asio/detail/push_options.hpp"
namespace asio {
namespace detail {
template <typename Executor, typename T>
class awaitable_handler_base
: public awaitable_thread<Executor>
{
public:
typedef void result_type;
typedef awaitable<T, Executor> awaitable_type;
// Construct from the entry point of a new thread of execution.
awaitable_handler_base(awaitable<awaitable_thread_entry_point, Executor> a,
const Executor& ex, cancellation_slot pcs, cancellation_state cs)
: awaitable_thread<Executor>(std::move(a), ex, pcs, cs)
{
}
// Transfer ownership from another awaitable_thread.
explicit awaitable_handler_base(awaitable_thread<Executor>* h)
: awaitable_thread<Executor>(std::move(*h))
{
}
protected:
awaitable_frame<T, Executor>* frame() noexcept
{
return static_cast<awaitable_frame<T, Executor>*>(
this->entry_point()->top_of_stack_);
}
};
template <typename, typename...>
class awaitable_handler;
template <typename Executor>
class awaitable_handler<Executor>
: public awaitable_handler_base<Executor, void>
{
public:
using awaitable_handler_base<Executor, void>::awaitable_handler_base;
void operator()()
{
this->frame()->attach_thread(this);
this->frame()->return_void();
this->frame()->clear_cancellation_slot();
this->frame()->pop_frame();
this->pump();
}
};
template <typename Executor>
class awaitable_handler<Executor, asio::error_code>
: public awaitable_handler_base<Executor, void>
{
public:
using awaitable_handler_base<Executor, void>::awaitable_handler_base;
void operator()(const asio::error_code& ec)
{
this->frame()->attach_thread(this);
if (ec)
this->frame()->set_error(ec);
else
this->frame()->return_void();
this->frame()->clear_cancellation_slot();
this->frame()->pop_frame();
this->pump();
}
};
template <typename Executor>
class awaitable_handler<Executor, std::exception_ptr>
: public awaitable_handler_base<Executor, void>
{
public:
using awaitable_handler_base<Executor, void>::awaitable_handler_base;
void operator()(std::exception_ptr ex)
{
this->frame()->attach_thread(this);
if (ex)
this->frame()->set_except(ex);
else
this->frame()->return_void();
this->frame()->clear_cancellation_slot();
this->frame()->pop_frame();
this->pump();
}
};
template <typename Executor, typename T>
class awaitable_handler<Executor, T>
: public awaitable_handler_base<Executor, T>
{
public:
using awaitable_handler_base<Executor, T>::awaitable_handler_base;
template <typename Arg>
void operator()(Arg&& arg)
{
this->frame()->attach_thread(this);
this->frame()->return_value(std::forward<Arg>(arg));
this->frame()->clear_cancellation_slot();
this->frame()->pop_frame();
this->pump();
}
};
template <typename Executor, typename T>
class awaitable_handler<Executor, asio::error_code, T>
: public awaitable_handler_base<Executor, T>
{
public:
using awaitable_handler_base<Executor, T>::awaitable_handler_base;
template <typename Arg>
void operator()(const asio::error_code& ec, Arg&& arg)
{
this->frame()->attach_thread(this);
if (ec)
this->frame()->set_error(ec);
else
this->frame()->return_value(std::forward<Arg>(arg));
this->frame()->clear_cancellation_slot();
this->frame()->pop_frame();
this->pump();
}
};
template <typename Executor, typename T>
class awaitable_handler<Executor, std::exception_ptr, T>
: public awaitable_handler_base<Executor, T>
{
public:
using awaitable_handler_base<Executor, T>::awaitable_handler_base;
template <typename Arg>
void operator()(std::exception_ptr ex, Arg&& arg)
{
this->frame()->attach_thread(this);
if (ex)
this->frame()->set_except(ex);
else
this->frame()->return_value(std::forward<Arg>(arg));
this->frame()->clear_cancellation_slot();
this->frame()->pop_frame();
this->pump();
}
};
template <typename Executor, typename... Ts>
class awaitable_handler
: public awaitable_handler_base<Executor, std::tuple<Ts...>>
{
public:
using awaitable_handler_base<Executor,
std::tuple<Ts...>>::awaitable_handler_base;
template <typename... Args>
void operator()(Args&&... args)
{
this->frame()->attach_thread(this);
this->frame()->return_values(std::forward<Args>(args)...);
this->frame()->clear_cancellation_slot();
this->frame()->pop_frame();
this->pump();
}
};
template <typename Executor, typename... Ts>
class awaitable_handler<Executor, asio::error_code, Ts...>
: public awaitable_handler_base<Executor, std::tuple<Ts...>>
{
public:
using awaitable_handler_base<Executor,
std::tuple<Ts...>>::awaitable_handler_base;
template <typename... Args>
void operator()(const asio::error_code& ec, Args&&... args)
{
this->frame()->attach_thread(this);
if (ec)
this->frame()->set_error(ec);
else
this->frame()->return_values(std::forward<Args>(args)...);
this->frame()->clear_cancellation_slot();
this->frame()->pop_frame();
this->pump();
}
};
template <typename Executor, typename... Ts>
class awaitable_handler<Executor, std::exception_ptr, Ts...>
: public awaitable_handler_base<Executor, std::tuple<Ts...>>
{
public:
using awaitable_handler_base<Executor,
std::tuple<Ts...>>::awaitable_handler_base;
template <typename... Args>
void operator()(std::exception_ptr ex, Args&&... args)
{
this->frame()->attach_thread(this);
if (ex)
this->frame()->set_except(ex);
else
this->frame()->return_values(std::forward<Args>(args)...);
this->frame()->clear_cancellation_slot();
this->frame()->pop_frame();
this->pump();
}
};
} // namespace detail
#if !defined(GENERATING_DOCUMENTATION)
#if defined(_MSC_VER)
template <typename T>
T dummy_return()
{
return std::move(*static_cast<T*>(nullptr));
}
template <>
inline void dummy_return()
{
}
#endif // defined(_MSC_VER)
template <typename Executor, typename R, typename... Args>
class async_result<use_awaitable_t<Executor>, R(Args...)>
{
public:
typedef typename detail::awaitable_handler<
Executor, decay_t<Args>...> handler_type;
typedef typename handler_type::awaitable_type return_type;
template <typename Initiation, typename... InitArgs>
#if defined(__APPLE_CC__) && (__clang_major__ == 13)
__attribute__((noinline))
#endif // defined(__APPLE_CC__) && (__clang_major__ == 13)
static handler_type* do_init(
detail::awaitable_frame_base<Executor>* frame, Initiation& initiation,
use_awaitable_t<Executor> u, InitArgs&... args)
{
(void)u;
ASIO_HANDLER_LOCATION((u.file_name_, u.line_, u.function_name_));
handler_type handler(frame->detach_thread());
std::move(initiation)(std::move(handler), std::move(args)...);
return nullptr;
}
template <typename Initiation, typename... InitArgs>
static return_type initiate(Initiation initiation,
use_awaitable_t<Executor> u, InitArgs... args)
{
co_await [&] (auto* frame)
{
return do_init(frame, initiation, u, args...);
};
for (;;) {} // Never reached.
#if defined(_MSC_VER)
co_return dummy_return<typename return_type::value_type>();
#endif // defined(_MSC_VER)
}
};
#endif // !defined(GENERATING_DOCUMENTATION)
} // namespace asio
#include "asio/detail/pop_options.hpp"
#endif // ASIO_IMPL_USE_AWAITABLE_HPP
|
0 | repos/asio/asio/include/asio | repos/asio/asio/include/asio/impl/prepend.hpp | //
// impl/prepend.hpp
// ~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef ASIO_IMPL_PREPEND_HPP
#define ASIO_IMPL_PREPEND_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include "asio/detail/config.hpp"
#include "asio/associator.hpp"
#include "asio/async_result.hpp"
#include "asio/detail/handler_cont_helpers.hpp"
#include "asio/detail/initiation_base.hpp"
#include "asio/detail/type_traits.hpp"
#include "asio/detail/utility.hpp"
#include "asio/detail/push_options.hpp"
namespace asio {
namespace detail {
// Class to adapt a prepend_t as a completion handler.
template <typename Handler, typename... Values>
class prepend_handler
{
public:
typedef void result_type;
template <typename H>
prepend_handler(H&& handler, std::tuple<Values...> values)
: handler_(static_cast<H&&>(handler)),
values_(static_cast<std::tuple<Values...>&&>(values))
{
}
template <typename... Args>
void operator()(Args&&... args)
{
this->invoke(
index_sequence_for<Values...>{},
static_cast<Args&&>(args)...);
}
template <std::size_t... I, typename... Args>
void invoke(index_sequence<I...>, Args&&... args)
{
static_cast<Handler&&>(handler_)(
static_cast<Values&&>(std::get<I>(values_))...,
static_cast<Args&&>(args)...);
}
//private:
Handler handler_;
std::tuple<Values...> values_;
};
template <typename Handler>
inline bool asio_handler_is_continuation(
prepend_handler<Handler>* this_handler)
{
return asio_handler_cont_helpers::is_continuation(
this_handler->handler_);
}
template <typename Signature, typename... Values>
struct prepend_signature;
template <typename R, typename... Args, typename... Values>
struct prepend_signature<R(Args...), Values...>
{
typedef R type(Values..., decay_t<Args>...);
};
} // namespace detail
#if !defined(GENERATING_DOCUMENTATION)
template <typename CompletionToken, typename... Values, typename Signature>
struct async_result<
prepend_t<CompletionToken, Values...>, Signature>
: async_result<CompletionToken,
typename detail::prepend_signature<
Signature, Values...>::type>
{
typedef typename detail::prepend_signature<
Signature, Values...>::type signature;
template <typename Initiation>
struct init_wrapper : detail::initiation_base<Initiation>
{
using detail::initiation_base<Initiation>::initiation_base;
template <typename Handler, typename... Args>
void operator()(Handler&& handler,
std::tuple<Values...> values, Args&&... args) &&
{
static_cast<Initiation&&>(*this)(
detail::prepend_handler<decay_t<Handler>, Values...>(
static_cast<Handler&&>(handler),
static_cast<std::tuple<Values...>&&>(values)),
static_cast<Args&&>(args)...);
}
template <typename Handler, typename... Args>
void operator()(Handler&& handler,
std::tuple<Values...> values, Args&&... args) const &
{
static_cast<const Initiation&>(*this)(
detail::prepend_handler<decay_t<Handler>, Values...>(
static_cast<Handler&&>(handler),
static_cast<std::tuple<Values...>&&>(values)),
static_cast<Args&&>(args)...);
}
};
template <typename Initiation, typename RawCompletionToken, typename... Args>
static auto initiate(Initiation&& initiation,
RawCompletionToken&& token, Args&&... args)
-> decltype(
async_initiate<CompletionToken, signature>(
declval<init_wrapper<decay_t<Initiation>>>(),
token.token_,
static_cast<std::tuple<Values...>&&>(token.values_),
static_cast<Args&&>(args)...))
{
return async_initiate<CompletionToken, signature>(
init_wrapper<decay_t<Initiation>>(
static_cast<Initiation&&>(initiation)),
token.token_,
static_cast<std::tuple<Values...>&&>(token.values_),
static_cast<Args&&>(args)...);
}
};
template <template <typename, typename> class Associator,
typename Handler, typename... Values, typename DefaultCandidate>
struct associator<Associator,
detail::prepend_handler<Handler, Values...>, DefaultCandidate>
: Associator<Handler, DefaultCandidate>
{
static typename Associator<Handler, DefaultCandidate>::type get(
const detail::prepend_handler<Handler, Values...>& h) noexcept
{
return Associator<Handler, DefaultCandidate>::get(h.handler_);
}
static auto get(const detail::prepend_handler<Handler, Values...>& 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)
} // namespace asio
#include "asio/detail/pop_options.hpp"
#endif // ASIO_IMPL_PREPEND_HPP
|
0 | repos/asio/asio/include/asio | repos/asio/asio/include/asio/impl/executor.ipp | //
// impl/executor.ipp
// ~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef ASIO_IMPL_EXECUTOR_IPP
#define ASIO_IMPL_EXECUTOR_IPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include "asio/detail/config.hpp"
#if !defined(ASIO_NO_TS_EXECUTORS)
#include "asio/executor.hpp"
#include "asio/detail/push_options.hpp"
namespace asio {
bad_executor::bad_executor() noexcept
{
}
const char* bad_executor::what() const noexcept
{
return "bad executor";
}
} // namespace asio
#include "asio/detail/pop_options.hpp"
#endif // !defined(ASIO_NO_TS_EXECUTORS)
#endif // ASIO_IMPL_EXECUTOR_IPP
|
0 | repos/asio/asio/include/asio | repos/asio/asio/include/asio/impl/any_completion_executor.ipp | //
// impl/any_completion_executor.ipp
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef ASIO_IMPL_ANY_COMPLETION_EXECUTOR_IPP
#define ASIO_IMPL_ANY_COMPLETION_EXECUTOR_IPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include "asio/detail/config.hpp"
#if !defined(ASIO_USE_TS_EXECUTOR_AS_DEFAULT)
#include "asio/any_completion_executor.hpp"
#include "asio/detail/push_options.hpp"
namespace asio {
any_completion_executor::any_completion_executor() noexcept
: base_type()
{
}
any_completion_executor::any_completion_executor(nullptr_t) noexcept
: base_type(nullptr_t())
{
}
any_completion_executor::any_completion_executor(
const any_completion_executor& e) noexcept
: base_type(static_cast<const base_type&>(e))
{
}
any_completion_executor::any_completion_executor(std::nothrow_t,
const any_completion_executor& e) noexcept
: base_type(static_cast<const base_type&>(e))
{
}
any_completion_executor::any_completion_executor(
any_completion_executor&& e) noexcept
: base_type(static_cast<base_type&&>(e))
{
}
any_completion_executor::any_completion_executor(std::nothrow_t,
any_completion_executor&& e) noexcept
: base_type(static_cast<base_type&&>(e))
{
}
any_completion_executor& any_completion_executor::operator=(
const any_completion_executor& e) noexcept
{
base_type::operator=(static_cast<const base_type&>(e));
return *this;
}
any_completion_executor& any_completion_executor::operator=(
any_completion_executor&& e) noexcept
{
base_type::operator=(static_cast<base_type&&>(e));
return *this;
}
any_completion_executor& any_completion_executor::operator=(nullptr_t)
{
base_type::operator=(nullptr_t());
return *this;
}
any_completion_executor::~any_completion_executor()
{
}
void any_completion_executor::swap(
any_completion_executor& other) noexcept
{
static_cast<base_type&>(*this).swap(static_cast<base_type&>(other));
}
template <>
any_completion_executor any_completion_executor::prefer(
const execution::outstanding_work_t::tracked_t& p, int) const
{
return static_cast<const base_type&>(*this).prefer(p);
}
template <>
any_completion_executor any_completion_executor::prefer(
const execution::outstanding_work_t::untracked_t& p, int) const
{
return static_cast<const base_type&>(*this).prefer(p);
}
template <>
any_completion_executor any_completion_executor::prefer(
const execution::relationship_t::fork_t& p, int) const
{
return static_cast<const base_type&>(*this).prefer(p);
}
template <>
any_completion_executor any_completion_executor::prefer(
const execution::relationship_t::continuation_t& p, int) const
{
return static_cast<const base_type&>(*this).prefer(p);
}
} // namespace asio
#include "asio/detail/pop_options.hpp"
#endif // !defined(ASIO_USE_TS_EXECUTOR_AS_DEFAULT)
#endif // ASIO_IMPL_ANY_COMPLETION_EXECUTOR_IPP
|
0 | repos/asio/asio/include/asio | repos/asio/asio/include/asio/impl/spawn.hpp | //
// impl/spawn.hpp
// ~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef ASIO_IMPL_SPAWN_HPP
#define ASIO_IMPL_SPAWN_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include "asio/detail/config.hpp"
#include <tuple>
#include "asio/associated_allocator.hpp"
#include "asio/associated_cancellation_slot.hpp"
#include "asio/associated_executor.hpp"
#include "asio/async_result.hpp"
#include "asio/bind_executor.hpp"
#include "asio/detail/atomic_count.hpp"
#include "asio/detail/bind_handler.hpp"
#include "asio/detail/handler_cont_helpers.hpp"
#include "asio/detail/memory.hpp"
#include "asio/detail/noncopyable.hpp"
#include "asio/detail/type_traits.hpp"
#include "asio/detail/utility.hpp"
#include "asio/error.hpp"
#include "asio/system_error.hpp"
#if defined(ASIO_HAS_BOOST_CONTEXT_FIBER)
# include <boost/context/fiber.hpp>
#endif // defined(ASIO_HAS_BOOST_CONTEXT_FIBER)
#include "asio/detail/push_options.hpp"
namespace asio {
namespace detail {
#if !defined(ASIO_NO_EXCEPTIONS)
inline void spawned_thread_rethrow(void* ex)
{
if (*static_cast<exception_ptr*>(ex))
rethrow_exception(*static_cast<exception_ptr*>(ex));
}
#endif // !defined(ASIO_NO_EXCEPTIONS)
#if defined(ASIO_HAS_BOOST_COROUTINE)
// Spawned thread implementation using Boost.Coroutine.
class spawned_coroutine_thread : public spawned_thread_base
{
public:
#if defined(BOOST_COROUTINES_UNIDIRECT) || defined(BOOST_COROUTINES_V2)
typedef boost::coroutines::pull_coroutine<void> callee_type;
typedef boost::coroutines::push_coroutine<void> caller_type;
#else
typedef boost::coroutines::coroutine<void()> callee_type;
typedef boost::coroutines::coroutine<void()> caller_type;
#endif
spawned_coroutine_thread(caller_type& caller)
: caller_(caller),
on_suspend_fn_(0),
on_suspend_arg_(0)
{
}
template <typename F>
static spawned_thread_base* spawn(F&& f,
const boost::coroutines::attributes& attributes,
cancellation_slot parent_cancel_slot = cancellation_slot(),
cancellation_state cancel_state = cancellation_state())
{
spawned_coroutine_thread* spawned_thread = 0;
callee_type callee(entry_point<decay_t<F>>(
static_cast<F&&>(f), &spawned_thread), attributes);
spawned_thread->callee_.swap(callee);
spawned_thread->parent_cancellation_slot_ = parent_cancel_slot;
spawned_thread->cancellation_state_ = cancel_state;
return spawned_thread;
}
template <typename F>
static spawned_thread_base* spawn(F&& f,
cancellation_slot parent_cancel_slot = cancellation_slot(),
cancellation_state cancel_state = cancellation_state())
{
return spawn(static_cast<F&&>(f), boost::coroutines::attributes(),
parent_cancel_slot, cancel_state);
}
void resume()
{
callee_();
if (on_suspend_fn_)
{
void (*fn)(void*) = on_suspend_fn_;
void* arg = on_suspend_arg_;
on_suspend_fn_ = 0;
fn(arg);
}
}
void suspend_with(void (*fn)(void*), void* arg)
{
if (throw_if_cancelled_)
if (!!cancellation_state_.cancelled())
throw_error(asio::error::operation_aborted, "yield");
has_context_switched_ = true;
on_suspend_fn_ = fn;
on_suspend_arg_ = arg;
caller_();
}
void destroy()
{
callee_type callee;
callee.swap(callee_);
if (terminal_)
callee();
}
private:
template <typename Function>
class entry_point
{
public:
template <typename F>
entry_point(F&& f,
spawned_coroutine_thread** spawned_thread_out)
: function_(static_cast<F&&>(f)),
spawned_thread_out_(spawned_thread_out)
{
}
void operator()(caller_type& caller)
{
Function function(static_cast<Function&&>(function_));
spawned_coroutine_thread spawned_thread(caller);
*spawned_thread_out_ = &spawned_thread;
spawned_thread_out_ = 0;
spawned_thread.suspend();
#if !defined(ASIO_NO_EXCEPTIONS)
try
#endif // !defined(ASIO_NO_EXCEPTIONS)
{
function(&spawned_thread);
spawned_thread.terminal_ = true;
spawned_thread.suspend();
}
#if !defined(ASIO_NO_EXCEPTIONS)
catch (const boost::coroutines::detail::forced_unwind&)
{
throw;
}
catch (...)
{
exception_ptr ex = current_exception();
spawned_thread.terminal_ = true;
spawned_thread.suspend_with(spawned_thread_rethrow, &ex);
}
#endif // !defined(ASIO_NO_EXCEPTIONS)
}
private:
Function function_;
spawned_coroutine_thread** spawned_thread_out_;
};
caller_type& caller_;
callee_type callee_;
void (*on_suspend_fn_)(void*);
void* on_suspend_arg_;
};
#endif // defined(ASIO_HAS_BOOST_COROUTINE)
#if defined(ASIO_HAS_BOOST_CONTEXT_FIBER)
// Spawned thread implementation using Boost.Context's fiber.
class spawned_fiber_thread : public spawned_thread_base
{
public:
typedef boost::context::fiber fiber_type;
spawned_fiber_thread(fiber_type&& caller)
: caller_(static_cast<fiber_type&&>(caller)),
on_suspend_fn_(0),
on_suspend_arg_(0)
{
}
template <typename StackAllocator, typename F>
static spawned_thread_base* spawn(allocator_arg_t,
StackAllocator&& stack_allocator,
F&& f,
cancellation_slot parent_cancel_slot = cancellation_slot(),
cancellation_state cancel_state = cancellation_state())
{
spawned_fiber_thread* spawned_thread = 0;
fiber_type callee(allocator_arg_t(),
static_cast<StackAllocator&&>(stack_allocator),
entry_point<decay_t<F>>(
static_cast<F&&>(f), &spawned_thread));
callee = fiber_type(static_cast<fiber_type&&>(callee)).resume();
spawned_thread->callee_ = static_cast<fiber_type&&>(callee);
spawned_thread->parent_cancellation_slot_ = parent_cancel_slot;
spawned_thread->cancellation_state_ = cancel_state;
return spawned_thread;
}
template <typename F>
static spawned_thread_base* spawn(F&& f,
cancellation_slot parent_cancel_slot = cancellation_slot(),
cancellation_state cancel_state = cancellation_state())
{
return spawn(allocator_arg_t(), boost::context::fixedsize_stack(),
static_cast<F&&>(f), parent_cancel_slot, cancel_state);
}
void resume()
{
callee_ = fiber_type(static_cast<fiber_type&&>(callee_)).resume();
if (on_suspend_fn_)
{
void (*fn)(void*) = on_suspend_fn_;
void* arg = on_suspend_arg_;
on_suspend_fn_ = 0;
fn(arg);
}
}
void suspend_with(void (*fn)(void*), void* arg)
{
if (throw_if_cancelled_)
if (!!cancellation_state_.cancelled())
throw_error(asio::error::operation_aborted, "yield");
has_context_switched_ = true;
on_suspend_fn_ = fn;
on_suspend_arg_ = arg;
caller_ = fiber_type(static_cast<fiber_type&&>(caller_)).resume();
}
void destroy()
{
fiber_type callee = static_cast<fiber_type&&>(callee_);
if (terminal_)
fiber_type(static_cast<fiber_type&&>(callee)).resume();
}
private:
template <typename Function>
class entry_point
{
public:
template <typename F>
entry_point(F&& f,
spawned_fiber_thread** spawned_thread_out)
: function_(static_cast<F&&>(f)),
spawned_thread_out_(spawned_thread_out)
{
}
fiber_type operator()(fiber_type&& caller)
{
Function function(static_cast<Function&&>(function_));
spawned_fiber_thread spawned_thread(
static_cast<fiber_type&&>(caller));
*spawned_thread_out_ = &spawned_thread;
spawned_thread_out_ = 0;
spawned_thread.suspend();
#if !defined(ASIO_NO_EXCEPTIONS)
try
#endif // !defined(ASIO_NO_EXCEPTIONS)
{
function(&spawned_thread);
spawned_thread.terminal_ = true;
spawned_thread.suspend();
}
#if !defined(ASIO_NO_EXCEPTIONS)
catch (const boost::context::detail::forced_unwind&)
{
throw;
}
catch (...)
{
exception_ptr ex = current_exception();
spawned_thread.terminal_ = true;
spawned_thread.suspend_with(spawned_thread_rethrow, &ex);
}
#endif // !defined(ASIO_NO_EXCEPTIONS)
return static_cast<fiber_type&&>(spawned_thread.caller_);
}
private:
Function function_;
spawned_fiber_thread** spawned_thread_out_;
};
fiber_type caller_;
fiber_type callee_;
void (*on_suspend_fn_)(void*);
void* on_suspend_arg_;
};
#endif // defined(ASIO_HAS_BOOST_CONTEXT_FIBER)
#if defined(ASIO_HAS_BOOST_CONTEXT_FIBER)
typedef spawned_fiber_thread default_spawned_thread_type;
#elif defined(ASIO_HAS_BOOST_COROUTINE)
typedef spawned_coroutine_thread default_spawned_thread_type;
#else
# error No spawn() implementation available
#endif
// Helper class to perform the initial resume on the correct executor.
class spawned_thread_resumer
{
public:
explicit spawned_thread_resumer(spawned_thread_base* spawned_thread)
: spawned_thread_(spawned_thread)
{
}
spawned_thread_resumer(spawned_thread_resumer&& other) noexcept
: spawned_thread_(other.spawned_thread_)
{
other.spawned_thread_ = 0;
}
~spawned_thread_resumer()
{
if (spawned_thread_)
spawned_thread_->destroy();
}
void operator()()
{
spawned_thread_->attach(&spawned_thread_);
spawned_thread_->resume();
}
private:
spawned_thread_base* spawned_thread_;
};
// Helper class to ensure spawned threads are destroyed on the correct executor.
class spawned_thread_destroyer
{
public:
explicit spawned_thread_destroyer(spawned_thread_base* spawned_thread)
: spawned_thread_(spawned_thread)
{
spawned_thread->detach();
}
spawned_thread_destroyer(spawned_thread_destroyer&& other) noexcept
: spawned_thread_(other.spawned_thread_)
{
other.spawned_thread_ = 0;
}
~spawned_thread_destroyer()
{
if (spawned_thread_)
spawned_thread_->destroy();
}
void operator()()
{
if (spawned_thread_)
{
spawned_thread_->destroy();
spawned_thread_ = 0;
}
}
private:
spawned_thread_base* spawned_thread_;
};
// Base class for all completion handlers associated with a spawned thread.
template <typename Executor>
class spawn_handler_base
{
public:
typedef Executor executor_type;
typedef cancellation_slot cancellation_slot_type;
spawn_handler_base(const basic_yield_context<Executor>& yield)
: yield_(yield),
spawned_thread_(yield.spawned_thread_)
{
spawned_thread_->detach();
}
spawn_handler_base(spawn_handler_base&& other) noexcept
: yield_(other.yield_),
spawned_thread_(other.spawned_thread_)
{
other.spawned_thread_ = 0;
}
~spawn_handler_base()
{
if (spawned_thread_)
(post)(yield_.executor_, spawned_thread_destroyer(spawned_thread_));
}
executor_type get_executor() const noexcept
{
return yield_.executor_;
}
cancellation_slot_type get_cancellation_slot() const noexcept
{
return spawned_thread_->get_cancellation_slot();
}
void resume()
{
spawned_thread_resumer resumer(spawned_thread_);
spawned_thread_ = 0;
resumer();
}
protected:
const basic_yield_context<Executor>& yield_;
spawned_thread_base* spawned_thread_;
};
// Completion handlers for when basic_yield_context is used as a token.
template <typename Executor, typename Signature>
class spawn_handler;
template <typename Executor, typename R>
class spawn_handler<Executor, R()>
: public spawn_handler_base<Executor>
{
public:
typedef void return_type;
struct result_type {};
spawn_handler(const basic_yield_context<Executor>& yield, result_type&)
: spawn_handler_base<Executor>(yield)
{
}
void operator()()
{
this->resume();
}
static return_type on_resume(result_type&)
{
}
};
template <typename Executor, typename R>
class spawn_handler<Executor, R(asio::error_code)>
: public spawn_handler_base<Executor>
{
public:
typedef void return_type;
typedef asio::error_code* result_type;
spawn_handler(const basic_yield_context<Executor>& yield, result_type& result)
: spawn_handler_base<Executor>(yield),
result_(result)
{
}
void operator()(asio::error_code ec)
{
if (this->yield_.ec_)
{
*this->yield_.ec_ = ec;
result_ = 0;
}
else
result_ = &ec;
this->resume();
}
static return_type on_resume(result_type& result)
{
if (result)
throw_error(*result);
}
private:
result_type& result_;
};
template <typename Executor, typename R>
class spawn_handler<Executor, R(exception_ptr)>
: public spawn_handler_base<Executor>
{
public:
typedef void return_type;
typedef exception_ptr* result_type;
spawn_handler(const basic_yield_context<Executor>& yield, result_type& result)
: spawn_handler_base<Executor>(yield),
result_(result)
{
}
void operator()(exception_ptr ex)
{
result_ = &ex;
this->resume();
}
static return_type on_resume(result_type& result)
{
if (*result)
rethrow_exception(*result);
}
private:
result_type& result_;
};
template <typename Executor, typename R, typename T>
class spawn_handler<Executor, R(T)>
: public spawn_handler_base<Executor>
{
public:
typedef T return_type;
typedef return_type* result_type;
spawn_handler(const basic_yield_context<Executor>& yield, result_type& result)
: spawn_handler_base<Executor>(yield),
result_(result)
{
}
void operator()(T value)
{
result_ = &value;
this->resume();
}
static return_type on_resume(result_type& result)
{
return static_cast<return_type&&>(*result);
}
private:
result_type& result_;
};
template <typename Executor, typename R, typename T>
class spawn_handler<Executor, R(asio::error_code, T)>
: public spawn_handler_base<Executor>
{
public:
typedef T return_type;
struct result_type
{
asio::error_code* ec_;
return_type* value_;
};
spawn_handler(const basic_yield_context<Executor>& yield, result_type& result)
: spawn_handler_base<Executor>(yield),
result_(result)
{
}
void operator()(asio::error_code ec, T value)
{
if (this->yield_.ec_)
{
*this->yield_.ec_ = ec;
result_.ec_ = 0;
}
else
result_.ec_ = &ec;
result_.value_ = &value;
this->resume();
}
static return_type on_resume(result_type& result)
{
if (result.ec_)
throw_error(*result.ec_);
return static_cast<return_type&&>(*result.value_);
}
private:
result_type& result_;
};
template <typename Executor, typename R, typename T>
class spawn_handler<Executor, R(exception_ptr, T)>
: public spawn_handler_base<Executor>
{
public:
typedef T return_type;
struct result_type
{
exception_ptr* ex_;
return_type* value_;
};
spawn_handler(const basic_yield_context<Executor>& yield, result_type& result)
: spawn_handler_base<Executor>(yield),
result_(result)
{
}
void operator()(exception_ptr ex, T value)
{
result_.ex_ = &ex;
result_.value_ = &value;
this->resume();
}
static return_type on_resume(result_type& result)
{
if (*result.ex_)
rethrow_exception(*result.ex_);
return static_cast<return_type&&>(*result.value_);
}
private:
result_type& result_;
};
template <typename Executor, typename R, typename... Ts>
class spawn_handler<Executor, R(Ts...)>
: public spawn_handler_base<Executor>
{
public:
typedef std::tuple<Ts...> return_type;
typedef return_type* result_type;
spawn_handler(const basic_yield_context<Executor>& yield, result_type& result)
: spawn_handler_base<Executor>(yield),
result_(result)
{
}
template <typename... Args>
void operator()(Args&&... args)
{
return_type value(static_cast<Args&&>(args)...);
result_ = &value;
this->resume();
}
static return_type on_resume(result_type& result)
{
return static_cast<return_type&&>(*result);
}
private:
result_type& result_;
};
template <typename Executor, typename R, typename... Ts>
class spawn_handler<Executor, R(asio::error_code, Ts...)>
: public spawn_handler_base<Executor>
{
public:
typedef std::tuple<Ts...> return_type;
struct result_type
{
asio::error_code* ec_;
return_type* value_;
};
spawn_handler(const basic_yield_context<Executor>& yield, result_type& result)
: spawn_handler_base<Executor>(yield),
result_(result)
{
}
template <typename... Args>
void operator()(asio::error_code ec,
Args&&... args)
{
return_type value(static_cast<Args&&>(args)...);
if (this->yield_.ec_)
{
*this->yield_.ec_ = ec;
result_.ec_ = 0;
}
else
result_.ec_ = &ec;
result_.value_ = &value;
this->resume();
}
static return_type on_resume(result_type& result)
{
if (result.ec_)
throw_error(*result.ec_);
return static_cast<return_type&&>(*result.value_);
}
private:
result_type& result_;
};
template <typename Executor, typename R, typename... Ts>
class spawn_handler<Executor, R(exception_ptr, Ts...)>
: public spawn_handler_base<Executor>
{
public:
typedef std::tuple<Ts...> return_type;
struct result_type
{
exception_ptr* ex_;
return_type* value_;
};
spawn_handler(const basic_yield_context<Executor>& yield, result_type& result)
: spawn_handler_base<Executor>(yield),
result_(result)
{
}
template <typename... Args>
void operator()(exception_ptr ex, Args&&... args)
{
return_type value(static_cast<Args&&>(args)...);
result_.ex_ = &ex;
result_.value_ = &value;
this->resume();
}
static return_type on_resume(result_type& result)
{
if (*result.ex_)
rethrow_exception(*result.ex_);
return static_cast<return_type&&>(*result.value_);
}
private:
result_type& result_;
};
template <typename Executor, typename Signature>
inline bool asio_handler_is_continuation(spawn_handler<Executor, Signature>*)
{
return true;
}
} // namespace detail
template <typename Executor, typename Signature>
class async_result<basic_yield_context<Executor>, Signature>
{
public:
typedef typename detail::spawn_handler<Executor, Signature> handler_type;
typedef typename handler_type::return_type return_type;
#if defined(ASIO_HAS_VARIADIC_LAMBDA_CAPTURES)
template <typename Initiation, typename... InitArgs>
static return_type initiate(Initiation&& init,
const basic_yield_context<Executor>& yield,
InitArgs&&... init_args)
{
typename handler_type::result_type result
= typename handler_type::result_type();
yield.spawned_thread_->suspend_with(
[&]()
{
static_cast<Initiation&&>(init)(
handler_type(yield, result),
static_cast<InitArgs&&>(init_args)...);
});
return handler_type::on_resume(result);
}
#else // defined(ASIO_HAS_VARIADIC_LAMBDA_CAPTURES)
template <typename Initiation, typename... InitArgs>
struct suspend_with_helper
{
typename handler_type::result_type& result_;
Initiation&& init_;
const basic_yield_context<Executor>& yield_;
std::tuple<InitArgs&&...> init_args_;
template <std::size_t... I>
void do_invoke(detail::index_sequence<I...>)
{
static_cast<Initiation&&>(init_)(
handler_type(yield_, result_),
static_cast<InitArgs&&>(std::get<I>(init_args_))...);
}
void operator()()
{
this->do_invoke(detail::make_index_sequence<sizeof...(InitArgs)>());
}
};
template <typename Initiation, typename... InitArgs>
static return_type initiate(Initiation&& init,
const basic_yield_context<Executor>& yield,
InitArgs&&... init_args)
{
typename handler_type::result_type result
= typename handler_type::result_type();
yield.spawned_thread_->suspend_with(
suspend_with_helper<Initiation, InitArgs...>{
result, static_cast<Initiation&&>(init), yield,
std::tuple<InitArgs&&...>(
static_cast<InitArgs&&>(init_args)...)});
return handler_type::on_resume(result);
}
#endif // defined(ASIO_HAS_VARIADIC_LAMBDA_CAPTURES)
};
namespace detail {
template <typename Executor, typename Function, typename Handler>
class spawn_entry_point
{
public:
template <typename F, typename H>
spawn_entry_point(const Executor& ex,
F&& f, H&& h)
: executor_(ex),
function_(static_cast<F&&>(f)),
handler_(static_cast<H&&>(h)),
work_(handler_, executor_)
{
}
void operator()(spawned_thread_base* spawned_thread)
{
const basic_yield_context<Executor> yield(spawned_thread, executor_);
this->call(yield,
void_type<result_of_t<Function(basic_yield_context<Executor>)>>());
}
private:
void call(const basic_yield_context<Executor>& yield, void_type<void>)
{
#if !defined(ASIO_NO_EXCEPTIONS)
try
#endif // !defined(ASIO_NO_EXCEPTIONS)
{
function_(yield);
if (!yield.spawned_thread_->has_context_switched())
(post)(yield);
detail::binder1<Handler, exception_ptr>
handler(handler_, exception_ptr());
work_.complete(handler, handler.handler_);
}
#if !defined(ASIO_NO_EXCEPTIONS)
# if defined(ASIO_HAS_BOOST_CONTEXT_FIBER)
catch (const boost::context::detail::forced_unwind&)
{
throw;
}
# endif // defined(ASIO_HAS_BOOST_CONTEXT_FIBER)
# if defined(ASIO_HAS_BOOST_COROUTINE)
catch (const boost::coroutines::detail::forced_unwind&)
{
throw;
}
# endif // defined(ASIO_HAS_BOOST_COROUTINE)
catch (...)
{
exception_ptr ex = current_exception();
if (!yield.spawned_thread_->has_context_switched())
(post)(yield);
detail::binder1<Handler, exception_ptr> handler(handler_, ex);
work_.complete(handler, handler.handler_);
}
#endif // !defined(ASIO_NO_EXCEPTIONS)
}
template <typename T>
void call(const basic_yield_context<Executor>& yield, void_type<T>)
{
#if !defined(ASIO_NO_EXCEPTIONS)
try
#endif // !defined(ASIO_NO_EXCEPTIONS)
{
T result(function_(yield));
if (!yield.spawned_thread_->has_context_switched())
(post)(yield);
detail::binder2<Handler, exception_ptr, T>
handler(handler_, exception_ptr(), static_cast<T&&>(result));
work_.complete(handler, handler.handler_);
}
#if !defined(ASIO_NO_EXCEPTIONS)
# if defined(ASIO_HAS_BOOST_CONTEXT_FIBER)
catch (const boost::context::detail::forced_unwind&)
{
throw;
}
# endif // defined(ASIO_HAS_BOOST_CONTEXT_FIBER)
# if defined(ASIO_HAS_BOOST_COROUTINE)
catch (const boost::coroutines::detail::forced_unwind&)
{
throw;
}
# endif // defined(ASIO_HAS_BOOST_COROUTINE)
catch (...)
{
exception_ptr ex = current_exception();
if (!yield.spawned_thread_->has_context_switched())
(post)(yield);
detail::binder2<Handler, exception_ptr, T> handler(handler_, ex, T());
work_.complete(handler, handler.handler_);
}
#endif // !defined(ASIO_NO_EXCEPTIONS)
}
Executor executor_;
Function function_;
Handler handler_;
handler_work<Handler, Executor> work_;
};
struct spawn_cancellation_signal_emitter
{
cancellation_signal* signal_;
cancellation_type_t type_;
void operator()()
{
signal_->emit(type_);
}
};
template <typename Handler, typename Executor, typename = void>
class spawn_cancellation_handler
{
public:
spawn_cancellation_handler(const Handler&, const Executor& ex)
: ex_(ex)
{
}
cancellation_slot slot()
{
return signal_.slot();
}
void operator()(cancellation_type_t type)
{
spawn_cancellation_signal_emitter emitter = { &signal_, type };
(dispatch)(ex_, emitter);
}
private:
cancellation_signal signal_;
Executor ex_;
};
template <typename Handler, typename Executor>
class spawn_cancellation_handler<Handler, Executor,
enable_if_t<
is_same<
typename associated_executor<Handler,
Executor>::asio_associated_executor_is_unspecialised,
void
>::value
>>
{
public:
spawn_cancellation_handler(const Handler&, const Executor&)
{
}
cancellation_slot slot()
{
return signal_.slot();
}
void operator()(cancellation_type_t type)
{
signal_.emit(type);
}
private:
cancellation_signal signal_;
};
template <typename Executor>
class initiate_spawn
{
public:
typedef Executor executor_type;
explicit initiate_spawn(const executor_type& ex)
: executor_(ex)
{
}
executor_type get_executor() const noexcept
{
return executor_;
}
template <typename Handler, typename F>
void operator()(Handler&& handler,
F&& f) const
{
typedef decay_t<Handler> handler_type;
typedef decay_t<F> function_type;
typedef spawn_cancellation_handler<
handler_type, Executor> cancel_handler_type;
associated_cancellation_slot_t<handler_type> slot
= asio::get_associated_cancellation_slot(handler);
cancel_handler_type* cancel_handler = slot.is_connected()
? &slot.template emplace<cancel_handler_type>(handler, executor_)
: 0;
cancellation_slot proxy_slot(
cancel_handler
? cancel_handler->slot()
: cancellation_slot());
cancellation_state cancel_state(proxy_slot);
(dispatch)(executor_,
spawned_thread_resumer(
default_spawned_thread_type::spawn(
spawn_entry_point<Executor, function_type, handler_type>(
executor_, static_cast<F&&>(f),
static_cast<Handler&&>(handler)),
proxy_slot, cancel_state)));
}
#if defined(ASIO_HAS_BOOST_CONTEXT_FIBER)
template <typename Handler, typename StackAllocator, typename F>
void operator()(Handler&& handler, allocator_arg_t,
StackAllocator&& stack_allocator,
F&& f) const
{
typedef decay_t<Handler> handler_type;
typedef decay_t<F> function_type;
typedef spawn_cancellation_handler<
handler_type, Executor> cancel_handler_type;
associated_cancellation_slot_t<handler_type> slot
= asio::get_associated_cancellation_slot(handler);
cancel_handler_type* cancel_handler = slot.is_connected()
? &slot.template emplace<cancel_handler_type>(handler, executor_)
: 0;
cancellation_slot proxy_slot(
cancel_handler
? cancel_handler->slot()
: cancellation_slot());
cancellation_state cancel_state(proxy_slot);
(dispatch)(executor_,
spawned_thread_resumer(
spawned_fiber_thread::spawn(allocator_arg_t(),
static_cast<StackAllocator&&>(stack_allocator),
spawn_entry_point<Executor, function_type, handler_type>(
executor_, static_cast<F&&>(f),
static_cast<Handler&&>(handler)),
proxy_slot, cancel_state)));
}
#endif // defined(ASIO_HAS_BOOST_CONTEXT_FIBER)
private:
executor_type executor_;
};
} // namespace detail
template <typename Executor, typename F,
ASIO_COMPLETION_TOKEN_FOR(typename detail::spawn_signature<
result_of_t<F(basic_yield_context<Executor>)>>::type) CompletionToken>
inline auto spawn(const Executor& ex, F&& function, CompletionToken&& token,
#if defined(ASIO_HAS_BOOST_COROUTINE)
constraint_t<
!is_same<
decay_t<CompletionToken>,
boost::coroutines::attributes
>::value
>,
#endif // defined(ASIO_HAS_BOOST_COROUTINE)
constraint_t<
is_executor<Executor>::value || execution::is_executor<Executor>::value
>)
-> decltype(
async_initiate<CompletionToken,
typename detail::spawn_signature<
result_of_t<F(basic_yield_context<Executor>)>>::type>(
declval<detail::initiate_spawn<Executor>>(),
token, static_cast<F&&>(function)))
{
return async_initiate<CompletionToken,
typename detail::spawn_signature<
result_of_t<F(basic_yield_context<Executor>)>>::type>(
detail::initiate_spawn<Executor>(ex),
token, static_cast<F&&>(function));
}
template <typename ExecutionContext, typename F,
ASIO_COMPLETION_TOKEN_FOR(typename detail::spawn_signature<
result_of_t<F(basic_yield_context<
typename ExecutionContext::executor_type>)>>::type) CompletionToken>
inline auto spawn(ExecutionContext& ctx, F&& function, CompletionToken&& token,
#if defined(ASIO_HAS_BOOST_COROUTINE)
constraint_t<
!is_same<
decay_t<CompletionToken>,
boost::coroutines::attributes
>::value
>,
#endif // defined(ASIO_HAS_BOOST_COROUTINE)
constraint_t<
is_convertible<ExecutionContext&, execution_context&>::value
>)
-> decltype(
async_initiate<CompletionToken,
typename detail::spawn_signature<
result_of_t<F(basic_yield_context<
typename ExecutionContext::executor_type>)>>::type>(
declval<detail::initiate_spawn<
typename ExecutionContext::executor_type>>(),
token, static_cast<F&&>(function)))
{
return (spawn)(ctx.get_executor(), static_cast<F&&>(function),
static_cast<CompletionToken&&>(token));
}
template <typename Executor, typename F,
ASIO_COMPLETION_TOKEN_FOR(typename detail::spawn_signature<
result_of_t<F(basic_yield_context<Executor>)>>::type)
CompletionToken>
inline auto spawn(const basic_yield_context<Executor>& ctx,
F&& function, CompletionToken&& token,
#if defined(ASIO_HAS_BOOST_COROUTINE)
constraint_t<
!is_same<
decay_t<CompletionToken>,
boost::coroutines::attributes
>::value
>,
#endif // defined(ASIO_HAS_BOOST_COROUTINE)
constraint_t<
is_executor<Executor>::value || execution::is_executor<Executor>::value
>)
-> decltype(
async_initiate<CompletionToken,
typename detail::spawn_signature<
result_of_t<F(basic_yield_context<Executor>)>>::type>(
declval<detail::initiate_spawn<Executor>>(),
token, static_cast<F&&>(function)))
{
return (spawn)(ctx.get_executor(), static_cast<F&&>(function),
static_cast<CompletionToken&&>(token));
}
#if defined(ASIO_HAS_BOOST_CONTEXT_FIBER)
template <typename Executor, typename StackAllocator, typename F,
ASIO_COMPLETION_TOKEN_FOR(typename detail::spawn_signature<
result_of_t<F(basic_yield_context<Executor>)>>::type)
CompletionToken>
inline auto spawn(const Executor& ex, allocator_arg_t,
StackAllocator&& stack_allocator, F&& function, CompletionToken&& token,
constraint_t<
is_executor<Executor>::value || execution::is_executor<Executor>::value
>)
-> decltype(
async_initiate<CompletionToken,
typename detail::spawn_signature<
result_of_t<F(basic_yield_context<Executor>)>>::type>(
declval<detail::initiate_spawn<Executor>>(),
token, allocator_arg_t(),
static_cast<StackAllocator&&>(stack_allocator),
static_cast<F&&>(function)))
{
return async_initiate<CompletionToken,
typename detail::spawn_signature<
result_of_t<F(basic_yield_context<Executor>)>>::type>(
detail::initiate_spawn<Executor>(ex), token, allocator_arg_t(),
static_cast<StackAllocator&&>(stack_allocator),
static_cast<F&&>(function));
}
template <typename ExecutionContext, typename StackAllocator, typename F,
ASIO_COMPLETION_TOKEN_FOR(typename detail::spawn_signature<
result_of_t<F(basic_yield_context<
typename ExecutionContext::executor_type>)>>::type) CompletionToken>
inline auto spawn(ExecutionContext& ctx, allocator_arg_t,
StackAllocator&& stack_allocator, F&& function, CompletionToken&& token,
constraint_t<
is_convertible<ExecutionContext&, execution_context&>::value
>)
-> decltype(
async_initiate<CompletionToken,
typename detail::spawn_signature<
result_of_t<F(basic_yield_context<
typename ExecutionContext::executor_type>)>>::type>(
declval<detail::initiate_spawn<
typename ExecutionContext::executor_type>>(),
token, allocator_arg_t(),
static_cast<StackAllocator&&>(stack_allocator),
static_cast<F&&>(function)))
{
return (spawn)(ctx.get_executor(), allocator_arg_t(),
static_cast<StackAllocator&&>(stack_allocator),
static_cast<F&&>(function), static_cast<CompletionToken&&>(token));
}
template <typename Executor, typename StackAllocator, typename F,
ASIO_COMPLETION_TOKEN_FOR(typename detail::spawn_signature<
result_of_t<F(basic_yield_context<Executor>)>>::type) CompletionToken>
inline auto spawn(const basic_yield_context<Executor>& ctx, allocator_arg_t,
StackAllocator&& stack_allocator, F&& function, CompletionToken&& token,
constraint_t<
is_executor<Executor>::value || execution::is_executor<Executor>::value
>)
-> decltype(
async_initiate<CompletionToken,
typename detail::spawn_signature<
result_of_t<F(basic_yield_context<Executor>)>>::type>(
declval<detail::initiate_spawn<Executor>>(), token,
allocator_arg_t(), static_cast<StackAllocator&&>(stack_allocator),
static_cast<F&&>(function)))
{
return (spawn)(ctx.get_executor(), allocator_arg_t(),
static_cast<StackAllocator&&>(stack_allocator),
static_cast<F&&>(function), static_cast<CompletionToken&&>(token));
}
#endif // defined(ASIO_HAS_BOOST_CONTEXT_FIBER)
#if defined(ASIO_HAS_BOOST_COROUTINE)
namespace detail {
template <typename Executor, typename Function, typename Handler>
class old_spawn_entry_point
{
public:
template <typename F, typename H>
old_spawn_entry_point(const Executor& ex, F&& f, H&& h)
: executor_(ex),
function_(static_cast<F&&>(f)),
handler_(static_cast<H&&>(h))
{
}
void operator()(spawned_thread_base* spawned_thread)
{
const basic_yield_context<Executor> yield(spawned_thread, executor_);
this->call(yield,
void_type<result_of_t<Function(basic_yield_context<Executor>)>>());
}
private:
void call(const basic_yield_context<Executor>& yield, void_type<void>)
{
function_(yield);
static_cast<Handler&&>(handler_)();
}
template <typename T>
void call(const basic_yield_context<Executor>& yield, void_type<T>)
{
static_cast<Handler&&>(handler_)(function_(yield));
}
Executor executor_;
Function function_;
Handler handler_;
};
inline void default_spawn_handler() {}
} // namespace detail
template <typename Function>
inline void spawn(Function&& function,
const boost::coroutines::attributes& attributes)
{
associated_executor_t<decay_t<Function>> ex(
(get_associated_executor)(function));
asio::spawn(ex, static_cast<Function&&>(function), attributes);
}
template <typename Handler, typename Function>
void spawn(Handler&& handler, Function&& function,
const boost::coroutines::attributes& attributes,
constraint_t<
!is_executor<decay_t<Handler>>::value &&
!execution::is_executor<decay_t<Handler>>::value &&
!is_convertible<Handler&, execution_context&>::value>)
{
typedef associated_executor_t<decay_t<Handler>> executor_type;
executor_type ex((get_associated_executor)(handler));
(dispatch)(ex,
detail::spawned_thread_resumer(
detail::spawned_coroutine_thread::spawn(
detail::old_spawn_entry_point<executor_type,
decay_t<Function>, void (*)()>(
ex, static_cast<Function&&>(function),
&detail::default_spawn_handler), attributes)));
}
template <typename Executor, typename Function>
void spawn(basic_yield_context<Executor> ctx, Function&& function,
const boost::coroutines::attributes& attributes)
{
(dispatch)(ctx.get_executor(),
detail::spawned_thread_resumer(
detail::spawned_coroutine_thread::spawn(
detail::old_spawn_entry_point<Executor,
decay_t<Function>, void (*)()>(
ctx.get_executor(), static_cast<Function&&>(function),
&detail::default_spawn_handler), attributes)));
}
template <typename Function, typename Executor>
inline void spawn(const Executor& ex, Function&& function,
const boost::coroutines::attributes& attributes,
constraint_t<
is_executor<Executor>::value || execution::is_executor<Executor>::value
>)
{
asio::spawn(asio::strand<Executor>(ex),
static_cast<Function&&>(function), attributes);
}
template <typename Function, typename Executor>
inline void spawn(const strand<Executor>& ex, Function&& function,
const boost::coroutines::attributes& attributes)
{
asio::spawn(asio::bind_executor(
ex, &detail::default_spawn_handler),
static_cast<Function&&>(function), attributes);
}
#if !defined(ASIO_NO_TS_EXECUTORS)
template <typename Function>
inline void spawn(const asio::io_context::strand& s, Function&& function,
const boost::coroutines::attributes& attributes)
{
asio::spawn(asio::bind_executor(
s, &detail::default_spawn_handler),
static_cast<Function&&>(function), attributes);
}
#endif // !defined(ASIO_NO_TS_EXECUTORS)
template <typename Function, typename ExecutionContext>
inline void spawn(ExecutionContext& ctx, Function&& function,
const boost::coroutines::attributes& attributes,
constraint_t<
is_convertible<ExecutionContext&, execution_context&>::value
>)
{
asio::spawn(ctx.get_executor(),
static_cast<Function&&>(function), attributes);
}
#endif // defined(ASIO_HAS_BOOST_COROUTINE)
} // namespace asio
#include "asio/detail/pop_options.hpp"
#endif // ASIO_IMPL_SPAWN_HPP
|
0 | repos/asio/asio/include/asio | repos/asio/asio/include/asio/impl/cancel_at.hpp | //
// impl/cancel_at.hpp
// ~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef ASIO_IMPL_CANCEL_AT_HPP
#define ASIO_IMPL_CANCEL_AT_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include "asio/detail/config.hpp"
#include "asio/associated_executor.hpp"
#include "asio/async_result.hpp"
#include "asio/detail/initiation_base.hpp"
#include "asio/detail/timed_cancel_op.hpp"
#include "asio/detail/push_options.hpp"
namespace asio {
namespace detail {
template <typename Initiation, typename Clock,
typename WaitTraits, typename... Signatures>
struct initiate_cancel_at : initiation_base<Initiation>
{
using initiation_base<Initiation>::initiation_base;
template <typename Handler, typename Duration, typename... Args>
void operator()(Handler&& handler,
const chrono::time_point<Clock, Duration>& expiry,
cancellation_type_t cancel_type, Args&&... args) &&
{
using op = detail::timed_cancel_op<decay_t<Handler>,
basic_waitable_timer<Clock, WaitTraits>, Signatures...>;
non_const_lvalue<Handler> handler2(handler);
typename op::ptr p = { asio::detail::addressof(handler2.value),
op::ptr::allocate(handler2.value), 0 };
p.p = new (p.v) op(handler2.value,
basic_waitable_timer<Clock, WaitTraits,
typename Initiation::executor_type>(this->get_executor(), expiry),
cancel_type);
op* o = p.p;
p.v = p.p = 0;
o->start(static_cast<Initiation&&>(*this), static_cast<Args&&>(args)...);
}
template <typename Handler, typename Duration, typename... Args>
void operator()(Handler&& handler,
const chrono::time_point<Clock, Duration>& expiry,
cancellation_type_t cancel_type, Args&&... args) const &
{
using op = detail::timed_cancel_op<decay_t<Handler>,
basic_waitable_timer<Clock, WaitTraits>, Signatures...>;
non_const_lvalue<Handler> handler2(handler);
typename op::ptr p = { asio::detail::addressof(handler2.value),
op::ptr::allocate(handler2.value), 0 };
p.p = new (p.v) op(handler2.value,
basic_waitable_timer<Clock, WaitTraits,
typename Initiation::executor_type>(this->get_executor(), expiry),
cancel_type);
op* o = p.p;
p.v = p.p = 0;
o->start(static_cast<const Initiation&>(*this),
static_cast<Args&&>(args)...);
}
};
template <typename Initiation, typename Clock,
typename WaitTraits, typename Executor, typename... Signatures>
struct initiate_cancel_at_timer : initiation_base<Initiation>
{
using initiation_base<Initiation>::initiation_base;
template <typename Handler, typename Duration, typename... Args>
void operator()(Handler&& handler,
basic_waitable_timer<Clock, WaitTraits, Executor>* timer,
const chrono::time_point<Clock, Duration>& expiry,
cancellation_type_t cancel_type, Args&&... args) &&
{
using op = detail::timed_cancel_op<decay_t<Handler>,
basic_waitable_timer<Clock, WaitTraits, Executor>&, Signatures...>;
non_const_lvalue<Handler> handler2(handler);
typename op::ptr p = { asio::detail::addressof(handler2.value),
op::ptr::allocate(handler2.value), 0 };
timer->expires_at(expiry);
p.p = new (p.v) op(handler2.value, *timer, cancel_type);
op* o = p.p;
p.v = p.p = 0;
o->start(static_cast<Initiation&&>(*this), static_cast<Args&&>(args)...);
}
template <typename Handler, typename Duration, typename... Args>
void operator()(Handler&& handler,
basic_waitable_timer<Clock, WaitTraits, Executor>* timer,
const chrono::time_point<Clock, Duration>& expiry,
cancellation_type_t cancel_type, Args&&... args) const &
{
using op = detail::timed_cancel_op<decay_t<Handler>,
basic_waitable_timer<Clock, WaitTraits, Executor>&, Signatures...>;
non_const_lvalue<Handler> handler2(handler);
typename op::ptr p = { asio::detail::addressof(handler2.value),
op::ptr::allocate(handler2.value), 0 };
timer->expires_at(expiry);
p.p = new (p.v) op(handler2.value, *timer, cancel_type);
op* o = p.p;
p.v = p.p = 0;
o->start(static_cast<const Initiation&>(*this),
static_cast<Args&&>(args)...);
}
};
} // namespace detail
#if !defined(GENERATING_DOCUMENTATION)
template <typename CompletionToken, typename Clock,
typename WaitTraits, typename... Signatures>
struct async_result<
cancel_at_t<CompletionToken, Clock, WaitTraits>, Signatures...>
: async_result<CompletionToken, Signatures...>
{
template <typename Initiation, typename RawCompletionToken, typename... Args>
static auto initiate(Initiation&& initiation,
RawCompletionToken&& token, Args&&... args)
-> decltype(
async_initiate<
conditional_t<
is_const<remove_reference_t<RawCompletionToken>>::value,
const CompletionToken, CompletionToken>,
Signatures...>(
declval<detail::initiate_cancel_at<
decay_t<Initiation>, Clock, WaitTraits, Signatures...>>(),
token.token_, token.expiry_, token.cancel_type_,
static_cast<Args&&>(args)...))
{
return async_initiate<
conditional_t<
is_const<remove_reference_t<RawCompletionToken>>::value,
const CompletionToken, CompletionToken>,
Signatures...>(
detail::initiate_cancel_at<
decay_t<Initiation>, Clock, WaitTraits, Signatures...>(
static_cast<Initiation&&>(initiation)),
token.token_, token.expiry_, token.cancel_type_,
static_cast<Args&&>(args)...);
}
};
template <typename CompletionToken, typename Clock,
typename WaitTraits, typename Executor, typename... Signatures>
struct async_result<
cancel_at_timer<CompletionToken, Clock, WaitTraits, Executor>,
Signatures...>
: async_result<CompletionToken, Signatures...>
{
template <typename Initiation, typename RawCompletionToken, typename... Args>
static auto initiate(Initiation&& initiation,
RawCompletionToken&& token, Args&&... args)
-> decltype(
async_initiate<
conditional_t<
is_const<remove_reference_t<RawCompletionToken>>::value,
const CompletionToken, CompletionToken>,
Signatures...>(
declval<detail::initiate_cancel_at_timer<
decay_t<Initiation>, Clock, WaitTraits, Executor, Signatures...>>(),
token.token_, &token.timer_, token.expiry_, token.cancel_type_,
static_cast<Args&&>(args)...))
{
return async_initiate<
conditional_t<
is_const<remove_reference_t<RawCompletionToken>>::value,
const CompletionToken, CompletionToken>,
Signatures...>(
detail::initiate_cancel_at_timer<
decay_t<Initiation>, Clock, WaitTraits, Executor, Signatures...>(
static_cast<Initiation&&>(initiation)),
token.token_, &token.timer_, token.expiry_, token.cancel_type_,
static_cast<Args&&>(args)...);
}
};
template <typename Clock, typename WaitTraits, typename... Signatures>
struct async_result<partial_cancel_at<Clock, WaitTraits>, Signatures...>
{
template <typename Initiation, typename RawCompletionToken, typename... Args>
static auto initiate(Initiation&& initiation,
RawCompletionToken&& token, Args&&... args)
-> decltype(
async_initiate<
const cancel_at_t<
default_completion_token_t<associated_executor_t<Initiation>>,
Clock, WaitTraits>&,
Signatures...>(
static_cast<Initiation&&>(initiation),
cancel_at_t<
default_completion_token_t<associated_executor_t<Initiation>>,
Clock, WaitTraits>(
default_completion_token_t<associated_executor_t<Initiation>>{},
token.expiry_, token.cancel_type_),
static_cast<Args&&>(args)...))
{
return async_initiate<
const cancel_at_t<
default_completion_token_t<associated_executor_t<Initiation>>,
Clock, WaitTraits>&,
Signatures...>(
static_cast<Initiation&&>(initiation),
cancel_at_t<
default_completion_token_t<associated_executor_t<Initiation>>,
Clock, WaitTraits>(
default_completion_token_t<associated_executor_t<Initiation>>{},
token.expiry_, token.cancel_type_),
static_cast<Args&&>(args)...);
}
};
template <typename Clock, typename WaitTraits,
typename Executor, typename... Signatures>
struct async_result<
partial_cancel_at_timer<Clock, WaitTraits, Executor>, Signatures...>
{
template <typename Initiation, typename RawCompletionToken, typename... Args>
static auto initiate(Initiation&& initiation,
RawCompletionToken&& token, Args&&... args)
-> decltype(
async_initiate<Signatures...>(
static_cast<Initiation&&>(initiation),
cancel_at_timer<
default_completion_token_t<associated_executor_t<Initiation>>,
Clock, WaitTraits, Executor>(
default_completion_token_t<associated_executor_t<Initiation>>{},
token.timer_, token.expiry_, token.cancel_type_),
static_cast<Args&&>(args)...))
{
return async_initiate<Signatures...>(
static_cast<Initiation&&>(initiation),
cancel_at_timer<
default_completion_token_t<associated_executor_t<Initiation>>,
Clock, WaitTraits, Executor>(
default_completion_token_t<associated_executor_t<Initiation>>{},
token.timer_, token.expiry_, token.cancel_type_),
static_cast<Args&&>(args)...);
}
};
#endif // !defined(GENERATING_DOCUMENTATION)
} // namespace asio
#include "asio/detail/pop_options.hpp"
#endif // ASIO_IMPL_CANCEL_AT_HPP
|
0 | repos/asio/asio/include/asio | repos/asio/asio/include/asio/impl/src.hpp | //
// impl/src.hpp
// ~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef ASIO_IMPL_SRC_HPP
#define ASIO_IMPL_SRC_HPP
#define ASIO_SOURCE
#include "asio/detail/config.hpp"
#if defined(ASIO_HEADER_ONLY)
# error Do not compile Asio library source with ASIO_HEADER_ONLY defined
#endif
#include "asio/impl/any_completion_executor.ipp"
#include "asio/impl/any_io_executor.ipp"
#include "asio/impl/cancellation_signal.ipp"
#include "asio/impl/connect_pipe.ipp"
#include "asio/impl/error.ipp"
#include "asio/impl/error_code.ipp"
#include "asio/impl/execution_context.ipp"
#include "asio/impl/executor.ipp"
#include "asio/impl/io_context.ipp"
#include "asio/impl/multiple_exceptions.ipp"
#include "asio/impl/serial_port_base.ipp"
#include "asio/impl/system_context.ipp"
#include "asio/impl/thread_pool.ipp"
#include "asio/detail/impl/buffer_sequence_adapter.ipp"
#include "asio/detail/impl/descriptor_ops.ipp"
#include "asio/detail/impl/dev_poll_reactor.ipp"
#include "asio/detail/impl/epoll_reactor.ipp"
#include "asio/detail/impl/eventfd_select_interrupter.ipp"
#include "asio/detail/impl/handler_tracking.ipp"
#include "asio/detail/impl/io_uring_descriptor_service.ipp"
#include "asio/detail/impl/io_uring_file_service.ipp"
#include "asio/detail/impl/io_uring_socket_service_base.ipp"
#include "asio/detail/impl/io_uring_service.ipp"
#include "asio/detail/impl/kqueue_reactor.ipp"
#include "asio/detail/impl/null_event.ipp"
#include "asio/detail/impl/pipe_select_interrupter.ipp"
#include "asio/detail/impl/posix_event.ipp"
#include "asio/detail/impl/posix_mutex.ipp"
#include "asio/detail/impl/posix_serial_port_service.ipp"
#include "asio/detail/impl/posix_thread.ipp"
#include "asio/detail/impl/posix_tss_ptr.ipp"
#include "asio/detail/impl/reactive_descriptor_service.ipp"
#include "asio/detail/impl/reactive_socket_service_base.ipp"
#include "asio/detail/impl/resolver_service_base.ipp"
#include "asio/detail/impl/scheduler.ipp"
#include "asio/detail/impl/select_reactor.ipp"
#include "asio/detail/impl/service_registry.ipp"
#include "asio/detail/impl/signal_set_service.ipp"
#include "asio/detail/impl/socket_ops.ipp"
#include "asio/detail/impl/socket_select_interrupter.ipp"
#include "asio/detail/impl/strand_executor_service.ipp"
#include "asio/detail/impl/strand_service.ipp"
#include "asio/detail/impl/thread_context.ipp"
#include "asio/detail/impl/throw_error.ipp"
#include "asio/detail/impl/timer_queue_ptime.ipp"
#include "asio/detail/impl/timer_queue_set.ipp"
#include "asio/detail/impl/win_iocp_file_service.ipp"
#include "asio/detail/impl/win_iocp_handle_service.ipp"
#include "asio/detail/impl/win_iocp_io_context.ipp"
#include "asio/detail/impl/win_iocp_serial_port_service.ipp"
#include "asio/detail/impl/win_iocp_socket_service_base.ipp"
#include "asio/detail/impl/win_event.ipp"
#include "asio/detail/impl/win_mutex.ipp"
#include "asio/detail/impl/win_object_handle_service.ipp"
#include "asio/detail/impl/win_static_mutex.ipp"
#include "asio/detail/impl/win_thread.ipp"
#include "asio/detail/impl/win_tss_ptr.ipp"
#include "asio/detail/impl/winrt_ssocket_service_base.ipp"
#include "asio/detail/impl/winrt_timer_scheduler.ipp"
#include "asio/detail/impl/winsock_init.ipp"
#include "asio/execution/impl/bad_executor.ipp"
#include "asio/experimental/impl/channel_error.ipp"
#include "asio/generic/detail/impl/endpoint.ipp"
#include "asio/ip/impl/address.ipp"
#include "asio/ip/impl/address_v4.ipp"
#include "asio/ip/impl/address_v6.ipp"
#include "asio/ip/impl/host_name.ipp"
#include "asio/ip/impl/network_v4.ipp"
#include "asio/ip/impl/network_v6.ipp"
#include "asio/ip/detail/impl/endpoint.ipp"
#include "asio/local/detail/impl/endpoint.ipp"
#endif // ASIO_IMPL_SRC_HPP
|
0 | repos/asio/asio/include/asio | repos/asio/asio/include/asio/impl/error.ipp | //
// impl/error.ipp
// ~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef ASIO_IMPL_ERROR_IPP
#define ASIO_IMPL_ERROR_IPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include "asio/detail/config.hpp"
#include <string>
#include "asio/error.hpp"
#include "asio/detail/push_options.hpp"
namespace asio {
namespace error {
#if !defined(ASIO_WINDOWS) && !defined(__CYGWIN__)
namespace detail {
class netdb_category : public asio::error_category
{
public:
const char* name() const noexcept
{
return "asio.netdb";
}
std::string message(int value) const
{
if (value == error::host_not_found)
return "Host not found (authoritative)";
if (value == error::host_not_found_try_again)
return "Host not found (non-authoritative), try again later";
if (value == error::no_data)
return "The query is valid, but it does not have associated data";
if (value == error::no_recovery)
return "A non-recoverable error occurred during database lookup";
return "asio.netdb error";
}
};
} // namespace detail
const asio::error_category& get_netdb_category()
{
static detail::netdb_category instance;
return instance;
}
namespace detail {
class addrinfo_category : public asio::error_category
{
public:
const char* name() const noexcept
{
return "asio.addrinfo";
}
std::string message(int value) const
{
if (value == error::service_not_found)
return "Service not found";
if (value == error::socket_type_not_supported)
return "Socket type not supported";
return "asio.addrinfo error";
}
};
} // namespace detail
const asio::error_category& get_addrinfo_category()
{
static detail::addrinfo_category instance;
return instance;
}
#endif // !defined(ASIO_WINDOWS) && !defined(__CYGWIN__)
namespace detail {
class misc_category : public asio::error_category
{
public:
const char* name() const noexcept
{
return "asio.misc";
}
std::string message(int value) const
{
if (value == error::already_open)
return "Already open";
if (value == error::eof)
return "End of file";
if (value == error::not_found)
return "Element not found";
if (value == error::fd_set_failure)
return "The descriptor does not fit into the select call's fd_set";
return "asio.misc error";
}
};
} // namespace detail
const asio::error_category& get_misc_category()
{
static detail::misc_category instance;
return instance;
}
} // namespace error
} // namespace asio
#include "asio/detail/pop_options.hpp"
#endif // ASIO_IMPL_ERROR_IPP
|
0 | repos/asio/asio/include/asio | repos/asio/asio/include/asio/impl/read.hpp | //
// impl/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 ASIO_IMPL_READ_HPP
#define ASIO_IMPL_READ_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <algorithm>
#include "asio/associator.hpp"
#include "asio/buffer.hpp"
#include "asio/detail/array_fwd.hpp"
#include "asio/detail/base_from_cancellation_state.hpp"
#include "asio/detail/base_from_completion_cond.hpp"
#include "asio/detail/bind_handler.hpp"
#include "asio/detail/consuming_buffers.hpp"
#include "asio/detail/dependent_type.hpp"
#include "asio/detail/handler_cont_helpers.hpp"
#include "asio/detail/handler_tracking.hpp"
#include "asio/detail/handler_type_requirements.hpp"
#include "asio/detail/non_const_lvalue.hpp"
#include "asio/detail/throw_error.hpp"
#include "asio/error.hpp"
#include "asio/detail/push_options.hpp"
namespace asio {
namespace detail
{
template <typename SyncReadStream, typename MutableBufferSequence,
typename MutableBufferIterator, typename CompletionCondition>
std::size_t read_buffer_seq(SyncReadStream& s,
const MutableBufferSequence& buffers, const MutableBufferIterator&,
CompletionCondition completion_condition, asio::error_code& ec)
{
ec = asio::error_code();
asio::detail::consuming_buffers<mutable_buffer,
MutableBufferSequence, MutableBufferIterator> tmp(buffers);
while (!tmp.empty())
{
if (std::size_t max_size = detail::adapt_completion_condition_result(
completion_condition(ec, tmp.total_consumed())))
tmp.consume(s.read_some(tmp.prepare(max_size), ec));
else
break;
}
return tmp.total_consumed();
}
} // namespace detail
template <typename SyncReadStream, typename MutableBufferSequence,
typename CompletionCondition>
std::size_t read(SyncReadStream& s, const MutableBufferSequence& buffers,
CompletionCondition completion_condition, asio::error_code& ec,
constraint_t<
is_mutable_buffer_sequence<MutableBufferSequence>::value
>,
constraint_t<
is_completion_condition<CompletionCondition>::value
>)
{
return detail::read_buffer_seq(s, buffers,
asio::buffer_sequence_begin(buffers),
static_cast<CompletionCondition&&>(completion_condition), ec);
}
template <typename SyncReadStream, typename MutableBufferSequence>
inline std::size_t read(SyncReadStream& s, const MutableBufferSequence& buffers,
constraint_t<
is_mutable_buffer_sequence<MutableBufferSequence>::value
>)
{
asio::error_code ec;
std::size_t bytes_transferred = read(s, buffers, transfer_all(), ec);
asio::detail::throw_error(ec, "read");
return bytes_transferred;
}
template <typename SyncReadStream, typename MutableBufferSequence>
inline std::size_t read(SyncReadStream& s, const MutableBufferSequence& buffers,
asio::error_code& ec,
constraint_t<
is_mutable_buffer_sequence<MutableBufferSequence>::value
>)
{
return read(s, buffers, transfer_all(), ec);
}
template <typename SyncReadStream, typename MutableBufferSequence,
typename CompletionCondition>
inline std::size_t read(SyncReadStream& s, const MutableBufferSequence& buffers,
CompletionCondition completion_condition,
constraint_t<
is_mutable_buffer_sequence<MutableBufferSequence>::value
>,
constraint_t<
is_completion_condition<CompletionCondition>::value
>)
{
asio::error_code ec;
std::size_t bytes_transferred = read(s, buffers,
static_cast<CompletionCondition&&>(completion_condition), ec);
asio::detail::throw_error(ec, "read");
return bytes_transferred;
}
#if !defined(ASIO_NO_DYNAMIC_BUFFER_V1)
template <typename SyncReadStream, typename DynamicBuffer_v1,
typename CompletionCondition>
std::size_t read(SyncReadStream& s,
DynamicBuffer_v1&& buffers,
CompletionCondition completion_condition, asio::error_code& ec,
constraint_t<
is_dynamic_buffer_v1<decay_t<DynamicBuffer_v1>>::value
>,
constraint_t<
!is_dynamic_buffer_v2<decay_t<DynamicBuffer_v1>>::value
>,
constraint_t<
is_completion_condition<CompletionCondition>::value
>)
{
decay_t<DynamicBuffer_v1> b(
static_cast<DynamicBuffer_v1&&>(buffers));
ec = asio::error_code();
std::size_t total_transferred = 0;
std::size_t max_size = detail::adapt_completion_condition_result(
completion_condition(ec, total_transferred));
std::size_t bytes_available = std::min<std::size_t>(
std::max<std::size_t>(512, b.capacity() - b.size()),
std::min<std::size_t>(max_size, b.max_size() - b.size()));
while (bytes_available > 0)
{
std::size_t bytes_transferred = s.read_some(b.prepare(bytes_available), ec);
b.commit(bytes_transferred);
total_transferred += bytes_transferred;
max_size = detail::adapt_completion_condition_result(
completion_condition(ec, total_transferred));
bytes_available = std::min<std::size_t>(
std::max<std::size_t>(512, b.capacity() - b.size()),
std::min<std::size_t>(max_size, b.max_size() - b.size()));
}
return total_transferred;
}
template <typename SyncReadStream, typename DynamicBuffer_v1>
inline std::size_t read(SyncReadStream& s,
DynamicBuffer_v1&& buffers,
constraint_t<
is_dynamic_buffer_v1<decay_t<DynamicBuffer_v1>>::value
>,
constraint_t<
!is_dynamic_buffer_v2<decay_t<DynamicBuffer_v1>>::value
>)
{
asio::error_code ec;
std::size_t bytes_transferred = read(s,
static_cast<DynamicBuffer_v1&&>(buffers), transfer_all(), ec);
asio::detail::throw_error(ec, "read");
return bytes_transferred;
}
template <typename SyncReadStream, typename DynamicBuffer_v1>
inline std::size_t read(SyncReadStream& s,
DynamicBuffer_v1&& buffers,
asio::error_code& ec,
constraint_t<
is_dynamic_buffer_v1<decay_t<DynamicBuffer_v1>>::value
>,
constraint_t<
!is_dynamic_buffer_v2<decay_t<DynamicBuffer_v1>>::value
>)
{
return read(s, static_cast<DynamicBuffer_v1&&>(buffers),
transfer_all(), ec);
}
template <typename SyncReadStream, typename DynamicBuffer_v1,
typename CompletionCondition>
inline std::size_t read(SyncReadStream& s,
DynamicBuffer_v1&& buffers,
CompletionCondition completion_condition,
constraint_t<
is_dynamic_buffer_v1<decay_t<DynamicBuffer_v1>>::value
>,
constraint_t<
!is_dynamic_buffer_v2<decay_t<DynamicBuffer_v1>>::value
>,
constraint_t<
is_completion_condition<CompletionCondition>::value
>)
{
asio::error_code ec;
std::size_t bytes_transferred = read(s,
static_cast<DynamicBuffer_v1&&>(buffers),
static_cast<CompletionCondition&&>(completion_condition), ec);
asio::detail::throw_error(ec, "read");
return bytes_transferred;
}
#if !defined(ASIO_NO_EXTENSIONS)
#if !defined(ASIO_NO_IOSTREAM)
template <typename SyncReadStream, typename Allocator,
typename CompletionCondition>
inline std::size_t read(SyncReadStream& s,
asio::basic_streambuf<Allocator>& b,
CompletionCondition completion_condition, asio::error_code& ec,
constraint_t<
is_completion_condition<CompletionCondition>::value
>)
{
return read(s, basic_streambuf_ref<Allocator>(b),
static_cast<CompletionCondition&&>(completion_condition), ec);
}
template <typename SyncReadStream, typename Allocator>
inline std::size_t read(SyncReadStream& s,
asio::basic_streambuf<Allocator>& b)
{
return read(s, basic_streambuf_ref<Allocator>(b));
}
template <typename SyncReadStream, typename Allocator>
inline std::size_t read(SyncReadStream& s,
asio::basic_streambuf<Allocator>& b,
asio::error_code& ec)
{
return read(s, basic_streambuf_ref<Allocator>(b), ec);
}
template <typename SyncReadStream, typename Allocator,
typename CompletionCondition>
inline std::size_t read(SyncReadStream& s,
asio::basic_streambuf<Allocator>& b,
CompletionCondition completion_condition,
constraint_t<
is_completion_condition<CompletionCondition>::value
>)
{
return read(s, basic_streambuf_ref<Allocator>(b),
static_cast<CompletionCondition&&>(completion_condition));
}
#endif // !defined(ASIO_NO_IOSTREAM)
#endif // !defined(ASIO_NO_EXTENSIONS)
#endif // !defined(ASIO_NO_DYNAMIC_BUFFER_V1)
template <typename SyncReadStream, typename DynamicBuffer_v2,
typename CompletionCondition>
std::size_t read(SyncReadStream& s, DynamicBuffer_v2 buffers,
CompletionCondition completion_condition, asio::error_code& ec,
constraint_t<
is_dynamic_buffer_v2<DynamicBuffer_v2>::value
>,
constraint_t<
is_completion_condition<CompletionCondition>::value
>)
{
DynamicBuffer_v2& b = buffers;
ec = asio::error_code();
std::size_t total_transferred = 0;
std::size_t max_size = detail::adapt_completion_condition_result(
completion_condition(ec, total_transferred));
std::size_t bytes_available = std::min<std::size_t>(
std::max<std::size_t>(512, b.capacity() - b.size()),
std::min<std::size_t>(max_size, b.max_size() - b.size()));
while (bytes_available > 0)
{
std::size_t pos = b.size();
b.grow(bytes_available);
std::size_t bytes_transferred = s.read_some(
b.data(pos, bytes_available), ec);
b.shrink(bytes_available - bytes_transferred);
total_transferred += bytes_transferred;
max_size = detail::adapt_completion_condition_result(
completion_condition(ec, total_transferred));
bytes_available = std::min<std::size_t>(
std::max<std::size_t>(512, b.capacity() - b.size()),
std::min<std::size_t>(max_size, b.max_size() - b.size()));
}
return total_transferred;
}
template <typename SyncReadStream, typename DynamicBuffer_v2>
inline std::size_t read(SyncReadStream& s, DynamicBuffer_v2 buffers,
constraint_t<
is_dynamic_buffer_v2<DynamicBuffer_v2>::value
>)
{
asio::error_code ec;
std::size_t bytes_transferred = read(s,
static_cast<DynamicBuffer_v2&&>(buffers), transfer_all(), ec);
asio::detail::throw_error(ec, "read");
return bytes_transferred;
}
template <typename SyncReadStream, typename DynamicBuffer_v2>
inline std::size_t read(SyncReadStream& s, DynamicBuffer_v2 buffers,
asio::error_code& ec,
constraint_t<
is_dynamic_buffer_v2<DynamicBuffer_v2>::value
>)
{
return read(s, static_cast<DynamicBuffer_v2&&>(buffers),
transfer_all(), ec);
}
template <typename SyncReadStream, typename DynamicBuffer_v2,
typename CompletionCondition>
inline std::size_t read(SyncReadStream& s, DynamicBuffer_v2 buffers,
CompletionCondition completion_condition,
constraint_t<
is_dynamic_buffer_v2<DynamicBuffer_v2>::value
>,
constraint_t<
is_completion_condition<CompletionCondition>::value
>)
{
asio::error_code ec;
std::size_t bytes_transferred = read(s,
static_cast<DynamicBuffer_v2&&>(buffers),
static_cast<CompletionCondition&&>(completion_condition), ec);
asio::detail::throw_error(ec, "read");
return bytes_transferred;
}
namespace detail
{
template <typename AsyncReadStream, typename MutableBufferSequence,
typename MutableBufferIterator, typename CompletionCondition,
typename ReadHandler>
class read_op
: public base_from_cancellation_state<ReadHandler>,
base_from_completion_cond<CompletionCondition>
{
public:
read_op(AsyncReadStream& stream, const MutableBufferSequence& buffers,
CompletionCondition& completion_condition, ReadHandler& handler)
: base_from_cancellation_state<ReadHandler>(
handler, enable_partial_cancellation()),
base_from_completion_cond<CompletionCondition>(completion_condition),
stream_(stream),
buffers_(buffers),
start_(0),
handler_(static_cast<ReadHandler&&>(handler))
{
}
read_op(const read_op& other)
: base_from_cancellation_state<ReadHandler>(other),
base_from_completion_cond<CompletionCondition>(other),
stream_(other.stream_),
buffers_(other.buffers_),
start_(other.start_),
handler_(other.handler_)
{
}
read_op(read_op&& other)
: base_from_cancellation_state<ReadHandler>(
static_cast<base_from_cancellation_state<ReadHandler>&&>(other)),
base_from_completion_cond<CompletionCondition>(
static_cast<base_from_completion_cond<CompletionCondition>&&>(other)),
stream_(other.stream_),
buffers_(static_cast<buffers_type&&>(other.buffers_)),
start_(other.start_),
handler_(static_cast<ReadHandler&&>(other.handler_))
{
}
void operator()(asio::error_code ec,
std::size_t bytes_transferred, int start = 0)
{
std::size_t max_size;
switch (start_ = start)
{
case 1:
max_size = this->check_for_completion(ec, buffers_.total_consumed());
for (;;)
{
{
ASIO_HANDLER_LOCATION((__FILE__, __LINE__, "async_read"));
stream_.async_read_some(buffers_.prepare(max_size),
static_cast<read_op&&>(*this));
}
return; default:
buffers_.consume(bytes_transferred);
if ((!ec && bytes_transferred == 0) || buffers_.empty())
break;
max_size = this->check_for_completion(ec, buffers_.total_consumed());
if (max_size == 0)
break;
if (this->cancelled() != cancellation_type::none)
{
ec = error::operation_aborted;
break;
}
}
static_cast<ReadHandler&&>(handler_)(
static_cast<const asio::error_code&>(ec),
static_cast<const std::size_t&>(buffers_.total_consumed()));
}
}
//private:
typedef asio::detail::consuming_buffers<mutable_buffer,
MutableBufferSequence, MutableBufferIterator> buffers_type;
AsyncReadStream& stream_;
buffers_type buffers_;
int start_;
ReadHandler handler_;
};
template <typename AsyncReadStream, typename MutableBufferSequence,
typename MutableBufferIterator, typename CompletionCondition,
typename ReadHandler>
inline bool asio_handler_is_continuation(
read_op<AsyncReadStream, MutableBufferSequence, MutableBufferIterator,
CompletionCondition, ReadHandler>* this_handler)
{
return this_handler->start_ == 0 ? true
: asio_handler_cont_helpers::is_continuation(
this_handler->handler_);
}
template <typename AsyncReadStream, typename MutableBufferSequence,
typename MutableBufferIterator, typename CompletionCondition,
typename ReadHandler>
inline void start_read_op(AsyncReadStream& stream,
const MutableBufferSequence& buffers, const MutableBufferIterator&,
CompletionCondition& completion_condition, ReadHandler& handler)
{
read_op<AsyncReadStream, MutableBufferSequence,
MutableBufferIterator, CompletionCondition, ReadHandler>(
stream, buffers, completion_condition, handler)(
asio::error_code(), 0, 1);
}
template <typename AsyncReadStream>
class initiate_async_read
{
public:
typedef typename AsyncReadStream::executor_type executor_type;
explicit initiate_async_read(AsyncReadStream& stream)
: stream_(stream)
{
}
executor_type get_executor() const noexcept
{
return stream_.get_executor();
}
template <typename ReadHandler, typename MutableBufferSequence,
typename CompletionCondition>
void operator()(ReadHandler&& handler,
const MutableBufferSequence& buffers,
CompletionCondition&& completion_cond) const
{
// If you get an error on the following line it means that your handler
// does not meet the documented type requirements for a ReadHandler.
ASIO_READ_HANDLER_CHECK(ReadHandler, handler) type_check;
non_const_lvalue<ReadHandler> handler2(handler);
non_const_lvalue<CompletionCondition> completion_cond2(completion_cond);
start_read_op(stream_, buffers,
asio::buffer_sequence_begin(buffers),
completion_cond2.value, handler2.value);
}
private:
AsyncReadStream& stream_;
};
} // namespace detail
#if !defined(GENERATING_DOCUMENTATION)
template <template <typename, typename> class Associator,
typename AsyncReadStream, typename MutableBufferSequence,
typename MutableBufferIterator, typename CompletionCondition,
typename ReadHandler, typename DefaultCandidate>
struct associator<Associator,
detail::read_op<AsyncReadStream, MutableBufferSequence,
MutableBufferIterator, CompletionCondition, ReadHandler>,
DefaultCandidate>
: Associator<ReadHandler, DefaultCandidate>
{
static typename Associator<ReadHandler, DefaultCandidate>::type get(
const detail::read_op<AsyncReadStream, MutableBufferSequence,
MutableBufferIterator, CompletionCondition, ReadHandler>& h) noexcept
{
return Associator<ReadHandler, DefaultCandidate>::get(h.handler_);
}
static auto get(
const detail::read_op<AsyncReadStream, MutableBufferSequence,
MutableBufferIterator, CompletionCondition, ReadHandler>& h,
const DefaultCandidate& c) noexcept
-> decltype(Associator<ReadHandler, DefaultCandidate>::get(h.handler_, c))
{
return Associator<ReadHandler, DefaultCandidate>::get(h.handler_, c);
}
};
#endif // !defined(GENERATING_DOCUMENTATION)
#if !defined(ASIO_NO_DYNAMIC_BUFFER_V1)
namespace detail
{
template <typename AsyncReadStream, typename DynamicBuffer_v1,
typename CompletionCondition, typename ReadHandler>
class read_dynbuf_v1_op
: public base_from_cancellation_state<ReadHandler>,
base_from_completion_cond<CompletionCondition>
{
public:
template <typename BufferSequence>
read_dynbuf_v1_op(AsyncReadStream& stream,
BufferSequence&& buffers,
CompletionCondition& completion_condition, ReadHandler& handler)
: base_from_cancellation_state<ReadHandler>(
handler, enable_partial_cancellation()),
base_from_completion_cond<CompletionCondition>(completion_condition),
stream_(stream),
buffers_(static_cast<BufferSequence&&>(buffers)),
start_(0),
total_transferred_(0),
handler_(static_cast<ReadHandler&&>(handler))
{
}
read_dynbuf_v1_op(const read_dynbuf_v1_op& other)
: base_from_cancellation_state<ReadHandler>(other),
base_from_completion_cond<CompletionCondition>(other),
stream_(other.stream_),
buffers_(other.buffers_),
start_(other.start_),
total_transferred_(other.total_transferred_),
handler_(other.handler_)
{
}
read_dynbuf_v1_op(read_dynbuf_v1_op&& other)
: base_from_cancellation_state<ReadHandler>(
static_cast<base_from_cancellation_state<ReadHandler>&&>(other)),
base_from_completion_cond<CompletionCondition>(
static_cast<base_from_completion_cond<CompletionCondition>&&>(other)),
stream_(other.stream_),
buffers_(static_cast<DynamicBuffer_v1&&>(other.buffers_)),
start_(other.start_),
total_transferred_(other.total_transferred_),
handler_(static_cast<ReadHandler&&>(other.handler_))
{
}
void operator()(asio::error_code ec,
std::size_t bytes_transferred, int start = 0)
{
std::size_t max_size, bytes_available;
switch (start_ = start)
{
case 1:
max_size = this->check_for_completion(ec, total_transferred_);
bytes_available = std::min<std::size_t>(
std::max<std::size_t>(512,
buffers_.capacity() - buffers_.size()),
std::min<std::size_t>(max_size,
buffers_.max_size() - buffers_.size()));
for (;;)
{
{
ASIO_HANDLER_LOCATION((__FILE__, __LINE__, "async_read"));
stream_.async_read_some(buffers_.prepare(bytes_available),
static_cast<read_dynbuf_v1_op&&>(*this));
}
return; default:
total_transferred_ += bytes_transferred;
buffers_.commit(bytes_transferred);
max_size = this->check_for_completion(ec, total_transferred_);
bytes_available = std::min<std::size_t>(
std::max<std::size_t>(512,
buffers_.capacity() - buffers_.size()),
std::min<std::size_t>(max_size,
buffers_.max_size() - buffers_.size()));
if ((!ec && bytes_transferred == 0) || bytes_available == 0)
break;
if (this->cancelled() != cancellation_type::none)
{
ec = error::operation_aborted;
break;
}
}
static_cast<ReadHandler&&>(handler_)(
static_cast<const asio::error_code&>(ec),
static_cast<const std::size_t&>(total_transferred_));
}
}
//private:
AsyncReadStream& stream_;
DynamicBuffer_v1 buffers_;
int start_;
std::size_t total_transferred_;
ReadHandler handler_;
};
template <typename AsyncReadStream, typename DynamicBuffer_v1,
typename CompletionCondition, typename ReadHandler>
inline bool asio_handler_is_continuation(
read_dynbuf_v1_op<AsyncReadStream, DynamicBuffer_v1,
CompletionCondition, ReadHandler>* this_handler)
{
return this_handler->start_ == 0 ? true
: asio_handler_cont_helpers::is_continuation(
this_handler->handler_);
}
template <typename AsyncReadStream>
class initiate_async_read_dynbuf_v1
{
public:
typedef typename AsyncReadStream::executor_type executor_type;
explicit initiate_async_read_dynbuf_v1(AsyncReadStream& stream)
: stream_(stream)
{
}
executor_type get_executor() const noexcept
{
return stream_.get_executor();
}
template <typename ReadHandler, typename DynamicBuffer_v1,
typename CompletionCondition>
void operator()(ReadHandler&& handler,
DynamicBuffer_v1&& buffers,
CompletionCondition&& completion_cond) const
{
// If you get an error on the following line it means that your handler
// does not meet the documented type requirements for a ReadHandler.
ASIO_READ_HANDLER_CHECK(ReadHandler, handler) type_check;
non_const_lvalue<ReadHandler> handler2(handler);
non_const_lvalue<CompletionCondition> completion_cond2(completion_cond);
read_dynbuf_v1_op<AsyncReadStream, decay_t<DynamicBuffer_v1>,
CompletionCondition, decay_t<ReadHandler>>(
stream_, static_cast<DynamicBuffer_v1&&>(buffers),
completion_cond2.value, handler2.value)(
asio::error_code(), 0, 1);
}
private:
AsyncReadStream& stream_;
};
} // namespace detail
#if !defined(GENERATING_DOCUMENTATION)
template <template <typename, typename> class Associator,
typename AsyncReadStream, typename DynamicBuffer_v1,
typename CompletionCondition, typename ReadHandler,
typename DefaultCandidate>
struct associator<Associator,
detail::read_dynbuf_v1_op<AsyncReadStream,
DynamicBuffer_v1, CompletionCondition, ReadHandler>,
DefaultCandidate>
: Associator<ReadHandler, DefaultCandidate>
{
static typename Associator<ReadHandler, DefaultCandidate>::type get(
const detail::read_dynbuf_v1_op<AsyncReadStream, DynamicBuffer_v1,
CompletionCondition, ReadHandler>& h) noexcept
{
return Associator<ReadHandler, DefaultCandidate>::get(h.handler_);
}
static auto get(
const detail::read_dynbuf_v1_op<AsyncReadStream,
DynamicBuffer_v1, CompletionCondition, ReadHandler>& h,
const DefaultCandidate& c) noexcept
-> decltype(Associator<ReadHandler, DefaultCandidate>::get(h.handler_, c))
{
return Associator<ReadHandler, DefaultCandidate>::get(h.handler_, c);
}
};
#endif // !defined(GENERATING_DOCUMENTATION)
#endif // !defined(ASIO_NO_DYNAMIC_BUFFER_V1)
namespace detail
{
template <typename AsyncReadStream, typename DynamicBuffer_v2,
typename CompletionCondition, typename ReadHandler>
class read_dynbuf_v2_op
: public base_from_cancellation_state<ReadHandler>,
base_from_completion_cond<CompletionCondition>
{
public:
template <typename BufferSequence>
read_dynbuf_v2_op(AsyncReadStream& stream,
BufferSequence&& buffers,
CompletionCondition& completion_condition, ReadHandler& handler)
: base_from_cancellation_state<ReadHandler>(
handler, enable_partial_cancellation()),
base_from_completion_cond<CompletionCondition>(completion_condition),
stream_(stream),
buffers_(static_cast<BufferSequence&&>(buffers)),
start_(0),
total_transferred_(0),
bytes_available_(0),
handler_(static_cast<ReadHandler&&>(handler))
{
}
read_dynbuf_v2_op(const read_dynbuf_v2_op& other)
: base_from_cancellation_state<ReadHandler>(other),
base_from_completion_cond<CompletionCondition>(other),
stream_(other.stream_),
buffers_(other.buffers_),
start_(other.start_),
total_transferred_(other.total_transferred_),
bytes_available_(other.bytes_available_),
handler_(other.handler_)
{
}
read_dynbuf_v2_op(read_dynbuf_v2_op&& other)
: base_from_cancellation_state<ReadHandler>(
static_cast<base_from_cancellation_state<ReadHandler>&&>(other)),
base_from_completion_cond<CompletionCondition>(
static_cast<base_from_completion_cond<CompletionCondition>&&>(other)),
stream_(other.stream_),
buffers_(static_cast<DynamicBuffer_v2&&>(other.buffers_)),
start_(other.start_),
total_transferred_(other.total_transferred_),
bytes_available_(other.bytes_available_),
handler_(static_cast<ReadHandler&&>(other.handler_))
{
}
void operator()(asio::error_code ec,
std::size_t bytes_transferred, int start = 0)
{
std::size_t max_size, pos;
switch (start_ = start)
{
case 1:
max_size = this->check_for_completion(ec, total_transferred_);
bytes_available_ = std::min<std::size_t>(
std::max<std::size_t>(512,
buffers_.capacity() - buffers_.size()),
std::min<std::size_t>(max_size,
buffers_.max_size() - buffers_.size()));
for (;;)
{
pos = buffers_.size();
buffers_.grow(bytes_available_);
{
ASIO_HANDLER_LOCATION((__FILE__, __LINE__, "async_read"));
stream_.async_read_some(buffers_.data(pos, bytes_available_),
static_cast<read_dynbuf_v2_op&&>(*this));
}
return; default:
total_transferred_ += bytes_transferred;
buffers_.shrink(bytes_available_ - bytes_transferred);
max_size = this->check_for_completion(ec, total_transferred_);
bytes_available_ = std::min<std::size_t>(
std::max<std::size_t>(512,
buffers_.capacity() - buffers_.size()),
std::min<std::size_t>(max_size,
buffers_.max_size() - buffers_.size()));
if ((!ec && bytes_transferred == 0) || bytes_available_ == 0)
break;
if (this->cancelled() != cancellation_type::none)
{
ec = error::operation_aborted;
break;
}
}
static_cast<ReadHandler&&>(handler_)(
static_cast<const asio::error_code&>(ec),
static_cast<const std::size_t&>(total_transferred_));
}
}
//private:
AsyncReadStream& stream_;
DynamicBuffer_v2 buffers_;
int start_;
std::size_t total_transferred_;
std::size_t bytes_available_;
ReadHandler handler_;
};
template <typename AsyncReadStream, typename DynamicBuffer_v2,
typename CompletionCondition, typename ReadHandler>
inline bool asio_handler_is_continuation(
read_dynbuf_v2_op<AsyncReadStream, DynamicBuffer_v2,
CompletionCondition, ReadHandler>* this_handler)
{
return this_handler->start_ == 0 ? true
: asio_handler_cont_helpers::is_continuation(
this_handler->handler_);
}
template <typename AsyncReadStream>
class initiate_async_read_dynbuf_v2
{
public:
typedef typename AsyncReadStream::executor_type executor_type;
explicit initiate_async_read_dynbuf_v2(AsyncReadStream& stream)
: stream_(stream)
{
}
executor_type get_executor() const noexcept
{
return stream_.get_executor();
}
template <typename ReadHandler, typename DynamicBuffer_v2,
typename CompletionCondition>
void operator()(ReadHandler&& handler,
DynamicBuffer_v2&& buffers,
CompletionCondition&& completion_cond) const
{
// If you get an error on the following line it means that your handler
// does not meet the documented type requirements for a ReadHandler.
ASIO_READ_HANDLER_CHECK(ReadHandler, handler) type_check;
non_const_lvalue<ReadHandler> handler2(handler);
non_const_lvalue<CompletionCondition> completion_cond2(completion_cond);
read_dynbuf_v2_op<AsyncReadStream, decay_t<DynamicBuffer_v2>,
CompletionCondition, decay_t<ReadHandler>>(
stream_, static_cast<DynamicBuffer_v2&&>(buffers),
completion_cond2.value, handler2.value)(
asio::error_code(), 0, 1);
}
private:
AsyncReadStream& stream_;
};
} // namespace detail
#if !defined(GENERATING_DOCUMENTATION)
template <template <typename, typename> class Associator,
typename AsyncReadStream, typename DynamicBuffer_v2,
typename CompletionCondition, typename ReadHandler,
typename DefaultCandidate>
struct associator<Associator,
detail::read_dynbuf_v2_op<AsyncReadStream,
DynamicBuffer_v2, CompletionCondition, ReadHandler>,
DefaultCandidate>
: Associator<ReadHandler, DefaultCandidate>
{
static typename Associator<ReadHandler, DefaultCandidate>::type get(
const detail::read_dynbuf_v2_op<AsyncReadStream, DynamicBuffer_v2,
CompletionCondition, ReadHandler>& h) noexcept
{
return Associator<ReadHandler, DefaultCandidate>::get(h.handler_);
}
static auto get(
const detail::read_dynbuf_v2_op<AsyncReadStream,
DynamicBuffer_v2, CompletionCondition, ReadHandler>& h,
const DefaultCandidate& c) noexcept
-> decltype(Associator<ReadHandler, DefaultCandidate>::get(h.handler_, c))
{
return Associator<ReadHandler, DefaultCandidate>::get(h.handler_, c);
}
};
#endif // !defined(GENERATING_DOCUMENTATION)
} // namespace asio
#include "asio/detail/pop_options.hpp"
#endif // ASIO_IMPL_READ_HPP
|
0 | repos/asio/asio/include/asio | repos/asio/asio/include/asio/impl/system_context.hpp | //
// impl/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 ASIO_IMPL_SYSTEM_CONTEXT_HPP
#define ASIO_IMPL_SYSTEM_CONTEXT_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include "asio/system_executor.hpp"
#include "asio/detail/push_options.hpp"
namespace asio {
inline system_context::executor_type
system_context::get_executor() noexcept
{
return system_executor();
}
} // namespace asio
#include "asio/detail/pop_options.hpp"
#endif // ASIO_IMPL_SYSTEM_CONTEXT_HPP
|
0 | repos/asio/asio/include/asio | repos/asio/asio/include/asio/impl/append.hpp | //
// impl/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 ASIO_IMPL_APPEND_HPP
#define ASIO_IMPL_APPEND_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include "asio/detail/config.hpp"
#include "asio/associator.hpp"
#include "asio/async_result.hpp"
#include "asio/detail/handler_cont_helpers.hpp"
#include "asio/detail/initiation_base.hpp"
#include "asio/detail/type_traits.hpp"
#include "asio/detail/utility.hpp"
#include "asio/detail/push_options.hpp"
namespace asio {
namespace detail {
// Class to adapt an append_t as a completion handler.
template <typename Handler, typename... Values>
class append_handler
{
public:
typedef void result_type;
template <typename H>
append_handler(H&& handler, std::tuple<Values...> values)
: handler_(static_cast<H&&>(handler)),
values_(static_cast<std::tuple<Values...>&&>(values))
{
}
template <typename... Args>
void operator()(Args&&... args)
{
this->invoke(
index_sequence_for<Values...>{},
static_cast<Args&&>(args)...);
}
template <std::size_t... I, typename... Args>
void invoke(index_sequence<I...>, Args&&... args)
{
static_cast<Handler&&>(handler_)(
static_cast<Args&&>(args)...,
static_cast<Values&&>(std::get<I>(values_))...);
}
//private:
Handler handler_;
std::tuple<Values...> values_;
};
template <typename Handler>
inline bool asio_handler_is_continuation(
append_handler<Handler>* this_handler)
{
return asio_handler_cont_helpers::is_continuation(
this_handler->handler_);
}
template <typename Signature, typename... Values>
struct append_signature;
template <typename R, typename... Args, typename... Values>
struct append_signature<R(Args...), Values...>
{
typedef R type(decay_t<Args>..., Values...);
};
} // namespace detail
#if !defined(GENERATING_DOCUMENTATION)
template <typename CompletionToken, typename... Values, typename Signature>
struct async_result<append_t<CompletionToken, Values...>, Signature>
: async_result<CompletionToken,
typename detail::append_signature<
Signature, Values...>::type>
{
typedef typename detail::append_signature<
Signature, Values...>::type signature;
template <typename Initiation>
struct init_wrapper : detail::initiation_base<Initiation>
{
using detail::initiation_base<Initiation>::initiation_base;
template <typename Handler, typename... Args>
void operator()(Handler&& handler,
std::tuple<Values...> values, Args&&... args) &&
{
static_cast<Initiation&&>(*this)(
detail::append_handler<decay_t<Handler>, Values...>(
static_cast<Handler&&>(handler),
static_cast<std::tuple<Values...>&&>(values)),
static_cast<Args&&>(args)...);
}
template <typename Handler, typename... Args>
void operator()(Handler&& handler,
std::tuple<Values...> values, Args&&... args) const &
{
static_cast<const Initiation&>(*this)(
detail::append_handler<decay_t<Handler>, Values...>(
static_cast<Handler&&>(handler),
static_cast<std::tuple<Values...>&&>(values)),
static_cast<Args&&>(args)...);
}
};
template <typename Initiation, typename RawCompletionToken, typename... Args>
static auto initiate(Initiation&& initiation,
RawCompletionToken&& token, Args&&... args)
-> decltype(
async_initiate<CompletionToken, signature>(
declval<init_wrapper<decay_t<Initiation>>>(),
token.token_,
static_cast<std::tuple<Values...>&&>(token.values_),
static_cast<Args&&>(args)...))
{
return async_initiate<CompletionToken, signature>(
init_wrapper<decay_t<Initiation>>(
static_cast<Initiation&&>(initiation)),
token.token_,
static_cast<std::tuple<Values...>&&>(token.values_),
static_cast<Args&&>(args)...);
}
};
template <template <typename, typename> class Associator,
typename Handler, typename... Values, typename DefaultCandidate>
struct associator<Associator,
detail::append_handler<Handler, Values...>, DefaultCandidate>
: Associator<Handler, DefaultCandidate>
{
static typename Associator<Handler, DefaultCandidate>::type get(
const detail::append_handler<Handler, Values...>& h) noexcept
{
return Associator<Handler, DefaultCandidate>::get(h.handler_);
}
static auto get(const detail::append_handler<Handler, Values...>& 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)
} // namespace asio
#include "asio/detail/pop_options.hpp"
#endif // ASIO_IMPL_APPEND_HPP
|
0 | repos/asio/asio/include/asio | repos/asio/asio/include/asio/impl/connect_pipe.ipp | //
// impl/connect_pipe.ipp
// ~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com)
// Copyright (c) 2021 Klemens D. Morgenstern
// (klemens dot morgenstern at gmx dot net)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef ASIO_IMPL_CONNECT_PIPE_IPP
#define ASIO_IMPL_CONNECT_PIPE_IPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include "asio/detail/config.hpp"
#if defined(ASIO_HAS_PIPE)
#include "asio/connect_pipe.hpp"
#if defined(ASIO_HAS_IOCP)
# include <cstdio>
# if _WIN32_WINNT >= 0x601
# include <bcrypt.h>
# if !defined(ASIO_NO_DEFAULT_LINKED_LIBS)
# if defined(_MSC_VER)
# pragma comment(lib, "bcrypt.lib")
# endif // defined(_MSC_VER)
# endif // !defined(ASIO_NO_DEFAULT_LINKED_LIBS)
# endif // _WIN32_WINNT >= 0x601
#else // defined(ASIO_HAS_IOCP)
# include "asio/detail/descriptor_ops.hpp"
#endif // defined(ASIO_HAS_IOCP)
#include "asio/detail/push_options.hpp"
namespace asio {
namespace detail {
void create_pipe(native_pipe_handle p[2], asio::error_code& ec)
{
#if defined(ASIO_HAS_IOCP)
using namespace std; // For sprintf and memcmp.
static long counter1 = 0;
static long counter2 = 0;
long n1 = ::InterlockedIncrement(&counter1);
long n2 = (static_cast<unsigned long>(n1) % 0x10000000) == 0
? ::InterlockedIncrement(&counter2)
: ::InterlockedExchangeAdd(&counter2, 0);
wchar_t pipe_name[128];
#if defined(ASIO_HAS_SECURE_RTL)
swprintf_s(
#else // defined(ASIO_HAS_SECURE_RTL)
_snwprintf(
#endif // defined(ASIO_HAS_SECURE_RTL)
pipe_name, 128,
L"\\\\.\\pipe\\asio-A0812896-741A-484D-AF23-BE51BF620E22-%u-%ld-%ld",
static_cast<unsigned int>(::GetCurrentProcessId()), n1, n2);
p[0] = ::CreateNamedPipeW(pipe_name,
PIPE_ACCESS_INBOUND | FILE_FLAG_OVERLAPPED,
0, 1, 8192, 8192, 0, 0);
if (p[0] == INVALID_HANDLE_VALUE)
{
DWORD last_error = ::GetLastError();
ec.assign(last_error, asio::error::get_system_category());
return;
}
p[1] = ::CreateFileW(pipe_name, GENERIC_WRITE, 0,
0, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
if (p[1] == INVALID_HANDLE_VALUE)
{
DWORD last_error = ::GetLastError();
::CloseHandle(p[0]);
ec.assign(last_error, asio::error::get_system_category());
return;
}
# if _WIN32_WINNT >= 0x601
unsigned char nonce[16];
if (::BCryptGenRandom(0, nonce, sizeof(nonce),
BCRYPT_USE_SYSTEM_PREFERRED_RNG) != 0)
{
ec = asio::error::connection_aborted;
::CloseHandle(p[0]);
::CloseHandle(p[1]);
return;
}
DWORD bytes_written = 0;
BOOL ok = ::WriteFile(p[1], nonce, sizeof(nonce), &bytes_written, 0);
if (!ok || bytes_written != sizeof(nonce))
{
ec = asio::error::connection_aborted;
::CloseHandle(p[0]);
::CloseHandle(p[1]);
return;
}
unsigned char nonce_check[sizeof(nonce)];
DWORD bytes_read = 0;
ok = ::ReadFile(p[0], nonce_check, sizeof(nonce), &bytes_read, 0);
if (!ok || bytes_read != sizeof(nonce)
|| memcmp(nonce, nonce_check, sizeof(nonce)) != 0)
{
ec = asio::error::connection_aborted;
::CloseHandle(p[0]);
::CloseHandle(p[1]);
return;
}
#endif // _WIN32_WINNT >= 0x601
asio::error::clear(ec);
#else // defined(ASIO_HAS_IOCP)
int result = ::pipe(p);
detail::descriptor_ops::get_last_error(ec, result != 0);
#endif // defined(ASIO_HAS_IOCP)
}
void close_pipe(native_pipe_handle p)
{
#if defined(ASIO_HAS_IOCP)
::CloseHandle(p);
#else // defined(ASIO_HAS_IOCP)
asio::error_code ignored_ec;
detail::descriptor_ops::state_type state = 0;
detail::descriptor_ops::close(p, state, ignored_ec);
#endif // defined(ASIO_HAS_IOCP)
}
} // namespace detail
} // namespace asio
#include "asio/detail/pop_options.hpp"
#endif // defined(ASIO_HAS_PIPE)
#endif // ASIO_IMPL_CONNECT_PIPE_IPP
|
0 | repos/asio/asio/include/asio | repos/asio/asio/include/asio/impl/executor.hpp | //
// impl/executor.hpp
// ~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef ASIO_IMPL_EXECUTOR_HPP
#define ASIO_IMPL_EXECUTOR_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include "asio/detail/config.hpp"
#if !defined(ASIO_NO_TS_EXECUTORS)
#include <new>
#include "asio/detail/atomic_count.hpp"
#include "asio/detail/global.hpp"
#include "asio/detail/memory.hpp"
#include "asio/executor.hpp"
#include "asio/system_executor.hpp"
#include "asio/detail/push_options.hpp"
namespace asio {
#if !defined(GENERATING_DOCUMENTATION)
// Default polymorphic executor implementation.
template <typename Executor, typename Allocator>
class executor::impl
: public executor::impl_base
{
public:
typedef ASIO_REBIND_ALLOC(Allocator, impl) allocator_type;
static impl_base* create(const Executor& e, Allocator a = Allocator())
{
raw_mem mem(a);
impl* p = new (mem.ptr_) impl(e, a);
mem.ptr_ = 0;
return p;
}
static impl_base* create(std::nothrow_t, const Executor& e) noexcept
{
return new (std::nothrow) impl(e, std::allocator<void>());
}
impl(const Executor& e, const Allocator& a) noexcept
: impl_base(false),
ref_count_(1),
executor_(e),
allocator_(a)
{
}
impl_base* clone() const noexcept
{
detail::ref_count_up(ref_count_);
return const_cast<impl_base*>(static_cast<const impl_base*>(this));
}
void destroy() noexcept
{
if (detail::ref_count_down(ref_count_))
{
allocator_type alloc(allocator_);
impl* p = this;
p->~impl();
alloc.deallocate(p, 1);
}
}
void on_work_started() noexcept
{
executor_.on_work_started();
}
void on_work_finished() noexcept
{
executor_.on_work_finished();
}
execution_context& context() noexcept
{
return executor_.context();
}
void dispatch(function&& f)
{
executor_.dispatch(static_cast<function&&>(f), allocator_);
}
void post(function&& f)
{
executor_.post(static_cast<function&&>(f), allocator_);
}
void defer(function&& f)
{
executor_.defer(static_cast<function&&>(f), allocator_);
}
type_id_result_type target_type() const noexcept
{
return type_id<Executor>();
}
void* target() noexcept
{
return &executor_;
}
const void* target() const noexcept
{
return &executor_;
}
bool equals(const impl_base* e) const noexcept
{
if (this == e)
return true;
if (target_type() != e->target_type())
return false;
return executor_ == *static_cast<const Executor*>(e->target());
}
private:
mutable detail::atomic_count ref_count_;
Executor executor_;
Allocator allocator_;
struct raw_mem
{
allocator_type allocator_;
impl* ptr_;
explicit raw_mem(const Allocator& a)
: allocator_(a),
ptr_(allocator_.allocate(1))
{
}
~raw_mem()
{
if (ptr_)
allocator_.deallocate(ptr_, 1);
}
private:
// Disallow copying and assignment.
raw_mem(const raw_mem&);
raw_mem operator=(const raw_mem&);
};
};
// Polymorphic executor specialisation for system_executor.
template <typename Allocator>
class executor::impl<system_executor, Allocator>
: public executor::impl_base
{
public:
static impl_base* create(const system_executor&,
const Allocator& = Allocator())
{
return &detail::global<impl<system_executor, std::allocator<void>> >();
}
static impl_base* create(std::nothrow_t, const system_executor&) noexcept
{
return &detail::global<impl<system_executor, std::allocator<void>> >();
}
impl()
: impl_base(true)
{
}
impl_base* clone() const noexcept
{
return const_cast<impl_base*>(static_cast<const impl_base*>(this));
}
void destroy() noexcept
{
}
void on_work_started() noexcept
{
executor_.on_work_started();
}
void on_work_finished() noexcept
{
executor_.on_work_finished();
}
execution_context& context() noexcept
{
return executor_.context();
}
void dispatch(function&& f)
{
executor_.dispatch(static_cast<function&&>(f),
std::allocator<void>());
}
void post(function&& f)
{
executor_.post(static_cast<function&&>(f),
std::allocator<void>());
}
void defer(function&& f)
{
executor_.defer(static_cast<function&&>(f),
std::allocator<void>());
}
type_id_result_type target_type() const noexcept
{
return type_id<system_executor>();
}
void* target() noexcept
{
return &executor_;
}
const void* target() const noexcept
{
return &executor_;
}
bool equals(const impl_base* e) const noexcept
{
return this == e;
}
private:
system_executor executor_;
};
template <typename Executor>
executor::executor(Executor e)
: impl_(impl<Executor, std::allocator<void>>::create(e))
{
}
template <typename Executor>
executor::executor(std::nothrow_t, Executor e) noexcept
: impl_(impl<Executor, std::allocator<void>>::create(std::nothrow, e))
{
}
template <typename Executor, typename Allocator>
executor::executor(allocator_arg_t, const Allocator& a, Executor e)
: impl_(impl<Executor, Allocator>::create(e, a))
{
}
template <typename Function, typename Allocator>
void executor::dispatch(Function&& f,
const Allocator& a) const
{
impl_base* i = get_impl();
if (i->fast_dispatch_)
system_executor().dispatch(static_cast<Function&&>(f), a);
else
i->dispatch(function(static_cast<Function&&>(f), a));
}
template <typename Function, typename Allocator>
void executor::post(Function&& f,
const Allocator& a) const
{
get_impl()->post(function(static_cast<Function&&>(f), a));
}
template <typename Function, typename Allocator>
void executor::defer(Function&& f,
const Allocator& a) const
{
get_impl()->defer(function(static_cast<Function&&>(f), a));
}
template <typename Executor>
Executor* executor::target() noexcept
{
return impl_ && impl_->target_type() == type_id<Executor>()
? static_cast<Executor*>(impl_->target()) : 0;
}
template <typename Executor>
const Executor* executor::target() const noexcept
{
return impl_ && impl_->target_type() == type_id<Executor>()
? static_cast<Executor*>(impl_->target()) : 0;
}
#endif // !defined(GENERATING_DOCUMENTATION)
} // namespace asio
#include "asio/detail/pop_options.hpp"
#endif // !defined(ASIO_NO_TS_EXECUTORS)
#endif // ASIO_IMPL_EXECUTOR_HPP
|
0 | repos/asio/asio/include/asio | repos/asio/asio/include/asio/impl/detached.hpp | //
// impl/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 ASIO_IMPL_DETACHED_HPP
#define ASIO_IMPL_DETACHED_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include "asio/detail/config.hpp"
#include "asio/async_result.hpp"
#include "asio/detail/push_options.hpp"
namespace asio {
namespace detail {
// Class to adapt a detached_t as a completion handler.
class detached_handler
{
public:
typedef void result_type;
detached_handler(detached_t)
{
}
template <typename... Args>
void operator()(Args...)
{
}
};
} // namespace detail
#if !defined(GENERATING_DOCUMENTATION)
template <typename... Signatures>
struct async_result<detached_t, Signatures...>
{
typedef asio::detail::detached_handler completion_handler_type;
typedef void return_type;
explicit async_result(completion_handler_type&)
{
}
void get()
{
}
template <typename Initiation, typename RawCompletionToken, typename... Args>
static return_type initiate(Initiation&& initiation,
RawCompletionToken&&, Args&&... args)
{
static_cast<Initiation&&>(initiation)(
detail::detached_handler(detached_t()),
static_cast<Args&&>(args)...);
}
};
#endif // !defined(GENERATING_DOCUMENTATION)
} // namespace asio
#include "asio/detail/pop_options.hpp"
#endif // ASIO_IMPL_DETACHED_HPP
|
0 | repos/asio/asio/include/asio | repos/asio/asio/include/asio/impl/execution_context.hpp | //
// impl/execution_context.hpp
// ~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef ASIO_IMPL_EXECUTION_CONTEXT_HPP
#define ASIO_IMPL_EXECUTION_CONTEXT_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include "asio/detail/handler_type_requirements.hpp"
#include "asio/detail/scoped_ptr.hpp"
#include "asio/detail/service_registry.hpp"
#include "asio/detail/push_options.hpp"
namespace asio {
#if !defined(GENERATING_DOCUMENTATION)
template <typename Service>
inline Service& use_service(execution_context& e)
{
// Check that Service meets the necessary type requirements.
(void)static_cast<execution_context::service*>(static_cast<Service*>(0));
return e.service_registry_->template use_service<Service>();
}
template <typename Service, typename... Args>
Service& make_service(execution_context& e, Args&&... args)
{
detail::scoped_ptr<Service> svc(
new Service(e, static_cast<Args&&>(args)...));
e.service_registry_->template add_service<Service>(svc.get());
Service& result = *svc;
svc.release();
return result;
}
template <typename Service>
inline void add_service(execution_context& e, Service* svc)
{
// Check that Service meets the necessary type requirements.
(void)static_cast<execution_context::service*>(static_cast<Service*>(0));
e.service_registry_->template add_service<Service>(svc);
}
template <typename Service>
inline bool has_service(execution_context& e)
{
// Check that Service meets the necessary type requirements.
(void)static_cast<execution_context::service*>(static_cast<Service*>(0));
return e.service_registry_->template has_service<Service>();
}
#endif // !defined(GENERATING_DOCUMENTATION)
inline execution_context& execution_context::service::context()
{
return owner_;
}
} // namespace asio
#include "asio/detail/pop_options.hpp"
#endif // ASIO_IMPL_EXECUTION_CONTEXT_HPP
|
0 | repos/asio/asio/include/asio | repos/asio/asio/include/asio/impl/serial_port_base.ipp | //
// impl/serial_port_base.ipp
// ~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com)
// Copyright (c) 2008 Rep Invariant Systems, Inc. ([email protected])
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef ASIO_IMPL_SERIAL_PORT_BASE_IPP
#define ASIO_IMPL_SERIAL_PORT_BASE_IPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include "asio/detail/config.hpp"
#if defined(ASIO_HAS_SERIAL_PORT)
#include <stdexcept>
#include "asio/error.hpp"
#include "asio/serial_port_base.hpp"
#include "asio/detail/throw_exception.hpp"
#if defined(GENERATING_DOCUMENTATION)
# define ASIO_OPTION_STORAGE implementation_defined
#elif defined(ASIO_WINDOWS) || defined(__CYGWIN__)
# define ASIO_OPTION_STORAGE DCB
#else
# define ASIO_OPTION_STORAGE termios
#endif
#include "asio/detail/push_options.hpp"
namespace asio {
ASIO_SYNC_OP_VOID serial_port_base::baud_rate::store(
ASIO_OPTION_STORAGE& storage, asio::error_code& ec) const
{
#if defined(ASIO_WINDOWS) || defined(__CYGWIN__)
storage.BaudRate = value_;
#else
speed_t baud;
switch (value_)
{
// Do POSIX-specified rates first.
case 0: baud = B0; break;
case 50: baud = B50; break;
case 75: baud = B75; break;
case 110: baud = B110; break;
case 134: baud = B134; break;
case 150: baud = B150; break;
case 200: baud = B200; break;
case 300: baud = B300; break;
case 600: baud = B600; break;
case 1200: baud = B1200; break;
case 1800: baud = B1800; break;
case 2400: baud = B2400; break;
case 4800: baud = B4800; break;
case 9600: baud = B9600; break;
case 19200: baud = B19200; break;
case 38400: baud = B38400; break;
// And now the extended ones conditionally.
# ifdef B7200
case 7200: baud = B7200; break;
# endif
# ifdef B14400
case 14400: baud = B14400; break;
# endif
# ifdef B57600
case 57600: baud = B57600; break;
# endif
# ifdef B115200
case 115200: baud = B115200; break;
# endif
# ifdef B230400
case 230400: baud = B230400; break;
# endif
# ifdef B460800
case 460800: baud = B460800; break;
# endif
# ifdef B500000
case 500000: baud = B500000; break;
# endif
# ifdef B576000
case 576000: baud = B576000; break;
# endif
# ifdef B921600
case 921600: baud = B921600; break;
# endif
# ifdef B1000000
case 1000000: baud = B1000000; break;
# endif
# ifdef B1152000
case 1152000: baud = B1152000; break;
# endif
# ifdef B2000000
case 2000000: baud = B2000000; break;
# endif
# ifdef B3000000
case 3000000: baud = B3000000; break;
# endif
# ifdef B3500000
case 3500000: baud = B3500000; break;
# endif
# ifdef B4000000
case 4000000: baud = B4000000; break;
# endif
default:
ec = asio::error::invalid_argument;
ASIO_SYNC_OP_VOID_RETURN(ec);
}
# if defined(_BSD_SOURCE) || defined(_DEFAULT_SOURCE)
::cfsetspeed(&storage, baud);
# else
::cfsetispeed(&storage, baud);
::cfsetospeed(&storage, baud);
# endif
#endif
ec = asio::error_code();
ASIO_SYNC_OP_VOID_RETURN(ec);
}
ASIO_SYNC_OP_VOID serial_port_base::baud_rate::load(
const ASIO_OPTION_STORAGE& storage, asio::error_code& ec)
{
#if defined(ASIO_WINDOWS) || defined(__CYGWIN__)
value_ = storage.BaudRate;
#else
speed_t baud = ::cfgetospeed(&storage);
switch (baud)
{
// First do those specified by POSIX.
case B0: value_ = 0; break;
case B50: value_ = 50; break;
case B75: value_ = 75; break;
case B110: value_ = 110; break;
case B134: value_ = 134; break;
case B150: value_ = 150; break;
case B200: value_ = 200; break;
case B300: value_ = 300; break;
case B600: value_ = 600; break;
case B1200: value_ = 1200; break;
case B1800: value_ = 1800; break;
case B2400: value_ = 2400; break;
case B4800: value_ = 4800; break;
case B9600: value_ = 9600; break;
case B19200: value_ = 19200; break;
case B38400: value_ = 38400; break;
// Now conditionally handle a bunch of extended rates.
# ifdef B7200
case B7200: value_ = 7200; break;
# endif
# ifdef B14400
case B14400: value_ = 14400; break;
# endif
# ifdef B57600
case B57600: value_ = 57600; break;
# endif
# ifdef B115200
case B115200: value_ = 115200; break;
# endif
# ifdef B230400
case B230400: value_ = 230400; break;
# endif
# ifdef B460800
case B460800: value_ = 460800; break;
# endif
# ifdef B500000
case B500000: value_ = 500000; break;
# endif
# ifdef B576000
case B576000: value_ = 576000; break;
# endif
# ifdef B921600
case B921600: value_ = 921600; break;
# endif
# ifdef B1000000
case B1000000: value_ = 1000000; break;
# endif
# ifdef B1152000
case B1152000: value_ = 1152000; break;
# endif
# ifdef B2000000
case B2000000: value_ = 2000000; break;
# endif
# ifdef B3000000
case B3000000: value_ = 3000000; break;
# endif
# ifdef B3500000
case B3500000: value_ = 3500000; break;
# endif
# ifdef B4000000
case B4000000: value_ = 4000000; break;
# endif
default:
value_ = 0;
ec = asio::error::invalid_argument;
ASIO_SYNC_OP_VOID_RETURN(ec);
}
#endif
ec = asio::error_code();
ASIO_SYNC_OP_VOID_RETURN(ec);
}
serial_port_base::flow_control::flow_control(
serial_port_base::flow_control::type t)
: value_(t)
{
if (t != none && t != software && t != hardware)
{
std::out_of_range ex("invalid flow_control value");
asio::detail::throw_exception(ex);
}
}
ASIO_SYNC_OP_VOID serial_port_base::flow_control::store(
ASIO_OPTION_STORAGE& storage, asio::error_code& ec) const
{
#if defined(ASIO_WINDOWS) || defined(__CYGWIN__)
storage.fOutxCtsFlow = FALSE;
storage.fOutxDsrFlow = FALSE;
storage.fTXContinueOnXoff = TRUE;
storage.fDtrControl = DTR_CONTROL_ENABLE;
storage.fDsrSensitivity = FALSE;
storage.fOutX = FALSE;
storage.fInX = FALSE;
storage.fRtsControl = RTS_CONTROL_ENABLE;
switch (value_)
{
case none:
break;
case software:
storage.fOutX = TRUE;
storage.fInX = TRUE;
break;
case hardware:
storage.fOutxCtsFlow = TRUE;
storage.fRtsControl = RTS_CONTROL_HANDSHAKE;
break;
default:
break;
}
#else
switch (value_)
{
case none:
storage.c_iflag &= ~(IXOFF | IXON);
# if defined(_BSD_SOURCE) || defined(_DEFAULT_SOURCE)
storage.c_cflag &= ~CRTSCTS;
# elif defined(__QNXNTO__)
storage.c_cflag &= ~(IHFLOW | OHFLOW);
# endif
break;
case software:
storage.c_iflag |= IXOFF | IXON;
# if defined(_BSD_SOURCE) || defined(_DEFAULT_SOURCE)
storage.c_cflag &= ~CRTSCTS;
# elif defined(__QNXNTO__)
storage.c_cflag &= ~(IHFLOW | OHFLOW);
# endif
break;
case hardware:
# if defined(_BSD_SOURCE) || defined(_DEFAULT_SOURCE)
storage.c_iflag &= ~(IXOFF | IXON);
storage.c_cflag |= CRTSCTS;
break;
# elif defined(__QNXNTO__)
storage.c_iflag &= ~(IXOFF | IXON);
storage.c_cflag |= (IHFLOW | OHFLOW);
break;
# else
ec = asio::error::operation_not_supported;
ASIO_SYNC_OP_VOID_RETURN(ec);
# endif
default:
break;
}
#endif
ec = asio::error_code();
ASIO_SYNC_OP_VOID_RETURN(ec);
}
ASIO_SYNC_OP_VOID serial_port_base::flow_control::load(
const ASIO_OPTION_STORAGE& storage, asio::error_code& ec)
{
#if defined(ASIO_WINDOWS) || defined(__CYGWIN__)
if (storage.fOutX && storage.fInX)
{
value_ = software;
}
else if (storage.fOutxCtsFlow && storage.fRtsControl == RTS_CONTROL_HANDSHAKE)
{
value_ = hardware;
}
else
{
value_ = none;
}
#else
if (storage.c_iflag & (IXOFF | IXON))
{
value_ = software;
}
# if defined(_BSD_SOURCE) || defined(_DEFAULT_SOURCE)
else if (storage.c_cflag & CRTSCTS)
{
value_ = hardware;
}
# elif defined(__QNXNTO__)
else if (storage.c_cflag & IHFLOW && storage.c_cflag & OHFLOW)
{
value_ = hardware;
}
# endif
else
{
value_ = none;
}
#endif
ec = asio::error_code();
ASIO_SYNC_OP_VOID_RETURN(ec);
}
serial_port_base::parity::parity(serial_port_base::parity::type t)
: value_(t)
{
if (t != none && t != odd && t != even)
{
std::out_of_range ex("invalid parity value");
asio::detail::throw_exception(ex);
}
}
ASIO_SYNC_OP_VOID serial_port_base::parity::store(
ASIO_OPTION_STORAGE& storage, asio::error_code& ec) const
{
#if defined(ASIO_WINDOWS) || defined(__CYGWIN__)
switch (value_)
{
case none:
storage.fParity = FALSE;
storage.Parity = NOPARITY;
break;
case odd:
storage.fParity = TRUE;
storage.Parity = ODDPARITY;
break;
case even:
storage.fParity = TRUE;
storage.Parity = EVENPARITY;
break;
default:
break;
}
#else
switch (value_)
{
case none:
storage.c_iflag |= IGNPAR;
storage.c_cflag &= ~(PARENB | PARODD);
break;
case even:
storage.c_iflag &= ~(IGNPAR | PARMRK);
storage.c_iflag |= INPCK;
storage.c_cflag |= PARENB;
storage.c_cflag &= ~PARODD;
break;
case odd:
storage.c_iflag &= ~(IGNPAR | PARMRK);
storage.c_iflag |= INPCK;
storage.c_cflag |= (PARENB | PARODD);
break;
default:
break;
}
#endif
ec = asio::error_code();
ASIO_SYNC_OP_VOID_RETURN(ec);
}
ASIO_SYNC_OP_VOID serial_port_base::parity::load(
const ASIO_OPTION_STORAGE& storage, asio::error_code& ec)
{
#if defined(ASIO_WINDOWS) || defined(__CYGWIN__)
if (storage.Parity == EVENPARITY)
{
value_ = even;
}
else if (storage.Parity == ODDPARITY)
{
value_ = odd;
}
else
{
value_ = none;
}
#else
if (storage.c_cflag & PARENB)
{
if (storage.c_cflag & PARODD)
{
value_ = odd;
}
else
{
value_ = even;
}
}
else
{
value_ = none;
}
#endif
ec = asio::error_code();
ASIO_SYNC_OP_VOID_RETURN(ec);
}
serial_port_base::stop_bits::stop_bits(
serial_port_base::stop_bits::type t)
: value_(t)
{
if (t != one && t != onepointfive && t != two)
{
std::out_of_range ex("invalid stop_bits value");
asio::detail::throw_exception(ex);
}
}
ASIO_SYNC_OP_VOID serial_port_base::stop_bits::store(
ASIO_OPTION_STORAGE& storage, asio::error_code& ec) const
{
#if defined(ASIO_WINDOWS) || defined(__CYGWIN__)
switch (value_)
{
case one:
storage.StopBits = ONESTOPBIT;
break;
case onepointfive:
storage.StopBits = ONE5STOPBITS;
break;
case two:
storage.StopBits = TWOSTOPBITS;
break;
default:
break;
}
#else
switch (value_)
{
case one:
storage.c_cflag &= ~CSTOPB;
break;
case two:
storage.c_cflag |= CSTOPB;
break;
default:
ec = asio::error::operation_not_supported;
ASIO_SYNC_OP_VOID_RETURN(ec);
}
#endif
ec = asio::error_code();
ASIO_SYNC_OP_VOID_RETURN(ec);
}
ASIO_SYNC_OP_VOID serial_port_base::stop_bits::load(
const ASIO_OPTION_STORAGE& storage, asio::error_code& ec)
{
#if defined(ASIO_WINDOWS) || defined(__CYGWIN__)
if (storage.StopBits == ONESTOPBIT)
{
value_ = one;
}
else if (storage.StopBits == ONE5STOPBITS)
{
value_ = onepointfive;
}
else if (storage.StopBits == TWOSTOPBITS)
{
value_ = two;
}
else
{
value_ = one;
}
#else
value_ = (storage.c_cflag & CSTOPB) ? two : one;
#endif
ec = asio::error_code();
ASIO_SYNC_OP_VOID_RETURN(ec);
}
serial_port_base::character_size::character_size(unsigned int t)
: value_(t)
{
if (t < 5 || t > 8)
{
std::out_of_range ex("invalid character_size value");
asio::detail::throw_exception(ex);
}
}
ASIO_SYNC_OP_VOID serial_port_base::character_size::store(
ASIO_OPTION_STORAGE& storage, asio::error_code& ec) const
{
#if defined(ASIO_WINDOWS) || defined(__CYGWIN__)
storage.ByteSize = value_;
#else
storage.c_cflag &= ~CSIZE;
switch (value_)
{
case 5: storage.c_cflag |= CS5; break;
case 6: storage.c_cflag |= CS6; break;
case 7: storage.c_cflag |= CS7; break;
case 8: storage.c_cflag |= CS8; break;
default: break;
}
#endif
ec = asio::error_code();
ASIO_SYNC_OP_VOID_RETURN(ec);
}
ASIO_SYNC_OP_VOID serial_port_base::character_size::load(
const ASIO_OPTION_STORAGE& storage, asio::error_code& ec)
{
#if defined(ASIO_WINDOWS) || defined(__CYGWIN__)
value_ = storage.ByteSize;
#else
if ((storage.c_cflag & CSIZE) == CS5) { value_ = 5; }
else if ((storage.c_cflag & CSIZE) == CS6) { value_ = 6; }
else if ((storage.c_cflag & CSIZE) == CS7) { value_ = 7; }
else if ((storage.c_cflag & CSIZE) == CS8) { value_ = 8; }
else
{
// Hmmm, use 8 for now.
value_ = 8;
}
#endif
ec = asio::error_code();
ASIO_SYNC_OP_VOID_RETURN(ec);
}
} // namespace asio
#include "asio/detail/pop_options.hpp"
#undef ASIO_OPTION_STORAGE
#endif // defined(ASIO_HAS_SERIAL_PORT)
#endif // ASIO_IMPL_SERIAL_PORT_BASE_IPP
|
0 | repos/asio/asio/include/asio | repos/asio/asio/include/asio/experimental/promise.hpp | //
// experimental/promise.hpp
// ~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2021-2023 Klemens D. Morgenstern
// (klemens dot morgenstern at gmx dot net)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef ASIO_EXPERIMENTAL_PROMISE_HPP
#define ASIO_EXPERIMENTAL_PROMISE_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include "asio/detail/config.hpp"
#include "asio/detail/type_traits.hpp"
#include "asio/any_io_executor.hpp"
#include "asio/associated_cancellation_slot.hpp"
#include "asio/associated_executor.hpp"
#include "asio/bind_executor.hpp"
#include "asio/cancellation_signal.hpp"
#include "asio/dispatch.hpp"
#include "asio/experimental/impl/promise.hpp"
#include "asio/post.hpp"
#include <algorithm>
#include "asio/detail/push_options.hpp"
namespace asio {
namespace experimental {
template <typename T>
struct is_promise : std::false_type {};
template <typename ... Ts>
struct is_promise<promise<Ts...>> : std::true_type {};
template <typename T>
constexpr bool is_promise_v = is_promise<T>::value;
template <typename ... Ts>
struct promise_value_type
{
using type = std::tuple<Ts...>;
};
template <typename T>
struct promise_value_type<T>
{
using type = T;
};
template <>
struct promise_value_type<>
{
using type = std::tuple<>;
};
#if defined(GENERATING_DOCUMENTATION)
/// A disposable handle for an eager operation.
/**
* @tparam Signature The signature of the operation.
*
* @tparam Executor The executor to be used by the promise (taken from the
* operation).
*
* @tparam Allocator The allocator used for the promise. Can be set through
* use_allocator.
*
* A promise can be used to initiate an asynchronous option that can be
* completed later. If the promise gets destroyed before completion, the
* operation gets a cancel signal and the result is ignored.
*
* A promise fulfills the requirements of async_operation.
*
* @par Examples
* Reading and writing from one coroutine.
* @code
* awaitable<void> read_write_some(asio::ip::tcp::socket & sock,
* asio::mutable_buffer read_buf, asio::const_buffer to_write)
* {
* auto p = asio::async_read(read_buf,
* asio::experimental::use_promise);
* co_await asio::async_write_some(to_write);
* co_await p;
* }
* @endcode
*/
template<typename Signature = void(),
typename Executor = asio::any_io_executor,
typename Allocator = std::allocator<void>>
struct promise
#else
template <typename ... Ts, typename Executor, typename Allocator>
struct promise<void(Ts...), Executor, Allocator>
#endif // defined(GENERATING_DOCUMENTATION)
{
/// The value that's returned by the promise.
using value_type = typename promise_value_type<Ts...>::type;
/// Cancel the promise. Usually done through the destructor.
void cancel(cancellation_type level = cancellation_type::all)
{
if (impl_ && !impl_->done)
{
asio::dispatch(impl_->executor,
[level, impl = impl_]{ impl->cancel.emit(level); });
}
}
/// Check if the promise is completed already.
bool completed() const noexcept
{
return impl_ && impl_->done;
}
/// Wait for the promise to become ready.
template <ASIO_COMPLETION_TOKEN_FOR(void(Ts...)) CompletionToken>
inline ASIO_INITFN_AUTO_RESULT_TYPE(CompletionToken, void(Ts...))
operator()(CompletionToken&& token)
{
assert(impl_);
return async_initiate<CompletionToken, void(Ts...)>(
initiate_async_wait{impl_}, token);
}
promise() = delete;
promise(const promise& ) = delete;
promise(promise&& ) noexcept = default;
/// Destruct the promise and cancel the operation.
/**
* It is safe to destruct a promise of a promise that didn't complete.
*/
~promise() { cancel(); }
private:
#if !defined(GENERATING_DOCUMENTATION)
template <typename, typename, typename> friend struct promise;
friend struct detail::promise_handler<void(Ts...), Executor, Allocator>;
#endif // !defined(GENERATING_DOCUMENTATION)
std::shared_ptr<detail::promise_impl<
void(Ts...), Executor, Allocator>> impl_;
promise(
std::shared_ptr<detail::promise_impl<
void(Ts...), Executor, Allocator>> impl)
: impl_(impl)
{
}
struct initiate_async_wait
{
std::shared_ptr<detail::promise_impl<
void(Ts...), Executor, Allocator>> self_;
template <typename WaitHandler>
void operator()(WaitHandler&& handler) const
{
const auto alloc = get_associated_allocator(
handler, self_->get_allocator());
auto cancel = get_associated_cancellation_slot(handler);
if (self_->done)
{
auto exec = asio::get_associated_executor(
handler, self_->get_executor());
asio::post(exec,
[self = std::move(self_),
handler = std::forward<WaitHandler>(handler)]() mutable
{
self->apply(std::move(handler));
});
}
else
{
if (cancel.is_connected())
{
struct cancel_handler
{
std::weak_ptr<detail::promise_impl<
void(Ts...), Executor, Allocator>> self;
cancel_handler(
std::weak_ptr<detail::promise_impl<
void(Ts...), Executor, Allocator>> self)
: self(std::move(self))
{
}
void operator()(cancellation_type level) const
{
if (auto p = self.lock())
{
p->cancel.emit(level);
p->cancel_();
}
}
};
cancel.template emplace<cancel_handler>(self_);
}
self_->set_completion(alloc, std::forward<WaitHandler>(handler));
}
}
};
};
} // namespace experimental
} // namespace asio
#include "asio/detail/pop_options.hpp"
#endif // ASIO_EXPERIMENTAL_PROMISE_HPP
|
0 | repos/asio/asio/include/asio | repos/asio/asio/include/asio/experimental/coro_traits.hpp | //
// experimental/detail/coro_traits.hpp
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2021-2023 Klemens D. Morgenstern
// (klemens dot morgenstern at gmx dot net)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef ASIO_EXPERIMENTAL_DETAIL_CORO_TRAITS_HPP
#define ASIO_EXPERIMENTAL_DETAIL_CORO_TRAITS_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include "asio/detail/config.hpp"
#include <optional>
#include <variant>
#include "asio/any_io_executor.hpp"
namespace asio {
namespace experimental {
namespace detail {
template <class From, class To>
concept convertible_to = std::is_convertible_v<From, To>;
template <typename T>
concept decays_to_executor = execution::executor<std::decay_t<T>>;
template <typename T, typename Executor = any_io_executor>
concept execution_context = requires (T& t)
{
{t.get_executor()} -> convertible_to<Executor>;
};
template <typename Yield, typename Return>
struct coro_result
{
using type = std::variant<Yield, Return>;
};
template <typename Yield>
struct coro_result<Yield, void>
{
using type = std::optional<Yield>;
};
template <typename Return>
struct coro_result<void, Return>
{
using type = Return;
};
template <typename YieldReturn>
struct coro_result<YieldReturn, YieldReturn>
{
using type = YieldReturn;
};
template <>
struct coro_result<void, void>
{
using type = void;
};
template <typename Yield, typename Return>
using coro_result_t = typename coro_result<Yield, Return>::type;
template <typename Result, bool IsNoexcept>
struct coro_handler;
template <>
struct coro_handler<void, false>
{
using type = void(std::exception_ptr);
};
template <>
struct coro_handler<void, true>
{
using type = void();
};
template <typename T>
struct coro_handler<T, false>
{
using type = void(std::exception_ptr, T);
};
template <typename T>
struct coro_handler<T, true>
{
using type = void(T);
};
template <typename Result, bool IsNoexcept>
using coro_handler_t = typename coro_handler<Result, IsNoexcept>::type;
} // namespace detail
#if defined(GENERATING_DOCUMENTATION)
/// The traits describing the resumable coroutine behaviour.
/**
* Template parameter @c Yield specifies type or signature used by co_yield,
* @c Return specifies the type used for co_return, and @c Executor specifies
* the underlying executor type.
*/
template <typename Yield, typename Return, typename Executor>
struct coro_traits
{
/// The value that can be passed into a symmetrical cororoutine. @c void if
/// asymmetrical.
using input_type = argument_dependent;
/// The type that can be passed out through a co_yield.
using yield_type = argument_dependent;
/// The type that can be passed out through a co_return.
using return_type = argument_dependent;
/// The type received by a co_await or async_resume. It's a combination of
/// yield and return.
using result_type = argument_dependent;
/// The signature used by the async_resume.
using signature_type = argument_dependent;
/// Whether or not the coroutine is noexcept.
constexpr static bool is_noexcept = argument_dependent;
/// The error type of the coroutine. @c void for noexcept.
using error_type = argument_dependent;
/// Completion handler type used by async_resume.
using completion_handler = argument_dependent;
};
#else // defined(GENERATING_DOCUMENTATION)
template <typename Yield, typename Return, typename Executor>
struct coro_traits
{
using input_type = void;
using yield_type = Yield;
using return_type = Return;
using result_type = detail::coro_result_t<yield_type, return_type>;
using signature_type = result_type();
constexpr static bool is_noexcept = false;
using error_type = std::conditional_t<is_noexcept, void, std::exception_ptr>;
using completion_handler = detail::coro_handler_t<result_type, is_noexcept>;
};
template <typename T, typename Return, typename Executor>
struct coro_traits<T(), Return, Executor>
{
using input_type = void;
using yield_type = T;
using return_type = Return;
using result_type = detail::coro_result_t<yield_type, return_type>;
using signature_type = result_type();
constexpr static bool is_noexcept = false;
using error_type = std::conditional_t<is_noexcept, void, std::exception_ptr>;
using completion_handler = detail::coro_handler_t<result_type, is_noexcept>;
};
template <typename T, typename Return, typename Executor>
struct coro_traits<T() noexcept, Return, Executor>
{
using input_type = void;
using yield_type = T;
using return_type = Return;
using result_type = detail::coro_result_t<yield_type, return_type>;
using signature_type = result_type();
constexpr static bool is_noexcept = true;
using error_type = std::conditional_t<is_noexcept, void, std::exception_ptr>;
using completion_handler = detail::coro_handler_t<result_type, is_noexcept>;
};
template <typename T, typename U, typename Return, typename Executor>
struct coro_traits<T(U), Return, Executor>
{
using input_type = U;
using yield_type = T;
using return_type = Return;
using result_type = detail::coro_result_t<yield_type, return_type>;
using signature_type = result_type(input_type);
constexpr static bool is_noexcept = false;
using error_type = std::conditional_t<is_noexcept, void, std::exception_ptr>;
using completion_handler = detail::coro_handler_t<result_type, is_noexcept>;
};
template <typename T, typename U, typename Return, typename Executor>
struct coro_traits<T(U) noexcept, Return, Executor>
{
using input_type = U;
using yield_type = T;
using return_type = Return;
using result_type = detail::coro_result_t<yield_type, return_type>;
using signature_type = result_type(input_type);
constexpr static bool is_noexcept = true;
using error_type = std::conditional_t<is_noexcept, void, std::exception_ptr>;
using completion_handler = detail::coro_handler_t<result_type, is_noexcept>;
};
template <typename Executor>
struct coro_traits<void() noexcept, void, Executor>
{
using input_type = void;
using yield_type = void;
using return_type = void;
using result_type = detail::coro_result_t<yield_type, return_type>;
using signature_type = result_type(input_type);
constexpr static bool is_noexcept = true;
using error_type = std::conditional_t<is_noexcept, void, std::exception_ptr>;
using completion_handler = detail::coro_handler_t<result_type, is_noexcept>;
};
#endif // defined(GENERATING_DOCUMENTATION)
} // namespace experimental
} // namespace asio
#endif // ASIO_EXPERIMENTAL_DETAIL_CORO_TRAITS_HPP
|
0 | repos/asio/asio/include/asio | repos/asio/asio/include/asio/experimental/concurrent_channel.hpp | //
// experimental/concurrent_channel.hpp
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef ASIO_EXPERIMENTAL_CONCURRENT_CHANNEL_HPP
#define ASIO_EXPERIMENTAL_CONCURRENT_CHANNEL_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include "asio/detail/config.hpp"
#include "asio/any_io_executor.hpp"
#include "asio/detail/type_traits.hpp"
#include "asio/execution/executor.hpp"
#include "asio/is_executor.hpp"
#include "asio/experimental/basic_concurrent_channel.hpp"
#include "asio/experimental/channel_traits.hpp"
#include "asio/detail/push_options.hpp"
namespace asio {
namespace experimental {
namespace detail {
template <typename ExecutorOrSignature, typename = void>
struct concurrent_channel_type
{
template <typename... Signatures>
struct inner
{
typedef basic_concurrent_channel<any_io_executor, channel_traits<>,
ExecutorOrSignature, Signatures...> type;
};
};
template <typename ExecutorOrSignature>
struct concurrent_channel_type<ExecutorOrSignature,
enable_if_t<
is_executor<ExecutorOrSignature>::value
|| execution::is_executor<ExecutorOrSignature>::value
>>
{
template <typename... Signatures>
struct inner
{
typedef basic_concurrent_channel<ExecutorOrSignature,
channel_traits<>, Signatures...> type;
};
};
} // namespace detail
/// Template type alias for common use of channel.
template <typename ExecutorOrSignature, typename... Signatures>
using concurrent_channel = typename detail::concurrent_channel_type<
ExecutorOrSignature>::template inner<Signatures...>::type;
} // namespace experimental
} // namespace asio
#include "asio/detail/pop_options.hpp"
#endif // ASIO_EXPERIMENTAL_CONCURRENT_CHANNEL_HPP
|
0 | repos/asio/asio/include/asio | repos/asio/asio/include/asio/experimental/basic_channel.hpp | //
// experimental/basic_channel.hpp
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef ASIO_EXPERIMENTAL_BASIC_CHANNEL_HPP
#define ASIO_EXPERIMENTAL_BASIC_CHANNEL_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include "asio/detail/config.hpp"
#include "asio/detail/non_const_lvalue.hpp"
#include "asio/detail/null_mutex.hpp"
#include "asio/execution/executor.hpp"
#include "asio/execution_context.hpp"
#include "asio/experimental/detail/channel_send_functions.hpp"
#include "asio/experimental/detail/channel_service.hpp"
#include "asio/detail/push_options.hpp"
namespace asio {
namespace experimental {
namespace detail {
} // namespace detail
/// A channel for messages.
/**
* The basic_channel class template is used for sending messages between
* different parts of the same application. A <em>message</em> is defined as a
* collection of arguments to be passed to a completion handler, and the set of
* messages supported by a channel is specified by its @c Traits and
* <tt>Signatures...</tt> template parameters. Messages may be sent and received
* using asynchronous or non-blocking synchronous operations.
*
* Unless customising the traits, applications will typically use the @c
* experimental::channel alias template. For example:
* @code void send_loop(int i, steady_timer& timer,
* channel<void(error_code, int)>& ch)
* {
* if (i < 10)
* {
* timer.expires_after(chrono::seconds(1));
* timer.async_wait(
* [i, &timer, &ch](error_code error)
* {
* if (!error)
* {
* ch.async_send(error_code(), i,
* [i, &timer, &ch](error_code error)
* {
* if (!error)
* {
* send_loop(i + 1, timer, ch);
* }
* });
* }
* });
* }
* else
* {
* ch.close();
* }
* }
*
* void receive_loop(channel<void(error_code, int)>& ch)
* {
* ch.async_receive(
* [&ch](error_code error, int i)
* {
* if (!error)
* {
* std::cout << "Received " << i << "\n";
* receive_loop(ch);
* }
* });
* } @endcode
*
* @par Thread Safety
* @e Distinct @e objects: Safe.@n
* @e Shared @e objects: Unsafe.
*
* The basic_channel class template is not thread-safe, and would typically be
* used for passing messages between application code that runs on the same
* thread or in the same strand. Consider using @ref basic_concurrent_channel,
* and its alias template @c experimental::concurrent_channel, to pass messages
* between code running in different threads.
*/
template <typename Executor, typename Traits, typename... Signatures>
class basic_channel
#if !defined(GENERATING_DOCUMENTATION)
: public detail::channel_send_functions<
basic_channel<Executor, Traits, Signatures...>,
Executor, Signatures...>
#endif // !defined(GENERATING_DOCUMENTATION)
{
private:
class initiate_async_send;
class initiate_async_receive;
typedef detail::channel_service<asio::detail::null_mutex> service_type;
typedef typename service_type::template implementation_type<
Traits, Signatures...>::payload_type payload_type;
template <typename... PayloadSignatures,
ASIO_COMPLETION_TOKEN_FOR(PayloadSignatures...) CompletionToken>
auto do_async_receive(
asio::detail::completion_payload<PayloadSignatures...>*,
CompletionToken&& token)
-> decltype(
async_initiate<CompletionToken, PayloadSignatures...>(
declval<initiate_async_receive>(), token))
{
return async_initiate<CompletionToken, PayloadSignatures...>(
initiate_async_receive(this), token);
}
public:
/// The type of the executor associated with the channel.
typedef Executor executor_type;
/// Rebinds the channel type to another executor.
template <typename Executor1>
struct rebind_executor
{
/// The channel type when rebound to the specified executor.
typedef basic_channel<Executor1, Traits, Signatures...> other;
};
/// The traits type associated with the channel.
typedef typename Traits::template rebind<Signatures...>::other traits_type;
/// Construct a basic_channel.
/**
* This constructor creates and channel.
*
* @param ex The I/O executor that the channel will use, by default, to
* dispatch handlers for any asynchronous operations performed on the channel.
*
* @param max_buffer_size The maximum number of messages that may be buffered
* in the channel.
*/
basic_channel(const executor_type& ex, std::size_t max_buffer_size = 0)
: service_(&asio::use_service<service_type>(
basic_channel::get_context(ex))),
impl_(),
executor_(ex)
{
service_->construct(impl_, max_buffer_size);
}
/// Construct and open a basic_channel.
/**
* This constructor creates and opens a channel.
*
* @param context An execution context which provides the I/O executor that
* the channel will use, by default, to dispatch handlers for any asynchronous
* operations performed on the channel.
*
* @param max_buffer_size The maximum number of messages that may be buffered
* in the channel.
*/
template <typename ExecutionContext>
basic_channel(ExecutionContext& context, std::size_t max_buffer_size = 0,
constraint_t<
is_convertible<ExecutionContext&, execution_context&>::value,
defaulted_constraint
> = defaulted_constraint())
: service_(&asio::use_service<service_type>(context)),
impl_(),
executor_(context.get_executor())
{
service_->construct(impl_, max_buffer_size);
}
/// Move-construct a basic_channel from another.
/**
* This constructor moves a channel from one object to another.
*
* @param other The other basic_channel 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_channel(const executor_type&) constructor.
*/
basic_channel(basic_channel&& other)
: service_(other.service_),
executor_(other.executor_)
{
service_->move_construct(impl_, other.impl_);
}
/// Move-assign a basic_channel from another.
/**
* This assignment operator moves a channel from one object to another.
* Cancels any outstanding asynchronous operations associated with the target
* object.
*
* @param other The other basic_channel 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_channel(const executor_type&)
* constructor.
*/
basic_channel& operator=(basic_channel&& other)
{
if (this != &other)
{
service_->move_assign(impl_, *other.service_, other.impl_);
executor_.~executor_type();
new (&executor_) executor_type(other.executor_);
service_ = other.service_;
}
return *this;
}
// All channels have access to each other's implementations.
template <typename, typename, typename...>
friend class basic_channel;
/// Move-construct a basic_channel from another.
/**
* This constructor moves a channel from one object to another.
*
* @param other The other basic_channel 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_channel(const executor_type&)
* constructor.
*/
template <typename Executor1>
basic_channel(
basic_channel<Executor1, Traits, Signatures...>&& other,
constraint_t<
is_convertible<Executor1, Executor>::value
> = 0)
: service_(other.service_),
executor_(other.executor_)
{
service_->move_construct(impl_, other.impl_);
}
/// Move-assign a basic_channel from another.
/**
* This assignment operator moves a channel from one object to another.
* Cancels any outstanding asynchronous operations associated with the target
* object.
*
* @param other The other basic_channel 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_channel(const executor_type&)
* constructor.
*/
template <typename Executor1>
constraint_t<
is_convertible<Executor1, Executor>::value,
basic_channel&
> operator=(basic_channel<Executor1, Traits, Signatures...>&& other)
{
if (this != &other)
{
service_->move_assign(impl_, *other.service_, other.impl_);
executor_.~executor_type();
new (&executor_) executor_type(other.executor_);
service_ = other.service_;
}
return *this;
}
/// Destructor.
~basic_channel()
{
service_->destroy(impl_);
}
/// Get the executor associated with the object.
const executor_type& get_executor() noexcept
{
return executor_;
}
/// Get the capacity of the channel's buffer.
std::size_t capacity() noexcept
{
return service_->capacity(impl_);
}
/// Determine whether the channel is open.
bool is_open() const noexcept
{
return service_->is_open(impl_);
}
/// Reset the channel to its initial state.
void reset()
{
service_->reset(impl_);
}
/// Close the channel.
void close()
{
service_->close(impl_);
}
/// Cancel all asynchronous operations waiting on the channel.
/**
* All outstanding send operations will complete with the error
* @c asio::experimental::error::channel_cancelled. Outstanding receive
* operations complete with the result as determined by the channel traits.
*/
void cancel()
{
service_->cancel(impl_);
}
/// Determine whether a message can be received without blocking.
bool ready() const noexcept
{
return service_->ready(impl_);
}
#if defined(GENERATING_DOCUMENTATION)
/// Try to send a message without blocking.
/**
* Fails if the buffer is full and there are no waiting receive operations.
*
* @returns @c true on success, @c false on failure.
*/
template <typename... Args>
bool try_send(Args&&... args);
/// Try to send a message without blocking, using dispatch semantics to call
/// the receive operation's completion handler.
/**
* Fails if the buffer is full and there are no waiting receive operations.
*
* The receive operation's completion handler may be called from inside this
* function.
*
* @returns @c true on success, @c false on failure.
*/
template <typename... Args>
bool try_send_via_dispatch(Args&&... args);
/// Try to send a number of messages without blocking.
/**
* @returns The number of messages that were sent.
*/
template <typename... Args>
std::size_t try_send_n(std::size_t count, Args&&... args);
/// Try to send a number of messages without blocking, using dispatch
/// semantics to call the receive operations' completion handlers.
/**
* The receive operations' completion handlers may be called from inside this
* function.
*
* @returns The number of messages that were sent.
*/
template <typename... Args>
std::size_t try_send_n_via_dispatch(std::size_t count, Args&&... args);
/// Asynchronously send a message.
/**
* @par Completion Signature
* @code void(asio::error_code) @endcode
*/
template <typename... Args,
ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code))
CompletionToken ASIO_DEFAULT_COMPLETION_TOKEN_TYPE(executor_type)>
auto async_send(Args&&... args,
CompletionToken&& token);
#endif // defined(GENERATING_DOCUMENTATION)
/// Try to receive a message without blocking.
/**
* Fails if the buffer is full and there are no waiting receive operations.
*
* @returns @c true on success, @c false on failure.
*/
template <typename Handler>
bool try_receive(Handler&& handler)
{
return service_->try_receive(impl_, static_cast<Handler&&>(handler));
}
/// Asynchronously receive a message.
/**
* @par Completion Signature
* As determined by the <tt>Signatures...</tt> template parameter and the
* channel traits.
*/
template <typename CompletionToken
ASIO_DEFAULT_COMPLETION_TOKEN_TYPE(executor_type)>
auto async_receive(
CompletionToken&& token
ASIO_DEFAULT_COMPLETION_TOKEN(Executor))
#if !defined(GENERATING_DOCUMENTATION)
-> decltype(
this->do_async_receive(static_cast<payload_type*>(0),
static_cast<CompletionToken&&>(token)))
#endif // !defined(GENERATING_DOCUMENTATION)
{
return this->do_async_receive(static_cast<payload_type*>(0),
static_cast<CompletionToken&&>(token));
}
private:
// Disallow copying and assignment.
basic_channel(const basic_channel&) = delete;
basic_channel& operator=(const basic_channel&) = delete;
template <typename, typename, typename...>
friend class detail::channel_send_functions;
// Helper function to get an executor's context.
template <typename T>
static execution_context& get_context(const T& t,
enable_if_t<execution::is_executor<T>::value>* = 0)
{
return asio::query(t, execution::context);
}
// Helper function to get an executor's context.
template <typename T>
static execution_context& get_context(const T& t,
enable_if_t<!execution::is_executor<T>::value>* = 0)
{
return t.context();
}
class initiate_async_send
{
public:
typedef Executor executor_type;
explicit initiate_async_send(basic_channel* self)
: self_(self)
{
}
const executor_type& get_executor() const noexcept
{
return self_->get_executor();
}
template <typename SendHandler>
void operator()(SendHandler&& handler,
payload_type&& payload) const
{
asio::detail::non_const_lvalue<SendHandler> handler2(handler);
self_->service_->async_send(self_->impl_,
static_cast<payload_type&&>(payload),
handler2.value, self_->get_executor());
}
private:
basic_channel* self_;
};
class initiate_async_receive
{
public:
typedef Executor executor_type;
explicit initiate_async_receive(basic_channel* self)
: self_(self)
{
}
const executor_type& get_executor() const noexcept
{
return self_->get_executor();
}
template <typename ReceiveHandler>
void operator()(ReceiveHandler&& handler) const
{
asio::detail::non_const_lvalue<ReceiveHandler> handler2(handler);
self_->service_->async_receive(self_->impl_,
handler2.value, self_->get_executor());
}
private:
basic_channel* self_;
};
// The service associated with the I/O object.
service_type* service_;
// The underlying implementation of the I/O object.
typename service_type::template implementation_type<
Traits, Signatures...> impl_;
// The associated executor.
Executor executor_;
};
} // namespace experimental
} // namespace asio
#include "asio/detail/pop_options.hpp"
#endif // ASIO_EXPERIMENTAL_BASIC_CHANNEL_HPP
|
0 | repos/asio/asio/include/asio | repos/asio/asio/include/asio/experimental/basic_concurrent_channel.hpp | //
// experimental/basic_concurrent_channel.hpp
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef ASIO_EXPERIMENTAL_BASIC_CONCURRENT_CHANNEL_HPP
#define ASIO_EXPERIMENTAL_BASIC_CONCURRENT_CHANNEL_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include "asio/detail/config.hpp"
#include "asio/detail/non_const_lvalue.hpp"
#include "asio/detail/mutex.hpp"
#include "asio/execution/executor.hpp"
#include "asio/execution_context.hpp"
#include "asio/experimental/detail/channel_send_functions.hpp"
#include "asio/experimental/detail/channel_service.hpp"
#include "asio/detail/push_options.hpp"
namespace asio {
namespace experimental {
namespace detail {
} // namespace detail
/// A channel for messages.
/**
* The basic_concurrent_channel class template is used for sending messages
* between different parts of the same application. A <em>message</em> is
* defined as a collection of arguments to be passed to a completion handler,
* and the set of messages supported by a channel is specified by its @c Traits
* and <tt>Signatures...</tt> template parameters. Messages may be sent and
* received using asynchronous or non-blocking synchronous operations.
*
* Unless customising the traits, applications will typically use the @c
* experimental::concurrent_channel alias template. For example:
* @code void send_loop(int i, steady_timer& timer,
* concurrent_channel<void(error_code, int)>& ch)
* {
* if (i < 10)
* {
* timer.expires_after(chrono::seconds(1));
* timer.async_wait(
* [i, &timer, &ch](error_code error)
* {
* if (!error)
* {
* ch.async_send(error_code(), i,
* [i, &timer, &ch](error_code error)
* {
* if (!error)
* {
* send_loop(i + 1, timer, ch);
* }
* });
* }
* });
* }
* else
* {
* ch.close();
* }
* }
*
* void receive_loop(concurent_channel<void(error_code, int)>& ch)
* {
* ch.async_receive(
* [&ch](error_code error, int i)
* {
* if (!error)
* {
* std::cout << "Received " << i << "\n";
* receive_loop(ch);
* }
* });
* } @endcode
*
* @par Thread Safety
* @e Distinct @e objects: Safe.@n
* @e Shared @e objects: Safe.
*
* The basic_concurrent_channel class template is thread-safe, and would
* typically be used for passing messages between application code that run on
* different threads. Consider using @ref basic_channel, and its alias template
* @c experimental::channel, to pass messages between code running in a single
* thread or on the same strand.
*/
template <typename Executor, typename Traits, typename... Signatures>
class basic_concurrent_channel
#if !defined(GENERATING_DOCUMENTATION)
: public detail::channel_send_functions<
basic_concurrent_channel<Executor, Traits, Signatures...>,
Executor, Signatures...>
#endif // !defined(GENERATING_DOCUMENTATION)
{
private:
class initiate_async_send;
class initiate_async_receive;
typedef detail::channel_service<asio::detail::mutex> service_type;
typedef typename service_type::template implementation_type<
Traits, Signatures...>::payload_type payload_type;
template <typename... PayloadSignatures,
ASIO_COMPLETION_TOKEN_FOR(PayloadSignatures...) CompletionToken>
auto do_async_receive(
asio::detail::completion_payload<PayloadSignatures...>*,
CompletionToken&& token)
-> decltype(
async_initiate<CompletionToken, PayloadSignatures...>(
declval<initiate_async_receive>(), token))
{
return async_initiate<CompletionToken, PayloadSignatures...>(
initiate_async_receive(this), token);
}
public:
/// The type of the executor associated with the channel.
typedef Executor executor_type;
/// Rebinds the channel type to another executor.
template <typename Executor1>
struct rebind_executor
{
/// The channel type when rebound to the specified executor.
typedef basic_concurrent_channel<Executor1, Traits, Signatures...> other;
};
/// The traits type associated with the channel.
typedef typename Traits::template rebind<Signatures...>::other traits_type;
/// Construct a basic_concurrent_channel.
/**
* This constructor creates and channel.
*
* @param ex The I/O executor that the channel will use, by default, to
* dispatch handlers for any asynchronous operations performed on the channel.
*
* @param max_buffer_size The maximum number of messages that may be buffered
* in the channel.
*/
basic_concurrent_channel(const executor_type& ex,
std::size_t max_buffer_size = 0)
: service_(&asio::use_service<service_type>(
basic_concurrent_channel::get_context(ex))),
impl_(),
executor_(ex)
{
service_->construct(impl_, max_buffer_size);
}
/// Construct and open a basic_concurrent_channel.
/**
* This constructor creates and opens a channel.
*
* @param context An execution context which provides the I/O executor that
* the channel will use, by default, to dispatch handlers for any asynchronous
* operations performed on the channel.
*
* @param max_buffer_size The maximum number of messages that may be buffered
* in the channel.
*/
template <typename ExecutionContext>
basic_concurrent_channel(ExecutionContext& context,
std::size_t max_buffer_size = 0,
constraint_t<
is_convertible<ExecutionContext&, execution_context&>::value,
defaulted_constraint
> = defaulted_constraint())
: service_(&asio::use_service<service_type>(context)),
impl_(),
executor_(context.get_executor())
{
service_->construct(impl_, max_buffer_size);
}
/// Move-construct a basic_concurrent_channel from another.
/**
* This constructor moves a channel from one object to another.
*
* @param other The other basic_concurrent_channel 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_concurrent_channel(const executor_type&)
* constructor.
*/
basic_concurrent_channel(basic_concurrent_channel&& other)
: service_(other.service_),
executor_(other.executor_)
{
service_->move_construct(impl_, other.impl_);
}
/// Move-assign a basic_concurrent_channel from another.
/**
* This assignment operator moves a channel from one object to another.
* Cancels any outstanding asynchronous operations associated with the target
* object.
*
* @param other The other basic_concurrent_channel 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_concurrent_channel(const executor_type&)
* constructor.
*/
basic_concurrent_channel& operator=(basic_concurrent_channel&& other)
{
if (this != &other)
{
service_->move_assign(impl_, *other.service_, other.impl_);
executor_.~executor_type();
new (&executor_) executor_type(other.executor_);
service_ = other.service_;
}
return *this;
}
// All channels have access to each other's implementations.
template <typename, typename, typename...>
friend class basic_concurrent_channel;
/// Move-construct a basic_concurrent_channel from another.
/**
* This constructor moves a channel from one object to another.
*
* @param other The other basic_concurrent_channel 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_concurrent_channel(const executor_type&)
* constructor.
*/
template <typename Executor1>
basic_concurrent_channel(
basic_concurrent_channel<Executor1, Traits, Signatures...>&& other,
constraint_t<
is_convertible<Executor1, Executor>::value
> = 0)
: service_(other.service_),
executor_(other.executor_)
{
service_->move_construct(impl_, other.impl_);
}
/// Move-assign a basic_concurrent_channel from another.
/**
* This assignment operator moves a channel from one object to another.
* Cancels any outstanding asynchronous operations associated with the target
* object.
*
* @param other The other basic_concurrent_channel 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_concurrent_channel(const executor_type&)
* constructor.
*/
template <typename Executor1>
constraint_t<
is_convertible<Executor1, Executor>::value,
basic_concurrent_channel&
> operator=(
basic_concurrent_channel<Executor1, Traits, Signatures...>&& other)
{
if (this != &other)
{
service_->move_assign(impl_, *other.service_, other.impl_);
executor_.~executor_type();
new (&executor_) executor_type(other.executor_);
service_ = other.service_;
}
return *this;
}
/// Destructor.
~basic_concurrent_channel()
{
service_->destroy(impl_);
}
/// Get the executor associated with the object.
const executor_type& get_executor() noexcept
{
return executor_;
}
/// Get the capacity of the channel's buffer.
std::size_t capacity() noexcept
{
return service_->capacity(impl_);
}
/// Determine whether the channel is open.
bool is_open() const noexcept
{
return service_->is_open(impl_);
}
/// Reset the channel to its initial state.
void reset()
{
service_->reset(impl_);
}
/// Close the channel.
void close()
{
service_->close(impl_);
}
/// Cancel all asynchronous operations waiting on the channel.
/**
* All outstanding send operations will complete with the error
* @c asio::experimental::error::channel_cancelled. Outstanding receive
* operations complete with the result as determined by the channel traits.
*/
void cancel()
{
service_->cancel(impl_);
}
/// Determine whether a message can be received without blocking.
bool ready() const noexcept
{
return service_->ready(impl_);
}
#if defined(GENERATING_DOCUMENTATION)
/// Try to send a message without blocking.
/**
* Fails if the buffer is full and there are no waiting receive operations.
*
* @returns @c true on success, @c false on failure.
*/
template <typename... Args>
bool try_send(Args&&... args);
/// Try to send a message without blocking, using dispatch semantics to call
/// the receive operation's completion handler.
/**
* Fails if the buffer is full and there are no waiting receive operations.
*
* The receive operation's completion handler may be called from inside this
* function.
*
* @returns @c true on success, @c false on failure.
*/
template <typename... Args>
bool try_send_via_dispatch(Args&&... args);
/// Try to send a number of messages without blocking.
/**
* @returns The number of messages that were sent.
*/
template <typename... Args>
std::size_t try_send_n(std::size_t count, Args&&... args);
/// Try to send a number of messages without blocking, using dispatch
/// semantics to call the receive operations' completion handlers.
/**
* The receive operations' completion handlers may be called from inside this
* function.
*
* @returns The number of messages that were sent.
*/
template <typename... Args>
std::size_t try_send_n_via_dispatch(std::size_t count, Args&&... args);
/// Asynchronously send a message.
template <typename... Args,
ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code))
CompletionToken ASIO_DEFAULT_COMPLETION_TOKEN_TYPE(executor_type)>
auto async_send(Args&&... args,
CompletionToken&& token);
#endif // defined(GENERATING_DOCUMENTATION)
/// Try to receive a message without blocking.
/**
* Fails if the buffer is full and there are no waiting receive operations.
*
* @returns @c true on success, @c false on failure.
*/
template <typename Handler>
bool try_receive(Handler&& handler)
{
return service_->try_receive(impl_, static_cast<Handler&&>(handler));
}
/// Asynchronously receive a message.
template <typename CompletionToken
ASIO_DEFAULT_COMPLETION_TOKEN_TYPE(executor_type)>
auto async_receive(
CompletionToken&& token
ASIO_DEFAULT_COMPLETION_TOKEN(Executor))
#if !defined(GENERATING_DOCUMENTATION)
-> decltype(
this->do_async_receive(static_cast<payload_type*>(0),
static_cast<CompletionToken&&>(token)))
#endif // !defined(GENERATING_DOCUMENTATION)
{
return this->do_async_receive(static_cast<payload_type*>(0),
static_cast<CompletionToken&&>(token));
}
private:
// Disallow copying and assignment.
basic_concurrent_channel(
const basic_concurrent_channel&) = delete;
basic_concurrent_channel& operator=(
const basic_concurrent_channel&) = delete;
template <typename, typename, typename...>
friend class detail::channel_send_functions;
// Helper function to get an executor's context.
template <typename T>
static execution_context& get_context(const T& t,
enable_if_t<execution::is_executor<T>::value>* = 0)
{
return asio::query(t, execution::context);
}
// Helper function to get an executor's context.
template <typename T>
static execution_context& get_context(const T& t,
enable_if_t<!execution::is_executor<T>::value>* = 0)
{
return t.context();
}
class initiate_async_send
{
public:
typedef Executor executor_type;
explicit initiate_async_send(basic_concurrent_channel* self)
: self_(self)
{
}
const executor_type& get_executor() const noexcept
{
return self_->get_executor();
}
template <typename SendHandler>
void operator()(SendHandler&& handler,
payload_type&& payload) const
{
asio::detail::non_const_lvalue<SendHandler> handler2(handler);
self_->service_->async_send(self_->impl_,
static_cast<payload_type&&>(payload),
handler2.value, self_->get_executor());
}
private:
basic_concurrent_channel* self_;
};
class initiate_async_receive
{
public:
typedef Executor executor_type;
explicit initiate_async_receive(basic_concurrent_channel* self)
: self_(self)
{
}
const executor_type& get_executor() const noexcept
{
return self_->get_executor();
}
template <typename ReceiveHandler>
void operator()(ReceiveHandler&& handler) const
{
asio::detail::non_const_lvalue<ReceiveHandler> handler2(handler);
self_->service_->async_receive(self_->impl_,
handler2.value, self_->get_executor());
}
private:
basic_concurrent_channel* self_;
};
// The service associated with the I/O object.
service_type* service_;
// The underlying implementation of the I/O object.
typename service_type::template implementation_type<
Traits, Signatures...> impl_;
// The associated executor.
Executor executor_;
};
} // namespace experimental
} // namespace asio
#include "asio/detail/pop_options.hpp"
#endif // ASIO_EXPERIMENTAL_BASIC_CONCURRENT_CHANNEL_HPP
|
0 | repos/asio/asio/include/asio | repos/asio/asio/include/asio/experimental/as_tuple.hpp | //
// experimental/as_tuple.hpp
// ~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef ASIO_EXPERIMENTAL_AS_TUPLE_HPP
#define ASIO_EXPERIMENTAL_AS_TUPLE_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include "asio/detail/config.hpp"
#include "asio/as_tuple.hpp"
#include "asio/detail/push_options.hpp"
namespace asio {
namespace experimental {
#if !defined(ASIO_NO_DEPRECATED)
using asio::as_tuple_t;
using asio::as_tuple;
#endif // !defined(ASIO_NO_DEPRECATED)
} // namespace experimental
} // namespace asio
#include "asio/detail/pop_options.hpp"
#endif // ASIO_EXPERIMENTAL_AS_TUPLE_HPP
|
0 | repos/asio/asio/include/asio | repos/asio/asio/include/asio/experimental/channel_error.hpp | //
// experimental/channel_error.hpp
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef ASIO_EXPERIMENTAL_CHANNEL_ERROR_HPP
#define ASIO_EXPERIMENTAL_CHANNEL_ERROR_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include "asio/detail/config.hpp"
#include "asio/error_code.hpp"
#include "asio/detail/push_options.hpp"
namespace asio {
namespace experimental {
namespace error {
enum channel_errors
{
/// The channel was closed.
channel_closed = 1,
/// The channel was cancelled.
channel_cancelled = 2
};
extern ASIO_DECL
const asio::error_category& get_channel_category();
static const asio::error_category&
channel_category ASIO_UNUSED_VARIABLE
= asio::experimental::error::get_channel_category();
} // namespace error
namespace channel_errc {
// Simulates a scoped enum.
using error::channel_closed;
using error::channel_cancelled;
} // namespace channel_errc
} // namespace experimental
} // namespace asio
namespace std {
template<> struct is_error_code_enum<
asio::experimental::error::channel_errors>
{
static const bool value = true;
};
} // namespace std
namespace asio {
namespace experimental {
namespace error {
inline asio::error_code make_error_code(channel_errors e)
{
return asio::error_code(
static_cast<int>(e), get_channel_category());
}
} // namespace error
} // namespace experimental
} // namespace asio
#include "asio/detail/pop_options.hpp"
#if defined(ASIO_HEADER_ONLY)
# include "asio/experimental/impl/channel_error.ipp"
#endif // defined(ASIO_HEADER_ONLY)
#endif // ASIO_EXPERIMENTAL_CHANNEL_ERROR_HPP
|
0 | repos/asio/asio/include/asio | repos/asio/asio/include/asio/experimental/use_coro.hpp | //
// experimental/use_coro.hpp
// ~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2021-2023 Klemens D. Morgenstern
// (klemens dot morgenstern at gmx dot net)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef ASIO_EXPERIMENTAL_USE_CORO_HPP
#define ASIO_EXPERIMENTAL_USE_CORO_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include "asio/detail/config.hpp"
#include <memory>
#include "asio/deferred.hpp"
#include "asio/detail/source_location.hpp"
#include "asio/detail/push_options.hpp"
namespace asio {
class any_io_executor;
namespace experimental {
/// A @ref completion_token that creates another coro for the task completion.
/**
* The @c use_coro_t class, with its value @c use_coro, is used to represent an
* operation that can be awaited by the current resumable coroutine. This
* completion token may be passed as a handler to an asynchronous operation.
* For example:
*
* @code coro<void> my_coroutine(tcp::socket my_socket)
* {
* std::size_t n = co_await my_socket.async_read_some(buffer, use_coro);
* ...
* } @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.
*
* Note that this token is not the most efficient (use the default completion
* token @c asio::deferred for that) but does provide type erasure, as it
* will always return a @c coro.
*/
template <typename Allocator = std::allocator<void>>
struct use_coro_t
{
/// The allocator type. The allocator is used when constructing the
/// @c std::promise object for a given asynchronous operation.
typedef Allocator allocator_type;
/// Default constructor.
constexpr use_coro_t(
allocator_type allocator = allocator_type{}
#if defined(ASIO_ENABLE_HANDLER_TRACKING)
# if defined(ASIO_HAS_SOURCE_LOCATION)
, asio::detail::source_location location =
asio::detail::source_location::current()
# endif // defined(ASIO_HAS_SOURCE_LOCATION)
#endif // defined(ASIO_ENABLE_HANDLER_TRACKING)
)
: allocator_(allocator)
#if defined(ASIO_ENABLE_HANDLER_TRACKING)
# if defined(ASIO_HAS_SOURCE_LOCATION)
, file_name_(location.file_name()),
line_(location.line()),
function_name_(location.function_name())
# else // defined(ASIO_HAS_SOURCE_LOCATION)
, file_name_(0),
line_(0),
function_name_(0)
# endif // defined(ASIO_HAS_SOURCE_LOCATION)
#endif // defined(ASIO_ENABLE_HANDLER_TRACKING)
{
}
/// Specify an alternate allocator.
template <typename OtherAllocator>
use_coro_t<OtherAllocator> rebind(const OtherAllocator& allocator) const
{
return use_future_t<OtherAllocator>(allocator);
}
/// Obtain allocator.
allocator_type get_allocator() const
{
return allocator_;
}
/// Constructor used to specify file name, line, and function name.
constexpr use_coro_t(const char* file_name,
int line, const char* function_name,
allocator_type allocator = allocator_type{}) :
#if defined(ASIO_ENABLE_HANDLER_TRACKING)
file_name_(file_name),
line_(line),
function_name_(function_name),
#endif // defined(ASIO_ENABLE_HANDLER_TRACKING)
allocator_(allocator)
{
#if !defined(ASIO_ENABLE_HANDLER_TRACKING)
(void)file_name;
(void)line;
(void)function_name;
#endif // !defined(ASIO_ENABLE_HANDLER_TRACKING)
}
/// Adapts an executor to add the @c use_coro_t completion token as the
/// default.
template <typename InnerExecutor>
struct executor_with_default : InnerExecutor
{
/// Specify @c use_coro_t as the default completion token type.
typedef use_coro_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_coro_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_coro_t as its
/// default completion token type.
template <typename T>
static typename decay_t<T>::template rebind_executor<
executor_with_default<typename decay_t<T>::executor_type>
>::other
as_default_on(T&& object)
{
return typename decay_t<T>::template rebind_executor<
executor_with_default<typename decay_t<T>::executor_type>
>::other(static_cast<T&&>(object));
}
#if defined(ASIO_ENABLE_HANDLER_TRACKING)
const char* file_name_;
int line_;
const char* function_name_;
#endif // defined(ASIO_ENABLE_HANDLER_TRACKING)
private:
Allocator allocator_;
};
/// A @ref completion_token object that represents the currently executing
/// resumable coroutine.
/**
* See the documentation for asio::use_coro_t for a usage example.
*/
#if defined(GENERATING_DOCUMENTATION)
ASIO_INLINE_VARIABLE constexpr use_coro_t<> use_coro;
#else
ASIO_INLINE_VARIABLE constexpr use_coro_t<> use_coro(0, 0, 0);
#endif
} // namespace experimental
} // namespace asio
#include "asio/detail/pop_options.hpp"
#include "asio/experimental/impl/use_coro.hpp"
#include "asio/experimental/coro.hpp"
#endif // ASIO_EXPERIMENTAL_USE_CORO_HPP
|
0 | repos/asio/asio/include/asio | repos/asio/asio/include/asio/experimental/parallel_group.hpp | //
// experimental/parallel_group.hpp
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef ASIO_EXPERIMENTAL_PARALLEL_GROUP_HPP
#define ASIO_EXPERIMENTAL_PARALLEL_GROUP_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include "asio/detail/config.hpp"
#include <vector>
#include "asio/async_result.hpp"
#include "asio/detail/array.hpp"
#include "asio/detail/memory.hpp"
#include "asio/detail/type_traits.hpp"
#include "asio/detail/utility.hpp"
#include "asio/experimental/cancellation_condition.hpp"
#include "asio/detail/push_options.hpp"
namespace asio {
namespace experimental {
namespace detail {
// Helper trait for getting a tuple from a completion signature.
template <typename Signature>
struct parallel_op_signature_as_tuple;
template <typename R, typename... Args>
struct parallel_op_signature_as_tuple<R(Args...)>
{
typedef std::tuple<decay_t<Args>...> type;
};
// Helper trait for concatenating completion signatures.
template <std::size_t N, typename Offsets, typename... Signatures>
struct parallel_group_signature;
template <std::size_t N, typename R0, typename... Args0>
struct parallel_group_signature<N, R0(Args0...)>
{
typedef asio::detail::array<std::size_t, N> order_type;
typedef R0 raw_type(Args0...);
typedef R0 type(order_type, Args0...);
};
template <std::size_t N,
typename R0, typename... Args0,
typename R1, typename... Args1>
struct parallel_group_signature<N, R0(Args0...), R1(Args1...)>
{
typedef asio::detail::array<std::size_t, N> order_type;
typedef R0 raw_type(Args0..., Args1...);
typedef R0 type(order_type, Args0..., Args1...);
};
template <std::size_t N, typename Sig0,
typename Sig1, typename... SigN>
struct parallel_group_signature<N, Sig0, Sig1, SigN...>
{
typedef asio::detail::array<std::size_t, N> order_type;
typedef typename parallel_group_signature<N,
typename parallel_group_signature<N, Sig0, Sig1>::raw_type,
SigN...>::raw_type raw_type;
typedef typename parallel_group_signature<N,
typename parallel_group_signature<N, Sig0, Sig1>::raw_type,
SigN...>::type type;
};
template <typename Condition, typename Handler,
typename... Ops, std::size_t... I>
void parallel_group_launch(Condition cancellation_condition, Handler handler,
std::tuple<Ops...>& ops, asio::detail::index_sequence<I...>);
// Helper trait for determining ranged parallel group completion signatures.
template <typename Signature, typename Allocator>
struct ranged_parallel_group_signature;
template <typename R, typename... Args, typename Allocator>
struct ranged_parallel_group_signature<R(Args...), Allocator>
{
typedef std::vector<std::size_t,
ASIO_REBIND_ALLOC(Allocator, std::size_t)> order_type;
typedef R raw_type(
std::vector<Args, ASIO_REBIND_ALLOC(Allocator, Args)>...);
typedef R type(order_type,
std::vector<Args, ASIO_REBIND_ALLOC(Allocator, Args)>...);
};
template <typename Condition, typename Handler,
typename Range, typename Allocator>
void ranged_parallel_group_launch(Condition cancellation_condition,
Handler handler, Range&& range, const Allocator& allocator);
char (¶llel_group_has_iterator_helper(...))[2];
template <typename T>
char parallel_group_has_iterator_helper(T*, typename T::iterator* = 0);
template <typename T>
struct parallel_group_has_iterator_typedef
{
enum { value = (sizeof((parallel_group_has_iterator_helper)((T*)(0))) == 1) };
};
} // namespace detail
/// Type trait used to determine whether a type is a range of asynchronous
/// operations that can be used with with @c make_parallel_group.
template <typename T>
struct is_async_operation_range
{
#if defined(GENERATING_DOCUMENTATION)
/// The value member is true if the type may be used as a range of
/// asynchronous operations.
static const bool value;
#else
enum
{
value = detail::parallel_group_has_iterator_typedef<T>::value
};
#endif
};
/// A group of asynchronous operations that may be launched in parallel.
/**
* See the documentation for asio::experimental::make_parallel_group for
* a usage example.
*/
template <typename... Ops>
class parallel_group
{
private:
struct initiate_async_wait
{
template <typename Handler, typename Condition>
void operator()(Handler&& h, Condition&& c, std::tuple<Ops...>&& ops) const
{
detail::parallel_group_launch(
std::forward<Condition>(c), std::forward<Handler>(h),
ops, asio::detail::index_sequence_for<Ops...>());
}
};
std::tuple<Ops...> ops_;
public:
/// Constructor.
explicit parallel_group(Ops... ops)
: ops_(std::move(ops)...)
{
}
/// The completion signature for the group of operations.
typedef typename detail::parallel_group_signature<sizeof...(Ops),
completion_signature_of_t<Ops>...>::type signature;
/// Initiate an asynchronous wait for the group of operations.
/**
* Launches the group and asynchronously waits for completion.
*
* @param cancellation_condition A function object, called on completion of
* an operation within the group, that is used to determine whether to cancel
* the remaining operations. The function object is passed the arguments of
* the completed operation's handler. To trigger cancellation of the remaining
* operations, it must return a asio::cancellation_type value other
* than <tt>asio::cancellation_type::none</tt>.
*
* @param token A @ref completion_token whose signature is comprised of
* a @c std::array<std::size_t, N> indicating the completion order of the
* operations, followed by all operations' completion handler arguments.
*
* The library provides the following @c cancellation_condition types:
*
* @li asio::experimental::wait_for_all
* @li asio::experimental::wait_for_one
* @li asio::experimental::wait_for_one_error
* @li asio::experimental::wait_for_one_success
*/
template <typename CancellationCondition,
ASIO_COMPLETION_TOKEN_FOR(signature) CompletionToken>
auto async_wait(CancellationCondition cancellation_condition,
CompletionToken&& token)
-> decltype(
asio::async_initiate<CompletionToken, signature>(
declval<initiate_async_wait>(), token,
std::move(cancellation_condition), std::move(ops_)))
{
return asio::async_initiate<CompletionToken, signature>(
initiate_async_wait(), token,
std::move(cancellation_condition), std::move(ops_));
}
};
/// Create a group of operations that may be launched in parallel.
/**
* For example:
* @code asio::experimental::make_parallel_group(
* in.async_read_some(asio::buffer(data)),
* timer.async_wait()
* ).async_wait(
* asio::experimental::wait_for_all(),
* [](
* std::array<std::size_t, 2> completion_order,
* std::error_code ec1, std::size_t n1,
* std::error_code ec2
* )
* {
* switch (completion_order[0])
* {
* case 0:
* {
* std::cout << "descriptor finished: " << ec1 << ", " << n1 << "\n";
* }
* break;
* case 1:
* {
* std::cout << "timer finished: " << ec2 << "\n";
* }
* break;
* }
* }
* );
* @endcode
*
* If preferred, the asynchronous operations may be explicitly packaged as
* function objects:
* @code asio::experimental::make_parallel_group(
* [&](auto token)
* {
* return in.async_read_some(asio::buffer(data), token);
* },
* [&](auto token)
* {
* return timer.async_wait(token);
* }
* ).async_wait(
* asio::experimental::wait_for_all(),
* [](
* std::array<std::size_t, 2> completion_order,
* std::error_code ec1, std::size_t n1,
* std::error_code ec2
* )
* {
* switch (completion_order[0])
* {
* case 0:
* {
* std::cout << "descriptor finished: " << ec1 << ", " << n1 << "\n";
* }
* break;
* case 1:
* {
* std::cout << "timer finished: " << ec2 << "\n";
* }
* break;
* }
* }
* );
* @endcode
*/
template <typename... Ops>
ASIO_NODISCARD inline parallel_group<Ops...>
make_parallel_group(Ops... ops)
{
return parallel_group<Ops...>(std::move(ops)...);
}
/// A range-based group of asynchronous operations that may be launched in
/// parallel.
/**
* See the documentation for asio::experimental::make_parallel_group for
* a usage example.
*/
template <typename Range, typename Allocator = std::allocator<void>>
class ranged_parallel_group
{
private:
struct initiate_async_wait
{
template <typename Handler, typename Condition>
void operator()(Handler&& h, Condition&& c,
Range&& range, const Allocator& allocator) const
{
detail::ranged_parallel_group_launch(std::move(c),
std::move(h), std::forward<Range>(range), allocator);
}
};
Range range_;
Allocator allocator_;
public:
/// Constructor.
explicit ranged_parallel_group(Range range,
const Allocator& allocator = Allocator())
: range_(std::move(range)),
allocator_(allocator)
{
}
/// The completion signature for the group of operations.
typedef typename detail::ranged_parallel_group_signature<
completion_signature_of_t<
decay_t<decltype(*std::declval<typename Range::iterator>())>>,
Allocator>::type signature;
/// Initiate an asynchronous wait for the group of operations.
/**
* Launches the group and asynchronously waits for completion.
*
* @param cancellation_condition A function object, called on completion of
* an operation within the group, that is used to determine whether to cancel
* the remaining operations. The function object is passed the arguments of
* the completed operation's handler. To trigger cancellation of the remaining
* operations, it must return a asio::cancellation_type value other
* than <tt>asio::cancellation_type::none</tt>.
*
* @param token A @ref completion_token whose signature is comprised of
* a @c std::vector<std::size_t, Allocator> indicating the completion order of
* the operations, followed by a vector for each of the completion signature's
* arguments.
*
* The library provides the following @c cancellation_condition types:
*
* @li asio::experimental::wait_for_all
* @li asio::experimental::wait_for_one
* @li asio::experimental::wait_for_one_error
* @li asio::experimental::wait_for_one_success
*/
template <typename CancellationCondition,
ASIO_COMPLETION_TOKEN_FOR(signature) CompletionToken>
auto async_wait(CancellationCondition cancellation_condition,
CompletionToken&& token)
-> decltype(
asio::async_initiate<CompletionToken, signature>(
declval<initiate_async_wait>(), token,
std::move(cancellation_condition),
std::move(range_), allocator_))
{
return asio::async_initiate<CompletionToken, signature>(
initiate_async_wait(), token,
std::move(cancellation_condition),
std::move(range_), allocator_);
}
};
/// Create a group of operations that may be launched in parallel.
/**
* @param range A range containing the operations to be launched.
*
* For example:
* @code
* using op_type =
* decltype(socket1.async_read_some(asio::buffer(data1)));
*
* std::vector<op_type> ops;
* ops.push_back(socket1.async_read_some(asio::buffer(data1)));
* ops.push_back(socket2.async_read_some(asio::buffer(data2)));
*
* asio::experimental::make_parallel_group(ops).async_wait(
* asio::experimental::wait_for_all(),
* [](
* std::vector<std::size_t> completion_order,
* std::vector<std::error_code> e,
* std::vector<std::size_t> n
* )
* {
* for (std::size_t i = 0; i < completion_order.size(); ++i)
* {
* std::size_t idx = completion_order[i];
* std::cout << "socket " << idx << " finished: ";
* std::cout << e[idx] << ", " << n[idx] << "\n";
* }
* }
* );
* @endcode
*/
template <typename Range>
ASIO_NODISCARD inline ranged_parallel_group<decay_t<Range>>
make_parallel_group(Range&& range,
constraint_t<
is_async_operation_range<decay_t<Range>>::value
> = 0)
{
return ranged_parallel_group<decay_t<Range>>(std::forward<Range>(range));
}
/// Create a group of operations that may be launched in parallel.
/**
* @param allocator Specifies the allocator to be used with the result vectors.
*
* @param range A range containing the operations to be launched.
*
* For example:
* @code
* using op_type =
* decltype(socket1.async_read_some(asio::buffer(data1)));
*
* std::vector<op_type> ops;
* ops.push_back(socket1.async_read_some(asio::buffer(data1)));
* ops.push_back(socket2.async_read_some(asio::buffer(data2)));
*
* asio::experimental::make_parallel_group(
* std::allocator_arg_t,
* my_allocator,
* ops
* ).async_wait(
* asio::experimental::wait_for_all(),
* [](
* std::vector<std::size_t> completion_order,
* std::vector<std::error_code> e,
* std::vector<std::size_t> n
* )
* {
* for (std::size_t i = 0; i < completion_order.size(); ++i)
* {
* std::size_t idx = completion_order[i];
* std::cout << "socket " << idx << " finished: ";
* std::cout << e[idx] << ", " << n[idx] << "\n";
* }
* }
* );
* @endcode
*/
template <typename Allocator, typename Range>
ASIO_NODISCARD inline ranged_parallel_group<decay_t<Range>, Allocator>
make_parallel_group(allocator_arg_t, const Allocator& allocator, Range&& range,
constraint_t<
is_async_operation_range<decay_t<Range>>::value
> = 0)
{
return ranged_parallel_group<decay_t<Range>, Allocator>(
std::forward<Range>(range), allocator);
}
} // namespace experimental
} // namespace asio
#include "asio/detail/pop_options.hpp"
#include "asio/experimental/impl/parallel_group.hpp"
#endif // ASIO_EXPERIMENTAL_PARALLEL_GROUP_HPP
|
0 | repos/asio/asio/include/asio | repos/asio/asio/include/asio/experimental/deferred.hpp | //
// experimental/deferred.hpp
// ~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef ASIO_EXPERIMENTAL_DEFERRED_HPP
#define ASIO_EXPERIMENTAL_DEFERRED_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include "asio/detail/config.hpp"
#include "asio/deferred.hpp"
#include "asio/detail/push_options.hpp"
namespace asio {
namespace experimental {
#if !defined(ASIO_NO_DEPRECATED)
using asio::deferred_t;
using asio::deferred;
#endif // !defined(ASIO_NO_DEPRECATED)
} // namespace experimental
} // namespace asio
#include "asio/detail/pop_options.hpp"
#endif // ASIO_EXPERIMENTAL_DEFERRED_HPP
|
0 | repos/asio/asio/include/asio | repos/asio/asio/include/asio/experimental/co_composed.hpp | //
// experimental/co_composed.hpp
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef ASIO_EXPERIMENTAL_CO_COMPOSED_HPP
#define ASIO_EXPERIMENTAL_CO_COMPOSED_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include "asio/detail/config.hpp"
#include "asio/co_composed.hpp"
#include "asio/detail/push_options.hpp"
namespace asio {
namespace experimental {
using asio::co_composed;
} // namespace experimental
} // namespace asio
#include "asio/detail/pop_options.hpp"
#endif // ASIO_EXPERIMENTAL_CO_COMPOSED_HPP
|
0 | repos/asio/asio/include/asio | repos/asio/asio/include/asio/experimental/co_spawn.hpp | //
// experimental/co_spawn.hpp
// ~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2021-2023 Klemens D. Morgenstern
// (klemens dot morgenstern at gmx dot net)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef ASIO_EXPERIMENTAL_CO_SPAWN_HPP
#define ASIO_EXPERIMENTAL_CO_SPAWN_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include "asio/detail/config.hpp"
#include <utility>
#include "asio/compose.hpp"
#include "asio/detail/type_traits.hpp"
#include "asio/experimental/coro.hpp"
#include "asio/experimental/deferred.hpp"
#include "asio/experimental/prepend.hpp"
#include "asio/redirect_error.hpp"
#include "asio/detail/push_options.hpp"
namespace asio {
namespace experimental {
namespace detail {
template <typename T, typename U, typename Executor>
struct coro_spawn_op
{
coro<T, U, Executor> c;
void operator()(auto& self)
{
auto op = c.async_resume(deferred);
std::move(op)((prepend)(std::move(self), 0));
}
void operator()(auto& self, int, auto... res)
{
self.complete(std::move(res)...);
}
};
} // namespace detail
/// Spawn a resumable coroutine.
/**
* This function spawns the coroutine for execution on its executor. It binds
* the lifetime of the coroutine to the executor.
*
* @param c The coroutine
*
* @param token The completion token
*
* @returns Implementation defined
*/
template <typename T, typename Executor, typename CompletionToken>
ASIO_INITFN_AUTO_RESULT_TYPE(
CompletionToken, void(std::exception_ptr, T))
co_spawn(coro<void, T, Executor> c, CompletionToken&& token)
{
auto exec = c.get_executor();
return async_compose<CompletionToken, void(std::exception_ptr, T)>(
detail::coro_spawn_op<void, T, Executor>{std::move(c)},
token, exec);
}
/// Spawn a resumable coroutine.
/**
* This function spawns the coroutine for execution on its executor. It binds
* the lifetime of the coroutine to the executor.
*
* @param c The coroutine
*
* @param token The completion token
*
* @returns Implementation defined
*/
template <typename T, typename Executor, typename CompletionToken>
ASIO_INITFN_AUTO_RESULT_TYPE(
CompletionToken, void(std::exception_ptr, T))
co_spawn(coro<void(), T, Executor> c, CompletionToken&& token)
{
auto exec = c.get_executor();
return async_compose<CompletionToken, void(std::exception_ptr, T)>(
detail::coro_spawn_op<void(), T, Executor>{std::move(c)},
token, exec);
}
/// Spawn a resumable coroutine.
/**
* This function spawns the coroutine for execution on its executor. It binds
* the lifetime of the coroutine to the executor.
*
* @param c The coroutine
*
* @param token The completion token
*
* @returns Implementation defined
*/
template <typename T, typename Executor, typename CompletionToken>
ASIO_INITFN_AUTO_RESULT_TYPE(CompletionToken, void(T))
co_spawn(coro<void() noexcept, T, Executor> c, CompletionToken&& token)
{
auto exec = c.get_executor();
return async_compose<CompletionToken, void(T)>(
detail::coro_spawn_op<void() noexcept, T, Executor>{std::move(c)},
token, exec);
}
/// Spawn a resumable coroutine.
/**
* This function spawns the coroutine for execution on its executor. It binds
* the lifetime of the coroutine to the executor.
*
* @param c The coroutine
*
* @param token The completion token
*
* @returns Implementation defined
*/
template <typename Executor, typename CompletionToken>
ASIO_INITFN_AUTO_RESULT_TYPE(
CompletionToken, void(std::exception_ptr))
co_spawn(coro<void, void, Executor> c, CompletionToken&& token)
{
auto exec = c.get_executor();
return async_compose<CompletionToken, void(std::exception_ptr)>(
detail::coro_spawn_op<void, void, Executor>{std::move(c)},
token, exec);
}
/// Spawn a resumable coroutine.
/**
* This function spawns the coroutine for execution on its executor. It binds
* the lifetime of the coroutine to the executor.
*
* @param c The coroutine
*
* @param token The completion token
*
* @returns Implementation defined
*/
template <typename Executor, typename CompletionToken>
ASIO_INITFN_AUTO_RESULT_TYPE(
CompletionToken, void(std::exception_ptr))
co_spawn(coro<void(), void, Executor> c, CompletionToken&& token)
{
auto exec = c.get_executor();
return async_compose<CompletionToken, void(std::exception_ptr)>(
detail::coro_spawn_op<void(), void, Executor>{std::move(c)},
token, exec);
}
/// Spawn a resumable coroutine.
/**
* This function spawns the coroutine for execution on its executor. It binds
* the lifetime of the coroutine to the executor.
*
* @param c The coroutine
*
* @param token The completion token
*
* @returns Implementation defined
*/
template <typename Executor, typename CompletionToken>
ASIO_INITFN_AUTO_RESULT_TYPE(CompletionToken, void())
co_spawn(coro<void() noexcept, void, Executor> c, CompletionToken&& token)
{
auto exec = c.get_executor();
return async_compose<CompletionToken, void()>(
detail::coro_spawn_op<void() noexcept, void, Executor>{std::move(c)},
token, exec);
}
} // namespace detail
} // namespace asio
#include "asio/detail/pop_options.hpp"
#endif //ASIO_EXPERIMENTAL_CO_SPAWN_HPP
|
0 | repos/asio/asio/include/asio | repos/asio/asio/include/asio/experimental/coro.hpp | //
// experimental/coro.hpp
// ~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2021-2023 Klemens D. Morgenstern
// (klemens dot morgenstern at gmx dot net)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef ASIO_EXPERIMENTAL_CORO_HPP
#define ASIO_EXPERIMENTAL_CORO_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include "asio/detail/config.hpp"
#include "asio/dispatch.hpp"
#include "asio/error.hpp"
#include "asio/error_code.hpp"
#include "asio/experimental/coro_traits.hpp"
#include "asio/experimental/detail/coro_promise_allocator.hpp"
#include "asio/experimental/detail/partial_promise.hpp"
#include "asio/post.hpp"
#include "asio/detail/push_options.hpp"
namespace asio {
namespace experimental {
namespace detail {
template <typename Signature, typename Return,
typename Executor, typename Allocator>
struct coro_promise;
template <typename T, typename Coroutine>
struct coro_with_arg;
} // namespace detail
/// The main type of a resumable coroutine.
/**
* Template parameter @c Yield specifies type or signature used by co_yield,
* @c Return specifies the type used for co_return, and @c Executor specifies
* the underlying executor type.
*/
template <typename Yield = void, typename Return = void,
typename Executor = any_io_executor,
typename Allocator = std::allocator<void>>
struct coro
{
/// The traits of the coroutine. See asio::experimental::coro_traits
/// for details.
using traits = coro_traits<Yield, Return, Executor>;
/// The value that can be passed into a symmetrical cororoutine. @c void if
/// asymmetrical.
using input_type = typename traits::input_type;
/// The type that can be passed out through a co_yield.
using yield_type = typename traits::yield_type;
/// The type that can be passed out through a co_return.
using return_type = typename traits::return_type;
/// The type received by a co_await or async_resume. Its a combination of
/// yield and return.
using result_type = typename traits::result_type;
/// The signature used by the async_resume.
using signature_type = typename traits::signature_type;
/// Whether or not the coroutine is noexcept.
constexpr static bool is_noexcept = traits::is_noexcept;
/// The error type of the coroutine. Void for noexcept
using error_type = typename traits::error_type;
/// Completion handler type used by async_resume.
using completion_handler = typename traits::completion_handler;
/// The internal promise-type of the coroutine.
using promise_type = detail::coro_promise<Yield, Return, Executor, Allocator>;
#if !defined(GENERATING_DOCUMENTATION)
template <typename T, typename Coroutine>
friend struct detail::coro_with_arg;
#endif // !defined(GENERATING_DOCUMENTATION)
/// The executor type.
using executor_type = Executor;
/// The allocator type.
using allocator_type = Allocator;
#if !defined(GENERATING_DOCUMENTATION)
friend struct detail::coro_promise<Yield, Return, Executor, Allocator>;
#endif // !defined(GENERATING_DOCUMENTATION)
/// The default constructor, gives an invalid coroutine.
coro() = default;
/// Move constructor.
coro(coro&& lhs) noexcept
: coro_(std::exchange(lhs.coro_, nullptr))
{
}
coro(const coro&) = delete;
/// Move assignment.
coro& operator=(coro&& lhs) noexcept
{
std::swap(coro_, lhs.coro_);
return *this;
}
coro& operator=(const coro&) = delete;
/// Destructor. Destroys the coroutine, if it holds a valid one.
/**
* @note This does not cancel an active coroutine. Destructing a resumable
* coroutine, i.e. one with a call to async_resume that has not completed, is
* undefined behaviour.
*/
~coro()
{
if (coro_ != nullptr)
{
struct destroyer
{
detail::coroutine_handle<promise_type> handle;
destroyer(const detail::coroutine_handle<promise_type>& handle)
: handle(handle)
{ }
destroyer(destroyer&& lhs)
: handle(std::exchange(lhs.handle, nullptr))
{
}
destroyer(const destroyer&) = delete;
void operator()() {}
~destroyer()
{
if (handle)
handle.destroy();
}
};
auto handle =
detail::coroutine_handle<promise_type>::from_promise(*coro_);
if (handle)
asio::dispatch(coro_->get_executor(), destroyer{handle});
}
}
/// Get the used executor.
executor_type get_executor() const
{
if (coro_)
return coro_->get_executor();
if constexpr (std::is_default_constructible_v<Executor>)
return Executor{};
else
throw std::logic_error("Coroutine has no executor");
}
/// Get the used allocator.
allocator_type get_allocator() const
{
if (coro_)
return coro_->get_allocator();
if constexpr (std::is_default_constructible_v<Allocator>)
return Allocator{};
else
throw std::logic_error(
"Coroutine has no available allocator without a constructed promise");
}
/// Resume the coroutine.
/**
* @param token The completion token of the async resume.
*
* @attention Calling an invalid coroutine with a noexcept signature is
* undefined behaviour.
*
* @note This overload is only available for coroutines without an input
* value.
*/
template <typename CompletionToken>
requires std::is_void_v<input_type>
auto async_resume(CompletionToken&& token) &
{
return async_initiate<CompletionToken,
typename traits::completion_handler>(
initiate_async_resume(this), token);
}
/// Resume the coroutine.
/**
* @param token The completion token of the async resume.
*
* @attention Calling an invalid coroutine with a noexcept signature is
* undefined behaviour.
*
* @note This overload is only available for coroutines with an input value.
*/
template <typename CompletionToken, detail::convertible_to<input_type> T>
auto async_resume(T&& ip, CompletionToken&& token) &
{
return async_initiate<CompletionToken,
typename traits::completion_handler>(
initiate_async_resume(this), token, std::forward<T>(ip));
}
/// Operator used for coroutines without input value.
auto operator co_await() requires (std::is_void_v<input_type>)
{
return awaitable_t{*this};
}
/// Operator used for coroutines with input value.
/**
* @param ip The input value
*
* @returns An awaitable handle.
*
* @code
* coro<void> push_values(coro<double(int)> c)
* {
* std::optional<double> res = co_await c(42);
* }
* @endcode
*/
template <detail::convertible_to<input_type> T>
auto operator()(T&& ip)
{
return detail::coro_with_arg<std::decay_t<T>, coro>{
std::forward<T>(ip), *this};
}
/// Check whether the coroutine is open, i.e. can be resumed.
bool is_open() const
{
if (coro_)
{
auto handle =
detail::coroutine_handle<promise_type>::from_promise(*coro_);
return handle && !handle.done();
}
else
return false;
}
/// Check whether the coroutine is open, i.e. can be resumed.
explicit operator bool() const { return is_open(); }
private:
struct awaitable_t;
struct initiate_async_resume;
explicit coro(promise_type* const cr) : coro_(cr) {}
promise_type* coro_{nullptr};
};
/// A generator is a coro that returns void and yields value.
template<typename T, typename Executor = asio::any_io_executor,
typename Allocator = std::allocator<void>>
using generator = coro<T, void, Executor, Allocator>;
/// A task is a coro that does not yield values
template<typename T, typename Executor = asio::any_io_executor,
typename Allocator = std::allocator<void>>
using task = coro<void(), T, Executor, Allocator>;
} // namespace experimental
} // namespace asio
#include "asio/detail/pop_options.hpp"
#include "asio/experimental/impl/coro.hpp"
#endif // ASIO_EXPERIMENTAL_CORO_HPP
|
0 | repos/asio/asio/include/asio | repos/asio/asio/include/asio/experimental/prepend.hpp | //
// experimental/prepend.hpp
// ~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef ASIO_EXPERIMENTAL_PREPEND_HPP
#define ASIO_EXPERIMENTAL_PREPEND_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include "asio/detail/config.hpp"
#include "asio/prepend.hpp"
#include "asio/detail/push_options.hpp"
namespace asio {
namespace experimental {
#if !defined(ASIO_NO_DEPRECATED)
using asio::prepend_t;
using asio::prepend;
#endif // !defined(ASIO_NO_DEPRECATED)
} // namespace experimental
} // namespace asio
#include "asio/detail/pop_options.hpp"
#endif // ASIO_EXPERIMENTAL_PREPEND_HPP
|
0 | repos/asio/asio/include/asio | repos/asio/asio/include/asio/experimental/channel_traits.hpp | //
// experimental/channel_traits.hpp
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef ASIO_EXPERIMENTAL_CHANNEL_TRAITS_HPP
#define ASIO_EXPERIMENTAL_CHANNEL_TRAITS_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include "asio/detail/config.hpp"
#include <deque>
#include "asio/detail/type_traits.hpp"
#include "asio/error.hpp"
#include "asio/experimental/channel_error.hpp"
#include "asio/detail/push_options.hpp"
namespace asio {
namespace experimental {
#if defined(GENERATING_DOCUMENTATION)
template <typename... Signatures>
struct channel_traits
{
/// Rebind the traits to a new set of signatures.
/**
* This nested structure must have a single nested type @c other that
* aliases a traits type with the specified set of signatures.
*/
template <typename... NewSignatures>
struct rebind
{
typedef user_defined other;
};
/// Determine the container for the specified elements.
/**
* This nested structure must have a single nested type @c other that
* aliases a container type for the specified element type.
*/
template <typename Element>
struct container
{
typedef user_defined type;
};
/// The signature of a channel cancellation notification.
typedef void receive_cancelled_signature(...);
/// Invoke the specified handler with a cancellation notification.
template <typename F>
static void invoke_receive_cancelled(F f);
/// The signature of a channel closed notification.
typedef void receive_closed_signature(...);
/// Invoke the specified handler with a closed notification.
template <typename F>
static void invoke_receive_closed(F f);
};
#else // defined(GENERATING_DOCUMENTATION)
/// Traits used for customising channel behaviour.
template <typename... Signatures>
struct channel_traits
{
template <typename... NewSignatures>
struct rebind
{
typedef channel_traits<NewSignatures...> other;
};
};
template <typename R>
struct channel_traits<R(asio::error_code)>
{
template <typename... NewSignatures>
struct rebind
{
typedef channel_traits<NewSignatures...> other;
};
template <typename Element>
struct container
{
typedef std::deque<Element> type;
};
typedef R receive_cancelled_signature(asio::error_code);
template <typename F>
static void invoke_receive_cancelled(F f)
{
const asio::error_code e = error::channel_cancelled;
static_cast<F&&>(f)(e);
}
typedef R receive_closed_signature(asio::error_code);
template <typename F>
static void invoke_receive_closed(F f)
{
const asio::error_code e = error::channel_closed;
static_cast<F&&>(f)(e);
}
};
template <typename R, typename... Args, typename... Signatures>
struct channel_traits<R(asio::error_code, Args...), Signatures...>
{
template <typename... NewSignatures>
struct rebind
{
typedef channel_traits<NewSignatures...> other;
};
template <typename Element>
struct container
{
typedef std::deque<Element> type;
};
typedef R receive_cancelled_signature(asio::error_code, Args...);
template <typename F>
static void invoke_receive_cancelled(F f)
{
const asio::error_code e = error::channel_cancelled;
static_cast<F&&>(f)(e, decay_t<Args>()...);
}
typedef R receive_closed_signature(asio::error_code, Args...);
template <typename F>
static void invoke_receive_closed(F f)
{
const asio::error_code e = error::channel_closed;
static_cast<F&&>(f)(e, decay_t<Args>()...);
}
};
template <typename R>
struct channel_traits<R(std::exception_ptr)>
{
template <typename... NewSignatures>
struct rebind
{
typedef channel_traits<NewSignatures...> other;
};
template <typename Element>
struct container
{
typedef std::deque<Element> type;
};
typedef R receive_cancelled_signature(std::exception_ptr);
template <typename F>
static void invoke_receive_cancelled(F f)
{
const asio::error_code e = error::channel_cancelled;
static_cast<F&&>(f)(
std::make_exception_ptr(asio::system_error(e)));
}
typedef R receive_closed_signature(std::exception_ptr);
template <typename F>
static void invoke_receive_closed(F f)
{
const asio::error_code e = error::channel_closed;
static_cast<F&&>(f)(
std::make_exception_ptr(asio::system_error(e)));
}
};
template <typename R, typename... Args, typename... Signatures>
struct channel_traits<R(std::exception_ptr, Args...), Signatures...>
{
template <typename... NewSignatures>
struct rebind
{
typedef channel_traits<NewSignatures...> other;
};
template <typename Element>
struct container
{
typedef std::deque<Element> type;
};
typedef R receive_cancelled_signature(std::exception_ptr, Args...);
template <typename F>
static void invoke_receive_cancelled(F f)
{
const asio::error_code e = error::channel_cancelled;
static_cast<F&&>(f)(
std::make_exception_ptr(asio::system_error(e)),
decay_t<Args>()...);
}
typedef R receive_closed_signature(std::exception_ptr, Args...);
template <typename F>
static void invoke_receive_closed(F f)
{
const asio::error_code e = error::channel_closed;
static_cast<F&&>(f)(
std::make_exception_ptr(asio::system_error(e)),
decay_t<Args>()...);
}
};
template <typename R>
struct channel_traits<R()>
{
template <typename... NewSignatures>
struct rebind
{
typedef channel_traits<NewSignatures...> other;
};
template <typename Element>
struct container
{
typedef std::deque<Element> type;
};
typedef R receive_cancelled_signature(asio::error_code);
template <typename F>
static void invoke_receive_cancelled(F f)
{
const asio::error_code e = error::channel_cancelled;
static_cast<F&&>(f)(e);
}
typedef R receive_closed_signature(asio::error_code);
template <typename F>
static void invoke_receive_closed(F f)
{
const asio::error_code e = error::channel_closed;
static_cast<F&&>(f)(e);
}
};
template <typename R, typename T>
struct channel_traits<R(T)>
{
template <typename... NewSignatures>
struct rebind
{
typedef channel_traits<NewSignatures...> other;
};
template <typename Element>
struct container
{
typedef std::deque<Element> type;
};
typedef R receive_cancelled_signature(asio::error_code);
template <typename F>
static void invoke_receive_cancelled(F f)
{
const asio::error_code e = error::channel_cancelled;
static_cast<F&&>(f)(e);
}
typedef R receive_closed_signature(asio::error_code);
template <typename F>
static void invoke_receive_closed(F f)
{
const asio::error_code e = error::channel_closed;
static_cast<F&&>(f)(e);
}
};
#endif // defined(GENERATING_DOCUMENTATION)
} // namespace experimental
} // namespace asio
#include "asio/detail/pop_options.hpp"
#endif // ASIO_EXPERIMENTAL_CHANNEL_TRAITS_HPP
|
0 | repos/asio/asio/include/asio | repos/asio/asio/include/asio/experimental/awaitable_operators.hpp | //
// experimental/awaitable_operators.hpp
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef ASIO_EXPERIMENTAL_AWAITABLE_OPERATORS_HPP
#define ASIO_EXPERIMENTAL_AWAITABLE_OPERATORS_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include "asio/detail/config.hpp"
#include <optional>
#include <stdexcept>
#include <tuple>
#include <variant>
#include "asio/awaitable.hpp"
#include "asio/co_spawn.hpp"
#include "asio/detail/type_traits.hpp"
#include "asio/experimental/deferred.hpp"
#include "asio/experimental/parallel_group.hpp"
#include "asio/multiple_exceptions.hpp"
#include "asio/this_coro.hpp"
#include "asio/detail/push_options.hpp"
namespace asio {
namespace experimental {
namespace awaitable_operators {
namespace detail {
template <typename T, typename Executor>
awaitable<T, Executor> awaitable_wrap(awaitable<T, Executor> a,
constraint_t<is_constructible<T>::value>* = 0)
{
return a;
}
template <typename T, typename Executor>
awaitable<std::optional<T>, Executor> awaitable_wrap(awaitable<T, Executor> a,
constraint_t<!is_constructible<T>::value>* = 0)
{
co_return std::optional<T>(co_await std::move(a));
}
template <typename T>
T& awaitable_unwrap(conditional_t<true, T, void>& r,
constraint_t<is_constructible<T>::value>* = 0)
{
return r;
}
template <typename T>
T& awaitable_unwrap(std::optional<conditional_t<true, T, void>>& r,
constraint_t<!is_constructible<T>::value>* = 0)
{
return *r;
}
} // namespace detail
/// Wait for both operations to succeed.
/**
* If one operations fails, the other is cancelled as the AND-condition can no
* longer be satisfied.
*/
template <typename Executor>
awaitable<void, Executor> operator&&(
awaitable<void, Executor> t, awaitable<void, Executor> u)
{
auto ex = co_await this_coro::executor;
auto [order, ex0, ex1] =
co_await make_parallel_group(
co_spawn(ex, std::move(t), deferred),
co_spawn(ex, std::move(u), deferred)
).async_wait(
wait_for_one_error(),
deferred
);
if (ex0 && ex1)
throw multiple_exceptions(ex0);
if (ex0)
std::rethrow_exception(ex0);
if (ex1)
std::rethrow_exception(ex1);
co_return;
}
/// Wait for both operations to succeed.
/**
* If one operations fails, the other is cancelled as the AND-condition can no
* longer be satisfied.
*/
template <typename U, typename Executor>
awaitable<U, Executor> operator&&(
awaitable<void, Executor> t, awaitable<U, Executor> u)
{
auto ex = co_await this_coro::executor;
auto [order, ex0, ex1, r1] =
co_await make_parallel_group(
co_spawn(ex, std::move(t), deferred),
co_spawn(ex, detail::awaitable_wrap(std::move(u)), deferred)
).async_wait(
wait_for_one_error(),
deferred
);
if (ex0 && ex1)
throw multiple_exceptions(ex0);
if (ex0)
std::rethrow_exception(ex0);
if (ex1)
std::rethrow_exception(ex1);
co_return std::move(detail::awaitable_unwrap<U>(r1));
}
/// Wait for both operations to succeed.
/**
* If one operations fails, the other is cancelled as the AND-condition can no
* longer be satisfied.
*/
template <typename T, typename Executor>
awaitable<T, Executor> operator&&(
awaitable<T, Executor> t, awaitable<void, Executor> u)
{
auto ex = co_await this_coro::executor;
auto [order, ex0, r0, ex1] =
co_await make_parallel_group(
co_spawn(ex, detail::awaitable_wrap(std::move(t)), deferred),
co_spawn(ex, std::move(u), deferred)
).async_wait(
wait_for_one_error(),
deferred
);
if (ex0 && ex1)
throw multiple_exceptions(ex0);
if (ex0)
std::rethrow_exception(ex0);
if (ex1)
std::rethrow_exception(ex1);
co_return std::move(detail::awaitable_unwrap<T>(r0));
}
/// Wait for both operations to succeed.
/**
* If one operations fails, the other is cancelled as the AND-condition can no
* longer be satisfied.
*/
template <typename T, typename U, typename Executor>
awaitable<std::tuple<T, U>, Executor> operator&&(
awaitable<T, Executor> t, awaitable<U, Executor> u)
{
auto ex = co_await this_coro::executor;
auto [order, ex0, r0, ex1, r1] =
co_await make_parallel_group(
co_spawn(ex, detail::awaitable_wrap(std::move(t)), deferred),
co_spawn(ex, detail::awaitable_wrap(std::move(u)), deferred)
).async_wait(
wait_for_one_error(),
deferred
);
if (ex0 && ex1)
throw multiple_exceptions(ex0);
if (ex0)
std::rethrow_exception(ex0);
if (ex1)
std::rethrow_exception(ex1);
co_return std::make_tuple(
std::move(detail::awaitable_unwrap<T>(r0)),
std::move(detail::awaitable_unwrap<U>(r1)));
}
/// Wait for both operations to succeed.
/**
* If one operations fails, the other is cancelled as the AND-condition can no
* longer be satisfied.
*/
template <typename... T, typename Executor>
awaitable<std::tuple<T..., std::monostate>, Executor> operator&&(
awaitable<std::tuple<T...>, Executor> t, awaitable<void, Executor> u)
{
auto ex = co_await this_coro::executor;
auto [order, ex0, r0, ex1, r1] =
co_await make_parallel_group(
co_spawn(ex, detail::awaitable_wrap(std::move(t)), deferred),
co_spawn(ex, std::move(u), deferred)
).async_wait(
wait_for_one_error(),
deferred
);
if (ex0 && ex1)
throw multiple_exceptions(ex0);
if (ex0)
std::rethrow_exception(ex0);
if (ex1)
std::rethrow_exception(ex1);
co_return std::move(detail::awaitable_unwrap<std::tuple<T...>>(r0));
}
/// Wait for both operations to succeed.
/**
* If one operations fails, the other is cancelled as the AND-condition can no
* longer be satisfied.
*/
template <typename... T, typename U, typename Executor>
awaitable<std::tuple<T..., U>, Executor> operator&&(
awaitable<std::tuple<T...>, Executor> t, awaitable<U, Executor> u)
{
auto ex = co_await this_coro::executor;
auto [order, ex0, r0, ex1, r1] =
co_await make_parallel_group(
co_spawn(ex, detail::awaitable_wrap(std::move(t)), deferred),
co_spawn(ex, detail::awaitable_wrap(std::move(u)), deferred)
).async_wait(
wait_for_one_error(),
deferred
);
if (ex0 && ex1)
throw multiple_exceptions(ex0);
if (ex0)
std::rethrow_exception(ex0);
if (ex1)
std::rethrow_exception(ex1);
co_return std::tuple_cat(
std::move(detail::awaitable_unwrap<std::tuple<T...>>(r0)),
std::make_tuple(std::move(detail::awaitable_unwrap<U>(r1))));
}
/// Wait for one operation to succeed.
/**
* If one operations succeeds, the other is cancelled as the OR-condition is
* already satisfied.
*/
template <typename Executor>
awaitable<std::variant<std::monostate, std::monostate>, Executor> operator||(
awaitable<void, Executor> t, awaitable<void, Executor> u)
{
auto ex = co_await this_coro::executor;
auto [order, ex0, ex1] =
co_await make_parallel_group(
co_spawn(ex, std::move(t), deferred),
co_spawn(ex, std::move(u), deferred)
).async_wait(
wait_for_one_success(),
deferred
);
if (order[0] == 0)
{
if (!ex0)
co_return std::variant<std::monostate, std::monostate>{
std::in_place_index<0>};
if (!ex1)
co_return std::variant<std::monostate, std::monostate>{
std::in_place_index<1>};
throw multiple_exceptions(ex0);
}
else
{
if (!ex1)
co_return std::variant<std::monostate, std::monostate>{
std::in_place_index<1>};
if (!ex0)
co_return std::variant<std::monostate, std::monostate>{
std::in_place_index<0>};
throw multiple_exceptions(ex1);
}
}
/// Wait for one operation to succeed.
/**
* If one operations succeeds, the other is cancelled as the OR-condition is
* already satisfied.
*/
template <typename U, typename Executor>
awaitable<std::variant<std::monostate, U>, Executor> operator||(
awaitable<void, Executor> t, awaitable<U, Executor> u)
{
auto ex = co_await this_coro::executor;
auto [order, ex0, ex1, r1] =
co_await make_parallel_group(
co_spawn(ex, std::move(t), deferred),
co_spawn(ex, detail::awaitable_wrap(std::move(u)), deferred)
).async_wait(
wait_for_one_success(),
deferred
);
if (order[0] == 0)
{
if (!ex0)
co_return std::variant<std::monostate, U>{
std::in_place_index<0>};
if (!ex1)
co_return std::variant<std::monostate, U>{
std::in_place_index<1>,
std::move(detail::awaitable_unwrap<U>(r1))};
throw multiple_exceptions(ex0);
}
else
{
if (!ex1)
co_return std::variant<std::monostate, U>{
std::in_place_index<1>,
std::move(detail::awaitable_unwrap<U>(r1))};
if (!ex0)
co_return std::variant<std::monostate, U>{
std::in_place_index<0>};
throw multiple_exceptions(ex1);
}
}
/// Wait for one operation to succeed.
/**
* If one operations succeeds, the other is cancelled as the OR-condition is
* already satisfied.
*/
template <typename T, typename Executor>
awaitable<std::variant<T, std::monostate>, Executor> operator||(
awaitable<T, Executor> t, awaitable<void, Executor> u)
{
auto ex = co_await this_coro::executor;
auto [order, ex0, r0, ex1] =
co_await make_parallel_group(
co_spawn(ex, detail::awaitable_wrap(std::move(t)), deferred),
co_spawn(ex, std::move(u), deferred)
).async_wait(
wait_for_one_success(),
deferred
);
if (order[0] == 0)
{
if (!ex0)
co_return std::variant<T, std::monostate>{
std::in_place_index<0>,
std::move(detail::awaitable_unwrap<T>(r0))};
if (!ex1)
co_return std::variant<T, std::monostate>{
std::in_place_index<1>};
throw multiple_exceptions(ex0);
}
else
{
if (!ex1)
co_return std::variant<T, std::monostate>{
std::in_place_index<1>};
if (!ex0)
co_return std::variant<T, std::monostate>{
std::in_place_index<0>,
std::move(detail::awaitable_unwrap<T>(r0))};
throw multiple_exceptions(ex1);
}
}
/// Wait for one operation to succeed.
/**
* If one operations succeeds, the other is cancelled as the OR-condition is
* already satisfied.
*/
template <typename T, typename U, typename Executor>
awaitable<std::variant<T, U>, Executor> operator||(
awaitable<T, Executor> t, awaitable<U, Executor> u)
{
auto ex = co_await this_coro::executor;
auto [order, ex0, r0, ex1, r1] =
co_await make_parallel_group(
co_spawn(ex, detail::awaitable_wrap(std::move(t)), deferred),
co_spawn(ex, detail::awaitable_wrap(std::move(u)), deferred)
).async_wait(
wait_for_one_success(),
deferred
);
if (order[0] == 0)
{
if (!ex0)
co_return std::variant<T, U>{
std::in_place_index<0>,
std::move(detail::awaitable_unwrap<T>(r0))};
if (!ex1)
co_return std::variant<T, U>{
std::in_place_index<1>,
std::move(detail::awaitable_unwrap<U>(r1))};
throw multiple_exceptions(ex0);
}
else
{
if (!ex1)
co_return std::variant<T, U>{
std::in_place_index<1>,
std::move(detail::awaitable_unwrap<U>(r1))};
if (!ex0)
co_return std::variant<T, U>{
std::in_place_index<0>,
std::move(detail::awaitable_unwrap<T>(r0))};
throw multiple_exceptions(ex1);
}
}
namespace detail {
template <typename... T>
struct widen_variant
{
template <std::size_t I, typename SourceVariant>
static std::variant<T...> call(SourceVariant& source)
{
if (source.index() == I)
return std::variant<T...>{
std::in_place_index<I>, std::move(std::get<I>(source))};
else if constexpr (I + 1 < std::variant_size_v<SourceVariant>)
return call<I + 1>(source);
else
throw std::logic_error("empty variant");
}
};
} // namespace detail
/// Wait for one operation to succeed.
/**
* If one operations succeeds, the other is cancelled as the OR-condition is
* already satisfied.
*/
template <typename... T, typename Executor>
awaitable<std::variant<T..., std::monostate>, Executor> operator||(
awaitable<std::variant<T...>, Executor> t, awaitable<void, Executor> u)
{
auto ex = co_await this_coro::executor;
auto [order, ex0, r0, ex1] =
co_await make_parallel_group(
co_spawn(ex, detail::awaitable_wrap(std::move(t)), deferred),
co_spawn(ex, std::move(u), deferred)
).async_wait(
wait_for_one_success(),
deferred
);
using widen = detail::widen_variant<T..., std::monostate>;
if (order[0] == 0)
{
if (!ex0)
co_return widen::template call<0>(
detail::awaitable_unwrap<std::variant<T...>>(r0));
if (!ex1)
co_return std::variant<T..., std::monostate>{
std::in_place_index<sizeof...(T)>};
throw multiple_exceptions(ex0);
}
else
{
if (!ex1)
co_return std::variant<T..., std::monostate>{
std::in_place_index<sizeof...(T)>};
if (!ex0)
co_return widen::template call<0>(
detail::awaitable_unwrap<std::variant<T...>>(r0));
throw multiple_exceptions(ex1);
}
}
/// Wait for one operation to succeed.
/**
* If one operations succeeds, the other is cancelled as the OR-condition is
* already satisfied.
*/
template <typename... T, typename U, typename Executor>
awaitable<std::variant<T..., U>, Executor> operator||(
awaitable<std::variant<T...>, Executor> t, awaitable<U, Executor> u)
{
auto ex = co_await this_coro::executor;
auto [order, ex0, r0, ex1, r1] =
co_await make_parallel_group(
co_spawn(ex, detail::awaitable_wrap(std::move(t)), deferred),
co_spawn(ex, detail::awaitable_wrap(std::move(u)), deferred)
).async_wait(
wait_for_one_success(),
deferred
);
using widen = detail::widen_variant<T..., U>;
if (order[0] == 0)
{
if (!ex0)
co_return widen::template call<0>(
detail::awaitable_unwrap<std::variant<T...>>(r0));
if (!ex1)
co_return std::variant<T..., U>{
std::in_place_index<sizeof...(T)>,
std::move(detail::awaitable_unwrap<U>(r1))};
throw multiple_exceptions(ex0);
}
else
{
if (!ex1)
co_return std::variant<T..., U>{
std::in_place_index<sizeof...(T)>,
std::move(detail::awaitable_unwrap<U>(r1))};
if (!ex0)
co_return widen::template call<0>(
detail::awaitable_unwrap<std::variant<T...>>(r0));
throw multiple_exceptions(ex1);
}
}
} // namespace awaitable_operators
} // namespace experimental
} // namespace asio
#include "asio/detail/pop_options.hpp"
#endif // ASIO_EXPERIMENTAL_AWAITABLE_OPERATORS_HPP
|
0 | repos/asio/asio/include/asio | repos/asio/asio/include/asio/experimental/use_promise.hpp | //
// experimental/use_promise.hpp
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2021-2023 Klemens D. Morgenstern
// (klemens dot morgenstern at gmx dot net)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef ASIO_EXPERIMENTAL_USE_PROMISE_HPP
#define ASIO_EXPERIMENTAL_USE_PROMISE_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include "asio/detail/config.hpp"
#include <memory>
#include "asio/detail/type_traits.hpp"
#include "asio/detail/push_options.hpp"
namespace asio {
namespace experimental {
template <typename Allocator = std::allocator<void>>
struct use_promise_t
{
/// The allocator type. The allocator is used when constructing the
/// @c promise object for a given asynchronous operation.
typedef Allocator allocator_type;
/// Construct using default-constructed allocator.
constexpr use_promise_t()
{
}
/// Construct using specified allocator.
explicit use_promise_t(const Allocator& allocator)
: allocator_(allocator)
{
}
/// Obtain allocator.
allocator_type get_allocator() const noexcept
{
return allocator_;
}
/// Adapts an executor to add the @c use_promise_t completion token as the
/// default.
template <typename InnerExecutor>
struct executor_with_default : InnerExecutor
{
/// Specify @c use_promise_t as the default completion token type.
typedef use_promise_t<Allocator> 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)
{
}
};
/// Function helper to adapt an I/O object to use @c use_promise_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));
}
/// Specify an alternate allocator.
template <typename OtherAllocator>
use_promise_t<OtherAllocator> rebind(const OtherAllocator& allocator) const
{
return use_promise_t<OtherAllocator>(allocator);
}
private:
Allocator allocator_;
};
ASIO_INLINE_VARIABLE constexpr use_promise_t<> use_promise;
} // namespace experimental
} // namespace asio
#include "asio/detail/pop_options.hpp"
#include "asio/experimental/impl/use_promise.hpp"
#endif // ASIO_EXPERIMENTAL_USE_CORO_HPP
|
0 | repos/asio/asio/include/asio | repos/asio/asio/include/asio/experimental/channel.hpp | //
// experimental/channel.hpp
// ~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef ASIO_EXPERIMENTAL_CHANNEL_HPP
#define ASIO_EXPERIMENTAL_CHANNEL_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include "asio/detail/config.hpp"
#include "asio/any_io_executor.hpp"
#include "asio/detail/type_traits.hpp"
#include "asio/execution/executor.hpp"
#include "asio/is_executor.hpp"
#include "asio/experimental/basic_channel.hpp"
#include "asio/experimental/channel_traits.hpp"
#include "asio/detail/push_options.hpp"
namespace asio {
namespace experimental {
namespace detail {
template <typename ExecutorOrSignature, typename = void>
struct channel_type
{
template <typename... Signatures>
struct inner
{
typedef basic_channel<any_io_executor, channel_traits<>,
ExecutorOrSignature, Signatures...> type;
};
};
template <typename ExecutorOrSignature>
struct channel_type<ExecutorOrSignature,
enable_if_t<
is_executor<ExecutorOrSignature>::value
|| execution::is_executor<ExecutorOrSignature>::value
>>
{
template <typename... Signatures>
struct inner
{
typedef basic_channel<ExecutorOrSignature,
channel_traits<>, Signatures...> type;
};
};
} // namespace detail
/// Template type alias for common use of channel.
template <typename ExecutorOrSignature, typename... Signatures>
using channel = typename detail::channel_type<
ExecutorOrSignature>::template inner<Signatures...>::type;
} // namespace experimental
} // namespace asio
#include "asio/detail/pop_options.hpp"
#endif // ASIO_EXPERIMENTAL_CHANNEL_HPP
|
0 | repos/asio/asio/include/asio | repos/asio/asio/include/asio/experimental/as_single.hpp | //
// experimental/as_single.hpp
// ~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef ASIO_EXPERIMENTAL_AS_SINGLE_HPP
#define ASIO_EXPERIMENTAL_AS_SINGLE_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include "asio/detail/config.hpp"
#include "asio/detail/type_traits.hpp"
#include "asio/detail/push_options.hpp"
namespace asio {
namespace experimental {
/// A @ref completion_token adapter used to specify that the completion handler
/// arguments should be combined into a single argument.
/**
* The as_single_t class is used to indicate that any arguments to the
* completion handler should be combined and passed as a single argument.
* If there is already one argument, that argument is passed as-is. If
* there is more than 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_single_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_single_t(
default_constructor_tag = default_constructor_tag(),
CompletionToken token = CompletionToken())
: token_(static_cast<CompletionToken&&>(token))
{
}
/// Constructor.
template <typename T>
constexpr explicit as_single_t(
T&& completion_token)
: token_(static_cast<T&&>(completion_token))
{
}
/// Adapts an executor to add the @c as_single_t completion token as the
/// default.
template <typename InnerExecutor>
struct executor_with_default : InnerExecutor
{
/// Specify @c as_single_t as the default completion token type.
typedef as_single_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 as_single_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_single_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 argument.
template <typename CompletionToken>
ASIO_NODISCARD inline
constexpr as_single_t<decay_t<CompletionToken>>
as_single(CompletionToken&& completion_token)
{
return as_single_t<decay_t<CompletionToken>>(
static_cast<CompletionToken&&>(completion_token));
}
} // namespace experimental
} // namespace asio
#include "asio/detail/pop_options.hpp"
#include "asio/experimental/impl/as_single.hpp"
#endif // ASIO_EXPERIMENTAL_AS_SINGLE_HPP
|
0 | repos/asio/asio/include/asio | repos/asio/asio/include/asio/experimental/cancellation_condition.hpp | //
// experimental/cancellation_condition.hpp
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef ASIO_EXPERIMENTAL_CANCELLATION_CONDITION_HPP
#define ASIO_EXPERIMENTAL_CANCELLATION_CONDITION_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include "asio/detail/config.hpp"
#include <exception>
#include "asio/cancellation_type.hpp"
#include "asio/error_code.hpp"
#include "asio/detail/type_traits.hpp"
#include "asio/detail/push_options.hpp"
namespace asio {
namespace experimental {
/// Wait for all operations to complete.
class wait_for_all
{
public:
template <typename... Args>
constexpr cancellation_type_t operator()(Args&&...) const noexcept
{
return cancellation_type::none;
}
};
/// Wait until an operation completes, then cancel the others.
class wait_for_one
{
public:
constexpr explicit wait_for_one(
cancellation_type_t cancel_type = cancellation_type::all)
: cancel_type_(cancel_type)
{
}
template <typename... Args>
constexpr cancellation_type_t operator()(Args&&...) const noexcept
{
return cancel_type_;
}
private:
cancellation_type_t cancel_type_;
};
/// Wait until an operation completes without an error, then cancel the others.
/**
* If no operation completes without an error, waits for completion of all
* operations.
*/
class wait_for_one_success
{
public:
constexpr explicit wait_for_one_success(
cancellation_type_t cancel_type = cancellation_type::all)
: cancel_type_(cancel_type)
{
}
constexpr cancellation_type_t
operator()() const noexcept
{
return cancel_type_;
}
template <typename E, typename... Args>
constexpr constraint_t<
!is_same<decay_t<E>, asio::error_code>::value
&& !is_same<decay_t<E>, std::exception_ptr>::value,
cancellation_type_t
> operator()(const E&, Args&&...) const noexcept
{
return cancel_type_;
}
template <typename E, typename... Args>
constexpr constraint_t<
is_same<decay_t<E>, asio::error_code>::value
|| is_same<decay_t<E>, std::exception_ptr>::value,
cancellation_type_t
> operator()(const E& e, Args&&...) const noexcept
{
return !!e ? cancellation_type::none : cancel_type_;
}
private:
cancellation_type_t cancel_type_;
};
/// Wait until an operation completes with an error, then cancel the others.
/**
* If no operation completes with an error, waits for completion of all
* operations.
*/
class wait_for_one_error
{
public:
constexpr explicit wait_for_one_error(
cancellation_type_t cancel_type = cancellation_type::all)
: cancel_type_(cancel_type)
{
}
constexpr cancellation_type_t operator()() const noexcept
{
return cancellation_type::none;
}
template <typename E, typename... Args>
constexpr constraint_t<
!is_same<decay_t<E>, asio::error_code>::value
&& !is_same<decay_t<E>, std::exception_ptr>::value,
cancellation_type_t
> operator()(const E&, Args&&...) const noexcept
{
return cancellation_type::none;
}
template <typename E, typename... Args>
constexpr constraint_t<
is_same<decay_t<E>, asio::error_code>::value
|| is_same<decay_t<E>, std::exception_ptr>::value,
cancellation_type_t
> operator()(const E& e, Args&&...) const noexcept
{
return !!e ? cancel_type_ : cancellation_type::none;
}
private:
cancellation_type_t cancel_type_;
};
} // namespace experimental
} // namespace asio
#include "asio/detail/pop_options.hpp"
#endif // ASIO_EXPERIMENTAL_CANCELLATION_CONDITION_HPP
|
0 | repos/asio/asio/include/asio | repos/asio/asio/include/asio/experimental/append.hpp | //
// experimental/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 ASIO_EXPERIMENTAL_APPEND_HPP
#define ASIO_EXPERIMENTAL_APPEND_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include "asio/detail/config.hpp"
#include "asio/append.hpp"
#include "asio/detail/push_options.hpp"
namespace asio {
namespace experimental {
#if !defined(ASIO_NO_DEPRECATED)
using asio::append_t;
using asio::append;
#endif // !defined(ASIO_NO_DEPRECATED)
} // namespace experimental
} // namespace asio
#include "asio/detail/pop_options.hpp"
#endif // ASIO_EXPERIMENTAL_APPEND_HPP
|
0 | repos/asio/asio/include/asio/experimental | repos/asio/asio/include/asio/experimental/detail/channel_operation.hpp | //
// experimental/detail/channel_operation.hpp
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef ASIO_EXPERIMENTAL_DETAIL_CHANNEL_OPERATION_HPP
#define ASIO_EXPERIMENTAL_DETAIL_CHANNEL_OPERATION_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include "asio/detail/config.hpp"
#include "asio/associated_allocator.hpp"
#include "asio/associated_executor.hpp"
#include "asio/associated_immediate_executor.hpp"
#include "asio/detail/initiate_post.hpp"
#include "asio/detail/initiate_dispatch.hpp"
#include "asio/detail/op_queue.hpp"
#include "asio/detail/type_traits.hpp"
#include "asio/execution/executor.hpp"
#include "asio/execution/outstanding_work.hpp"
#include "asio/executor_work_guard.hpp"
#include "asio/prefer.hpp"
#include "asio/detail/push_options.hpp"
namespace asio {
namespace experimental {
namespace detail {
// Base class for all channel operations. A function pointer is used instead of
// virtual functions to avoid the associated overhead.
class channel_operation ASIO_INHERIT_TRACKED_HANDLER
{
public:
template <typename Executor, typename = void, typename = void>
class handler_work_base;
template <typename Handler, typename IoExecutor, typename = void>
class handler_work;
void destroy()
{
func_(this, destroy_op, 0);
}
protected:
enum action
{
destroy_op = 0,
immediate_op = 1,
post_op = 2,
dispatch_op = 3,
cancel_op = 4,
close_op = 5
};
typedef void (*func_type)(channel_operation*, action, void*);
channel_operation(func_type func)
: next_(0),
func_(func),
cancellation_key_(0)
{
}
// Prevents deletion through this type.
~channel_operation()
{
}
friend class asio::detail::op_queue_access;
channel_operation* next_;
func_type func_;
public:
// The operation key used for targeted cancellation.
void* cancellation_key_;
};
template <typename Executor, typename, typename>
class channel_operation::handler_work_base
{
public:
typedef decay_t<
prefer_result_t<Executor,
execution::outstanding_work_t::tracked_t
>
> executor_type;
handler_work_base(int, const Executor& ex)
: executor_(asio::prefer(ex, execution::outstanding_work.tracked))
{
}
const executor_type& get_executor() const noexcept
{
return executor_;
}
template <typename IoExecutor, typename Function, typename Handler>
void post(const IoExecutor& io_exec, Function& function, Handler&)
{
(asio::detail::initiate_post_with_executor<IoExecutor>(io_exec))(
static_cast<Function&&>(function));
}
template <typename Function, typename Handler>
void dispatch(Function& function, Handler& handler)
{
associated_allocator_t<Handler> allocator =
(get_associated_allocator)(handler);
asio::prefer(executor_,
execution::allocator(allocator)
).execute(static_cast<Function&&>(function));
}
private:
executor_type executor_;
};
template <typename Executor>
class channel_operation::handler_work_base<Executor,
enable_if_t<
execution::is_executor<Executor>::value
>,
enable_if_t<
can_require<Executor, execution::blocking_t::never_t>::value
>
>
{
public:
typedef decay_t<
prefer_result_t<Executor,
execution::outstanding_work_t::tracked_t
>
> executor_type;
handler_work_base(int, const Executor& ex)
: executor_(asio::prefer(ex, execution::outstanding_work.tracked))
{
}
const executor_type& get_executor() const noexcept
{
return executor_;
}
template <typename IoExecutor, typename Function, typename Handler>
void post(const IoExecutor&, Function& function, Handler& handler)
{
associated_allocator_t<Handler> allocator =
(get_associated_allocator)(handler);
asio::prefer(
asio::require(executor_, execution::blocking.never),
execution::allocator(allocator)
).execute(static_cast<Function&&>(function));
}
template <typename Function, typename Handler>
void dispatch(Function& function, Handler& handler)
{
associated_allocator_t<Handler> allocator =
(get_associated_allocator)(handler);
asio::prefer(executor_,
execution::allocator(allocator)
).execute(static_cast<Function&&>(function));
}
private:
executor_type executor_;
};
#if !defined(ASIO_NO_TS_EXECUTORS)
template <typename Executor>
class channel_operation::handler_work_base<Executor,
enable_if_t<
!execution::is_executor<Executor>::value
>
>
{
public:
typedef Executor executor_type;
handler_work_base(int, const Executor& ex)
: work_(ex)
{
}
executor_type get_executor() const noexcept
{
return work_.get_executor();
}
template <typename IoExecutor, typename Function, typename Handler>
void post(const IoExecutor&, Function& function, Handler& handler)
{
associated_allocator_t<Handler> allocator =
(get_associated_allocator)(handler);
work_.get_executor().post(
static_cast<Function&&>(function), allocator);
}
template <typename Function, typename Handler>
void dispatch(Function& function, Handler& handler)
{
associated_allocator_t<Handler> allocator =
(get_associated_allocator)(handler);
work_.get_executor().dispatch(
static_cast<Function&&>(function), allocator);
}
private:
executor_work_guard<Executor> work_;
};
#endif // !defined(ASIO_NO_TS_EXECUTORS)
template <typename Handler, typename IoExecutor, typename>
class channel_operation::handler_work :
channel_operation::handler_work_base<IoExecutor>,
channel_operation::handler_work_base<
associated_executor_t<Handler, IoExecutor>, IoExecutor>
{
public:
typedef channel_operation::handler_work_base<IoExecutor> base1_type;
typedef channel_operation::handler_work_base<
associated_executor_t<Handler, IoExecutor>, IoExecutor>
base2_type;
handler_work(Handler& handler, const IoExecutor& io_ex) noexcept
: base1_type(0, io_ex),
base2_type(0, (get_associated_executor)(handler, io_ex))
{
}
template <typename Function>
void post(Function& function, Handler& handler)
{
base2_type::post(base1_type::get_executor(), function, handler);
}
template <typename Function>
void dispatch(Function& function, Handler& handler)
{
base2_type::dispatch(function, handler);
}
template <typename Function>
void immediate(Function& function, Handler& handler, ...)
{
typedef associated_immediate_executor_t<Handler,
typename base1_type::executor_type> immediate_ex_type;
immediate_ex_type immediate_ex = (get_associated_immediate_executor)(
handler, base1_type::get_executor());
(asio::detail::initiate_dispatch_with_executor<immediate_ex_type>(
immediate_ex))(static_cast<Function&&>(function));
}
template <typename Function>
void immediate(Function& function, Handler&,
enable_if_t<
is_same<
typename associated_immediate_executor<
conditional_t<false, Function, Handler>,
typename base1_type::executor_type>::
asio_associated_immediate_executor_is_unspecialised,
void
>::value
>*)
{
(asio::detail::initiate_post_with_executor<
typename base1_type::executor_type>(
base1_type::get_executor()))(
static_cast<Function&&>(function));
}
};
template <typename Handler, typename IoExecutor>
class channel_operation::handler_work<
Handler, IoExecutor,
enable_if_t<
is_same<
typename associated_executor<Handler,
IoExecutor>::asio_associated_executor_is_unspecialised,
void
>::value
>
> : handler_work_base<IoExecutor>
{
public:
typedef channel_operation::handler_work_base<IoExecutor> base1_type;
handler_work(Handler&, const IoExecutor& io_ex) noexcept
: base1_type(0, io_ex)
{
}
template <typename Function>
void post(Function& function, Handler& handler)
{
base1_type::post(base1_type::get_executor(), function, handler);
}
template <typename Function>
void dispatch(Function& function, Handler& handler)
{
base1_type::dispatch(function, handler);
}
template <typename Function>
void immediate(Function& function, Handler& handler, ...)
{
typedef associated_immediate_executor_t<Handler,
typename base1_type::executor_type> immediate_ex_type;
immediate_ex_type immediate_ex = (get_associated_immediate_executor)(
handler, base1_type::get_executor());
(asio::detail::initiate_dispatch_with_executor<immediate_ex_type>(
immediate_ex))(static_cast<Function&&>(function));
}
template <typename Function>
void immediate(Function& function, Handler& handler,
enable_if_t<
is_same<
typename associated_immediate_executor<
conditional_t<false, Function, Handler>,
typename base1_type::executor_type>::
asio_associated_immediate_executor_is_unspecialised,
void
>::value
>*)
{
base1_type::post(base1_type::get_executor(), function, handler);
}
};
} // namespace detail
} // namespace experimental
} // namespace asio
#include "asio/detail/pop_options.hpp"
#endif // ASIO_EXPERIMENTAL_DETAIL_CHANNEL_OPERATION_HPP
|
0 | repos/asio/asio/include/asio/experimental | repos/asio/asio/include/asio/experimental/detail/channel_receive_op.hpp | //
// experimental/detail/channel_receive_op.hpp
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef ASIO_EXPERIMENTAL_DETAIL_CHANNEL_RECEIVE_OP_HPP
#define ASIO_EXPERIMENTAL_DETAIL_CHANNEL_RECEIVE_OP_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include "asio/detail/config.hpp"
#include "asio/detail/bind_handler.hpp"
#include "asio/detail/completion_handler.hpp"
#include "asio/detail/handler_alloc_helpers.hpp"
#include "asio/error.hpp"
#include "asio/experimental/detail/channel_operation.hpp"
#include "asio/detail/push_options.hpp"
namespace asio {
namespace experimental {
namespace detail {
template <typename Payload>
class channel_receive : public channel_operation
{
public:
void immediate(Payload payload)
{
func_(this, immediate_op, &payload);
}
void post(Payload payload)
{
func_(this, post_op, &payload);
}
void dispatch(Payload payload)
{
func_(this, dispatch_op, &payload);
}
protected:
channel_receive(func_type func)
: channel_operation(func)
{
}
};
template <typename Payload, typename Handler, typename IoExecutor>
class channel_receive_op : public channel_receive<Payload>
{
public:
ASIO_DEFINE_HANDLER_PTR(channel_receive_op);
template <typename... Args>
channel_receive_op(Handler& handler, const IoExecutor& io_ex)
: channel_receive<Payload>(&channel_receive_op::do_action),
handler_(static_cast<Handler&&>(handler)),
work_(handler_, io_ex)
{
}
static void do_action(channel_operation* base,
channel_operation::action a, void* v)
{
// Take ownership of the operation object.
channel_receive_op* o(static_cast<channel_receive_op*>(base));
ptr p = { asio::detail::addressof(o->handler_), o, o };
ASIO_HANDLER_COMPLETION((*o));
// Take ownership of the operation's outstanding work.
channel_operation::handler_work<Handler, IoExecutor> w(
static_cast<channel_operation::handler_work<Handler, IoExecutor>&&>(
o->work_));
// Make a copy of the handler so that the memory can be deallocated before
// the handler is posted. Even if we're not about to post the handler, a
// sub-object of the handler may be the true owner of the memory associated
// with the handler. Consequently, a local copy of the handler is required
// to ensure that any owning sub-object remains valid until after we have
// deallocated the memory here.
if (a != channel_operation::destroy_op)
{
Payload* payload = static_cast<Payload*>(v);
asio::detail::completion_payload_handler<Payload, Handler> handler(
static_cast<Payload&&>(*payload), o->handler_);
p.h = asio::detail::addressof(handler.handler_);
p.reset();
ASIO_HANDLER_INVOCATION_BEGIN(());
if (a == channel_operation::immediate_op)
w.immediate(handler, handler.handler_, 0);
else if (a == channel_operation::dispatch_op)
w.dispatch(handler, handler.handler_);
else
w.post(handler, handler.handler_);
ASIO_HANDLER_INVOCATION_END;
}
else
{
asio::detail::binder0<Handler> handler(o->handler_);
p.h = asio::detail::addressof(handler.handler_);
p.reset();
}
}
private:
Handler handler_;
channel_operation::handler_work<Handler, IoExecutor> work_;
};
} // namespace detail
} // namespace experimental
} // namespace asio
#include "asio/detail/pop_options.hpp"
#endif // ASIO_EXPERIMENTAL_DETAIL_CHANNEL_RECEIVE_OP_HPP
|
0 | repos/asio/asio/include/asio/experimental | repos/asio/asio/include/asio/experimental/detail/channel_service.hpp | //
// experimental/detail/channel_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 ASIO_EXPERIMENTAL_DETAIL_CHANNEL_SERVICE_HPP
#define ASIO_EXPERIMENTAL_DETAIL_CHANNEL_SERVICE_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include "asio/detail/config.hpp"
#include "asio/associated_cancellation_slot.hpp"
#include "asio/cancellation_type.hpp"
#include "asio/detail/completion_message.hpp"
#include "asio/detail/completion_payload.hpp"
#include "asio/detail/completion_payload_handler.hpp"
#include "asio/detail/mutex.hpp"
#include "asio/detail/op_queue.hpp"
#include "asio/execution_context.hpp"
#include "asio/experimental/detail/channel_receive_op.hpp"
#include "asio/experimental/detail/channel_send_op.hpp"
#include "asio/experimental/detail/has_signature.hpp"
#include "asio/detail/push_options.hpp"
namespace asio {
namespace experimental {
namespace detail {
template <typename Mutex>
class channel_service
: public asio::detail::execution_context_service_base<
channel_service<Mutex>>
{
public:
// Possible states for a channel end.
enum state
{
buffer = 0,
waiter = 1,
block = 2,
closed = 3
};
// The base implementation type of all channels.
struct base_implementation_type
{
// Default constructor.
base_implementation_type()
: receive_state_(block),
send_state_(block),
max_buffer_size_(0),
next_(0),
prev_(0)
{
}
// The current state of the channel.
state receive_state_ : 16;
state send_state_ : 16;
// The maximum number of elements that may be buffered in the channel.
std::size_t max_buffer_size_;
// The operations that are waiting on the channel.
asio::detail::op_queue<channel_operation> waiters_;
// Pointers to adjacent channel implementations in linked list.
base_implementation_type* next_;
base_implementation_type* prev_;
// The mutex type to protect the internal implementation.
mutable Mutex mutex_;
};
// The implementation for a specific value type.
template <typename Traits, typename... Signatures>
struct implementation_type;
// Constructor.
channel_service(asio::execution_context& ctx);
// Destroy all user-defined handler objects owned by the service.
void shutdown();
// Construct a new channel implementation.
void construct(base_implementation_type& impl, std::size_t max_buffer_size);
// Destroy a channel implementation.
template <typename Traits, typename... Signatures>
void destroy(implementation_type<Traits, Signatures...>& impl);
// Move-construct a new channel implementation.
template <typename Traits, typename... Signatures>
void move_construct(implementation_type<Traits, Signatures...>& impl,
implementation_type<Traits, Signatures...>& other_impl);
// Move-assign from another channel implementation.
template <typename Traits, typename... Signatures>
void move_assign(implementation_type<Traits, Signatures...>& impl,
channel_service& other_service,
implementation_type<Traits, Signatures...>& other_impl);
// Get the capacity of the channel.
std::size_t capacity(
const base_implementation_type& impl) const noexcept;
// Determine whether the channel is open.
bool is_open(const base_implementation_type& impl) const noexcept;
// Reset the channel to its initial state.
template <typename Traits, typename... Signatures>
void reset(implementation_type<Traits, Signatures...>& impl);
// Close the channel.
template <typename Traits, typename... Signatures>
void close(implementation_type<Traits, Signatures...>& impl);
// Cancel all operations associated with the channel.
template <typename Traits, typename... Signatures>
void cancel(implementation_type<Traits, Signatures...>& impl);
// Cancel the operation associated with the channel that has the given key.
template <typename Traits, typename... Signatures>
void cancel_by_key(implementation_type<Traits, Signatures...>& impl,
void* cancellation_key);
// Determine whether a value can be read from the channel without blocking.
bool ready(const base_implementation_type& impl) const noexcept;
// Synchronously send a new value into the channel.
template <typename Message, typename Traits,
typename... Signatures, typename... Args>
bool try_send(implementation_type<Traits, Signatures...>& impl,
bool via_dispatch, Args&&... args);
// Synchronously send a number of new values into the channel.
template <typename Message, typename Traits,
typename... Signatures, typename... Args>
std::size_t try_send_n(implementation_type<Traits, Signatures...>& impl,
std::size_t count, bool via_dispatch, Args&&... args);
// Asynchronously send a new value into the channel.
template <typename Traits, typename... Signatures,
typename Handler, typename IoExecutor>
void async_send(implementation_type<Traits, Signatures...>& impl,
typename implementation_type<Traits,
Signatures...>::payload_type&& payload,
Handler& handler, const IoExecutor& io_ex)
{
associated_cancellation_slot_t<Handler> slot
= asio::get_associated_cancellation_slot(handler);
// Allocate and construct an operation to wrap the handler.
typedef channel_send_op<
typename implementation_type<Traits, Signatures...>::payload_type,
Handler, IoExecutor> op;
typename op::ptr p = { asio::detail::addressof(handler),
op::ptr::allocate(handler), 0 };
p.p = new (p.v) op(static_cast<typename implementation_type<
Traits, Signatures...>::payload_type&&>(payload), handler, io_ex);
// Optionally register for per-operation cancellation.
if (slot.is_connected())
{
p.p->cancellation_key_ =
&slot.template emplace<op_cancellation<Traits, Signatures...>>(
this, &impl);
}
ASIO_HANDLER_CREATION((this->context(), *p.p,
"channel", &impl, 0, "async_send"));
start_send_op(impl, p.p);
p.v = p.p = 0;
}
// Synchronously receive a value from the channel.
template <typename Traits, typename... Signatures, typename Handler>
bool try_receive(implementation_type<Traits, Signatures...>& impl,
Handler&& handler);
// Asynchronously receive a value from the channel.
template <typename Traits, typename... Signatures,
typename Handler, typename IoExecutor>
void async_receive(implementation_type<Traits, Signatures...>& impl,
Handler& handler, const IoExecutor& io_ex)
{
associated_cancellation_slot_t<Handler> slot
= asio::get_associated_cancellation_slot(handler);
// Allocate and construct an operation to wrap the handler.
typedef channel_receive_op<
typename implementation_type<Traits, Signatures...>::payload_type,
Handler, IoExecutor> op;
typename op::ptr p = { asio::detail::addressof(handler),
op::ptr::allocate(handler), 0 };
p.p = new (p.v) op(handler, io_ex);
// Optionally register for per-operation cancellation.
if (slot.is_connected())
{
p.p->cancellation_key_ =
&slot.template emplace<op_cancellation<Traits, Signatures...>>(
this, &impl);
}
ASIO_HANDLER_CREATION((this->context(), *p.p,
"channel", &impl, 0, "async_receive"));
start_receive_op(impl, p.p);
p.v = p.p = 0;
}
private:
// Helper function object to handle a closed notification.
template <typename Payload, typename Signature>
struct post_receive
{
explicit post_receive(channel_receive<Payload>* op)
: op_(op)
{
}
template <typename... Args>
void operator()(Args&&... args)
{
op_->post(
asio::detail::completion_message<Signature>(0,
static_cast<Args&&>(args)...));
}
channel_receive<Payload>* op_;
};
// Destroy a base channel implementation.
void base_destroy(base_implementation_type& impl);
// Helper function to start an asynchronous put operation.
template <typename Traits, typename... Signatures>
void start_send_op(implementation_type<Traits, Signatures...>& impl,
channel_send<typename implementation_type<
Traits, Signatures...>::payload_type>* send_op);
// Helper function to start an asynchronous get operation.
template <typename Traits, typename... Signatures>
void start_receive_op(implementation_type<Traits, Signatures...>& impl,
channel_receive<typename implementation_type<
Traits, Signatures...>::payload_type>* receive_op);
// Helper class used to implement per-operation cancellation.
template <typename Traits, typename... Signatures>
class op_cancellation
{
public:
op_cancellation(channel_service* s,
implementation_type<Traits, Signatures...>* impl)
: service_(s),
impl_(impl)
{
}
void operator()(cancellation_type_t type)
{
if (!!(type &
(cancellation_type::terminal
| cancellation_type::partial
| cancellation_type::total)))
{
service_->cancel_by_key(*impl_, this);
}
}
private:
channel_service* service_;
implementation_type<Traits, Signatures...>* impl_;
};
// Mutex to protect access to the linked list of implementations.
asio::detail::mutex mutex_;
// The head of a linked list of all implementations.
base_implementation_type* impl_list_;
};
// The implementation for a specific value type.
template <typename Mutex>
template <typename Traits, typename... Signatures>
struct channel_service<Mutex>::implementation_type : base_implementation_type
{
// The traits type associated with the channel.
typedef typename Traits::template rebind<Signatures...>::other traits_type;
// Type of an element stored in the buffer.
typedef conditional_t<
has_signature<
typename traits_type::receive_cancelled_signature,
Signatures...
>::value,
conditional_t<
has_signature<
typename traits_type::receive_closed_signature,
Signatures...
>::value,
asio::detail::completion_payload<Signatures...>,
asio::detail::completion_payload<
Signatures...,
typename traits_type::receive_closed_signature
>
>,
conditional_t<
has_signature<
typename traits_type::receive_closed_signature,
Signatures...,
typename traits_type::receive_cancelled_signature
>::value,
asio::detail::completion_payload<
Signatures...,
typename traits_type::receive_cancelled_signature
>,
asio::detail::completion_payload<
Signatures...,
typename traits_type::receive_cancelled_signature,
typename traits_type::receive_closed_signature
>
>
> payload_type;
// Move from another buffer.
void buffer_move_from(implementation_type& other)
{
buffer_ = static_cast<
typename traits_type::template container<payload_type>::type&&>(
other.buffer_);
other.buffer_clear();
}
// Get number of buffered elements.
std::size_t buffer_size() const
{
return buffer_.size();
}
// Push a new value to the back of the buffer.
void buffer_push(payload_type payload)
{
buffer_.push_back(static_cast<payload_type&&>(payload));
}
// Push new values to the back of the buffer.
std::size_t buffer_push_n(std::size_t count, payload_type payload)
{
std::size_t i = 0;
for (; i < count && buffer_.size() < this->max_buffer_size_; ++i)
buffer_.push_back(payload);
return i;
}
// Get the element at the front of the buffer.
payload_type buffer_front()
{
return static_cast<payload_type&&>(buffer_.front());
}
// Pop a value from the front of the buffer.
void buffer_pop()
{
buffer_.pop_front();
}
// Clear all buffered values.
void buffer_clear()
{
buffer_.clear();
}
private:
// Buffered values.
typename traits_type::template container<payload_type>::type buffer_;
};
// The implementation for a void value type.
template <typename Mutex>
template <typename Traits, typename R>
struct channel_service<Mutex>::implementation_type<Traits, R()>
: channel_service::base_implementation_type
{
// The traits type associated with the channel.
typedef typename Traits::template rebind<R()>::other traits_type;
// Type of an element stored in the buffer.
typedef conditional_t<
has_signature<
typename traits_type::receive_cancelled_signature,
R()
>::value,
conditional_t<
has_signature<
typename traits_type::receive_closed_signature,
R()
>::value,
asio::detail::completion_payload<R()>,
asio::detail::completion_payload<
R(),
typename traits_type::receive_closed_signature
>
>,
conditional_t<
has_signature<
typename traits_type::receive_closed_signature,
R(),
typename traits_type::receive_cancelled_signature
>::value,
asio::detail::completion_payload<
R(),
typename traits_type::receive_cancelled_signature
>,
asio::detail::completion_payload<
R(),
typename traits_type::receive_cancelled_signature,
typename traits_type::receive_closed_signature
>
>
> payload_type;
// Construct with empty buffer.
implementation_type()
: buffer_(0)
{
}
// Move from another buffer.
void buffer_move_from(implementation_type& other)
{
buffer_ = other.buffer_;
other.buffer_ = 0;
}
// Get number of buffered elements.
std::size_t buffer_size() const
{
return buffer_;
}
// Push a new value to the back of the buffer.
void buffer_push(payload_type)
{
++buffer_;
}
// Push new values to the back of the buffer.
std::size_t buffer_push_n(std::size_t count, payload_type)
{
std::size_t available = this->max_buffer_size_ - buffer_;
count = (count < available) ? count : available;
buffer_ += count;
return count;
}
// Get the element at the front of the buffer.
payload_type buffer_front()
{
return payload_type(asio::detail::completion_message<R()>(0));
}
// Pop a value from the front of the buffer.
void buffer_pop()
{
--buffer_;
}
// Clear all values from the buffer.
void buffer_clear()
{
buffer_ = 0;
}
private:
// Number of buffered "values".
std::size_t buffer_;
};
// The implementation for an error_code signature.
template <typename Mutex>
template <typename Traits, typename R>
struct channel_service<Mutex>::implementation_type<
Traits, R(asio::error_code)>
: channel_service::base_implementation_type
{
// The traits type associated with the channel.
typedef typename Traits::template rebind<R(asio::error_code)>::other
traits_type;
// Type of an element stored in the buffer.
typedef conditional_t<
has_signature<
typename traits_type::receive_cancelled_signature,
R(asio::error_code)
>::value,
conditional_t<
has_signature<
typename traits_type::receive_closed_signature,
R(asio::error_code)
>::value,
asio::detail::completion_payload<R(asio::error_code)>,
asio::detail::completion_payload<
R(asio::error_code),
typename traits_type::receive_closed_signature
>
>,
conditional_t<
has_signature<
typename traits_type::receive_closed_signature,
R(asio::error_code),
typename traits_type::receive_cancelled_signature
>::value,
asio::detail::completion_payload<
R(asio::error_code),
typename traits_type::receive_cancelled_signature
>,
asio::detail::completion_payload<
R(asio::error_code),
typename traits_type::receive_cancelled_signature,
typename traits_type::receive_closed_signature
>
>
> payload_type;
// Construct with empty buffer.
implementation_type()
: size_(0)
{
first_.count_ = 0;
}
// Move from another buffer.
void buffer_move_from(implementation_type& other)
{
size_ = other.buffer_;
other.size_ = 0;
first_ = other.first_;
other.first.count_ = 0;
rest_ = static_cast<
typename traits_type::template container<buffered_value>::type&&>(
other.rest_);
other.buffer_clear();
}
// Get number of buffered elements.
std::size_t buffer_size() const
{
return size_;
}
// Push a new value to the back of the buffer.
void buffer_push(payload_type payload)
{
buffered_value& last = rest_.empty() ? first_ : rest_.back();
if (last.count_ == 0)
{
value_handler handler{last.value_};
payload.receive(handler);
last.count_ = 1;
}
else
{
asio::error_code value{last.value_};
value_handler handler{value};
payload.receive(handler);
if (last.value_ == value)
++last.count_;
else
rest_.push_back({value, 1});
}
++size_;
}
// Push new values to the back of the buffer.
std::size_t buffer_push_n(std::size_t count, payload_type payload)
{
std::size_t available = this->max_buffer_size_ - size_;
count = (count < available) ? count : available;
if (count > 0)
{
buffered_value& last = rest_.empty() ? first_ : rest_.back();
if (last.count_ == 0)
{
payload.receive(value_handler{last.value_});
last.count_ = count;
}
else
{
asio::error_code value{last.value_};
payload.receive(value_handler{value});
if (last.value_ == value)
last.count_ += count;
else
rest_.push_back({value, count});
}
size_ += count;
}
return count;
}
// Get the element at the front of the buffer.
payload_type buffer_front()
{
return payload_type({0, first_.value_});
}
// Pop a value from the front of the buffer.
void buffer_pop()
{
--size_;
if (--first_.count_ == 0 && !rest_.empty())
{
first_ = rest_.front();
rest_.pop_front();
}
}
// Clear all values from the buffer.
void buffer_clear()
{
size_ = 0;
first_.count_ == 0;
rest_.clear();
}
private:
struct buffered_value
{
asio::error_code value_;
std::size_t count_;
};
struct value_handler
{
asio::error_code& target_;
template <typename... Args>
void operator()(const asio::error_code& value, Args&&...)
{
target_ = value;
}
};
buffered_value& last_value()
{
return rest_.empty() ? first_ : rest_.back();
}
// Total number of buffered values.
std::size_t size_;
// The first buffered value is maintained as a separate data member to avoid
// allocating space in the container in the common case.
buffered_value first_;
// The rest of the buffered values.
typename traits_type::template container<buffered_value>::type rest_;
};
} // namespace detail
} // namespace experimental
} // namespace asio
#include "asio/detail/pop_options.hpp"
#include "asio/experimental/detail/impl/channel_service.hpp"
#endif // ASIO_EXPERIMENTAL_DETAIL_CHANNEL_SERVICE_HPP
|
0 | repos/asio/asio/include/asio/experimental | repos/asio/asio/include/asio/experimental/detail/coro_promise_allocator.hpp | //
// experimental/detail/coro_promise_allocator.hpp
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2021-2023 Klemens D. Morgenstern
// (klemens dot morgenstern at gmx dot net)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef ASIO_EXPERIMENTAL_DETAIL_CORO_PROMISE_ALLOCATOR_HPP
#define ASIO_EXPERIMENTAL_DETAIL_CORO_PROMISE_ALLOCATOR_HPP
#include "asio/detail/config.hpp"
#include "asio/experimental/coro_traits.hpp"
namespace asio {
namespace experimental {
namespace detail {
/// Allocate the memory and put the allocator behind the coro memory
template <typename AllocatorType>
void* allocate_coroutine(const std::size_t size, AllocatorType alloc_)
{
using alloc_type = typename std::allocator_traits<AllocatorType>::template
rebind_alloc<unsigned char>;
alloc_type alloc{alloc_};
const auto align_needed = size % alignof(alloc_type);
const auto align_offset = align_needed != 0
? alignof(alloc_type) - align_needed : 0ull;
const auto alloc_size = size + sizeof(alloc_type) + align_offset;
const auto raw =
std::allocator_traits<alloc_type>::allocate(alloc, alloc_size);
new(raw + size + align_offset) alloc_type(std::move(alloc));
return raw;
}
/// Deallocate the memory and destroy the allocator in the coro memory.
template <typename AllocatorType>
void deallocate_coroutine(void* raw_, const std::size_t size)
{
using alloc_type = typename std::allocator_traits<AllocatorType>::template
rebind_alloc<unsigned char>;
const auto raw = static_cast<unsigned char *>(raw_);
const auto align_needed = size % alignof(alloc_type);
const auto align_offset = align_needed != 0
? alignof(alloc_type) - align_needed : 0ull;
const auto alloc_size = size + sizeof(alloc_type) + align_offset;
auto alloc_p = reinterpret_cast<alloc_type *>(raw + size + align_offset);
auto alloc = std::move(*alloc_p);
alloc_p->~alloc_type();
std::allocator_traits<alloc_type>::deallocate(alloc, raw, alloc_size);
}
template <typename T>
constexpr std::size_t variadic_first(std::size_t = 0u)
{
return std::numeric_limits<std::size_t>::max();
}
template <typename T, typename First, typename... Args>
constexpr std::size_t variadic_first(std::size_t pos = 0u)
{
if constexpr (std::is_same_v<std::decay_t<First>, T>)
return pos;
else
return variadic_first<T, Args...>(pos+1);
}
template <std::size_t Idx, typename First, typename... Args>
requires (Idx <= sizeof...(Args))
constexpr decltype(auto) get_variadic(First&& first, Args&&... args)
{
if constexpr (Idx == 0u)
return static_cast<First>(first);
else
return get_variadic<Idx-1u>(static_cast<Args>(args)...);
}
template <std::size_t Idx>
constexpr decltype(auto) get_variadic();
template <typename Allocator>
struct coro_promise_allocator
{
using allocator_type = Allocator;
allocator_type get_allocator() const {return alloc_;}
template <typename... Args>
void* operator new(std::size_t size, Args & ... args)
{
return allocate_coroutine(size,
get_variadic<variadic_first<std::allocator_arg_t,
std::decay_t<Args>...>() + 1u>(args...));
}
void operator delete(void* raw, std::size_t size)
{
deallocate_coroutine<allocator_type>(raw, size);
}
template <typename... Args>
coro_promise_allocator(Args&& ... args)
: alloc_(
get_variadic<variadic_first<std::allocator_arg_t,
std::decay_t<Args>...>() + 1u>(args...))
{
}
private:
allocator_type alloc_;
};
template <>
struct coro_promise_allocator<std::allocator<void>>
{
using allocator_type = std::allocator<void>;
template <typename... Args>
coro_promise_allocator(Args&&...)
{
}
allocator_type get_allocator() const
{
return {};
}
};
} // namespace detail
} // namespace experimental
} // namespace asio
#endif // ASIO_EXPERIMENTAL_DETAIL_CORO_PROMISE_ALLOCATOR_HPP
|
0 | repos/asio/asio/include/asio/experimental | repos/asio/asio/include/asio/experimental/detail/channel_send_op.hpp | //
// experimental/detail/channel_send_op.hpp
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef ASIO_EXPERIMENTAL_DETAIL_CHANNEL_SEND_OP_HPP
#define ASIO_EXPERIMENTAL_DETAIL_CHANNEL_SEND_OP_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include "asio/detail/config.hpp"
#include "asio/detail/bind_handler.hpp"
#include "asio/detail/handler_alloc_helpers.hpp"
#include "asio/error.hpp"
#include "asio/experimental/channel_error.hpp"
#include "asio/experimental/detail/channel_operation.hpp"
#include "asio/detail/push_options.hpp"
namespace asio {
namespace experimental {
namespace detail {
template <typename Payload>
class channel_send : public channel_operation
{
public:
Payload get_payload()
{
return static_cast<Payload&&>(payload_);
}
void immediate()
{
func_(this, immediate_op, 0);
}
void post()
{
func_(this, post_op, 0);
}
void cancel()
{
func_(this, cancel_op, 0);
}
void close()
{
func_(this, close_op, 0);
}
protected:
channel_send(func_type func, Payload&& payload)
: channel_operation(func),
payload_(static_cast<Payload&&>(payload))
{
}
private:
Payload payload_;
};
template <typename Payload, typename Handler, typename IoExecutor>
class channel_send_op : public channel_send<Payload>
{
public:
ASIO_DEFINE_HANDLER_PTR(channel_send_op);
channel_send_op(Payload&& payload,
Handler& handler, const IoExecutor& io_ex)
: channel_send<Payload>(&channel_send_op::do_action,
static_cast<Payload&&>(payload)),
handler_(static_cast<Handler&&>(handler)),
work_(handler_, io_ex)
{
}
static void do_action(channel_operation* base,
channel_operation::action a, void*)
{
// Take ownership of the operation object.
channel_send_op* o(static_cast<channel_send_op*>(base));
ptr p = { asio::detail::addressof(o->handler_), o, o };
ASIO_HANDLER_COMPLETION((*o));
// Take ownership of the operation's outstanding work.
channel_operation::handler_work<Handler, IoExecutor> w(
static_cast<channel_operation::handler_work<Handler, IoExecutor>&&>(
o->work_));
asio::error_code ec;
switch (a)
{
case channel_operation::cancel_op:
ec = error::channel_cancelled;
break;
case channel_operation::close_op:
ec = error::channel_closed;
break;
default:
break;
}
// Make a copy of the handler so that the memory can be deallocated before
// the handler is posted. Even if we're not about to post the handler, a
// sub-object of the handler may be the true owner of the memory associated
// with the handler. Consequently, a local copy of the handler is required
// to ensure that any owning sub-object remains valid until after we have
// deallocated the memory here.
asio::detail::binder1<Handler, asio::error_code>
handler(o->handler_, ec);
p.h = asio::detail::addressof(handler.handler_);
p.reset();
// Post the completion if required.
if (a != channel_operation::destroy_op)
{
ASIO_HANDLER_INVOCATION_BEGIN((handler.arg1_));
if (a == channel_operation::immediate_op)
w.immediate(handler, handler.handler_, 0);
else
w.post(handler, handler.handler_);
ASIO_HANDLER_INVOCATION_END;
}
}
private:
Handler handler_;
channel_operation::handler_work<Handler, IoExecutor> work_;
};
} // namespace detail
} // namespace experimental
} // namespace asio
#include "asio/detail/pop_options.hpp"
#endif // ASIO_EXPERIMENTAL_DETAIL_CHANNEL_SEND_OP_HPP
|
0 | repos/asio/asio/include/asio/experimental | repos/asio/asio/include/asio/experimental/detail/partial_promise.hpp | //
// experimental/detail/partial_promise.hpp
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2021-2023 Klemens D. Morgenstern
// (klemens dot morgenstern at gmx dot net)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef ASIO_EXPERIMENTAL_DETAIL_PARTIAL_PROMISE_HPP
#define ASIO_EXPERIMENTAL_DETAIL_PARTIAL_PROMISE_HPP
#include "asio/detail/config.hpp"
#include "asio/append.hpp"
#include "asio/awaitable.hpp"
#include "asio/experimental/coro_traits.hpp"
#if defined(ASIO_HAS_STD_COROUTINE)
# include <coroutine>
#else // defined(ASIO_HAS_STD_COROUTINE)
# include <experimental/coroutine>
#endif // defined(ASIO_HAS_STD_COROUTINE)
namespace asio {
namespace experimental {
namespace detail {
#if defined(ASIO_HAS_STD_COROUTINE)
using std::coroutine_handle;
using std::coroutine_traits;
using std::suspend_never;
using std::suspend_always;
using std::noop_coroutine;
#else // defined(ASIO_HAS_STD_COROUTINE)
using std::experimental::coroutine_handle;
using std::experimental::coroutine_traits;
using std::experimental::suspend_never;
using std::experimental::suspend_always;
using std::experimental::noop_coroutine;
#endif // defined(ASIO_HAS_STD_COROUTINE)
struct partial_coro
{
coroutine_handle<void> handle{nullptr};
};
template <typename Allocator>
struct partial_promise_base
{
template <typename Executor, typename Token, typename... Args>
void* operator new(std::size_t size, Executor&, Token& tk, Args&...)
{
return allocate_coroutine<Allocator>(size, get_associated_allocator(tk));
}
void operator delete(void* raw, std::size_t size)
{
deallocate_coroutine<Allocator>(raw, size);
}
};
template <>
struct partial_promise_base<std::allocator<void>>
{
};
template <typename Allocator>
struct partial_promise : partial_promise_base<Allocator>
{
auto initial_suspend() noexcept
{
return asio::detail::suspend_always{};
}
auto final_suspend() noexcept
{
struct awaitable_t
{
partial_promise *p;
constexpr bool await_ready() noexcept { return true; }
auto await_suspend(asio::detail::coroutine_handle<>) noexcept
{
p->get_return_object().handle.destroy();
}
constexpr void await_resume() noexcept {}
};
return awaitable_t{this};
}
void return_void() {}
partial_coro get_return_object()
{
return partial_coro{coroutine_handle<partial_promise>::from_promise(*this)};
}
void unhandled_exception()
{
assert(false);
}
};
} // namespace detail
} // namespace experimental
} // namespace asio
#if defined(ASIO_HAS_STD_COROUTINE)
namespace std {
template <typename Executor, typename Completion, typename... Args>
struct coroutine_traits<
asio::experimental::detail::partial_coro,
Executor, Completion, Args...>
{
using promise_type =
asio::experimental::detail::partial_promise<
asio::associated_allocator_t<Completion>>;
};
} // namespace std
#else // defined(ASIO_HAS_STD_COROUTINE)
namespace std { namespace experimental {
template <typename Executor, typename Completion, typename... Args>
struct coroutine_traits<
asio::experimental::detail::partial_coro,
Executor, Completion, Args...>
{
using promise_type =
asio::experimental::detail::partial_promise<
asio::associated_allocator_t<Completion>>;
};
}} // namespace std::experimental
#endif // defined(ASIO_HAS_STD_COROUTINE)
namespace asio {
namespace experimental {
namespace detail {
template <execution::executor Executor,
typename CompletionToken, typename... Args>
partial_coro post_coroutine(Executor exec,
CompletionToken token, Args&&... args) noexcept
{
post(exec, asio::append(std::move(token), std::move(args)...));
co_return;
}
template <detail::execution_context Context,
typename CompletionToken, typename... Args>
partial_coro post_coroutine(Context& ctx,
CompletionToken token, Args&&... args) noexcept
{
post(ctx, asio::append(std::move(token), std::move(args)...));
co_return;
}
template <execution::executor Executor,
typename CompletionToken, typename... Args>
partial_coro dispatch_coroutine(Executor exec,
CompletionToken token, Args&&... args) noexcept
{
dispatch(exec, asio::append(std::move(token), std::move(args)...));
co_return;
}
template <detail::execution_context Context,
typename CompletionToken, typename... Args>
partial_coro dispatch_coroutine(Context& ctx,
CompletionToken token, Args &&... args) noexcept
{
dispatch(ctx, asio::append(std::move(token), std::move(args)...));
co_return;
}
} // namespace detail
} // namespace experimental
} // namespace asio
#endif // ASIO_EXPERIMENTAL_DETAIL_PARTIAL_PROMISE_HPP
|
0 | repos/asio/asio/include/asio/experimental | repos/asio/asio/include/asio/experimental/detail/channel_send_functions.hpp | //
// experimental/detail/channel_send_functions.hpp
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef ASIO_EXPERIMENTAL_DETAIL_CHANNEL_SEND_FUNCTIONS_HPP
#define ASIO_EXPERIMENTAL_DETAIL_CHANNEL_SEND_FUNCTIONS_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include "asio/detail/config.hpp"
#include "asio/async_result.hpp"
#include "asio/detail/completion_message.hpp"
#include "asio/detail/type_traits.hpp"
#include "asio/error_code.hpp"
#include "asio/detail/push_options.hpp"
namespace asio {
namespace experimental {
namespace detail {
template <typename Derived, typename Executor, typename... Signatures>
class channel_send_functions;
template <typename Derived, typename Executor, typename R, typename... Args>
class channel_send_functions<Derived, Executor, R(Args...)>
{
public:
template <typename... Args2>
enable_if_t<
is_constructible<asio::detail::completion_message<R(Args...)>,
int, Args2...>::value,
bool
> try_send(Args2&&... args)
{
typedef asio::detail::completion_message<R(Args...)> message_type;
Derived* self = static_cast<Derived*>(this);
return self->service_->template try_send<message_type>(
self->impl_, false, static_cast<Args2&&>(args)...);
}
template <typename... Args2>
enable_if_t<
is_constructible<asio::detail::completion_message<R(Args...)>,
int, Args2...>::value,
bool
> try_send_via_dispatch(Args2&&... args)
{
typedef asio::detail::completion_message<R(Args...)> message_type;
Derived* self = static_cast<Derived*>(this);
return self->service_->template try_send<message_type>(
self->impl_, true, static_cast<Args2&&>(args)...);
}
template <typename... Args2>
enable_if_t<
is_constructible<asio::detail::completion_message<R(Args...)>,
int, Args2...>::value,
std::size_t
> try_send_n(std::size_t count, Args2&&... args)
{
typedef asio::detail::completion_message<R(Args...)> message_type;
Derived* self = static_cast<Derived*>(this);
return self->service_->template try_send_n<message_type>(
self->impl_, count, false, static_cast<Args2&&>(args)...);
}
template <typename... Args2>
enable_if_t<
is_constructible<asio::detail::completion_message<R(Args...)>,
int, Args2...>::value,
std::size_t
> try_send_n_via_dispatch(std::size_t count, Args2&&... args)
{
typedef asio::detail::completion_message<R(Args...)> message_type;
Derived* self = static_cast<Derived*>(this);
return self->service_->template try_send_n<message_type>(
self->impl_, count, true, static_cast<Args2&&>(args)...);
}
template <
ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code))
CompletionToken ASIO_DEFAULT_COMPLETION_TOKEN_TYPE(Executor)>
auto async_send(Args... args,
CompletionToken&& token
ASIO_DEFAULT_COMPLETION_TOKEN(Executor))
-> decltype(
async_initiate<CompletionToken, void (asio::error_code)>(
declval<typename conditional_t<false, CompletionToken,
Derived>::initiate_async_send>(), token,
declval<typename conditional_t<false, CompletionToken,
Derived>::payload_type>()))
{
typedef typename Derived::payload_type payload_type;
typedef asio::detail::completion_message<R(Args...)> message_type;
Derived* self = static_cast<Derived*>(this);
return async_initiate<CompletionToken, void (asio::error_code)>(
typename Derived::initiate_async_send(self), token,
payload_type(message_type(0, static_cast<Args&&>(args)...)));
}
};
template <typename Derived, typename Executor,
typename R, typename... Args, typename... Signatures>
class channel_send_functions<Derived, Executor, R(Args...), Signatures...> :
public channel_send_functions<Derived, Executor, Signatures...>
{
public:
using channel_send_functions<Derived, Executor, Signatures...>::try_send;
using channel_send_functions<Derived, Executor, Signatures...>::async_send;
template <typename... Args2>
enable_if_t<
is_constructible<asio::detail::completion_message<R(Args...)>,
int, Args2...>::value,
bool
> try_send(Args2&&... args)
{
typedef asio::detail::completion_message<R(Args...)> message_type;
Derived* self = static_cast<Derived*>(this);
return self->service_->template try_send<message_type>(
self->impl_, false, static_cast<Args2&&>(args)...);
}
template <typename... Args2>
enable_if_t<
is_constructible<asio::detail::completion_message<R(Args...)>,
int, Args2...>::value,
bool
> try_send_via_dispatch(Args2&&... args)
{
typedef asio::detail::completion_message<R(Args...)> message_type;
Derived* self = static_cast<Derived*>(this);
return self->service_->template try_send<message_type>(
self->impl_, true, static_cast<Args2&&>(args)...);
}
template <typename... Args2>
enable_if_t<
is_constructible<asio::detail::completion_message<R(Args...)>,
int, Args2...>::value,
std::size_t
> try_send_n(std::size_t count, Args2&&... args)
{
typedef asio::detail::completion_message<R(Args...)> message_type;
Derived* self = static_cast<Derived*>(this);
return self->service_->template try_send_n<message_type>(
self->impl_, count, false, static_cast<Args2&&>(args)...);
}
template <typename... Args2>
enable_if_t<
is_constructible<asio::detail::completion_message<R(Args...)>,
int, Args2...>::value,
std::size_t
> try_send_n_via_dispatch(std::size_t count, Args2&&... args)
{
typedef asio::detail::completion_message<R(Args...)> message_type;
Derived* self = static_cast<Derived*>(this);
return self->service_->template try_send_n<message_type>(
self->impl_, count, true, static_cast<Args2&&>(args)...);
}
template <
ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code))
CompletionToken ASIO_DEFAULT_COMPLETION_TOKEN_TYPE(Executor)>
auto async_send(Args... args,
CompletionToken&& token
ASIO_DEFAULT_COMPLETION_TOKEN(Executor))
-> decltype(
async_initiate<CompletionToken, void (asio::error_code)>(
declval<typename conditional_t<false, CompletionToken,
Derived>::initiate_async_send>(), token,
declval<typename conditional_t<false, CompletionToken,
Derived>::payload_type>()))
{
typedef typename Derived::payload_type payload_type;
typedef asio::detail::completion_message<R(Args...)> message_type;
Derived* self = static_cast<Derived*>(this);
return async_initiate<CompletionToken, void (asio::error_code)>(
typename Derived::initiate_async_send(self), token,
payload_type(message_type(0, static_cast<Args&&>(args)...)));
}
};
} // namespace detail
} // namespace experimental
} // namespace asio
#include "asio/detail/pop_options.hpp"
#endif // ASIO_EXPERIMENTAL_DETAIL_CHANNEL_SEND_FUNCTIONS_HPP
|
0 | repos/asio/asio/include/asio/experimental | repos/asio/asio/include/asio/experimental/detail/has_signature.hpp | //
// experimental/detail/has_signature.hpp
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef ASIO_EXPERIMENTAL_DETAIL_HAS_SIGNATURE_HPP
#define ASIO_EXPERIMENTAL_DETAIL_HAS_SIGNATURE_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include "asio/detail/config.hpp"
#include "asio/detail/type_traits.hpp"
#include "asio/detail/push_options.hpp"
namespace asio {
namespace experimental {
namespace detail {
template <typename S, typename... Signatures>
struct has_signature;
template <typename S, typename... Signatures>
struct has_signature;
template <typename S>
struct has_signature<S> : false_type
{
};
template <typename S, typename... Signatures>
struct has_signature<S, S, Signatures...> : true_type
{
};
template <typename S, typename Head, typename... Tail>
struct has_signature<S, Head, Tail...> : has_signature<S, Tail...>
{
};
} // namespace detail
} // namespace experimental
} // namespace asio
#include "asio/detail/pop_options.hpp"
#endif // ASIO_EXPERIMENTAL_DETAIL_HAS_SIGNATURE_HPP
|
0 | repos/asio/asio/include/asio/experimental | repos/asio/asio/include/asio/experimental/detail/coro_completion_handler.hpp | //
// experimental/detail/coro_completion_handler.hpp
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2021-2023 Klemens D. Morgenstern
// (klemens dot morgenstern at gmx dot net)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef ASIO_EXPERIMENTAL_DETAIL_CORO_COMPLETION_HANDLER_HPP
#define ASIO_EXPERIMENTAL_DETAIL_CORO_COMPLETION_HANDLER_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include "asio/detail/config.hpp"
#include "asio/deferred.hpp"
#include "asio/experimental/coro.hpp"
#include "asio/detail/push_options.hpp"
namespace asio {
namespace experimental {
namespace detail {
template <typename Promise, typename... Args>
struct coro_completion_handler
{
coro_completion_handler(coroutine_handle<Promise> h,
std::optional<std::tuple<Args...>>& result)
: self(h),
result(result)
{
}
coro_completion_handler(coro_completion_handler&&) = default;
coroutine_handle<Promise> self;
std::optional<std::tuple<Args...>>& result;
using promise_type = Promise;
void operator()(Args... args)
{
result.emplace(std::move(args)...);
self.resume();
}
using allocator_type = typename promise_type::allocator_type;
allocator_type get_allocator() const noexcept
{
return self.promise().get_allocator();
}
using executor_type = typename promise_type::executor_type;
executor_type get_executor() const noexcept
{
return self.promise().get_executor();
}
using cancellation_slot_type = typename promise_type::cancellation_slot_type;
cancellation_slot_type get_cancellation_slot() const noexcept
{
return self.promise().get_cancellation_slot();
}
};
template <typename Signature>
struct coro_completion_handler_type;
template <typename... Args>
struct coro_completion_handler_type<void(Args...)>
{
using type = std::tuple<Args...>;
template <typename Promise>
using completion_handler = coro_completion_handler<Promise, Args...>;
};
template <typename Signature>
using coro_completion_handler_type_t =
typename coro_completion_handler_type<Signature>::type;
inline void coro_interpret_result(std::tuple<>&&)
{
}
template <typename... Args>
inline auto coro_interpret_result(std::tuple<Args...>&& args)
{
return std::move(args);
}
template <typename... Args>
auto coro_interpret_result(std::tuple<std::exception_ptr, Args...>&& args)
{
if (std::get<0>(args))
std::rethrow_exception(std::get<0>(args));
return std::apply(
[](auto, auto&&... rest)
{
return std::make_tuple(std::move(rest)...);
}, std::move(args));
}
template <typename... Args>
auto coro_interpret_result(
std::tuple<asio::error_code, Args...>&& args)
{
if (std::get<0>(args))
asio::detail::throw_exception(
asio::system_error(std::get<0>(args)));
return std::apply(
[](auto, auto&&... rest)
{
return std::make_tuple(std::move(rest)...);
}, std::move(args));
}
template <typename Arg>
inline auto coro_interpret_result(std::tuple<Arg>&& args)
{
return std::get<0>(std::move(args));
}
template <typename Arg>
auto coro_interpret_result(std::tuple<std::exception_ptr, Arg>&& args)
{
if (std::get<0>(args))
std::rethrow_exception(std::get<0>(args));
return std::get<1>(std::move(args));
}
inline auto coro_interpret_result(
std::tuple<asio::error_code>&& args)
{
if (std::get<0>(args))
asio::detail::throw_exception(
asio::system_error(std::get<0>(args)));
}
inline auto coro_interpret_result(std::tuple<std::exception_ptr>&& args)
{
if (std::get<0>(args))
std::rethrow_exception(std::get<0>(args));
}
template <typename Arg>
auto coro_interpret_result(std::tuple<asio::error_code, Arg>&& args)
{
if (std::get<0>(args))
asio::detail::throw_exception(
asio::system_error(std::get<0>(args)));
return std::get<1>(std::move(args));
}
} // namespace detail
} // namespace experimental
} // namespace asio
#include "asio/detail/pop_options.hpp"
#endif // ASIO_EXPERIMENTAL_DETAIL_CORO_COMPLETION_HANDLER_HPP
|
0 | repos/asio/asio/include/asio/experimental/detail | repos/asio/asio/include/asio/experimental/detail/impl/channel_service.hpp | //
// experimental/detail/impl/channel_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 ASIO_EXPERIMENTAL_DETAIL_IMPL_CHANNEL_SERVICE_HPP
#define ASIO_EXPERIMENTAL_DETAIL_IMPL_CHANNEL_SERVICE_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include "asio/detail/push_options.hpp"
namespace asio {
namespace experimental {
namespace detail {
template <typename Mutex>
inline channel_service<Mutex>::channel_service(
asio::execution_context& ctx)
: asio::detail::execution_context_service_base<channel_service>(ctx),
mutex_(),
impl_list_(0)
{
}
template <typename Mutex>
inline void channel_service<Mutex>::shutdown()
{
// Abandon all pending operations.
asio::detail::op_queue<channel_operation> ops;
asio::detail::mutex::scoped_lock lock(mutex_);
base_implementation_type* impl = impl_list_;
while (impl)
{
ops.push(impl->waiters_);
impl = impl->next_;
}
}
template <typename Mutex>
inline void channel_service<Mutex>::construct(
channel_service<Mutex>::base_implementation_type& impl,
std::size_t max_buffer_size)
{
impl.max_buffer_size_ = max_buffer_size;
impl.receive_state_ = block;
impl.send_state_ = max_buffer_size ? buffer : block;
// Insert implementation into linked list of all implementations.
asio::detail::mutex::scoped_lock lock(mutex_);
impl.next_ = impl_list_;
impl.prev_ = 0;
if (impl_list_)
impl_list_->prev_ = &impl;
impl_list_ = &impl;
}
template <typename Mutex>
template <typename Traits, typename... Signatures>
void channel_service<Mutex>::destroy(
channel_service<Mutex>::implementation_type<Traits, Signatures...>& impl)
{
cancel(impl);
base_destroy(impl);
}
template <typename Mutex>
template <typename Traits, typename... Signatures>
void channel_service<Mutex>::move_construct(
channel_service<Mutex>::implementation_type<Traits, Signatures...>& impl,
channel_service<Mutex>::implementation_type<
Traits, Signatures...>& other_impl)
{
impl.max_buffer_size_ = other_impl.max_buffer_size_;
impl.receive_state_ = other_impl.receive_state_;
other_impl.receive_state_ = block;
impl.send_state_ = other_impl.send_state_;
other_impl.send_state_ = other_impl.max_buffer_size_ ? buffer : block;
impl.buffer_move_from(other_impl);
// Insert implementation into linked list of all implementations.
asio::detail::mutex::scoped_lock lock(mutex_);
impl.next_ = impl_list_;
impl.prev_ = 0;
if (impl_list_)
impl_list_->prev_ = &impl;
impl_list_ = &impl;
}
template <typename Mutex>
template <typename Traits, typename... Signatures>
void channel_service<Mutex>::move_assign(
channel_service<Mutex>::implementation_type<Traits, Signatures...>& impl,
channel_service& other_service,
channel_service<Mutex>::implementation_type<
Traits, Signatures...>& other_impl)
{
cancel(impl);
if (this != &other_service)
{
// Remove implementation from linked list of all implementations.
asio::detail::mutex::scoped_lock lock(mutex_);
if (impl_list_ == &impl)
impl_list_ = impl.next_;
if (impl.prev_)
impl.prev_->next_ = impl.next_;
if (impl.next_)
impl.next_->prev_= impl.prev_;
impl.next_ = 0;
impl.prev_ = 0;
}
impl.max_buffer_size_ = other_impl.max_buffer_size_;
impl.receive_state_ = other_impl.receive_state_;
other_impl.receive_state_ = block;
impl.send_state_ = other_impl.send_state_;
other_impl.send_state_ = other_impl.max_buffer_size_ ? buffer : block;
impl.buffer_move_from(other_impl);
if (this != &other_service)
{
// Insert implementation into linked list of all implementations.
asio::detail::mutex::scoped_lock lock(other_service.mutex_);
impl.next_ = other_service.impl_list_;
impl.prev_ = 0;
if (other_service.impl_list_)
other_service.impl_list_->prev_ = &impl;
other_service.impl_list_ = &impl;
}
}
template <typename Mutex>
inline void channel_service<Mutex>::base_destroy(
channel_service<Mutex>::base_implementation_type& impl)
{
// Remove implementation from linked list of all implementations.
asio::detail::mutex::scoped_lock lock(mutex_);
if (impl_list_ == &impl)
impl_list_ = impl.next_;
if (impl.prev_)
impl.prev_->next_ = impl.next_;
if (impl.next_)
impl.next_->prev_= impl.prev_;
impl.next_ = 0;
impl.prev_ = 0;
}
template <typename Mutex>
inline std::size_t channel_service<Mutex>::capacity(
const channel_service<Mutex>::base_implementation_type& impl)
const noexcept
{
typename Mutex::scoped_lock lock(impl.mutex_);
return impl.max_buffer_size_;
}
template <typename Mutex>
inline bool channel_service<Mutex>::is_open(
const channel_service<Mutex>::base_implementation_type& impl)
const noexcept
{
typename Mutex::scoped_lock lock(impl.mutex_);
return impl.send_state_ != closed;
}
template <typename Mutex>
template <typename Traits, typename... Signatures>
void channel_service<Mutex>::reset(
channel_service<Mutex>::implementation_type<Traits, Signatures...>& impl)
{
cancel(impl);
typename Mutex::scoped_lock lock(impl.mutex_);
impl.receive_state_ = block;
impl.send_state_ = impl.max_buffer_size_ ? buffer : block;
impl.buffer_clear();
}
template <typename Mutex>
template <typename Traits, typename... Signatures>
void channel_service<Mutex>::close(
channel_service<Mutex>::implementation_type<Traits, Signatures...>& impl)
{
typedef typename implementation_type<Traits,
Signatures...>::traits_type traits_type;
typedef typename implementation_type<Traits,
Signatures...>::payload_type payload_type;
typename Mutex::scoped_lock lock(impl.mutex_);
if (impl.receive_state_ == block)
{
while (channel_operation* op = impl.waiters_.front())
{
impl.waiters_.pop();
traits_type::invoke_receive_closed(
post_receive<payload_type,
typename traits_type::receive_closed_signature>(
static_cast<channel_receive<payload_type>*>(op)));
}
}
impl.send_state_ = closed;
if (impl.receive_state_ != buffer)
impl.receive_state_ = closed;
}
template <typename Mutex>
template <typename Traits, typename... Signatures>
void channel_service<Mutex>::cancel(
channel_service<Mutex>::implementation_type<Traits, Signatures...>& impl)
{
typedef typename implementation_type<Traits,
Signatures...>::traits_type traits_type;
typedef typename implementation_type<Traits,
Signatures...>::payload_type payload_type;
typename Mutex::scoped_lock lock(impl.mutex_);
while (channel_operation* op = impl.waiters_.front())
{
if (impl.send_state_ == block)
{
impl.waiters_.pop();
static_cast<channel_send<payload_type>*>(op)->cancel();
}
else
{
impl.waiters_.pop();
traits_type::invoke_receive_cancelled(
post_receive<payload_type,
typename traits_type::receive_cancelled_signature>(
static_cast<channel_receive<payload_type>*>(op)));
}
}
if (impl.receive_state_ == waiter)
impl.receive_state_ = block;
if (impl.send_state_ == waiter)
impl.send_state_ = impl.max_buffer_size_ ? buffer : block;
}
template <typename Mutex>
template <typename Traits, typename... Signatures>
void channel_service<Mutex>::cancel_by_key(
channel_service<Mutex>::implementation_type<Traits, Signatures...>& impl,
void* cancellation_key)
{
typedef typename implementation_type<Traits,
Signatures...>::traits_type traits_type;
typedef typename implementation_type<Traits,
Signatures...>::payload_type payload_type;
typename Mutex::scoped_lock lock(impl.mutex_);
asio::detail::op_queue<channel_operation> other_ops;
while (channel_operation* op = impl.waiters_.front())
{
if (op->cancellation_key_ == cancellation_key)
{
if (impl.send_state_ == block)
{
impl.waiters_.pop();
static_cast<channel_send<payload_type>*>(op)->cancel();
}
else
{
impl.waiters_.pop();
traits_type::invoke_receive_cancelled(
post_receive<payload_type,
typename traits_type::receive_cancelled_signature>(
static_cast<channel_receive<payload_type>*>(op)));
}
}
else
{
impl.waiters_.pop();
other_ops.push(op);
}
}
impl.waiters_.push(other_ops);
if (impl.waiters_.empty())
{
if (impl.receive_state_ == waiter)
impl.receive_state_ = block;
if (impl.send_state_ == waiter)
impl.send_state_ = impl.max_buffer_size_ ? buffer : block;
}
}
template <typename Mutex>
inline bool channel_service<Mutex>::ready(
const channel_service<Mutex>::base_implementation_type& impl)
const noexcept
{
typename Mutex::scoped_lock lock(impl.mutex_);
return impl.receive_state_ != block;
}
template <typename Mutex>
template <typename Message, typename Traits,
typename... Signatures, typename... Args>
bool channel_service<Mutex>::try_send(
channel_service<Mutex>::implementation_type<Traits, Signatures...>& impl,
bool via_dispatch, Args&&... args)
{
typedef typename implementation_type<Traits,
Signatures...>::payload_type payload_type;
typename Mutex::scoped_lock lock(impl.mutex_);
switch (impl.send_state_)
{
case block:
{
return false;
}
case buffer:
{
impl.buffer_push(Message(0, static_cast<Args&&>(args)...));
impl.receive_state_ = buffer;
if (impl.buffer_size() == impl.max_buffer_size_)
impl.send_state_ = block;
return true;
}
case waiter:
{
payload_type payload(Message(0, static_cast<Args&&>(args)...));
channel_receive<payload_type>* receive_op =
static_cast<channel_receive<payload_type>*>(impl.waiters_.front());
impl.waiters_.pop();
if (impl.waiters_.empty())
impl.send_state_ = impl.max_buffer_size_ ? buffer : block;
lock.unlock();
if (via_dispatch)
receive_op->dispatch(static_cast<payload_type&&>(payload));
else
receive_op->post(static_cast<payload_type&&>(payload));
return true;
}
case closed:
default:
{
return false;
}
}
}
template <typename Mutex>
template <typename Message, typename Traits,
typename... Signatures, typename... Args>
std::size_t channel_service<Mutex>::try_send_n(
channel_service<Mutex>::implementation_type<Traits, Signatures...>& impl,
std::size_t count, bool via_dispatch, Args&&... args)
{
typedef typename implementation_type<Traits,
Signatures...>::payload_type payload_type;
typename Mutex::scoped_lock lock(impl.mutex_);
if (count == 0)
return 0;
switch (impl.send_state_)
{
case block:
return 0;
case buffer:
case waiter:
break;
case closed:
default:
return 0;
}
payload_type payload(Message(0, static_cast<Args&&>(args)...));
for (std::size_t i = 0; i < count; ++i)
{
switch (impl.send_state_)
{
case block:
{
return i;
}
case buffer:
{
i += impl.buffer_push_n(count - i,
static_cast<payload_type&&>(payload));
impl.receive_state_ = buffer;
if (impl.buffer_size() == impl.max_buffer_size_)
impl.send_state_ = block;
return i;
}
case waiter:
{
channel_receive<payload_type>* receive_op =
static_cast<channel_receive<payload_type>*>(impl.waiters_.front());
impl.waiters_.pop();
if (impl.waiters_.empty())
impl.send_state_ = impl.max_buffer_size_ ? buffer : block;
lock.unlock();
if (via_dispatch)
receive_op->dispatch(payload);
else
receive_op->post(payload);
break;
}
case closed:
default:
{
return i;
}
}
}
return count;
}
template <typename Mutex>
template <typename Traits, typename... Signatures>
void channel_service<Mutex>::start_send_op(
channel_service<Mutex>::implementation_type<Traits, Signatures...>& impl,
channel_send<typename implementation_type<
Traits, Signatures...>::payload_type>* send_op)
{
typedef typename implementation_type<Traits,
Signatures...>::payload_type payload_type;
typename Mutex::scoped_lock lock(impl.mutex_);
switch (impl.send_state_)
{
case block:
{
impl.waiters_.push(send_op);
if (impl.receive_state_ == block)
impl.receive_state_ = waiter;
return;
}
case buffer:
{
impl.buffer_push(send_op->get_payload());
impl.receive_state_ = buffer;
if (impl.buffer_size() == impl.max_buffer_size_)
impl.send_state_ = block;
send_op->immediate();
break;
}
case waiter:
{
channel_receive<payload_type>* receive_op =
static_cast<channel_receive<payload_type>*>(impl.waiters_.front());
impl.waiters_.pop();
if (impl.waiters_.empty())
impl.send_state_ = impl.max_buffer_size_ ? buffer : block;
receive_op->post(send_op->get_payload());
send_op->immediate();
break;
}
case closed:
default:
{
send_op->close();
break;
}
}
}
template <typename Mutex>
template <typename Traits, typename... Signatures, typename Handler>
bool channel_service<Mutex>::try_receive(
channel_service<Mutex>::implementation_type<Traits, Signatures...>& impl,
Handler&& handler)
{
typedef typename implementation_type<Traits,
Signatures...>::payload_type payload_type;
typename Mutex::scoped_lock lock(impl.mutex_);
switch (impl.receive_state_)
{
case block:
{
return false;
}
case buffer:
{
payload_type payload(impl.buffer_front());
if (channel_send<payload_type>* send_op =
static_cast<channel_send<payload_type>*>(impl.waiters_.front()))
{
impl.buffer_pop();
impl.buffer_push(send_op->get_payload());
impl.waiters_.pop();
send_op->post();
}
else
{
impl.buffer_pop();
if (impl.buffer_size() == 0)
impl.receive_state_ = (impl.send_state_ == closed) ? closed : block;
impl.send_state_ = (impl.send_state_ == closed) ? closed : buffer;
}
lock.unlock();
asio::detail::non_const_lvalue<Handler> handler2(handler);
asio::detail::completion_payload_handler<
payload_type, decay_t<Handler>>(
static_cast<payload_type&&>(payload), handler2.value)();
return true;
}
case waiter:
{
channel_send<payload_type>* send_op =
static_cast<channel_send<payload_type>*>(impl.waiters_.front());
payload_type payload = send_op->get_payload();
impl.waiters_.pop();
if (impl.waiters_.front() == 0)
impl.receive_state_ = (impl.send_state_ == closed) ? closed : block;
send_op->post();
lock.unlock();
asio::detail::non_const_lvalue<Handler> handler2(handler);
asio::detail::completion_payload_handler<
payload_type, decay_t<Handler>>(
static_cast<payload_type&&>(payload), handler2.value)();
return true;
}
case closed:
default:
{
return false;
}
}
}
template <typename Mutex>
template <typename Traits, typename... Signatures>
void channel_service<Mutex>::start_receive_op(
channel_service<Mutex>::implementation_type<Traits, Signatures...>& impl,
channel_receive<typename implementation_type<
Traits, Signatures...>::payload_type>* receive_op)
{
typedef typename implementation_type<Traits,
Signatures...>::traits_type traits_type;
typedef typename implementation_type<Traits,
Signatures...>::payload_type payload_type;
typename Mutex::scoped_lock lock(impl.mutex_);
switch (impl.receive_state_)
{
case block:
{
impl.waiters_.push(receive_op);
if (impl.send_state_ != closed)
impl.send_state_ = waiter;
return;
}
case buffer:
{
payload_type payload(
static_cast<payload_type&&>(impl.buffer_front()));
if (channel_send<payload_type>* send_op =
static_cast<channel_send<payload_type>*>(impl.waiters_.front()))
{
impl.buffer_pop();
impl.buffer_push(send_op->get_payload());
impl.waiters_.pop();
send_op->post();
}
else
{
impl.buffer_pop();
if (impl.buffer_size() == 0)
impl.receive_state_ = (impl.send_state_ == closed) ? closed : block;
impl.send_state_ = (impl.send_state_ == closed) ? closed : buffer;
}
receive_op->immediate(static_cast<payload_type&&>(payload));
break;
}
case waiter:
{
channel_send<payload_type>* send_op =
static_cast<channel_send<payload_type>*>(impl.waiters_.front());
payload_type payload = send_op->get_payload();
impl.waiters_.pop();
if (impl.waiters_.front() == 0)
impl.receive_state_ = (impl.send_state_ == closed) ? closed : block;
send_op->post();
receive_op->immediate(static_cast<payload_type&&>(payload));
break;
}
case closed:
default:
{
traits_type::invoke_receive_closed(
post_receive<payload_type,
typename traits_type::receive_closed_signature>(receive_op));
break;
}
}
}
} // namespace detail
} // namespace experimental
} // namespace asio
#include "asio/detail/pop_options.hpp"
#endif // ASIO_EXPERIMENTAL_DETAIL_IMPL_CHANNEL_SERVICE_HPP
|
0 | repos/asio/asio/include/asio/experimental | repos/asio/asio/include/asio/experimental/impl/promise.hpp | //
// experimental/impl/promise.hpp
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2021-2023 Klemens D. Morgenstern
// (klemens dot morgenstern at gmx dot net)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef ASIO_EXPERIMENTAL_IMPL_PROMISE_HPP
#define ASIO_EXPERIMENTAL_IMPL_PROMISE_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include "asio/detail/config.hpp"
#include "asio/cancellation_signal.hpp"
#include "asio/detail/utility.hpp"
#include "asio/error.hpp"
#include "asio/system_error.hpp"
#include <tuple>
#include "asio/detail/push_options.hpp"
namespace asio {
namespace experimental {
template<typename Signature = void(),
typename Executor = asio::any_io_executor,
typename Allocator = std::allocator<void>>
struct promise;
namespace detail {
template<typename Signature, typename Executor, typename Allocator>
struct promise_impl;
template<typename... Ts, typename Executor, typename Allocator>
struct promise_impl<void(Ts...), Executor, Allocator>
{
using result_type = std::tuple<Ts...>;
promise_impl(Allocator allocator, Executor executor)
: allocator(std::move(allocator)), executor(std::move(executor))
{
}
promise_impl(const promise_impl&) = delete;
~promise_impl()
{
if (completion)
this->cancel_();
if (done)
reinterpret_cast<result_type*>(&result)->~result_type();
}
aligned_storage_t<sizeof(result_type), alignof(result_type)> result;
std::atomic<bool> done{false};
cancellation_signal cancel;
Allocator allocator;
Executor executor;
template<typename Func, std::size_t... Idx>
void apply_impl(Func f, asio::detail::index_sequence<Idx...>)
{
auto& result_type = *reinterpret_cast<promise_impl::result_type*>(&result);
f(std::get<Idx>(std::move(result_type))...);
}
using allocator_type = Allocator;
allocator_type get_allocator() {return allocator;}
using executor_type = Executor;
executor_type get_executor() {return executor;}
template<typename Func>
void apply(Func f)
{
apply_impl(std::forward<Func>(f),
asio::detail::make_index_sequence<sizeof...(Ts)>{});
}
struct completion_base
{
virtual void invoke(Ts&&...ts) = 0;
};
template<typename Alloc, typename WaitHandler_>
struct completion_impl final : completion_base
{
WaitHandler_ handler;
Alloc allocator;
void invoke(Ts&&... ts)
{
auto h = std::move(handler);
using alloc_t = typename std::allocator_traits<
typename asio::decay<Alloc>::type>::template
rebind_alloc<completion_impl>;
alloc_t alloc_{allocator};
this->~completion_impl();
std::allocator_traits<alloc_t>::deallocate(alloc_, this, 1u);
std::move(h)(std::forward<Ts>(ts)...);
}
template<typename Alloc_, typename Handler_>
completion_impl(Alloc_&& alloc, Handler_&& wh)
: handler(std::forward<Handler_>(wh)),
allocator(std::forward<Alloc_>(alloc))
{
}
};
completion_base* completion = nullptr;
typename asio::aligned_storage<sizeof(void*) * 4,
alignof(completion_base)>::type completion_opt;
template<typename Alloc, typename Handler>
void set_completion(Alloc&& alloc, Handler&& handler)
{
if (completion)
cancel_();
using impl_t = completion_impl<
typename asio::decay<Alloc>::type, Handler>;
using alloc_t = typename std::allocator_traits<
typename asio::decay<Alloc>::type>::template rebind_alloc<impl_t>;
alloc_t alloc_{alloc};
auto p = std::allocator_traits<alloc_t>::allocate(alloc_, 1u);
completion = new (p) impl_t(std::forward<Alloc>(alloc),
std::forward<Handler>(handler));
}
template<typename... T_>
void complete(T_&&... ts)
{
assert(completion);
std::exchange(completion, nullptr)->invoke(std::forward<T_>(ts)...);
}
template<std::size_t... Idx>
void complete_with_result_impl(asio::detail::index_sequence<Idx...>)
{
auto& result_type = *reinterpret_cast<promise_impl::result_type*>(&result);
this->complete(std::get<Idx>(std::move(result_type))...);
}
void complete_with_result()
{
complete_with_result_impl(
asio::detail::make_index_sequence<sizeof...(Ts)>{});
}
template<typename... T_>
void cancel_impl_(std::exception_ptr*, T_*...)
{
complete(
std::make_exception_ptr(
asio::system_error(
asio::error::operation_aborted)),
T_{}...);
}
template<typename... T_>
void cancel_impl_(asio::error_code*, T_*...)
{
complete(asio::error::operation_aborted, T_{}...);
}
template<typename... T_>
void cancel_impl_(T_*...)
{
complete(T_{}...);
}
void cancel_()
{
cancel_impl_(static_cast<Ts*>(nullptr)...);
}
};
template<typename Signature = void(),
typename Executor = asio::any_io_executor,
typename Allocator = any_io_executor>
struct promise_handler;
template<typename... Ts, typename Executor, typename Allocator>
struct promise_handler<void(Ts...), Executor, Allocator>
{
using promise_type = promise<void(Ts...), Executor, Allocator>;
promise_handler(
Allocator allocator, Executor executor) // get_associated_allocator(exec)
: impl_(
std::allocate_shared<promise_impl<void(Ts...), Executor, Allocator>>(
allocator, allocator, executor))
{
}
std::shared_ptr<promise_impl<void(Ts...), Executor, Allocator>> impl_;
using cancellation_slot_type = cancellation_slot;
cancellation_slot_type get_cancellation_slot() const noexcept
{
return impl_->cancel.slot();
}
using allocator_type = Allocator;
allocator_type get_allocator() const noexcept
{
return impl_->get_allocator();
}
using executor_type = Executor;
Executor get_executor() const noexcept
{
return impl_->get_executor();
}
auto make_promise() -> promise<void(Ts...), executor_type, allocator_type>
{
return promise<void(Ts...), executor_type, allocator_type>{impl_};
}
void operator()(std::remove_reference_t<Ts>... ts)
{
assert(impl_);
using result_type = typename promise_impl<
void(Ts...), allocator_type, executor_type>::result_type ;
new (&impl_->result) result_type(std::move(ts)...);
impl_->done = true;
if (impl_->completion)
impl_->complete_with_result();
}
};
} // namespace detail
} // namespace experimental
} // namespace asio
#include "asio/detail/pop_options.hpp"
#endif // ASIO_EXPERIMENTAL_IMPL_PROMISE_HPP
|
0 | repos/asio/asio/include/asio/experimental | repos/asio/asio/include/asio/experimental/impl/use_coro.hpp | //
// experimental/impl/use_coro.hpp
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2021-2023 Klemens D. Morgenstern
// (klemens dot morgenstern at gmx dot net)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef ASIO_EXPERIMENTAL_IMPL_USE_CORO_HPP
#define ASIO_EXPERIMENTAL_IMPL_USE_CORO_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include "asio/deferred.hpp"
#include "asio/experimental/coro.hpp"
#include "asio/detail/push_options.hpp"
namespace asio {
#if !defined(GENERATING_DOCUMENTATION)
template <typename Allocator, typename R>
struct async_result<experimental::use_coro_t<Allocator>, R()>
{
template <typename Initiation, typename... InitArgs>
static auto initiate_impl(Initiation initiation,
std::allocator_arg_t, Allocator, InitArgs... args)
-> experimental::coro<void() noexcept, void,
asio::associated_executor_t<Initiation>, Allocator>
{
co_await deferred_async_operation<R(), Initiation, InitArgs...>(
deferred_init_tag{}, std::move(initiation), std::move(args)...);
}
template <typename... InitArgs>
static auto initiate_impl(asio::detail::initiation_archetype<R()>,
std::allocator_arg_t, Allocator, InitArgs... args)
-> experimental::coro<void(), void,
asio::any_io_executor, Allocator>;
template <typename Initiation, typename... InitArgs>
static auto initiate(Initiation initiation,
experimental::use_coro_t<Allocator> tk, InitArgs&&... args)
{
return initiate_impl(std::move(initiation), std::allocator_arg,
tk.get_allocator(), std::forward<InitArgs>(args)...);
}
};
template <typename Allocator, typename R>
struct async_result<
experimental::use_coro_t<Allocator>, R(asio::error_code)>
{
template <typename Initiation, typename... InitArgs>
static auto initiate_impl(Initiation initiation,
std::allocator_arg_t, Allocator, InitArgs... args)
-> experimental::coro<void() noexcept, void,
asio::associated_executor_t<Initiation>, Allocator>
{
co_await deferred_async_operation<
R(asio::error_code), Initiation, InitArgs...>(
deferred_init_tag{}, std::move(initiation), std::move(args)...);
}
template <typename... InitArgs>
static auto initiate_impl(
asio::detail::initiation_archetype<R(asio::error_code)>,
std::allocator_arg_t, Allocator, InitArgs... args)
-> experimental::coro<void(), void,
asio::any_io_executor, Allocator>;
template <typename Initiation, typename... InitArgs>
static auto initiate(Initiation initiation,
experimental::use_coro_t<Allocator> tk, InitArgs&&... args)
{
return initiate_impl(std::move(initiation), std::allocator_arg,
tk.get_allocator(), std::forward<InitArgs>(args)...);
}
};
template <typename Allocator, typename R>
struct async_result<
experimental::use_coro_t<Allocator>, R(std::exception_ptr)>
{
template <typename Initiation, typename... InitArgs>
static auto initiate_impl(Initiation initiation,
std::allocator_arg_t, Allocator, InitArgs... args)
-> experimental::coro<void(), void,
asio::associated_executor_t<Initiation>, Allocator>
{
co_await deferred_async_operation<
R(std::exception_ptr), Initiation, InitArgs...>(
deferred_init_tag{}, std::move(initiation), std::move(args)...);
}
template <typename... InitArgs>
static auto initiate_impl(
asio::detail::initiation_archetype<R(std::exception_ptr)>,
std::allocator_arg_t, Allocator, InitArgs... args)
-> experimental::coro<void(), void,
asio::any_io_executor, Allocator>;
template <typename Initiation, typename... InitArgs>
static auto initiate(Initiation initiation,
experimental::use_coro_t<Allocator> tk, InitArgs&&... args)
{
return initiate_impl(std::move(initiation), std::allocator_arg,
tk.get_allocator(), std::forward<InitArgs>(args)...);
}
};
template <typename Allocator, typename R, typename T>
struct async_result<experimental::use_coro_t<Allocator>, R(T)>
{
template <typename Initiation, typename... InitArgs>
static auto initiate_impl(Initiation initiation,
std::allocator_arg_t, Allocator, InitArgs... args)
-> experimental::coro<void() noexcept, T,
asio::associated_executor_t<Initiation>, Allocator>
{
co_return co_await deferred_async_operation<R(T), Initiation, InitArgs...>(
deferred_init_tag{}, std::move(initiation), std::move(args)...);
}
template <typename... InitArgs>
static auto initiate_impl(asio::detail::initiation_archetype<R(T)>,
std::allocator_arg_t, Allocator, InitArgs... args)
-> experimental::coro<void() noexcept, T,
asio::any_io_executor, Allocator>;
template <typename Initiation, typename... InitArgs>
static auto initiate(Initiation initiation,
experimental::use_coro_t<Allocator> tk, InitArgs&&... args)
{
return initiate_impl(std::move(initiation), std::allocator_arg,
tk.get_allocator(), std::forward<InitArgs>(args)...);
}
};
template <typename Allocator, typename R, typename T>
struct async_result<
experimental::use_coro_t<Allocator>, R(asio::error_code, T)>
{
template <typename Initiation, typename... InitArgs>
static auto initiate_impl(Initiation initiation,
std::allocator_arg_t, Allocator, InitArgs... args)
-> experimental::coro<void(), T,
asio::associated_executor_t<Initiation>, Allocator>
{
co_return co_await deferred_async_operation<
R(asio::error_code, T), Initiation, InitArgs...>(
deferred_init_tag{}, std::move(initiation), std::move(args)...);
}
template <typename... InitArgs>
static auto initiate_impl(
asio::detail::initiation_archetype<
R(asio::error_code, T)>,
std::allocator_arg_t, Allocator, InitArgs... args)
-> experimental::coro<void(), T, asio::any_io_executor, Allocator>;
template <typename Initiation, typename... InitArgs>
static auto initiate(Initiation initiation,
experimental::use_coro_t<Allocator> tk, InitArgs&&... args)
{
return initiate_impl(std::move(initiation), std::allocator_arg,
tk.get_allocator(), std::forward<InitArgs>(args)...);
}
};
template <typename Allocator, typename R, typename T>
struct async_result<
experimental::use_coro_t<Allocator>, R(std::exception_ptr, T)>
{
template <typename Initiation, typename... InitArgs>
static auto initiate_impl(Initiation initiation,
std::allocator_arg_t, Allocator, InitArgs... args)
-> experimental::coro<void(), T,
asio::associated_executor_t<Initiation>, Allocator>
{
co_return co_await deferred_async_operation<
R(std::exception_ptr, T), Initiation, InitArgs...>(
deferred_init_tag{}, std::move(initiation), std::move(args)...);
}
template <typename... InitArgs>
static auto initiate_impl(
asio::detail::initiation_archetype<R(std::exception_ptr, T)>,
std::allocator_arg_t, Allocator, InitArgs... args)
-> experimental::coro<void(), T, asio::any_io_executor, Allocator>;
template <typename Initiation, typename... InitArgs>
static auto initiate(Initiation initiation,
experimental::use_coro_t<Allocator> tk, InitArgs&&... args)
{
return initiate_impl(std::move(initiation), std::allocator_arg,
tk.get_allocator(), std::forward<InitArgs>(args)...);
}
};
#endif // !defined(GENERATING_DOCUMENTATION)
} // namespace asio
#include "asio/detail/pop_options.hpp"
#endif // ASIO_EXPERIMENTAL_IMPL_USE_CORO_HPP
|
0 | repos/asio/asio/include/asio/experimental | repos/asio/asio/include/asio/experimental/impl/parallel_group.hpp | //
// experimental/impl/parallel_group.hpp
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef ASIO_IMPL_EXPERIMENTAL_PARALLEL_GROUP_HPP
#define ASIO_IMPL_EXPERIMENTAL_PARALLEL_GROUP_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include "asio/detail/config.hpp"
#include <atomic>
#include <deque>
#include <memory>
#include <new>
#include <tuple>
#include "asio/associated_cancellation_slot.hpp"
#include "asio/detail/recycling_allocator.hpp"
#include "asio/detail/type_traits.hpp"
#include "asio/dispatch.hpp"
#include "asio/detail/push_options.hpp"
namespace asio {
namespace experimental {
namespace detail {
// Stores the result from an individual asynchronous operation.
template <typename T, typename = void>
struct parallel_group_op_result
{
public:
parallel_group_op_result()
: has_value_(false)
{
}
parallel_group_op_result(parallel_group_op_result&& other)
: has_value_(other.has_value_)
{
if (has_value_)
new (&u_.value_) T(std::move(other.get()));
}
~parallel_group_op_result()
{
if (has_value_)
u_.value_.~T();
}
T& get() noexcept
{
return u_.value_;
}
template <typename... Args>
void emplace(Args&&... args)
{
new (&u_.value_) T(std::forward<Args>(args)...);
has_value_ = true;
}
private:
union u
{
u() {}
~u() {}
char c_;
T value_;
} u_;
bool has_value_;
};
// Proxy completion handler for the group of parallel operatations. Unpacks and
// concatenates the individual operations' results, and invokes the user's
// completion handler.
template <typename Handler, typename... Ops>
struct parallel_group_completion_handler
{
typedef decay_t<
prefer_result_t<
associated_executor_t<Handler>,
execution::outstanding_work_t::tracked_t
>
> executor_type;
parallel_group_completion_handler(Handler&& h)
: handler_(std::move(h)),
executor_(
asio::prefer(
asio::get_associated_executor(handler_),
execution::outstanding_work.tracked))
{
}
executor_type get_executor() const noexcept
{
return executor_;
}
void operator()()
{
this->invoke(asio::detail::make_index_sequence<sizeof...(Ops)>());
}
template <std::size_t... I>
void invoke(asio::detail::index_sequence<I...>)
{
this->invoke(std::tuple_cat(std::move(std::get<I>(args_).get())...));
}
template <typename... Args>
void invoke(std::tuple<Args...>&& args)
{
this->invoke(std::move(args),
asio::detail::index_sequence_for<Args...>());
}
template <typename... Args, std::size_t... I>
void invoke(std::tuple<Args...>&& args,
asio::detail::index_sequence<I...>)
{
std::move(handler_)(completion_order_, std::move(std::get<I>(args))...);
}
Handler handler_;
executor_type executor_;
std::array<std::size_t, sizeof...(Ops)> completion_order_{};
std::tuple<
parallel_group_op_result<
typename parallel_op_signature_as_tuple<
completion_signature_of_t<Ops>
>::type
>...
> args_{};
};
// Shared state for the parallel group.
template <typename Condition, typename Handler, typename... Ops>
struct parallel_group_state
{
parallel_group_state(Condition&& c, Handler&& h)
: cancellation_condition_(std::move(c)),
handler_(std::move(h))
{
}
// The number of operations that have completed so far. Used to determine the
// order of completion.
std::atomic<unsigned int> completed_{0};
// The non-none cancellation type that resulted from a cancellation condition.
// Stored here for use by the group's initiating function.
std::atomic<cancellation_type_t> cancel_type_{cancellation_type::none};
// The number of cancellations that have been requested, either on completion
// of the operations within the group, or via the cancellation slot for the
// group operation. Initially set to the number of operations to prevent
// cancellation signals from being emitted until after all of the group's
// operations' initiating functions have completed.
std::atomic<unsigned int> cancellations_requested_{sizeof...(Ops)};
// The number of operations that are yet to complete. Used to determine when
// it is safe to invoke the user's completion handler.
std::atomic<unsigned int> outstanding_{sizeof...(Ops)};
// The cancellation signals for each operation in the group.
asio::cancellation_signal cancellation_signals_[sizeof...(Ops)];
// The cancellation condition is used to determine whether the results from an
// individual operation warrant a cancellation request for the whole group.
Condition cancellation_condition_;
// The proxy handler to be invoked once all operations in the group complete.
parallel_group_completion_handler<Handler, Ops...> handler_;
};
// Handler for an individual operation within the parallel group.
template <std::size_t I, typename Condition, typename Handler, typename... Ops>
struct parallel_group_op_handler
{
typedef asio::cancellation_slot cancellation_slot_type;
parallel_group_op_handler(
std::shared_ptr<parallel_group_state<Condition, Handler, Ops...>> state)
: state_(std::move(state))
{
}
cancellation_slot_type get_cancellation_slot() const noexcept
{
return state_->cancellation_signals_[I].slot();
}
template <typename... Args>
void operator()(Args... args)
{
// Capture this operation into the completion order.
state_->handler_.completion_order_[state_->completed_++] = I;
// Determine whether the results of this operation require cancellation of
// the whole group.
cancellation_type_t cancel_type = state_->cancellation_condition_(args...);
// Capture the result of the operation into the proxy completion handler.
std::get<I>(state_->handler_.args_).emplace(std::move(args)...);
if (cancel_type != cancellation_type::none)
{
// Save the type for potential use by the group's initiating function.
state_->cancel_type_ = cancel_type;
// If we are the first operation to request cancellation, emit a signal
// for each operation in the group.
if (state_->cancellations_requested_++ == 0)
for (std::size_t i = 0; i < sizeof...(Ops); ++i)
if (i != I)
state_->cancellation_signals_[i].emit(cancel_type);
}
// If this is the last outstanding operation, invoke the user's handler.
if (--state_->outstanding_ == 0)
asio::dispatch(std::move(state_->handler_));
}
std::shared_ptr<parallel_group_state<Condition, Handler, Ops...>> state_;
};
// Handler for an individual operation within the parallel group that has an
// explicitly specified executor.
template <typename Executor, std::size_t I,
typename Condition, typename Handler, typename... Ops>
struct parallel_group_op_handler_with_executor :
parallel_group_op_handler<I, Condition, Handler, Ops...>
{
typedef parallel_group_op_handler<I, Condition, Handler, Ops...> base_type;
typedef asio::cancellation_slot cancellation_slot_type;
typedef Executor executor_type;
parallel_group_op_handler_with_executor(
std::shared_ptr<parallel_group_state<Condition, Handler, Ops...>> state,
executor_type ex)
: parallel_group_op_handler<I, Condition, Handler, Ops...>(std::move(state))
{
cancel_proxy_ =
&this->state_->cancellation_signals_[I].slot().template
emplace<cancel_proxy>(this->state_, std::move(ex));
}
cancellation_slot_type get_cancellation_slot() const noexcept
{
return cancel_proxy_->signal_.slot();
}
executor_type get_executor() const noexcept
{
return cancel_proxy_->executor_;
}
// Proxy handler that forwards the emitted signal to the correct executor.
struct cancel_proxy
{
cancel_proxy(
std::shared_ptr<parallel_group_state<
Condition, Handler, Ops...>> state,
executor_type ex)
: state_(std::move(state)),
executor_(std::move(ex))
{
}
void operator()(cancellation_type_t type)
{
if (auto state = state_.lock())
{
asio::cancellation_signal* sig = &signal_;
asio::dispatch(executor_,
[state, sig, type]{ sig->emit(type); });
}
}
std::weak_ptr<parallel_group_state<Condition, Handler, Ops...>> state_;
asio::cancellation_signal signal_;
executor_type executor_;
};
cancel_proxy* cancel_proxy_;
};
// Helper to launch an operation using the correct executor, if any.
template <std::size_t I, typename Op, typename = void>
struct parallel_group_op_launcher
{
template <typename Condition, typename Handler, typename... Ops>
static void launch(Op& op,
const std::shared_ptr<parallel_group_state<
Condition, Handler, Ops...>>& state)
{
typedef associated_executor_t<Op> ex_type;
ex_type ex = asio::get_associated_executor(op);
std::move(op)(
parallel_group_op_handler_with_executor<ex_type, I,
Condition, Handler, Ops...>(state, std::move(ex)));
}
};
// Specialised launcher for operations that specify no executor.
template <std::size_t I, typename Op>
struct parallel_group_op_launcher<I, Op,
enable_if_t<
is_same<
typename associated_executor<
Op>::asio_associated_executor_is_unspecialised,
void
>::value
>>
{
template <typename Condition, typename Handler, typename... Ops>
static void launch(Op& op,
const std::shared_ptr<parallel_group_state<
Condition, Handler, Ops...>>& state)
{
std::move(op)(
parallel_group_op_handler<I, Condition, Handler, Ops...>(state));
}
};
template <typename Condition, typename Handler, typename... Ops>
struct parallel_group_cancellation_handler
{
parallel_group_cancellation_handler(
std::shared_ptr<parallel_group_state<Condition, Handler, Ops...>> state)
: state_(std::move(state))
{
}
void operator()(cancellation_type_t cancel_type)
{
// If we are the first place to request cancellation, i.e. no operation has
// yet completed and requested cancellation, emit a signal for each
// operation in the group.
if (cancel_type != cancellation_type::none)
if (auto state = state_.lock())
if (state->cancellations_requested_++ == 0)
for (std::size_t i = 0; i < sizeof...(Ops); ++i)
state->cancellation_signals_[i].emit(cancel_type);
}
std::weak_ptr<parallel_group_state<Condition, Handler, Ops...>> state_;
};
template <typename Condition, typename Handler,
typename... Ops, std::size_t... I>
void parallel_group_launch(Condition cancellation_condition, Handler handler,
std::tuple<Ops...>& ops, asio::detail::index_sequence<I...>)
{
// Get the user's completion handler's cancellation slot, so that we can allow
// cancellation of the entire group.
associated_cancellation_slot_t<Handler> slot
= asio::get_associated_cancellation_slot(handler);
// Create the shared state for the operation.
typedef parallel_group_state<Condition, Handler, Ops...> state_type;
std::shared_ptr<state_type> state = std::allocate_shared<state_type>(
asio::detail::recycling_allocator<state_type,
asio::detail::thread_info_base::parallel_group_tag>(),
std::move(cancellation_condition), std::move(handler));
// Initiate each individual operation in the group.
int fold[] = { 0,
( parallel_group_op_launcher<I, Ops>::launch(std::get<I>(ops), state),
0 )...
};
(void)fold;
// Check if any of the operations has already requested cancellation, and if
// so, emit a signal for each operation in the group.
if ((state->cancellations_requested_ -= sizeof...(Ops)) > 0)
for (auto& signal : state->cancellation_signals_)
signal.emit(state->cancel_type_);
// Register a handler with the user's completion handler's cancellation slot.
if (slot.is_connected())
slot.template emplace<
parallel_group_cancellation_handler<
Condition, Handler, Ops...>>(state);
}
// Proxy completion handler for the ranged group of parallel operatations.
// Unpacks and recombines the individual operations' results, and invokes the
// user's completion handler.
template <typename Handler, typename Op, typename Allocator>
struct ranged_parallel_group_completion_handler
{
typedef decay_t<
prefer_result_t<
associated_executor_t<Handler>,
execution::outstanding_work_t::tracked_t
>
> executor_type;
typedef typename parallel_op_signature_as_tuple<
completion_signature_of_t<Op>
>::type op_tuple_type;
typedef parallel_group_op_result<op_tuple_type> op_result_type;
ranged_parallel_group_completion_handler(Handler&& h,
std::size_t size, const Allocator& allocator)
: handler_(std::move(h)),
executor_(
asio::prefer(
asio::get_associated_executor(handler_),
execution::outstanding_work.tracked)),
allocator_(allocator),
completion_order_(size, 0,
ASIO_REBIND_ALLOC(Allocator, std::size_t)(allocator)),
args_(ASIO_REBIND_ALLOC(Allocator, op_result_type)(allocator))
{
for (std::size_t i = 0; i < size; ++i)
args_.emplace_back();
}
executor_type get_executor() const noexcept
{
return executor_;
}
void operator()()
{
this->invoke(
asio::detail::make_index_sequence<
std::tuple_size<op_tuple_type>::value>());
}
template <std::size_t... I>
void invoke(asio::detail::index_sequence<I...>)
{
typedef typename parallel_op_signature_as_tuple<
typename ranged_parallel_group_signature<
completion_signature_of_t<Op>,
Allocator
>::raw_type
>::type vectors_type;
// Construct all result vectors using the supplied allocator.
vectors_type vectors{
typename std::tuple_element<I, vectors_type>::type(
ASIO_REBIND_ALLOC(Allocator, int)(allocator_))...};
// Reserve sufficient space in each of the result vectors.
int reserve_fold[] = { 0,
( std::get<I>(vectors).reserve(completion_order_.size()),
0 )...
};
(void)reserve_fold;
// Copy the results from all operations into the result vectors.
for (std::size_t idx = 0; idx < completion_order_.size(); ++idx)
{
int pushback_fold[] = { 0,
( std::get<I>(vectors).push_back(
std::move(std::get<I>(args_[idx].get()))),
0 )...
};
(void)pushback_fold;
}
std::move(handler_)(std::move(completion_order_),
std::move(std::get<I>(vectors))...);
}
Handler handler_;
executor_type executor_;
Allocator allocator_;
std::vector<std::size_t,
ASIO_REBIND_ALLOC(Allocator, std::size_t)> completion_order_;
std::deque<op_result_type,
ASIO_REBIND_ALLOC(Allocator, op_result_type)> args_;
};
// Shared state for the parallel group.
template <typename Condition, typename Handler, typename Op, typename Allocator>
struct ranged_parallel_group_state
{
ranged_parallel_group_state(Condition&& c, Handler&& h,
std::size_t size, const Allocator& allocator)
: cancellations_requested_(size),
outstanding_(size),
cancellation_signals_(
ASIO_REBIND_ALLOC(Allocator,
asio::cancellation_signal)(allocator)),
cancellation_condition_(std::move(c)),
handler_(std::move(h), size, allocator)
{
for (std::size_t i = 0; i < size; ++i)
cancellation_signals_.emplace_back();
}
// The number of operations that have completed so far. Used to determine the
// order of completion.
std::atomic<unsigned int> completed_{0};
// The non-none cancellation type that resulted from a cancellation condition.
// Stored here for use by the group's initiating function.
std::atomic<cancellation_type_t> cancel_type_{cancellation_type::none};
// The number of cancellations that have been requested, either on completion
// of the operations within the group, or via the cancellation slot for the
// group operation. Initially set to the number of operations to prevent
// cancellation signals from being emitted until after all of the group's
// operations' initiating functions have completed.
std::atomic<unsigned int> cancellations_requested_;
// The number of operations that are yet to complete. Used to determine when
// it is safe to invoke the user's completion handler.
std::atomic<unsigned int> outstanding_;
// The cancellation signals for each operation in the group.
std::deque<asio::cancellation_signal,
ASIO_REBIND_ALLOC(Allocator, asio::cancellation_signal)>
cancellation_signals_;
// The cancellation condition is used to determine whether the results from an
// individual operation warrant a cancellation request for the whole group.
Condition cancellation_condition_;
// The proxy handler to be invoked once all operations in the group complete.
ranged_parallel_group_completion_handler<Handler, Op, Allocator> handler_;
};
// Handler for an individual operation within the parallel group.
template <typename Condition, typename Handler, typename Op, typename Allocator>
struct ranged_parallel_group_op_handler
{
typedef asio::cancellation_slot cancellation_slot_type;
ranged_parallel_group_op_handler(
std::shared_ptr<ranged_parallel_group_state<
Condition, Handler, Op, Allocator>> state,
std::size_t idx)
: state_(std::move(state)),
idx_(idx)
{
}
cancellation_slot_type get_cancellation_slot() const noexcept
{
return state_->cancellation_signals_[idx_].slot();
}
template <typename... Args>
void operator()(Args... args)
{
// Capture this operation into the completion order.
state_->handler_.completion_order_[state_->completed_++] = idx_;
// Determine whether the results of this operation require cancellation of
// the whole group.
cancellation_type_t cancel_type = state_->cancellation_condition_(args...);
// Capture the result of the operation into the proxy completion handler.
state_->handler_.args_[idx_].emplace(std::move(args)...);
if (cancel_type != cancellation_type::none)
{
// Save the type for potential use by the group's initiating function.
state_->cancel_type_ = cancel_type;
// If we are the first operation to request cancellation, emit a signal
// for each operation in the group.
if (state_->cancellations_requested_++ == 0)
for (std::size_t i = 0; i < state_->cancellation_signals_.size(); ++i)
if (i != idx_)
state_->cancellation_signals_[i].emit(cancel_type);
}
// If this is the last outstanding operation, invoke the user's handler.
if (--state_->outstanding_ == 0)
asio::dispatch(std::move(state_->handler_));
}
std::shared_ptr<ranged_parallel_group_state<
Condition, Handler, Op, Allocator>> state_;
std::size_t idx_;
};
// Handler for an individual operation within the parallel group that has an
// explicitly specified executor.
template <typename Executor, typename Condition,
typename Handler, typename Op, typename Allocator>
struct ranged_parallel_group_op_handler_with_executor :
ranged_parallel_group_op_handler<Condition, Handler, Op, Allocator>
{
typedef ranged_parallel_group_op_handler<
Condition, Handler, Op, Allocator> base_type;
typedef asio::cancellation_slot cancellation_slot_type;
typedef Executor executor_type;
ranged_parallel_group_op_handler_with_executor(
std::shared_ptr<ranged_parallel_group_state<
Condition, Handler, Op, Allocator>> state,
executor_type ex, std::size_t idx)
: ranged_parallel_group_op_handler<Condition, Handler, Op, Allocator>(
std::move(state), idx)
{
cancel_proxy_ =
&this->state_->cancellation_signals_[idx].slot().template
emplace<cancel_proxy>(this->state_, std::move(ex));
}
cancellation_slot_type get_cancellation_slot() const noexcept
{
return cancel_proxy_->signal_.slot();
}
executor_type get_executor() const noexcept
{
return cancel_proxy_->executor_;
}
// Proxy handler that forwards the emitted signal to the correct executor.
struct cancel_proxy
{
cancel_proxy(
std::shared_ptr<ranged_parallel_group_state<
Condition, Handler, Op, Allocator>> state,
executor_type ex)
: state_(std::move(state)),
executor_(std::move(ex))
{
}
void operator()(cancellation_type_t type)
{
if (auto state = state_.lock())
{
asio::cancellation_signal* sig = &signal_;
asio::dispatch(executor_,
[state, sig, type]{ sig->emit(type); });
}
}
std::weak_ptr<ranged_parallel_group_state<
Condition, Handler, Op, Allocator>> state_;
asio::cancellation_signal signal_;
executor_type executor_;
};
cancel_proxy* cancel_proxy_;
};
template <typename Condition, typename Handler, typename Op, typename Allocator>
struct ranged_parallel_group_cancellation_handler
{
ranged_parallel_group_cancellation_handler(
std::shared_ptr<ranged_parallel_group_state<
Condition, Handler, Op, Allocator>> state)
: state_(std::move(state))
{
}
void operator()(cancellation_type_t cancel_type)
{
// If we are the first place to request cancellation, i.e. no operation has
// yet completed and requested cancellation, emit a signal for each
// operation in the group.
if (cancel_type != cancellation_type::none)
if (auto state = state_.lock())
if (state->cancellations_requested_++ == 0)
for (std::size_t i = 0; i < state->cancellation_signals_.size(); ++i)
state->cancellation_signals_[i].emit(cancel_type);
}
std::weak_ptr<ranged_parallel_group_state<
Condition, Handler, Op, Allocator>> state_;
};
template <typename Condition, typename Handler,
typename Range, typename Allocator>
void ranged_parallel_group_launch(Condition cancellation_condition,
Handler handler, Range&& range, const Allocator& allocator)
{
// Get the user's completion handler's cancellation slot, so that we can allow
// cancellation of the entire group.
associated_cancellation_slot_t<Handler> slot
= asio::get_associated_cancellation_slot(handler);
// The type of the asynchronous operation.
typedef decay_t<decltype(*declval<typename Range::iterator>())> op_type;
// Create the shared state for the operation.
typedef ranged_parallel_group_state<Condition,
Handler, op_type, Allocator> state_type;
std::shared_ptr<state_type> state = std::allocate_shared<state_type>(
asio::detail::recycling_allocator<state_type,
asio::detail::thread_info_base::parallel_group_tag>(),
std::move(cancellation_condition),
std::move(handler), range.size(), allocator);
std::size_t idx = 0;
for (auto&& op : std::forward<Range>(range))
{
typedef associated_executor_t<op_type> ex_type;
ex_type ex = asio::get_associated_executor(op);
std::move(op)(
ranged_parallel_group_op_handler_with_executor<
ex_type, Condition, Handler, op_type, Allocator>(
state, std::move(ex), idx++));
}
// Check if any of the operations has already requested cancellation, and if
// so, emit a signal for each operation in the group.
if ((state->cancellations_requested_ -= range.size()) > 0)
for (auto& signal : state->cancellation_signals_)
signal.emit(state->cancel_type_);
// Register a handler with the user's completion handler's cancellation slot.
if (slot.is_connected())
slot.template emplace<
ranged_parallel_group_cancellation_handler<
Condition, Handler, op_type, Allocator>>(state);
}
} // namespace detail
} // namespace experimental
template <template <typename, typename> class Associator,
typename Handler, typename... Ops, typename DefaultCandidate>
struct associator<Associator,
experimental::detail::parallel_group_completion_handler<Handler, Ops...>,
DefaultCandidate>
: Associator<Handler, DefaultCandidate>
{
static typename Associator<Handler, DefaultCandidate>::type get(
const experimental::detail::parallel_group_completion_handler<
Handler, Ops...>& h) noexcept
{
return Associator<Handler, DefaultCandidate>::get(h.handler_);
}
static auto get(
const experimental::detail::parallel_group_completion_handler<
Handler, Ops...>& h,
const DefaultCandidate& c) noexcept
-> decltype(Associator<Handler, DefaultCandidate>::get(h.handler_, c))
{
return Associator<Handler, DefaultCandidate>::get(h.handler_, c);
}
};
template <template <typename, typename> class Associator, typename Handler,
typename Op, typename Allocator, typename DefaultCandidate>
struct associator<Associator,
experimental::detail::ranged_parallel_group_completion_handler<
Handler, Op, Allocator>,
DefaultCandidate>
: Associator<Handler, DefaultCandidate>
{
static typename Associator<Handler, DefaultCandidate>::type get(
const experimental::detail::ranged_parallel_group_completion_handler<
Handler, Op, Allocator>& h) noexcept
{
return Associator<Handler, DefaultCandidate>::get(h.handler_);
}
static auto get(
const experimental::detail::ranged_parallel_group_completion_handler<
Handler, Op, Allocator>& h,
const DefaultCandidate& c) noexcept
-> decltype(Associator<Handler, DefaultCandidate>::get(h.handler_, c))
{
return Associator<Handler, DefaultCandidate>::get(h.handler_, c);
}
};
} // namespace asio
#include "asio/detail/pop_options.hpp"
#endif // ASIO_IMPL_EXPERIMENTAL_PARALLEL_GROUP_HPP
|
0 | repos/asio/asio/include/asio/experimental | repos/asio/asio/include/asio/experimental/impl/channel_error.ipp | //
// experimental/impl/channel_error.ipp
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef ASIO_EXPERIMENTAL_IMPL_CHANNEL_ERROR_IPP
#define ASIO_EXPERIMENTAL_IMPL_CHANNEL_ERROR_IPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include "asio/detail/config.hpp"
#include "asio/experimental/channel_error.hpp"
#include "asio/detail/push_options.hpp"
namespace asio {
namespace experimental {
namespace error {
namespace detail {
class channel_category : public asio::error_category
{
public:
const char* name() const noexcept
{
return "asio.channel";
}
std::string message(int value) const
{
switch (value)
{
case channel_closed: return "Channel closed";
case channel_cancelled: return "Channel cancelled";
default: return "asio.channel error";
}
}
};
} // namespace detail
const asio::error_category& get_channel_category()
{
static detail::channel_category instance;
return instance;
}
} // namespace error
} // namespace experimental
} // namespace asio
#include "asio/detail/pop_options.hpp"
#endif // ASIO_EXPERIMENTAL_IMPL_CHANNEL_ERROR_IPP
|
0 | repos/asio/asio/include/asio/experimental | repos/asio/asio/include/asio/experimental/impl/coro.hpp | //
// experimental/impl/coro.hpp
// ~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2021-2023 Klemens D. Morgenstern
// (klemens dot morgenstern at gmx dot net)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef ASIO_EXPERIMENTAL_IMPL_CORO_HPP
#define ASIO_EXPERIMENTAL_IMPL_CORO_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include "asio/detail/config.hpp"
#include "asio/append.hpp"
#include "asio/associated_cancellation_slot.hpp"
#include "asio/bind_allocator.hpp"
#include "asio/deferred.hpp"
#include "asio/experimental/detail/coro_completion_handler.hpp"
#include "asio/detail/push_options.hpp"
namespace asio {
namespace experimental {
template <typename Yield, typename Return,
typename Executor, typename Allocator>
struct coro;
namespace detail {
struct coro_cancellation_source
{
cancellation_slot slot;
cancellation_state state;
bool throw_if_cancelled_ = true;
void reset_cancellation_state()
{
state = cancellation_state(slot);
}
template <typename Filter>
void reset_cancellation_state(Filter&& filter)
{
state = cancellation_state(slot, static_cast<Filter&&>(filter));
}
template <typename InFilter, typename OutFilter>
void reset_cancellation_state(InFilter&& in_filter,
OutFilter&& out_filter)
{
state = cancellation_state(slot,
static_cast<InFilter&&>(in_filter),
static_cast<OutFilter&&>(out_filter));
}
bool throw_if_cancelled() const
{
return throw_if_cancelled_;
}
void throw_if_cancelled(bool value)
{
throw_if_cancelled_ = value;
}
};
template <typename Signature, typename Return,
typename Executor, typename Allocator>
struct coro_promise;
template <typename T>
struct is_noexcept : std::false_type
{
};
template <typename Return, typename... Args>
struct is_noexcept<Return(Args...)> : std::false_type
{
};
template <typename Return, typename... Args>
struct is_noexcept<Return(Args...) noexcept> : std::true_type
{
};
template <typename T>
constexpr bool is_noexcept_v = is_noexcept<T>::value;
template <typename T>
struct coro_error;
template <>
struct coro_error<asio::error_code>
{
static asio::error_code invalid()
{
return asio::error::fault;
}
static asio::error_code cancelled()
{
return asio::error::operation_aborted;
}
static asio::error_code interrupted()
{
return asio::error::interrupted;
}
static asio::error_code done()
{
return asio::error::broken_pipe;
}
};
template <>
struct coro_error<std::exception_ptr>
{
static std::exception_ptr invalid()
{
return std::make_exception_ptr(
asio::system_error(
coro_error<asio::error_code>::invalid()));
}
static std::exception_ptr cancelled()
{
return std::make_exception_ptr(
asio::system_error(
coro_error<asio::error_code>::cancelled()));
}
static std::exception_ptr interrupted()
{
return std::make_exception_ptr(
asio::system_error(
coro_error<asio::error_code>::interrupted()));
}
static std::exception_ptr done()
{
return std::make_exception_ptr(
asio::system_error(
coro_error<asio::error_code>::done()));
}
};
template <typename T, typename Coroutine >
struct coro_with_arg
{
using coro_t = Coroutine;
T value;
coro_t& coro;
struct awaitable_t
{
T value;
coro_t& coro;
constexpr static bool await_ready() { return false; }
template <typename Y, typename R, typename E, typename A>
auto await_suspend(coroutine_handle<coro_promise<Y, R, E, A>> h)
-> coroutine_handle<>
{
auto& hp = h.promise();
if constexpr (!coro_promise<Y, R, E, A>::is_noexcept)
{
if ((hp.cancel->state.cancelled() != cancellation_type::none)
&& hp.cancel->throw_if_cancelled_)
{
asio::detail::throw_error(
asio::error::operation_aborted, "coro-cancelled");
}
}
if (hp.get_executor() == coro.get_executor())
{
coro.coro_->awaited_from = h;
coro.coro_->reset_error();
coro.coro_->input_ = std::move(value);
coro.coro_->cancel = hp.cancel;
return coro.coro_->get_handle();
}
else
{
coro.coro_->awaited_from =
dispatch_coroutine(
asio::prefer(hp.get_executor(),
execution::outstanding_work.tracked),
[h]() mutable { h.resume(); }).handle;
coro.coro_->reset_error();
coro.coro_->input_ = std::move(value);
struct cancel_handler
{
using src = std::pair<cancellation_signal,
detail::coro_cancellation_source>;
std::shared_ptr<src> st = std::make_shared<src>();
cancel_handler(E e, coro_t& coro) : e(e), coro_(coro.coro_)
{
st->second.state =
cancellation_state(st->second.slot = st->first.slot());
}
E e;
typename coro_t::promise_type* coro_;
void operator()(cancellation_type ct)
{
asio::dispatch(e, [ct, st = st]() mutable
{
auto & [sig, state] = *st;
sig.emit(ct);
});
}
};
if (hp.cancel->state.slot().is_connected())
{
hp.cancel->state.slot().template emplace<cancel_handler>(
coro.get_executor(), coro);
}
auto hh = detail::coroutine_handle<
typename coro_t::promise_type>::from_promise(*coro.coro_);
return dispatch_coroutine(
coro.coro_->get_executor(), [hh]() mutable { hh.resume(); }).handle;
}
}
auto await_resume() -> typename coro_t::result_type
{
coro.coro_->cancel = nullptr;
coro.coro_->rethrow_if();
return std::move(coro.coro_->result_);
}
};
template <typename CompletionToken>
auto async_resume(CompletionToken&& token) &&
{
return coro.async_resume(std::move(value),
std::forward<CompletionToken>(token));
}
auto operator co_await() &&
{
return awaitable_t{std::move(value), coro};
}
};
template <bool IsNoexcept>
struct coro_promise_error;
template <>
struct coro_promise_error<false>
{
std::exception_ptr error_;
void reset_error()
{
error_ = std::exception_ptr{};
}
void unhandled_exception()
{
error_ = std::current_exception();
}
void rethrow_if()
{
if (error_)
std::rethrow_exception(error_);
}
};
#if defined(__GNUC__)
# pragma GCC diagnostic push
# if defined(__clang__)
# pragma GCC diagnostic ignored "-Wexceptions"
# else
# pragma GCC diagnostic ignored "-Wterminate"
# endif
#elif defined(_MSC_VER)
# pragma warning(push)
# pragma warning (disable:4297)
#endif
template <>
struct coro_promise_error<true>
{
void reset_error()
{
}
void unhandled_exception() noexcept
{
throw;
}
void rethrow_if()
{
}
};
#if defined(__GNUC__)
# pragma GCC diagnostic pop
#elif defined(_MSC_VER)
# pragma warning(pop)
#endif
template <typename T = void>
struct yield_input
{
T& value;
coroutine_handle<> awaited_from{noop_coroutine()};
bool await_ready() const noexcept
{
return false;
}
template <typename U>
coroutine_handle<> await_suspend(coroutine_handle<U>) noexcept
{
return std::exchange(awaited_from, noop_coroutine());
}
T await_resume() const noexcept
{
return std::move(value);
}
};
template <>
struct yield_input<void>
{
coroutine_handle<> awaited_from{noop_coroutine()};
bool await_ready() const noexcept
{
return false;
}
auto await_suspend(coroutine_handle<>) noexcept
{
return std::exchange(awaited_from, noop_coroutine());
}
constexpr void await_resume() const noexcept
{
}
};
struct coro_awaited_from
{
coroutine_handle<> awaited_from{noop_coroutine()};
auto final_suspend() noexcept
{
struct suspendor
{
coroutine_handle<> awaited_from;
constexpr static bool await_ready() noexcept
{
return false;
}
auto await_suspend(coroutine_handle<>) noexcept
{
return std::exchange(awaited_from, noop_coroutine());
}
constexpr static void await_resume() noexcept
{
}
};
return suspendor{std::exchange(awaited_from, noop_coroutine())};
}
~coro_awaited_from()
{
awaited_from.resume();
}//must be on the right executor
};
template <typename Yield, typename Input, typename Return>
struct coro_promise_exchange : coro_awaited_from
{
using result_type = coro_result_t<Yield, Return>;
result_type result_;
Input input_;
auto yield_value(Yield&& y)
{
result_ = std::move(y);
return yield_input<Input>{std::move(input_),
std::exchange(awaited_from, noop_coroutine())};
}
auto yield_value(const Yield& y)
{
result_ = y;
return yield_input<Input>{std::move(input_),
std::exchange(awaited_from, noop_coroutine())};
}
void return_value(const Return& r)
{
result_ = r;
}
void return_value(Return&& r)
{
result_ = std::move(r);
}
};
template <typename YieldReturn>
struct coro_promise_exchange<YieldReturn, void, YieldReturn> : coro_awaited_from
{
using result_type = coro_result_t<YieldReturn, YieldReturn>;
result_type result_;
auto yield_value(const YieldReturn& y)
{
result_ = y;
return yield_input<void>{std::exchange(awaited_from, noop_coroutine())};
}
auto yield_value(YieldReturn&& y)
{
result_ = std::move(y);
return yield_input<void>{std::exchange(awaited_from, noop_coroutine())};
}
void return_value(const YieldReturn& r)
{
result_ = r;
}
void return_value(YieldReturn&& r)
{
result_ = std::move(r);
}
};
template <typename Yield, typename Return>
struct coro_promise_exchange<Yield, void, Return> : coro_awaited_from
{
using result_type = coro_result_t<Yield, Return>;
result_type result_;
auto yield_value(const Yield& y)
{
result_.template emplace<0>(y);
return yield_input<void>{std::exchange(awaited_from, noop_coroutine())};
}
auto yield_value(Yield&& y)
{
result_.template emplace<0>(std::move(y));
return yield_input<void>{std::exchange(awaited_from, noop_coroutine())};
}
void return_value(const Return& r)
{
result_.template emplace<1>(r);
}
void return_value(Return&& r)
{
result_.template emplace<1>(std::move(r));
}
};
template <typename Yield, typename Input>
struct coro_promise_exchange<Yield, Input, void> : coro_awaited_from
{
using result_type = coro_result_t<Yield, void>;
result_type result_;
Input input_;
auto yield_value(Yield&& y)
{
result_ = std::move(y);
return yield_input<Input>{input_,
std::exchange(awaited_from, noop_coroutine())};
}
auto yield_value(const Yield& y)
{
result_ = y;
return yield_input<Input>{input_,
std::exchange(awaited_from, noop_coroutine())};
}
void return_void()
{
result_.reset();
}
};
template <typename Return>
struct coro_promise_exchange<void, void, Return> : coro_awaited_from
{
using result_type = coro_result_t<void, Return>;
result_type result_;
void yield_value();
void return_value(const Return& r)
{
result_ = r;
}
void return_value(Return&& r)
{
result_ = std::move(r);
}
};
template <>
struct coro_promise_exchange<void, void, void> : coro_awaited_from
{
void return_void() {}
void yield_value();
};
template <typename Yield>
struct coro_promise_exchange<Yield, void, void> : coro_awaited_from
{
using result_type = coro_result_t<Yield, void>;
result_type result_;
auto yield_value(const Yield& y)
{
result_ = y;
return yield_input<void>{std::exchange(awaited_from, noop_coroutine())};
}
auto yield_value(Yield&& y)
{
result_ = std::move(y);
return yield_input<void>{std::exchange(awaited_from, noop_coroutine())};
}
void return_void()
{
result_.reset();
}
};
template <typename Yield, typename Return,
typename Executor, typename Allocator>
struct coro_promise final :
coro_promise_allocator<Allocator>,
coro_promise_error<coro_traits<Yield, Return, Executor>::is_noexcept>,
coro_promise_exchange<
typename coro_traits<Yield, Return, Executor>::yield_type,
typename coro_traits<Yield, Return, Executor>::input_type,
typename coro_traits<Yield, Return, Executor>::return_type>
{
using coro_type = coro<Yield, Return, Executor, Allocator>;
auto handle()
{
return coroutine_handle<coro_promise>::from_promise(this);
}
using executor_type = Executor;
executor_type executor_;
std::optional<coro_cancellation_source> cancel_source;
coro_cancellation_source * cancel;
using cancellation_slot_type = asio::cancellation_slot;
cancellation_slot_type get_cancellation_slot() const noexcept
{
return cancel ? cancel->state.slot() : cancellation_slot_type{};
}
using allocator_type =
typename std::allocator_traits<associated_allocator_t<Executor>>::
template rebind_alloc<std::byte>;
using traits = coro_traits<Yield, Return, Executor>;
using input_type = typename traits::input_type;
using yield_type = typename traits::yield_type;
using return_type = typename traits::return_type;
using error_type = typename traits::error_type;
using result_type = typename traits::result_type;
constexpr static bool is_noexcept = traits::is_noexcept;
auto get_executor() const -> Executor
{
return executor_;
}
auto get_handle()
{
return coroutine_handle<coro_promise>::from_promise(*this);
}
template <typename... Args>
coro_promise(Executor executor, Args&&... args) noexcept
: coro_promise_allocator<Allocator>(
executor, std::forward<Args>(args)...),
executor_(std::move(executor))
{
}
template <typename First, typename... Args>
coro_promise(First&& f, Executor executor, Args&&... args) noexcept
: coro_promise_allocator<Allocator>(
f, executor, std::forward<Args>(args)...),
executor_(std::move(executor))
{
}
template <typename First, detail::execution_context Context, typename... Args>
coro_promise(First&& f, Context&& ctx, Args&&... args) noexcept
: coro_promise_allocator<Allocator>(
f, ctx, std::forward<Args>(args)...),
executor_(ctx.get_executor())
{
}
template <detail::execution_context Context, typename... Args>
coro_promise(Context&& ctx, Args&&... args) noexcept
: coro_promise_allocator<Allocator>(
ctx, std::forward<Args>(args)...),
executor_(ctx.get_executor())
{
}
auto get_return_object()
{
return coro<Yield, Return, Executor, Allocator>{this};
}
auto initial_suspend() noexcept
{
return suspend_always{};
}
using coro_promise_exchange<
typename coro_traits<Yield, Return, Executor>::yield_type,
typename coro_traits<Yield, Return, Executor>::input_type,
typename coro_traits<Yield, Return, Executor>::return_type>::yield_value;
auto await_transform(this_coro::executor_t) const
{
struct exec_helper
{
const executor_type& value;
constexpr static bool await_ready() noexcept
{
return true;
}
constexpr static void await_suspend(coroutine_handle<>) noexcept
{
}
executor_type await_resume() const noexcept
{
return value;
}
};
return exec_helper{executor_};
}
auto await_transform(this_coro::cancellation_state_t) const
{
struct exec_helper
{
const asio::cancellation_state& value;
constexpr static bool await_ready() noexcept
{
return true;
}
constexpr static void await_suspend(coroutine_handle<>) noexcept
{
}
asio::cancellation_state await_resume() const noexcept
{
return value;
}
};
assert(cancel);
return exec_helper{cancel->state};
}
// This await transformation resets the associated cancellation state.
auto await_transform(this_coro::reset_cancellation_state_0_t) noexcept
{
struct result
{
detail::coro_cancellation_source * src_;
bool await_ready() const noexcept
{
return true;
}
void await_suspend(coroutine_handle<void>) noexcept
{
}
auto await_resume() const
{
return src_->reset_cancellation_state();
}
};
return result{cancel};
}
// This await transformation resets the associated cancellation state.
template <typename Filter>
auto await_transform(
this_coro::reset_cancellation_state_1_t<Filter> reset) noexcept
{
struct result
{
detail::coro_cancellation_source* src_;
Filter filter_;
bool await_ready() const noexcept
{
return true;
}
void await_suspend(coroutine_handle<void>) noexcept
{
}
auto await_resume()
{
return src_->reset_cancellation_state(
static_cast<Filter&&>(filter_));
}
};
return result{cancel, static_cast<Filter&&>(reset.filter)};
}
// This await transformation resets the associated cancellation state.
template <typename InFilter, typename OutFilter>
auto await_transform(
this_coro::reset_cancellation_state_2_t<InFilter, OutFilter> reset)
noexcept
{
struct result
{
detail::coro_cancellation_source* src_;
InFilter in_filter_;
OutFilter out_filter_;
bool await_ready() const noexcept
{
return true;
}
void await_suspend(coroutine_handle<void>) noexcept
{
}
auto await_resume()
{
return src_->reset_cancellation_state(
static_cast<InFilter&&>(in_filter_),
static_cast<OutFilter&&>(out_filter_));
}
};
return result{cancel,
static_cast<InFilter&&>(reset.in_filter),
static_cast<OutFilter&&>(reset.out_filter)};
}
// This await transformation determines whether cancellation is propagated as
// an exception.
auto await_transform(this_coro::throw_if_cancelled_0_t) noexcept
requires (!is_noexcept)
{
struct result
{
detail::coro_cancellation_source* src_;
bool await_ready() const noexcept
{
return true;
}
void await_suspend(coroutine_handle<void>) noexcept
{
}
auto await_resume()
{
return src_->throw_if_cancelled();
}
};
return result{cancel};
}
// This await transformation sets whether cancellation is propagated as an
// exception.
auto await_transform(
this_coro::throw_if_cancelled_1_t throw_if_cancelled) noexcept
requires (!is_noexcept)
{
struct result
{
detail::coro_cancellation_source* src_;
bool value_;
bool await_ready() const noexcept
{
return true;
}
void await_suspend(coroutine_handle<void>) noexcept
{
}
auto await_resume()
{
src_->throw_if_cancelled(value_);
}
};
return result{cancel, throw_if_cancelled.value};
}
template <typename Yield_, typename Return_,
typename Executor_, typename Allocator_>
auto await_transform(coro<Yield_, Return_, Executor_, Allocator_>& kr)
-> decltype(auto)
{
return kr;
}
template <typename Yield_, typename Return_,
typename Executor_, typename Allocator_>
auto await_transform(coro<Yield_, Return_, Executor_, Allocator_>&& kr)
{
return std::move(kr);
}
template <typename T_, typename Coroutine >
auto await_transform(coro_with_arg<T_, Coroutine>&& kr) -> decltype(auto)
{
return std::move(kr);
}
template <typename T_>
requires requires(T_ t) {{ t.async_wait(deferred) }; }
auto await_transform(T_& t) -> decltype(auto)
{
return await_transform(t.async_wait(deferred));
}
template <typename Op>
auto await_transform(Op&& op,
constraint_t<is_async_operation<Op>::value> = 0)
{
if ((cancel->state.cancelled() != cancellation_type::none)
&& cancel->throw_if_cancelled_)
{
asio::detail::throw_error(
asio::error::operation_aborted, "coro-cancelled");
}
using signature = completion_signature_of_t<Op>;
using result_type = detail::coro_completion_handler_type_t<signature>;
using handler_type =
typename detail::coro_completion_handler_type<signature>::template
completion_handler<coro_promise>;
struct aw_t
{
Op op;
std::optional<result_type> result;
constexpr static bool await_ready()
{
return false;
}
void await_suspend(coroutine_handle<coro_promise> h)
{
std::move(op)(handler_type{h, result});
}
auto await_resume()
{
if constexpr (is_noexcept)
{
if constexpr (std::tuple_size_v<result_type> == 0u)
return;
else if constexpr (std::tuple_size_v<result_type> == 1u)
return std::get<0>(std::move(result).value());
else
return std::move(result).value();
}
else
return detail::coro_interpret_result(std::move(result).value());
}
};
return aw_t{std::move(op), {}};
}
};
} // namespace detail
template <typename Yield, typename Return,
typename Executor, typename Allocator>
struct coro<Yield, Return, Executor, Allocator>::awaitable_t
{
coro& coro_;
constexpr static bool await_ready() { return false; }
template <typename Y, typename R, typename E, typename A>
auto await_suspend(
detail::coroutine_handle<detail::coro_promise<Y, R, E, A>> h)
-> detail::coroutine_handle<>
{
auto& hp = h.promise();
if constexpr (!detail::coro_promise<Y, R, E, A>::is_noexcept)
{
if ((hp.cancel->state.cancelled() != cancellation_type::none)
&& hp.cancel->throw_if_cancelled_)
{
asio::detail::throw_error(
asio::error::operation_aborted, "coro-cancelled");
}
}
if (hp.get_executor() == coro_.get_executor())
{
coro_.coro_->awaited_from = h;
coro_.coro_->cancel = hp.cancel;
coro_.coro_->reset_error();
return coro_.coro_->get_handle();
}
else
{
coro_.coro_->awaited_from = detail::dispatch_coroutine(
asio::prefer(hp.get_executor(),
execution::outstanding_work.tracked),
[h]() mutable
{
h.resume();
}).handle;
coro_.coro_->reset_error();
struct cancel_handler
{
std::shared_ptr<std::pair<cancellation_signal,
detail::coro_cancellation_source>> st = std::make_shared<
std::pair<cancellation_signal, detail::coro_cancellation_source>>();
cancel_handler(E e, coro& coro) : e(e), coro_(coro.coro_)
{
st->second.state = cancellation_state(
st->second.slot = st->first.slot());
}
E e;
typename coro::promise_type* coro_;
void operator()(cancellation_type ct)
{
asio::dispatch(e,
[ct, st = st]() mutable
{
auto & [sig, state] = *st;
sig.emit(ct);
});
}
};
if (hp.cancel->state.slot().is_connected())
{
hp.cancel->state.slot().template emplace<cancel_handler>(
coro_.get_executor(), coro_);
}
auto hh = detail::coroutine_handle<
detail::coro_promise<Yield, Return, Executor, Allocator>>::from_promise(
*coro_.coro_);
return detail::dispatch_coroutine(
coro_.coro_->get_executor(),
[hh]() mutable { hh.resume(); }).handle;
}
}
auto await_resume() -> result_type
{
coro_.coro_->cancel = nullptr;
coro_.coro_->rethrow_if();
if constexpr (!std::is_void_v<result_type>)
return std::move(coro_.coro_->result_);
}
};
template <typename Yield, typename Return,
typename Executor, typename Allocator>
struct coro<Yield, Return, Executor, Allocator>::initiate_async_resume
{
typedef Executor executor_type;
typedef Allocator allocator_type;
typedef asio::cancellation_slot cancellation_slot_type;
explicit initiate_async_resume(coro* self)
: coro_(self->coro_)
{
}
executor_type get_executor() const noexcept
{
return coro_->get_executor();
}
allocator_type get_allocator() const noexcept
{
return coro_->get_allocator();
}
template <typename E, typename WaitHandler>
auto handle(E exec, WaitHandler&& handler,
std::true_type /* error is noexcept */,
std::true_type /* result is void */) //noexcept
{
return [this, the_coro = coro_,
h = std::forward<WaitHandler>(handler),
exec = std::move(exec)]() mutable
{
assert(the_coro);
auto ch = detail::coroutine_handle<promise_type>::from_promise(*the_coro);
assert(ch && !ch.done());
the_coro->awaited_from = post_coroutine(std::move(exec), std::move(h));
the_coro->reset_error();
ch.resume();
};
}
template <typename E, typename WaitHandler>
requires (!std::is_void_v<result_type>)
auto handle(E exec, WaitHandler&& handler,
std::true_type /* error is noexcept */,
std::false_type /* result is void */) //noexcept
{
return [the_coro = coro_,
h = std::forward<WaitHandler>(handler),
exec = std::move(exec)]() mutable
{
assert(the_coro);
auto ch = detail::coroutine_handle<promise_type>::from_promise(*the_coro);
assert(ch && !ch.done());
the_coro->awaited_from = detail::post_coroutine(
exec, std::move(h), the_coro->result_).handle;
the_coro->reset_error();
ch.resume();
};
}
template <typename E, typename WaitHandler>
auto handle(E exec, WaitHandler&& handler,
std::false_type /* error is noexcept */,
std::true_type /* result is void */)
{
return [the_coro = coro_,
h = std::forward<WaitHandler>(handler),
exec = std::move(exec)]() mutable
{
if (!the_coro)
return asio::post(exec,
asio::append(std::move(h),
detail::coro_error<error_type>::invalid()));
auto ch = detail::coroutine_handle<promise_type>::from_promise(*the_coro);
if (!ch)
return asio::post(exec,
asio::append(std::move(h),
detail::coro_error<error_type>::invalid()));
else if (ch.done())
return asio::post(exec,
asio::append(std::move(h),
detail::coro_error<error_type>::done()));
else
{
the_coro->awaited_from = detail::post_coroutine(
exec, std::move(h), the_coro->error_).handle;
the_coro->reset_error();
ch.resume();
}
};
}
template <typename E, typename WaitHandler>
auto handle(E exec, WaitHandler&& handler,
std::false_type /* error is noexcept */,
std::false_type /* result is void */)
{
return [the_coro = coro_,
h = std::forward<WaitHandler>(handler),
exec = std::move(exec)]() mutable
{
if (!the_coro)
return asio::post(exec,
asio::append(std::move(h),
detail::coro_error<error_type>::invalid(), result_type{}));
auto ch =
detail::coroutine_handle<promise_type>::from_promise(*the_coro);
if (!ch)
return asio::post(exec,
asio::append(std::move(h),
detail::coro_error<error_type>::invalid(), result_type{}));
else if (ch.done())
return asio::post(exec,
asio::append(std::move(h),
detail::coro_error<error_type>::done(), result_type{}));
else
{
the_coro->awaited_from = detail::post_coroutine(
exec, std::move(h), the_coro->error_, the_coro->result_).handle;
the_coro->reset_error();
ch.resume();
}
};
}
template <typename WaitHandler>
void operator()(WaitHandler&& handler)
{
const auto exec = asio::prefer(
get_associated_executor(handler, get_executor()),
execution::outstanding_work.tracked);
coro_->cancel = &coro_->cancel_source.emplace();
coro_->cancel->state = cancellation_state(
coro_->cancel->slot = get_associated_cancellation_slot(handler));
asio::dispatch(get_executor(),
handle(exec, std::forward<WaitHandler>(handler),
std::integral_constant<bool, is_noexcept>{},
std::is_void<result_type>{}));
}
template <typename WaitHandler, typename Input>
void operator()(WaitHandler&& handler, Input&& input)
{
const auto exec = asio::prefer(
get_associated_executor(handler, get_executor()),
execution::outstanding_work.tracked);
coro_->cancel = &coro_->cancel_source.emplace();
coro_->cancel->state = cancellation_state(
coro_->cancel->slot = get_associated_cancellation_slot(handler));
asio::dispatch(get_executor(),
[h = handle(exec, std::forward<WaitHandler>(handler),
std::integral_constant<bool, is_noexcept>{},
std::is_void<result_type>{}),
in = std::forward<Input>(input), the_coro = coro_]() mutable
{
the_coro->input_ = std::move(in);
std::move(h)();
});
}
private:
typename coro::promise_type* coro_;
};
} // namespace experimental
} // namespace asio
#include "asio/detail/pop_options.hpp"
#endif // ASIO_EXPERIMENTAL_IMPL_CORO_HPP
|
0 | repos/asio/asio/include/asio/experimental | repos/asio/asio/include/asio/experimental/impl/use_promise.hpp | //
// experimental/impl/use_promise.hpp
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2021-2023 Klemens D. Morgenstern
// (klemens dot morgenstern at gmx dot net)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef ASIO_EXPERIMENTAL_IMPL_USE_PROMISE_HPP
#define ASIO_EXPERIMENTAL_IMPL_USE_PROMISE_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include "asio/detail/config.hpp"
#include <memory>
#include "asio/async_result.hpp"
#include "asio/detail/push_options.hpp"
namespace asio {
namespace experimental {
template <typename Allocator>
struct use_promise_t;
namespace detail {
template<typename Signature, typename Executor, typename Allocator>
struct promise_handler;
} // namespace detail
} // namespace experimental
#if !defined(GENERATING_DOCUMENTATION)
template <typename Allocator, typename R, typename... Args>
struct async_result<experimental::use_promise_t<Allocator>, R(Args...)>
{
template <typename Initiation, typename... InitArgs>
static auto initiate(Initiation initiation,
experimental::use_promise_t<Allocator> up, InitArgs... args)
-> experimental::promise<void(decay_t<Args>...),
asio::associated_executor_t<Initiation>, Allocator>
{
using handler_type = experimental::detail::promise_handler<
void(decay_t<Args>...),
asio::associated_executor_t<Initiation>, Allocator>;
handler_type ht{up.get_allocator(), get_associated_executor(initiation)};
std::move(initiation)(ht, std::move(args)...);
return ht.make_promise();
}
};
#endif // !defined(GENERATING_DOCUMENTATION)
} // namespace asio
#include "asio/detail/pop_options.hpp"
#endif // ASIO_EXPERIMENTAL_IMPL_USE_PROMISE_HPP
|
0 | repos/asio/asio/include/asio/experimental | repos/asio/asio/include/asio/experimental/impl/as_single.hpp | //
// experimental/impl/as_single.hpp
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef ASIO_IMPL_EXPERIMENTAL_AS_SINGLE_HPP
#define ASIO_IMPL_EXPERIMENTAL_AS_SINGLE_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include "asio/detail/config.hpp"
#include <tuple>
#include "asio/associator.hpp"
#include "asio/async_result.hpp"
#include "asio/detail/handler_cont_helpers.hpp"
#include "asio/detail/initiation_base.hpp"
#include "asio/detail/type_traits.hpp"
#include "asio/detail/push_options.hpp"
namespace asio {
namespace experimental {
namespace detail {
// Class to adapt a as_single_t as a completion handler.
template <typename Handler>
class as_single_handler
{
public:
typedef void result_type;
template <typename CompletionToken>
as_single_handler(as_single_t<CompletionToken> e)
: handler_(static_cast<CompletionToken&&>(e.token_))
{
}
template <typename RedirectedHandler>
as_single_handler(RedirectedHandler&& h)
: handler_(static_cast<RedirectedHandler&&>(h))
{
}
void operator()()
{
static_cast<Handler&&>(handler_)();
}
template <typename Arg>
void operator()(Arg&& arg)
{
static_cast<Handler&&>(handler_)(static_cast<Arg&&>(arg));
}
template <typename... Args>
void operator()(Args&&... args)
{
static_cast<Handler&&>(handler_)(
std::make_tuple(static_cast<Args&&>(args)...));
}
//private:
Handler handler_;
};
template <typename Handler>
inline bool asio_handler_is_continuation(
as_single_handler<Handler>* this_handler)
{
return asio_handler_cont_helpers::is_continuation(
this_handler->handler_);
}
template <typename Signature>
struct as_single_signature
{
typedef Signature type;
};
template <typename R>
struct as_single_signature<R()>
{
typedef R type();
};
template <typename R, typename Arg>
struct as_single_signature<R(Arg)>
{
typedef R type(Arg);
};
template <typename R, typename... Args>
struct as_single_signature<R(Args...)>
{
typedef R type(std::tuple<decay_t<Args>...>);
};
} // namespace detail
} // namespace experimental
#if !defined(GENERATING_DOCUMENTATION)
template <typename CompletionToken, typename Signature>
struct async_result<experimental::as_single_t<CompletionToken>, Signature>
{
template <typename Initiation>
struct init_wrapper : detail::initiation_base<Initiation>
{
using detail::initiation_base<Initiation>::initiation_base;
template <typename Handler, typename... Args>
void operator()(Handler&& handler, Args&&... args) &&
{
static_cast<Initiation&&>(*this)(
experimental::detail::as_single_handler<decay_t<Handler>>(
static_cast<Handler&&>(handler)),
static_cast<Args&&>(args)...);
}
template <typename Handler, typename... Args>
void operator()(Handler&& handler, Args&&... args) const &
{
static_cast<const Initiation&>(*this)(
experimental::detail::as_single_handler<decay_t<Handler>>(
static_cast<Handler&&>(handler)),
static_cast<Args&&>(args)...);
}
};
template <typename Initiation, typename RawCompletionToken, typename... Args>
static auto initiate(Initiation&& initiation,
RawCompletionToken&& token, Args&&... args)
-> decltype(
async_initiate<CompletionToken,
typename experimental::detail::as_single_signature<Signature>::type>(
init_wrapper<decay_t<Initiation>>(
static_cast<Initiation&&>(initiation)),
token.token_, static_cast<Args&&>(args)...))
{
return async_initiate<CompletionToken,
typename experimental::detail::as_single_signature<Signature>::type>(
init_wrapper<decay_t<Initiation>>(
static_cast<Initiation&&>(initiation)),
token.token_, static_cast<Args&&>(args)...);
}
};
template <template <typename, typename> class Associator,
typename Handler, typename DefaultCandidate>
struct associator<Associator,
experimental::detail::as_single_handler<Handler>, DefaultCandidate>
: Associator<Handler, DefaultCandidate>
{
static typename Associator<Handler, DefaultCandidate>::type get(
const experimental::detail::as_single_handler<Handler>& h) noexcept
{
return Associator<Handler, DefaultCandidate>::get(h.handler_);
}
static auto get(const experimental::detail::as_single_handler<Handler>& 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)
} // namespace asio
#include "asio/detail/pop_options.hpp"
#endif // ASIO_IMPL_EXPERIMENTAL_AS_SINGLE_HPP
|
0 | repos/asio/asio/include/asio | repos/asio/asio/include/asio/local/datagram_protocol.hpp | //
// local/datagram_protocol.hpp
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef ASIO_LOCAL_DATAGRAM_PROTOCOL_HPP
#define ASIO_LOCAL_DATAGRAM_PROTOCOL_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include "asio/detail/config.hpp"
#if defined(ASIO_HAS_LOCAL_SOCKETS) \
|| defined(GENERATING_DOCUMENTATION)
#include "asio/basic_datagram_socket.hpp"
#include "asio/detail/socket_types.hpp"
#include "asio/local/basic_endpoint.hpp"
#include "asio/detail/push_options.hpp"
namespace asio {
namespace local {
/// Encapsulates the flags needed for datagram-oriented UNIX sockets.
/**
* The asio::local::datagram_protocol class contains flags necessary for
* datagram-oriented UNIX domain sockets.
*
* @par Thread Safety
* @e Distinct @e objects: Safe.@n
* @e Shared @e objects: Safe.
*
* @par Concepts:
* Protocol.
*/
class datagram_protocol
{
public:
/// Obtain an identifier for the type of the protocol.
int type() const noexcept
{
return SOCK_DGRAM;
}
/// Obtain an identifier for the protocol.
int protocol() const noexcept
{
return 0;
}
/// Obtain an identifier for the protocol family.
int family() const noexcept
{
return AF_UNIX;
}
/// The type of a UNIX domain endpoint.
typedef basic_endpoint<datagram_protocol> endpoint;
/// The UNIX domain socket type.
typedef basic_datagram_socket<datagram_protocol> socket;
};
} // namespace local
} // namespace asio
#include "asio/detail/pop_options.hpp"
#endif // defined(ASIO_HAS_LOCAL_SOCKETS)
// || defined(GENERATING_DOCUMENTATION)
#endif // ASIO_LOCAL_DATAGRAM_PROTOCOL_HPP
|
0 | repos/asio/asio/include/asio | repos/asio/asio/include/asio/local/stream_protocol.hpp | //
// local/stream_protocol.hpp
// ~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef ASIO_LOCAL_STREAM_PROTOCOL_HPP
#define ASIO_LOCAL_STREAM_PROTOCOL_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include "asio/detail/config.hpp"
#if defined(ASIO_HAS_LOCAL_SOCKETS) \
|| defined(GENERATING_DOCUMENTATION)
#include "asio/basic_socket_acceptor.hpp"
#include "asio/basic_socket_iostream.hpp"
#include "asio/basic_stream_socket.hpp"
#include "asio/detail/socket_types.hpp"
#include "asio/local/basic_endpoint.hpp"
#include "asio/detail/push_options.hpp"
namespace asio {
namespace local {
/// Encapsulates the flags needed for stream-oriented UNIX sockets.
/**
* The asio::local::stream_protocol class contains flags necessary for
* stream-oriented UNIX domain sockets.
*
* @par Thread Safety
* @e Distinct @e objects: Safe.@n
* @e Shared @e objects: Safe.
*
* @par Concepts:
* Protocol.
*/
class stream_protocol
{
public:
/// Obtain an identifier for the type of the protocol.
int type() const noexcept
{
return SOCK_STREAM;
}
/// Obtain an identifier for the protocol.
int protocol() const noexcept
{
return 0;
}
/// Obtain an identifier for the protocol family.
int family() const noexcept
{
return AF_UNIX;
}
/// The type of a UNIX domain endpoint.
typedef basic_endpoint<stream_protocol> endpoint;
/// The UNIX domain socket type.
typedef basic_stream_socket<stream_protocol> socket;
/// The UNIX domain acceptor type.
typedef basic_socket_acceptor<stream_protocol> acceptor;
#if !defined(ASIO_NO_IOSTREAM)
/// The UNIX domain iostream type.
typedef basic_socket_iostream<stream_protocol> iostream;
#endif // !defined(ASIO_NO_IOSTREAM)
};
} // namespace local
} // namespace asio
#include "asio/detail/pop_options.hpp"
#endif // defined(ASIO_HAS_LOCAL_SOCKETS)
// || defined(GENERATING_DOCUMENTATION)
#endif // ASIO_LOCAL_STREAM_PROTOCOL_HPP
|
0 | repos/asio/asio/include/asio | repos/asio/asio/include/asio/local/connect_pair.hpp | //
// local/connect_pair.hpp
// ~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef ASIO_LOCAL_CONNECT_PAIR_HPP
#define ASIO_LOCAL_CONNECT_PAIR_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include "asio/detail/config.hpp"
#if defined(ASIO_HAS_LOCAL_SOCKETS) \
|| defined(GENERATING_DOCUMENTATION)
#include "asio/basic_socket.hpp"
#include "asio/detail/socket_ops.hpp"
#include "asio/detail/throw_error.hpp"
#include "asio/error.hpp"
#include "asio/local/basic_endpoint.hpp"
#include "asio/detail/push_options.hpp"
namespace asio {
namespace local {
/// Create a pair of connected sockets.
template <typename Protocol, typename Executor1, typename Executor2>
void connect_pair(basic_socket<Protocol, Executor1>& socket1,
basic_socket<Protocol, Executor2>& socket2);
/// Create a pair of connected sockets.
template <typename Protocol, typename Executor1, typename Executor2>
ASIO_SYNC_OP_VOID connect_pair(basic_socket<Protocol, Executor1>& socket1,
basic_socket<Protocol, Executor2>& socket2, asio::error_code& ec);
template <typename Protocol, typename Executor1, typename Executor2>
inline void connect_pair(basic_socket<Protocol, Executor1>& socket1,
basic_socket<Protocol, Executor2>& socket2)
{
asio::error_code ec;
connect_pair(socket1, socket2, ec);
asio::detail::throw_error(ec, "connect_pair");
}
template <typename Protocol, typename Executor1, typename Executor2>
inline ASIO_SYNC_OP_VOID connect_pair(
basic_socket<Protocol, Executor1>& socket1,
basic_socket<Protocol, Executor2>& socket2, asio::error_code& ec)
{
// Check that this function is only being used with a UNIX domain socket.
asio::local::basic_endpoint<Protocol>* tmp
= static_cast<typename Protocol::endpoint*>(0);
(void)tmp;
Protocol protocol;
asio::detail::socket_type sv[2];
if (asio::detail::socket_ops::socketpair(protocol.family(),
protocol.type(), protocol.protocol(), sv, ec)
== asio::detail::socket_error_retval)
ASIO_SYNC_OP_VOID_RETURN(ec);
socket1.assign(protocol, sv[0], ec);
if (ec)
{
asio::error_code temp_ec;
asio::detail::socket_ops::state_type state[2] = { 0, 0 };
asio::detail::socket_ops::close(sv[0], state[0], true, temp_ec);
asio::detail::socket_ops::close(sv[1], state[1], true, temp_ec);
ASIO_SYNC_OP_VOID_RETURN(ec);
}
socket2.assign(protocol, sv[1], ec);
if (ec)
{
asio::error_code temp_ec;
socket1.close(temp_ec);
asio::detail::socket_ops::state_type state = 0;
asio::detail::socket_ops::close(sv[1], state, true, temp_ec);
ASIO_SYNC_OP_VOID_RETURN(ec);
}
ASIO_SYNC_OP_VOID_RETURN(ec);
}
} // namespace local
} // namespace asio
#include "asio/detail/pop_options.hpp"
#endif // defined(ASIO_HAS_LOCAL_SOCKETS)
// || defined(GENERATING_DOCUMENTATION)
#endif // ASIO_LOCAL_CONNECT_PAIR_HPP
|
0 | repos/asio/asio/include/asio | repos/asio/asio/include/asio/local/seq_packet_protocol.hpp | //
// local/seq_packet_protocol.hpp
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef ASIO_LOCAL_SEQ_PACKET_PROTOCOL_HPP
#define ASIO_LOCAL_SEQ_PACKET_PROTOCOL_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include "asio/detail/config.hpp"
#if defined(ASIO_HAS_LOCAL_SOCKETS) \
|| defined(GENERATING_DOCUMENTATION)
#include "asio/basic_socket_acceptor.hpp"
#include "asio/basic_seq_packet_socket.hpp"
#include "asio/detail/socket_types.hpp"
#include "asio/local/basic_endpoint.hpp"
#include "asio/detail/push_options.hpp"
namespace asio {
namespace local {
/// Encapsulates the flags needed for seq_packet UNIX sockets.
/**
* The asio::local::seq_packet_protocol class contains flags necessary
* for sequenced packet UNIX domain sockets.
*
* @par Thread Safety
* @e Distinct @e objects: Safe.@n
* @e Shared @e objects: Safe.
*
* @par Concepts:
* Protocol.
*/
class seq_packet_protocol
{
public:
/// Obtain an identifier for the type of the protocol.
int type() const noexcept
{
return SOCK_SEQPACKET;
}
/// Obtain an identifier for the protocol.
int protocol() const noexcept
{
return 0;
}
/// Obtain an identifier for the protocol family.
int family() const noexcept
{
return AF_UNIX;
}
/// The type of a UNIX domain endpoint.
typedef basic_endpoint<seq_packet_protocol> endpoint;
/// The UNIX domain socket type.
typedef basic_seq_packet_socket<seq_packet_protocol> socket;
/// The UNIX domain acceptor type.
typedef basic_socket_acceptor<seq_packet_protocol> acceptor;
};
} // namespace local
} // namespace asio
#include "asio/detail/pop_options.hpp"
#endif // defined(ASIO_HAS_LOCAL_SOCKETS)
// || defined(GENERATING_DOCUMENTATION)
#endif // ASIO_LOCAL_SEQ_PACKET_PROTOCOL_HPP
|
0 | repos/asio/asio/include/asio | repos/asio/asio/include/asio/local/basic_endpoint.hpp | //
// local/basic_endpoint.hpp
// ~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com)
// Derived from a public domain implementation written by Daniel Casimiro.
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef ASIO_LOCAL_BASIC_ENDPOINT_HPP
#define ASIO_LOCAL_BASIC_ENDPOINT_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include "asio/detail/config.hpp"
#if defined(ASIO_HAS_LOCAL_SOCKETS) \
|| defined(GENERATING_DOCUMENTATION)
#include "asio/local/detail/endpoint.hpp"
#if !defined(ASIO_NO_IOSTREAM)
# include <iosfwd>
#endif // !defined(ASIO_NO_IOSTREAM)
#include "asio/detail/push_options.hpp"
namespace asio {
namespace local {
/// Describes an endpoint for a UNIX socket.
/**
* The asio::local::basic_endpoint class template describes an endpoint
* that may be associated with a particular UNIX socket.
*
* @par Thread Safety
* @e Distinct @e objects: Safe.@n
* @e Shared @e objects: Unsafe.
*
* @par Concepts:
* Endpoint.
*/
template <typename Protocol>
class basic_endpoint
{
public:
/// The protocol type associated with the endpoint.
typedef Protocol protocol_type;
/// The type of the endpoint structure. This type is dependent on the
/// underlying implementation of the socket layer.
#if defined(GENERATING_DOCUMENTATION)
typedef implementation_defined data_type;
#else
typedef asio::detail::socket_addr_type data_type;
#endif
/// Default constructor.
basic_endpoint() noexcept
{
}
/// Construct an endpoint using the specified path name.
basic_endpoint(const char* path_name)
: impl_(path_name)
{
}
/// Construct an endpoint using the specified path name.
basic_endpoint(const std::string& path_name)
: impl_(path_name)
{
}
#if defined(ASIO_HAS_STRING_VIEW)
/// Construct an endpoint using the specified path name.
basic_endpoint(string_view path_name)
: impl_(path_name)
{
}
#endif // defined(ASIO_HAS_STRING_VIEW)
/// Copy constructor.
basic_endpoint(const basic_endpoint& other)
: impl_(other.impl_)
{
}
/// Move constructor.
basic_endpoint(basic_endpoint&& other)
: impl_(other.impl_)
{
}
/// Assign from another endpoint.
basic_endpoint& operator=(const basic_endpoint& other)
{
impl_ = other.impl_;
return *this;
}
/// Move-assign from another endpoint.
basic_endpoint& operator=(basic_endpoint&& other)
{
impl_ = other.impl_;
return *this;
}
/// The protocol associated with the endpoint.
protocol_type protocol() const
{
return protocol_type();
}
/// Get the underlying endpoint in the native type.
data_type* data()
{
return impl_.data();
}
/// Get the underlying endpoint in the native type.
const data_type* data() const
{
return impl_.data();
}
/// Get the underlying size of the endpoint in the native type.
std::size_t size() const
{
return impl_.size();
}
/// Set the underlying size of the endpoint in the native type.
void resize(std::size_t new_size)
{
impl_.resize(new_size);
}
/// Get the capacity of the endpoint in the native type.
std::size_t capacity() const
{
return impl_.capacity();
}
/// Get the path associated with the endpoint.
std::string path() const
{
return impl_.path();
}
/// Set the path associated with the endpoint.
void path(const char* p)
{
impl_.path(p);
}
/// Set the path associated with the endpoint.
void path(const std::string& p)
{
impl_.path(p);
}
/// Compare two endpoints for equality.
friend bool operator==(const basic_endpoint<Protocol>& e1,
const basic_endpoint<Protocol>& e2)
{
return e1.impl_ == e2.impl_;
}
/// Compare two endpoints for inequality.
friend bool operator!=(const basic_endpoint<Protocol>& e1,
const basic_endpoint<Protocol>& e2)
{
return !(e1.impl_ == e2.impl_);
}
/// Compare endpoints for ordering.
friend bool operator<(const basic_endpoint<Protocol>& e1,
const basic_endpoint<Protocol>& e2)
{
return e1.impl_ < e2.impl_;
}
/// Compare endpoints for ordering.
friend bool operator>(const basic_endpoint<Protocol>& e1,
const basic_endpoint<Protocol>& e2)
{
return e2.impl_ < e1.impl_;
}
/// Compare endpoints for ordering.
friend bool operator<=(const basic_endpoint<Protocol>& e1,
const basic_endpoint<Protocol>& e2)
{
return !(e2 < e1);
}
/// Compare endpoints for ordering.
friend bool operator>=(const basic_endpoint<Protocol>& e1,
const basic_endpoint<Protocol>& e2)
{
return !(e1 < e2);
}
private:
// The underlying UNIX domain endpoint.
asio::local::detail::endpoint impl_;
};
/// Output an endpoint as a string.
/**
* Used to output a human-readable string for a specified endpoint.
*
* @param os The output stream to which the string will be written.
*
* @param endpoint The endpoint to be written.
*
* @return The output stream.
*
* @relates asio::local::basic_endpoint
*/
template <typename Elem, typename Traits, typename Protocol>
std::basic_ostream<Elem, Traits>& operator<<(
std::basic_ostream<Elem, Traits>& os,
const basic_endpoint<Protocol>& endpoint)
{
os << endpoint.path();
return os;
}
} // namespace local
} // namespace asio
#include "asio/detail/pop_options.hpp"
#endif // defined(ASIO_HAS_LOCAL_SOCKETS)
// || defined(GENERATING_DOCUMENTATION)
#endif // ASIO_LOCAL_BASIC_ENDPOINT_HPP
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.