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)
282 struct EndianInt : public EndianIntBase<T> {
285 return kIsLittleEndian ? EndianInt::swap(x) : x;
287 static T little(T x) {
288 return kIsBigEndian ? EndianInt::swap(x) : x;
292 } // namespace detail
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
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); } \
303 #define FB_GEN2(t, sz) \
304 FB_GEN1(swap, t, sz) \
305 FB_GEN1(big, t, sz) \
306 FB_GEN1(little, t, sz)
309 FB_GEN2(uint##sz##_t, sz) \
310 FB_GEN2(int##sz##_t, sz)
314 enum class Order : uint8_t {
319 static constexpr Order order = kIsLittleEndian ? Order::LITTLE : Order::BIG;
321 template <class T> static T swap(T x) {
322 return folly::detail::EndianInt<T>::swap(x);
324 template <class T> static T big(T x) {
325 return folly::detail::EndianInt<T>::big(x);
327 template <class T> static T little(T x) {
328 return folly::detail::EndianInt<T>::little(x);
331 #if !defined(__ANDROID__)
344 * Fast bit iteration facility.
348 template <class BaseIter> class BitIterator;
349 template <class BaseIter>
350 BitIterator<BaseIter> findFirstSet(BitIterator<BaseIter>,
351 BitIterator<BaseIter>);
353 * Wrapper around an iterator over an integer type that iterates
354 * over its underlying bits in LSb to MSb order.
356 * BitIterator models the same iterator concepts as the base iterator.
358 template <class BaseIter>
360 : public bititerator_detail::BitIteratorBase<BaseIter>::type {
363 * Return the number of bits in an element of the underlying iterator.
365 static unsigned int bitsPerBlock() {
366 return std::numeric_limits<
367 typename std::make_unsigned<
368 typename std::iterator_traits<BaseIter>::value_type
374 * Construct a BitIterator that points at a given bit offset (default 0)
377 #pragma GCC diagnostic push // bitOffset shadows a member
378 #pragma GCC diagnostic ignored "-Wshadow"
379 explicit BitIterator(const BaseIter& iter, size_t bitOffset=0)
380 : bititerator_detail::BitIteratorBase<BaseIter>::type(iter),
381 bitOffset_(bitOffset) {
382 assert(bitOffset_ < bitsPerBlock());
384 #pragma GCC diagnostic pop
386 size_t bitOffset() const {
390 void advanceToNextBlock() {
392 ++this->base_reference();
395 BitIterator& operator=(const BaseIter& other) {
396 this->~BitIterator();
397 new (this) BitIterator(other);
402 friend class boost::iterator_core_access;
403 friend BitIterator findFirstSet<>(BitIterator, BitIterator);
405 typedef bititerator_detail::BitReference<
406 typename std::iterator_traits<BaseIter>::reference,
407 typename std::iterator_traits<BaseIter>::value_type
410 void advanceInBlock(size_t n) {
412 assert(bitOffset_ < bitsPerBlock());
415 BitRef dereference() const {
416 return BitRef(*this->base_reference(), bitOffset_);
419 void advance(ssize_t n) {
420 size_t bpb = bitsPerBlock();
421 ssize_t blocks = n / bpb;
422 bitOffset_ += n % bpb;
423 if (bitOffset_ >= bpb) {
427 this->base_reference() += blocks;
431 if (++bitOffset_ == bitsPerBlock()) {
432 advanceToNextBlock();
437 if (bitOffset_-- == 0) {
438 bitOffset_ = bitsPerBlock() - 1;
439 --this->base_reference();
443 bool equal(const BitIterator& other) const {
444 return (bitOffset_ == other.bitOffset_ &&
445 this->base_reference() == other.base_reference());
448 ssize_t distance_to(const BitIterator& other) const {
450 (other.base_reference() - this->base_reference()) * bitsPerBlock() +
451 other.bitOffset_ - bitOffset_;
454 unsigned int bitOffset_;
458 * Helper function, so you can write
459 * auto bi = makeBitIterator(container.begin());
461 template <class BaseIter>
462 BitIterator<BaseIter> makeBitIterator(const BaseIter& iter) {
463 return BitIterator<BaseIter>(iter);
468 * Find first bit set in a range of bit iterators.
469 * 4.5x faster than the obvious std::find(begin, end, true);
471 template <class BaseIter>
472 BitIterator<BaseIter> findFirstSet(BitIterator<BaseIter> begin,
473 BitIterator<BaseIter> end) {
474 // shortcut to avoid ugly static_cast<>
475 static const typename BaseIter::value_type one = 1;
477 while (begin.base() != end.base()) {
478 typename BaseIter::value_type v = *begin.base();
479 // mask out the bits that don't matter (< begin.bitOffset)
480 v &= ~((one << begin.bitOffset()) - 1);
481 size_t firstSet = findFirstSet(v);
483 --firstSet; // now it's 0-based
484 assert(firstSet >= begin.bitOffset());
485 begin.advanceInBlock(firstSet - begin.bitOffset());
488 begin.advanceToNextBlock();
491 // now begin points to the same block as end
492 if (end.bitOffset() != 0) { // assume end is dereferenceable
493 typename BaseIter::value_type v = *begin.base();
494 // mask out the bits that don't matter (< begin.bitOffset)
495 v &= ~((one << begin.bitOffset()) - 1);
496 // mask out the bits that don't matter (>= end.bitOffset)
497 v &= (one << end.bitOffset()) - 1;
498 size_t firstSet = findFirstSet(v);
500 --firstSet; // now it's 0-based
501 assert(firstSet >= begin.bitOffset());
502 begin.advanceInBlock(firstSet - begin.bitOffset());
511 template <class T, class Enable=void> struct Unaligned;
514 * Representation of an unaligned value of a POD type.
520 typename std::enable_if<std::is_pod<T>::value>::type> {
521 Unaligned() = default; // uninitialized
522 /* implicit */ Unaligned(T v) : value(v) { }
528 * Read an unaligned value of type T and return it.
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 if (kHasUnalignedAccess) {
535 return static_cast<const Unaligned<T>*>(p)->value;
538 memcpy(&value, p, sizeof(T));
544 * Write an unaligned value of type T.
547 inline void storeUnaligned(void* p, T value) {
548 static_assert(sizeof(Unaligned<T>) == sizeof(T), "Invalid unaligned size");
549 static_assert(alignof(Unaligned<T>) == 1, "Invalid alignment");
550 if (kHasUnalignedAccess) {
551 new (p) Unaligned<T>(value);
553 memcpy(p, &value, sizeof(T));