text:
namespace boost {
namespace asio {
namespace detail {

template <typename Protocol, typename Reactor>
class reactive_socket_service
  : public boost::asio::detail::service_base<
      reactive_socket_service<Protocol, Reactor> >
{
public:
  // The protocol type.
  typedef Protocol protocol_type;

  // The endpoint type.
  typedef typename Protocol::endpoint endpoint_type;

  // The native type of a socket.
  typedef socket_type native_type;

  // The implementation type of the socket.
  class implementation_type
    : private boost::asio::detail::noncopyable
  {
  public:
    // Default constructor.
    implementation_type()
      : socket_(invalid_socket),
        flags_(0),
        protocol_(endpoint_type().protocol())
    {
    }

  private:
    // Only this service will have access to the internal values.
    friend class reactive_socket_service<Protocol, Reactor>;

    // The native socket representation.
    socket_type socket_;

    enum
    {
      // The user wants a non-blocking socket.
      user_set_non_blocking = 1,

      // The implementation wants a non-blocking socket (in order to be able to
      // perform asynchronous read and write operations).
      internal_non_blocking = 2,

      // Helper "flag" used to determine whether the socket is non-blocking.
      non_blocking = user_set_non_blocking | internal_non_blocking,

      // User wants connection_aborted errors, which are disabled by default.
      enable_connection_aborted = 4,

      // The user set the linger option. Needs to be checked when closing.
      user_set_linger = 8
    };

    // Flags indicating the current state of the socket.
    unsigned char flags_;

    // The protocol associated with the socket.
    protocol_type protocol_;

    // Per-descriptor data used by the reactor.
    typename Reactor::per_descriptor_data reactor_data_;
  };

  // The maximum number of buffers to support in a single operation.
  enum { max_buffers = 64 < max_iov_len ? 64 : max_iov_len };

  // Constructor.
  reactive_socket_service(boost::asio::io_service& io_service)
    : boost::asio::detail::service_base<
        reactive_socket_service<Protocol, Reactor> >(io_service),
      reactor_(boost::asio::use_service<Reactor>(io_service))
  {
    reactor_.init_task();
  }

  // Destroy all user-defined handler objects owned by the service.
  void shutdown_service()
  {
  }

  // Construct a new socket implementation.
  void construct(implementation_type& impl)
  {
    impl.socket_ = invalid_socket;
    impl.flags_ = 0;
  }

  // Destroy a socket implementation.
  void destroy(implementation_type& impl)
  {
    if (impl.socket_ != invalid_socket)
    {
      reactor_.close_descriptor(impl.socket_, impl.reactor_data_);

      if (impl.flags_ & implementation_type::non_blocking)
      {
        ioctl_arg_type non_blocking = 0;
        boost::system::error_code ignored_ec;
        socket_ops::ioctl(impl.socket_, FIONBIO, &non_blocking, ignored_ec);
        impl.flags_ &= ~implementation_type::non_blocking;
      }

      if (impl.flags_ & implementation_type::user_set_linger)
      {
        ::linger opt;
        opt.l_onoff = 0;
        opt.l_linger = 0;
        boost::system::error_code ignored_ec;
        socket_ops::setsockopt(impl.socket_,
            SOL_SOCKET, SO_LINGER, &opt, sizeof(opt), ignored_ec);
      }

      boost::system::error_code ignored_ec;
      socket_ops::close(impl.socket_, ignored_ec);

      impl.socket_ = invalid_socket;
    }
  }

  // Open a new socket implementation.
  boost::system::error_code open(implementation_type& impl,
      const protocol_type& protocol, boost::system::error_code& ec)
  {
    if (is_open(impl))
    {
      ec = boost::asio::error::already_open;
      return ec;
    }

    socket_holder sock(socket_ops::socket(protocol.family(),
          protocol.type(), protocol.protocol(), ec));
    if (sock.get() == invalid_socket)
      return ec;

    if (int err = reactor_.register_descriptor(sock.get(), impl.reactor_data_))
    {
      ec = boost::system::error_code(err,
          boost::asio::error::get_system_category());
      return ec;
    }

    impl.socket_ = sock.release();
    impl.flags_ = 0;
    impl.protocol_ = protocol;
    ec = boost::system::error_code();
    return ec;
  }

  // Assign a native socket to a socket implementation.
  boost::system::error_code assign(implementation_type& impl,
      const protocol_type& protocol, const native_type& native_socket,
      boost::system::error_code& ec)
  {
    if (is_open(impl))
    {
      ec = boost::asio::error::already_open;
      return ec;
    }

    if (int err = reactor_.register_descriptor(
          native_socket, impl.reactor_data_))
    {
      ec = boost::system::error_code(err,
          boost::asio::error::get_system_category());
      return ec;
    }

    impl.socket_ = native_socket;
    impl.flags_ = 0;
    impl.protocol_ = protocol;
    ec = boost::system::error_code();
    return ec;
  }

  // Determine whether the socket is open.
  bool is_open(const implementation_type& impl) const
  {
    return impl.socket_ != invalid_socket;
  }

  // Destroy a socket implementation.
  boost::system::error_code close(implementation_type& impl,
      boost::system::error_code& ec)
  {
    if (is_open(impl))
    {
      reactor_.close_descriptor(impl.socket_, impl.reactor_data_);

      if (impl.flags_ & implementation_type::non_blocking)
      {
        ioctl_arg_type non_blocking = 0;
        boost::system::error_code ignored_ec;
        socket_ops::ioctl(impl.socket_, FIONBIO, &non_blocking, ignored_ec);
        impl.flags_ &= ~implementation_type::non_blocking;
      }

      if (socket_ops::close(impl.socket_, ec) == socket_error_retval)
        return ec;

      impl.socket_ = invalid_socket;
    }

    ec = boost::system::error_code();
    return ec;
  }

  // Get the native socket representation.
  native_type native(implementation_type& impl)
  {
    return impl.socket_;
  }

  // Cancel all operations associated with the socket.
  boost::system::error_code cancel(implementation_type& impl,
      boost::system::error_code& ec)
  {
    if (!is_open(impl))
    {
      ec = boost::asio::error::bad_descriptor;
      return ec;
    }

    reactor_.cancel_ops(impl.socket_, impl.reactor_data_);
    ec = boost::system::error_code();
    return ec;
  }

  // Determine whether the socket is at the out-of-band data mark.
  bool at_mark(const implementation_type& impl,
      boost::system::error_code& ec) const
  {
    if (!is_open(impl))
    {
      ec = boost::asio::error::bad_descriptor;
      return false;
    }

    boost::asio::detail::ioctl_arg_type value = 0;
    socket_ops::ioctl(impl.socket_, SIOCATMARK, &value, ec);
#if defined(ENOTTY)
    if (ec.value() == ENOTTY)
      ec = boost::asio::error::not_socket;
#endif // defined(ENOTTY)
    return ec ? false : value != 0;
  }

  // Determine the number of bytes available for reading.
  std::size_t available(const implementation_type& impl,
      boost::system::error_code& ec) const
  {
    if (!is_open(impl))
    {
      ec = boost::asio::error::bad_descriptor;
      return 0;
    }

    boost::asio::detail::ioctl_arg_type value = 0;
    socket_ops::ioctl(impl.socket_, FIONREAD, &value, ec);
#if defined(ENOTTY)
    if (ec.value() == ENOTTY)
      ec = boost::asio::error::not_socket;
#endif // defined(ENOTTY)
    return ec ? static_cast<std::size_t>(0) : static_cast<std::size_t>(value);
  }

  // Bind the socket to the specified local endpoint.
  boost::system::error_code bind(implementation_type& impl,
      const endpoint_type& endpoint, boost::system::error_code& ec)
  {
    if (!is_open(impl))
    {
      ec = boost::asio::error::bad_descriptor;
      return ec;
    }

    socket_ops::bind(impl.socket_, endpoint.data(), endpoint.size(), ec);
    return ec;
  }

  // Place the socket into the state where it will listen for new connections.
  boost::system::error_code listen(implementation_type& impl, int backlog,
      boost::system::error_code& ec)
  {
    if (!is_open(impl))
    {
      ec = boost::asio::error::bad_descriptor;
      return ec;
    }

    socket_ops::listen(impl.socket_, backlog, ec);
    return ec;
  }

  // Set a socket option.
  template <typename Option>
  boost::system::error_code set_option(implementation_type& impl,
      const Option& option, boost::system::error_code& ec)
  {
    if (!is_open(impl))
    {
      ec = boost::asio::error::bad_descriptor;
      return ec;
    }

    if (option.level(impl.protocol_) == custom_socket_option_level
        && option.name(impl.protocol_) == enable_connection_aborted_option)
    {
      if (option.size(impl.protocol_) != sizeof(int))
      {
        ec = boost::asio::error::invalid_argument;
      }
      else
      {
        if (*reinterpret_cast<const int*>(option.data(impl.protocol_)))
          impl.flags_ |= implementation_type::enable_connection_aborted;
        else
          impl.flags_ &= ~implementation_type::enable_connection_aborted;
        ec = boost::system::error_code();
      }
      return ec;
    }
    else
    {
      if (option.level(impl.protocol_) == SOL_SOCKET
          && option.name(impl.protocol_) == SO_LINGER)
      {
        impl.flags_ |= implementation_type::user_set_linger;
      }

      socket_ops::setsockopt(impl.socket_,
          option.level(impl.protocol_), option.name(impl.protocol_),
          option.data(impl.protocol_), option.size(impl.protocol_), ec);

#if defined(__MACH__) && defined(__APPLE__) \
|| defined(__NetBSD__) || defined(__FreeBSD__) || defined(__OpenBSD__)
      // To implement portable behaviour for SO_REUSEADDR with UDP sockets we
      // need to also set SO_REUSEPORT on BSD-based platforms.
      if (!ec && impl.protocol_.type() == SOCK_DGRAM
          && option.level(impl.protocol_) == SOL_SOCKET
          && option.name(impl.protocol_) == SO_REUSEADDR)
      {
        boost::system::error_code ignored_ec;
        socket_ops::setsockopt(impl.socket_, SOL_SOCKET, SO_REUSEPORT,
            option.data(impl.protocol_), option.size(impl.protocol_),
            ignored_ec);
      }
#endif

      return ec;
    }
  }

  // Set a socket option.
  template <typename Option>
  boost::system::error_code get_option(const implementation_type& impl,
      Option& option, boost::system::error_code& ec) const
  {
    if (!is_open(impl))
    {
      ec = boost::asio::error::bad_descriptor;
      return ec;
    }

    if (option.level(impl.protocol_) == custom_socket_option_level
        && option.name(impl.protocol_) == enable_connection_aborted_option)
    {
      if (option.size(impl.protocol_) != sizeof(int))
      {
        ec = boost::asio::error::invalid_argument;
      }
      else
      {
        int* target = reinterpret_cast<int*>(option.data(impl.protocol_));
        if (impl.flags_ & implementation_type::enable_connection_aborted)
          *target = 1;
        else
          *target = 0;
        option.resize(impl.protocol_, sizeof(int));
        ec = boost::system::error_code();
      }
      return ec;
    }
    else
    {
      size_t size = option.size(impl.protocol_);
      socket_ops::getsockopt(impl.socket_,
          option.level(impl.protocol_), option.name(impl.protocol_),
          option.data(impl.protocol_), &size, ec);
      if (!ec)
        option.resize(impl.protocol_, size);
      return ec;
    }
  }

  // Perform an IO control command on the socket.
  template <typename IO_Control_Command>
  boost::system::error_code io_control(implementation_type& impl,
      IO_Control_Command& command, boost::system::error_code& ec)
  {
    if (!is_open(impl))
    {
      ec = boost::asio::error::bad_descriptor;
      return ec;
    }

    if (command.name() == static_cast<int>(FIONBIO))
    {
      // Flags are manipulated in a temporary variable so that the socket
      // implementation is not updated unless the ioctl operation succeeds.
      unsigned char new_flags = impl.flags_;
      if (*static_cast<ioctl_arg_type*>(command.data()))
        new_flags |= implementation_type::user_set_non_blocking;
      else
        new_flags &= ~implementation_type::user_set_non_blocking;

      // Perform ioctl on socket if the non-blocking state has changed.
      if (!(impl.flags_ & implementation_type::non_blocking)
          && (new_flags & implementation_type::non_blocking))
      {
        ioctl_arg_type non_blocking = 1;
        socket_ops::ioctl(impl.socket_, FIONBIO, &non_blocking, ec);
      }
      else if ((impl.flags_ & implementation_type::non_blocking)
          && !(new_flags & implementation_type::non_blocking))
      {
        ioctl_arg_type non_blocking = 0;
        socket_ops::ioctl(impl.socket_, FIONBIO, &non_blocking, ec);
      }
      else
      {
        ec = boost::system::error_code();
      }

      // Update socket implementation's flags only if successful.
      if (!ec)
        impl.flags_ = new_flags;
    }
    else
    {
      socket_ops::ioctl(impl.socket_, command.name(),
          static_cast<ioctl_arg_type*>(command.data()), ec);
    }
    return ec;
  }

  // Get the local endpoint.
  endpoint_type local_endpoint(const implementation_type& impl,
      boost::system::error_code& ec) const
  {
    if (!is_open(impl))
    {
      ec = boost::asio::error::bad_descriptor;
      return endpoint_type();
    }

    endpoint_type endpoint;
    std::size_t addr_len = endpoint.capacity();
    if (socket_ops::getsockname(impl.socket_, endpoint.data(), &addr_len, ec))
      return endpoint_type();
    endpoint.resize(addr_len);
    return endpoint;
  }

  // Get the remote endpoint.
  endpoint_type remote_endpoint(const implementation_type& impl,
      boost::system::error_code& ec) const
  {
    if (!is_open(impl))
    {
      ec = boost::asio::error::bad_descriptor;
      return endpoint_type();
    }

    endpoint_type endpoint;
    std::size_t addr_len = endpoint.capacity();
    if (socket_ops::getpeername(impl.socket_, endpoint.data(), &addr_len, ec))
      return endpoint_type();
    endpoint.resize(addr_len);
    return endpoint;
  }

  /// Disable sends or receives on the socket.
  boost::system::error_code shutdown(implementation_type& impl,
      socket_base::shutdown_type what, boost::system::error_code& ec)
  {
    if (!is_open(impl))
    {
      ec = boost::asio::error::bad_descriptor;
      return ec;
    }

    socket_ops::shutdown(impl.socket_, what, ec);
    return ec;
  }

  // Send the given data to the peer.
  template <typename ConstBufferSequence>
  size_t send(implementation_type& impl, const ConstBufferSequence& buffers,
      socket_base::message_flags flags, boost::system::error_code& ec)
  {
    if (!is_open(impl))
    {
      ec = boost::asio::error::bad_descriptor;
      return 0;
    }

    // Copy buffers into array.
    socket_ops::buf bufs[max_buffers];
    typename ConstBufferSequence::const_iterator iter = buffers.begin();
    typename ConstBufferSequence::const_iterator end = buffers.end();
    size_t i = 0;
    size_t total_buffer_size = 0;
    for (; iter != end && i < max_buffers; ++iter, ++i)
    {
      boost::asio::const_buffer buffer(*iter);
      socket_ops::init_buf(bufs[i],
          boost::asio::buffer_cast<const void*>(buffer),
          boost::asio::buffer_size(buffer));
      total_buffer_size += boost::asio::buffer_size(buffer);
    }

    // A request to receive 0 bytes on a stream socket is a no-op.
    if (impl.protocol_.type() == SOCK_STREAM && total_buffer_size == 0)
    {
      ec = boost::system::error_code();
      return 0;
    }

    // Send the data.
    for (;;)
    {
      // Try to complete the operation without blocking.
      int bytes_sent = socket_ops::send(impl.socket_, bufs, i, flags, ec);

      // Check if operation succeeded.
      if (bytes_sent >= 0)
        return bytes_sent;

      // Operation failed.
      if ((impl.flags_ & implementation_type::user_set_non_blocking)
          || (ec != boost::asio::error::would_block
            && ec != boost::asio::error::try_again))
        return 0;

      // Wait for socket to become ready.
      if (socket_ops::poll_write(impl.socket_, ec) < 0)
        return 0;
    }
  }

  // Wait until data can be sent without blocking.
  size_t send(implementation_type& impl, const null_buffers&,
      socket_base::message_flags, boost::system::error_code& ec)
  {
    if (!is_open(impl))
    {
      ec = boost::asio::error::bad_descriptor;
      return 0;
    }

    // Wait for socket to become ready.
    socket_ops::poll_write(impl.socket_, ec);

    return 0;
  }

  template <typename ConstBufferSequence, typename Handler>
  class send_operation :
    public handler_base_from_member<Handler>
  {
  public:
    send_operation(socket_type socket, boost::asio::io_service& io_service,
        const ConstBufferSequence& buffers, socket_base::message_flags flags,
        Handler handler)
      : handler_base_from_member<Handler>(handler),
        socket_(socket),
        io_service_(io_service),
        work_(io_service),
        buffers_(buffers),
        flags_(flags)
    {
    }

    bool perform(boost::system::error_code& ec,
        std::size_t& bytes_transferred)
    {
      // Check whether the operation was successful.
      if (ec)
      {
        bytes_transferred = 0;
        return true;
      }

      // Copy buffers into array.
      socket_ops::buf bufs[max_buffers];
      typename ConstBufferSequence::const_iterator iter = buffers_.begin();
      typename ConstBufferSequence::const_iterator end = buffers_.end();
      size_t i = 0;
      for (; iter != end && i < max_buffers; ++iter, ++i)
      {
        boost::asio::const_buffer buffer(*iter);
        socket_ops::init_buf(bufs[i],
            boost::asio::buffer_cast<const void*>(buffer),
            boost::asio::buffer_size(buffer));
      }

      // Send the data.
      int bytes = socket_ops::send(socket_, bufs, i, flags_, ec);

      // Check if we need to run the operation again.
      if (ec == boost::asio::error::would_block
          || ec == boost::asio::error::try_again)
        return false;

      bytes_transferred = (bytes < 0 ? 0 : bytes);
      return true;
    }

    void complete(const boost::system::error_code& ec,
        std::size_t bytes_transferred)
    {
      io_service_.post(bind_handler(this->handler_, ec, bytes_transferred));
    }

  private:
    socket_type socket_;
    boost::asio::io_service& io_service_;
    boost::asio::io_service::work work_;
    ConstBufferSequence buffers_;
    socket_base::message_flags flags_;
  };

  // Start an asynchronous send. The data being sent must be valid for the
  // lifetime of the asynchronous operation.
  template <typename ConstBufferSequence, typename Handler>
  void async_send(implementation_type& impl, const ConstBufferSequence& buffers,
      socket_base::message_flags flags, Handler handler)
  {
    if (!is_open(impl))
    {
      this->get_io_service().post(bind_handler(handler,
            boost::asio::error::bad_descriptor, 0));
    }
    else
    {
      if (impl.protocol_.type() == SOCK_STREAM)
      {
        // Determine total size of buffers.
        typename ConstBufferSequence::const_iterator iter = buffers.begin();
        typename ConstBufferSequence::const_iterator end = buffers.end();
        size_t i = 0;
        size_t total_buffer_size = 0;
        for (; iter != end && i < max_buffers; ++iter, ++i)
        {
          boost::asio::const_buffer buffer(*iter);
          total_buffer_size += boost::asio::buffer_size(buffer);
        }

        // A request to receive 0 bytes on a stream socket is a no-op.
        if (total_buffer_size == 0)
        {
          this->get_io_service().post(bind_handler(handler,
                boost::system::error_code(), 0));
          return;
        }
      }

      // Make socket non-blocking.
      if (!(impl.flags_ & implementation_type::internal_non_blocking))
      {
        if (!(impl.flags_ & implementation_type::non_blocking))
        {
          ioctl_arg_type non_blocking = 1;
          boost::system::error_code ec;
          if (socket_ops::ioctl(impl.socket_, FIONBIO, &non_blocking, ec))
          {
            this->get_io_service().post(bind_handler(handler, ec, 0));
            return;
          }
        }
        impl.flags_ |= implementation_type::internal_non_blocking;
      }

      reactor_.start_write_op(impl.socket_, impl.reactor_data_,
          send_operation<ConstBufferSequence, Handler>(
            impl.socket_, this->get_io_service(), buffers, flags, handler));
    }
  }

  template <typename Handler>
  class null_buffers_operation :
    public handler_base_from_member<Handler>
  {
  public:
    null_buffers_operation(boost::asio::io_service& io_service, Handler handler)
      : handler_base_from_member<Handler>(handler),
        work_(io_service)
    {
    }

    bool perform(boost::system::error_code&,
        std::size_t& bytes_transferred)
    {
      bytes_transferred = 0;
      return true;
    }

    void complete(const boost::system::error_code& ec,
        std::size_t bytes_transferred)
    {
      work_.get_io_service().post(bind_handler(
            this->handler_, ec, bytes_transferred));
    }

  private:
    boost::asio::io_service::work work_;
  };

  // Start an asynchronous wait until data can be sent without blocking.
  template <typename Handler>
  void async_send(implementation_type& impl, const null_buffers&,
      socket_base::message_flags, Handler handler)
  {
    if (!is_open(impl))
    {
      this->get_io_service().post(bind_handler(handler,
            boost::asio::error::bad_descriptor, 0));
    }
    else
    {
      reactor_.start_write_op(impl.socket_, impl.reactor_data_,
          null_buffers_operation<Handler>(this->get_io_service(), handler),
          false);
    }
  }

  // Send a datagram to the specified endpoint. Returns the number of bytes
  // sent.
  template <typename ConstBufferSequence>
  size_t send_to(implementation_type& impl, const ConstBufferSequence& buffers,
      const endpoint_type& destination, socket_base::message_flags flags,
      boost::system::error_code& ec)
  {
    if (!is_open(impl))
    {
      ec = boost::asio::error::bad_descriptor;
      return 0;
    }

    // Copy buffers into array.
    socket_ops::buf bufs[max_buffers];
    typename ConstBufferSequence::const_iterator iter = buffers.begin();
    typename ConstBufferSequence::const_iterator end = buffers.end();
    size_t i = 0;
    for (; iter != end && i < max_buffers; ++iter, ++i)
    {
      boost::asio::const_buffer buffer(*iter);
      socket_ops::init_buf(bufs[i],
          boost::asio::buffer_cast<const void*>(buffer),
          boost::asio::buffer_size(buffer));
    }

    // Send the data.
    for (;;)
    {
      // Try to complete the operation without blocking.
      int bytes_sent = socket_ops::sendto(impl.socket_, bufs, i, flags,
          destination.data(), destination.size(), ec);

      // Check if operation succeeded.
      if (bytes_sent >= 0)
        return bytes_sent;

      // Operation failed.
      if ((impl.flags_ & implementation_type::user_set_non_blocking)
          || (ec != boost::asio::error::would_block
            && ec != boost::asio::error::try_again))
        return 0;

      // Wait for socket to become ready.
      if (socket_ops::poll_write(impl.socket_, ec) < 0)
        return 0;
    }
  }

  // Wait until data can be sent without blocking.
  size_t send_to(implementation_type& impl, const null_buffers&,
      socket_base::message_flags, const endpoint_type&,
      boost::system::error_code& ec)
  {
    if (!is_open(impl))
    {
      ec = boost::asio::error::bad_descriptor;
      return 0;
    }

    // Wait for socket to become ready.
    socket_ops::poll_write(impl.socket_, ec);

    return 0;
  }

  template <typename ConstBufferSequence, typename Handler>
  class send_to_operation :
    public handler_base_from_member<Handler>
  {
  public:
    send_to_operation(socket_type socket, boost::asio::io_service& io_service,
        const ConstBufferSequence& buffers, const endpoint_type& endpoint,
        socket_base::message_flags flags, Handler handler)
      : handler_base_from_member<Handler>(handler),
        socket_(socket),
        io_service_(io_service),
        work_(io_service),
        buffers_(buffers),
        destination_(endpoint),
        flags_(flags)
    {
    }

    bool perform(boost::system::error_code& ec,
        std::size_t& bytes_transferred)
    {
      // Check whether the operation was successful.
      if (ec)
      {
        bytes_transferred = 0;
        return true;
      }

      // Copy buffers into array.
      socket_ops::buf bufs[max_buffers];
      typename ConstBufferSequence::const_iterator iter = buffers_.begin();
      typename ConstBufferSequence::const_iterator end = buffers_.end();
      size_t i = 0;
      for (; iter != end && i < max_buffers; ++iter, ++i)
      {
        boost::asio::const_buffer buffer(*iter);
        socket_ops::init_buf(bufs[i],
            boost::asio::buffer_cast<const void*>(buffer),
            boost::asio::buffer_size(buffer));
      }

      // Send the data.
      int bytes = socket_ops::sendto(socket_, bufs, i, flags_,
          destination_.data(), destination_.size(), ec);

      // Check if we need to run the operation again.
      if (ec == boost::asio::error::would_block
          || ec == boost::asio::error::try_again)
        return false;

      bytes_transferred = (bytes < 0 ? 0 : bytes);
      return true;
    }

    void complete(const boost::system::error_code& ec,
        std::size_t bytes_transferred)
    {
      io_service_.post(bind_handler(this->handler_, ec, bytes_transferred));
    }

  private:
    socket_type socket_;
    boost::asio::io_service& io_service_;
    boost::asio::io_service::work work_;
    ConstBufferSequence buffers_;
    endpoint_type destination_;
    socket_base::message_flags flags_;
  };

  // Start an asynchronous send. The data being sent must be valid for the
  // lifetime of the asynchronous operation.
  template <typename ConstBufferSequence, typename Handler>
  void async_send_to(implementation_type& impl,
      const ConstBufferSequence& buffers,
      const endpoint_type& destination, socket_base::message_flags flags,
      Handler handler)
  {
    if (!is_open(impl))
    {
      this->get_io_service().post(bind_handler(handler,
            boost::asio::error::bad_descriptor, 0));
    }
    else
    {
      // Make socket non-blocking.
      if (!(impl.flags_ & implementation_type::internal_non_blocking))
      {
        if (!(impl.flags_ & implementation_type::non_blocking))
        {
          ioctl_arg_type non_blocking = 1;
          boost::system::error_code ec;
          if (socket_ops::ioctl(impl.socket_, FIONBIO, &non_blocking, ec))
          {
            this->get_io_service().post(bind_handler(handler, ec, 0));
            return;
          }
        }
        impl.flags_ |= implementation_type::internal_non_blocking;
      }

      reactor_.start_write_op(impl.socket_, impl.reactor_data_,
          send_to_operation<ConstBufferSequence, Handler>(
            impl.socket_, this->get_io_service(), buffers,
            destination, flags, handler));
    }
  }

  // Start an asynchronous wait until data can be sent without blocking.
  template <typename Handler>
  void async_send_to(implementation_type& impl, const null_buffers&,
      socket_base::message_flags, const endpoint_type&, Handler handler)
  {
    if (!is_open(impl))
    {
      this->get_io_service().post(bind_handler(handler,
            boost::asio::error::bad_descriptor, 0));
    }
    else
    {
      reactor_.start_write_op(impl.socket_, impl.reactor_data_,
          null_buffers_operation<Handler>(this->get_io_service(), handler),
          false);
    }
  }

  // Receive some data from the peer. Returns the number of bytes received.
  template <typename MutableBufferSequence>
  size_t receive(implementation_type& impl,
      const MutableBufferSequence& buffers,
      socket_base::message_flags flags, boost::system::error_code& ec)
  {
    if (!is_open(impl))
    {
      ec = boost::asio::error::bad_descriptor;
      return 0;
    }

    // Copy buffers into array.
    socket_ops::buf bufs[max_buffers];
    typename MutableBufferSequence::const_iterator iter = buffers.begin();
    typename MutableBufferSequence::const_iterator end = buffers.end();
    size_t i = 0;
    size_t total_buffer_size = 0;
    for (; iter != end && i < max_buffers; ++iter, ++i)
    {
      boost::asio::mutable_buffer buffer(*iter);
      socket_ops::init_buf(bufs[i],
          boost::asio::buffer_cast<void*>(buffer),
          boost::asio::buffer_size(buffer));
      total_buffer_size += boost::asio::buffer_size(buffer);
    }

    // A request to receive 0 bytes on a stream socket is a no-op.
    if (impl.protocol_.type() == SOCK_STREAM && total_buffer_size == 0)
    {
      ec = boost::system::error_code();
      return 0;
    }

    // Receive some data.
    for (;;)
    {
      // Try to complete the operation without blocking.
      int bytes_recvd = socket_ops::recv(impl.socket_, bufs, i, flags, ec);

      // Check if operation succeeded.
      if (bytes_recvd > 0)
        return bytes_recvd;

      // Check for EOF.
      if (bytes_recvd == 0 && impl.protocol_.type() == SOCK_STREAM)
      {
        ec = boost::asio::error::eof;
        return 0;
      }

      // Operation failed.
      if ((impl.flags_ & implementation_type::user_set_non_blocking)
          || (ec != boost::asio::error::would_block
            && ec != boost::asio::error::try_again))
        return 0;

      // Wait for socket to become ready.
      if (socket_ops::poll_read(impl.socket_, ec) < 0)
        return 0;
    }
  }

  // Wait until data can be received without blocking.
  size_t receive(implementation_type& impl, const null_buffers&,
      socket_base::message_flags, boost::system::error_code& ec)
  {
    if (!is_open(impl))
    {
      ec = boost::asio::error::bad_descriptor;
      return 0;
    }

    // Wait for socket to become ready.
    socket_ops::poll_read(impl.socket_, ec);

    return 0;
  }

  template <typename MutableBufferSequence, typename Handler>
  class receive_operation :
    public handler_base_from_member<Handler>
  {
  public:
    receive_operation(socket_type socket, int protocol_type,
        boost::asio::io_service& io_service,
        const MutableBufferSequence& buffers,
        socket_base::message_flags flags, Handler handler)
      : handler_base_from_member<Handler>(handler),
        socket_(socket),
        protocol_type_(protocol_type),
        io_service_(io_service),
        work_(io_service),
        buffers_(buffers),
        flags_(flags)
    {
    }

    bool perform(boost::system::error_code& ec,
        std::size_t& bytes_transferred)
    {
      // Check whether the operation was successful.
      if (ec)
      {
        bytes_transferred = 0;
        return true;
      }

      // Copy buffers into array.
      socket_ops::buf bufs[max_buffers];
      typename MutableBufferSequence::const_iterator iter = buffers_.begin();
      typename MutableBufferSequence::const_iterator end = buffers_.end();
      size_t i = 0;
      for (; iter != end && i < max_buffers; ++iter, ++i)
      {
        boost::asio::mutable_buffer buffer(*iter);
        socket_ops::init_buf(bufs[i],
            boost::asio::buffer_cast<void*>(buffer),
            boost::asio::buffer_size(buffer));
      }

      // Receive some data.
      int bytes = socket_ops::recv(socket_, bufs, i, flags_, ec);
      if (bytes == 0 && protocol_type_ == SOCK_STREAM)
        ec = boost::asio::error::eof;

      // Check if we need to run the operation again.
      if (ec == boost::asio::error::would_block
          || ec == boost::asio::error::try_again)
        return false;

      bytes_transferred = (bytes < 0 ? 0 : bytes);
      return true;
    }

    void complete(const boost::system::error_code& ec,
        std::size_t bytes_transferred)
    {
      io_service_.post(bind_handler(this->handler_, ec, bytes_transferred));
    }

  private:
    socket_type socket_;
    int protocol_type_;
    boost::asio::io_service& io_service_;
    boost::asio::io_service::work work_;
    MutableBufferSequence buffers_;
    socket_base::message_flags flags_;
  };

  // Start an asynchronous receive. The buffer for the data being received
  // must be valid for the lifetime of the asynchronous operation.
  template <typename MutableBufferSequence, typename Handler>
  void async_receive(implementation_type& impl,
      const MutableBufferSequence& buffers,
      socket_base::message_flags flags, Handler handler)
  {
    if (!is_open(impl))
    {
      this->get_io_service().post(bind_handler(handler,
            boost::asio::error::bad_descriptor, 0));
    }
    else
    {
      if (impl.protocol_.type() == SOCK_STREAM)
      {
        // Determine total size of buffers.
        typename MutableBufferSequence::const_iterator iter = buffers.begin();
        typename MutableBufferSequence::const_iterator end = buffers.end();
        size_t i = 0;
        size_t total_buffer_size = 0;
        for (; iter != end && i < max_buffers; ++iter, ++i)
        {
          boost::asio::mutable_buffer buffer(*iter);
          total_buffer_size += boost::asio::buffer_size(buffer);
        }

        // A request to receive 0 bytes on a stream socket is a no-op.
        if (total_buffer_size == 0)
        {
          this->get_io_service().post(bind_handler(handler,
                boost::system::error_code(), 0));
          return;
        }
      }

      // Make socket non-blocking.
      if (!(impl.flags_ & implementation_type::internal_non_blocking))
      {
        if (!(impl.flags_ & implementation_type::non_blocking))
        {
          ioctl_arg_type non_blocking = 1;
          boost::system::error_code ec;
          if (socket_ops::ioctl(impl.socket_, FIONBIO, &non_blocking, ec))
          {
            this->get_io_service().post(bind_handler(handler, ec, 0));
            return;
          }
        }
        impl.flags_ |= implementation_type::internal_non_blocking;
      }

      if (flags & socket_base::message_out_of_band)
      {
        reactor_.start_except_op(impl.socket_, impl.reactor_data_,
            receive_operation<MutableBufferSequence, Handler>(
              impl.socket_, impl.protocol_.type(),
              this->get_io_service(), buffers, flags, handler));
      }
      else
      {
        reactor_.start_read_op(impl.socket_, impl.reactor_data_,
            receive_operation<MutableBufferSequence, Handler>(
              impl.socket_, impl.protocol_.type(),
              this->get_io_service(), buffers, flags, handler));
      }
    }
  }

  // Wait until data can be received without blocking.
  template <typename Handler>
  void async_receive(implementation_type& impl, const null_buffers&,
      socket_base::message_flags flags, Handler handler)
  {
    if (!is_open(impl))
    {
      this->get_io_service().post(bind_handler(handler,
            boost::asio::error::bad_descriptor, 0));
    }
    else if (flags & socket_base::message_out_of_band)
    {
      reactor_.start_except_op(impl.socket_, impl.reactor_data_,
          null_buffers_operation<Handler>(this->get_io_service(), handler));
    }
    else
    {
      reactor_.start_read_op(impl.socket_, impl.reactor_data_,
          null_buffers_operation<Handler>(this->get_io_service(), handler),
          false);
    }
  }

  // Receive a datagram with the endpoint of the sender. Returns the number of
  // bytes received.
  template <typename MutableBufferSequence>
  size_t receive_from(implementation_type& impl,
      const MutableBufferSequence& buffers,
      endpoint_type& sender_endpoint, socket_base::message_flags flags,
      boost::system::error_code& ec)
  {
    if (!is_open(impl))
    {
      ec = boost::asio::error::bad_descriptor;
      return 0;
    }

    // Copy buffers into array.
    socket_ops::buf bufs[max_buffers];
    typename MutableBufferSequence::const_iterator iter = buffers.begin();
    typename MutableBufferSequence::const_iterator end = buffers.end();
    size_t i = 0;
    for (; iter != end && i < max_buffers; ++iter, ++i)
    {
      boost::asio::mutable_buffer buffer(*iter);
      socket_ops::init_buf(bufs[i],
          boost::asio::buffer_cast<void*>(buffer),
          boost::asio::buffer_size(buffer));
    }

    // Receive some data.
    for (;;)
    {
      // Try to complete the operation without blocking.
      std::size_t addr_len = sender_endpoint.capacity();
      int bytes_recvd = socket_ops::recvfrom(impl.socket_, bufs, i, flags,
          sender_endpoint.data(), &addr_len, ec);

      // Check if operation succeeded.
      if (bytes_recvd > 0)
      {
        sender_endpoint.resize(addr_len);
        return bytes_recvd;
      }

      // Check for EOF.
      if (bytes_recvd == 0 && impl.protocol_.type() == SOCK_STREAM)
      {
        ec = boost::asio::error::eof;
        return 0;
      }

      // Operation failed.
      if ((impl.flags_ & implementation_type::user_set_non_blocking)
          || (ec != boost::asio::error::would_block
            && ec != boost::asio::error::try_again))
        return 0;

      // Wait for socket to become ready.
      if (socket_ops::poll_read(impl.socket_, ec) < 0)
        return 0;
    }
  }

  // Wait until data can be received without blocking.
  size_t receive_from(implementation_type& impl, const null_buffers&,
      endpoint_type& sender_endpoint, socket_base::message_flags,
      boost::system::error_code& ec)
  {
    if (!is_open(impl))
    {
      ec = boost::asio::error::bad_descriptor;
      return 0;
    }

    // Wait for socket to become ready.
    socket_ops::poll_read(impl.socket_, ec);

    // Reset endpoint since it can be given no sensible value at this time.
    sender_endpoint = endpoint_type();

    return 0;
  }

  template <typename MutableBufferSequence, typename Handler>
  class receive_from_operation :
    public handler_base_from_member<Handler>
  {
  public:
    receive_from_operation(socket_type socket, int protocol_type,
        boost::asio::io_service& io_service,
        const MutableBufferSequence& buffers, endpoint_type& endpoint,
        socket_base::message_flags flags, Handler handler)
      : handler_base_from_member<Handler>(handler),
        socket_(socket),
        protocol_type_(protocol_type),
        io_service_(io_service),
        work_(io_service),
        buffers_(buffers),
        sender_endpoint_(endpoint),
        flags_(flags)
    {
    }

    bool perform(boost::system::error_code& ec,
        std::size_t& bytes_transferred)
    {
      // Check whether the operation was successful.
      if (ec)
      {
        bytes_transferred = 0;
        return true;
      }

      // Copy buffers into array.
      socket_ops::buf bufs[max_buffers];
      typename MutableBufferSequence::const_iterator iter = buffers_.begin();
      typename MutableBufferSequence::const_iterator end = buffers_.end();
      size_t i = 0;
      for (; iter != end && i < max_buffers; ++iter, ++i)
      {
        boost::asio::mutable_buffer buffer(*iter);
        socket_ops::init_buf(bufs[i],
            boost::asio::buffer_cast<void*>(buffer),
            boost::asio::buffer_size(buffer));
      }

      // Receive some data.
      std::size_t addr_len = sender_endpoint_.capacity();
      int bytes = socket_ops::recvfrom(socket_, bufs, i, flags_,
          sender_endpoint_.data(), &addr_len, ec);
      if (bytes == 0 && protocol_type_ == SOCK_STREAM)
        ec = boost::asio::error::eof;

      // Check if we need to run the operation again.
      if (ec == boost::asio::error::would_block
          || ec == boost::asio::error::try_again)
        return false;

      sender_endpoint_.resize(addr_len);
      bytes_transferred = (bytes < 0 ? 0 : bytes);
      return true;
    }

    void complete(const boost::system::error_code& ec,
        std::size_t bytes_transferred)
    {
      io_service_.post(bind_handler(this->handler_, ec, bytes_transferred));
    }

  private:
    socket_type socket_;
    int protocol_type_;
    boost::asio::io_service& io_service_;
    boost::asio::io_service::work work_;
    MutableBufferSequence buffers_;
    endpoint_type& sender_endpoint_;
    socket_base::message_flags flags_;
  };

  // Start an asynchronous receive. The buffer for the data being received and
  // the sender_endpoint object must both be valid for the lifetime of the
  // asynchronous operation.
  template <typename MutableBufferSequence, typename Handler>
  void async_receive_from(implementation_type& impl,
      const MutableBufferSequence& buffers, endpoint_type& sender_endpoint,
      socket_base::message_flags flags, Handler handler)
  {
    if (!is_open(impl))
    {
      this->get_io_service().post(bind_handler(handler,
            boost::asio::error::bad_descriptor, 0));
    }
    else
    {
      // Make socket non-blocking.
      if (!(impl.flags_ & implementation_type::internal_non_blocking))
      {
        if (!(impl.flags_ & implementation_type::non_blocking))
        {
          ioctl_arg_type non_blocking = 1;
          boost::system::error_code ec;
          if (socket_ops::ioctl(impl.socket_, FIONBIO, &non_blocking, ec))
          {
            this->get_io_service().post(bind_handler(handler, ec, 0));
            return;
          }
        }
        impl.flags_ |= implementation_type::internal_non_blocking;
      }

      reactor_.start_read_op(impl.socket_, impl.reactor_data_,
          receive_from_operation<MutableBufferSequence, Handler>(
            impl.socket_, impl.protocol_.type(), this->get_io_service(),
            buffers, sender_endpoint, flags, handler));
    }
  }

  // Wait until data can be received without blocking.
  template <typename Handler>
  void async_receive_from(implementation_type& impl,
      const null_buffers&, endpoint_type& sender_endpoint,
      socket_base::message_flags flags, Handler handler)
  {
    if (!is_open(impl))
    {
      this->get_io_service().post(bind_handler(handler,
            boost::asio::error::bad_descriptor, 0));
    }
    else
    {
      // Reset endpoint since it can be given no sensible value at this time.
      sender_endpoint = endpoint_type();

      if (flags & socket_base::message_out_of_band)
      {
        reactor_.start_except_op(impl.socket_, impl.reactor_data_,
            null_buffers_operation<Handler>(this->get_io_service(), handler));
      }
      else
      {
        reactor_.start_read_op(impl.socket_, impl.reactor_data_,
            null_buffers_operation<Handler>(this->get_io_service(), handler),
            false);
      }
    }
  }

  // Accept a new connection.
  template <typename Socket>
  boost::system::error_code accept(implementation_type& impl,
      Socket& peer, endpoint_type* peer_endpoint, boost::system::error_code& ec)
  {
    if (!is_open(impl))
    {
      ec = boost::asio::error::bad_descriptor;
      return ec;
    }

    // We cannot accept a socket that is already open.
    if (peer.is_open())
    {
      ec = boost::asio::error::already_open;
      return ec;
    }

    // Accept a socket.
    for (;;)
    {
      // Try to complete the operation without blocking.
      boost::system::error_code ec;
      socket_holder new_socket;
      std::size_t addr_len = 0;
      if (peer_endpoint)
      {
        addr_len = peer_endpoint->capacity();
        new_socket.reset(socket_ops::accept(impl.socket_,
              peer_endpoint->data(), &addr_len, ec));
      }
      else
      {
        new_socket.reset(socket_ops::accept(impl.socket_, 0, 0, ec));
      }

      // Check if operation succeeded.
      if (new_socket.get() >= 0)
      {
        if (peer_endpoint)
          peer_endpoint->resize(addr_len);
        peer.assign(impl.protocol_, new_socket.get(), ec);
        if (!ec)
          new_socket.release();
        return ec;
      }

      // Operation failed.
      if (ec == boost::asio::error::would_block
          || ec == boost::asio::error::try_again)
      {
        if (impl.flags_ & implementation_type::user_set_non_blocking)
          return ec;
        // Fall through to retry operation.
      }
      else if (ec == boost::asio::error::connection_aborted)
      {
        if (impl.flags_ & implementation_type::enable_connection_aborted)
          return ec;
        // Fall through to retry operation.
      }
#if defined(EPROTO)
      else if (ec.value() == EPROTO)
      {
        if (impl.flags_ & implementation_type::enable_connection_aborted)
          return ec;
        // Fall through to retry operation.
      }
#endif // defined(EPROTO)
      else
        return ec;

      // Wait for socket to become ready.
      if (socket_ops::poll_read(impl.socket_, ec) < 0)
        return ec;
    }
  }

  template <typename Socket, typename Handler>
  class accept_operation :
    public handler_base_from_member<Handler>
  {
  public:
    accept_operation(socket_type socket, boost::asio::io_service& io_service,
        Socket& peer, const protocol_type& protocol,
        endpoint_type* peer_endpoint, bool enable_connection_aborted,
        Handler handler)
      : handler_base_from_member<Handler>(handler),
        socket_(socket),
        io_service_(io_service),
        work_(io_service),
        peer_(peer),
        protocol_(protocol),
        peer_endpoint_(peer_endpoint),
        enable_connection_aborted_(enable_connection_aborted)
    {
    }

    bool perform(boost::system::error_code& ec, std::size_t&)
    {
      // Check whether the operation was successful.
      if (ec)
        return true;

      // Accept the waiting connection.
      socket_holder new_socket;
      std::size_t addr_len = 0;
      if (peer_endpoint_)
      {
        addr_len = peer_endpoint_->capacity();
        new_socket.reset(socket_ops::accept(socket_,
              peer_endpoint_->data(), &addr_len, ec));
      }
      else
      {
        new_socket.reset(socket_ops::accept(socket_, 0, 0, ec));
      }

      // Check if we need to run the operation again.
      if (ec == boost::asio::error::would_block
          || ec == boost::asio::error::try_again)
        return false;
      if (ec == boost::asio::error::connection_aborted
          && !enable_connection_aborted_)
        return false;
#if defined(EPROTO)
      if (ec.value() == EPROTO && !enable_connection_aborted_)
        return false;
#endif // defined(EPROTO)

      // Transfer ownership of the new socket to the peer object.
      if (!ec)
      {
        if (peer_endpoint_)
          peer_endpoint_->resize(addr_len);
        peer_.assign(protocol_, new_socket.get(), ec);
        if (!ec)
          new_socket.release();
      }

      return true;
    }

    void complete(const boost::system::error_code& ec, std::size_t)
    {
      io_service_.post(bind_handler(this->handler_, ec));
    }

  private:
    socket_type socket_;
    boost::asio::io_service& io_service_;
    boost::asio::io_service::work work_;
    Socket& peer_;
    protocol_type protocol_;
    endpoint_type* peer_endpoint_;
    bool enable_connection_aborted_;
  };

  // Start an asynchronous accept. The peer and peer_endpoint objects
  // must be valid until the accept's handler is invoked.
  template <typename Socket, typename Handler>
  void async_accept(implementation_type& impl, Socket& peer,
      endpoint_type* peer_endpoint, Handler handler)
  {
    if (!is_open(impl))
    {
      this->get_io_service().post(bind_handler(handler,
            boost::asio::error::bad_descriptor));
    }
    else if (peer.is_open())
    {
      this->get_io_service().post(bind_handler(handler,
            boost::asio::error::already_open));
    }
    else
    {
      // Make socket non-blocking.
      if (!(impl.flags_ & implementation_type::internal_non_blocking))
      {
        if (!(impl.flags_ & implementation_type::non_blocking))
        {
          ioctl_arg_type non_blocking = 1;
          boost::system::error_code ec;
          if (socket_ops::ioctl(impl.socket_, FIONBIO, &non_blocking, ec))
          {
            this->get_io_service().post(bind_handler(handler, ec));
            return;
          }
        }
        impl.flags_ |= implementation_type::internal_non_blocking;
      }

      reactor_.start_read_op(impl.socket_, impl.reactor_data_,
          accept_operation<Socket, Handler>(
            impl.socket_, this->get_io_service(),
            peer, impl.protocol_, peer_endpoint,
            (impl.flags_ & implementation_type::enable_connection_aborted) != 0,
            handler));
    }
  }

  // Connect the socket to the specified endpoint.
  boost::system::error_code connect(implementation_type& impl,
      const endpoint_type& peer_endpoint, boost::system::error_code& ec)
  {
    if (!is_open(impl))
    {
      ec = boost::asio::error::bad_descriptor;
      return ec;
    }

    // Perform the connect operation.
    socket_ops::connect(impl.socket_,
        peer_endpoint.data(), peer_endpoint.size(), ec);
    if (ec != boost::asio::error::in_progress
        && ec != boost::asio::error::would_block)
    {
      // The connect operation finished immediately.
      return ec;
    }

    // Wait for socket to become ready.
    if (socket_ops::poll_connect(impl.socket_, ec) < 0)
      return ec;

    // Get the error code from the connect operation.
    int connect_error = 0;
    size_t connect_error_len = sizeof(connect_error);
    if (socket_ops::getsockopt(impl.socket_, SOL_SOCKET, SO_ERROR,
          &connect_error, &connect_error_len, ec) == socket_error_retval)
      return ec;

    // Return the result of the connect operation.
    ec = boost::system::error_code(connect_error,
        boost::asio::error::get_system_category());
    return ec;
  }

  template <typename Handler>
  class connect_operation :
    public handler_base_from_member<Handler>
  {
  public:
    connect_operation(socket_type socket,
        boost::asio::io_service& io_service, Handler handler)
      : handler_base_from_member<Handler>(handler),
        socket_(socket),
        io_service_(io_service),
        work_(io_service)
    {
    }

    bool perform(boost::system::error_code& ec, std::size_t&)
    {
      // Check whether the operation was successful.
      if (ec)
        return true;

      // Get the error code from the connect operation.
      int connect_error = 0;
      size_t connect_error_len = sizeof(connect_error);
      if (socket_ops::getsockopt(socket_, SOL_SOCKET, SO_ERROR,
            &connect_error, &connect_error_len, ec) == socket_error_retval)
        return true;

      // The connection failed so the handler will be posted with an error code.
      if (connect_error)
      {
        ec = boost::system::error_code(connect_error,
            boost::asio::error::get_system_category());
        return true;
      }

      return true;
    }

    void complete(const boost::system::error_code& ec, std::size_t)
    {
      io_service_.post(bind_handler(this->handler_, ec));
    }

  private:
    socket_type socket_;
    boost::asio::io_service& io_service_;
    boost::asio::io_service::work work_;
  };

  // Start an asynchronous connect.
  template <typename Handler>
  void async_connect(implementation_type& impl,
      const endpoint_type& peer_endpoint, Handler handler)
  {
    if (!is_open(impl))
    {
      this->get_io_service().post(bind_handler(handler,
            boost::asio::error::bad_descriptor));
      return;
    }

    // Make socket non-blocking.
    if (!(impl.flags_ & implementation_type::internal_non_blocking))
    {
      if (!(impl.flags_ & implementation_type::non_blocking))
      {
        ioctl_arg_type non_blocking = 1;
        boost::system::error_code ec;
        if (socket_ops::ioctl(impl.socket_, FIONBIO, &non_blocking, ec))
        {
          this->get_io_service().post(bind_handler(handler, ec));
          return;
        }
      }
      impl.flags_ |= implementation_type::internal_non_blocking;
    }

    // Start the connect operation. The socket is already marked as non-blocking
    // so the connection will take place asynchronously.
    boost::system::error_code ec;
    if (socket_ops::connect(impl.socket_, peer_endpoint.data(),
          peer_endpoint.size(), ec) == 0)
    {
      // The connect operation has finished successfully so we need to post the
      // handler immediately.
      this->get_io_service().post(bind_handler(handler,
            boost::system::error_code()));
    }
    else if (ec == boost::asio::error::in_progress
        || ec == boost::asio::error::would_block)
    {
      // The connection is happening in the background, and we need to wait
      // until the socket becomes writeable.
      reactor_.start_connect_op(impl.socket_, impl.reactor_data_,
          connect_operation<Handler>(impl.socket_,
            this->get_io_service(), handler));
    }
    else
    {
      // The connect operation has failed, so post the handler immediately.
      this->get_io_service().post(bind_handler(handler, ec));
    }
  }

private:
  // The selector that performs event demultiplexing for the service.
  Reactor& reactor_;
};

} // namespace detail
} // namespace asio
} // namespace boost

