aboutsummaryrefslogtreecommitdiff
path: root/utils.h
diff options
context:
space:
mode:
Diffstat (limited to 'utils.h')
-rw-r--r--utils.h19
1 files changed, 19 insertions, 0 deletions
diff --git a/utils.h b/utils.h
new file mode 100644
index 0000000..ba13f27
--- /dev/null
+++ b/utils.h
@@ -0,0 +1,19 @@
+#include <limits>
+#include <stdexcept>
+
+/*
+ * Credits to:
+ * http://stackoverflow.com/questions/13150449/efficient-unsigned-to-signed-cast-avoiding-implementation-defined-behavior
+ */
+template<typename Uint, typename Int>
+Int uintToInt(Uint x)
+{
+ if (x <= std::numeric_limits<Int>::max())
+ return static_cast<Int>(x);
+
+ if (x >= std::numeric_limits<Int>::min())
+ return static_cast<Int>(x - std::numeric_limits<Int>::min())
+ + std::numeric_limits<Int>::min();
+
+ throw std::overflow_error("given value does not fit integer type");
+}