1 : // Copyright 2011 Google Inc.
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 : } 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 : } 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 : } // namespace common
|