#include <boost/asio/detail/pop_options.hpp>

#endif // BOOST_ASIO_DETAIL_REACTIVE_SOCKET_SERVICE_HPP


text:
from django.template.loader import select_template
from django.utils.html import format_html
from django.utils.translation import gettext_lazy as _
from django.utils.module_loading import import_string
from entangled.forms import EntangledModelFormMixin
from cms.plugin_pool import plugin_pool
from cmsplugin_cascade.link.cms_plugins import LinkElementMixin, LinkPluginBase
from cmsplugin_cascade.link.forms import LinkForm
from djng.forms.fields import ChoiceField
from shop.conf import app_settings

AUTH_FORM_TYPES = [
    ('login', _("Login Form")),
    ('login-reset-request', _("Login & Reset Request"), 'login'),
    ('logout', _("Logout Form")),
    ('login-logout', _("Shared Login/Logout Form"), 'login'),
    ('password-reset-request', _("Request Password Reset")),
    ('password-reset-confirm', _("Confirm Password Reset")),
    ('password-change', _("Change Password Form")),
    ('register-user', _("Register User"), app_settings.SHOP_CASCADE_FORMS['RegisterUserForm']),
    ('continue-as-guest', _("Continue as guest")),
]

class ShopAuthFormMixin(EntangledModelFormMixin):
    form_type = ChoiceField(
        label=_("Rendered Form"),
        choices=[ft[:2] for ft in AUTH_FORM_TYPES],
        help_text=_("Select the appropriate form for various authentication purposes."),
    )

    class Meta:
        entangled_fields = {'glossary': ['form_type']}

