Chromium Code Reviews| Index: src/utils.h |
| =================================================================== |
| --- src/utils.h (revision 4849) |
| +++ src/utils.h (working copy) |
| @@ -47,6 +47,36 @@ |
| } |
| +// X must be a power of 2. Returns the number of trailing zeros. |
| +template <typename T> |
| +static inline int WhichPowerOf2(T x) { |
|
Søren Thygesen Gjesse
2010/06/14 07:56:47
Shouldn't there be a test case for this?
Erik Corry
2010/06/14 21:05:46
Assert added.
|
| + ASSERT(IsPowerOf2(x)); |
| + if (x < 0) return 31; |
| + if (x == 0) return 32; |
| + int bits = 0; |
| + if (x >= 0x10000) { |
| + bits += 16; |
| + x >>= 16; |
| + } |
| + if (x >= 0x100) { |
| + bits += 8; |
| + x >>= 8; |
| + } |
| + if (x >= 0x10) { |
| + bits += 4; |
| + x >>= 4; |
| + } |
| + switch (x) { |
| + case 1: return bits; |
| + case 2: return bits + 1; |
| + case 4: return bits + 2; |
| + case 8: return bits + 3; |
| + default: UNREACHABLE(); |
| + } |
| + return 0; |
| +} |
| + |
| + |
| // The C++ standard leaves the semantics of '>>' undefined for |
| // negative signed operands. Most implementations do the right thing, |
| // though. |