SafeMath.sol 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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. }