aboutsummaryrefslogtreecommitdiff
path: root/src/util/math_util.hpp
diff options
context:
space:
mode:
authorcrupest <crupest@outlook.com>2019-03-19 16:21:54 +0800
committercrupest <crupest@outlook.com>2019-03-19 16:21:54 +0800
commit5dc738a57930271194bd86673eb86f149096a7b2 (patch)
tree71174aba0d1c0918cc7d7a1be0b86ec0d5c20401 /src/util/math_util.hpp
parent06edefebe8dfb138404397fb2c46732da6cd733a (diff)
downloadcru-5dc738a57930271194bd86673eb86f149096a7b2.tar.gz
cru-5dc738a57930271194bd86673eb86f149096a7b2.tar.bz2
cru-5dc738a57930271194bd86673eb86f149096a7b2.zip
...
Diffstat (limited to 'src/util/math_util.hpp')
-rw-r--r--src/util/math_util.hpp51
1 files changed, 51 insertions, 0 deletions
diff --git a/src/util/math_util.hpp b/src/util/math_util.hpp
new file mode 100644
index 00000000..01348641
--- /dev/null
+++ b/src/util/math_util.hpp
@@ -0,0 +1,51 @@
+#pragma once
+#include "pre.hpp"
+
+#include <optional>
+#include <type_traits>
+
+namespace cru::util {
+template <typename T, typename = std::enable_if_t<std::is_arithmetic_v<T>>>
+float Coerce(const T n, const std::optional<T> min,
+ const std::optional<T> max) {
+ if (min.has_value() && n < min.value()) return min.value();
+ if (max.has_value() && n > max.value()) return max.value();
+ return n;
+}
+
+template <typename T, typename = std::enable_if_t<std::is_arithmetic_v<T>>>
+float Coerce(const T n, const T min, const T max) {
+ if (n < min) return min;
+ if (n > max) return max;
+ return n;
+}
+
+template <typename T, typename = std::enable_if_t<std::is_arithmetic_v<T>>>
+float Coerce(const T n, const std::nullopt_t, const std::optional<T> max) {
+ if (max.has_value() && n > max.value()) return max.value();
+ return n;
+}
+
+template <typename T, typename = std::enable_if_t<std::is_arithmetic_v<T>>>
+float Coerce(const T n, const std::optional<T> min, const std::nullopt_t) {
+ if (min.has_value() && n < min.value()) return min.value();
+ return n;
+}
+
+template <typename T, typename = std::enable_if_t<std::is_arithmetic_v<T>>>
+float Coerce(const T n, const std::nullopt_t, const T max) {
+ if (n > max) return max;
+ return n;
+}
+
+template <typename T, typename = std::enable_if_t<std::is_arithmetic_v<T>>>
+float Coerce(const T n, const T min, const std::nullopt_t) {
+ if (n < min) return min;
+ return n;
+}
+
+template <typename T, typename = std::enable_if_t<std::is_arithmetic_v<T>>>
+T AtLeast0(const T value) {
+ return value < static_cast<T>(0) ? static_cast<T>(0) : value;
+}
+} // namespace cru::util