OLD | NEW |
1 // Copyright (c) 2009 The Chromium Authors. All rights reserved. | 1 // Copyright (c) 2009 The Chromium Authors. All rights reserved. |
2 // Use of this source code is governed by a BSD-style license that can be | 2 // Use of this source code is governed by a BSD-style license that can be |
3 // found in the LICENSE file. | 3 // found in the LICENSE file. |
4 | 4 |
5 // This file defines some bit utilities. | 5 // This file defines some bit utilities. |
6 | 6 |
7 #ifndef BASE_BITS_H_ | 7 #ifndef BASE_BITS_H_ |
8 #define BASE_BITS_H_ | 8 #define BASE_BITS_H_ |
9 | 9 |
10 #include "base/basictypes.h" | 10 #include <stddef.h> |
| 11 #include <stdint.h> |
| 12 |
11 #include "base/logging.h" | 13 #include "base/logging.h" |
12 | 14 |
13 namespace base { | 15 namespace base { |
14 namespace bits { | 16 namespace bits { |
15 | 17 |
16 // Returns the integer i such as 2^i <= n < 2^(i+1) | 18 // Returns the integer i such as 2^i <= n < 2^(i+1) |
17 inline int Log2Floor(uint32 n) { | 19 inline int Log2Floor(uint32_t n) { |
18 if (n == 0) | 20 if (n == 0) |
19 return -1; | 21 return -1; |
20 int log = 0; | 22 int log = 0; |
21 uint32 value = n; | 23 uint32_t value = n; |
22 for (int i = 4; i >= 0; --i) { | 24 for (int i = 4; i >= 0; --i) { |
23 int shift = (1 << i); | 25 int shift = (1 << i); |
24 uint32 x = value >> shift; | 26 uint32_t x = value >> shift; |
25 if (x != 0) { | 27 if (x != 0) { |
26 value = x; | 28 value = x; |
27 log += shift; | 29 log += shift; |
28 } | 30 } |
29 } | 31 } |
30 DCHECK_EQ(value, 1u); | 32 DCHECK_EQ(value, 1u); |
31 return log; | 33 return log; |
32 } | 34 } |
33 | 35 |
34 // Returns the integer i such as 2^(i-1) < n <= 2^i | 36 // Returns the integer i such as 2^(i-1) < n <= 2^i |
35 inline int Log2Ceiling(uint32 n) { | 37 inline int Log2Ceiling(uint32_t n) { |
36 if (n == 0) { | 38 if (n == 0) { |
37 return -1; | 39 return -1; |
38 } else { | 40 } else { |
39 // Log2Floor returns -1 for 0, so the following works correctly for n=1. | 41 // Log2Floor returns -1 for 0, so the following works correctly for n=1. |
40 return 1 + Log2Floor(n - 1); | 42 return 1 + Log2Floor(n - 1); |
41 } | 43 } |
42 } | 44 } |
43 | 45 |
44 // Round up |size| to a multiple of alignment, which must be a power of two. | 46 // Round up |size| to a multiple of alignment, which must be a power of two. |
45 inline size_t Align(size_t size, size_t alignment) { | 47 inline size_t Align(size_t size, size_t alignment) { |
46 DCHECK_EQ(alignment & (alignment - 1), 0u); | 48 DCHECK_EQ(alignment & (alignment - 1), 0u); |
47 return (size + alignment - 1) & ~(alignment - 1); | 49 return (size + alignment - 1) & ~(alignment - 1); |
48 } | 50 } |
49 | 51 |
50 } // namespace bits | 52 } // namespace bits |
51 } // namespace base | 53 } // namespace base |
52 | 54 |
53 #endif // BASE_BITS_H_ | 55 #endif // BASE_BITS_H_ |
OLD | NEW |