checked_math.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  1. // Copyright 2017 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_CHECKED_MATH_H_
  5. #define BASE_NUMERICS_CHECKED_MATH_H_
  6. #include <stddef.h>
  7. #include <limits>
  8. #include <type_traits>
  9. #include "base/numerics/checked_math_impl.h"
  10. namespace base {
  11. namespace internal {
  12. template <typename T>
  13. class CheckedNumeric {
  14. static_assert(std::is_arithmetic<T>::value,
  15. "CheckedNumeric<T>: T must be a numeric type.");
  16. public:
  17. using type = T;
  18. constexpr CheckedNumeric() = default;
  19. // Copy constructor.
  20. template <typename Src>
  21. constexpr CheckedNumeric(const CheckedNumeric<Src>& rhs)
  22. : state_(rhs.state_.value(), rhs.IsValid()) {}
  23. template <typename Src>
  24. friend class CheckedNumeric;
  25. // This is not an explicit constructor because we implicitly upgrade regular
  26. // numerics to CheckedNumerics to make them easier to use.
  27. template <typename Src>
  28. constexpr CheckedNumeric(Src value) // NOLINT(runtime/explicit)
  29. : state_(value) {
  30. static_assert(std::is_arithmetic<Src>::value, "Argument must be numeric.");
  31. }
  32. // This is not an explicit constructor because we want a seamless conversion
  33. // from StrictNumeric types.
  34. template <typename Src>
  35. constexpr CheckedNumeric(
  36. StrictNumeric<Src> value) // NOLINT(runtime/explicit)
  37. : state_(static_cast<Src>(value)) {}
  38. // IsValid() - The public API to test if a CheckedNumeric is currently valid.
  39. // A range checked destination type can be supplied using the Dst template
  40. // parameter.
  41. template <typename Dst = T>
  42. constexpr bool IsValid() const {
  43. return state_.is_valid() &&
  44. IsValueInRangeForNumericType<Dst>(state_.value());
  45. }
  46. // AssignIfValid(Dst) - Assigns the underlying value if it is currently valid
  47. // and is within the range supported by the destination type. Returns true if
  48. // successful and false otherwise.
  49. template <typename Dst>
  50. #if defined(__clang__) || defined(__GNUC__)
  51. __attribute__((warn_unused_result))
  52. #elif defined(_MSC_VER)
  53. _Check_return_
  54. #endif
  55. constexpr bool
  56. AssignIfValid(Dst* result) const {
  57. return BASE_NUMERICS_LIKELY(IsValid<Dst>())
  58. ? ((*result = static_cast<Dst>(state_.value())), true)
  59. : false;
  60. }
  61. // ValueOrDie() - The primary accessor for the underlying value. If the
  62. // current state is not valid it will CHECK and crash.
  63. // A range checked destination type can be supplied using the Dst template
  64. // parameter, which will trigger a CHECK if the value is not in bounds for
  65. // the destination.
  66. // The CHECK behavior can be overridden by supplying a handler as a
  67. // template parameter, for test code, etc. However, the handler cannot access
  68. // the underlying value, and it is not available through other means.
  69. template <typename Dst = T, class CheckHandler = CheckOnFailure>
  70. constexpr StrictNumeric<Dst> ValueOrDie() const {
  71. return BASE_NUMERICS_LIKELY(IsValid<Dst>())
  72. ? static_cast<Dst>(state_.value())
  73. : CheckHandler::template HandleFailure<Dst>();
  74. }
  75. // ValueOrDefault(T default_value) - A convenience method that returns the
  76. // current value if the state is valid, and the supplied default_value for
  77. // any other state.
  78. // A range checked destination type can be supplied using the Dst template
  79. // parameter. WARNING: This function may fail to compile or CHECK at runtime
  80. // if the supplied default_value is not within range of the destination type.
  81. template <typename Dst = T, typename Src>
  82. constexpr StrictNumeric<Dst> ValueOrDefault(const Src default_value) const {
  83. return BASE_NUMERICS_LIKELY(IsValid<Dst>())
  84. ? static_cast<Dst>(state_.value())
  85. : checked_cast<Dst>(default_value);
  86. }
  87. // Returns a checked numeric of the specified type, cast from the current
  88. // CheckedNumeric. If the current state is invalid or the destination cannot
  89. // represent the result then the returned CheckedNumeric will be invalid.
  90. template <typename Dst>
  91. constexpr CheckedNumeric<typename UnderlyingType<Dst>::type> Cast() const {
  92. return *this;
  93. }
  94. // This friend method is available solely for providing more detailed logging
  95. // in the tests. Do not implement it in production code, because the
  96. // underlying values may change at any time.
  97. template <typename U>
  98. friend U GetNumericValueForTest(const CheckedNumeric<U>& src);
  99. // Prototypes for the supported arithmetic operator overloads.
  100. template <typename Src>
  101. constexpr CheckedNumeric& operator+=(const Src rhs);
  102. template <typename Src>
  103. constexpr CheckedNumeric& operator-=(const Src rhs);
  104. template <typename Src>
  105. constexpr CheckedNumeric& operator*=(const Src rhs);
  106. template <typename Src>
  107. constexpr CheckedNumeric& operator/=(const Src rhs);
  108. template <typename Src>
  109. constexpr CheckedNumeric& operator%=(const Src rhs);
  110. template <typename Src>
  111. constexpr CheckedNumeric& operator<<=(const Src rhs);
  112. template <typename Src>
  113. constexpr CheckedNumeric& operator>>=(const Src rhs);
  114. template <typename Src>
  115. constexpr CheckedNumeric& operator&=(const Src rhs);
  116. template <typename Src>
  117. constexpr CheckedNumeric& operator|=(const Src rhs);
  118. template <typename Src>
  119. constexpr CheckedNumeric& operator^=(const Src rhs);
  120. constexpr CheckedNumeric operator-() const {
  121. // The negation of two's complement int min is int min, so we simply
  122. // check for that in the constexpr case.
  123. // We use an optimized code path for a known run-time variable.
  124. return MustTreatAsConstexpr(state_.value()) || !std::is_signed<T>::value ||
  125. std::is_floating_point<T>::value
  126. ? CheckedNumeric<T>(
  127. NegateWrapper(state_.value()),
  128. IsValid() && (!std::is_signed<T>::value ||
  129. std::is_floating_point<T>::value ||
  130. NegateWrapper(state_.value()) !=
  131. std::numeric_limits<T>::lowest()))
  132. : FastRuntimeNegate();
  133. }
  134. constexpr CheckedNumeric operator~() const {
  135. return CheckedNumeric<decltype(InvertWrapper(T()))>(
  136. InvertWrapper(state_.value()), IsValid());
  137. }
  138. constexpr CheckedNumeric Abs() const {
  139. return !IsValueNegative(state_.value()) ? *this : -*this;
  140. }
  141. template <typename U>
  142. constexpr CheckedNumeric<typename MathWrapper<CheckedMaxOp, T, U>::type> Max(
  143. const U rhs) const {
  144. using R = typename UnderlyingType<U>::type;
  145. using result_type = typename MathWrapper<CheckedMaxOp, T, U>::type;
  146. // TODO(jschuh): This can be converted to the MathOp version and remain
  147. // constexpr once we have C++14 support.
  148. return CheckedNumeric<result_type>(
  149. static_cast<result_type>(
  150. IsGreater<T, R>::Test(state_.value(), Wrapper<U>::value(rhs))
  151. ? state_.value()
  152. : Wrapper<U>::value(rhs)),
  153. state_.is_valid() && Wrapper<U>::is_valid(rhs));
  154. }
  155. template <typename U>
  156. constexpr CheckedNumeric<typename MathWrapper<CheckedMinOp, T, U>::type> Min(
  157. const U rhs) const {
  158. using R = typename UnderlyingType<U>::type;
  159. using result_type = typename MathWrapper<CheckedMinOp, T, U>::type;
  160. // TODO(jschuh): This can be converted to the MathOp version and remain
  161. // constexpr once we have C++14 support.
  162. return CheckedNumeric<result_type>(
  163. static_cast<result_type>(
  164. IsLess<T, R>::Test(state_.value(), Wrapper<U>::value(rhs))
  165. ? state_.value()
  166. : Wrapper<U>::value(rhs)),
  167. state_.is_valid() && Wrapper<U>::is_valid(rhs));
  168. }
  169. // This function is available only for integral types. It returns an unsigned
  170. // integer of the same width as the source type, containing the absolute value
  171. // of the source, and properly handling signed min.
  172. constexpr CheckedNumeric<typename UnsignedOrFloatForSize<T>::type>
  173. UnsignedAbs() const {
  174. return CheckedNumeric<typename UnsignedOrFloatForSize<T>::type>(
  175. SafeUnsignedAbs(state_.value()), state_.is_valid());
  176. }
  177. constexpr CheckedNumeric& operator++() {
  178. *this += 1;
  179. return *this;
  180. }
  181. constexpr CheckedNumeric operator++(int) {
  182. CheckedNumeric value = *this;
  183. *this += 1;
  184. return value;
  185. }
  186. constexpr CheckedNumeric& operator--() {
  187. *this -= 1;
  188. return *this;
  189. }
  190. constexpr CheckedNumeric operator--(int) {
  191. CheckedNumeric value = *this;
  192. *this -= 1;
  193. return value;
  194. }
  195. // These perform the actual math operations on the CheckedNumerics.
  196. // Binary arithmetic operations.
  197. template <template <typename, typename, typename> class M,
  198. typename L,
  199. typename R>
  200. static constexpr CheckedNumeric MathOp(const L lhs, const R rhs) {
  201. using Math = typename MathWrapper<M, L, R>::math;
  202. T result = 0;
  203. bool is_valid =
  204. Wrapper<L>::is_valid(lhs) && Wrapper<R>::is_valid(rhs) &&
  205. Math::Do(Wrapper<L>::value(lhs), Wrapper<R>::value(rhs), &result);
  206. return CheckedNumeric<T>(result, is_valid);
  207. }
  208. // Assignment arithmetic operations.
  209. template <template <typename, typename, typename> class M, typename R>
  210. constexpr CheckedNumeric& MathOp(const R rhs) {
  211. using Math = typename MathWrapper<M, T, R>::math;
  212. T result = 0; // Using T as the destination saves a range check.
  213. bool is_valid = state_.is_valid() && Wrapper<R>::is_valid(rhs) &&
  214. Math::Do(state_.value(), Wrapper<R>::value(rhs), &result);
  215. *this = CheckedNumeric<T>(result, is_valid);
  216. return *this;
  217. }
  218. private:
  219. CheckedNumericState<T> state_;
  220. CheckedNumeric FastRuntimeNegate() const {
  221. T result;
  222. bool success = CheckedSubOp<T, T>::Do(T(0), state_.value(), &result);
  223. return CheckedNumeric<T>(result, IsValid() && success);
  224. }
  225. template <typename Src>
  226. constexpr CheckedNumeric(Src value, bool is_valid)
  227. : state_(value, is_valid) {}
  228. // These wrappers allow us to handle state the same way for both
  229. // CheckedNumeric and POD arithmetic types.
  230. template <typename Src>
  231. struct Wrapper {
  232. static constexpr bool is_valid(Src) { return true; }
  233. static constexpr Src value(Src value) { return value; }
  234. };
  235. template <typename Src>
  236. struct Wrapper<CheckedNumeric<Src>> {
  237. static constexpr bool is_valid(const CheckedNumeric<Src> v) {
  238. return v.IsValid();
  239. }
  240. static constexpr Src value(const CheckedNumeric<Src> v) {
  241. return v.state_.value();
  242. }
  243. };
  244. template <typename Src>
  245. struct Wrapper<StrictNumeric<Src>> {
  246. static constexpr bool is_valid(const StrictNumeric<Src>) { return true; }
  247. static constexpr Src value(const StrictNumeric<Src> v) {
  248. return static_cast<Src>(v);
  249. }
  250. };
  251. };
  252. // Convenience functions to avoid the ugly template disambiguator syntax.
  253. template <typename Dst, typename Src>
  254. constexpr bool IsValidForType(const CheckedNumeric<Src> value) {
  255. return value.template IsValid<Dst>();
  256. }
  257. template <typename Dst, typename Src>
  258. constexpr StrictNumeric<Dst> ValueOrDieForType(
  259. const CheckedNumeric<Src> value) {
  260. return value.template ValueOrDie<Dst>();
  261. }
  262. template <typename Dst, typename Src, typename Default>
  263. constexpr StrictNumeric<Dst> ValueOrDefaultForType(
  264. const CheckedNumeric<Src> value,
  265. const Default default_value) {
  266. return value.template ValueOrDefault<Dst>(default_value);
  267. }
  268. // Convience wrapper to return a new CheckedNumeric from the provided arithmetic
  269. // or CheckedNumericType.
  270. template <typename T>
  271. constexpr CheckedNumeric<typename UnderlyingType<T>::type> MakeCheckedNum(
  272. const T value) {
  273. return value;
  274. }
  275. // These implement the variadic wrapper for the math operations.
  276. template <template <typename, typename, typename> class M,
  277. typename L,
  278. typename R>
  279. constexpr CheckedNumeric<typename MathWrapper<M, L, R>::type> CheckMathOp(
  280. const L lhs,
  281. const R rhs) {
  282. using Math = typename MathWrapper<M, L, R>::math;
  283. return CheckedNumeric<typename Math::result_type>::template MathOp<M>(lhs,
  284. rhs);
  285. }
  286. // General purpose wrapper template for arithmetic operations.
  287. template <template <typename, typename, typename> class M,
  288. typename L,
  289. typename R,
  290. typename... Args>
  291. constexpr CheckedNumeric<typename ResultType<M, L, R, Args...>::type>
  292. CheckMathOp(const L lhs, const R rhs, const Args... args) {
  293. return CheckMathOp<M>(CheckMathOp<M>(lhs, rhs), args...);
  294. }
  295. BASE_NUMERIC_ARITHMETIC_OPERATORS(Checked, Check, Add, +, +=)
  296. BASE_NUMERIC_ARITHMETIC_OPERATORS(Checked, Check, Sub, -, -=)
  297. BASE_NUMERIC_ARITHMETIC_OPERATORS(Checked, Check, Mul, *, *=)
  298. BASE_NUMERIC_ARITHMETIC_OPERATORS(Checked, Check, Div, /, /=)
  299. BASE_NUMERIC_ARITHMETIC_OPERATORS(Checked, Check, Mod, %, %=)
  300. BASE_NUMERIC_ARITHMETIC_OPERATORS(Checked, Check, Lsh, <<, <<=)
  301. BASE_NUMERIC_ARITHMETIC_OPERATORS(Checked, Check, Rsh, >>, >>=)
  302. BASE_NUMERIC_ARITHMETIC_OPERATORS(Checked, Check, And, &, &=)
  303. BASE_NUMERIC_ARITHMETIC_OPERATORS(Checked, Check, Or, |, |=)
  304. BASE_NUMERIC_ARITHMETIC_OPERATORS(Checked, Check, Xor, ^, ^=)
  305. BASE_NUMERIC_ARITHMETIC_VARIADIC(Checked, Check, Max)
  306. BASE_NUMERIC_ARITHMETIC_VARIADIC(Checked, Check, Min)
  307. // These are some extra StrictNumeric operators to support simple pointer
  308. // arithmetic with our result types. Since wrapping on a pointer is always
  309. // bad, we trigger the CHECK condition here.
  310. template <typename L, typename R>
  311. L* operator+(L* lhs, const StrictNumeric<R> rhs) {
  312. uintptr_t result = CheckAdd(reinterpret_cast<uintptr_t>(lhs),
  313. CheckMul(sizeof(L), static_cast<R>(rhs)))
  314. .template ValueOrDie<uintptr_t>();
  315. return reinterpret_cast<L*>(result);
  316. }
  317. template <typename L, typename R>
  318. L* operator-(L* lhs, const StrictNumeric<R> rhs) {
  319. uintptr_t result = CheckSub(reinterpret_cast<uintptr_t>(lhs),
  320. CheckMul(sizeof(L), static_cast<R>(rhs)))
  321. .template ValueOrDie<uintptr_t>();
  322. return reinterpret_cast<L*>(result);
  323. }
  324. } // namespace internal
  325. using internal::CheckedNumeric;
  326. using internal::IsValidForType;
  327. using internal::ValueOrDieForType;
  328. using internal::ValueOrDefaultForType;
  329. using internal::MakeCheckedNum;
  330. using internal::CheckMax;
  331. using internal::CheckMin;
  332. using internal::CheckAdd;
  333. using internal::CheckSub;
  334. using internal::CheckMul;
  335. using internal::CheckDiv;
  336. using internal::CheckMod;
  337. using internal::CheckLsh;
  338. using internal::CheckRsh;
  339. using internal::CheckAnd;
  340. using internal::CheckOr;
  341. using internal::CheckXor;
  342. } // namespace base
  343. #endif // BASE_NUMERICS_CHECKED_MATH_H_