class ShopAuthForm(LinkForm, ShopAuthFormMixin):
    LINK_TYPE_CHOICES = [
        ('RELOAD_PAGE', _("Reload Page")),
        ('cmspage', _("CMS Page")),
        ('DO_NOTHING', _("Do Nothing")),
    ]

class ShopAuthenticationPlugin(LinkPluginBase):
    """
    A placeholder plugin which provides various authentication forms, such as login-, logout-,
    register-, and other forms. They can be added any to placeholder using the Cascade framework.
    """
    name = _("Authentication Forms")
    module = "Shop"
    parent_classes = ['BootstrapColumnPlugin']
    model_mixins = (LinkElementMixin,)
    form = ShopAuthForm
    cache = False

    @classmethod
    def get_identifier(cls, instance):
        identifier = super().get_identifier(instance)
        content = dict(ft[:2] for ft in AUTH_FORM_TYPES).get(instance.glossary.get('form_type'), _("unknown"))
        return format_html('{0}{1}', identifier, content)

    def get_render_template(self, context, instance, placeholder):
        form_type = instance.glossary.get('form_type')
        template_names = [
            '{}/auth/{}.html'.format(app_settings.APP_LABEL, form_type),
            'shop/auth/{}.html'.format(form_type),
            'shop/auth/form-not-found.html',
        ]
        return select_template(template_names)

    def render(self, context, instance, placeholder):
        """
        Return the context to render a DialogFormPlugin
        """
        form_type = instance.glossary.get('form_type')
        if form_type:
            try:
                # prevent a malicious database entry to import an ineligible file
                form_type = AUTH_FORM_TYPES[[ft[0] for ft in AUTH_FORM_TYPES].index(form_type)]
                FormClass = import_string(form_type[2])
            except ValueError:
                context['form_name'] = 'not_found_form'
            except IndexError:
                form_name = form_type[0].replace('-', '_')
                context['form_name'] = '{0}_form'.format(form_name)
            except ImportError:
                form_name = form_type[2]
                context['form_name'] = '{0}_form'.format(form_name)
            else:
                context['form_name'] = FormClass.form_name
                context[FormClass.form_name] = FormClass()
        context['proceed_with'] = instance.link
        return self.super(ShopAuthenticationPlugin, self).render(context, instance, placeholder)

