SignedSafeMath.sol 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. // SPDX-License-Identifier: MIT
  2. pragma solidity ^0.6.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 Multiplies two signed integers, reverts on overflow.
  11. */
  12. function mul(int256 a, int256 b) internal pure returns (int256) {
  13. // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
  14. // benefit is lost if 'b' is also tested.
  15. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
  16. if (a == 0) {
  17. return 0;
  18. }
  19. require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow");
  20. int256 c = a * b;
  21. require(c / a == b, "SignedSafeMath: multiplication overflow");
  22. return c;
  23. }
  24. /**
  25. * @dev Integer division of two signed integers truncating the quotient, reverts on division by zero.
  26. */
  27. function div(int256 a, int256 b) internal pure returns (int256) {
  28. require(b != 0, "SignedSafeMath: division by zero");
  29. require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow");
  30. int256 c = a / b;
  31. return c;
  32. }
  33. /**
  34. * @dev Subtracts two signed integers, reverts on overflow.
  35. */
  36. function sub(int256 a, int256 b) internal pure returns (int256) {
  37. int256 c = a - b;
  38. require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow");
  39. return c;
  40. }
  41. /**
  42. * @dev Adds two signed integers, reverts on overflow.
  43. */
  44. function add(int256 a, int256 b) internal pure returns (int256) {
  45. int256 c = a + b;
  46. require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow");
  47. return c;
  48. }
  49. }