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

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

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