plugin_pool.register_plugin(ShopAuthenticationPlugin)

redpajama_set_name: RedPajamaGithub


text:
/*
 * Licensed under MIT (https://github.com/ligoj/ligoj/blob/master/LICENSE)
 */
package org.ligoj.bootstrap.resource.system.plugin;

import org.ligoj.bootstrap.core.plugin.FeaturePlugin;

/**
 * Sample tool for test.
 */
public class SampleTool1 implements FeaturePlugin {

	@Override
	public String getKey() {
		return "service:sample:tool1";
	}

}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="postiveprogrammers.jacket.MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        android:id="@+id/TextExample" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="test location"
        android:id="@+id/updateButton" />

</LinearLayout>


text:
package org.sleuthkit.autopsy.imagegallery.datamodel;

import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.function.Function;
import javafx.beans.property.ReadOnlyStringWrapper;
import javafx.beans.property.StringProperty;
import javafx.scene.image.Image;
import org.apache.commons.lang3.StringUtils;
import org.sleuthkit.autopsy.datamodel.ContentUtils;
import org.sleuthkit.datamodel.TagName;

/**
 * psuedo-enum of attributes to filter, sort, and group on. They mostly
 * correspond to the columns in the db.
 *
 * TODO: Review and refactor DrawableAttribute related code with an eye to usage
 * of type paramaters and multivalued attributes
 */
