SignedMath.sol 967 B

123456789101112131415161718192021222324252627282930313233
  1. // SPDX-License-Identifier: MIT
  2. // OpenZeppelin Contracts (last updated v4.5.0-rc.0) (utils/math/SignedMath.sol)
  3. pragma solidity ^0.8.0;
  4. /**
  5. * @dev Standard signed math utilities missing in the Solidity language.
  6. */
  7. library SignedMath {
  8. /**
  9. * @dev Returns the largest of two signed numbers.
  10. */
  11. function max(int256 a, int256 b) internal pure returns (int256) {
  12. return a >= b ? a : b;
  13. }
  14. /**
  15. * @dev Returns the smallest of two signed numbers.
  16. */
  17. function min(int256 a, int256 b) internal pure returns (int256) {
  18. return a < b ? a : b;
  19. }
  20. /**
  21. * @dev Returns the average of two signed numbers without overflow.
  22. * The result is rounded towards zero.
  23. */
  24. function average(int256 a, int256 b) internal pure returns (int256) {
  25. // Formula from the book "Hacker's Delight"
  26. int256 x = (a & b) + ((a ^ b) >> 1);
  27. return x + (int256(uint256(x) >> 255) & (a ^ b));
  28. }
  29. }