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