| 1 | // -*- C++ -*- |
| 2 | |
| 3 | /* |
| 4 | |
| 5 | Heap Layers: An Extensible Memory Allocation Infrastructure |
| 6 | |
| 7 | Copyright (C) 2000-2020 by Emery Berger |
| 8 | http://www.emeryberger.com |
| 9 | [email protected] |
| 10 | |
| 11 | Heap Layers is distributed under the terms of the Apache 2.0 license. |
| 12 | |
| 13 | You may obtain a copy of the License at |
| 14 | http://www.apache.org/licenses/LICENSE-2.0 |
| 15 | |
| 16 | */ |
| 17 | |
| 18 | #ifndef HL_ILOG2_H |
| 19 | #define HL_ILOG2_H |
| 20 | |
| 21 | #if defined(_WIN32) |
| 22 | #include <windows.h> |
| 23 | #endif |
| 24 | |
| 25 | namespace HL { |
| 26 | |
| 27 | /// Quickly calculate the CEILING of the log (base 2) of the argument. |
| 28 | #if defined(_WIN32) |
| 29 | static inline unsigned int ilog2 (size_t sz) |
| 30 | { |
| 31 | DWORD index; |
| 32 | _BitScanReverse (&index, sz); |
| 33 | if (!(sz & (sz-1))) { |
| 34 | return index; |
| 35 | } else { |
| 36 | return index+1; |
| 37 | } |
| 38 | } |
| 39 | #elif defined(__GNUC__) |
| 40 | // Just use the intrinsic. |
| 41 | static constexpr inline unsigned int ilog2 (const size_t sz) |
| 42 | { |
| 43 | return ((unsigned int) (sizeof(size_t) * 8UL) - (unsigned int) __builtin_clzl((sz << 1) - 1UL) - 1); |
| 44 | } |
| 45 | #else |
| 46 | #error "Could not find an efficient implementation of log2." |
| 47 | static constexpr inline unsigned int ilog2 (size_t v) { |
| 48 | int log = 0; |
| 49 | unsigned int value = 1; |
| 50 | while (value < v) { |
| 51 | value <<= 1; |
| 52 | log++; |
| 53 | } |
| 54 | return log; |
| 55 | } |
| 56 | #endif |
| 57 | |
| 58 | |
| 59 | } |
| 60 | |
| 61 | #endif |