28dbfd89bf505f502cbf566632a55634e8c443fc
[folly.git] / folly / detail / IPAddress.h
1 /*
2  * Copyright 2017 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 <string>
20 #include <sys/types.h>
21 #include <folly/portability/Sockets.h>
22
23 namespace folly { namespace detail {
24
25 std::string familyNameStrDefault(sa_family_t family);
26
27 inline std::string familyNameStr(sa_family_t family) {
28   switch (family) {
29     case AF_INET:
30       return "AF_INET";
31     case AF_INET6:
32       return "AF_INET6";
33     case AF_UNSPEC:
34       return "AF_UNSPEC";
35     case AF_UNIX:
36       return "AF_UNIX";
37     default:
38       return familyNameStrDefault(family);
39   }
40 }
41
42 [[noreturn]] void getNthMSBitImplThrow(size_t bitCount, sa_family_t family);
43
44 template <typename IPAddrType>
45 inline bool
46 getNthMSBitImpl(const IPAddrType& ip, size_t bitIndex, sa_family_t family) {
47   if (bitIndex >= ip.bitCount()) {
48     getNthMSBitImplThrow(ip.bitCount(), family);
49   }
50   //Underlying bytes are in n/w byte order
51   return (ip.getNthMSByte(bitIndex / 8) & (0x80 >> (bitIndex % 8))) != 0;
52 }
53
54 }}  // folly::detail