safe_conversions.h 15 KB

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