summaryrefslogtreecommitdiff
path: root/goo/GooCheckedOps.h
diff options
context:
space:
mode:
Diffstat (limited to 'goo/GooCheckedOps.h')
-rw-r--r--goo/GooCheckedOps.h11
1 files changed, 11 insertions, 0 deletions
diff --git a/goo/GooCheckedOps.h b/goo/GooCheckedOps.h
index 3da6b337..5eedf34b 100644
--- a/goo/GooCheckedOps.h
+++ b/goo/GooCheckedOps.h
@@ -5,6 +5,7 @@
// This file is licensed under the GPLv2 or later
//
// Copyright (C) 2018 Adam Reichold <adam.reichold@t-online.de>
+// Copyright (C) 2019 LE GARREC Vincent <legarrec.vincent@gmail.com>
//
//========================================================================
@@ -12,6 +13,7 @@
#define GOO_CHECKED_OPS_H
#include <climits>
+#include <limits>
inline bool checkedAssign(long long lz, int *z) {
static_assert(LLONG_MAX > INT_MAX, "Need type larger than int to perform overflow checks.");
@@ -46,4 +48,13 @@ inline bool checkedMultiply(int x, int y, int *z) {
#endif
}
+template<typename T> inline T safeAverage(T a, T b) {
+ static_assert(std::numeric_limits<long long>::max() > std::numeric_limits<T>::max(),
+ "The max of long long type must be larger to perform overflow checks.");
+ static_assert(std::numeric_limits<long long>::min() < std::numeric_limits<T>::min(),
+ "The min of long long type must be smaller to perform overflow checks.");
+
+ return static_cast<T>((static_cast<long long>(a) + static_cast<long long>(b)) / 2);
+}
+
#endif // GOO_CHECKED_OPS_H