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