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