Debian Codegraph @

src/mpt/base/math.hpp

raw
1 /* SPDX-License-Identifier: BSL-1.0 OR BSD-3-Clause */
2
3 #ifndef MPT_BASE_MATH_HPP
4 #define MPT_BASE_MATH_HPP
5
6
7
8 #include "mpt/base/detect.hpp"
9 #include "mpt/base/namespace.hpp"
10
11 #include <algorithm>
12 #include <type_traits>
13
14 #include <cmath>
15
16
17
18 namespace mpt {
19 inline namespace MPT_INLINE_NS {
20
21
22 #if MPT_OS_DJGPP
23
24 inline long double log2(const long double val) {
25 return static_cast<long double>(::log2(static_cast<double>(val)));
26 }
27
28 inline double log2(const double val) {
29 return ::log2(val);
30 }
31
32 inline float log2(const float val) {
33 return ::log2f(val);
34 }
35
36 #else // !MPT_OS_DJGPP
37
38 // C++11 std::log2
39 using std::log2;
40
41 #endif // MPT_OS_DJGPP
42
43
44 #if MPT_OS_DJGPP
45
46 inline long double round(const long double val) {
47 return ::roundl(val);
48 }
49
50 inline double round(const double val) {
51 return ::round(val);
52 }
53
54 inline float round(const float val) {
55 return ::roundf(val);
56 }
57
58 #else // !MPT_OS_DJGPP
59
60 // C++11 std::round
61 using std::round;
62
63 #endif // MPT_OS_DJGPP
64
65
66 #if MPT_OS_DJGPP
67
68 inline long double trunc(const long double val) {
69 return ::truncl(val);
70 }
71
72 inline double trunc(const double val) {
73 return ::trunc(val);
74 }
75
76 inline float trunc(const float val) {
77 return ::truncf(val);
78 }
79
80 #else // !MPT_OS_DJGPP
81
82 // C++11 std::trunc
83 using std::trunc;
84
85 #endif // MPT_OS_DJGPP
86
87
88 template <typename T>
89 inline T sanitize_nan(T val) {
90 static_assert(std::is_floating_point<T>::value);
91 if (std::isnan(val)) {
92 return T(0.0);
93 }
94 return val;
95 }
96
97
98 template <typename T>
99 inline T safe_clamp(T v, T lo, T hi) {
100 static_assert(std::is_floating_point<T>::value);
101 return std::clamp(mpt::sanitize_nan(v), lo, hi);
102 }
103
104
105 } // namespace MPT_INLINE_NS
106 } // namespace mpt
107
108
109
110 #endif // MPT_BASE_MATH_HPP