xref: /aosp_15_r20/external/libchrome/base/numerics/safe_conversions.h (revision 635a864187cb8b6c713ff48b7e790a6b21769273)
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 #if !defined(__native_client__) && (defined(__ARMEL__) || defined(__arch64__))
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 const 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 const 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 const 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 const 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     return std::numeric_limits<T>::has_quiet_NaN
120                ? std::numeric_limits<T>::quiet_NaN()
121                : T();
122   }
123   using std::numeric_limits<T>::max;
124   static constexpr T Overflow() {
125     return std::numeric_limits<T>::has_infinity
126                ? std::numeric_limits<T>::infinity()
127                : std::numeric_limits<T>::max();
128   }
129   using std::numeric_limits<T>::lowest;
130   static constexpr T Underflow() {
131     return std::numeric_limits<T>::has_infinity
132                ? std::numeric_limits<T>::infinity() * -1
133                : std::numeric_limits<T>::lowest();
134   }
135 };
136 
137 template <typename Dst, template <typename> class S, typename Src>
138 constexpr Dst saturated_cast_impl(Src value, RangeCheck constraint) {
139   // For some reason clang generates much better code when the branch is
140   // structured exactly this way, rather than a sequence of checks.
141   return !constraint.IsOverflowFlagSet()
142              ? (!constraint.IsUnderflowFlagSet() ? static_cast<Dst>(value)
143                                                  : S<Dst>::Underflow())
144              // Skip this check for integral Src, which cannot be NaN.
145              : (std::is_integral<Src>::value || !constraint.IsUnderflowFlagSet()
146                     ? S<Dst>::Overflow()
147                     : S<Dst>::NaN());
148 }
149 
150 // We can reduce the number of conditions and get slightly better performance
151 // for normal signed and unsigned integer ranges. And in the specific case of
152 // Arm, we can use the optimized saturation instructions.
153 template <typename Dst, typename Src, typename Enable = void>
154 struct SaturateFastOp {
155   static const bool is_supported = false;
156   static constexpr Dst Do(Src value) {
157     // Force a compile failure if instantiated.
158     return CheckOnFailure::template HandleFailure<Dst>();
159   }
160 };
161 
162 template <typename Dst, typename Src>
163 struct SaturateFastOp<
164     Dst,
165     Src,
166     typename std::enable_if<std::is_integral<Src>::value &&
167                             std::is_integral<Dst>::value>::type> {
168   static const bool is_supported = true;
169   static Dst Do(Src value) {
170     if (SaturateFastAsmOp<Dst, Src>::is_supported)
171       return SaturateFastAsmOp<Dst, Src>::Do(value);
172 
173     // The exact order of the following is structured to hit the correct
174     // optimization heuristics across compilers. Do not change without
175     // checking the emitted code.
176     Dst saturated = CommonMaxOrMin<Dst, Src>(
177         IsMaxInRangeForNumericType<Dst, Src>() ||
178         (!IsMinInRangeForNumericType<Dst, Src>() && IsValueNegative(value)));
179     return BASE_NUMERICS_LIKELY(IsValueInRangeForNumericType<Dst>(value))
180                ? static_cast<Dst>(value)
181                : saturated;
182   }
183 };
184 
185 // saturated_cast<> is analogous to static_cast<> for numeric types, except
186 // that the specified numeric conversion will saturate by default rather than
187 // overflow or underflow, and NaN assignment to an integral will return 0.
188 // All boundary condition behaviors can be overriden with a custom handler.
189 template <typename Dst,
190           template <typename> class SaturationHandler = SaturationDefaultLimits,
191           typename Src>
192 constexpr Dst saturated_cast(Src value) {
193   using SrcType = typename UnderlyingType<Src>::type;
194   return !IsCompileTimeConstant(value) &&
195                  SaturateFastOp<Dst, SrcType>::is_supported &&
196                  std::is_same<SaturationHandler<Dst>,
197                               SaturationDefaultLimits<Dst>>::value
198              ? SaturateFastOp<Dst, SrcType>::Do(static_cast<SrcType>(value))
199              : saturated_cast_impl<Dst, SaturationHandler, SrcType>(
200                    static_cast<SrcType>(value),
201                    DstRangeRelationToSrcRange<Dst, SaturationHandler, SrcType>(
202                        static_cast<SrcType>(value)));
203 }
204 
205 // strict_cast<> is analogous to static_cast<> for numeric types, except that
206 // it will cause a compile failure if the destination type is not large enough
207 // to contain any value in the source type. It performs no runtime checking.
208 template <typename Dst, typename Src>
209 constexpr Dst strict_cast(Src value) {
210   using SrcType = typename UnderlyingType<Src>::type;
211   static_assert(UnderlyingType<Src>::is_numeric, "Argument must be numeric.");
212   static_assert(std::is_arithmetic<Dst>::value, "Result must be numeric.");
213 
214   // If you got here from a compiler error, it's because you tried to assign
215   // from a source type to a destination type that has insufficient range.
216   // The solution may be to change the destination type you're assigning to,
217   // and use one large enough to represent the source.
218   // Alternatively, you may be better served with the checked_cast<> or
219   // saturated_cast<> template functions for your particular use case.
220   static_assert(StaticDstRangeRelationToSrcRange<Dst, SrcType>::value ==
221                     NUMERIC_RANGE_CONTAINED,
222                 "The source type is out of range for the destination type. "
223                 "Please see strict_cast<> comments for more information.");
224 
225   return static_cast<Dst>(static_cast<SrcType>(value));
226 }
227 
228 // Some wrappers to statically check that a type is in range.
229 template <typename Dst, typename Src, class Enable = void>
230 struct IsNumericRangeContained {
231   static const bool value = false;
232 };
233 
234 template <typename Dst, typename Src>
235 struct IsNumericRangeContained<
236     Dst,
237     Src,
238     typename std::enable_if<ArithmeticOrUnderlyingEnum<Dst>::value &&
239                             ArithmeticOrUnderlyingEnum<Src>::value>::type> {
240   static const bool value = StaticDstRangeRelationToSrcRange<Dst, Src>::value ==
241                             NUMERIC_RANGE_CONTAINED;
242 };
243 
244 // StrictNumeric implements compile time range checking between numeric types by
245 // wrapping assignment operations in a strict_cast. This class is intended to be
246 // used for function arguments and return types, to ensure the destination type
247 // can always contain the source type. This is essentially the same as enforcing
248 // -Wconversion in gcc and C4302 warnings on MSVC, but it can be applied
249 // incrementally at API boundaries, making it easier to convert code so that it
250 // compiles cleanly with truncation warnings enabled.
251 // This template should introduce no runtime overhead, but it also provides no
252 // runtime checking of any of the associated mathematical operations. Use
253 // CheckedNumeric for runtime range checks of the actual value being assigned.
254 template <typename T>
255 class StrictNumeric {
256  public:
257   using type = T;
258 
259   constexpr StrictNumeric() : value_(0) {}
260 
261   // Copy constructor.
262   template <typename Src>
263   constexpr StrictNumeric(const StrictNumeric<Src>& rhs)
264       : value_(strict_cast<T>(rhs.value_)) {}
265 
266   // This is not an explicit constructor because we implicitly upgrade regular
267   // numerics to StrictNumerics to make them easier to use.
268   template <typename Src>
269   constexpr StrictNumeric(Src value)  // NOLINT(runtime/explicit)
270       : value_(strict_cast<T>(value)) {}
271 
272   // If you got here from a compiler error, it's because you tried to assign
273   // from a source type to a destination type that has insufficient range.
274   // The solution may be to change the destination type you're assigning to,
275   // and use one large enough to represent the source.
276   // If you're assigning from a CheckedNumeric<> class, you may be able to use
277   // the AssignIfValid() member function, specify a narrower destination type to
278   // the member value functions (e.g. val.template ValueOrDie<Dst>()), use one
279   // of the value helper functions (e.g. ValueOrDieForType<Dst>(val)).
280   // If you've encountered an _ambiguous overload_ you can use a static_cast<>
281   // to explicitly cast the result to the destination type.
282   // If none of that works, you may be better served with the checked_cast<> or
283   // saturated_cast<> template functions for your particular use case.
284   template <typename Dst,
285             typename std::enable_if<
286                 IsNumericRangeContained<Dst, T>::value>::type* = nullptr>
287   constexpr operator Dst() const {
288     return static_cast<typename ArithmeticOrUnderlyingEnum<Dst>::type>(value_);
289   }
290 
291  private:
292   const T value_;
293 };
294 
295 // Convience wrapper returns a StrictNumeric from the provided arithmetic type.
296 template <typename T>
297 constexpr StrictNumeric<typename UnderlyingType<T>::type> MakeStrictNum(
298     const T value) {
299   return value;
300 }
301 
302 // Overload the ostream output operator to make logging work nicely.
303 template <typename T>
304 std::ostream& operator<<(std::ostream& os, const StrictNumeric<T>& value) {
305   os << static_cast<T>(value);
306   return os;
307 }
308 
309 #define BASE_NUMERIC_COMPARISON_OPERATORS(CLASS, NAME, OP)              \
310   template <typename L, typename R,                                     \
311             typename std::enable_if<                                    \
312                 internal::Is##CLASS##Op<L, R>::value>::type* = nullptr> \
313   constexpr bool operator OP(const L lhs, const R rhs) {                \
314     return SafeCompare<NAME, typename UnderlyingType<L>::type,          \
315                        typename UnderlyingType<R>::type>(lhs, rhs);     \
316   }
317 
318 BASE_NUMERIC_COMPARISON_OPERATORS(Strict, IsLess, <);
319 BASE_NUMERIC_COMPARISON_OPERATORS(Strict, IsLessOrEqual, <=);
320 BASE_NUMERIC_COMPARISON_OPERATORS(Strict, IsGreater, >);
321 BASE_NUMERIC_COMPARISON_OPERATORS(Strict, IsGreaterOrEqual, >=);
322 BASE_NUMERIC_COMPARISON_OPERATORS(Strict, IsEqual, ==);
323 BASE_NUMERIC_COMPARISON_OPERATORS(Strict, IsNotEqual, !=);
324 
325 };  // namespace internal
326 
327 using internal::as_signed;
328 using internal::as_unsigned;
329 using internal::checked_cast;
330 using internal::strict_cast;
331 using internal::saturated_cast;
332 using internal::SafeUnsignedAbs;
333 using internal::StrictNumeric;
334 using internal::MakeStrictNum;
335 using internal::IsValueInRangeForNumericType;
336 using internal::IsTypeInRangeForNumericType;
337 using internal::IsValueNegative;
338 
339 // Explicitly make a shorter size_t alias for convenience.
340 using SizeT = StrictNumeric<size_t>;
341 
342 }  // namespace base
343 
344 #endif  // BASE_NUMERICS_SAFE_CONVERSIONS_H_
345