summaryrefslogtreecommitdiffstats
path: root/src/common/overflow.h
diff options
context:
space:
mode:
authorliamwhite <liamwhite@users.noreply.github.com>2024-01-26 15:55:25 +0100
committerGitHub <noreply@github.com>2024-01-26 15:55:25 +0100
commit55482ab5dce463d5014498b006c18a90d0d004e6 (patch)
treeb343faa9cadc692265efb4b6b88e157c97ef76d2 /src/common/overflow.h
parentMerge pull request #12796 from t895/controller-optimizations (diff)
parentAddress review comments and fix compilation problems (diff)
downloadyuzu-55482ab5dce463d5014498b006c18a90d0d004e6.tar
yuzu-55482ab5dce463d5014498b006c18a90d0d004e6.tar.gz
yuzu-55482ab5dce463d5014498b006c18a90d0d004e6.tar.bz2
yuzu-55482ab5dce463d5014498b006c18a90d0d004e6.tar.lz
yuzu-55482ab5dce463d5014498b006c18a90d0d004e6.tar.xz
yuzu-55482ab5dce463d5014498b006c18a90d0d004e6.tar.zst
yuzu-55482ab5dce463d5014498b006c18a90d0d004e6.zip
Diffstat (limited to 'src/common/overflow.h')
-rw-r--r--src/common/overflow.h18
1 files changed, 18 insertions, 0 deletions
diff --git a/src/common/overflow.h b/src/common/overflow.h
index 44d8e7e73..e184ead95 100644
--- a/src/common/overflow.h
+++ b/src/common/overflow.h
@@ -3,6 +3,7 @@
#pragma once
+#include <algorithm>
#include <type_traits>
#include "bit_cast.h"
@@ -19,4 +20,21 @@ inline T WrappingAdd(T lhs, T rhs) {
return BitCast<T>(lhs_u + rhs_u);
}
+template <typename T>
+ requires(std::is_integral_v<T> && std::is_signed_v<T>)
+inline bool CanAddWithoutOverflow(T lhs, T rhs) {
+#ifdef _MSC_VER
+ if (lhs >= 0 && rhs >= 0) {
+ return WrappingAdd(lhs, rhs) >= std::max(lhs, rhs);
+ } else if (lhs < 0 && rhs < 0) {
+ return WrappingAdd(lhs, rhs) <= std::min(lhs, rhs);
+ } else {
+ return true;
+ }
+#else
+ T res;
+ return !__builtin_add_overflow(lhs, rhs, &res);
+#endif
+}
+
} // namespace Common