checked_math.h 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  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. template <typename Src>
  18. friend class CheckedNumeric;
  19. using type = T;
  20. constexpr CheckedNumeric() = default;
  21. // Copy constructor.
  22. template <typename Src>
  23. constexpr CheckedNumeric(const CheckedNumeric<Src>& rhs)
  24. : state_(rhs.state_.value(), rhs.IsValid()) {}
  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(UnderlyingType<Src>::is_numeric, "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. // Use an optimized code path for a known run-time variable.
  122. if (!IsConstantEvaluated() && std::is_signed<T>::value &&
  123. std::is_floating_point<T>::value) {
  124. return FastRuntimeNegate();
  125. }
  126. // The negation of two's complement int min is int min.
  127. const bool is_valid =
  128. IsValid() &&
  129. (!std::is_signed<T>::value || std::is_floating_point<T>::value ||
  130. NegateWrapper(state_.value()) != std::numeric_limits<T>::lowest());
  131. return CheckedNumeric<T>(NegateWrapper(state_.value()), is_valid);
  132. }
  133. constexpr CheckedNumeric operator~() const {
  134. return CheckedNumeric<decltype(InvertWrapper(T()))>(
  135. InvertWrapper(state_.value()), IsValid());
  136. }
  137. constexpr CheckedNumeric Abs() const {
  138. return !IsValueNegative(state_.value()) ? *this : -*this;
  139. }
  140. template <typename U>
  141. constexpr CheckedNumeric<typename MathWrapper<CheckedMaxOp, T, U>::type> Max(
  142. const U rhs) const {
  143. return CheckMax(*this, rhs);
  144. }
  145. template <typename U>
  146. constexpr CheckedNumeric<typename MathWrapper<CheckedMinOp, T, U>::type> Min(
  147. const U rhs) const {
  148. return CheckMin(*this, rhs);
  149. }
  150. // This function is available only for integral types. It returns an unsigned
  151. // integer of the same width as the source type, containing the absolute value
  152. // of the source, and properly handling signed min.
  153. constexpr CheckedNumeric<typename UnsignedOrFloatForSize<T>::type>
  154. UnsignedAbs() const {
  155. return CheckedNumeric<typename UnsignedOrFloatForSize<T>::type>(
  156. SafeUnsignedAbs(state_.value()), state_.is_valid());
  157. }
  158. constexpr CheckedNumeric& operator++() {
  159. *this += 1;
  160. return *this;
  161. }
  162. constexpr CheckedNumeric operator++(int) {
  163. CheckedNumeric value = *this;
  164. *this += 1;
  165. return value;
  166. }
  167. constexpr CheckedNumeric& operator--() {
  168. *this -= 1;
  169. return *this;
  170. }
  171. constexpr CheckedNumeric operator--(int) {
  172. // TODO(pkasting): Consider std::exchange() once it's constexpr in C++20.
  173. const CheckedNumeric value = *this;
  174. *this -= 1;
  175. return value;
  176. }
  177. // These perform the actual math operations on the CheckedNumerics.
  178. // Binary arithmetic operations.
  179. template <template <typename, typename, typename> class M,
  180. typename L,
  181. typename R>
  182. static constexpr CheckedNumeric MathOp(const L lhs, const R rhs) {
  183. using Math = typename MathWrapper<M, L, R>::math;
  184. T result = 0;
  185. const bool is_valid =
  186. Wrapper<L>::is_valid(lhs) && Wrapper<R>::is_valid(rhs) &&
  187. Math::Do(Wrapper<L>::value(lhs), Wrapper<R>::value(rhs), &result);
  188. return CheckedNumeric<T>(result, is_valid);
  189. }
  190. // Assignment arithmetic operations.
  191. template <template <typename, typename, typename> class M, typename R>
  192. constexpr CheckedNumeric& MathOp(const R rhs) {
  193. using Math = typename MathWrapper<M, T, R>::math;
  194. T result = 0; // Using T as the destination saves a range check.
  195. const bool is_valid =
  196. state_.is_valid() && Wrapper<R>::is_valid(rhs) &&
  197. Math::Do(state_.value(), Wrapper<R>::value(rhs), &result);
  198. *this = CheckedNumeric<T>(result, is_valid);
  199. return *this;
  200. }
  201. private:
  202. CheckedNumericState<T> state_;
  203. CheckedNumeric FastRuntimeNegate() const {
  204. T result;
  205. const bool success = CheckedSubOp<T, T>::Do(T(0), state_.value(), &result);
  206. return CheckedNumeric<T>(result, IsValid() && success);
  207. }
  208. template <typename Src>
  209. constexpr CheckedNumeric(Src value, bool is_valid)
  210. : state_(value, is_valid) {}
  211. // These wrappers allow us to handle state the same way for both
  212. // CheckedNumeric and POD arithmetic types.
  213. template <typename Src>
  214. struct Wrapper {
  215. static constexpr bool is_valid(Src) { return true; }
  216. static constexpr Src value(Src value) { return value; }
  217. };
  218. template <typename Src>
  219. struct Wrapper<CheckedNumeric<Src>> {
  220. static constexpr bool is_valid(const CheckedNumeric<Src> v) {
  221. return v.IsValid();
  222. }
  223. static constexpr Src value(const CheckedNumeric<Src> v) {
  224. return v.state_.value();
  225. }
  226. };
  227. template <typename Src>
  228. struct Wrapper<StrictNumeric<Src>> {
  229. static constexpr bool is_valid(const StrictNumeric<Src>) { return true; }
  230. static constexpr Src value(const StrictNumeric<Src> v) {
  231. return static_cast<Src>(v);
  232. }
  233. };
  234. };
  235. template <typename T>
  236. CheckedNumeric(T t) -> CheckedNumeric<T>;
  237. // Convenience functions to avoid the ugly template disambiguator syntax.
  238. template <typename Dst, typename Src>
  239. constexpr bool IsValidForType(const CheckedNumeric<Src> value) {
  240. return value.template IsValid<Dst>();
  241. }
  242. template <typename Dst, typename Src>
  243. constexpr StrictNumeric<Dst> ValueOrDieForType(
  244. const CheckedNumeric<Src> value) {
  245. return value.template ValueOrDie<Dst>();
  246. }
  247. template <typename Dst, typename Src, typename Default>
  248. constexpr StrictNumeric<Dst> ValueOrDefaultForType(
  249. const CheckedNumeric<Src> value,
  250. const Default default_value) {
  251. return value.template ValueOrDefault<Dst>(default_value);
  252. }
  253. // Convenience wrapper to return a new CheckedNumeric from the provided
  254. // arithmetic or CheckedNumericType.
  255. template <typename T>
  256. constexpr CheckedNumeric<typename UnderlyingType<T>::type> MakeCheckedNum(
  257. const T value) {
  258. return value;
  259. }
  260. // These implement the variadic wrapper for the math operations.
  261. template <template <typename, typename, typename> class M,
  262. typename L,
  263. typename R>
  264. constexpr CheckedNumeric<typename MathWrapper<M, L, R>::type> CheckMathOp(
  265. const L lhs,
  266. const R rhs) {
  267. using Math = typename MathWrapper<M, L, R>::math;
  268. return CheckedNumeric<typename Math::result_type>::template MathOp<M>(lhs,
  269. rhs);
  270. }
  271. // General purpose wrapper template for arithmetic operations.
  272. template <template <typename, typename, typename> class M,
  273. typename L,
  274. typename R,
  275. typename... Args>
  276. constexpr auto CheckMathOp(const L lhs, const R rhs, const Args... args) {
  277. return CheckMathOp<M>(CheckMathOp<M>(lhs, rhs), args...);
  278. }
  279. BASE_NUMERIC_ARITHMETIC_OPERATORS(Checked, Check, Add, +, +=)
  280. BASE_NUMERIC_ARITHMETIC_OPERATORS(Checked, Check, Sub, -, -=)
  281. BASE_NUMERIC_ARITHMETIC_OPERATORS(Checked, Check, Mul, *, *=)
  282. BASE_NUMERIC_ARITHMETIC_OPERATORS(Checked, Check, Div, /, /=)
  283. BASE_NUMERIC_ARITHMETIC_OPERATORS(Checked, Check, Mod, %, %=)
  284. BASE_NUMERIC_ARITHMETIC_OPERATORS(Checked, Check, Lsh, <<, <<=)
  285. BASE_NUMERIC_ARITHMETIC_OPERATORS(Checked, Check, Rsh, >>, >>=)
  286. BASE_NUMERIC_ARITHMETIC_OPERATORS(Checked, Check, And, &, &=)
  287. BASE_NUMERIC_ARITHMETIC_OPERATORS(Checked, Check, Or, |, |=)
  288. BASE_NUMERIC_ARITHMETIC_OPERATORS(Checked, Check, Xor, ^, ^=)
  289. BASE_NUMERIC_ARITHMETIC_VARIADIC(Checked, Check, Max)
  290. BASE_NUMERIC_ARITHMETIC_VARIADIC(Checked, Check, Min)
  291. // These are some extra StrictNumeric operators to support simple pointer
  292. // arithmetic with our result types. Since wrapping on a pointer is always
  293. // bad, we trigger the CHECK condition here.
  294. template <typename L, typename R>
  295. L* operator+(L* lhs, const StrictNumeric<R> rhs) {
  296. const uintptr_t result = CheckAdd(reinterpret_cast<uintptr_t>(lhs),
  297. CheckMul(sizeof(L), static_cast<R>(rhs)))
  298. .template ValueOrDie<uintptr_t>();
  299. return reinterpret_cast<L*>(result);
  300. }
  301. template <typename L, typename R>
  302. L* operator-(L* lhs, const StrictNumeric<R> rhs) {
  303. const uintptr_t result = CheckSub(reinterpret_cast<uintptr_t>(lhs),
  304. CheckMul(sizeof(L), static_cast<R>(rhs)))
  305. .template ValueOrDie<uintptr_t>();
  306. return reinterpret_cast<L*>(result);
  307. }
  308. } // namespace internal
  309. using internal::CheckAdd;
  310. using internal::CheckAnd;
  311. using internal::CheckDiv;
  312. using internal::CheckedNumeric;
  313. using internal::CheckLsh;
  314. using internal::CheckMax;
  315. using internal::CheckMin;
  316. using internal::CheckMod;
  317. using internal::CheckMul;
  318. using internal::CheckOr;
  319. using internal::CheckRsh;
  320. using internal::CheckSub;
  321. using internal::CheckXor;
  322. using internal::IsValidForType;
  323. using internal::MakeCheckedNum;
  324. using internal::ValueOrDefaultForType;
  325. using internal::ValueOrDieForType;
  326. } // namespace base
  327. #endif // BASE_NUMERICS_CHECKED_MATH_H_