include/boost/corosio/native/detail/iocp/win_wsa_init.hpp

90.0% Lines (9/10) 100.0% Functions (2/2) 85.7% Branches (6/7)
include/boost/corosio/native/detail/iocp/win_wsa_init.hpp
Line Branch TLA Hits Source Code
1 //
2 // Copyright (c) 2025 Vinnie Falco ([email protected])
3 // Copyright (c) 2026 Steve Gerbino
4 //
5 // Distributed under the Boost Software License, Version 1.0. (See accompanying
6 // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
7 //
8 // Official repository: https://github.com/cppalliance/corosio
9 //
10
11 #ifndef BOOST_COROSIO_NATIVE_DETAIL_IOCP_WIN_WSA_INIT_HPP
12 #define BOOST_COROSIO_NATIVE_DETAIL_IOCP_WIN_WSA_INIT_HPP
13
14 #include <boost/corosio/detail/platform.hpp>
15
16 #if BOOST_COROSIO_HAS_IOCP
17
18 #include <boost/corosio/detail/config.hpp>
19 #include <boost/corosio/detail/make_err.hpp>
20 #include <boost/corosio/detail/except.hpp>
21
22 #include <boost/corosio/native/detail/iocp/win_windows.hpp>
23
24 namespace boost::corosio::detail {
25
26 /** RAII class for Winsock initialization.
27
28 Uses reference counting to ensure WSAStartup is called once on
29 first construction and WSACleanup on last destruction.
30
31 Derive from this class to ensure Winsock is initialized before
32 any socket operations.
33 */
34 class win_wsa_init
35 {
36 protected:
37 win_wsa_init();
38 ~win_wsa_init();
39
40 win_wsa_init(win_wsa_init const&) = delete;
41 win_wsa_init& operator=(win_wsa_init const&) = delete;
42
43 private:
44 static long count_;
45 };
46
47 inline long win_wsa_init::count_ = 0;
48
49 580 inline win_wsa_init::win_wsa_init()
50 {
51
2/2
✓ Branch 4 → 5 taken 287 times.
✓ Branch 4 → 12 taken 293 times.
580 if (::InterlockedIncrement(&count_) == 1)
52 {
53 WSADATA wsaData;
54
1/1
✓ Branch 5 → 6 taken 287 times.
287 int result = ::WSAStartup(MAKEWORD(2, 2), &wsaData);
55
1/2
✗ Branch 6 → 7 not taken.
✓ Branch 6 → 11 taken 287 times.
287 if (result != 0)
56 {
57 ::InterlockedDecrement(&count_);
58 throw_system_error(make_err(result));
59 }
60 }
61 580 }
62
63 580 inline win_wsa_init::~win_wsa_init()
64 {
65
2/2
✓ Branch 4 → 5 taken 287 times.
✓ Branch 4 → 6 taken 293 times.
580 if (::InterlockedDecrement(&count_) == 0)
66 287 ::WSACleanup();
67 580 }
68
69 } // namespace boost::corosio::detail
70
71 #endif // BOOST_COROSIO_HAS_IOCP
72
73 #endif // BOOST_COROSIO_NATIVE_DETAIL_IOCP_WIN_WSA_INIT_HPP
74