Add mechanizm for caching local and peer addresses in AsyncSSLSocket.
[folly.git] / folly / Bits.h
1 /*
2  * Copyright 2015 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 /**
18  * Various low-level, bit-manipulation routines.
19  *
20  * findFirstSet(x)  [constexpr]
21  *    find first (least significant) bit set in a value of an integral type,
22  *    1-based (like ffs()).  0 = no bits are set (x == 0)
23  *
24  * findLastSet(x)  [constexpr]
25  *    find last (most significant) bit set in a value of an integral type,
26  *    1-based.  0 = no bits are set (x == 0)
27  *    for x != 0, findLastSet(x) == 1 + floor(log2(x))
28  *
29  * nextPowTwo(x)  [constexpr]
30  *    Finds the next power of two >= x.
31  *
32  * isPowTwo(x)  [constexpr]
33  *    return true iff x is a power of two
34  *
35  * popcount(x)
36  *    return the number of 1 bits in x
37  *
38  * Endian
39  *    convert between native, big, and little endian representation
40  *    Endian::big(x)      big <-> native
41  *    Endian::little(x)   little <-> native
42  *    Endian::swap(x)     big <-> little
43  *
44  * BitIterator
45  *    Wrapper around an iterator over an integral type that iterates
46  *    over its underlying bits in MSb to LSb order
47  *
48  * findFirstSet(BitIterator begin, BitIterator end)
49  *    return a BitIterator pointing to the first 1 bit in [begin, end), or
50  *    end if all bits in [begin, end) are 0
51  *
52  * @author Tudor Bosman (tudorb@fb.com)
53  */
54
55 #ifndef FOLLY_BITS_H_
56 #define FOLLY_BITS_H_
57
58 #if !defined(__clang__) && !(defined(_MSC_VER) && (_MSC_VER < 1900))
59 #define FOLLY_INTRINSIC_CONSTEXPR constexpr
60 #else
61 // GCC and MSVC 2015+ are the only compilers with
62 // intrinsics constexpr.
63 #define FOLLY_INTRINSIC_CONSTEXPR const
64 #endif
65
66 #include <folly/Portability.h>
67
68 #include <folly/detail/BitsDetail.h>
69 #include <folly/detail/BitIteratorDetail.h>
70 #include <folly/Likely.h>
71
72 #if FOLLY_HAVE_BYTESWAP_H
73 # include <byteswap.h>
74 #endif
75
76 #include <cassert>
77 #include <cinttypes>
78 #include <iterator>
79 #include <limits>
80 #include <type_traits>
81 #include <boost/iterator/iterator_adaptor.hpp>
82 #include <stdint.h>
83
84 namespace folly {
85
86 // Generate overloads for findFirstSet as wrappers around
87 // appropriate ffs, ffsl, ffsll gcc builtins
88 template <class T>
89 inline FOLLY_INTRINSIC_CONSTEXPR
90 typename std::enable_if<
91   (std::is_integral<T>::value &&
92    std::is_unsigned<T>::value &&
93    sizeof(T) <= sizeof(unsigned int)),
94   unsigned int>::type
95   findFirstSet(T x) {
96   return __builtin_ffs(x);
97 }
98
99 template <class T>
100 inline FOLLY_INTRINSIC_CONSTEXPR
101 typename std::enable_if<
102   (std::is_integral<T>::value &&
103    std::is_unsigned<T>::value &&
104    sizeof(T) > sizeof(unsigned int) &&
105    sizeof(T) <= sizeof(unsigned long)),
106   unsigned int>::type
107   findFirstSet(T x) {
108   return __builtin_ffsl(x);
109 }
110
111 template <class T>
112 inline FOLLY_INTRINSIC_CONSTEXPR
113 typename std::enable_if<
114   (std::is_integral<T>::value &&
115    std::is_unsigned<T>::value &&
116    sizeof(T) > sizeof(unsigned long) &&
117    sizeof(T) <= sizeof(unsigned long long)),
118   unsigned int>::type
119   findFirstSet(T x) {
120   return __builtin_ffsll(x);
121 }
122
123 template <class T>
124 inline FOLLY_INTRINSIC_CONSTEXPR
125 typename std::enable_if<
126   (std::is_integral<T>::value && std::is_signed<T>::value),
127   unsigned int>::type
128   findFirstSet(T x) {
129   // Note that conversion from a signed type to the corresponding unsigned
130   // type is technically implementation-defined, but will likely work
131   // on any impementation that uses two's complement.
132   return findFirstSet(static_cast<typename std::make_unsigned<T>::type>(x));
133 }
134
135 // findLastSet: return the 1-based index of the highest bit set
136 // for x > 0, findLastSet(x) == 1 + floor(log2(x))
137 template <class T>
138 inline FOLLY_INTRINSIC_CONSTEXPR
139 typename std::enable_if<
140   (std::is_integral<T>::value &&
141    std::is_unsigned<T>::value &&
142    sizeof(T) <= sizeof(unsigned int)),
143   unsigned int>::type
144   findLastSet(T x) {
145   return x ? 8 * sizeof(unsigned int) - __builtin_clz(x) : 0;
146 }
147
148 template <class T>
149 inline FOLLY_INTRINSIC_CONSTEXPR
150 typename std::enable_if<
151   (std::is_integral<T>::value &&
152    std::is_unsigned<T>::value &&
153    sizeof(T) > sizeof(unsigned int) &&
154    sizeof(T) <= sizeof(unsigned long)),
155   unsigned int>::type
156   findLastSet(T x) {
157   return x ? 8 * sizeof(unsigned long) - __builtin_clzl(x) : 0;
158 }
159
160 template <class T>
161 inline FOLLY_INTRINSIC_CONSTEXPR
162 typename std::enable_if<
163   (std::is_integral<T>::value &&
164    std::is_unsigned<T>::value &&
165    sizeof(T) > sizeof(unsigned long) &&
166    sizeof(T) <= sizeof(unsigned long long)),
167   unsigned int>::type
168   findLastSet(T x) {
169   return x ? 8 * sizeof(unsigned long long) - __builtin_clzll(x) : 0;
170 }
171
172 template <class T>
173 inline FOLLY_INTRINSIC_CONSTEXPR
174 typename std::enable_if<
175   (std::is_integral<T>::value &&
176    std::is_signed<T>::value),
177   unsigned int>::type
178   findLastSet(T x) {
179   return findLastSet(static_cast<typename std::make_unsigned<T>::type>(x));
180 }
181
182 template <class T>
183 inline FOLLY_INTRINSIC_CONSTEXPR
184 typename std::enable_if<
185   std::is_integral<T>::value && std::is_unsigned<T>::value,
186   T>::type
187 nextPowTwo(T v) {
188   return v ? (1ul << findLastSet(v - 1)) : 1;
189 }
190
191 template <class T>
192 inline constexpr
193 typename std::enable_if<
194   std::is_integral<T>::value && std::is_unsigned<T>::value,
195   bool>::type
196 isPowTwo(T v) {
197   return (v != 0) && !(v & (v - 1));
198 }
199
200 /**
201  * Population count
202  */
203 template <class T>
204 inline typename std::enable_if<
205   (std::is_integral<T>::value &&
206    std::is_unsigned<T>::value &&
207    sizeof(T) <= sizeof(unsigned int)),
208   size_t>::type
209   popcount(T x) {
210   return detail::popcount(x);
211 }
212
213 template <class T>
214 inline typename std::enable_if<
215   (std::is_integral<T>::value &&
216    std::is_unsigned<T>::value &&
217    sizeof(T) > sizeof(unsigned int) &&
218    sizeof(T) <= sizeof(unsigned long long)),
219   size_t>::type
220   popcount(T x) {
221   return detail::popcountll(x);
222 }
223
224 /**
225  * Endianness detection and manipulation primitives.
226  */
227 namespace detail {
228
229 template <class T>
230 struct EndianIntBase {
231  public:
232   static T swap(T x);
233 };
234
235 #ifndef _MSC_VER
236
237 /**
238  * If we have the bswap_16 macro from byteswap.h, use it; otherwise, provide our
239  * own definition.
240  */
241 #ifdef bswap_16
242 # define our_bswap16 bswap_16
243 #else
244
245 template<class Int16>
246 inline constexpr typename std::enable_if<
247   sizeof(Int16) == 2,
248   Int16>::type
249 our_bswap16(Int16 x) {
250   return ((x >> 8) & 0xff) | ((x & 0xff) << 8);
251 }
252 #endif
253
254 #endif
255
256 #define FB_GEN(t, fn) \
257 template<> inline t EndianIntBase<t>::swap(t x) { return fn(x); }
258
259 // fn(x) expands to (x) if the second argument is empty, which is exactly
260 // what we want for [u]int8_t. Also, gcc 4.7 on Intel doesn't have
261 // __builtin_bswap16 for some reason, so we have to provide our own.
262 FB_GEN( int8_t,)
263 FB_GEN(uint8_t,)
264 #ifdef _MSC_VER
265 FB_GEN( int64_t, _byteswap_uint64)
266 FB_GEN(uint64_t, _byteswap_uint64)
267 FB_GEN( int32_t, _byteswap_ulong)
268 FB_GEN(uint32_t, _byteswap_ulong)
269 FB_GEN( int16_t, _byteswap_ushort)
270 FB_GEN(uint16_t, _byteswap_ushort)
271 #else
272 FB_GEN( int64_t, __builtin_bswap64)
273 FB_GEN(uint64_t, __builtin_bswap64)
274 FB_GEN( int32_t, __builtin_bswap32)
275 FB_GEN(uint32_t, __builtin_bswap32)
276 FB_GEN( int16_t, our_bswap16)
277 FB_GEN(uint16_t, our_bswap16)
278 #endif
279
280 #undef FB_GEN
281
282 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
283
284 template <class T>
285 struct EndianInt : public detail::EndianIntBase<T> {
286  public:
287   static T big(T x) { return EndianInt::swap(x); }
288   static T little(T x) { return x; }
289 };
290
291 #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
292
293 template <class T>
294 struct EndianInt : public detail::EndianIntBase<T> {
295  public:
296   static T big(T x) { return x; }
297   static T little(T x) { return EndianInt::swap(x); }
298 };
299
300 #else
301 # error Your machine uses a weird endianness!
302 #endif  /* __BYTE_ORDER__ */
303
304 }  // namespace detail
305
306 // big* convert between native and big-endian representations
307 // little* convert between native and little-endian representations
308 // swap* convert between big-endian and little-endian representations
309 //
310 // ntohs, htons == big16
311 // ntohl, htonl == big32
312 #define FB_GEN1(fn, t, sz) \
313   static t fn##sz(t x) { return fn<t>(x); } \
314
315 #define FB_GEN2(t, sz) \
316   FB_GEN1(swap, t, sz) \
317   FB_GEN1(big, t, sz) \
318   FB_GEN1(little, t, sz)
319
320 #define FB_GEN(sz) \
321   FB_GEN2(uint##sz##_t, sz) \
322   FB_GEN2(int##sz##_t, sz)
323
324 class Endian {
325  public:
326   enum class Order : uint8_t {
327     LITTLE,
328     BIG
329   };
330
331   static constexpr Order order =
332 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
333     Order::LITTLE;
334 #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
335     Order::BIG;
336 #else
337 # error Your machine uses a weird endianness!
338 #endif  /* __BYTE_ORDER__ */
339
340   template <class T> static T swap(T x) {
341     return detail::EndianInt<T>::swap(x);
342   }
343   template <class T> static T big(T x) {
344     return detail::EndianInt<T>::big(x);
345   }
346   template <class T> static T little(T x) {
347     return detail::EndianInt<T>::little(x);
348   }
349
350 #if !defined(__ANDROID__)
351   FB_GEN(64)
352   FB_GEN(32)
353   FB_GEN(16)
354   FB_GEN(8)
355 #endif
356 };
357
358 #undef FB_GEN
359 #undef FB_GEN2
360 #undef FB_GEN1
361
362 /**
363  * Fast bit iteration facility.
364  */
365
366
367 template <class BaseIter> class BitIterator;
368 template <class BaseIter>
369 BitIterator<BaseIter> findFirstSet(BitIterator<BaseIter>,
370                                    BitIterator<BaseIter>);
371 /**
372  * Wrapper around an iterator over an integer type that iterates
373  * over its underlying bits in LSb to MSb order.
374  *
375  * BitIterator models the same iterator concepts as the base iterator.
376  */
377 template <class BaseIter>
378 class BitIterator
379   : public bititerator_detail::BitIteratorBase<BaseIter>::type {
380  public:
381   /**
382    * Return the number of bits in an element of the underlying iterator.
383    */
384   static unsigned int bitsPerBlock() {
385     return std::numeric_limits<
386       typename std::make_unsigned<
387         typename std::iterator_traits<BaseIter>::value_type
388       >::type
389     >::digits;
390   }
391
392   /**
393    * Construct a BitIterator that points at a given bit offset (default 0)
394    * in iter.
395    */
396   #pragma GCC diagnostic push // bitOffset shadows a member
397   #pragma GCC diagnostic ignored "-Wshadow"
398   explicit BitIterator(const BaseIter& iter, size_t bitOffset=0)
399     : bititerator_detail::BitIteratorBase<BaseIter>::type(iter),
400       bitOffset_(bitOffset) {
401     assert(bitOffset_ < bitsPerBlock());
402   }
403   #pragma GCC diagnostic pop
404
405   size_t bitOffset() const {
406     return bitOffset_;
407   }
408
409   void advanceToNextBlock() {
410     bitOffset_ = 0;
411     ++this->base_reference();
412   }
413
414   BitIterator& operator=(const BaseIter& other) {
415     this->~BitIterator();
416     new (this) BitIterator(other);
417     return *this;
418   }
419
420  private:
421   friend class boost::iterator_core_access;
422   friend BitIterator findFirstSet<>(BitIterator, BitIterator);
423
424   typedef bititerator_detail::BitReference<
425       typename std::iterator_traits<BaseIter>::reference,
426       typename std::iterator_traits<BaseIter>::value_type
427     > BitRef;
428
429   void advanceInBlock(size_t n) {
430     bitOffset_ += n;
431     assert(bitOffset_ < bitsPerBlock());
432   }
433
434   BitRef dereference() const {
435     return BitRef(*this->base_reference(), bitOffset_);
436   }
437
438   void advance(ssize_t n) {
439     size_t bpb = bitsPerBlock();
440     ssize_t blocks = n / bpb;
441     bitOffset_ += n % bpb;
442     if (bitOffset_ >= bpb) {
443       bitOffset_ -= bpb;
444       ++blocks;
445     }
446     this->base_reference() += blocks;
447   }
448
449   void increment() {
450     if (++bitOffset_ == bitsPerBlock()) {
451       advanceToNextBlock();
452     }
453   }
454
455   void decrement() {
456     if (bitOffset_-- == 0) {
457       bitOffset_ = bitsPerBlock() - 1;
458       --this->base_reference();
459     }
460   }
461
462   bool equal(const BitIterator& other) const {
463     return (bitOffset_ == other.bitOffset_ &&
464             this->base_reference() == other.base_reference());
465   }
466
467   ssize_t distance_to(const BitIterator& other) const {
468     return
469       (other.base_reference() - this->base_reference()) * bitsPerBlock() +
470       other.bitOffset_ - bitOffset_;
471   }
472
473   unsigned int bitOffset_;
474 };
475
476 /**
477  * Helper function, so you can write
478  * auto bi = makeBitIterator(container.begin());
479  */
480 template <class BaseIter>
481 BitIterator<BaseIter> makeBitIterator(const BaseIter& iter) {
482   return BitIterator<BaseIter>(iter);
483 }
484
485
486 /**
487  * Find first bit set in a range of bit iterators.
488  * 4.5x faster than the obvious std::find(begin, end, true);
489  */
490 template <class BaseIter>
491 BitIterator<BaseIter> findFirstSet(BitIterator<BaseIter> begin,
492                                    BitIterator<BaseIter> end) {
493   // shortcut to avoid ugly static_cast<>
494   static const typename BaseIter::value_type one = 1;
495
496   while (begin.base() != end.base()) {
497     typename BaseIter::value_type v = *begin.base();
498     // mask out the bits that don't matter (< begin.bitOffset)
499     v &= ~((one << begin.bitOffset()) - 1);
500     size_t firstSet = findFirstSet(v);
501     if (firstSet) {
502       --firstSet;  // now it's 0-based
503       assert(firstSet >= begin.bitOffset());
504       begin.advanceInBlock(firstSet - begin.bitOffset());
505       return begin;
506     }
507     begin.advanceToNextBlock();
508   }
509
510   // now begin points to the same block as end
511   if (end.bitOffset() != 0) {  // assume end is dereferenceable
512     typename BaseIter::value_type v = *begin.base();
513     // mask out the bits that don't matter (< begin.bitOffset)
514     v &= ~((one << begin.bitOffset()) - 1);
515     // mask out the bits that don't matter (>= end.bitOffset)
516     v &= (one << end.bitOffset()) - 1;
517     size_t firstSet = findFirstSet(v);
518     if (firstSet) {
519       --firstSet;  // now it's 0-based
520       assert(firstSet >= begin.bitOffset());
521       begin.advanceInBlock(firstSet - begin.bitOffset());
522       return begin;
523     }
524   }
525
526   return end;
527 }
528
529
530 template <class T, class Enable=void> struct Unaligned;
531
532 /**
533  * Representation of an unaligned value of a POD type.
534  */
535 FOLLY_PACK_PUSH
536 template <class T>
537 struct Unaligned<
538     T,
539     typename std::enable_if<std::is_pod<T>::value>::type> {
540   Unaligned() = default;  // uninitialized
541   /* implicit */ Unaligned(T v) : value(v) { }
542   T value;
543 } FOLLY_PACK_ATTR;
544 FOLLY_PACK_POP
545
546 /**
547  * Read an unaligned value of type T and return it.
548  */
549 template <class T>
550 inline T loadUnaligned(const void* p) {
551   static_assert(sizeof(Unaligned<T>) == sizeof(T), "Invalid unaligned size");
552   static_assert(alignof(Unaligned<T>) == 1, "Invalid alignment");
553   return static_cast<const Unaligned<T>*>(p)->value;
554 }
555
556 /**
557  * Write an unaligned value of type T.
558  */
559 template <class T>
560 inline void storeUnaligned(void* p, T value) {
561   static_assert(sizeof(Unaligned<T>) == sizeof(T), "Invalid unaligned size");
562   static_assert(alignof(Unaligned<T>) == 1, "Invalid alignment");
563   new (p) Unaligned<T>(value);
564 }
565
566 }  // namespace folly
567
568 #endif /* FOLLY_BITS_H_ */