SignedMath.sol 886 B

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