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