blob: 483f524ccc2f22de195343d0d57bffef415eef5d [file] [log] [blame]
Corentin Wallezf07e3bd2017-04-20 14:38:20 -04001// Copyright 2017 The NXT Authors
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 "Math.h"
16
17#include "Forward.h"
18
19namespace backend {
20
21 unsigned long ScanForward(unsigned long bits) {
22 ASSERT(bits != 0);
23 // TODO(cwallez@chromium.org): handle non-posix platforms
24 // unsigned long firstBitIndex = 0ul;
25 // unsigned char ret = _BitScanForward(&firstBitIndex, bits);
26 // ASSERT(ret != 0);
27 // return firstBitIndex;
28 return static_cast<unsigned long>(__builtin_ctzl(bits));
29 }
30
31 uint32_t Log2(uint32_t value) {
32 ASSERT(value != 0);
33 return 31 - __builtin_clz(value);
34 }
35
36 bool IsPowerOfTwo(size_t n) {
37 ASSERT(n != 0);
38 return (n & (n - 1)) == 0;
39 }
40
41 bool IsAligned(const void* ptr, size_t alignment) {
42 ASSERT(IsPowerOfTwo(alignment));
43 ASSERT(alignment != 0);
44 return (reinterpret_cast<intptr_t>(ptr) & (alignment - 1)) == 0;
45 }
46
47 void* AlignVoidPtr(void* ptr, size_t alignment) {
48 ASSERT(alignment != 0);
49 return reinterpret_cast<void*>((reinterpret_cast<intptr_t>(ptr) + (alignment - 1)) & ~(alignment - 1));
50 }
51
52}