Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(22)

Unified Diff: base/numerics/safe_math_impl.h

Issue 2440143003: Fix some lurking div by 0s in safe_math_impl.h (Closed)
Patch Set: Rebase Created 4 years, 1 month ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View side-by-side diff with in-line comments
Download patch
« no previous file with comments | « no previous file | base/numerics/safe_numerics_unittest.cc » ('j') | no next file with comments »
Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
Index: base/numerics/safe_math_impl.h
diff --git a/base/numerics/safe_math_impl.h b/base/numerics/safe_math_impl.h
index 1a6b49b250b5c34a353cbd7605357e776ec43aa2..cfc7e38993acac89920b316fe683ad5fefe87909 100644
--- a/base/numerics/safe_math_impl.h
+++ b/base/numerics/safe_math_impl.h
@@ -238,13 +238,18 @@ CheckedMul(T x, T y, RangeConstraint* validity) {
return static_cast<T>(*validity == RANGE_VALID ? x * y : 0);
}
-// Division just requires a check for an invalid negation on signed min/-1.
+// Division just requires a check for a zero denominator or an invalid negation
+// on signed min/-1.
template <typename T>
T CheckedDiv(T x,
T y,
RangeConstraint* validity,
typename std::enable_if<std::numeric_limits<T>::is_integer,
int>::type = 0) {
+ if (y == 0) {
+ *validity = RANGE_INVALID;
+ return static_cast<T>(0);
+ }
if (std::numeric_limits<T>::is_signed && x == std::numeric_limits<T>::min() &&
y == static_cast<T>(-1)) {
*validity = RANGE_OVERFLOW;
@@ -269,8 +274,8 @@ typename std::enable_if<std::numeric_limits<T>::is_integer &&
!std::numeric_limits<T>::is_signed,
T>::type
CheckedMod(T x, T y, RangeConstraint* validity) {
- *validity = RANGE_VALID;
- return static_cast<T>(x % y);
+ *validity = y != 0 ? RANGE_VALID : RANGE_INVALID;
+ return static_cast<T>(*validity == RANGE_VALID ? x % y: 0);
}
template <typename T>
« no previous file with comments | « no previous file | base/numerics/safe_numerics_unittest.cc » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698