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

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: style fixes 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
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 // int x = checked_int.ValueOrDefault(0) | kFlagValues;
37 // Comparison:
38 // if (checked_size.IsValid() && checked_size.ValueOrDie() < buffer_size)
awong 2014/02/11 20:14:12 I don't see where checked_int and checked_size are
jschuh 2014/02/21 19:22:28 Done.
39 // Do stuff...
40 template <typename T>
41 class CheckedNumeric {
42 private:
43 CheckedNumericState<T> state_;
44
45 public:
46 typedef T type;
47 template <typename Src>
48 friend class CheckedNumeric;
49
50 CheckedNumeric() {}
51
52 // Copy constructor.
53 template <typename Src>
54 CheckedNumeric(const CheckedNumeric<Src>& rhs)
55 : state_(rhs.state_.value(), rhs.state_.validity()) {}
56
57 template <typename Src>
58 CheckedNumeric(Src value, RangeCheckId validity)
59 : state_(value, validity) {}
60
61 // This is not an explicit constructor because we implicitly upgrade regular
62 // numerics to CheckedNumerics to make them easier to use.
63 template <typename Src>
64 CheckedNumeric(Src value)
65 : state_(value) {
66 COMPILE_ASSERT(numeric_limits<Src>::is_specialized,
67 argument_must_be_numeric);
68 }
69
70 // validity() - DO NOT USE THIS IN EXTERNAL CODE - It is public right now for
71 // tests and to avoid a big matrix of friend operator overloads. But the
72 // values it returns are likely to change in the future.
73 // Returns: current validity state (i.e. valid, overflow, underflow, nan).
74 // TODO(jschuh): crbug.com/332611 Figure out and implement semantics for
75 // saturation/wrapping so we can expose this state consistently and implement
76 // saturated arithmetic.
77 RangeCheckId validity() const { return state_.validity(); }
78
79 // IsValid() is the public API to test if a CheckedNumeric is currently valid.
80 bool IsValid() const { return validity() == TYPE_VALID; }
81
82 // ValueUnsafe() - DO NOT USE THIS IN EXTERNAL CODE - It is public right now
83 // for tests and to avoid a big matrix of friend operator overloads. But the
84 // values it returns are likely to change in the future.
85 // Returns: the raw numeric value, regardless of the current state.
86 // TODO(jschuh): crbug.com/332611 Figure out and implement semantics for
87 // saturation/wrapping so we can expose this state consistently and implement
88 // saturated arithmetic.
89 T ValueUnsafe() const { return state_.value(); }
90
91 // ValueOrDie() The primary accessor for the underlying value. If the current
92 // state is not valid it will CHECK and crash.
93 T ValueOrDie() const {
94 CHECK(IsValid());
95 return state_.value();
96 }
97
98 // ValueOrDefault(T default_value) A convenience method that returns the
99 // current value if the state is valid, and the supplied default_value for
100 // any other state.
101 T ValueOrDefault(T default_value) const {
102 return IsValid() ? state_.value() : default_value;
103 }
104
105 // ValueFloating() - Since floating point values include their validity state,
106 // we provide an easy method for extracting them directly, without a risk of
107 // crashing on a CHECK.
108 T ValueFloating() {
awong 2014/02/11 20:14:12 Why isn't this const?
jschuh 2014/02/21 19:22:28 Done.
109 COMPILE_ASSERT(numeric_limits<T>::is_iec559, argument_must_be_float);
110 return CheckedNumeric<T>::cast(*this).ValueUnsafe();
111 }
112
113 // Prototypes for the supported arithmetic operator overloads.
114 template <typename Src>
awong 2014/02/11 20:14:12 Ugh. Do you really need overloaded operators?
jschuh 2014/02/21 19:22:28 Well, if I want it to be easy to use. :)
115 CheckedNumeric& operator+=(Src rhs);
116 template <typename Src>
117 CheckedNumeric& operator-=(Src rhs);
118 template <typename Src>
119 CheckedNumeric& operator*=(Src rhs);
120 template <typename Src>
121 CheckedNumeric& operator/=(Src rhs);
122 template <typename Src>
123 CheckedNumeric& operator%=(Src rhs);
124
125 CheckedNumeric operator-() const {
126 RangeCheckId validity;
127 T value = CheckedNeg(state_.value(), &validity);
128 // Negation is always valid for floating point.
129 if (numeric_limits<T>::is_iec559)
130 return CheckedNumeric<T>(value);
131
132 validity = static_cast<RangeCheckId>(state_.validity() | validity);
133 return CheckedNumeric<T>(value, validity);
134 }
135
136 CheckedNumeric Abs() const {
137 RangeCheckId validity;
138 T value = CheckedAbs(state_.value(), &validity);
139 // Absolute value is always valid for floating point.
140 if (numeric_limits<T>::is_iec559)
141 return CheckedNumeric<T>(value);
142
143 validity = static_cast<RangeCheckId>(state_.validity() | validity);
144 return CheckedNumeric<T>(value, validity);
145 }
146
147 CheckedNumeric& operator++() {
148 *this += 1;
149 return *this;
150 }
151
152 CheckedNumeric operator++(int) {
153 CheckedNumeric value = *this;
154 *this += 1;
155 return value;
156 }
157
158 CheckedNumeric& operator--() {
159 *this -= 1;
160 return *this;
161 }
162
163 CheckedNumeric operator--(int) {
164 CheckedNumeric value = *this;
165 *this -= 1;
166 return value;
167 }
168
169 // These static methods behave like a convenience cast operator targeting
170 // the desired CheckedNumeric type. As an optimization, a reference is
171 // returned when Src is the same type as T.
172 template <typename Src>
173 static CheckedNumeric<T> cast(
174 Src u,
175 typename enable_if<numeric_limits<Src>::is_specialized, int>::type = 0) {
176 return u;
177 }
178
179 template <typename Src>
180 static CheckedNumeric<T> cast(
181 const CheckedNumeric<Src>& u,
182 typename enable_if<!is_same<Src, T>::value, int>::type = 0) {
183 return u;
184 }
185
186 static const CheckedNumeric<T>& cast(const CheckedNumeric<T>& u) { return u; }
187 };
188
189 // This is the boilerplate for the standard arithmetic operator overloads. A
190 // macro isn't the prettiest solution, but it beats rewriting these five times.
191 // Some details worth noting are:
192 // * We apply the standard arithmetic promotions.
193 // * We skip range checks for floating points.
194 // * We skip range checks for destination integers with sufficient range.
195 #define BASE_NUMERIC_ARITHMETIC_OPERATORS( \
awong 2014/02/11 19:40:10 ?! Is there some way to make this more sane? I fe
awong 2014/02/11 21:02:11 To expand on this, assume you wrote a bunch of sil
jschuh 2014/02/21 19:22:28 Punting for now based on our conversation, but I w
196 NAME, OP, COMPOUND_OP) /* Binary arithmetic operator for CheckedNumerics \
197 of the same type. */ \
198 template <typename T> \
199 CheckedNumeric<typename ArithmeticPromotion<T>::type> operator OP( \
200 const CheckedNumeric<T>& lhs, const CheckedNumeric<T>& rhs) { \
201 typedef typename ArithmeticPromotion<T>::type Promotion; \
202 /* Floating point always takes the fast path */ \
203 if (numeric_limits<T>::is_iec559) \
204 return CheckedNumeric<T>(lhs.ValueUnsafe() OP rhs.ValueUnsafe()); \
205 if (IsIntegerArithmeticSafe<Promotion, T, T>::value) \
206 return CheckedNumeric<Promotion>( \
207 lhs.ValueUnsafe() OP rhs.ValueUnsafe(), \
208 static_cast<RangeCheckId>(rhs.validity() | lhs.validity())); \
209 RangeCheckId validity = TYPE_VALID; \
210 T result = Checked##NAME(static_cast<Promotion>(lhs.ValueUnsafe()), \
211 static_cast<Promotion>(rhs.ValueUnsafe()), \
212 &validity); \
213 return CheckedNumeric<Promotion>( \
214 result, \
215 static_cast<RangeCheckId>(validity | lhs.validity() | \
216 rhs.validity())); \
217 } /* Assignment arithmetic operator implementation from CheckedNumeric \
218 above. */ \
219 template <typename T> \
220 template <typename Src> \
221 CheckedNumeric<T>& CheckedNumeric<T>::operator COMPOUND_OP(Src rhs) { \
222 *this = CheckedNumeric<T>::cast(*this) OP CheckedNumeric<Src>::cast(rhs); \
223 return *this; \
224 } /* Binary arithmetic operator for CheckedNumeric of different type. */ \
225 template <typename T, typename Src> \
226 CheckedNumeric<typename ArithmeticPromotion<T, Src>::type> operator OP( \
227 const CheckedNumeric<Src>& lhs, const CheckedNumeric<T>& rhs) { \
228 typedef typename ArithmeticPromotion<T, Src>::type Promotion; \
229 if (IsIntegerArithmeticSafe<Promotion, T, Src>::value) \
230 return CheckedNumeric<Promotion>( \
231 lhs.ValueUnsafe() OP rhs.ValueUnsafe(), \
232 static_cast<RangeCheckId>(rhs.validity() | lhs.validity())); \
233 return CheckedNumeric<Promotion>::cast(lhs) \
234 OP CheckedNumeric<Promotion>::cast(rhs); \
235 } /* Binary arithmetic operator for left CheckedNumeric and right numeric. \
236 */ \
237 template <typename T, typename Src> \
238 CheckedNumeric<typename ArithmeticPromotion<T, Src>::type> operator OP( \
239 const CheckedNumeric<T>& lhs, Src rhs) { \
240 typedef typename ArithmeticPromotion<T, Src>::type Promotion; \
241 if (IsIntegerArithmeticSafe<Promotion, T, Src>::value) \
242 return CheckedNumeric<Promotion>(lhs.ValueUnsafe() OP rhs, \
243 lhs.validity()); \
244 return CheckedNumeric<Promotion>::cast(lhs) \
245 OP CheckedNumeric<Promotion>::cast(rhs); \
246 } /* Binary arithmetic operator for right numeric and left CheckedNumeric. \
247 */ \
248 template <typename T, typename Src> \
249 CheckedNumeric<typename ArithmeticPromotion<T, Src>::type> operator OP( \
250 Src lhs, const CheckedNumeric<T>& rhs) { \
251 typedef typename ArithmeticPromotion<T, Src>::type Promotion; \
252 if (IsIntegerArithmeticSafe<Promotion, T, Src>::value) \
253 return CheckedNumeric<Promotion>(lhs OP rhs.ValueUnsafe(), \
254 rhs.validity()); \
255 return CheckedNumeric<Promotion>::cast(lhs) \
256 OP CheckedNumeric<Promotion>::cast(rhs); \
257 }
258
259 BASE_NUMERIC_ARITHMETIC_OPERATORS(Add, +, += )
260 BASE_NUMERIC_ARITHMETIC_OPERATORS(Sub, -, -= )
261 BASE_NUMERIC_ARITHMETIC_OPERATORS(Mul, *, *= )
262 BASE_NUMERIC_ARITHMETIC_OPERATORS(Div, /, /= )
263 BASE_NUMERIC_ARITHMETIC_OPERATORS(Mod, %, %= )
264
265 #undef BASE_NUMERIC_ARITHMETIC_OPERATORS
266
267 } // namespace internal
268
269 using internal::CheckedNumeric;
270
271 } // namespace base
272
273 #endif // BASE_SAFE_MATH_H_
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698