safe_conversions.h 15 KB

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