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

Side by Side Diff: base/numerics/safe_math.h

Issue 141583008: Add support for safe math operations in base/numerics (Closed) Base URL: svn://svn.chromium.org/chrome/trunk/src/
Patch Set: Actioned feedback Created 6 years, 10 months 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 unified diff | Download patch | Annotate | Revision Log
« no previous file with comments | « base/numerics/safe_conversions_impl.h ('k') | base/numerics/safe_math_impl.h » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
(Empty)
1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #ifndef BASE_SAFE_MATH_H_
6 #define BASE_SAFE_MATH_H_
7
8 #include "base/numerics/safe_math_impl.h"
9
10 namespace base {
11
12 namespace internal {
13
14 // CheckedNumeric implements all the logic and operators for detecting integer
15 // boundary conditions such as overflow, underflow, and invalid conversions.
16 // The CheckedNumeric type implicitly converts from floating point and integer
17 // data types, and contains overloads for basic arithmetic operations (i.e.: +,
18 // -, *, /, %).
19 //
20 // The following methods convert from CheckedNumeric to standard numeric values:
21 // IsValid() - Returns true if the underlying numeric value is valid (i.e. has
22 // has not wrapped and is not the result of an invalid conversion).
23 // ValueOrDie() - Returns the underlying value. If the state is not valid this
24 // call will crash on a CHECK.
25 // ValueOrDefault() - Returns the current value, or the supplied default if the
26 // state is not valid.
27 // ValueFloating() - Returns the underlying floating point value (valid only
28 // only for floating point CheckedNumeric types).
29 //
30 // Bitwise operations are explicitly not supported, because correct
31 // handling of some cases (e.g. sign manipulation) is ambiguous. Comparison
32 // operations are explicitly not supported because they could result in a crash
33 // on a CHECK condition. You should use patterns like the following for these
34 // operations:
35 // Bitwise operation:
36 // CheckedNumeric<int> checked_int = untrusted_input_value;
37 // int x = checked_int.ValueOrDefault(0) | kFlagValues;
38 // Comparison:
39 // CheckedNumeric<size_t> checked_size;
40 // CheckedNumeric<int> checked_size = untrusted_input_value;
41 // checked_size = checked_size + HEADER LENGTH;
42 // if (checked_size.IsValid() && checked_size.ValueOrDie() < buffer_size)
43 // Do stuff...
44 template <typename T>
45 class CheckedNumeric {
46 private:
awong 2014/02/25 22:41:02 Private goes at the end. http://google-styleguide
jschuh 2014/02/25 22:56:16 Done.
47 CheckedNumericState<T> state_;
48
49 public:
50 typedef T type;
51 template <typename Src> friend class CheckedNumeric;
awong 2014/02/25 22:41:02 Shouldn't friend declarations go in the private se
jschuh 2014/02/25 22:56:16 Done.
52
53 CheckedNumeric() {}
54
55 // Copy constructor.
56 template <typename Src>
57 CheckedNumeric(const CheckedNumeric<Src>& rhs)
58 : state_(rhs.state_.value(), rhs.state_.validity()) {}
awong 2014/02/25 22:41:02 Can't we just do rhs.ValueUnsafe() and rhs.validit
jschuh 2014/02/25 22:56:16 Done.
59
60 template <typename Src>
61 CheckedNumeric(Src value, RangeConstraint validity)
62 : state_(value, validity) {}
63
64 // This is not an explicit constructor because we implicitly upgrade regular
65 // numerics to CheckedNumerics to make them easier to use.
66 template <typename Src>
67 CheckedNumeric(Src value)
68 : state_(value) {
69 COMPILE_ASSERT(std::numeric_limits<Src>::is_specialized,
70 argument_must_be_numeric);
71 }
72
73 // IsValid() is the public API to test if a CheckedNumeric is currently valid.
74 bool IsValid() const { return validity() == RANGE_VALID; }
75
76 // ValueOrDie() The primary accessor for the underlying value. If the current
77 // state is not valid it will CHECK and crash.
78 T ValueOrDie() const {
79 CHECK(IsValid());
80 return state_.value();
81 }
82
83 // ValueOrDefault(T default_value) A convenience method that returns the
84 // current value if the state is valid, and the supplied default_value for
85 // any other state.
86 T ValueOrDefault(T default_value) const {
87 return IsValid() ? state_.value() : default_value;
88 }
89
90 // ValueFloating() - Since floating point values include their validity state,
91 // we provide an easy method for extracting them directly, without a risk of
92 // crashing on a CHECK.
93 T ValueFloating() const {
94 COMPILE_ASSERT(std::numeric_limits<T>::is_iec559, argument_must_be_float);
95 return CheckedNumeric<T>::cast(*this).ValueUnsafe();
96 }
97
98 // validity() - DO NOT USE THIS IN EXTERNAL CODE - It is public right now for
99 // tests and to avoid a big matrix of friend operator overloads. But the
100 // values it returns are likely to change in the future.
101 // Returns: current validity state (i.e. valid, overflow, underflow, nan).
102 // TODO(jschuh): crbug.com/332611 Figure out and implement semantics for
103 // saturation/wrapping so we can expose this state consistently and implement
104 // saturated arithmetic.
105 RangeConstraint validity() const { return state_.validity(); }
106
107 // ValueUnsafe() - DO NOT USE THIS IN EXTERNAL CODE - It is public right now
108 // for tests and to avoid a big matrix of friend operator overloads. But the
109 // values it returns are likely to change in the future.
110 // Returns: the raw numeric value, regardless of the current state.
111 // TODO(jschuh): crbug.com/332611 Figure out and implement semantics for
112 // saturation/wrapping so we can expose this state consistently and implement
113 // saturated arithmetic.
114 T ValueUnsafe() const { return state_.value(); }
115
116 // Prototypes for the supported arithmetic operator overloads.
117 template <typename Src> CheckedNumeric& operator+=(Src rhs);
118 template <typename Src> CheckedNumeric& operator-=(Src rhs);
119 template <typename Src> CheckedNumeric& operator*=(Src rhs);
120 template <typename Src> CheckedNumeric& operator/=(Src rhs);
121 template <typename Src> CheckedNumeric& operator%=(Src rhs);
122
123 CheckedNumeric operator-() const {
124 RangeConstraint validity;
125 T value = CheckedNeg(state_.value(), &validity);
126 // Negation is always valid for floating point.
127 if (std::numeric_limits<T>::is_iec559)
128 return CheckedNumeric<T>(value);
129
130 validity = GetRangeConstraint(state_.validity() | validity);
131 return CheckedNumeric<T>(value, validity);
132 }
133
134 CheckedNumeric Abs() const {
135 RangeConstraint validity;
136 T value = CheckedAbs(state_.value(), &validity);
137 // Absolute value is always valid for floating point.
138 if (std::numeric_limits<T>::is_iec559)
139 return CheckedNumeric<T>(value);
140
141 validity = GetRangeConstraint(state_.validity() | validity);
142 return CheckedNumeric<T>(value, validity);
143 }
144
145 CheckedNumeric& operator++() {
146 *this += 1;
147 return *this;
148 }
149
150 CheckedNumeric operator++(int) {
151 CheckedNumeric value = *this;
152 *this += 1;
153 return value;
154 }
155
156 CheckedNumeric& operator--() {
157 *this -= 1;
158 return *this;
159 }
160
161 CheckedNumeric operator--(int) {
162 CheckedNumeric value = *this;
163 *this -= 1;
164 return value;
165 }
166
167 // These static methods behave like a convenience cast operator targeting
168 // the desired CheckedNumeric type. As an optimization, a reference is
169 // returned when Src is the same type as T.
170 template <typename Src>
171 static CheckedNumeric<T> cast(
172 Src u,
173 typename enable_if<std::numeric_limits<Src>::is_specialized, int>::type =
174 0) {
175 return u;
176 }
177
178 template <typename Src>
179 static CheckedNumeric<T> cast(
180 const CheckedNumeric<Src>& u,
181 typename enable_if<!is_same<Src, T>::value, int>::type = 0) {
182 return u;
183 }
184
185 static const CheckedNumeric<T>& cast(const CheckedNumeric<T>& u) { return u; }
186 };
187
188 // This is the boilerplate for the standard arithmetic operator overloads. A
189 // macro isn't the prettiest solution, but it beats rewriting these five times.
190 // Some details worth noting are:
191 // * We apply the standard arithmetic promotions.
192 // * We skip range checks for floating points.
193 // * We skip range checks for destination integers with sufficient range.
194 // TODO(jschuh): extract these out into templates.
195 #define BASE_NUMERIC_ARITHMETIC_OPERATORS(NAME, OP, COMPOUND_OP) \
196 /* Binary arithmetic operator for CheckedNumerics of the same type. */ \
197 template <typename T> \
198 CheckedNumeric<typename ArithmeticPromotion<T>::type> operator OP( \
199 const CheckedNumeric<T>& lhs, const CheckedNumeric<T>& rhs) { \
200 typedef typename ArithmeticPromotion<T>::type Promotion; \
201 /* Floating point always takes the fast path */ \
202 if (std::numeric_limits<T>::is_iec559) \
203 return CheckedNumeric<T>(lhs.ValueUnsafe() OP rhs.ValueUnsafe()); \
204 if (IsIntegerArithmeticSafe<Promotion, T, T>::value) \
205 return CheckedNumeric<Promotion>( \
206 lhs.ValueUnsafe() OP rhs.ValueUnsafe(), \
207 GetRangeConstraint(rhs.validity() | lhs.validity())); \
208 RangeConstraint validity = RANGE_VALID; \
209 T result = Checked##NAME(static_cast<Promotion>(lhs.ValueUnsafe()), \
210 static_cast<Promotion>(rhs.ValueUnsafe()), \
211 &validity); \
212 return CheckedNumeric<Promotion>( \
213 result, \
214 GetRangeConstraint(validity | lhs.validity() | rhs.validity())); \
215 } \
216 /* Assignment arithmetic operator implementation from CheckedNumeric. */ \
217 template <typename T> \
218 template <typename Src> \
219 CheckedNumeric<T>& CheckedNumeric<T>::operator COMPOUND_OP(Src rhs) { \
220 *this = CheckedNumeric<T>::cast(*this) OP CheckedNumeric<Src>::cast(rhs); \
221 return *this; \
222 } \
223 /* Binary arithmetic operator for CheckedNumeric of different type. */ \
224 template <typename T, typename Src> \
225 CheckedNumeric<typename ArithmeticPromotion<T, Src>::type> operator OP( \
226 const CheckedNumeric<Src>& lhs, const CheckedNumeric<T>& rhs) { \
227 typedef typename ArithmeticPromotion<T, Src>::type Promotion; \
228 if (IsIntegerArithmeticSafe<Promotion, T, Src>::value) \
229 return CheckedNumeric<Promotion>( \
230 lhs.ValueUnsafe() OP rhs.ValueUnsafe(), \
231 GetRangeConstraint(rhs.validity() | lhs.validity())); \
232 return CheckedNumeric<Promotion>::cast(lhs) \
233 OP CheckedNumeric<Promotion>::cast(rhs); \
234 } \
235 /* Binary arithmetic operator for left CheckedNumeric and right numeric. */ \
236 template <typename T, typename Src> \
237 CheckedNumeric<typename ArithmeticPromotion<T, Src>::type> operator OP( \
238 const CheckedNumeric<T>& lhs, Src rhs) { \
239 typedef typename ArithmeticPromotion<T, Src>::type Promotion; \
240 if (IsIntegerArithmeticSafe<Promotion, T, Src>::value) \
241 return CheckedNumeric<Promotion>(lhs.ValueUnsafe() OP rhs, \
242 lhs.validity()); \
243 return CheckedNumeric<Promotion>::cast(lhs) \
244 OP CheckedNumeric<Promotion>::cast(rhs); \
245 } \
246 /* Binary arithmetic operator for right numeric and left CheckedNumeric. */ \
247 template <typename T, typename Src> \
248 CheckedNumeric<typename ArithmeticPromotion<T, Src>::type> operator OP( \
249 Src lhs, const CheckedNumeric<T>& rhs) { \
250 typedef typename ArithmeticPromotion<T, Src>::type Promotion; \
251 if (IsIntegerArithmeticSafe<Promotion, T, Src>::value) \
252 return CheckedNumeric<Promotion>(lhs OP rhs.ValueUnsafe(), \
253 rhs.validity()); \
254 return CheckedNumeric<Promotion>::cast(lhs) \
255 OP CheckedNumeric<Promotion>::cast(rhs); \
256 }
257
258 BASE_NUMERIC_ARITHMETIC_OPERATORS(Add, +, += )
259 BASE_NUMERIC_ARITHMETIC_OPERATORS(Sub, -, -= )
260 BASE_NUMERIC_ARITHMETIC_OPERATORS(Mul, *, *= )
261 BASE_NUMERIC_ARITHMETIC_OPERATORS(Div, /, /= )
262 BASE_NUMERIC_ARITHMETIC_OPERATORS(Mod, %, %= )
263
264 #undef BASE_NUMERIC_ARITHMETIC_OPERATORS
265
266 } // namespace internal
267
268 using internal::CheckedNumeric;
269
270 } // namespace base
271
272 #endif // BASE_SAFE_MATH_H_
OLDNEW
« no previous file with comments | « base/numerics/safe_conversions_impl.h ('k') | base/numerics/safe_math_impl.h » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698