2 * Copyright 2014 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)
58 #include "folly/Portability.h"
65 #define FOLLY_INTRINSIC_CONSTEXPR constexpr
67 // Unlike GCC, in Clang (as of 3.2) intrinsics aren't constexpr.
68 #define FOLLY_INTRINSIC_CONSTEXPR const
71 #ifndef FOLLY_NO_CONFIG
72 #include "folly/folly-config.h"
75 #include "folly/detail/BitsDetail.h"
76 #include "folly/detail/BitIteratorDetail.h"
77 #include "folly/Likely.h"
79 #if FOLLY_HAVE_BYTESWAP_H
80 # include <byteswap.h>
87 #include <type_traits>
88 #include <boost/iterator/iterator_adaptor.hpp>
93 // Generate overloads for findFirstSet as wrappers around
94 // appropriate ffs, ffsl, ffsll gcc builtins
96 inline FOLLY_INTRINSIC_CONSTEXPR
97 typename std::enable_if<
98 (std::is_integral<T>::value &&
99 std::is_unsigned<T>::value &&
100 sizeof(T) <= sizeof(unsigned int)),
103 return __builtin_ffs(x);
107 inline FOLLY_INTRINSIC_CONSTEXPR
108 typename std::enable_if<
109 (std::is_integral<T>::value &&
110 std::is_unsigned<T>::value &&
111 sizeof(T) > sizeof(unsigned int) &&
112 sizeof(T) <= sizeof(unsigned long)),
115 return __builtin_ffsl(x);
119 inline FOLLY_INTRINSIC_CONSTEXPR
120 typename std::enable_if<
121 (std::is_integral<T>::value &&
122 std::is_unsigned<T>::value &&
123 sizeof(T) > sizeof(unsigned long) &&
124 sizeof(T) <= sizeof(unsigned long long)),
127 return __builtin_ffsll(x);
131 inline FOLLY_INTRINSIC_CONSTEXPR
132 typename std::enable_if<
133 (std::is_integral<T>::value && std::is_signed<T>::value),
136 // Note that conversion from a signed type to the corresponding unsigned
137 // type is technically implementation-defined, but will likely work
138 // on any impementation that uses two's complement.
139 return findFirstSet(static_cast<typename std::make_unsigned<T>::type>(x));
142 // findLastSet: return the 1-based index of the highest bit set
143 // for x > 0, findLastSet(x) == 1 + floor(log2(x))
145 inline FOLLY_INTRINSIC_CONSTEXPR
146 typename std::enable_if<
147 (std::is_integral<T>::value &&
148 std::is_unsigned<T>::value &&
149 sizeof(T) <= sizeof(unsigned int)),
152 return x ? 8 * sizeof(unsigned int) - __builtin_clz(x) : 0;
156 inline FOLLY_INTRINSIC_CONSTEXPR
157 typename std::enable_if<
158 (std::is_integral<T>::value &&
159 std::is_unsigned<T>::value &&
160 sizeof(T) > sizeof(unsigned int) &&
161 sizeof(T) <= sizeof(unsigned long)),
164 return x ? 8 * sizeof(unsigned long) - __builtin_clzl(x) : 0;
168 inline FOLLY_INTRINSIC_CONSTEXPR
169 typename std::enable_if<
170 (std::is_integral<T>::value &&
171 std::is_unsigned<T>::value &&
172 sizeof(T) > sizeof(unsigned long) &&
173 sizeof(T) <= sizeof(unsigned long long)),
176 return x ? 8 * sizeof(unsigned long long) - __builtin_clzll(x) : 0;
180 inline FOLLY_INTRINSIC_CONSTEXPR
181 typename std::enable_if<
182 (std::is_integral<T>::value &&
183 std::is_signed<T>::value),
186 return findLastSet(static_cast<typename std::make_unsigned<T>::type>(x));
190 inline FOLLY_INTRINSIC_CONSTEXPR
191 typename std::enable_if<
192 std::is_integral<T>::value && std::is_unsigned<T>::value,
195 return v ? (1ul << findLastSet(v - 1)) : 1;
200 typename std::enable_if<
201 std::is_integral<T>::value && std::is_unsigned<T>::value,
204 return (v != 0) && !(v & (v - 1));
211 inline typename std::enable_if<
212 (std::is_integral<T>::value &&
213 std::is_unsigned<T>::value &&
214 sizeof(T) <= sizeof(unsigned int)),
217 return detail::popcount(x);
221 inline typename std::enable_if<
222 (std::is_integral<T>::value &&
223 std::is_unsigned<T>::value &&
224 sizeof(T) > sizeof(unsigned int) &&
225 sizeof(T) <= sizeof(unsigned long long)),
228 return detail::popcountll(x);
232 * Endianness detection and manipulation primitives.
237 struct EndianIntBase {
243 * If we have the bswap_16 macro from byteswap.h, use it; otherwise, provide our
247 # define our_bswap16 bswap_16
250 template<class Int16>
251 inline constexpr typename std::enable_if<
254 our_bswap16(Int16 x) {
255 return ((x >> 8) & 0xff) | ((x & 0xff) << 8);
259 #define FB_GEN(t, fn) \
260 template<> inline t EndianIntBase<t>::swap(t x) { return fn(x); }
262 // fn(x) expands to (x) if the second argument is empty, which is exactly
263 // what we want for [u]int8_t. Also, gcc 4.7 on Intel doesn't have
264 // __builtin_bswap16 for some reason, so we have to provide our own.
267 FB_GEN( int64_t, __builtin_bswap64)
268 FB_GEN(uint64_t, __builtin_bswap64)
269 FB_GEN( int32_t, __builtin_bswap32)
270 FB_GEN(uint32_t, __builtin_bswap32)
271 FB_GEN( int16_t, our_bswap16)
272 FB_GEN(uint16_t, our_bswap16)
276 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
279 struct EndianInt : public detail::EndianIntBase<T> {
281 static T big(T x) { return EndianInt::swap(x); }
282 static T little(T x) { return x; }
285 #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
288 struct EndianInt : public detail::EndianIntBase<T> {
290 static T big(T x) { return x; }
291 static T little(T x) { return EndianInt::swap(x); }
295 # error Your machine uses a weird endianness!
296 #endif /* __BYTE_ORDER__ */
298 } // namespace detail
300 // big* convert between native and big-endian representations
301 // little* convert between native and little-endian representations
302 // swap* convert between big-endian and little-endian representations
304 // ntohs, htons == big16
305 // ntohl, htonl == big32
306 #define FB_GEN1(fn, t, sz) \
307 static t fn##sz(t x) { return fn<t>(x); } \
309 #define FB_GEN2(t, sz) \
310 FB_GEN1(swap, t, sz) \
311 FB_GEN1(big, t, sz) \
312 FB_GEN1(little, t, sz)
315 FB_GEN2(uint##sz##_t, sz) \
316 FB_GEN2(int##sz##_t, sz)
320 enum class Order : uint8_t {
325 static constexpr Order order =
326 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
328 #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
331 # error Your machine uses a weird endianness!
332 #endif /* __BYTE_ORDER__ */
334 template <class T> static T swap(T x) {
335 return detail::EndianInt<T>::swap(x);
337 template <class T> static T big(T x) {
338 return detail::EndianInt<T>::big(x);
340 template <class T> static T little(T x) {
341 return detail::EndianInt<T>::little(x);
355 * Fast bit iteration facility.
359 template <class BaseIter> class BitIterator;
360 template <class BaseIter>
361 BitIterator<BaseIter> findFirstSet(BitIterator<BaseIter>,
362 BitIterator<BaseIter>);
364 * Wrapper around an iterator over an integer type that iterates
365 * over its underlying bits in LSb to MSb order.
367 * BitIterator models the same iterator concepts as the base iterator.
369 template <class BaseIter>
371 : public bititerator_detail::BitIteratorBase<BaseIter>::type {
374 * Return the number of bits in an element of the underlying iterator.
376 static size_t bitsPerBlock() {
377 return std::numeric_limits<
378 typename std::make_unsigned<
379 typename std::iterator_traits<BaseIter>::value_type
385 * Construct a BitIterator that points at a given bit offset (default 0)
388 #pragma GCC diagnostic push // bitOffset shadows a member
389 #pragma GCC diagnostic ignored "-Wshadow"
390 explicit BitIterator(const BaseIter& iter, size_t bitOffset=0)
391 : bititerator_detail::BitIteratorBase<BaseIter>::type(iter),
392 bitOffset_(bitOffset) {
393 assert(bitOffset_ < bitsPerBlock());
395 #pragma GCC diagnostic pop
397 size_t bitOffset() const {
401 void advanceToNextBlock() {
403 ++this->base_reference();
406 BitIterator& operator=(const BaseIter& other) {
407 this->~BitIterator();
408 new (this) BitIterator(other);
413 friend class boost::iterator_core_access;
414 friend BitIterator findFirstSet<>(BitIterator, BitIterator);
416 typedef bititerator_detail::BitReference<
417 typename std::iterator_traits<BaseIter>::reference,
418 typename std::iterator_traits<BaseIter>::value_type
421 void advanceInBlock(size_t n) {
423 assert(bitOffset_ < bitsPerBlock());
426 BitRef dereference() const {
427 return BitRef(*this->base_reference(), bitOffset_);
430 void advance(ssize_t n) {
431 size_t bpb = bitsPerBlock();
432 ssize_t blocks = n / bpb;
433 bitOffset_ += n % bpb;
434 if (bitOffset_ >= bpb) {
438 this->base_reference() += blocks;
442 if (++bitOffset_ == bitsPerBlock()) {
443 advanceToNextBlock();
448 if (bitOffset_-- == 0) {
449 bitOffset_ = bitsPerBlock() - 1;
450 --this->base_reference();
454 bool equal(const BitIterator& other) const {
455 return (bitOffset_ == other.bitOffset_ &&
456 this->base_reference() == other.base_reference());
459 ssize_t distance_to(const BitIterator& other) const {
461 (other.base_reference() - this->base_reference()) * bitsPerBlock() +
462 (other.bitOffset_ - bitOffset_);
469 * Helper function, so you can write
470 * auto bi = makeBitIterator(container.begin());
472 template <class BaseIter>
473 BitIterator<BaseIter> makeBitIterator(const BaseIter& iter) {
474 return BitIterator<BaseIter>(iter);
479 * Find first bit set in a range of bit iterators.
480 * 4.5x faster than the obvious std::find(begin, end, true);
482 template <class BaseIter>
483 BitIterator<BaseIter> findFirstSet(BitIterator<BaseIter> begin,
484 BitIterator<BaseIter> end) {
485 // shortcut to avoid ugly static_cast<>
486 static const typename BaseIter::value_type one = 1;
488 while (begin.base() != end.base()) {
489 typename BaseIter::value_type v = *begin.base();
490 // mask out the bits that don't matter (< begin.bitOffset)
491 v &= ~((one << begin.bitOffset()) - 1);
492 size_t firstSet = findFirstSet(v);
494 --firstSet; // now it's 0-based
495 assert(firstSet >= begin.bitOffset());
496 begin.advanceInBlock(firstSet - begin.bitOffset());
499 begin.advanceToNextBlock();
502 // now begin points to the same block as end
503 if (end.bitOffset() != 0) { // assume end is dereferenceable
504 typename BaseIter::value_type v = *begin.base();
505 // mask out the bits that don't matter (< begin.bitOffset)
506 v &= ~((one << begin.bitOffset()) - 1);
507 // mask out the bits that don't matter (>= end.bitOffset)
508 v &= (one << end.bitOffset()) - 1;
509 size_t firstSet = findFirstSet(v);
511 --firstSet; // now it's 0-based
512 assert(firstSet >= begin.bitOffset());
513 begin.advanceInBlock(firstSet - begin.bitOffset());
522 template <class T, class Enable=void> struct Unaligned;
525 * Representation of an unaligned value of a POD type.
531 typename std::enable_if<std::is_pod<T>::value>::type> {
532 Unaligned() = default; // uninitialized
533 /* implicit */ Unaligned(T v) : value(v) { }
539 * Read an unaligned value of type T and return it.
542 inline T loadUnaligned(const void* p) {
543 static_assert(sizeof(Unaligned<T>) == sizeof(T), "Invalid unaligned size");
544 static_assert(alignof(Unaligned<T>) == 1, "Invalid alignment");
545 return static_cast<const Unaligned<T>*>(p)->value;
549 * Write an unaligned value of type T.
552 inline void storeUnaligned(void* p, T value) {
553 static_assert(sizeof(Unaligned<T>) == sizeof(T), "Invalid unaligned size");
554 static_assert(alignof(Unaligned<T>) == 1, "Invalid alignment");
555 new (p) Unaligned<T>(value);
560 #endif /* FOLLY_BITS_H_ */