SafeMath.sol 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. pragma solidity ^0.4.24;
  2. /**
  3. * @title SafeMath
  4. * @dev Math operations with safety checks that throw on error
  5. */
  6. library SafeMath {
  7. /**
  8. * @dev Multiplies two numbers, throws on overflow.
  9. */
  10. function mul(uint256 _a, uint256 _b) internal pure returns (uint256) {
  11. // Gas optimization: this is cheaper than asserting '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. assert(c / _a == _b);
  19. return c;
  20. }
  21. /**
  22. * @dev Integer division of two numbers, truncating the quotient.
  23. */
  24. function div(uint256 _a, uint256 _b) internal pure returns (uint256) {
  25. // assert(_b > 0); // Solidity automatically throws 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, throws on overflow (i.e. if subtrahend is greater than minuend).
  32. */
  33. function sub(uint256 _a, uint256 _b) internal pure returns (uint256) {
  34. assert(_b <= _a);
  35. uint256 c = _a - _b;
  36. return c;
  37. }
  38. /**
  39. * @dev Adds two numbers, throws on overflow.
  40. */
  41. function add(uint256 _a, uint256 _b) internal pure returns (uint256) {
  42. uint256 c = _a + _b;
  43. assert(c >= _a);
  44. return c;
  45. }
  46. }