SafeMath.sol 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. pragma solidity ^0.4.23;
  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 c) {
  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. 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 a / b;
  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. return a - b;
  36. }
  37. /**
  38. * @dev Adds two numbers, throws on overflow.
  39. */
  40. function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
  41. c = a + b;
  42. assert(c >= a);
  43. return c;
  44. }
  45. }