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

Unified Diff: base/numerics/safe_math_impl.h

Issue 2537773009: Fix a bunch of undefined behavior in CheckedNumericState (Closed)
Patch Set: comments Created 4 years 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 | no next file » | 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 15de619e76fae11ce35d8ecac5b950c4e7ba432b..e3c753dc94b3b047a6e33e8ba4608ac6053322b6 100644
--- a/base/numerics/safe_math_impl.h
+++ b/base/numerics/safe_math_impl.h
@@ -800,19 +800,22 @@ class CheckedNumericState {};
template <typename T>
class CheckedNumericState<T, NUMERIC_INTEGER> {
private:
- T value_;
+ // is_valid_ precedes value_ because member intializers in the constructors
+ // are evaluated in field order, and is_valid_ must be read when initializing
+ // value_.
bool is_valid_;
+ T value_;
public:
template <typename Src, NumericRepresentation type>
friend class CheckedNumericState;
- constexpr CheckedNumericState() : value_(0), is_valid_(true) {}
+ constexpr CheckedNumericState() : is_valid_(true), value_(0) {}
template <typename Src>
constexpr CheckedNumericState(Src value, bool is_valid)
- : value_(static_cast<T>(value)),
- is_valid_(is_valid && IsValueInRangeForNumericType<T>(value)) {
+ : is_valid_(is_valid && IsValueInRangeForNumericType<T>(value)),
+ value_(is_valid_ ? static_cast<T>(value) : 0) {
static_assert(std::numeric_limits<Src>::is_specialized,
"Argument must be numeric.");
}
@@ -820,15 +823,16 @@ class CheckedNumericState<T, NUMERIC_INTEGER> {
// Copy constructor.
template <typename Src>
constexpr CheckedNumericState(const CheckedNumericState<Src>& rhs)
- : value_(static_cast<T>(rhs.value())), is_valid_(rhs.IsValid()) {}
+ : is_valid_(rhs.IsValid()),
+ value_(is_valid_ ? static_cast<T>(rhs.value()) : 0) {}
template <typename Src>
constexpr explicit CheckedNumericState(
Src value,
typename std::enable_if<std::numeric_limits<Src>::is_specialized,
int>::type = 0)
- : value_(static_cast<T>(value)),
- is_valid_(IsValueInRangeForNumericType<T>(value)) {}
+ : is_valid_(IsValueInRangeForNumericType<T>(value)),
+ value_(is_valid_ ? static_cast<T>(value) : 0) {}
constexpr bool is_valid() const { return is_valid_; }
constexpr T value() const { return value_; }
« no previous file with comments | « no previous file | no next file » | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698