• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2014 The Chromium Authors
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_CONVERSIONS_H_
6 #define BASE_NUMERICS_SAFE_CONVERSIONS_H_
7 
8 #include <stddef.h>
9 
10 #include <cmath>
11 #include <limits>
12 #include <type_traits>
13 
14 #include "base/numerics/safe_conversions_impl.h"
15 
16 #if defined(__ARMEL__) && !defined(__native_client__)
17 #include "base/numerics/safe_conversions_arm_impl.h"
18 #define BASE_HAS_OPTIMIZED_SAFE_CONVERSIONS (1)
19 #else
20 #define BASE_HAS_OPTIMIZED_SAFE_CONVERSIONS (0)
21 #endif
22 
23 namespace base {
24 namespace internal {
25 
26 #if !BASE_HAS_OPTIMIZED_SAFE_CONVERSIONS
27 template <typename Dst, typename Src>
28 struct SaturateFastAsmOp {
29   static constexpr bool is_supported = false;
DoSaturateFastAsmOp30   static constexpr Dst Do(Src) {
31     // Force a compile failure if instantiated.
32     return CheckOnFailure::template HandleFailure<Dst>();
33   }
34 };
35 #endif  // BASE_HAS_OPTIMIZED_SAFE_CONVERSIONS
36 #undef BASE_HAS_OPTIMIZED_SAFE_CONVERSIONS
37 
38 // The following special case a few specific integer conversions where we can
39 // eke out better performance than range checking.
40 template <typename Dst, typename Src, typename Enable = void>
41 struct IsValueInRangeFastOp {
42   static constexpr bool is_supported = false;
DoIsValueInRangeFastOp43   static constexpr bool Do(Src value) {
44     // Force a compile failure if instantiated.
45     return CheckOnFailure::template HandleFailure<bool>();
46   }
47 };
48 
49 // Signed to signed range comparison.
50 template <typename Dst, typename Src>
51 struct IsValueInRangeFastOp<
52     Dst,
53     Src,
54     typename std::enable_if<
55         std::is_integral<Dst>::value && std::is_integral<Src>::value &&
56         std::is_signed<Dst>::value && std::is_signed<Src>::value &&
57         !IsTypeInRangeForNumericType<Dst, Src>::value>::type> {
58   static constexpr bool is_supported = true;
59 
60   static constexpr bool Do(Src value) {
61     // Just downcast to the smaller type, sign extend it back to the original
62     // type, and then see if it matches the original value.
63     return value == static_cast<Dst>(value);
64   }
65 };
66 
67 // Signed to unsigned range comparison.
68 template <typename Dst, typename Src>
69 struct IsValueInRangeFastOp<
70     Dst,
71     Src,
72     typename std::enable_if<
73         std::is_integral<Dst>::value && std::is_integral<Src>::value &&
74         !std::is_signed<Dst>::value && std::is_signed<Src>::value &&
75         !IsTypeInRangeForNumericType<Dst, Src>::value>::type> {
76   static constexpr bool is_supported = true;
77 
78   static constexpr bool Do(Src value) {
79     // We cast a signed as unsigned to overflow negative values to the top,
80     // then compare against whichever maximum is smaller, as our upper bound.
81     return as_unsigned(value) <= as_unsigned(CommonMax<Src, Dst>());
82   }
83 };
84 
85 // Convenience function that returns true if the supplied value is in range
86 // for the destination type.
87 template <typename Dst, typename Src>
88 constexpr bool IsValueInRangeForNumericType(Src value) {
89   using SrcType = typename internal::UnderlyingType<Src>::type;
90   return internal::IsValueInRangeFastOp<Dst, SrcType>::is_supported
91              ? internal::IsValueInRangeFastOp<Dst, SrcType>::Do(
92                    static_cast<SrcType>(value))
93              : internal::DstRangeRelationToSrcRange<Dst>(
94                    static_cast<SrcType>(value))
95                    .IsValid();
96 }
97 
98 // checked_cast<> is analogous to static_cast<> for numeric types,
99 // except that it CHECKs that the specified numeric conversion will not
100 // overflow or underflow. NaN source will always trigger a CHECK.
101 template <typename Dst,
102           class CheckHandler = internal::CheckOnFailure,
103           typename Src>
104 constexpr Dst checked_cast(Src value) {
105   // This throws a compile-time error on evaluating the constexpr if it can be
106   // determined at compile-time as failing, otherwise it will CHECK at runtime.
107   using SrcType = typename internal::UnderlyingType<Src>::type;
108   return BASE_NUMERICS_LIKELY((IsValueInRangeForNumericType<Dst>(value)))
109              ? static_cast<Dst>(static_cast<SrcType>(value))
110              : CheckHandler::template HandleFailure<Dst>();
111 }
112 
113 // Default boundaries for integral/float: max/infinity, lowest/-infinity, 0/NaN.
114 // You may provide your own limits (e.g. to saturated_cast) so long as you
115 // implement all of the static constexpr member functions in the class below.
116 template <typename T>
117 struct SaturationDefaultLimits : public std::numeric_limits<T> {
118   static constexpr T NaN() {
119     if constexpr (std::numeric_limits<T>::has_quiet_NaN) {
120       return std::numeric_limits<T>::quiet_NaN();
121     } else {
122       return T();
123     }
124   }
125   using std::numeric_limits<T>::max;
126   static constexpr T Overflow() {
127     if constexpr (std::numeric_limits<T>::has_infinity) {
128       return std::numeric_limits<T>::infinity();
129     } else {
130       return std::numeric_limits<T>::max();
131     }
132   }
133   using std::numeric_limits<T>::lowest;
134   static constexpr T Underflow() {
135     if constexpr (std::numeric_limits<T>::has_infinity) {
136       return std::numeric_limits<T>::infinity() * -1;
137     } else {
138       return std::numeric_limits<T>::lowest();
139     }
140   }
141 };
142 
143 template <typename Dst, template <typename> class S, typename Src>
144 constexpr Dst saturated_cast_impl(Src value, RangeCheck constraint) {
145   // For some reason clang generates much better code when the branch is
146   // structured exactly this way, rather than a sequence of checks.
147   return !constraint.IsOverflowFlagSet()
148              ? (!constraint.IsUnderflowFlagSet() ? static_cast<Dst>(value)
149                                                  : S<Dst>::Underflow())
150              // Skip this check for integral Src, which cannot be NaN.
151              : (std::is_integral<Src>::value || !constraint.IsUnderflowFlagSet()
152                     ? S<Dst>::Overflow()
153                     : S<Dst>::NaN());
154 }
155 
156 // We can reduce the number of conditions and get slightly better performance
157 // for normal signed and unsigned integer ranges. And in the specific case of
158 // Arm, we can use the optimized saturation instructions.
159 template <typename Dst, typename Src, typename Enable = void>
160 struct SaturateFastOp {
161   static constexpr bool is_supported = false;
162   static constexpr Dst Do(Src value) {
163     // Force a compile failure if instantiated.
164     return CheckOnFailure::template HandleFailure<Dst>();
165   }
166 };
167 
168 template <typename Dst, typename Src>
169 struct SaturateFastOp<
170     Dst,
171     Src,
172     typename std::enable_if<std::is_integral<Src>::value &&
173                             std::is_integral<Dst>::value &&
174                             SaturateFastAsmOp<Dst, Src>::is_supported>::type> {
175   static constexpr bool is_supported = true;
176   static constexpr Dst Do(Src value) {
177     return SaturateFastAsmOp<Dst, Src>::Do(value);
178   }
179 };
180 
181 template <typename Dst, typename Src>
182 struct SaturateFastOp<
183     Dst,
184     Src,
185     typename std::enable_if<std::is_integral<Src>::value &&
186                             std::is_integral<Dst>::value &&
187                             !SaturateFastAsmOp<Dst, Src>::is_supported>::type> {
188   static constexpr bool is_supported = true;
189   static constexpr Dst Do(Src value) {
190     // The exact order of the following is structured to hit the correct
191     // optimization heuristics across compilers. Do not change without
192     // checking the emitted code.
193     const Dst saturated = CommonMaxOrMin<Dst, Src>(
194         IsMaxInRangeForNumericType<Dst, Src>() ||
195         (!IsMinInRangeForNumericType<Dst, Src>() && IsValueNegative(value)));
196     return BASE_NUMERICS_LIKELY(IsValueInRangeForNumericType<Dst>(value))
197                ? static_cast<Dst>(value)
198                : saturated;
199   }
200 };
201 
202 // saturated_cast<> is analogous to static_cast<> for numeric types, except
203 // that the specified numeric conversion will saturate by default rather than
204 // overflow or underflow, and NaN assignment to an integral will return 0.
205 // All boundary condition behaviors can be overridden with a custom handler.
206 template <typename Dst,
207           template <typename> class SaturationHandler = SaturationDefaultLimits,
208           typename Src>
209 constexpr Dst saturated_cast(Src value) {
210   using SrcType = typename UnderlyingType<Src>::type;
211   return !IsConstantEvaluated() && SaturateFastOp<Dst, SrcType>::is_supported &&
212                  std::is_same<SaturationHandler<Dst>,
213                               SaturationDefaultLimits<Dst>>::value
214              ? SaturateFastOp<Dst, SrcType>::Do(static_cast<SrcType>(value))
215              : saturated_cast_impl<Dst, SaturationHandler, SrcType>(
216                    static_cast<SrcType>(value),
217                    DstRangeRelationToSrcRange<Dst, SaturationHandler, SrcType>(
218                        static_cast<SrcType>(value)));
219 }
220 
221 // strict_cast<> is analogous to static_cast<> for numeric types, except that
222 // it will cause a compile failure if the destination type is not large enough
223 // to contain any value in the source type. It performs no runtime checking.
224 template <typename Dst, typename Src>
225 constexpr Dst strict_cast(Src value) {
226   using SrcType = typename UnderlyingType<Src>::type;
227   static_assert(UnderlyingType<Src>::is_numeric, "Argument must be numeric.");
228   static_assert(std::is_arithmetic<Dst>::value, "Result must be numeric.");
229 
230   // If you got here from a compiler error, it's because you tried to assign
231   // from a source type to a destination type that has insufficient range.
232   // The solution may be to change the destination type you're assigning to,
233   // and use one large enough to represent the source.
234   // Alternatively, you may be better served with the checked_cast<> or
235   // saturated_cast<> template functions for your particular use case.
236   static_assert(StaticDstRangeRelationToSrcRange<Dst, SrcType>::value ==
237                     NUMERIC_RANGE_CONTAINED,
238                 "The source type is out of range for the destination type. "
239                 "Please see strict_cast<> comments for more information.");
240 
241   return static_cast<Dst>(static_cast<SrcType>(value));
242 }
243 
244 // Some wrappers to statically check that a type is in range.
245 template <typename Dst, typename Src, class Enable = void>
246 struct IsNumericRangeContained {
247   static constexpr bool value = false;
248 };
249 
250 template <typename Dst, typename Src>
251 struct IsNumericRangeContained<
252     Dst,
253     Src,
254     typename std::enable_if<ArithmeticOrUnderlyingEnum<Dst>::value &&
255                             ArithmeticOrUnderlyingEnum<Src>::value>::type> {
256   static constexpr bool value =
257       StaticDstRangeRelationToSrcRange<Dst, Src>::value ==
258       NUMERIC_RANGE_CONTAINED;
259 };
260 
261 // StrictNumeric implements compile time range checking between numeric types by
262 // wrapping assignment operations in a strict_cast. This class is intended to be
263 // used for function arguments and return types, to ensure the destination type
264 // can always contain the source type. This is essentially the same as enforcing
265 // -Wconversion in gcc and C4302 warnings on MSVC, but it can be applied
266 // incrementally at API boundaries, making it easier to convert code so that it
267 // compiles cleanly with truncation warnings enabled.
268 // This template should introduce no runtime overhead, but it also provides no
269 // runtime checking of any of the associated mathematical operations. Use
270 // CheckedNumeric for runtime range checks of the actual value being assigned.
271 template <typename T>
272 class StrictNumeric {
273  public:
274   using type = T;
275 
276   constexpr StrictNumeric() : value_(0) {}
277 
278   // Copy constructor.
279   template <typename Src>
280   constexpr StrictNumeric(const StrictNumeric<Src>& rhs)
281       : value_(strict_cast<T>(rhs.value_)) {}
282 
283   // Strictly speaking, this is not necessary, but declaring this allows class
284   // template argument deduction to be used so that it is possible to simply
285   // write `StrictNumeric(777)` instead of `StrictNumeric<int>(777)`.
286   // NOLINTNEXTLINE(google-explicit-constructor)
287   constexpr StrictNumeric(T value) : value_(value) {}
288 
289   // This is not an explicit constructor because we implicitly upgrade regular
290   // numerics to StrictNumerics to make them easier to use.
291   template <typename Src>
292   // NOLINTNEXTLINE(google-explicit-constructor)
293   constexpr StrictNumeric(Src value) : value_(strict_cast<T>(value)) {}
294 
295   // If you got here from a compiler error, it's because you tried to assign
296   // from a source type to a destination type that has insufficient range.
297   // The solution may be to change the destination type you're assigning to,
298   // and use one large enough to represent the source.
299   // If you're assigning from a CheckedNumeric<> class, you may be able to use
300   // the AssignIfValid() member function, specify a narrower destination type to
301   // the member value functions (e.g. val.template ValueOrDie<Dst>()), use one
302   // of the value helper functions (e.g. ValueOrDieForType<Dst>(val)).
303   // If you've encountered an _ambiguous overload_ you can use a static_cast<>
304   // to explicitly cast the result to the destination type.
305   // If none of that works, you may be better served with the checked_cast<> or
306   // saturated_cast<> template functions for your particular use case.
307   template <typename Dst,
308             typename std::enable_if<
309                 IsNumericRangeContained<Dst, T>::value>::type* = nullptr>
310   constexpr operator Dst() const {
311     return static_cast<typename ArithmeticOrUnderlyingEnum<Dst>::type>(value_);
312   }
313 
314  private:
315   const T value_;
316 };
317 
318 // Convenience wrapper returns a StrictNumeric from the provided arithmetic
319 // type.
320 template <typename T>
321 constexpr StrictNumeric<typename UnderlyingType<T>::type> MakeStrictNum(
322     const T value) {
323   return value;
324 }
325 
326 #define BASE_NUMERIC_COMPARISON_OPERATORS(CLASS, NAME, OP)              \
327   template <typename L, typename R,                                     \
328             typename std::enable_if<                                    \
329                 internal::Is##CLASS##Op<L, R>::value>::type* = nullptr> \
330   constexpr bool operator OP(const L lhs, const R rhs) {                \
331     return SafeCompare<NAME, typename UnderlyingType<L>::type,          \
332                        typename UnderlyingType<R>::type>(lhs, rhs);     \
333   }
334 
335 BASE_NUMERIC_COMPARISON_OPERATORS(Strict, IsLess, <)
336 BASE_NUMERIC_COMPARISON_OPERATORS(Strict, IsLessOrEqual, <=)
337 BASE_NUMERIC_COMPARISON_OPERATORS(Strict, IsGreater, >)
338 BASE_NUMERIC_COMPARISON_OPERATORS(Strict, IsGreaterOrEqual, >=)
339 BASE_NUMERIC_COMPARISON_OPERATORS(Strict, IsEqual, ==)
340 BASE_NUMERIC_COMPARISON_OPERATORS(Strict, IsNotEqual, !=)
341 
342 }  // namespace internal
343 
344 using internal::as_signed;
345 using internal::as_unsigned;
346 using internal::checked_cast;
347 using internal::IsTypeInRangeForNumericType;
348 using internal::IsValueInRangeForNumericType;
349 using internal::IsValueNegative;
350 using internal::MakeStrictNum;
351 using internal::SafeUnsignedAbs;
352 using internal::saturated_cast;
353 using internal::strict_cast;
354 using internal::StrictNumeric;
355 
356 // Explicitly make a shorter size_t alias for convenience.
357 using SizeT = StrictNumeric<size_t>;
358 
359 // floating -> integral conversions that saturate and thus can actually return
360 // an integral type.  In most cases, these should be preferred over the std::
361 // versions.
362 template <typename Dst = int,
363           typename Src,
364           typename = std::enable_if_t<std::is_integral<Dst>::value &&
365                                       std::is_floating_point<Src>::value>>
366 Dst ClampFloor(Src value) {
367   return saturated_cast<Dst>(std::floor(value));
368 }
369 template <typename Dst = int,
370           typename Src,
371           typename = std::enable_if_t<std::is_integral<Dst>::value &&
372                                       std::is_floating_point<Src>::value>>
373 Dst ClampCeil(Src value) {
374   return saturated_cast<Dst>(std::ceil(value));
375 }
376 template <typename Dst = int,
377           typename Src,
378           typename = std::enable_if_t<std::is_integral<Dst>::value &&
379                                       std::is_floating_point<Src>::value>>
380 Dst ClampRound(Src value) {
381   const Src rounded =
382       (value >= 0.0f) ? std::floor(value + 0.5f) : std::ceil(value - 0.5f);
383   return saturated_cast<Dst>(rounded);
384 }
385 
386 }  // namespace base
387 
388 #endif  // BASE_NUMERICS_SAFE_CONVERSIONS_H_
389