1*3ac0a46fSAndroid Build Coastguard Worker // Copyright (c) 2013 The Chromium Authors. All rights reserved. 2*3ac0a46fSAndroid Build Coastguard Worker // Use of this source code is governed by a BSD-style license that can be 3*3ac0a46fSAndroid Build Coastguard Worker // found in the LICENSE file. 4*3ac0a46fSAndroid Build Coastguard Worker 5*3ac0a46fSAndroid Build Coastguard Worker // This file defines some bit utilities. 6*3ac0a46fSAndroid Build Coastguard Worker 7*3ac0a46fSAndroid Build Coastguard Worker #ifndef THIRD_PARTY_BASE_BITS_H_ 8*3ac0a46fSAndroid Build Coastguard Worker #define THIRD_PARTY_BASE_BITS_H_ 9*3ac0a46fSAndroid Build Coastguard Worker 10*3ac0a46fSAndroid Build Coastguard Worker #include <type_traits> 11*3ac0a46fSAndroid Build Coastguard Worker 12*3ac0a46fSAndroid Build Coastguard Worker namespace pdfium { 13*3ac0a46fSAndroid Build Coastguard Worker namespace base { 14*3ac0a46fSAndroid Build Coastguard Worker namespace bits { 15*3ac0a46fSAndroid Build Coastguard Worker 16*3ac0a46fSAndroid Build Coastguard Worker // TODO(thestig): When C++20 is required, replace with std::has_single_bit(). 17*3ac0a46fSAndroid Build Coastguard Worker // Returns true iff |value| is a power of 2. 18*3ac0a46fSAndroid Build Coastguard Worker template <typename T, typename = std::enable_if<std::is_integral<T>::value>> IsPowerOfTwo(T value)19*3ac0a46fSAndroid Build Coastguard Workerconstexpr inline bool IsPowerOfTwo(T value) { 20*3ac0a46fSAndroid Build Coastguard Worker // From "Hacker's Delight": Section 2.1 Manipulating Rightmost Bits. 21*3ac0a46fSAndroid Build Coastguard Worker // 22*3ac0a46fSAndroid Build Coastguard Worker // Only positive integers with a single bit set are powers of two. If only one 23*3ac0a46fSAndroid Build Coastguard Worker // bit is set in x (e.g. 0b00000100000000) then |x-1| will have that bit set 24*3ac0a46fSAndroid Build Coastguard Worker // to zero and all bits to its right set to 1 (e.g. 0b00000011111111). Hence 25*3ac0a46fSAndroid Build Coastguard Worker // |x & (x-1)| is 0 iff x is a power of two. 26*3ac0a46fSAndroid Build Coastguard Worker return value > 0 && (value & (value - 1)) == 0; 27*3ac0a46fSAndroid Build Coastguard Worker } 28*3ac0a46fSAndroid Build Coastguard Worker 29*3ac0a46fSAndroid Build Coastguard Worker } // namespace bits 30*3ac0a46fSAndroid Build Coastguard Worker } // namespace base 31*3ac0a46fSAndroid Build Coastguard Worker } // namespace pdfium 32*3ac0a46fSAndroid Build Coastguard Worker 33*3ac0a46fSAndroid Build Coastguard Worker #endif // THIRD_PARTY_BASE_BITS_H_ 34