public class DrawableAttribute<T extends Comparable<T>> {

    public final static DrawableAttribute<String> MD5_HASH
            = new DrawableAttribute<>(AttributeName.MD5_HASH, "MD5 Hash", false, "icon-hashtag.png", f -> Collections.singleton(f.getMd5Hash()));

    public final static DrawableAttribute<String> NAME
            = new DrawableAttribute<>(AttributeName.NAME, "Name", true, "folder-rename.png", f -> Collections.singleton(f.getName()));

    public final static DrawableAttribute<Boolean> ANALYZED
            = new DrawableAttribute<>(AttributeName.ANALYZED, "Analyzed", true, "", f -> Collections.singleton(f.isAnalyzed()));

    /**
     * since categories are really just tags in autopsy, they are not dealt with
     * in the DrawableDB. they have special code in various places to make this
     * transparent.
     *
     * //TODO: this has lead to awkward hard to maintain code, and little
     * advantage. move categories into DrawableDB?
     */
    public final static DrawableAttribute<Category> CATEGORY
            = new DrawableAttribute<>(AttributeName.CATEGORY, "Category", false, "category-icon.png", f -> Collections.singleton(f.getCategory()));

    public final static DrawableAttribute<TagName> TAGS
            = new DrawableAttribute<>(AttributeName.TAGS, "Tags", false, "tag_red.png", DrawableFile::getTagNames);

