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

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

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

Powered by Google App Engine
This is Rietveld 408576698