SafeMath.sol 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. pragma solidity ^0.4.18;
  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. if (a == 0) {
  12. return 0;
  13. }
  14. uint256 c = a * b;
  15. assert(c / a == b);
  16. return c;
  17. }
  18. /**
  19. * @dev Integer division of two numbers, truncating the quotient.
  20. */
  21. function div(uint256 a, uint256 b) internal pure returns (uint256) {
  22. // assert(b > 0); // Solidity automatically throws when dividing by 0
  23. uint256 c = a / b;
  24. // assert(a == b * c + a % b); // There is no case in which this doesn't hold
  25. return c;
  26. }
  27. /**
  28. * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
  29. */
  30. function sub(uint256 a, uint256 b) internal pure returns (uint256) {
  31. assert(b <= a);
  32. return a - b;
  33. }
  34. /**
  35. * @dev Adds two numbers, throws on overflow.
  36. */
  37. function add(uint256 a, uint256 b) internal pure returns (uint256) {
  38. uint256 c = a + b;
  39. assert(c >= a);
  40. return c;
  41. }
  42. }