2 * Copyright 2016 Facebook, Inc.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
18 * Various low-level, bit-manipulation routines.
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)
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))
29 * nextPowTwo(x) [constexpr]
30 * Finds the next power of two >= x.
32 * isPowTwo(x) [constexpr]
33 * return true iff x is a power of two
36 * return the number of 1 bits in x
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
45 * Wrapper around an iterator over an integral type that iterates
46 * over its underlying bits in MSb to LSb order
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
52 * @author Tudor Bosman (tudorb@fb.com)
57 #if !defined(__clang__) && !(defined(_MSC_VER) && (_MSC_VER < 1900))
58 #define FOLLY_INTRINSIC_CONSTEXPR constexpr
60 // GCC and MSVC 2015+ are the only compilers with
61 // intrinsics constexpr.
62 #define FOLLY_INTRINSIC_CONSTEXPR const
65 #include <folly/Portability.h>
67 #include <folly/detail/BitsDetail.h>
68 #include <folly/detail/BitIteratorDetail.h>
69 #include <folly/Likely.h>
71 #if FOLLY_HAVE_BYTESWAP_H
72 # include <byteswap.h>
79 #include <type_traits>
80 #include <boost/iterator/iterator_adaptor.hpp>
85 // Generate overloads for findFirstSet as wrappers around
86 // appropriate ffs, ffsl, ffsll gcc builtins
88 inline FOLLY_INTRINSIC_CONSTEXPR
89 typename std::enable_if<
90 (std::is_integral<T>::value &&
91 std::is_unsigned<T>::value &&
92 sizeof(T) <= sizeof(unsigned int)),
95 return __builtin_ffs(x);
99 inline FOLLY_INTRINSIC_CONSTEXPR
100 typename std::enable_if<
101 (std::is_integral<T>::value &&
102 std::is_unsigned<T>::value &&
103 sizeof(T) > sizeof(unsigned int) &&
104 sizeof(T) <= sizeof(unsigned long)),
107 return __builtin_ffsl(x);
111 inline FOLLY_INTRINSIC_CONSTEXPR
112 typename std::enable_if<
113 (std::is_integral<T>::value &&
114 std::is_unsigned<T>::value &&
115 sizeof(T) > sizeof(unsigned long) &&
116 sizeof(T) <= sizeof(unsigned long long)),
119 return __builtin_ffsll(x);
123 inline FOLLY_INTRINSIC_CONSTEXPR
124 typename std::enable_if<
125 (std::is_integral<T>::value && std::is_signed<T>::value),
128 // Note that conversion from a signed type to the corresponding unsigned
129 // type is technically implementation-defined, but will likely work
130 // on any impementation that uses two's complement.
131 return findFirstSet(static_cast<typename std::make_unsigned<T>::type>(x));
134 // findLastSet: return the 1-based index of the highest bit set
135 // for x > 0, findLastSet(x) == 1 + floor(log2(x))
137 inline FOLLY_INTRINSIC_CONSTEXPR
138 typename std::enable_if<
139 (std::is_integral<T>::value &&
140 std::is_unsigned<T>::value &&
141 sizeof(T) <= sizeof(unsigned int)),
144 return x ? 8 * sizeof(unsigned int) - __builtin_clz(x) : 0;
148 inline FOLLY_INTRINSIC_CONSTEXPR
149 typename std::enable_if<
150 (std::is_integral<T>::value &&
151 std::is_unsigned<T>::value &&
152 sizeof(T) > sizeof(unsigned int) &&
153 sizeof(T) <= sizeof(unsigned long)),
156 return x ? 8 * sizeof(unsigned long) - __builtin_clzl(x) : 0;
160 inline FOLLY_INTRINSIC_CONSTEXPR
161 typename std::enable_if<
162 (std::is_integral<T>::value &&
163 std::is_unsigned<T>::value &&
164 sizeof(T) > sizeof(unsigned long) &&
165 sizeof(T) <= sizeof(unsigned long long)),
168 return x ? 8 * sizeof(unsigned long long) - __builtin_clzll(x) : 0;
172 inline FOLLY_INTRINSIC_CONSTEXPR
173 typename std::enable_if<
174 (std::is_integral<T>::value &&
175 std::is_signed<T>::value),
178 return findLastSet(static_cast<typename std::make_unsigned<T>::type>(x));
182 inline FOLLY_INTRINSIC_CONSTEXPR
183 typename std::enable_if<
184 std::is_integral<T>::value && std::is_unsigned<T>::value,
187 return v ? (1ul << findLastSet(v - 1)) : 1;
192 typename std::enable_if<
193 std::is_integral<T>::value && std::is_unsigned<T>::value,
196 return (v != 0) && !(v & (v - 1));
203 inline typename std::enable_if<
204 (std::is_integral<T>::value &&
205 std::is_unsigned<T>::value &&
206 sizeof(T) <= sizeof(unsigned int)),
209 return detail::popcount(x);
213 inline typename std::enable_if<
214 (std::is_integral<T>::value &&
215 std::is_unsigned<T>::value &&
216 sizeof(T) > sizeof(unsigned int) &&
217 sizeof(T) <= sizeof(unsigned long long)),
220 return detail::popcountll(x);
224 * Endianness detection and manipulation primitives.
229 struct EndianIntBase {
237 * If we have the bswap_16 macro from byteswap.h, use it; otherwise, provide our
241 # define our_bswap16 bswap_16
244 template<class Int16>
245 inline constexpr typename std::enable_if<
248 our_bswap16(Int16 x) {
249 return ((x >> 8) & 0xff) | ((x & 0xff) << 8);
255 #define FB_GEN(t, fn) \
256 template<> inline t EndianIntBase<t>::swap(t x) { return fn(x); }
258 // fn(x) expands to (x) if the second argument is empty, which is exactly
259 // what we want for [u]int8_t. Also, gcc 4.7 on Intel doesn't have
260 // __builtin_bswap16 for some reason, so we have to provide our own.
264 FB_GEN( int64_t, _byteswap_uint64)
265 FB_GEN(uint64_t, _byteswap_uint64)
266 FB_GEN( int32_t, _byteswap_ulong)
267 FB_GEN(uint32_t, _byteswap_ulong)
268 FB_GEN( int16_t, _byteswap_ushort)
269 FB_GEN(uint16_t, _byteswap_ushort)
271 FB_GEN( int64_t, __builtin_bswap64)
272 FB_GEN(uint64_t, __builtin_bswap64)
273 FB_GEN( int32_t, __builtin_bswap32)
274 FB_GEN(uint32_t, __builtin_bswap32)
275 FB_GEN( int16_t, our_bswap16)
276 FB_GEN(uint16_t, our_bswap16)
281 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
284 struct EndianInt : public EndianIntBase<T> {
286 static T big(T x) { return EndianInt::swap(x); }
287 static T little(T x) { return x; }
290 #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
293 struct EndianInt : public EndianIntBase<T> {
295 static T big(T x) { return x; }
296 static T little(T x) { return EndianInt::swap(x); }
300 # error Your machine uses a weird endianness!
301 #endif /* __BYTE_ORDER__ */
303 } // namespace detail
305 // big* convert between native and big-endian representations
306 // little* convert between native and little-endian representations
307 // swap* convert between big-endian and little-endian representations
309 // ntohs, htons == big16
310 // ntohl, htonl == big32
311 #define FB_GEN1(fn, t, sz) \
312 static t fn##sz(t x) { return fn<t>(x); } \
314 #define FB_GEN2(t, sz) \
315 FB_GEN1(swap, t, sz) \
316 FB_GEN1(big, t, sz) \
317 FB_GEN1(little, t, sz)
320 FB_GEN2(uint##sz##_t, sz) \
321 FB_GEN2(int##sz##_t, sz)
325 enum class Order : uint8_t {
330 static constexpr Order order =
331 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
333 #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
336 # error Your machine uses a weird endianness!
337 #endif /* __BYTE_ORDER__ */
339 template <class T> static T swap(T x) {
340 return folly::detail::EndianInt<T>::swap(x);
342 template <class T> static T big(T x) {
343 return folly::detail::EndianInt<T>::big(x);
345 template <class T> static T little(T x) {
346 return folly::detail::EndianInt<T>::little(x);
349 #if !defined(__ANDROID__)
362 * Fast bit iteration facility.
366 template <class BaseIter> class BitIterator;
367 template <class BaseIter>
368 BitIterator<BaseIter> findFirstSet(BitIterator<BaseIter>,
369 BitIterator<BaseIter>);
371 * Wrapper around an iterator over an integer type that iterates
372 * over its underlying bits in LSb to MSb order.
374 * BitIterator models the same iterator concepts as the base iterator.
376 template <class BaseIter>
378 : public bititerator_detail::BitIteratorBase<BaseIter>::type {
381 * Return the number of bits in an element of the underlying iterator.
383 static unsigned int bitsPerBlock() {
384 return std::numeric_limits<
385 typename std::make_unsigned<
386 typename std::iterator_traits<BaseIter>::value_type
392 * Construct a BitIterator that points at a given bit offset (default 0)
395 #pragma GCC diagnostic push // bitOffset shadows a member
396 #pragma GCC diagnostic ignored "-Wshadow"
397 explicit BitIterator(const BaseIter& iter, size_t bitOffset=0)
398 : bititerator_detail::BitIteratorBase<BaseIter>::type(iter),
399 bitOffset_(bitOffset) {
400 assert(bitOffset_ < bitsPerBlock());
402 #pragma GCC diagnostic pop
404 size_t bitOffset() const {
408 void advanceToNextBlock() {
410 ++this->base_reference();
413 BitIterator& operator=(const BaseIter& other) {
414 this->~BitIterator();
415 new (this) BitIterator(other);
420 friend class boost::iterator_core_access;
421 friend BitIterator findFirstSet<>(BitIterator, BitIterator);
423 typedef bititerator_detail::BitReference<
424 typename std::iterator_traits<BaseIter>::reference,
425 typename std::iterator_traits<BaseIter>::value_type
428 void advanceInBlock(size_t n) {
430 assert(bitOffset_ < bitsPerBlock());
433 BitRef dereference() const {
434 return BitRef(*this->base_reference(), bitOffset_);
437 void advance(ssize_t n) {
438 size_t bpb = bitsPerBlock();
439 ssize_t blocks = n / bpb;
440 bitOffset_ += n % bpb;
441 if (bitOffset_ >= bpb) {
445 this->base_reference() += blocks;
449 if (++bitOffset_ == bitsPerBlock()) {
450 advanceToNextBlock();
455 if (bitOffset_-- == 0) {
456 bitOffset_ = bitsPerBlock() - 1;
457 --this->base_reference();
461 bool equal(const BitIterator& other) const {
462 return (bitOffset_ == other.bitOffset_ &&
463 this->base_reference() == other.base_reference());
466 ssize_t distance_to(const BitIterator& other) const {
468 (other.base_reference() - this->base_reference()) * bitsPerBlock() +
469 other.bitOffset_ - bitOffset_;
472 unsigned int bitOffset_;
476 * Helper function, so you can write
477 * auto bi = makeBitIterator(container.begin());
479 template <class BaseIter>
480 BitIterator<BaseIter> makeBitIterator(const BaseIter& iter) {
481 return BitIterator<BaseIter>(iter);
486 * Find first bit set in a range of bit iterators.
487 * 4.5x faster than the obvious std::find(begin, end, true);
489 template <class BaseIter>
490 BitIterator<BaseIter> findFirstSet(BitIterator<BaseIter> begin,
491 BitIterator<BaseIter> end) {
492 // shortcut to avoid ugly static_cast<>
493 static const typename BaseIter::value_type one = 1;
495 while (begin.base() != end.base()) {
496 typename BaseIter::value_type v = *begin.base();
497 // mask out the bits that don't matter (< begin.bitOffset)
498 v &= ~((one << begin.bitOffset()) - 1);
499 size_t firstSet = findFirstSet(v);
501 --firstSet; // now it's 0-based
502 assert(firstSet >= begin.bitOffset());
503 begin.advanceInBlock(firstSet - begin.bitOffset());
506 begin.advanceToNextBlock();
509 // now begin points to the same block as end
510 if (end.bitOffset() != 0) { // assume end is dereferenceable
511 typename BaseIter::value_type v = *begin.base();
512 // mask out the bits that don't matter (< begin.bitOffset)
513 v &= ~((one << begin.bitOffset()) - 1);
514 // mask out the bits that don't matter (>= end.bitOffset)
515 v &= (one << end.bitOffset()) - 1;
516 size_t firstSet = findFirstSet(v);
518 --firstSet; // now it's 0-based
519 assert(firstSet >= begin.bitOffset());
520 begin.advanceInBlock(firstSet - begin.bitOffset());
529 template <class T, class Enable=void> struct Unaligned;
532 * Representation of an unaligned value of a POD type.
538 typename std::enable_if<std::is_pod<T>::value>::type> {
539 Unaligned() = default; // uninitialized
540 /* implicit */ Unaligned(T v) : value(v) { }
546 * Read an unaligned value of type T and return it.
549 inline T loadUnaligned(const void* p) {
550 static_assert(sizeof(Unaligned<T>) == sizeof(T), "Invalid unaligned size");
551 static_assert(alignof(Unaligned<T>) == 1, "Invalid alignment");
552 if (kHasUnalignedAccess) {
553 return static_cast<const Unaligned<T>*>(p)->value;
556 memcpy(&value, p, sizeof(T));
562 * Write an unaligned value of type T.
565 inline void storeUnaligned(void* p, T value) {
566 static_assert(sizeof(Unaligned<T>) == sizeof(T), "Invalid unaligned size");
567 static_assert(alignof(Unaligned<T>) == 1, "Invalid alignment");
568 if (kHasUnalignedAccess) {
569 new (p) Unaligned<T>(value);
571 memcpy(p, &value, sizeof(T));