    public final static DrawableAttribute<String> PATH
            = new DrawableAttribute<>(AttributeName.PATH, "Path", true, "folder_picture.png", f -> Collections.singleton(f.getDrawablePath()));

    public final static DrawableAttribute<String> CREATED_TIME
            = new DrawableAttribute<>(AttributeName.CREATED_TIME, "Created Time", true, "clock--plus.png", f -> Collections.singleton(ContentUtils.getStringTime(f.getCrtime(), f)));

    public final static DrawableAttribute<String> MODIFIED_TIME
            = new DrawableAttribute<>(AttributeName.MODIFIED_TIME, "Modified Time", true, "clock--pencil.png", f -> Collections.singleton(ContentUtils.getStringTime(f.getMtime(), f)));

    public final static DrawableAttribute<String> MAKE
            = new DrawableAttribute<>(AttributeName.MAKE, "Camera Make", true, "camera.png", f -> Collections.singleton(f.getMake()));

    public final static DrawableAttribute<String> MODEL
            = new DrawableAttribute<>(AttributeName.MODEL, "Camera Model", true, "camera.png", f -> Collections.singleton(f.getModel()));

    public final static DrawableAttribute<String> HASHSET
            = new DrawableAttribute<>(AttributeName.HASHSET, "Hashset", true, "hashset_hits.png", DrawableFile::getHashSetNamesUnchecked);

