1//
2// detail/impl/winsock_init.ipp
3// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
4//
5// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com)
6//
7// Distributed under the Boost Software License, Version 1.0. (See accompanying
8// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
9//
10
11#ifndef BOOST_ASIO_DETAIL_IMPL_WINSOCK_INIT_IPP
12#define BOOST_ASIO_DETAIL_IMPL_WINSOCK_INIT_IPP
13
14#if defined(_MSC_VER) && (_MSC_VER >= 1200)
15# pragma once
16#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
17
18#include <boost/asio/detail/config.hpp>
19
20#if defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
21
22#include <boost/asio/detail/socket_types.hpp>
23#include <boost/asio/detail/winsock_init.hpp>
24#include <boost/asio/detail/throw_error.hpp>
25#include <boost/asio/error.hpp>
26
27#include <boost/asio/detail/push_options.hpp>
28
29namespace boost {
30namespace asio {
31namespace detail {
32
33void winsock_init_base::startup(data& d,
34    unsigned char major, unsigned char minor)
35{
36  if (::InterlockedIncrement(&d.init_count_) == 1)
37  {
38    WSADATA wsa_data;
39    long result = ::WSAStartup(MAKEWORD(major, minor), &wsa_data);
40    ::InterlockedExchange(&d.result_, result);
41  }
42}
43
44void winsock_init_base::manual_startup(data& d)
45{
46  if (::InterlockedIncrement(&d.init_count_) == 1)
47  {
48    ::InterlockedExchange(&d.result_, 0);
49  }
50}
51
52void winsock_init_base::cleanup(data& d)
53{
54  if (::InterlockedDecrement(&d.init_count_) == 0)
55  {
56    ::WSACleanup();
57  }
58}
59
60void winsock_init_base::manual_cleanup(data& d)
61{
62  ::InterlockedDecrement(&d.init_count_);
63}
64
65void winsock_init_base::throw_on_error(data& d)
66{
67  long result = ::InterlockedExchangeAdd(&d.result_, 0);
68  if (result != 0)
69  {
70    boost::system::error_code ec(result,
71        boost::asio::error::get_system_category());
72    boost::asio::detail::throw_error(ec, "winsock");
73  }
74}
75
76} // namespace detail
77} // namespace asio
78} // namespace boost
79
80#include <boost/asio/detail/pop_options.hpp>
81
82#endif // defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
83
84#endif // BOOST_ASIO_DETAIL_IMPL_WINSOCK_INIT_IPP
85