add LockTraits
[folly.git] / folly / MacAddress.cpp
1 /*
2  * Copyright 2016 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 #include <folly/MacAddress.h>
18
19 #include <folly/Exception.h>
20 #include <folly/IPAddressV6.h>
21
22 using std::invalid_argument;
23 using std::string;
24
25 namespace folly {
26
27 const MacAddress MacAddress::BROADCAST{Endian::big(uint64_t(0xffffffffffffU))};
28 const MacAddress MacAddress::ZERO;
29
30 MacAddress::MacAddress(StringPiece str) {
31   memset(&bytes_, 0, 8);
32   parse(str);
33 }
34
35 MacAddress MacAddress::createMulticast(IPAddressV6 v6addr) {
36   // This method should only be used for multicast addresses.
37   DCHECK(v6addr.isMulticast());
38
39   uint8_t bytes[SIZE];
40   bytes[0] = 0x33;
41   bytes[1] = 0x33;
42   memcpy(bytes + 2, v6addr.bytes() + 12, 4);
43   return fromBinary(ByteRange(bytes, SIZE));
44 }
45
46 string MacAddress::toString() const {
47   static const char hexValues[] = "0123456789abcdef";
48   string result;
49   result.resize(17);
50   result[0] = hexValues[getByte(0) >> 4];
51   result[1] = hexValues[getByte(0) & 0xf];
52   result[2] = ':';
53   result[3] = hexValues[getByte(1) >> 4];
54   result[4] = hexValues[getByte(1) & 0xf];
55   result[5] = ':';
56   result[6] = hexValues[getByte(2) >> 4];
57   result[7] = hexValues[getByte(2) & 0xf];
58   result[8] = ':';
59   result[9] = hexValues[getByte(3) >> 4];
60   result[10] = hexValues[getByte(3) & 0xf];
61   result[11] = ':';
62   result[12] = hexValues[getByte(4) >> 4];
63   result[13] = hexValues[getByte(4) & 0xf];
64   result[14] = ':';
65   result[15] = hexValues[getByte(5) >> 4];
66   result[16] = hexValues[getByte(5) & 0xf];
67   return result;
68 }
69
70 void MacAddress::parse(StringPiece str) {
71   // Helper function to convert a single hex char into an integer
72   auto unhex = [](char c) -> int {
73     return c >= '0' && c <= '9' ? c - '0' :
74            c >= 'A' && c <= 'F' ? c - 'A' + 10 :
75            c >= 'a' && c <= 'f' ? c - 'a' + 10 :
76            -1;
77   };
78   auto isSeparatorChar = [](char c) {
79     return c == ':' || c == '-';
80   };
81
82   uint8_t parsed[SIZE];
83   auto p = str.begin();
84   for (unsigned int byteIndex = 0; byteIndex < SIZE; ++byteIndex) {
85     if (p == str.end()) {
86       throw invalid_argument(to<string>("invalid MAC address \"", str,
87                                         "\": not enough digits"));
88     }
89
90     // Skip over ':' or '-' separators between bytes
91     if (byteIndex != 0 && isSeparatorChar(*p)) {
92       ++p;
93       if (p == str.end()) {
94         throw invalid_argument(to<string>("invalid MAC address \"", str,
95                                           "\": not enough digits"));
96       }
97     }
98
99     // Parse the upper nibble
100     int upper = unhex(*p);
101     if (upper < 0) {
102       throw invalid_argument(to<string>("invalid MAC address \"", str,
103                                         "\": contains non-hex digit"));
104     }
105     ++p;
106
107     // Parse the lower nibble
108     int lower;
109     if (p == str.end()) {
110       lower = upper;
111       upper = 0;
112     } else {
113       lower = unhex(*p);
114       if (lower < 0) {
115         // Also accept ':', '-', or '\0', to handle the case where one
116         // of the bytes was represented by just a single digit.
117         if (isSeparatorChar(*p)) {
118           lower = upper;
119           upper = 0;
120         } else {
121           throw invalid_argument(to<string>("invalid MAC address \"", str,
122                                             "\": contains non-hex digit"));
123         }
124       }
125       ++p;
126     }
127
128     // Update parsed with the newly parsed byte
129     parsed[byteIndex] = ((upper << 4) | lower);
130   }
131
132   if (p != str.end()) {
133     // String is too long to be a MAC address
134     throw invalid_argument(to<string>("invalid MAC address \"", str,
135                                       "\": found trailing characters"));
136   }
137
138   // Only update now that we have successfully parsed the entire
139   // string.  This way we remain unchanged on error.
140   setFromBinary(ByteRange(parsed, SIZE));
141 }
142
143 void MacAddress::setFromBinary(ByteRange value) {
144   if (value.size() != SIZE) {
145     throw invalid_argument(to<string>("MAC address must be 6 bytes "
146                                       "long, got ", value.size()));
147   }
148   memcpy(bytes_ + 2, value.begin(), SIZE);
149 }
150
151 std::ostream& operator<<(std::ostream& os, MacAddress address) {
152   os << address.toString();
153   return os;
154 }
155
156 } // folly