summaryrefslogtreecommitdiffstats
path: root/include/o3tl/safeint.hxx
diff options
context:
space:
mode:
authorCaolán McNamara <caolanm@redhat.com>2017-10-25 09:44:59 +0100
committerCaolán McNamara <caolanm@redhat.com>2017-10-25 15:19:15 +0200
commit7b0bb820bb27d298eb4abec3ff4b09e7b6b299e7 (patch)
treeb8853cef234f09574798fd2528a9bb6538bf2f9a /include/o3tl/safeint.hxx
parentofz#3780 Integer-overflow (diff)
downloadcore-7b0bb820bb27d298eb4abec3ff4b09e7b6b299e7.tar.gz
core-7b0bb820bb27d298eb4abec3ff4b09e7b6b299e7.zip
add checked_sub
Change-Id: I440cd18c249f38194cfd3dfd4a1fc4b7f80858d6 Reviewed-on: https://gerrit.libreoffice.org/43810 Reviewed-by: Caolán McNamara <caolanm@redhat.com> Tested-by: Caolán McNamara <caolanm@redhat.com>
Diffstat (limited to 'include/o3tl/safeint.hxx')
-rw-r--r--include/o3tl/safeint.hxx35
1 files changed, 35 insertions, 0 deletions
diff --git a/include/o3tl/safeint.hxx b/include/o3tl/safeint.hxx
index 1c8bf280171e..8b735fe2edfa 100644
--- a/include/o3tl/safeint.hxx
+++ b/include/o3tl/safeint.hxx
@@ -68,6 +68,11 @@ template<typename T> inline bool checked_add(T a, T b, T& result)
return !msl::utilities::SafeAdd(a, b, result);
}
+template<typename T> inline bool checked_sub(T a, T b, T& result)
+{
+ return !msl::utilities::SafeSubtract(a, b, result);
+}
+
#elif (defined __GNUC__ && __GNUC__ >= 5) || (__has_builtin(__builtin_mul_overflow) && !(defined ANDROID && defined __clang__))
template<typename T> inline bool checked_multiply(T a, T b, T& result)
@@ -80,6 +85,11 @@ template<typename T> inline bool checked_add(T a, T b, T& result)
return __builtin_add_overflow(a, b, &result);
}
+template<typename T> inline bool checked_sub(T a, T b, T& result)
+{
+ return __builtin_sub_overflow(a, b, &result);
+}
+
#else
//https://www.securecoding.cert.org/confluence/display/c/INT32-C.+Ensure+that+operations+on+signed+integers+do+not+result+in+overflow
@@ -149,6 +159,31 @@ template<typename T> inline typename std::enable_if<std::is_unsigned<T>::value,
return false;
}
+//https://www.securecoding.cert.org/confluence/display/c/INT32-C.+Ensure+that+operations+on+signed+integers+do+not+result+in+overflow
+template<typename T> inline typename std::enable_if<std::is_signed<T>::value, bool>::type checked_sub(T a, T b, T& result)
+{
+ if ((b > 0 && a < std::numeric_limits<T>::min() + b) ||
+ (b < 0 && a > std::numeric_limits<T>::max() + b)) {
+ return true;
+ }
+
+ result = a - b;
+
+ return false;
+}
+
+//https://www.securecoding.cert.org/confluence/display/c/INT30-C.+Ensure+that+unsigned+integer+operations+do+not+wrap
+template<typename T> inline typename std::enable_if<std::is_unsigned<T>::value, bool>::type checked_sub(T a, T b, T& result)
+{
+ if (a < b) {
+ return true;
+ }
+
+ result = a - b;
+
+ return false;
+}
+
#endif
}