mitteLib
Loading...
Searching...
No Matches
mathutils.hpp
Go to the documentation of this file.
1//
2// Created by spak on 2/1/23.
3//
4
5#ifndef MLAB_MATHUTILS_HPP
6#define MLAB_MATHUTILS_HPP
7
8namespace mlab {
9
10 template <class N>
11 [[nodiscard]] constexpr N next_multiple(N n, N d);
12
13 template <class N>
14 [[nodiscard]] constexpr std::pair<N, N> log2_remainder(N n);
15}// namespace mlab
16
17namespace mlab {
18
19 template <class N>
20 constexpr N next_multiple(N n, N d) {
21 static_assert(std::is_integral_v<N>);
22 if (d % 2 == 0) {
23 return (n + d - 1) & -d;
24 } else {
25 return (n / d) * d + ((n % d) > 0 ? d : 0);
26 }
27 }
28
29 template <class N>
30 constexpr std::pair<N, N> log2_remainder(N n) {
31 static_assert(std::is_integral_v<N> and std::is_unsigned_v<N>);
32 N mask = ~N(0);
33 for (N i = 0; i < sizeof(N) * 8; ++i) {
34 mask >>= 1;
35 if (const N remainder = n & mask; remainder != n) {
36 return {sizeof(N) * 8 - i - 1, remainder};
37 }
38 }
39 return {0, n};
40 }
41}// namespace mlab
42
43#endif//MLAB_MATHUTILS_HPP
Definition log.cpp:8
constexpr std::pair< N, N > log2_remainder(N n)
Definition mathutils.hpp:30
constexpr N next_multiple(N n, N d)
Definition mathutils.hpp:20