    public final static DrawableAttribute<Long> OBJ_ID
            = new DrawableAttribute<>(AttributeName.OBJ_ID, "Internal Object ID", true, "", f -> Collections.singleton(f.getId()));

    public final static DrawableAttribute<Double> WIDTH
            = new DrawableAttribute<>(AttributeName.WIDTH, "Width", true, "arrow-resize.png", f -> Collections.singleton(f.getWidth()));

    public final static DrawableAttribute<Double> HEIGHT
            = new DrawableAttribute<>(AttributeName.HEIGHT, "Height", true, "arrow-resize-090.png", f -> Collections.singleton(f.getHeight()));

    final private static List< DrawableAttribute<?>> groupables
            = Arrays.asList(PATH, HASHSET, CATEGORY, TAGS, MAKE, MODEL);

    final private static List<DrawableAttribute<?>> values
            = Arrays.asList(NAME, ANALYZED, CATEGORY, TAGS, PATH, CREATED_TIME,
                    MODIFIED_TIME, MD5_HASH, HASHSET, MAKE, MODEL, OBJ_ID, WIDTH, HEIGHT);

    private final Function<DrawableFile<?>, Collection<T>> extractor;

    private DrawableAttribute(AttributeName name, String displayName, Boolean isDBColumn, String imageName, Function<DrawableFile<?>, Collection<T>> extractor) {
        this.attrName = name;
        this.displayName = new ReadOnlyStringWrapper(displayName);
        this.isDBColumn = isDBColumn;
        this.imageName = imageName;
        this.extractor = extractor;
    }

    private Image icon;

    public final boolean isDBColumn;

    public final AttributeName attrName;

    private final StringProperty displayName;

    private final String imageName;

    public Image getIcon() {
        if (icon == null) {
            if (StringUtils.isBlank(imageName) == false) {
                this.icon = new Image("org/sleuthkit/autopsy/imagegallery/images/" + imageName, true);
            }
        }
        return icon;
    }

    public static List<DrawableAttribute<?>> getGroupableAttrs() {
        return Collections.unmodifiableList(groupables);
    }

    public static List<DrawableAttribute<?>> getValues() {
        return Collections.unmodifiableList(values);
    }

    public StringProperty displayName() {
        return displayName;
    }

    public String getDisplayName() {
        return displayName.get();
    }

    public static enum AttributeName {

        NAME,
        ANALYZED,
        CATEGORY,
        TAGS,
        PATH,
        CREATED_TIME,
        MODIFIED_TIME,
        MAKE,
        MODEL,
        HASHSET,
        OBJ_ID,
        WIDTH,
        HEIGHT,
        MD5_HASH;
    }

    public Collection<T> getValue(DrawableFile<?> f) {
        return extractor.apply(f);
    }
}


text:
package backend.interpreter.data;

import backend.interpreter.instances.Instance;
import frontend.tokeniser.Token;

public abstract class DataType {
    Type type = Type.Undefined;
    Instance dataInstance;

    public Type getType() {
	return type;
    }

    public Instance getInstance() {
	return this.dataInstance;
    }

    public abstract void setFromToken(Token t);
}


text:
title: Date.prototype.toUTCString
localeTitle: Date.prototype.toUTCString
---
## Date.prototype.toUTCString

