1/*
2 * Copyright 2013-present Facebook, Inc.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#pragma once
18
19#include <ostream>
20
21#include <folly/net/detail/SocketFileDescriptorMap.h>
22#include <folly/portability/Windows.h>
23
24namespace folly {
25/**
26 * This is just a very thin wrapper around either a file descriptor or
27 * a SOCKET depending on platform, along with a couple of helper methods
28 * for explicitly converting to/from file descriptors, even on Windows.
29 */
30struct NetworkSocket {
31#if _WIN32
32 using native_handle_type = SOCKET;
33 static constexpr native_handle_type invalid_handle_value = INVALID_SOCKET;
34#else
35 using native_handle_type = int;
36 static constexpr native_handle_type invalid_handle_value = -1;
37#endif
38
39 native_handle_type data;
40
41 constexpr NetworkSocket() : data(invalid_handle_value) {}
42 constexpr explicit NetworkSocket(native_handle_type d) : data(d) {}
43
44 static NetworkSocket fromFd(int fd) {
45 return NetworkSocket(
46 netops::detail::SocketFileDescriptorMap::fdToSocket(fd));
47 }
48
49 int toFd() const {
50 return netops::detail::SocketFileDescriptorMap::socketToFd(data);
51 }
52
53 friend constexpr bool operator==(
54 const NetworkSocket& a,
55 const NetworkSocket& b) noexcept {
56 return a.data == b.data;
57 }
58
59 friend constexpr bool operator!=(
60 const NetworkSocket& a,
61 const NetworkSocket& b) noexcept {
62 return !(a == b);
63 }
64};
65
66template <class CharT, class Traits>
67inline std::basic_ostream<CharT, Traits>& operator<<(
68 std::basic_ostream<CharT, Traits>& os,
69 const NetworkSocket& addr) {
70 os << "folly::NetworkSocket(" << addr.data << ")";
71 return os;
72}
73} // namespace folly
74