1 : // Copyright 2011 Google Inc. All Rights Reserved.
2 : //
3 : // Licensed under the Apache License, Version 2.0 (the "License");
4 : // you may not use this file except in compliance with the License.
5 : // You may obtain a copy of the License at
6 : //
7 : // http://www.apache.org/licenses/LICENSE-2.0
8 : //
9 : // Unless required by applicable law or agreed to in writing, software
10 : // distributed under the License is distributed on an "AS IS" BASIS,
11 : // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 : // See the License for the specific language governing permissions and
13 : // limitations under the License.
14 :
15 : #include "syzygy/common/align.h"
16 :
17 : #include "base/logging.h"
18 :
19 : namespace common {
20 :
21 E : bool IsPowerOfTwo(size_t value) {
22 E : return value != 0 && (value & (value - 1)) == 0;
23 E : }
24 :
25 E : size_t AlignUp(size_t value, size_t alignment) {
26 E : DCHECK(alignment != 0);
27 :
28 E : if (IsPowerOfTwo(alignment)) {
29 E : return (value + alignment - 1) & ~(alignment - 1);
30 i : } else {
31 E : return ((value + alignment - 1) / alignment) * alignment;
32 : }
33 E : }
34 :
35 E : size_t AlignDown(size_t value, size_t alignment) {
36 E : DCHECK(alignment != 0);
37 :
38 E : if (IsPowerOfTwo(alignment)) {
39 E : return value & ~(alignment - 1);
40 i : } else {
41 E : return (value / alignment) * alignment;
42 : }
43 E : }
44 :
45 E : bool IsAligned(size_t value, size_t alignment) {
46 E : return AlignDown(value, alignment) == value;
47 E : }
48 :
49 E : bool IsPowerOfTwo64(uint64 value) {
50 E : return value != 0 && (value & (value - 1)) == 0;
51 E : }
52 :
53 E : uint64 AlignUp64(uint64 value, uint64 alignment) {
54 E : DCHECK(alignment != 0);
55 :
56 E : if (IsPowerOfTwo64(alignment)) {
57 E : return (value + alignment - 1) & ~(alignment - 1);
58 i : } else {
59 E : return ((value + alignment - 1) / alignment) * alignment;
60 : }
61 E : }
62 :
63 E : uint64 AlignDown64(uint64 value, uint64 alignment) {
64 E : DCHECK(alignment != 0);
65 :
66 E : if (IsPowerOfTwo64(alignment)) {
67 E : return value & ~(alignment - 1);
68 i : } else {
69 E : return (value / alignment) * alignment;
70 : }
71 E : }
72 :
73 E : bool IsAligned64(uint64 value, uint64 alignment) {
74 E : return AlignDown64(value, alignment) == value;
75 E : }
76 :
77 : } // namespace common
|