summaryrefslogtreecommitdiffstats
path: root/src/util/math.h
diff options
context:
space:
mode:
authorRJ Ryan <rryan@mixxx.org>2014-11-18 10:11:19 -0500
committerRJ Ryan <rryan@mixxx.org>2014-11-18 10:11:19 -0500
commit40066529a9fb22e0cb5c41442d93e2bb48cd0893 (patch)
tree90f113778d166530ed750b5e9186a71eb78ff6e6 /src/util/math.h
parenta74c65d6469a2f1ce0d1927ffbd73be90bf754c5 (diff)
parente597e9b2c63960f0af1cdbf190176ca53df6a9c1 (diff)
Merge pull request #390 from uklotzde/math_clamp_variants
New math_clamp() variants
Diffstat (limited to 'src/util/math.h')
-rw-r--r--src/util/math.h33
1 files changed, 24 insertions, 9 deletions
diff --git a/src/util/math.h b/src/util/math.h
index ecdce81ad5..17d928b190 100644
--- a/src/util/math.h
+++ b/src/util/math.h
@@ -9,8 +9,6 @@
#include <QtDebug>
-#include "util/cmdlineargs.h"
-
// If we don't do this then we get the C90 fabs from the global namespace which
// is only defined for double.
using std::fabs;
@@ -19,17 +17,34 @@ using std::fabs;
#define math_min std::min
#define math_max3(a, b, c) math_max(math_max((a), (b)), (c))
+// Restrict value to the range [min, max]. Undefined behavior
+// if min > max.
template <typename T>
-inline T math_clamp(T value, T min, T max) {
- // XXX: If max < min, behavior is undefined, and has been causing problems.
- // if debugging is on, assert when this happens.
- if (CmdlineArgs::Instance().getDeveloper() && max < min) {
- qWarning() << "PROGRAMMING ERROR: math_clamp called with max < min! "
- << max << " " << min;
- }
+inline T math_clamp_unsafe(T value, T min, T max) {
return math_max(min, math_min(max, value));
}
+// Clamp with bounds checking to avoid undefined behavior
+// on invalid min/max parameters.
+template <typename T>
+inline T math_clamp_safe(T value, T min, T max) {
+ if (min <= max) {
+ // valid bounds
+ return math_clamp_unsafe(value, min, max);
+ } else {
+ // invalid bounds
+ qWarning() << "PROGRAMMING ERROR: math_clamp_safe() called with min > max!"
+ << min << ">" << max;
+ // simply return the value unchanged
+ return value;
+ }
+}
+
+template <typename T>
+inline T math_clamp(T value, T min, T max) {
+ return math_clamp_safe(value, min, max);
+}
+
// NOTE(rryan): It is an error to call even() on a floating point number. Do not
// hack this to support floating point values! The programmer should be required
// to manually convert so they are aware of the conversion.