1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
|
/* SPDX-License-Identifier: BSL-1.0 OR BSD-3-Clause */
#ifndef MPT_BASE_NUMERIC_HPP
#define MPT_BASE_NUMERIC_HPP
#include "mpt/base/detect_compiler.hpp"
#include "mpt/base/namespace.hpp"
#include "mpt/base/bit.hpp"
#include "mpt/base/saturate_cast.hpp"
#include <algorithm>
#include <limits>
#include <type_traits>
namespace mpt {
inline namespace MPT_INLINE_NS {
template <typename Tmod, Tmod m>
struct ModIfNotZeroImpl {
template <typename Tval>
constexpr Tval mod(Tval x) {
static_assert(std::numeric_limits<Tmod>::is_integer);
static_assert(!std::numeric_limits<Tmod>::is_signed);
static_assert(std::numeric_limits<Tval>::is_integer);
static_assert(!std::numeric_limits<Tval>::is_signed);
return static_cast<Tval>(x % m);
}
};
template <>
struct ModIfNotZeroImpl<uint8, 0> {
template <typename Tval>
constexpr Tval mod(Tval x) {
return x;
}
};
template <>
struct ModIfNotZeroImpl<uint16, 0> {
template <typename Tval>
constexpr Tval mod(Tval x) {
return x;
}
};
template <>
struct ModIfNotZeroImpl<uint32, 0> {
template <typename Tval>
constexpr Tval mod(Tval x) {
return x;
}
};
template <>
struct ModIfNotZeroImpl<uint64, 0> {
template <typename Tval>
constexpr Tval mod(Tval x) {
return x;
}
};
// Returns x % m if m != 0, x otherwise.
// i.e. "return (m == 0) ? x : (x % m);", but without causing a warning with stupid older compilers
template <typename Tmod, Tmod m, typename Tval>
constexpr Tval modulo_if_not_zero(Tval x) {
return ModIfNotZeroImpl<Tmod, m>().mod(x);
}
// rounds x up to multiples of target
template <typename T>
constexpr T align_up(T x, T target) {
return ((x + (target - 1)) / target) * target;
}
// rounds x down to multiples of target
template <typename T>
constexpr T align_down(T x, T target) {
return (x / target) * target;
}
// Returns sign of a number (-1 for negative numbers, 1 for positive numbers, 0 for 0)
template <class T>
constexpr int signum(T value) {
return (value > T(0)) - (value < T(0));
}
} // namespace MPT_INLINE_NS
} // namespace mpt
#endif // MPT_BASE_ALGORITHM_HPP
|