Bitcoin ABC  0.26.3
P2P Digital Currency
intmath.h
Go to the documentation of this file.
1 // Copyright (c) 2021 The Bitcoin developers
2 // Distributed under the MIT software license, see the accompanying
3 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
4 #ifndef BITCOIN_SCRIPT_INTMATH_H
5 #define BITCOIN_SCRIPT_INTMATH_H
6 
7 #include <cstdlib>
8 #include <limits>
9 
15 static bool AddInt63OverflowEmulated(int64_t a, int64_t b, int64_t &result) {
16  if (a > 0 && b > std::numeric_limits<int64_t>::max() - a) {
17  // integer overflow
18  return true;
19  }
20  if (a < 0 && b <= std::numeric_limits<int64_t>::min() - a) {
21  // integer underflow
22  return true;
23  }
24  result = a + b;
25  return result == std::numeric_limits<int64_t>::min();
26 }
27 
34 static bool AddInt63Overflow(int64_t a, int64_t b, int64_t &result) {
35 #if HAVE_DECL___BUILTIN_SADDLL_OVERFLOW
36  if (__builtin_saddll_overflow(a, b, (long long int *)&result)) {
37  return true;
38  }
39  return result == std::numeric_limits<int64_t>::min();
40 #else
41  return AddInt63OverflowEmulated(a, b, result);
42 #endif
43 }
44 
50 static bool SubInt63OverflowEmulated(int64_t a, int64_t b, int64_t &result) {
51  if (a < 0 && b > std::numeric_limits<int64_t>::max() + a) {
52  // integer overflow
53  return true;
54  }
55  if (a > 0 && b <= std::numeric_limits<int64_t>::min() + a) {
56  // integer underflow
57  return true;
58  }
59  result = a - b;
60  return result == std::numeric_limits<int64_t>::min();
61 }
62 
69 static bool SubInt63Overflow(int64_t a, int64_t b, int64_t &result) {
70 #if HAVE_DECL___BUILTIN_SSUBLL_OVERFLOW
71  if (__builtin_ssubll_overflow(a, b, (long long int *)&result)) {
72  return true;
73  }
74  return result == std::numeric_limits<int64_t>::min();
75 #else
76  return SubInt63OverflowEmulated(a, b, result);
77 #endif
78 }
79 
80 #endif // BITCOIN_SCRIPT_INTMATH_H
static bool AddInt63Overflow(int64_t a, int64_t b, int64_t &result)
Computes a + b and stores it in result.
Definition: intmath.h:34
static bool AddInt63OverflowEmulated(int64_t a, int64_t b, int64_t &result)
Computes a + b and stores it in result.
Definition: intmath.h:15
static bool SubInt63Overflow(int64_t a, int64_t b, int64_t &result)
Computes a - b and stores it in result.
Definition: intmath.h:69
static bool SubInt63OverflowEmulated(int64_t a, int64_t b, int64_t &result)
Computes a - b and stores it in result.
Definition: intmath.h:50