SafeMath.sol 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. pragma solidity ^0.4.24;
  2. /**
  3. * @title SafeMath
  4. * @dev Math operations with safety checks that revert on error
  5. */
  6. library SafeMath {
  7. /**
  8. * @dev Multiplies two numbers, 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 numbers truncating the quotient, reverts on division by zero.
  23. */
  24. function div(uint256 a, uint256 b) internal pure returns (uint256) {
  25. require(b > 0); // Solidity only automatically asserts when dividing by 0
  26. uint256 c = a / b;
  27. // assert(a == b * c + a % b); // There is no case in which this doesn't hold
  28. return c;
  29. }
  30. /**
  31. * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
  32. */
  33. function sub(uint256 a, uint256 b) internal pure returns (uint256) {
  34. require(b <= a);
  35. uint256 c = a - b;
  36. return c;
  37. }
  38. /**
  39. * @dev Adds two numbers, reverts on overflow.
  40. */
  41. function add(uint256 a, uint256 b) internal pure returns (uint256) {
  42. uint256 c = a + b;
  43. require(c >= a);
  44. return c;
  45. }
  46. /**
  47. * @dev Divides two numbers and returns the remainder (unsigned integer modulo),
  48. * reverts when dividing by zero.
  49. */
  50. function mod(uint256 a, uint256 b) internal pure returns (uint256) {
  51. require(b != 0);
  52. return a % b;
  53. }
  54. }