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 * return true iff x is a power of two
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"
68 #include "folly/detail/BitsDetail.h"
69 #include "folly/detail/BitIteratorDetail.h"
70 #include "folly/Likely.h"
78 #include <type_traits>
79 #include <boost/iterator/iterator_adaptor.hpp>
84 // Generate overloads for findFirstSet as wrappers around
85 // appropriate ffs, ffsl, ffsll gcc builtins
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 __builtin_ffs(x);
97 typename std::enable_if<
98 (std::is_integral<T>::value &&
99 std::is_unsigned<T>::value &&
100 sizeof(T) > sizeof(unsigned int) &&
101 sizeof(T) <= sizeof(unsigned long)),
104 return __builtin_ffsl(x);
108 typename std::enable_if<
109 (std::is_integral<T>::value &&
110 std::is_unsigned<T>::value &&
111 sizeof(T) > sizeof(unsigned long) &&
112 sizeof(T) <= sizeof(unsigned long long)),
115 return __builtin_ffsll(x);
119 typename std::enable_if<
120 (std::is_integral<T>::value && std::is_signed<T>::value),
123 // Note that conversion from a signed type to the corresponding unsigned
124 // type is technically implementation-defined, but will likely work
125 // on any impementation that uses two's complement.
126 return findFirstSet(static_cast<typename std::make_unsigned<T>::type>(x));
129 // findLastSet: return the 1-based index of the highest bit set
130 // for x > 0, findLastSet(x) == 1 + floor(log2(x))
132 typename std::enable_if<
133 (std::is_integral<T>::value &&
134 std::is_unsigned<T>::value &&
135 sizeof(T) <= sizeof(unsigned int)),
138 return x ? 8 * sizeof(unsigned int) - __builtin_clz(x) : 0;
142 typename std::enable_if<
143 (std::is_integral<T>::value &&
144 std::is_unsigned<T>::value &&
145 sizeof(T) > sizeof(unsigned int) &&
146 sizeof(T) <= sizeof(unsigned long)),
149 return x ? 8 * sizeof(unsigned long) - __builtin_clzl(x) : 0;
153 typename std::enable_if<
154 (std::is_integral<T>::value &&
155 std::is_unsigned<T>::value &&
156 sizeof(T) > sizeof(unsigned long) &&
157 sizeof(T) <= sizeof(unsigned long long)),
160 return x ? 8 * sizeof(unsigned long long) - __builtin_clzll(x) : 0;
164 typename std::enable_if<
165 (std::is_integral<T>::value &&
166 std::is_signed<T>::value),
169 return findLastSet(static_cast<typename std::make_unsigned<T>::type>(x));
174 typename std::enable_if<
175 std::is_integral<T>::value && std::is_unsigned<T>::value,
178 if (UNLIKELY(v == 0)) {
181 return 1ul << findLastSet(v - 1);
186 typename std::enable_if<
187 std::is_integral<T>::value && std::is_unsigned<T>::value,
190 return ((v != 0) && !(v & (v-1))); // yes, this is endian-agnostic
197 inline typename std::enable_if<
198 (std::is_integral<T>::value &&
199 std::is_unsigned<T>::value &&
200 sizeof(T) <= sizeof(unsigned int)),
203 return detail::popcount(x);
207 inline typename std::enable_if<
208 (std::is_integral<T>::value &&
209 std::is_unsigned<T>::value &&
210 sizeof(T) > sizeof(unsigned int) &&
211 sizeof(T) <= sizeof(unsigned long long)),
214 return detail::popcountll(x);
218 * Endianness detection and manipulation primitives.
223 struct EndianIntBase {
228 #define FB_GEN(t, fn) \
229 template<> inline t EndianIntBase<t>::swap(t x) { return fn(x); }
231 // fn(x) expands to (x) if the second argument is empty, which is exactly
232 // what we want for [u]int8_t
235 FB_GEN( int64_t, bswap_64)
236 FB_GEN(uint64_t, bswap_64)
237 FB_GEN( int32_t, bswap_32)
238 FB_GEN(uint32_t, bswap_32)
239 FB_GEN( int16_t, bswap_16)
240 FB_GEN(uint16_t, bswap_16)
244 #if __BYTE_ORDER == __LITTLE_ENDIAN
247 struct EndianInt : public detail::EndianIntBase<T> {
249 static T big(T x) { return EndianInt::swap(x); }
250 static T little(T x) { return x; }
253 #elif __BYTE_ORDER == __BIG_ENDIAN
256 struct EndianInt : public detail::EndianIntBase<T> {
258 static T big(T x) { return x; }
259 static T little(T x) { return EndianInt::swap(x); }
263 # error Your machine uses a weird endianness!
264 #endif /* __BYTE_ORDER */
266 } // namespace detail
268 // big* convert between native and big-endian representations
269 // little* convert between native and little-endian representations
270 // swap* convert between big-endian and little-endian representations
272 // ntohs, htons == big16
273 // ntohl, htonl == big32
274 #define FB_GEN1(fn, t, sz) \
275 static t fn##sz(t x) { return fn<t>(x); } \
277 #define FB_GEN2(t, sz) \
278 FB_GEN1(swap, t, sz) \
279 FB_GEN1(big, t, sz) \
280 FB_GEN1(little, t, sz)
283 FB_GEN2(uint##sz##_t, sz) \
284 FB_GEN2(int##sz##_t, sz)
288 enum class Order : uint8_t {
293 static constexpr Order order =
294 #if __BYTE_ORDER == __LITTLE_ENDIAN
296 #elif __BYTE_ORDER == __BIG_ENDIAN
299 # error Your machine uses a weird endianness!
300 #endif /* __BYTE_ORDER */
302 template <class T> static T swap(T x) {
303 return detail::EndianInt<T>::swap(x);
305 template <class T> static T big(T x) {
306 return detail::EndianInt<T>::big(x);
308 template <class T> static T little(T x) {
309 return detail::EndianInt<T>::little(x);
323 * Fast bit iteration facility.
327 template <class BaseIter> class BitIterator;
328 template <class BaseIter>
329 BitIterator<BaseIter> findFirstSet(BitIterator<BaseIter>,
330 BitIterator<BaseIter>);
332 * Wrapper around an iterator over an integer type that iterates
333 * over its underlying bits in LSb to MSb order.
335 * BitIterator models the same iterator concepts as the base iterator.
337 template <class BaseIter>
339 : public bititerator_detail::BitIteratorBase<BaseIter>::type {
342 * Return the number of bits in an element of the underlying iterator.
344 static size_t bitsPerBlock() {
345 return std::numeric_limits<
346 typename std::make_unsigned<
347 typename std::iterator_traits<BaseIter>::value_type
353 * Construct a BitIterator that points at a given bit offset (default 0)
356 explicit BitIterator(const BaseIter& iter, size_t bitOffset=0)
357 : bititerator_detail::BitIteratorBase<BaseIter>::type(iter),
358 bitOffset_(bitOffset) {
359 assert(bitOffset_ < bitsPerBlock());
362 size_t bitOffset() const {
366 void advanceToNextBlock() {
368 ++this->base_reference();
371 BitIterator& operator=(const BaseIter& other) {
372 this->~BitIterator();
373 new (this) BitIterator(other);
378 friend class boost::iterator_core_access;
379 friend BitIterator findFirstSet<>(BitIterator, BitIterator);
381 typedef bititerator_detail::BitReference<
382 typename std::iterator_traits<BaseIter>::reference,
383 typename std::iterator_traits<BaseIter>::value_type
386 void advanceInBlock(size_t n) {
388 assert(bitOffset_ < bitsPerBlock());
391 BitRef dereference() const {
392 return BitRef(*this->base_reference(), bitOffset_);
395 void advance(ssize_t n) {
396 size_t bpb = bitsPerBlock();
397 ssize_t blocks = n / bpb;
398 bitOffset_ += n % bpb;
399 if (bitOffset_ >= bpb) {
403 this->base_reference() += blocks;
407 if (++bitOffset_ == bitsPerBlock()) {
408 advanceToNextBlock();
413 if (bitOffset_-- == 0) {
414 bitOffset_ = bitsPerBlock() - 1;
415 --this->base_reference();
419 bool equal(const BitIterator& other) const {
420 return (bitOffset_ == other.bitOffset_ &&
421 this->base_reference() == other.base_reference());
424 ssize_t distance_to(const BitIterator& other) const {
426 (other.base_reference() - this->base_reference()) * bitsPerBlock() +
427 (other.bitOffset_ - bitOffset_);
434 * Helper function, so you can write
435 * auto bi = makeBitIterator(container.begin());
437 template <class BaseIter>
438 BitIterator<BaseIter> makeBitIterator(const BaseIter& iter) {
439 return BitIterator<BaseIter>(iter);
444 * Find first bit set in a range of bit iterators.
445 * 4.5x faster than the obvious std::find(begin, end, true);
447 template <class BaseIter>
448 BitIterator<BaseIter> findFirstSet(BitIterator<BaseIter> begin,
449 BitIterator<BaseIter> end) {
450 // shortcut to avoid ugly static_cast<>
451 static const typename BaseIter::value_type one = 1;
453 while (begin.base() != end.base()) {
454 typename BaseIter::value_type v = *begin.base();
455 // mask out the bits that don't matter (< begin.bitOffset)
456 v &= ~((one << begin.bitOffset()) - 1);
457 size_t firstSet = findFirstSet(v);
459 --firstSet; // now it's 0-based
460 assert(firstSet >= begin.bitOffset());
461 begin.advanceInBlock(firstSet - begin.bitOffset());
464 begin.advanceToNextBlock();
467 // now begin points to the same block as end
468 if (end.bitOffset() != 0) { // assume end is dereferenceable
469 typename BaseIter::value_type v = *begin.base();
470 // mask out the bits that don't matter (< begin.bitOffset)
471 v &= ~((one << begin.bitOffset()) - 1);
472 // mask out the bits that don't matter (>= end.bitOffset)
473 v &= (one << end.bitOffset()) - 1;
474 size_t firstSet = findFirstSet(v);
476 --firstSet; // now it's 0-based
477 assert(firstSet >= begin.bitOffset());
478 begin.advanceInBlock(firstSet - begin.bitOffset());
487 template <class T, class Enable=void> struct Unaligned;
490 * Representation of an unaligned value of a POD type.
495 typename std::enable_if<std::is_pod<T>::value>::type> {
496 Unaligned() { } // uninitialized
497 /* implicit */ Unaligned(T v) : value(v) { }
499 } __attribute__((packed));
502 * Read an unaligned value of type T and return it.
505 inline T loadUnaligned(const void* p) {
506 static_assert(sizeof(Unaligned<T>) == sizeof(T), "Invalid unaligned size");
507 static_assert(alignof(Unaligned<T>) == 1, "Invalid alignment");
508 return static_cast<const Unaligned<T>*>(p)->value;
512 * Write an unaligned value of type T.
515 inline void storeUnaligned(void* p, T value) {
516 static_assert(sizeof(Unaligned<T>) == sizeof(T), "Invalid unaligned size");
517 static_assert(alignof(Unaligned<T>) == 1, "Invalid alignment");
518 new (p) Unaligned<T>(value);
523 #endif /* FOLLY_BITS_H_ */