SafeMath.sol 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. pragma solidity ^0.5.7;
  2. /**
  3. * @title SafeMath
  4. * @dev Unsigned math operations with safety checks that revert on error.
  5. */
  6. library SafeMath {
  7. /**
  8. * @dev Multiplies two unsigned integers, reverts on overflow.
  9. */
  10. function mul(uint256 a, uint256 b) internal pure returns (uint256) {
  11. // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
  12. // benefit is lost if 'b' is also tested.
  13. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
  14. if (a == 0) {
  15. return 0;
  16. }
  17. uint256 c = a * b;
  18. require(c / a == b);
  19. return c;
  20. }
  21. /**
  22. * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero.
  23. */
  24. function div(uint256 a, uint256 b) internal pure returns (uint256) {
  25. // Solidity only automatically asserts when dividing by 0
  26. require(b > 0);
  27. uint256 c = a / b;
  28. // assert(a == b * c + a % b); // There is no case in which this doesn't hold
  29. return c;
  30. }
  31. /**
  32. * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend).
  33. */
  34. function sub(uint256 a, uint256 b) internal pure returns (uint256) {
  35. require(b <= a);
  36. uint256 c = a - b;
  37. return c;
  38. }
  39. /**
  40. * @dev Adds two unsigned integers, reverts on overflow.
  41. */
  42. function add(uint256 a, uint256 b) internal pure returns (uint256) {
  43. uint256 c = a + b;
  44. require(c >= a);
  45. return c;
  46. }
  47. /**
  48. * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo),
  49. * reverts when dividing by zero.
  50. */
  51. function mod(uint256 a, uint256 b) internal pure returns (uint256) {
  52. require(b != 0);
  53. return a % b;
  54. }
  55. }