• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2018 Google LLC
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 //     https://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 #ifndef ASTC_CODEC_BASE_MATH_UTILS_H_
16 #define ASTC_CODEC_BASE_MATH_UTILS_H_
17 
18 #include "src/base/uint128.h"
19 
20 #include <cassert>
21 #include <cstdint>
22 #include <type_traits>
23 
24 namespace astc_codec {
25 namespace base {
26 
Log2Floor(uint32_t n)27 inline int Log2Floor(uint32_t n) {
28   if (n == 0) {
29     return -1;
30   }
31 
32   int log = 0;
33   uint32_t value = n;
34   for (int i = 4; i >= 0; --i) {
35     int shift = (1 << i);
36     uint32_t x = value >> shift;
37     if (x != 0) {
38       value = x;
39       log += shift;
40     }
41   }
42   assert(value == 1);
43   return log;
44 }
45 
CountOnes(uint32_t n)46 inline int CountOnes(uint32_t n) {
47   n -= ((n >> 1) & 0x55555555);
48   n = ((n >> 2) & 0x33333333) + (n & 0x33333333);
49   return static_cast<int>((((n + (n >> 4)) & 0xF0F0F0F) * 0x1010101) >> 24);
50 }
51 
52 template<typename T>
ReverseBits(T value)53 inline T ReverseBits(T value) {
54   uint32_t s = sizeof(value) * 8;
55   T mask = ~T(0);
56   while ((s >>= 1) > 0) {
57     mask ^= (mask << s);
58     value = ((value >> s) & mask) | ((value << s) & ~mask);
59   }
60 
61   return value;
62 }
63 
64 template<typename T>
GetBits(T source,uint32_t offset,uint32_t count)65 inline T GetBits(T source, uint32_t offset, uint32_t count) {
66   static_assert(std::is_same<T, UInt128>::value || std::is_unsigned<T>::value,
67                 "T must be unsigned.");
68 
69   const uint32_t total_bits = sizeof(T) * 8;
70   assert(count > 0);
71   assert(offset + count <= total_bits);
72 
73   const T mask = count == total_bits ? ~T(0) : ~T(0) >> (total_bits - count);
74   return (source >> offset) & mask;
75 }
76 
77 }  // namespace base
78 }  // namespace astc_codec
79 
80 #endif  // ASTC_CODEC_BASE_MATH_UTILS_H_
81