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>
66 #include <folly/portability/Builtins.h>
68 #include <folly/detail/BitsDetail.h>
69 #include <folly/detail/BitIteratorDetail.h>
70 #include <folly/Likely.h>
72 #if FOLLY_HAVE_BYTESWAP_H
73 # include <byteswap.h>
80 #include <type_traits>
81 #include <boost/iterator/iterator_adaptor.hpp>
86 // Generate overloads for findFirstSet as wrappers around
87 // appropriate ffs, ffsl, ffsll gcc builtins
89 inline FOLLY_INTRINSIC_CONSTEXPR
90 typename std::enable_if<
91 (std::is_integral<T>::value &&
92 std::is_unsigned<T>::value &&
93 sizeof(T) <= sizeof(unsigned int)),
96 return __builtin_ffs(x);
100 inline FOLLY_INTRINSIC_CONSTEXPR
101 typename std::enable_if<
102 (std::is_integral<T>::value &&
103 std::is_unsigned<T>::value &&
104 sizeof(T) > sizeof(unsigned int) &&
105 sizeof(T) <= sizeof(unsigned long)),
108 return __builtin_ffsl(x);
112 inline FOLLY_INTRINSIC_CONSTEXPR
113 typename std::enable_if<
114 (std::is_integral<T>::value &&
115 std::is_unsigned<T>::value &&
116 sizeof(T) > sizeof(unsigned long) &&
117 sizeof(T) <= sizeof(unsigned long long)),
120 return __builtin_ffsll(x);
124 inline FOLLY_INTRINSIC_CONSTEXPR
125 typename std::enable_if<
126 (std::is_integral<T>::value && std::is_signed<T>::value),
129 // Note that conversion from a signed type to the corresponding unsigned
130 // type is technically implementation-defined, but will likely work
131 // on any impementation that uses two's complement.
132 return findFirstSet(static_cast<typename std::make_unsigned<T>::type>(x));
135 // findLastSet: return the 1-based index of the highest bit set
136 // for x > 0, findLastSet(x) == 1 + floor(log2(x))
138 inline FOLLY_INTRINSIC_CONSTEXPR
139 typename std::enable_if<
140 (std::is_integral<T>::value &&
141 std::is_unsigned<T>::value &&
142 sizeof(T) <= sizeof(unsigned int)),
145 return x ? 8 * sizeof(unsigned int) - __builtin_clz(x) : 0;
149 inline FOLLY_INTRINSIC_CONSTEXPR
150 typename std::enable_if<
151 (std::is_integral<T>::value &&
152 std::is_unsigned<T>::value &&
153 sizeof(T) > sizeof(unsigned int) &&
154 sizeof(T) <= sizeof(unsigned long)),
157 return x ? 8 * sizeof(unsigned long) - __builtin_clzl(x) : 0;
161 inline FOLLY_INTRINSIC_CONSTEXPR
162 typename std::enable_if<
163 (std::is_integral<T>::value &&
164 std::is_unsigned<T>::value &&
165 sizeof(T) > sizeof(unsigned long) &&
166 sizeof(T) <= sizeof(unsigned long long)),
169 return x ? 8 * sizeof(unsigned long long) - __builtin_clzll(x) : 0;
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;
193 typename std::enable_if<
194 std::is_integral<T>::value && std::is_unsigned<T>::value,
197 return (v != 0) && !(v & (v - 1));
204 inline typename std::enable_if<
205 (std::is_integral<T>::value &&
206 std::is_unsigned<T>::value &&
207 sizeof(T) <= sizeof(unsigned int)),
210 return detail::popcount(x);
214 inline typename std::enable_if<
215 (std::is_integral<T>::value &&
216 std::is_unsigned<T>::value &&
217 sizeof(T) > sizeof(unsigned int) &&
218 sizeof(T) <= sizeof(unsigned long long)),
221 return detail::popcountll(x);
225 * Endianness detection and manipulation primitives.
230 struct EndianIntBase {
238 * If we have the bswap_16 macro from byteswap.h, use it; otherwise, provide our
242 # define our_bswap16 bswap_16
245 template<class Int16>
246 inline constexpr typename std::enable_if<
249 our_bswap16(Int16 x) {
250 return ((x >> 8) & 0xff) | ((x & 0xff) << 8);
256 #define FB_GEN(t, fn) \
257 template<> inline t EndianIntBase<t>::swap(t x) { return fn(x); }
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.
265 FB_GEN( int64_t, _byteswap_uint64)
266 FB_GEN(uint64_t, _byteswap_uint64)
267 FB_GEN( int32_t, _byteswap_ulong)
268 FB_GEN(uint32_t, _byteswap_ulong)
269 FB_GEN( int16_t, _byteswap_ushort)
270 FB_GEN(uint16_t, _byteswap_ushort)
272 FB_GEN( int64_t, __builtin_bswap64)
273 FB_GEN(uint64_t, __builtin_bswap64)
274 FB_GEN( int32_t, __builtin_bswap32)
275 FB_GEN(uint32_t, __builtin_bswap32)
276 FB_GEN( int16_t, our_bswap16)
277 FB_GEN(uint16_t, our_bswap16)
283 struct EndianInt : public EndianIntBase<T> {
286 return kIsLittleEndian ? EndianInt::swap(x) : x;
288 static T little(T x) {
289 return kIsBigEndian ? EndianInt::swap(x) : x;
293 } // namespace detail
295 // big* convert between native and big-endian representations
296 // little* convert between native and little-endian representations
297 // swap* convert between big-endian and little-endian representations
299 // ntohs, htons == big16
300 // ntohl, htonl == big32
301 #define FB_GEN1(fn, t, sz) \
302 static t fn##sz(t x) { return fn<t>(x); } \
304 #define FB_GEN2(t, sz) \
305 FB_GEN1(swap, t, sz) \
306 FB_GEN1(big, t, sz) \
307 FB_GEN1(little, t, sz)
310 FB_GEN2(uint##sz##_t, sz) \
311 FB_GEN2(int##sz##_t, sz)
315 enum class Order : uint8_t {
320 static constexpr Order order = kIsLittleEndian ? Order::LITTLE : Order::BIG;
322 template <class T> static T swap(T x) {
323 return folly::detail::EndianInt<T>::swap(x);
325 template <class T> static T big(T x) {
326 return folly::detail::EndianInt<T>::big(x);
328 template <class T> static T little(T x) {
329 return folly::detail::EndianInt<T>::little(x);
332 #if !defined(__ANDROID__)
345 * Fast bit iteration facility.
349 template <class BaseIter> class BitIterator;
350 template <class BaseIter>
351 BitIterator<BaseIter> findFirstSet(BitIterator<BaseIter>,
352 BitIterator<BaseIter>);
354 * Wrapper around an iterator over an integer type that iterates
355 * over its underlying bits in LSb to MSb order.
357 * BitIterator models the same iterator concepts as the base iterator.
359 template <class BaseIter>
361 : public bititerator_detail::BitIteratorBase<BaseIter>::type {
364 * Return the number of bits in an element of the underlying iterator.
366 static unsigned int bitsPerBlock() {
367 return std::numeric_limits<
368 typename std::make_unsigned<
369 typename std::iterator_traits<BaseIter>::value_type
375 * Construct a BitIterator that points at a given bit offset (default 0)
378 explicit BitIterator(const BaseIter& iter, size_t bitOff=0)
379 : bititerator_detail::BitIteratorBase<BaseIter>::type(iter),
381 assert(bitOffset_ < bitsPerBlock());
384 size_t bitOffset() const {
388 void advanceToNextBlock() {
390 ++this->base_reference();
393 BitIterator& operator=(const BaseIter& other) {
394 this->~BitIterator();
395 new (this) BitIterator(other);
400 friend class boost::iterator_core_access;
401 friend BitIterator findFirstSet<>(BitIterator, BitIterator);
403 typedef bititerator_detail::BitReference<
404 typename std::iterator_traits<BaseIter>::reference,
405 typename std::iterator_traits<BaseIter>::value_type
408 void advanceInBlock(size_t n) {
410 assert(bitOffset_ < bitsPerBlock());
413 BitRef dereference() const {
414 return BitRef(*this->base_reference(), bitOffset_);
417 void advance(ssize_t n) {
418 size_t bpb = bitsPerBlock();
419 ssize_t blocks = n / bpb;
420 bitOffset_ += n % bpb;
421 if (bitOffset_ >= bpb) {
425 this->base_reference() += blocks;
429 if (++bitOffset_ == bitsPerBlock()) {
430 advanceToNextBlock();
435 if (bitOffset_-- == 0) {
436 bitOffset_ = bitsPerBlock() - 1;
437 --this->base_reference();
441 bool equal(const BitIterator& other) const {
442 return (bitOffset_ == other.bitOffset_ &&
443 this->base_reference() == other.base_reference());
446 ssize_t distance_to(const BitIterator& other) const {
448 (other.base_reference() - this->base_reference()) * bitsPerBlock() +
449 other.bitOffset_ - bitOffset_;
452 unsigned int bitOffset_;
456 * Helper function, so you can write
457 * auto bi = makeBitIterator(container.begin());
459 template <class BaseIter>
460 BitIterator<BaseIter> makeBitIterator(const BaseIter& iter) {
461 return BitIterator<BaseIter>(iter);
466 * Find first bit set in a range of bit iterators.
467 * 4.5x faster than the obvious std::find(begin, end, true);
469 template <class BaseIter>
470 BitIterator<BaseIter> findFirstSet(BitIterator<BaseIter> begin,
471 BitIterator<BaseIter> end) {
472 // shortcut to avoid ugly static_cast<>
473 static const typename BaseIter::value_type one = 1;
475 while (begin.base() != end.base()) {
476 typename BaseIter::value_type v = *begin.base();
477 // mask out the bits that don't matter (< begin.bitOffset)
478 v &= ~((one << begin.bitOffset()) - 1);
479 size_t firstSet = findFirstSet(v);
481 --firstSet; // now it's 0-based
482 assert(firstSet >= begin.bitOffset());
483 begin.advanceInBlock(firstSet - begin.bitOffset());
486 begin.advanceToNextBlock();
489 // now begin points to the same block as end
490 if (end.bitOffset() != 0) { // assume end is dereferenceable
491 typename BaseIter::value_type v = *begin.base();
492 // mask out the bits that don't matter (< begin.bitOffset)
493 v &= ~((one << begin.bitOffset()) - 1);
494 // mask out the bits that don't matter (>= end.bitOffset)
495 v &= (one << end.bitOffset()) - 1;
496 size_t firstSet = findFirstSet(v);
498 --firstSet; // now it's 0-based
499 assert(firstSet >= begin.bitOffset());
500 begin.advanceInBlock(firstSet - begin.bitOffset());
509 template <class T, class Enable=void> struct Unaligned;
512 * Representation of an unaligned value of a POD type.
518 typename std::enable_if<std::is_pod<T>::value>::type> {
519 Unaligned() = default; // uninitialized
520 /* implicit */ Unaligned(T v) : value(v) { }
526 * Read an unaligned value of type T and return it.
529 inline T loadUnaligned(const void* p) {
530 static_assert(sizeof(Unaligned<T>) == sizeof(T), "Invalid unaligned size");
531 static_assert(alignof(Unaligned<T>) == 1, "Invalid alignment");
532 if (kHasUnalignedAccess) {
533 return static_cast<const Unaligned<T>*>(p)->value;
536 memcpy(&value, p, sizeof(T));
542 * Write an unaligned value of type T.
545 inline void storeUnaligned(void* p, T value) {
546 static_assert(sizeof(Unaligned<T>) == sizeof(T), "Invalid unaligned size");
547 static_assert(alignof(Unaligned<T>) == 1, "Invalid alignment");
548 if (kHasUnalignedAccess) {
549 new (p) Unaligned<T>(value);
551 memcpy(p, &value, sizeof(T));