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

Unified Diff: base/numerics/safe_math.h

Issue 2528243002: Fix silent truncations when extracting values from CheckedNumeric (Closed)
Patch Set: compile cleanup and fix 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
Index: base/numerics/safe_math.h
diff --git a/base/numerics/safe_math.h b/base/numerics/safe_math.h
index 78b88326c44bdf697091f4ea74232b71a434788a..6b5d4c2a99e47fe315a849752d10d78b9b0f9440 100644
--- a/base/numerics/safe_math.h
+++ b/base/numerics/safe_math.h
@@ -131,8 +131,8 @@ class CheckedNumeric {
// template parameter, for test code, etc. However, the handler cannot access
// the underlying value, and it is not available through other means.
template <typename Dst = T, class CheckHandler = CheckOnFailure>
- constexpr Dst ValueOrDie() const {
- return IsValid<Dst>() ? state_.value()
+ constexpr StrictNumeric<Dst> ValueOrDie() const {
+ return IsValid<Dst>() ? static_cast<Dst>(state_.value())
: CheckHandler::template HandleFailure<Dst>();
}
@@ -143,8 +143,9 @@ class CheckedNumeric {
// parameter. WARNING: This function may fail to compile or CHECK at runtime
// if the supplied default_value is not within range of the destination type.
template <typename Dst = T, typename Src>
- constexpr Dst ValueOrDefault(const Src default_value) const {
- return IsValid<Dst>() ? state_.value() : checked_cast<Dst>(default_value);
+ constexpr StrictNumeric<Dst> ValueOrDefault(const Src default_value) const {
+ return IsValid<Dst>() ? static_cast<Dst>(state_.value())
+ : checked_cast<Dst>(default_value);
}
// ValueFloating() - Since floating point values include their validity state,
@@ -153,7 +154,7 @@ class CheckedNumeric {
// A range checked destination type can be supplied using the Dst template
// parameter.
template <typename Dst = T>
- constexpr Dst ValueFloating() const {
+ constexpr StrictNumeric<Dst> ValueFloating() const {
static_assert(std::numeric_limits<T>::is_iec559,
"Type must be floating point.");
static_assert(std::numeric_limits<Dst>::is_iec559,

Powered by Google App Engine
This is Rietveld 408576698