SignedSafeMath.sol 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. // SPDX-License-Identifier: MIT
  2. pragma solidity >=0.6.0 <0.8.0;
  3. /**
  4. * @title SignedSafeMath
  5. * @dev Signed math operations with safety checks that revert on error.
  6. */
  7. library SignedSafeMath {
  8. int256 constant private _INT256_MIN = -2**255;
  9. /**
  10. * @dev Returns the multiplication of two signed integers, reverting on
  11. * overflow.
  12. *
  13. * Counterpart to Solidity's `*` operator.
  14. *
  15. * Requirements:
  16. *
  17. * - Multiplication cannot overflow.
  18. */
  19. function mul(int256 a, int256 b) internal pure returns (int256) {
  20. // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
  21. // benefit is lost if 'b' is also tested.
  22. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
  23. if (a == 0) {
  24. return 0;
  25. }
  26. require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow");
  27. int256 c = a * b;
  28. require(c / a == b, "SignedSafeMath: multiplication overflow");
  29. return c;
  30. }
  31. /**
  32. * @dev Returns the integer division of two signed integers. Reverts on
  33. * division by zero. The result is rounded towards zero.
  34. *
  35. * Counterpart to Solidity's `/` operator. Note: this function uses a
  36. * `revert` opcode (which leaves remaining gas untouched) while Solidity
  37. * uses an invalid opcode to revert (consuming all remaining gas).
  38. *
  39. * Requirements:
  40. *
  41. * - The divisor cannot be zero.
  42. */
  43. function div(int256 a, int256 b) internal pure returns (int256) {
  44. require(b != 0, "SignedSafeMath: division by zero");
  45. require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow");
  46. int256 c = a / b;
  47. return c;
  48. }
  49. /**
  50. * @dev Returns the subtraction of two signed integers, reverting on
  51. * overflow.
  52. *
  53. * Counterpart to Solidity's `-` operator.
  54. *
  55. * Requirements:
  56. *
  57. * - Subtraction cannot overflow.
  58. */
  59. function sub(int256 a, int256 b) internal pure returns (int256) {
  60. int256 c = a - b;
  61. require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow");
  62. return c;
  63. }
  64. /**
  65. * @dev Returns the addition of two signed integers, reverting on
  66. * overflow.
  67. *
  68. * Counterpart to Solidity's `+` operator.
  69. *
  70. * Requirements:
  71. *
  72. * - Addition cannot overflow.
  73. */
  74. function add(int256 a, int256 b) internal pure returns (int256) {
  75. int256 c = a + b;
  76. require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow");
  77. return c;
  78. }
  79. }