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

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

Issue 1753293002: Safe numeric library: base/numerics (copied from Chromium) (Closed) Base URL: https://chromium.googlesource.com/external/webrtc.git@master
Patch Set: Comment about chromium_revision Created 4 years, 9 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
OLDNEW
(Empty)
1 /*
2 * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 *
10 */
11
12 // Borrowed from Chromium's src/base/numerics/safe_math.h.
13 // - Modified to work in WebRTC (paths, #ifndef, namespace, webrtc/base/checks,
14 // compiler warnings and cpplint.py, etc).
15 // Based on 'chromium_revision': 'ee311243eae6aef9c907543663754ff38f1f4f40'.
16
17 #ifndef WEBRTC_BASE_NUMERICS_SAFE_MATH_H_
18 #define WEBRTC_BASE_NUMERICS_SAFE_MATH_H_
19
20 #include <stddef.h>
21 #include <type_traits>
22
23 #include <limits>
24
25 #include "webrtc/base/checks.h"
26 #include "webrtc/base/numerics/safe_math_impl.h"
27
28 namespace rtc {
29
30 namespace internal {
31
32 // CheckedNumeric implements all the logic and operators for detecting integer
33 // boundary conditions such as overflow, underflow, and invalid conversions.
34 // The CheckedNumeric type implicitly converts from floating point and integer
35 // data types, and contains overloads for basic arithmetic operations (i.e.: +,
36 // -, *, /, %).
37 //
38 // The following methods convert from CheckedNumeric to standard numeric values:
39 // IsValid() - Returns true if the underlying numeric value is valid (i.e. has
40 // has not wrapped and is not the result of an invalid conversion).
41 // ValueOrDie() - Returns the underlying value. If the state is not valid this
42 // call will crash on a RTC_CHECK.
43 // ValueOrDefault() - Returns the current value, or the supplied default if the
44 // state is not valid.
45 // ValueFloating() - Returns the underlying floating point value (valid only
46 // only for floating point CheckedNumeric types).
47 //
48 // Bitwise operations are explicitly not supported, because correct
49 // handling of some cases (e.g. sign manipulation) is ambiguous. Comparison
50 // operations are explicitly not supported because they could result in a crash
51 // on a RTC_CHECK condition. You should use patterns like the following for
52 // these operations:
53 // Bitwise operation:
54 // CheckedNumeric<int> checked_int = untrusted_input_value;
55 // int x = checked_int.ValueOrDefault(0) | kFlagValues;
56 // Comparison:
57 // CheckedNumeric<size_t> checked_size = untrusted_input_value;
58 // checked_size += HEADER LENGTH;
59 // if (checked_size.IsValid() && checked_size.ValueOrDie() < buffer_size)
60 // Do stuff...
61 template <typename T>
62 class CheckedNumeric {
63 public:
64 typedef T type;
65
66 CheckedNumeric() {}
67
68 // Copy constructor.
69 template <typename Src>
70 CheckedNumeric(const CheckedNumeric<Src>& rhs)
71 : state_(rhs.ValueUnsafe(), rhs.validity()) {}
72
73 template <typename Src>
74 CheckedNumeric(Src value, RangeConstraint validity)
75 : state_(value, validity) {}
76
77 // This is not an explicit constructor because we implicitly upgrade regular
78 // numerics to CheckedNumerics to make them easier to use.
79 template <typename Src>
80 explicit CheckedNumeric(Src value)
81 : state_(value) {
82 static_assert(std::numeric_limits<Src>::is_specialized,
83 "Argument must be numeric.");
84 }
85
86 // This is not an explicit constructor because we want a seamless conversion
87 // from StrictNumeric types.
88 template <typename Src>
89 explicit CheckedNumeric(StrictNumeric<Src> value)
90 : state_(static_cast<Src>(value)) {
91 }
92
93 // IsValid() is the public API to test if a CheckedNumeric is currently valid.
94 bool IsValid() const { return validity() == RANGE_VALID; }
95
96 // ValueOrDie() The primary accessor for the underlying value. If the current
97 // state is not valid it will RTC_CHECK and crash.
98 T ValueOrDie() const {
99 RTC_CHECK(IsValid());
100 return state_.value();
101 }
102
103 // ValueOrDefault(T default_value) A convenience method that returns the
104 // current value if the state is valid, and the supplied default_value for
105 // any other state.
106 T ValueOrDefault(T default_value) const {
107 return IsValid() ? state_.value() : default_value;
108 }
109
110 // ValueFloating() - Since floating point values include their validity state,
111 // we provide an easy method for extracting them directly, without a risk of
112 // crashing on a RTC_CHECK.
113 T ValueFloating() const {
114 static_assert(std::numeric_limits<T>::is_iec559, "Argument must be float.");
115 return CheckedNumeric<T>::cast(*this).ValueUnsafe();
116 }
117
118 // validity() - DO NOT USE THIS IN EXTERNAL CODE - It is public right now for
119 // tests and to avoid a big matrix of friend operator overloads. But the
120 // values it returns are likely to change in the future.
121 // Returns: current validity state (i.e. valid, overflow, underflow, nan).
122 // TODO(jschuh): crbug.com/332611 Figure out and implement semantics for
123 // saturation/wrapping so we can expose this state consistently and implement
124 // saturated arithmetic.
125 RangeConstraint validity() const { return state_.validity(); }
126
127 // ValueUnsafe() - DO NOT USE THIS IN EXTERNAL CODE - It is public right now
128 // for tests and to avoid a big matrix of friend operator overloads. But the
129 // values it returns are likely to change in the future.
130 // Returns: the raw numeric value, regardless of the current state.
131 // TODO(jschuh): crbug.com/332611 Figure out and implement semantics for
132 // saturation/wrapping so we can expose this state consistently and implement
133 // saturated arithmetic.
134 T ValueUnsafe() const { return state_.value(); }
135
136 // Prototypes for the supported arithmetic operator overloads.
137 template <typename Src> CheckedNumeric& operator+=(Src rhs);
138 template <typename Src> CheckedNumeric& operator-=(Src rhs);
139 template <typename Src> CheckedNumeric& operator*=(Src rhs);
140 template <typename Src> CheckedNumeric& operator/=(Src rhs);
141 template <typename Src> CheckedNumeric& operator%=(Src rhs);
142
143 CheckedNumeric operator-() const {
144 RangeConstraint validity;
145 T value = CheckedNeg(state_.value(), &validity);
146 // Negation is always valid for floating point.
147 if (std::numeric_limits<T>::is_iec559)
148 return CheckedNumeric<T>(value);
149
150 validity = GetRangeConstraint(state_.validity() | validity);
151 return CheckedNumeric<T>(value, validity);
152 }
153
154 CheckedNumeric Abs() const {
155 RangeConstraint validity;
156 T value = CheckedAbs(state_.value(), &validity);
157 // Absolute value is always valid for floating point.
158 if (std::numeric_limits<T>::is_iec559)
159 return CheckedNumeric<T>(value);
160
161 validity = GetRangeConstraint(state_.validity() | validity);
162 return CheckedNumeric<T>(value, validity);
163 }
164
165 // This function is available only for integral types. It returns an unsigned
166 // integer of the same width as the source type, containing the absolute value
167 // of the source, and properly handling signed min.
168 CheckedNumeric<typename UnsignedOrFloatForSize<T>::type> UnsignedAbs() const {
169 return CheckedNumeric<typename UnsignedOrFloatForSize<T>::type>(
170 CheckedUnsignedAbs(state_.value()), state_.validity());
171 }
172
173 CheckedNumeric& operator++() {
174 *this += 1;
175 return *this;
176 }
177
178 CheckedNumeric operator++(int) {
179 CheckedNumeric value = *this;
180 *this += 1;
181 return value;
182 }
183
184 CheckedNumeric& operator--() {
185 *this -= 1;
186 return *this;
187 }
188
189 CheckedNumeric operator--(int) {
190 CheckedNumeric value = *this;
191 *this -= 1;
192 return value;
193 }
194
195 // These static methods behave like a convenience cast operator targeting
196 // the desired CheckedNumeric type. As an optimization, a reference is
197 // returned when Src is the same type as T.
198 template <typename Src>
199 static CheckedNumeric<T> cast(
200 Src u,
201 typename std::enable_if<std::numeric_limits<Src>::is_specialized,
202 int>::type = 0) {
203 return u;
204 }
205
206 template <typename Src>
207 static CheckedNumeric<T> cast(
208 const CheckedNumeric<Src>& u,
209 typename std::enable_if<!std::is_same<Src, T>::value, int>::type = 0) {
210 return u;
211 }
212
213 static const CheckedNumeric<T>& cast(const CheckedNumeric<T>& u) { return u; }
214
215 private:
216 template <typename NumericType>
217 struct UnderlyingType {
218 using type = NumericType;
219 };
220
221 template <typename NumericType>
222 struct UnderlyingType<CheckedNumeric<NumericType>> {
223 using type = NumericType;
224 };
225
226 CheckedNumericState<T> state_;
227 };
228
229 // This is the boilerplate for the standard arithmetic operator overloads. A
230 // macro isn't the prettiest solution, but it beats rewriting these five times.
231 // Some details worth noting are:
232 // * We apply the standard arithmetic promotions.
233 // * We skip range checks for floating points.
234 // * We skip range checks for destination integers with sufficient range.
235 // TODO(jschuh): extract these out into templates.
236 #define BASE_NUMERIC_ARITHMETIC_OPERATORS(NAME, OP, COMPOUND_OP) \
237 /* Binary arithmetic operator for CheckedNumerics of the same type. */ \
238 template <typename T> \
239 CheckedNumeric<typename ArithmeticPromotion<T>::type> operator OP( \
240 const CheckedNumeric<T>& lhs, const CheckedNumeric<T>& rhs) { \
241 typedef typename ArithmeticPromotion<T>::type Promotion; \
242 /* Floating point always takes the fast path */ \
243 if (std::numeric_limits<T>::is_iec559) \
244 return CheckedNumeric<T>(lhs.ValueUnsafe() OP rhs.ValueUnsafe()); \
245 if (IsIntegerArithmeticSafe<Promotion, T, T>::value) \
246 return CheckedNumeric<Promotion>( \
247 lhs.ValueUnsafe() OP rhs.ValueUnsafe(), \
248 GetRangeConstraint(rhs.validity() | lhs.validity())); \
249 RangeConstraint validity = RANGE_VALID; \
250 T result = static_cast<T>(Checked##NAME( \
251 static_cast<Promotion>(lhs.ValueUnsafe()), \
252 static_cast<Promotion>(rhs.ValueUnsafe()), \
253 &validity)); \
254 return CheckedNumeric<Promotion>( \
255 result, \
256 GetRangeConstraint(validity | lhs.validity() | rhs.validity())); \
257 } \
258 /* Assignment arithmetic operator implementation from CheckedNumeric. */ \
259 template <typename T> \
260 template <typename Src> \
261 CheckedNumeric<T>& CheckedNumeric<T>::operator COMPOUND_OP(Src rhs) { \
262 *this = CheckedNumeric<T>::cast(*this) \
263 OP CheckedNumeric<typename UnderlyingType<Src>::type>::cast(rhs); \
264 return *this; \
265 } \
266 /* Binary arithmetic operator for CheckedNumeric of different type. */ \
267 template <typename T, typename Src> \
268 CheckedNumeric<typename ArithmeticPromotion<T, Src>::type> operator OP( \
269 const CheckedNumeric<Src>& lhs, const CheckedNumeric<T>& rhs) { \
270 typedef typename ArithmeticPromotion<T, Src>::type Promotion; \
271 if (IsIntegerArithmeticSafe<Promotion, T, Src>::value) \
272 return CheckedNumeric<Promotion>( \
273 lhs.ValueUnsafe() OP rhs.ValueUnsafe(), \
274 GetRangeConstraint(rhs.validity() | lhs.validity())); \
275 return CheckedNumeric<Promotion>::cast(lhs) \
276 OP CheckedNumeric<Promotion>::cast(rhs); \
277 } \
278 /* Binary arithmetic operator for left CheckedNumeric and right numeric. */ \
279 template <typename T, typename Src> \
280 CheckedNumeric<typename ArithmeticPromotion<T, Src>::type> operator OP( \
281 const CheckedNumeric<T>& lhs, Src rhs) { \
282 typedef typename ArithmeticPromotion<T, Src>::type Promotion; \
283 if (IsIntegerArithmeticSafe<Promotion, T, Src>::value) \
284 return CheckedNumeric<Promotion>(lhs.ValueUnsafe() OP rhs, \
285 lhs.validity()); \
286 return CheckedNumeric<Promotion>::cast(lhs) \
287 OP CheckedNumeric<Promotion>::cast(rhs); \
288 } \
289 /* Binary arithmetic operator for right numeric and left CheckedNumeric. */ \
290 template <typename T, typename Src> \
291 CheckedNumeric<typename ArithmeticPromotion<T, Src>::type> operator OP( \
292 Src lhs, const CheckedNumeric<T>& rhs) { \
293 typedef typename ArithmeticPromotion<T, Src>::type Promotion; \
294 if (IsIntegerArithmeticSafe<Promotion, T, Src>::value) \
295 return CheckedNumeric<Promotion>(lhs OP rhs.ValueUnsafe(), \
296 rhs.validity()); \
297 return CheckedNumeric<Promotion>::cast(lhs) \
298 OP CheckedNumeric<Promotion>::cast(rhs); \
299 }
300
301 BASE_NUMERIC_ARITHMETIC_OPERATORS(Add, +, += )
302 BASE_NUMERIC_ARITHMETIC_OPERATORS(Sub, -, -= )
303 BASE_NUMERIC_ARITHMETIC_OPERATORS(Mul, *, *= )
304 BASE_NUMERIC_ARITHMETIC_OPERATORS(Div, /, /= )
305 BASE_NUMERIC_ARITHMETIC_OPERATORS(Mod, %, %= )
306
307 #undef BASE_NUMERIC_ARITHMETIC_OPERATORS
308
309 } // namespace internal
310
311 using internal::CheckedNumeric;
312
313 } // namespace rtc
314
315 #endif // WEBRTC_BASE_NUMERICS_SAFE_MATH_H_
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698