SignedSafeMath.sol 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. pragma solidity ^0.6.0;
  2. /**
  3. * @title SignedSafeMath
  4. * @dev Signed math operations with safety checks that revert on error.
  5. */
  6. library SignedSafeMath {
  7. int256 constant private INT256_MIN = -2**255;
  8. /**
  9. * @dev Multiplies two signed integers, reverts on overflow.
  10. */
  11. function mul(int256 a, int256 b) internal pure returns (int256) {
  12. // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
  13. // benefit is lost if 'b' is also tested.
  14. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
  15. if (a == 0) {
  16. return 0;
  17. }
  18. require(!(a == -1 && b == INT256_MIN), "SignedSafeMath: multiplication overflow");
  19. int256 c = a * b;
  20. require(c / a == b, "SignedSafeMath: multiplication overflow");
  21. return c;
  22. }
  23. /**
  24. * @dev Integer division of two signed integers truncating the quotient, reverts on division by zero.
  25. */
  26. function div(int256 a, int256 b) internal pure returns (int256) {
  27. require(b != 0, "SignedSafeMath: division by zero");
  28. require(!(b == -1 && a == INT256_MIN), "SignedSafeMath: division overflow");
  29. int256 c = a / b;
  30. return c;
  31. }
  32. /**
  33. * @dev Subtracts two signed integers, reverts on overflow.
  34. */
  35. function sub(int256 a, int256 b) internal pure returns (int256) {
  36. int256 c = a - b;
  37. require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow");
  38. return c;
  39. }
  40. /**
  41. * @dev Adds two signed integers, reverts on overflow.
  42. */
  43. function add(int256 a, int256 b) internal pure returns (int256) {
  44. int256 c = a + b;
  45. require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow");
  46. return c;
  47. }
  48. }