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