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