2 * Copyright 2017 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>
66 #include <folly/portability/Builtins.h>
68 #include <folly/Assume.h>
69 #include <folly/detail/BitsDetail.h>
70 #include <folly/detail/BitIteratorDetail.h>
71 #include <folly/Likely.h>
77 #include <type_traits>
78 #include <boost/iterator/iterator_adaptor.hpp>
83 // Generate overloads for findFirstSet as wrappers around
84 // appropriate ffs, ffsl, ffsll gcc builtins
86 inline FOLLY_INTRINSIC_CONSTEXPR
87 typename std::enable_if<
88 (std::is_integral<T>::value &&
89 std::is_unsigned<T>::value &&
90 sizeof(T) <= sizeof(unsigned int)),
93 return static_cast<unsigned int>(__builtin_ffs(static_cast<int>(x)));
97 inline FOLLY_INTRINSIC_CONSTEXPR
98 typename std::enable_if<
99 (std::is_integral<T>::value &&
100 std::is_unsigned<T>::value &&
101 sizeof(T) > sizeof(unsigned int) &&
102 sizeof(T) <= sizeof(unsigned long)),
105 return static_cast<unsigned int>(__builtin_ffsl(static_cast<long>(x)));
109 inline FOLLY_INTRINSIC_CONSTEXPR
110 typename std::enable_if<
111 (std::is_integral<T>::value &&
112 std::is_unsigned<T>::value &&
113 sizeof(T) > sizeof(unsigned long) &&
114 sizeof(T) <= sizeof(unsigned long long)),
117 return static_cast<unsigned int>(__builtin_ffsll(static_cast<long long>(x)));
121 inline FOLLY_INTRINSIC_CONSTEXPR
122 typename std::enable_if<
123 (std::is_integral<T>::value && std::is_signed<T>::value),
126 // Note that conversion from a signed type to the corresponding unsigned
127 // type is technically implementation-defined, but will likely work
128 // on any impementation that uses two's complement.
129 return findFirstSet(static_cast<typename std::make_unsigned<T>::type>(x));
132 // findLastSet: return the 1-based index of the highest bit set
133 // for x > 0, findLastSet(x) == 1 + floor(log2(x))
135 inline FOLLY_INTRINSIC_CONSTEXPR
136 typename std::enable_if<
137 (std::is_integral<T>::value &&
138 std::is_unsigned<T>::value &&
139 sizeof(T) <= sizeof(unsigned int)),
142 // If X is a power of two X - Y = ((X - 1) ^ Y) + 1. Doing this transformation
143 // allows GCC to remove its own xor that it adds to implement clz using bsr
144 return x ? ((8 * sizeof(unsigned int) - 1) ^ __builtin_clz(x)) + 1 : 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) - 1) ^ __builtin_clzl(x)) + 1 : 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) - 1) ^ __builtin_clzll(x)) + 1
173 inline FOLLY_INTRINSIC_CONSTEXPR
174 typename std::enable_if<
175 (std::is_integral<T>::value &&
176 std::is_signed<T>::value),
179 return findLastSet(static_cast<typename std::make_unsigned<T>::type>(x));
183 inline FOLLY_INTRINSIC_CONSTEXPR
184 typename std::enable_if<
185 std::is_integral<T>::value && std::is_unsigned<T>::value,
188 return v ? (T(1) << findLastSet(v - 1)) : 1;
192 inline FOLLY_INTRINSIC_CONSTEXPR typename std::
193 enable_if<std::is_integral<T>::value && std::is_unsigned<T>::value, T>::type
195 return v ? (T(1) << (findLastSet(v) - 1)) : 0;
199 inline constexpr typename std::enable_if<
200 std::is_integral<T>::value && std::is_unsigned<T>::value,
203 return (v != 0) && !(v & (v - 1));
210 inline typename std::enable_if<
211 (std::is_integral<T>::value &&
212 std::is_unsigned<T>::value &&
213 sizeof(T) <= sizeof(unsigned int)),
216 return size_t(detail::popcount(x));
220 inline typename std::enable_if<
221 (std::is_integral<T>::value &&
222 std::is_unsigned<T>::value &&
223 sizeof(T) > sizeof(unsigned int) &&
224 sizeof(T) <= sizeof(unsigned long long)),
227 return size_t(detail::popcountll(x));
231 * Endianness detection and manipulation primitives.
236 struct EndianIntBase {
241 #define FB_GEN(t, fn) \
243 inline t EndianIntBase<t>::swap(t x) { \
244 return t(fn(std::make_unsigned<t>::type(x))); \
247 // fn(x) expands to (x) if the second argument is empty, which is exactly
248 // what we want for [u]int8_t.
252 FB_GEN( int64_t, _byteswap_uint64)
253 FB_GEN(uint64_t, _byteswap_uint64)
254 FB_GEN( int32_t, _byteswap_ulong)
255 FB_GEN(uint32_t, _byteswap_ulong)
256 FB_GEN( int16_t, _byteswap_ushort)
257 FB_GEN(uint16_t, _byteswap_ushort)
259 FB_GEN( int64_t, __builtin_bswap64)
260 FB_GEN(uint64_t, __builtin_bswap64)
261 FB_GEN( int32_t, __builtin_bswap32)
262 FB_GEN(uint32_t, __builtin_bswap32)
263 FB_GEN( int16_t, __builtin_bswap16)
264 FB_GEN(uint16_t, __builtin_bswap16)
270 struct EndianInt : public EndianIntBase<T> {
273 return kIsLittleEndian ? EndianInt::swap(x) : x;
275 static T little(T x) {
276 return kIsBigEndian ? EndianInt::swap(x) : x;
280 } // namespace detail
282 // big* convert between native and big-endian representations
283 // little* convert between native and little-endian representations
284 // swap* convert between big-endian and little-endian representations
286 // ntohs, htons == big16
287 // ntohl, htonl == big32
288 #define FB_GEN1(fn, t, sz) \
289 static t fn##sz(t x) { return fn<t>(x); } \
291 #define FB_GEN2(t, sz) \
292 FB_GEN1(swap, t, sz) \
293 FB_GEN1(big, t, sz) \
294 FB_GEN1(little, t, sz)
297 FB_GEN2(uint##sz##_t, sz) \
298 FB_GEN2(int##sz##_t, sz)
302 enum class Order : uint8_t {
307 static constexpr Order order = kIsLittleEndian ? Order::LITTLE : Order::BIG;
309 template <class T> static T swap(T x) {
310 return folly::detail::EndianInt<T>::swap(x);
312 template <class T> static T big(T x) {
313 return folly::detail::EndianInt<T>::big(x);
315 template <class T> static T little(T x) {
316 return folly::detail::EndianInt<T>::little(x);
319 #if !defined(__ANDROID__)
332 * Fast bit iteration facility.
336 template <class BaseIter> class BitIterator;
337 template <class BaseIter>
338 BitIterator<BaseIter> findFirstSet(BitIterator<BaseIter>,
339 BitIterator<BaseIter>);
341 * Wrapper around an iterator over an integer type that iterates
342 * over its underlying bits in LSb to MSb order.
344 * BitIterator models the same iterator concepts as the base iterator.
346 template <class BaseIter>
348 : public bititerator_detail::BitIteratorBase<BaseIter>::type {
351 * Return the number of bits in an element of the underlying iterator.
353 static unsigned int bitsPerBlock() {
354 return std::numeric_limits<
355 typename std::make_unsigned<
356 typename std::iterator_traits<BaseIter>::value_type
362 * Construct a BitIterator that points at a given bit offset (default 0)
365 explicit BitIterator(const BaseIter& iter, size_t bitOff=0)
366 : bititerator_detail::BitIteratorBase<BaseIter>::type(iter),
368 assert(bitOffset_ < bitsPerBlock());
371 size_t bitOffset() const {
375 void advanceToNextBlock() {
377 ++this->base_reference();
380 BitIterator& operator=(const BaseIter& other) {
381 this->~BitIterator();
382 new (this) BitIterator(other);
387 friend class boost::iterator_core_access;
388 friend BitIterator findFirstSet<>(BitIterator, BitIterator);
390 typedef bititerator_detail::BitReference<
391 typename std::iterator_traits<BaseIter>::reference,
392 typename std::iterator_traits<BaseIter>::value_type
395 void advanceInBlock(size_t n) {
397 assert(bitOffset_ < bitsPerBlock());
400 BitRef dereference() const {
401 return BitRef(*this->base_reference(), bitOffset_);
404 void advance(ssize_t n) {
405 size_t bpb = bitsPerBlock();
406 ssize_t blocks = n / ssize_t(bpb);
407 bitOffset_ += n % bpb;
408 if (bitOffset_ >= bpb) {
412 this->base_reference() += blocks;
416 if (++bitOffset_ == bitsPerBlock()) {
417 advanceToNextBlock();
422 if (bitOffset_-- == 0) {
423 bitOffset_ = bitsPerBlock() - 1;
424 --this->base_reference();
428 bool equal(const BitIterator& other) const {
429 return (bitOffset_ == other.bitOffset_ &&
430 this->base_reference() == other.base_reference());
433 ssize_t distance_to(const BitIterator& other) const {
435 (other.base_reference() - this->base_reference()) * bitsPerBlock() +
436 other.bitOffset_ - bitOffset_);
443 * Helper function, so you can write
444 * auto bi = makeBitIterator(container.begin());
446 template <class BaseIter>
447 BitIterator<BaseIter> makeBitIterator(const BaseIter& iter) {
448 return BitIterator<BaseIter>(iter);
453 * Find first bit set in a range of bit iterators.
454 * 4.5x faster than the obvious std::find(begin, end, true);
456 template <class BaseIter>
457 BitIterator<BaseIter> findFirstSet(BitIterator<BaseIter> begin,
458 BitIterator<BaseIter> end) {
459 // shortcut to avoid ugly static_cast<>
460 static const typename BaseIter::value_type one = 1;
462 while (begin.base() != end.base()) {
463 typename BaseIter::value_type v = *begin.base();
464 // mask out the bits that don't matter (< begin.bitOffset)
465 v &= ~((one << begin.bitOffset()) - 1);
466 size_t firstSet = findFirstSet(v);
468 --firstSet; // now it's 0-based
469 assert(firstSet >= begin.bitOffset());
470 begin.advanceInBlock(firstSet - begin.bitOffset());
473 begin.advanceToNextBlock();
476 // now begin points to the same block as end
477 if (end.bitOffset() != 0) { // assume end is dereferenceable
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 // mask out the bits that don't matter (>= end.bitOffset)
482 v &= (one << end.bitOffset()) - 1;
483 size_t firstSet = findFirstSet(v);
485 --firstSet; // now it's 0-based
486 assert(firstSet >= begin.bitOffset());
487 begin.advanceInBlock(firstSet - begin.bitOffset());
496 template <class T, class Enable=void> struct Unaligned;
499 * Representation of an unaligned value of a POD type.
505 typename std::enable_if<std::is_pod<T>::value>::type> {
506 Unaligned() = default; // uninitialized
507 /* implicit */ Unaligned(T v) : value(v) { }
513 * Read an unaligned value of type T and return it.
516 inline T loadUnaligned(const void* p) {
517 static_assert(sizeof(Unaligned<T>) == sizeof(T), "Invalid unaligned size");
518 static_assert(alignof(Unaligned<T>) == 1, "Invalid alignment");
519 if (kHasUnalignedAccess) {
520 return static_cast<const Unaligned<T>*>(p)->value;
523 memcpy(&value, p, sizeof(T));
529 * Write an unaligned value of type T.
532 inline void storeUnaligned(void* p, T value) {
533 static_assert(sizeof(Unaligned<T>) == sizeof(T), "Invalid unaligned size");
534 static_assert(alignof(Unaligned<T>) == 1, "Invalid alignment");
535 if (kHasUnalignedAccess) {
536 // Prior to C++14, the spec says that a placement new like this
537 // is required to check that p is not nullptr, and to do nothing
538 // if p is a nullptr. By assuming it's not a nullptr, we get a
539 // nice loud segfault in optimized builds if p is nullptr, rather
540 // than just silently doing nothing.
541 folly::assume(p != nullptr);
542 new (p) Unaligned<T>(value);
544 memcpy(p, &value, sizeof(T));