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 <type_traits>
12 
13 #include "base/logging.h"
14 #include "base/numerics/safe_conversions_impl.h"
15 
16 namespace base {
17 
18 // Convenience function that returns true if the supplied value is in range
19 // for the destination type.
20 template <typename Dst, typename Src>
IsValueInRangeForNumericType(Src value)21 inline bool IsValueInRangeForNumericType(Src value) {
22   return internal::DstRangeRelationToSrcRange<Dst>(value) ==
23          internal::RANGE_VALID;
24 }
25 
26 // Convenience function for determining if a numeric value is negative without
27 // throwing compiler warnings on: unsigned(value) < 0.
28 template <typename T>
29 typename std::enable_if<std::numeric_limits<T>::is_signed, bool>::type
IsValueNegative(T value)30 IsValueNegative(T value) {
31   static_assert(std::numeric_limits<T>::is_specialized,
32                 "Argument must be numeric.");
33   return value < 0;
34 }
35 
36 template <typename T>
37 typename std::enable_if<!std::numeric_limits<T>::is_signed, bool>::type
IsValueNegative(T)38     IsValueNegative(T) {
39   static_assert(std::numeric_limits<T>::is_specialized,
40                 "Argument must be numeric.");
41   return false;
42 }
43 
44 // checked_cast<> is analogous to static_cast<> for numeric types,
45 // except that it CHECKs that the specified numeric conversion will not
46 // overflow or underflow. NaN source will always trigger a CHECK.
47 template <typename Dst, typename Src>
checked_cast(Src value)48 inline Dst checked_cast(Src value) {
49   CHECK(IsValueInRangeForNumericType<Dst>(value));
50   return static_cast<Dst>(value);
51 }
52 
53 // HandleNaN will cause this class to CHECK(false).
54 struct SaturatedCastNaNBehaviorCheck {
55   template <typename T>
HandleNaNSaturatedCastNaNBehaviorCheck56   static T HandleNaN() {
57     CHECK(false);
58     return T();
59   }
60 };
61 
62 // HandleNaN will return 0 in this case.
63 struct SaturatedCastNaNBehaviorReturnZero {
64   template <typename T>
HandleNaNSaturatedCastNaNBehaviorReturnZero65   static T HandleNaN() {
66     return T();
67   }
68 };
69 
70 // saturated_cast<> is analogous to static_cast<> for numeric types, except
71 // that the specified numeric conversion will saturate rather than overflow or
72 // underflow. NaN assignment to an integral will defer the behavior to a
73 // specified class. By default, it will return 0.
74 template <typename Dst,
75           class NaNHandler = SaturatedCastNaNBehaviorReturnZero,
76           typename Src>
saturated_cast(Src value)77 inline Dst saturated_cast(Src value) {
78   // Optimization for floating point values, which already saturate.
79   if (std::numeric_limits<Dst>::is_iec559)
80     return static_cast<Dst>(value);
81 
82   switch (internal::DstRangeRelationToSrcRange<Dst>(value)) {
83     case internal::RANGE_VALID:
84       return static_cast<Dst>(value);
85 
86     case internal::RANGE_UNDERFLOW:
87       return std::numeric_limits<Dst>::min();
88 
89     case internal::RANGE_OVERFLOW:
90       return std::numeric_limits<Dst>::max();
91 
92     // Should fail only on attempting to assign NaN to a saturated integer.
93     case internal::RANGE_INVALID:
94       return NaNHandler::template HandleNaN<Dst>();
95   }
96 
97   NOTREACHED();
98   return static_cast<Dst>(value);
99 }
100 
101 // strict_cast<> is analogous to static_cast<> for numeric types, except that
102 // it will cause a compile failure if the destination type is not large enough
103 // to contain any value in the source type. It performs no runtime checking.
104 template <typename Dst, typename Src>
strict_cast(Src value)105 inline Dst strict_cast(Src value) {
106   static_assert(std::numeric_limits<Src>::is_specialized,
107                 "Argument must be numeric.");
108   static_assert(std::numeric_limits<Dst>::is_specialized,
109                 "Result must be numeric.");
110   static_assert((internal::StaticDstRangeRelationToSrcRange<Dst, Src>::value ==
111                  internal::NUMERIC_RANGE_CONTAINED),
112                 "The numeric conversion is out of range for this type. You "
113                 "should probably use one of the following conversion "
114                 "mechanisms on the value you want to pass:\n"
115                 "- base::checked_cast\n"
116                 "- base::saturated_cast\n"
117                 "- base::CheckedNumeric");
118 
119   return static_cast<Dst>(value);
120 }
121 
122 // StrictNumeric implements compile time range checking between numeric types by
123 // wrapping assignment operations in a strict_cast. This class is intended to be
124 // used for function arguments and return types, to ensure the destination type
125 // can always contain the source type. This is essentially the same as enforcing
126 // -Wconversion in gcc and C4302 warnings on MSVC, but it can be applied
127 // incrementally at API boundaries, making it easier to convert code so that it
128 // compiles cleanly with truncation warnings enabled.
129 // This template should introduce no runtime overhead, but it also provides no
130 // runtime checking of any of the associated mathematical operations. Use
131 // CheckedNumeric for runtime range checks of tha actual value being assigned.
132 template <typename T>
133 class StrictNumeric {
134  public:
135   typedef T type;
136 
StrictNumeric()137   StrictNumeric() : value_(0) {}
138 
139   // Copy constructor.
140   template <typename Src>
StrictNumeric(const StrictNumeric<Src> & rhs)141   StrictNumeric(const StrictNumeric<Src>& rhs)
142       : value_(strict_cast<T>(rhs.value_)) {}
143 
144   // This is not an explicit constructor because we implicitly upgrade regular
145   // numerics to StrictNumerics to make them easier to use.
146   template <typename Src>
StrictNumeric(Src value)147   StrictNumeric(Src value)
148       : value_(strict_cast<T>(value)) {}
149 
150   // The numeric cast operator basically handles all the magic.
151   template <typename Dst>
Dst()152   operator Dst() const {
153     return strict_cast<Dst>(value_);
154   }
155 
156  private:
157   T value_;
158 };
159 
160 // Explicitly make a shorter size_t typedef for convenience.
161 typedef StrictNumeric<size_t> SizeT;
162 
163 }  // namespace base
164 
165 #endif  // BASE_NUMERICS_SAFE_CONVERSIONS_H_
166