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

Side by Side Diff: third_party/base/numerics/safe_conversions.h

Issue 2640143003: Update safe numerics package to get bitwise ops (Closed)
Patch Set: 0 is a perfectly fine value of zero Created 3 years, 11 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
1 // Copyright 2014 The Chromium Authors. All rights reserved. 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 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 4
5 #ifndef PDFIUM_THIRD_PARTY_BASE_SAFE_CONVERSIONS_H_ 5 #ifndef PDFIUM_THIRD_PARTY_BASE_NUMERICS_SAFE_CONVERSIONS_H_
6 #define PDFIUM_THIRD_PARTY_BASE_SAFE_CONVERSIONS_H_ 6 #define PDFIUM_THIRD_PARTY_BASE_NUMERICS_SAFE_CONVERSIONS_H_
7
8 #include <stddef.h>
7 9
8 #include <limits> 10 #include <limits>
9 11 #include <ostream>
10 #include "safe_conversions_impl.h" 12 #include <type_traits>
11 #include "third_party/base/logging.h" 13
14 #include "third_party/base/numerics/safe_conversions_impl.h"
12 15
13 namespace pdfium { 16 namespace pdfium {
14 namespace base { 17 namespace base {
15 18
19 // The following are helper constexpr template functions and classes for safely
20 // performing a range of conversions, assignments, and tests:
21 //
22 // checked_cast<> - Analogous to static_cast<> for numeric types, except
23 // that it CHECKs that the specified numeric conversion will not overflow
24 // or underflow. NaN source will always trigger a CHECK.
25 // The default CHECK triggers a crash, but the handler can be overriden.
26 // saturated_cast<> - Analogous to static_cast<> for numeric types, except
27 // that it returns a saturated result when the specified numeric conversion
28 // would otherwise overflow or underflow. An NaN source returns 0 by
29 // default, but can be overridden to return a different result.
30 // strict_cast<> - Analogous to static_cast<> for numeric types, except that
31 // it will cause a compile failure if the destination type is not large
32 // enough to contain any value in the source type. It performs no runtime
33 // checking and thus introduces no runtime overhead.
34 // IsValueInRangeForNumericType<>() - A convenience function that returns true
35 // if the type supplied to the template parameter can represent the value
36 // passed as an argument to the function.
37 // IsValueNegative<>() - A convenience function that will accept any arithmetic
38 // type as an argument and will return whether the value is less than zero.
39 // Unsigned types always return false.
40 // SafeUnsignedAbs() - Returns the absolute value of the supplied integer
41 // parameter as an unsigned result (thus avoiding an overflow if the value
42 // is the signed, two's complement minimum).
43 // StrictNumeric<> - A wrapper type that performs assignments and copies via
44 // the strict_cast<> template, and can perform valid arithmetic comparisons
45 // across any range of arithmetic types. StrictNumeric is the return type
46 // for values extracted from a CheckedNumeric class instance. The raw
47 // arithmetic value is extracted via static_cast to the underlying type.
48 // MakeStrictNum() - Creates a new StrictNumeric from the underlying type of
49 // the supplied arithmetic or StrictNumeric type.
50
16 // Convenience function that returns true if the supplied value is in range 51 // Convenience function that returns true if the supplied value is in range
17 // for the destination type. 52 // for the destination type.
18 template <typename Dst, typename Src> 53 template <typename Dst, typename Src>
19 inline bool IsValueInRangeForNumericType(Src value) { 54 constexpr bool IsValueInRangeForNumericType(Src value) {
20 return internal::DstRangeRelationToSrcRange<Dst>(value) == 55 return internal::DstRangeRelationToSrcRange<Dst>(value).IsValid();
21 internal::RANGE_VALID; 56 }
22 } 57
58 // Forces a crash, like a CHECK(false). Used for numeric boundary errors.
59 struct CheckOnFailure {
60 template <typename T>
61 static T HandleFailure() {
62 #if defined(__GNUC__) || defined(__clang__)
63 __builtin_trap();
64 #else
65 ((void)(*(volatile char*)0 = 0));
66 #endif
67 return T();
68 }
69 };
23 70
24 // checked_cast<> is analogous to static_cast<> for numeric types, 71 // checked_cast<> is analogous to static_cast<> for numeric types,
25 // except that it CHECKs that the specified numeric conversion will not 72 // except that it CHECKs that the specified numeric conversion will not
26 // overflow or underflow. NaN source will always trigger a CHECK. 73 // overflow or underflow. NaN source will always trigger a CHECK.
74 template <typename Dst, class CheckHandler = CheckOnFailure, typename Src>
75 constexpr Dst checked_cast(Src value) {
76 // This throws a compile-time error on evaluating the constexpr if it can be
77 // determined at compile-time as failing, otherwise it will CHECK at runtime.
78 using SrcType = typename internal::UnderlyingType<Src>::type;
79 return IsValueInRangeForNumericType<Dst, SrcType>(value)
80 ? static_cast<Dst>(static_cast<SrcType>(value))
81 : CheckHandler::template HandleFailure<Dst>();
82 }
83
84 // Default boundaries for integral/float: max/infinity, lowest/-infinity, 0/NaN.
85 template <typename T>
86 struct SaturationDefaultHandler {
87 static constexpr T NaN() {
88 return std::numeric_limits<T>::has_quiet_NaN
89 ? std::numeric_limits<T>::quiet_NaN()
90 : T();
91 }
92 static constexpr T max() { return std::numeric_limits<T>::max(); }
93 static constexpr T Overflow() {
94 return std::numeric_limits<T>::has_infinity
95 ? std::numeric_limits<T>::infinity()
96 : std::numeric_limits<T>::max();
97 }
98 static constexpr T lowest() { return std::numeric_limits<T>::lowest(); }
99 static constexpr T Underflow() {
100 return std::numeric_limits<T>::has_infinity
101 ? std::numeric_limits<T>::infinity() * -1
102 : std::numeric_limits<T>::lowest();
103 }
104 };
105
106 namespace internal {
107
108 template <typename Dst, template <typename> class S, typename Src>
109 constexpr Dst saturated_cast_impl(Src value, RangeCheck constraint) {
110 // For some reason clang generates much better code when the branch is
111 // structured exactly this way, rather than a sequence of checks.
112 return !constraint.IsOverflowFlagSet()
113 ? (!constraint.IsUnderflowFlagSet() ? static_cast<Dst>(value)
114 : S<Dst>::Underflow())
115 // Skip this check for integral Src, which cannot be NaN.
116 : (std::is_integral<Src>::value || !constraint.IsUnderflowFlagSet()
117 ? S<Dst>::Overflow()
118 : S<Dst>::NaN());
119 }
120
121 // saturated_cast<> is analogous to static_cast<> for numeric types, except
122 // that the specified numeric conversion will saturate by default rather than
123 // overflow or underflow, and NaN assignment to an integral will return 0.
124 // All boundary condition behaviors can be overriden with a custom handler.
125 template <typename Dst,
126 template <typename>
127 class SaturationHandler = SaturationDefaultHandler,
128 typename Src>
129 constexpr Dst saturated_cast(Src value) {
130 using SrcType = typename UnderlyingType<Src>::type;
131 return saturated_cast_impl<Dst, SaturationHandler, SrcType>(
132 value,
133 DstRangeRelationToSrcRange<Dst, SaturationHandler, SrcType>(value));
134 }
135
136 // strict_cast<> is analogous to static_cast<> for numeric types, except that
137 // it will cause a compile failure if the destination type is not large enough
138 // to contain any value in the source type. It performs no runtime checking.
27 template <typename Dst, typename Src> 139 template <typename Dst, typename Src>
28 inline Dst checked_cast(Src value) { 140 constexpr Dst strict_cast(Src value) {
29 CHECK(IsValueInRangeForNumericType<Dst>(value)); 141 using SrcType = typename UnderlyingType<Src>::type;
30 return static_cast<Dst>(value); 142 static_assert(UnderlyingType<Src>::is_numeric, "Argument must be numeric.");
31 } 143 static_assert(std::is_arithmetic<Dst>::value, "Result must be numeric.");
32 144
33 // saturated_cast<> is analogous to static_cast<> for numeric types, except 145 // If you got here from a compiler error, it's because you tried to assign
34 // that the specified numeric conversion will saturate rather than overflow or 146 // from a source type to a destination type that has insufficient range.
35 // underflow. NaN assignment to an integral will trigger a CHECK condition. 147 // The solution may be to change the destination type you're assigning to,
148 // and use one large enough to represent the source.
149 // Alternatively, you may be better served with the checked_cast<> or
150 // saturated_cast<> template functions for your particular use case.
151 static_assert(StaticDstRangeRelationToSrcRange<Dst, SrcType>::value ==
152 NUMERIC_RANGE_CONTAINED,
153 "The source type is out of range for the destination type. "
154 "Please see strict_cast<> comments for more information.");
155
156 return static_cast<Dst>(static_cast<SrcType>(value));
157 }
158
159 // Some wrappers to statically check that a type is in range.
160 template <typename Dst, typename Src, class Enable = void>
161 struct IsNumericRangeContained {
162 static const bool value = false;
163 };
164
36 template <typename Dst, typename Src> 165 template <typename Dst, typename Src>
37 inline Dst saturated_cast(Src value) { 166 struct IsNumericRangeContained<
38 // Optimization for floating point values, which already saturate. 167 Dst,
39 if (std::numeric_limits<Dst>::is_iec559) 168 Src,
40 return static_cast<Dst>(value); 169 typename std::enable_if<ArithmeticOrUnderlyingEnum<Dst>::value &&
41 170 ArithmeticOrUnderlyingEnum<Src>::value>::type> {
42 switch (internal::DstRangeRelationToSrcRange<Dst>(value)) { 171 static const bool value = StaticDstRangeRelationToSrcRange<Dst, Src>::value ==
43 case internal::RANGE_VALID: 172 NUMERIC_RANGE_CONTAINED;
44 return static_cast<Dst>(value); 173 };
45 174
46 case internal::RANGE_UNDERFLOW: 175 // StrictNumeric implements compile time range checking between numeric types by
47 return std::numeric_limits<Dst>::min(); 176 // wrapping assignment operations in a strict_cast. This class is intended to be
48 177 // used for function arguments and return types, to ensure the destination type
49 case internal::RANGE_OVERFLOW: 178 // can always contain the source type. This is essentially the same as enforcing
50 return std::numeric_limits<Dst>::max(); 179 // -Wconversion in gcc and C4302 warnings on MSVC, but it can be applied
51 180 // incrementally at API boundaries, making it easier to convert code so that it
52 // Should fail only on attempting to assign NaN to a saturated integer. 181 // compiles cleanly with truncation warnings enabled.
53 case internal::RANGE_INVALID: 182 // This template should introduce no runtime overhead, but it also provides no
54 CHECK(false); 183 // runtime checking of any of the associated mathematical operations. Use
55 return std::numeric_limits<Dst>::max(); 184 // CheckedNumeric for runtime range checks of the actual value being assigned.
56 } 185 template <typename T>
57 186 class StrictNumeric {
58 NOTREACHED(); 187 public:
59 return static_cast<Dst>(value); 188 using type = T;
60 } 189
190 constexpr StrictNumeric() : value_(0) {}
191
192 // Copy constructor.
193 template <typename Src>
194 constexpr StrictNumeric(const StrictNumeric<Src>& rhs)
195 : value_(strict_cast<T>(rhs.value_)) {}
196
197 // This is not an explicit constructor because we implicitly upgrade regular
198 // numerics to StrictNumerics to make them easier to use.
199 template <typename Src>
200 constexpr StrictNumeric(Src value) // NOLINT(runtime/explicit)
201 : value_(strict_cast<T>(value)) {}
202
203 // If you got here from a compiler error, it's because you tried to assign
204 // from a source type to a destination type that has insufficient range.
205 // The solution may be to change the destination type you're assigning to,
206 // and use one large enough to represent the source.
207 // If you're assigning from a CheckedNumeric<> class, you may be able to use
208 // the AssignIfValid() member function, specify a narrower destination type to
209 // the member value functions (e.g. val.template ValueOrDie<Dst>()), use one
210 // of the value helper functions (e.g. ValueOrDieForType<Dst>(val)).
211 // If you've encountered an _ambiguous overload_ you can use a static_cast<>
212 // to explicitly cast the result to the destination type.
213 // If none of that works, you may be better served with the checked_cast<> or
214 // saturated_cast<> template functions for your particular use case.
215 template <typename Dst,
216 typename std::enable_if<
217 IsNumericRangeContained<Dst, T>::value>::type* = nullptr>
218 constexpr operator Dst() const {
219 return static_cast<typename ArithmeticOrUnderlyingEnum<Dst>::type>(value_);
220 }
221
222 private:
223 const T value_;
224 };
225
226 // Convience wrapper returns a StrictNumeric from the provided arithmetic type.
227 template <typename T>
228 constexpr StrictNumeric<typename UnderlyingType<T>::type> MakeStrictNum(
229 const T value) {
230 return value;
231 }
232
233 // Overload the ostream output operator to make logging work nicely.
234 template <typename T>
235 std::ostream& operator<<(std::ostream& os, const StrictNumeric<T>& value) {
236 os << static_cast<T>(value);
237 return os;
238 }
239
240 #define STRICT_COMPARISON_OP(NAME, OP) \
241 template <typename L, typename R, \
242 typename std::enable_if< \
243 internal::IsStrictOp<L, R>::value>::type* = nullptr> \
244 constexpr bool operator OP(const L lhs, const R rhs) { \
245 return SafeCompare<NAME, typename UnderlyingType<L>::type, \
246 typename UnderlyingType<R>::type>(lhs, rhs); \
247 }
248
249 STRICT_COMPARISON_OP(IsLess, <);
250 STRICT_COMPARISON_OP(IsLessOrEqual, <=);
251 STRICT_COMPARISON_OP(IsGreater, >);
252 STRICT_COMPARISON_OP(IsGreaterOrEqual, >=);
253 STRICT_COMPARISON_OP(IsEqual, ==);
254 STRICT_COMPARISON_OP(IsNotEqual, !=);
255
256 #undef STRICT_COMPARISON_OP
257 };
258
259 using internal::strict_cast;
260 using internal::saturated_cast;
261 using internal::SafeUnsignedAbs;
262 using internal::StrictNumeric;
263 using internal::MakeStrictNum;
264 using internal::IsValueNegative;
265
266 // Explicitly make a shorter size_t alias for convenience.
267 using SizeT = StrictNumeric<size_t>;
61 268
62 } // namespace base 269 } // namespace base
63 } // namespace pdfium 270 } // namespace pdfium
64 271
65 #endif // PDFIUM_THIRD_PARTY_BASE_SAFE_CONVERSIONS_H_ 272 #endif // PDFIUM_THIRD_PARTY_BASE_NUMERICS_SAFE_CONVERSIONS_H_
66
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698