• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2021 The Tint 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 #ifndef SRC_UTILS_MATH_H_
16 #define SRC_UTILS_MATH_H_
17 
18 #include <sstream>
19 #include <string>
20 #include <type_traits>
21 
22 namespace tint {
23 namespace utils {
24 
25 /// @param alignment the next multiple to round `value` to
26 /// @param value the value to round to the next multiple of `alignment`
27 /// @return `value` rounded to the next multiple of `alignment`
28 /// @note `alignment` must be positive. An alignment of zero will cause a DBZ.
29 template <typename T>
RoundUp(T alignment,T value)30 inline T RoundUp(T alignment, T value) {
31   return ((value + alignment - 1) / alignment) * alignment;
32 }
33 
34 /// @param value the value to check whether it is a power-of-two
35 /// @returns true if `value` is a power-of-two
36 /// @note `value` must be positive if `T` is signed
37 template <typename T>
IsPowerOfTwo(T value)38 inline bool IsPowerOfTwo(T value) {
39   return (value & (value - 1)) == 0;
40 }
41 
42 /// @param value the input value
43 /// @returns the largest power of two that `value` is a multiple of
44 template <typename T>
MaxAlignOf(T value)45 inline std::enable_if_t<std::is_unsigned<T>::value, T> MaxAlignOf(T value) {
46   T pot = 1;
47   while (value && ((value & 1u) == 0)) {
48     pot <<= 1;
49     value >>= 1;
50   }
51   return pot;
52 }
53 
54 }  // namespace utils
55 }  // namespace tint
56 
57 #endif  //  SRC_UTILS_MATH_H_
58