2 * Copyright 2012 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.
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)
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))
30 * return the number of 1 bits in x
33 * Finds the next power of two >= x.
36 * convert between native, big, and little endian representation
37 * Endian::big(x) big <-> native
38 * Endian::little(x) little <-> native
39 * Endian::swap(x) big <-> little
42 * Wrapper around an iterator over an integral type that iterates
43 * over its underlying bits in MSb to LSb order
45 * findFirstSet(BitIterator begin, BitIterator end)
46 * return a BitIterator pointing to the first 1 bit in [begin, end), or
47 * end if all bits in [begin, end) are 0
49 * @author Tudor Bosman (tudorb@fb.com)
55 #include "folly/Portability.h"
65 #include "folly/detail/BitsDetail.h"
66 #include "folly/detail/BitIteratorDetail.h"
67 #include "folly/Likely.h"
72 #include <cstring> // for ffs, ffsl, ffsll
76 #include <type_traits>
77 #include <boost/iterator/iterator_adaptor.hpp>
82 // Generate overloads for findFirstSet as wrappers around
83 // appropriate ffs, ffsl, ffsll functions from glibc.
84 // We first define these overloads for signed types (because ffs, ffsl, ffsll
85 // take int, long, and long long as arguments, respectively) and then
86 // define an overload for unsigned that forwards to the overload for the
87 // corresponding signed type.
89 typename std::enable_if<
90 (std::is_integral<T>::value &&
91 std::is_signed<T>::value &&
92 (std::numeric_limits<T>::digits <= std::numeric_limits<int>::digits)),
95 return ::ffs(static_cast<int>(x));
99 typename std::enable_if<
100 (std::is_integral<T>::value &&
101 std::is_signed<T>::value &&
102 (std::numeric_limits<T>::digits > std::numeric_limits<int>::digits) &&
103 (std::numeric_limits<T>::digits <= std::numeric_limits<long>::digits)),
106 return ::ffsl(static_cast<long>(x));
109 #ifdef FOLLY_HAVE_FFSLL
112 typename std::enable_if<
113 (std::is_integral<T>::value &&
114 std::is_signed<T>::value &&
115 (std::numeric_limits<T>::digits > std::numeric_limits<long>::digits) &&
116 (std::numeric_limits<T>::digits <= std::numeric_limits<long long>::digits)),
119 return ::ffsll(static_cast<long long>(x));
125 typename std::enable_if<
126 (std::is_integral<T>::value &&
127 !std::is_signed<T>::value),
130 // Note that conversion from an unsigned type to the corresponding signed
131 // type is technically implementation-defined, but will likely work
132 // on any impementation that uses two's complement.
133 return findFirstSet(static_cast<typename std::make_signed<T>::type>(x));
136 // findLastSet: return the 1-based index of the highest bit set
137 // for x > 0, findLastSet(x) == 1 + floor(log2(x))
139 typename std::enable_if<
140 (std::is_integral<T>::value &&
141 std::is_unsigned<T>::value &&
142 (std::numeric_limits<T>::digits <=
143 std::numeric_limits<unsigned int>::digits)),
146 return x ? 8 * sizeof(unsigned int) - __builtin_clz(x) : 0;
150 typename std::enable_if<
151 (std::is_integral<T>::value &&
152 std::is_unsigned<T>::value &&
153 (std::numeric_limits<T>::digits >
154 std::numeric_limits<unsigned int>::digits) &&
155 (std::numeric_limits<T>::digits <=
156 std::numeric_limits<unsigned long>::digits)),
159 return x ? 8 * sizeof(unsigned long) - __builtin_clzl(x) : 0;
163 typename std::enable_if<
164 (std::is_integral<T>::value &&
165 std::is_unsigned<T>::value &&
166 (std::numeric_limits<T>::digits >
167 std::numeric_limits<unsigned long>::digits) &&
168 (std::numeric_limits<T>::digits <=
169 std::numeric_limits<unsigned long long>::digits)),
172 return x ? 8 * sizeof(unsigned long long) - __builtin_clzll(x) : 0;
176 typename std::enable_if<
177 (std::is_integral<T>::value &&
178 std::is_signed<T>::value),
181 return findLastSet(static_cast<typename std::make_unsigned<T>::type>(x));
186 typename std::enable_if<
187 std::is_integral<T>::value && std::is_unsigned<T>::value,
190 if (UNLIKELY(v == 0)) {
193 return 1ul << findLastSet(v - 1);
200 inline typename std::enable_if<
201 (std::is_integral<T>::value &&
202 std::is_unsigned<T>::value &&
203 sizeof(T) <= sizeof(unsigned int)),
206 return detail::popcount(x);
210 inline typename std::enable_if<
211 (std::is_integral<T>::value &&
212 std::is_unsigned<T>::value &&
213 sizeof(T) > sizeof(unsigned int) &&
214 sizeof(T) <= sizeof(unsigned long long)),
217 return detail::popcountll(x);
221 * Endianness detection and manipulation primitives.
226 struct EndianIntBase {
231 #define FB_GEN(t, fn) \
232 template<> inline t EndianIntBase<t>::swap(t x) { return fn(x); }
234 // fn(x) expands to (x) if the second argument is empty, which is exactly
235 // what we want for [u]int8_t
238 FB_GEN( int64_t, bswap_64)
239 FB_GEN(uint64_t, bswap_64)
240 FB_GEN( int32_t, bswap_32)
241 FB_GEN(uint32_t, bswap_32)
242 FB_GEN( int16_t, bswap_16)
243 FB_GEN(uint16_t, bswap_16)
247 #if __BYTE_ORDER == __LITTLE_ENDIAN
250 struct EndianInt : public detail::EndianIntBase<T> {
252 static T big(T x) { return EndianInt::swap(x); }
253 static T little(T x) { return x; }
256 #elif __BYTE_ORDER == __BIG_ENDIAN
259 struct EndianInt : public detail::EndianIntBase<T> {
261 static T big(T x) { return x; }
262 static T little(T x) { return EndianInt::swap(x); }
266 # error Your machine uses a weird endianness!
267 #endif /* __BYTE_ORDER */
269 } // namespace detail
271 // big* convert between native and big-endian representations
272 // little* convert between native and little-endian representations
273 // swap* convert between big-endian and little-endian representations
275 // ntohs, htons == big16
276 // ntohl, htonl == big32
277 #define FB_GEN1(fn, t, sz) \
278 static t fn##sz(t x) { return fn<t>(x); } \
280 #define FB_GEN2(t, sz) \
281 FB_GEN1(swap, t, sz) \
282 FB_GEN1(big, t, sz) \
283 FB_GEN1(little, t, sz)
286 FB_GEN2(uint##sz##_t, sz) \
287 FB_GEN2(int##sz##_t, sz)
291 enum class Order : uint8_t {
296 static constexpr Order order =
297 #if __BYTE_ORDER == __LITTLE_ENDIAN
299 #elif __BYTE_ORDER == __BIG_ENDIAN
302 # error Your machine uses a weird endianness!
303 #endif /* __BYTE_ORDER */
305 template <class T> static T swap(T x) {
306 return detail::EndianInt<T>::swap(x);
308 template <class T> static T big(T x) {
309 return detail::EndianInt<T>::big(x);
311 template <class T> static T little(T x) {
312 return detail::EndianInt<T>::little(x);
326 * Fast bit iteration facility.
330 template <class BaseIter> class BitIterator;
331 template <class BaseIter>
332 BitIterator<BaseIter> findFirstSet(BitIterator<BaseIter>,
333 BitIterator<BaseIter>);
335 * Wrapper around an iterator over an integer type that iterates
336 * over its underlying bits in LSb to MSb order.
338 * BitIterator models the same iterator concepts as the base iterator.
340 template <class BaseIter>
342 : public bititerator_detail::BitIteratorBase<BaseIter>::type {
345 * Return the number of bits in an element of the underlying iterator.
347 static size_t bitsPerBlock() {
348 return std::numeric_limits<
349 typename std::make_unsigned<
350 typename std::iterator_traits<BaseIter>::value_type
356 * Construct a BitIterator that points at a given bit offset (default 0)
359 explicit BitIterator(const BaseIter& iter, size_t bitOffset=0)
360 : bititerator_detail::BitIteratorBase<BaseIter>::type(iter),
361 bitOffset_(bitOffset) {
362 assert(bitOffset_ < bitsPerBlock());
365 size_t bitOffset() const {
369 void advanceToNextBlock() {
371 ++this->base_reference();
374 BitIterator& operator=(const BaseIter& other) {
375 this->~BitIterator();
376 new (this) BitIterator(other);
381 friend class boost::iterator_core_access;
382 friend BitIterator findFirstSet<>(BitIterator, BitIterator);
384 typedef bititerator_detail::BitReference<
385 typename std::iterator_traits<BaseIter>::reference,
386 typename std::iterator_traits<BaseIter>::value_type
389 void advanceInBlock(size_t n) {
391 assert(bitOffset_ < bitsPerBlock());
394 BitRef dereference() const {
395 return BitRef(*this->base_reference(), bitOffset_);
398 void advance(ssize_t n) {
399 size_t bpb = bitsPerBlock();
400 ssize_t blocks = n / bpb;
401 bitOffset_ += n % bpb;
402 if (bitOffset_ >= bpb) {
406 this->base_reference() += blocks;
410 if (++bitOffset_ == bitsPerBlock()) {
411 advanceToNextBlock();
416 if (bitOffset_-- == 0) {
417 bitOffset_ = bitsPerBlock() - 1;
418 --this->base_reference();
422 bool equal(const BitIterator& other) const {
423 return (bitOffset_ == other.bitOffset_ &&
424 this->base_reference() == other.base_reference());
427 ssize_t distance_to(const BitIterator& other) const {
429 (other.base_reference() - this->base_reference()) * bitsPerBlock() +
430 (other.bitOffset_ - bitOffset_);
437 * Helper function, so you can write
438 * auto bi = makeBitIterator(container.begin());
440 template <class BaseIter>
441 BitIterator<BaseIter> makeBitIterator(const BaseIter& iter) {
442 return BitIterator<BaseIter>(iter);
447 * Find first bit set in a range of bit iterators.
448 * 4.5x faster than the obvious std::find(begin, end, true);
450 template <class BaseIter>
451 BitIterator<BaseIter> findFirstSet(BitIterator<BaseIter> begin,
452 BitIterator<BaseIter> end) {
453 // shortcut to avoid ugly static_cast<>
454 static const typename BaseIter::value_type one = 1;
456 while (begin.base() != end.base()) {
457 typename BaseIter::value_type v = *begin.base();
458 // mask out the bits that don't matter (< begin.bitOffset)
459 v &= ~((one << begin.bitOffset()) - 1);
460 size_t firstSet = findFirstSet(v);
462 --firstSet; // now it's 0-based
463 assert(firstSet >= begin.bitOffset());
464 begin.advanceInBlock(firstSet - begin.bitOffset());
467 begin.advanceToNextBlock();
470 // now begin points to the same block as end
471 if (end.bitOffset() != 0) { // assume end is dereferenceable
472 typename BaseIter::value_type v = *begin.base();
473 // mask out the bits that don't matter (< begin.bitOffset)
474 v &= ~((one << begin.bitOffset()) - 1);
475 // mask out the bits that don't matter (>= end.bitOffset)
476 v &= (one << end.bitOffset()) - 1;
477 size_t firstSet = findFirstSet(v);
479 --firstSet; // now it's 0-based
480 assert(firstSet >= begin.bitOffset());
481 begin.advanceInBlock(firstSet - begin.bitOffset());
490 template <class T, class Enable=void> struct Unaligned;
493 * Representation of an unaligned value of a POD type.
498 typename std::enable_if<std::is_pod<T>::value>::type> {
499 Unaligned() { } // uninitialized
500 /* implicit */ Unaligned(T v) : value(v) { }
502 } __attribute__((packed));
505 * Read an unaligned value of type T and return it.
508 inline T loadUnaligned(const void* p) {
509 static_assert(sizeof(Unaligned<T>) == sizeof(T), "Invalid unaligned size");
510 static_assert(alignof(Unaligned<T>) == 1, "Invalid alignment");
511 return static_cast<const Unaligned<T>*>(p)->value;
515 * Write an unaligned value of type T.
518 inline void storeUnaligned(void* p, T value) {
519 static_assert(sizeof(Unaligned<T>) == sizeof(T), "Invalid unaligned size");
520 static_assert(alignof(Unaligned<T>) == 1, "Invalid alignment");
521 new (p) Unaligned<T>(value);
526 #endif /* FOLLY_BITS_H_ */