这是一个存根。 [帮助我们的社区扩展它](https://github.com/freecodecamp/guides/tree/master/src/pages/javascript/standard-objects/date/date-prototype-toutcstring/index.md) 。

[这种快速风格指南有助于确保您的拉取请求被接受](https://github.com/freecodecamp/guides/blob/master/README.md) 。

#### 更多信息:


text:
<?php

/**
 * @file
 * Definition of Drupal\locale\Tests\LocaleUninstallTest.
 */

namespace Drupal\locale\Tests;

use Drupal\simpletest\WebTestBase;
use Drupal\Core\Language\Language;
use Drupal\Component\Utility\String;

/**
 * Locale uninstall with English UI functional test.
 */
class LocaleUninstallTest extends WebTestBase {

  /**
   * Modules to enable.
   *
   * @var array
   */
  public static $modules = array('node', 'locale');

  public static function getInfo() {
    return array(
      'name' => 'Locale uninstall (EN)',
      'description' => 'Tests the uninstall process using the built-in UI language.',
      'group' => 'Locale',
    );
  }

  /**
   * The default language set for the UI before uninstall.
   */
  protected $language;

  function setUp() {
    parent::setUp();

    $this->langcode = 'en';

    // Create Article node type.
    $this->drupalCreateContentType(array('type' => 'article', 'name' => 'Article'));
  }

  /**
   * Check if the values of the Locale variables are correct after uninstall.
   */
  function testUninstallProcess() {
    $locale_module = array('locale', 'language');
    $config = config('locale.settings');
    $language = new Language(array(
      'id' => 'fr',
      'name' => 'French',
      'default' => $this->langcode == 'fr',
    ));
    language_save($language);
    // Reset the language manager.
    $language_manager = $this->container->get('language_manager');
    $language_manager->reset();
    $language_manager->init();
    // Check the UI language.

    // @todo: If the global user is an EntityBCDecorator, getting the roles
    // from it within LocaleLookup results in a loop that invokes LocaleLookup
    // again.
    global $user;
    $user = drupal_anonymous_user();

    $this->assertEqual(language(Language::TYPE_INTERFACE)->id, $this->langcode, String::format('Current language: %lang', array('%lang' => language(Language::TYPE_INTERFACE)->id)));

    // Enable multilingual workflow option for articles.
    language_save_default_configuration('node', 'article', array('langcode' => 'site_default', 'language_show' => TRUE));
    // Change JavaScript translations directory.
    $config->set('javascript.directory', 'js_translations')->save();
    // Build the JavaScript translation file for French.
    $user = $this->drupalCreateUser(array('translate interface', 'access administration pages'));
    $this->drupalLogin($user);
    $this->drupalGet('admin/config/regional/translate/translate');
    // Get any of the javascript strings to translate.
    $js_strings = $this->container->get('locale.storage')->getStrings(array('type' => 'javascript'));
    $string = reset($js_strings);
    $edit = array('string' => $string->source);
    $this->drupalPost('admin/config/regional/translate', $edit, t('Filter'));
    $edit = array('strings[' . $string->lid . '][translations][0]' => 'french translation');
    $this->drupalPost('admin/config/regional/translate', $edit, t('Save translations'));
    _locale_rebuild_js('fr');
    $config = config('locale.settings');
    $locale_javascripts = $this->container->get('state')->get('locale.translation.javascript') ?: array();
    $js_file = 'public://' . $config->get('javascript.directory') . '/fr_' . $locale_javascripts['fr'] . '.js';
    $this->assertTrue($result = file_exists($js_file), String::format('JavaScript file created: %file', array('%file' => $result ? $js_file : 'none')));

    // Disable string caching.
    $config->set('cache_strings', 0)->save();

    // Change language negotiation options.
    drupal_load('module', 'locale');
    \Drupal::config('system.language.types')->set('configurable', language_types_get_default() + array('language_custom' => TRUE))->save();
    variable_set('language_negotiation_' . Language::TYPE_INTERFACE, language_language_negotiation_info());
    variable_set('language_negotiation_' . Language::TYPE_CONTENT, language_language_negotiation_info());
    variable_set('language_negotiation_' . Language::TYPE_URL, language_language_negotiation_info());

    // Change language negotiation settings.
    config('language.negotiation')
      ->set('url.source', LANGUAGE_NEGOTIATION_URL_PREFIX)
      ->set('session.parameter', TRUE)
      ->save();

    // Uninstall Locale.
    module_disable($locale_module);
    module_uninstall($locale_module);
    $this->rebuildContainer();

    // Visit the front page.
    $this->drupalGet('');
    // Check the init language logic.
    $this->assertEqual(language(Language::TYPE_INTERFACE)->id, 'en', String::format('Language after uninstall: %lang', array('%lang' => language(Language::TYPE_INTERFACE)->id)));

    // Check JavaScript files deletion.
    $this->assertTrue($result = !file_exists($js_file), String::format('JavaScript file deleted: %file', array('%file' => $result ? $js_file : 'found')));

    // Check language count.
    $language_count = $this->container->get('state')->get('language_count') ?: 1;
    $this->assertEqual($language_count, 1, String::format('Language count: %count', array('%count' => $language_count)));

    // Check language negotiation.
    require_once DRUPAL_ROOT . '/core/includes/language.inc';
    $this->assertTrue(count(language_types_get_all()) == count(language_types_get_default()), 'Language types reset');
    $language_negotiation = language_negotiation_method_get_first(Language::TYPE_INTERFACE) == LANGUAGE_NEGOTIATION_SELECTED;
    $this->assertTrue($language_negotiation, String::format('Interface language negotiation: %setting', array('%setting' => $language_negotiation ? 'none' : 'set')));
    $language_negotiation = language_negotiation_method_get_first(Language::TYPE_CONTENT) == LANGUAGE_NEGOTIATION_SELECTED;
    $this->assertTrue($language_negotiation, String::format('Content language negotiation: %setting', array('%setting' => $language_negotiation ? 'none' : 'set')));
    $language_negotiation = language_negotiation_method_get_first(Language::TYPE_URL) == LANGUAGE_NEGOTIATION_SELECTED;
    $this->assertTrue($language_negotiation, String::format('URL language negotiation: %setting', array('%setting' => $language_negotiation ? 'none' : 'set')));

    // Check language negotiation method settings.
    $this->assertFalse(config('language.negotiation')->get('url.source'), 'URL language negotiation method indicator settings cleared.');
    $this->assertFalse(config('language.negotiation')->get('session.parameter'), 'Visit language negotiation method settings cleared.');

    // Check JavaScript parsed.
    $javascript_parsed_count = count($this->container->get('state')->get('system.javascript_parsed') ?: array());
    $this->assertEqual($javascript_parsed_count, 0, String::format('JavaScript parsed count: %count', array('%count' => $javascript_parsed_count)));
  }
}


text:
import {validateData, writeScript} from '../3p/3p';

/**
 * @param {!Window} global
 * @param {!Object} data
 */
export function f1e(global, data) {
  validateData(data, ['url','target'], []);
  global.f1eData = data;
  writeScript(global, 'https://img.ak.impact-ad.jp/util/f1e_amp.min.js');
}


text:
package edu.jhu.thrax.hadoop.features.pivot;

import java.util.ArrayList;
import java.util.List;

import edu.jhu.thrax.util.FormatUtils;

public class PivotedFeatureFactory {

  public static PivotedFeature get(String name) {
    if (name.equals(PivotedTargetPhraseGivenSourceFeature.NAME))
      return new PivotedTargetPhraseGivenSourceFeature();
    else if (name.equals(PivotedSourcePhraseGivenTargetFeature.NAME))
      return new PivotedSourcePhraseGivenTargetFeature();
    else if (name.equals(PivotedRarityPenaltyFeature.NAME))
      return new PivotedRarityPenaltyFeature();
    else if (name.equals(PivotedLexicalSourceGivenTargetFeature.NAME))
      return new PivotedLexicalSourceGivenTargetFeature();
    else if (name.equals(PivotedLexicalTargetGivenSourceFeature.NAME))
      return new PivotedLexicalTargetGivenSourceFeature();
    else if (name.equals(PivotedSourcePhraseGivenLHSFeature.NAME))
      return new PivotedSourcePhraseGivenLHSFeature();
    else if (name.equals(PivotedLhsGivenSourcePhraseFeature.NAME))
      return new PivotedLhsGivenSourcePhraseFeature();
    else if (name.equals(PivotedSourcePhraseGivenTargetAndLHSFeature.NAME))
      return new PivotedSourcePhraseGivenTargetAndLHSFeature();
    else if (name.equals(PivotedTargetPhraseGivenLHSFeature.NAME))
      return new PivotedTargetPhraseGivenLHSFeature();
    else if (name.equals(PivotedLhsGivenTargetPhraseFeature.NAME))
      return new PivotedLhsGivenTargetPhraseFeature();
    else if (name.equals(PivotedTargetPhraseGivenSourceAndLHSFeature.NAME))
      return new PivotedTargetPhraseGivenSourceAndLHSFeature();

    return null;
  }

  public static List<PivotedFeature> getAll(String names) {
    String[] feature_names = FormatUtils.P_COMMA_OR_SPACE.split(names);
    List<PivotedFeature> features = new ArrayList<PivotedFeature>();

    for (String feature_name : feature_names) {
      PivotedFeature feature = get(feature_name);
      if (feature != null) features.add(feature);
    }
    return features;
  }
}


text:
set -e

. /opt/kolla/config-neutron.sh
. /sudoers.sh

: ${NEUTRON_FLAT_NETWORK_NAME:=physnet1}
: ${NEUTRON_FLAT_NETWORK_INTERFACE:=eth1}

check_required_vars PUBLIC_IP

cfg=/etc/neutron/plugins/ml2/ml2_conf.ini

# Configure ml2_conf.ini
crudini --set $cfg \
        vxlan \
        local_ip \
        "${PUBLIC_IP}"
crudini --set $cfg \
        linux_bridge \
        physical_interface_mappings \
        "${NEUTRON_FLAT_NETWORK_NAME}:${NEUTRON_FLAT_NETWORK_INTERFACE}"

#Initialization scripts expect a symbolic link
/usr/bin/ln -s /etc/neutron/plugins/ml2/ml2_conf.ini /etc/neutron/plugin.ini

# Start the linux bridge agent.
exec /usr/bin/neutron-linuxbridge-agent