SignedMath.sol 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. // SPDX-License-Identifier: MIT
  2. // OpenZeppelin Contracts (last updated v4.5.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. /**
  30. * @dev Returns the absolute unsigned value of a signed value.
  31. */
  32. function abs(int256 n) internal pure returns (uint256) {
  33. unchecked {
  34. // must be unchecked in order to support `n = type(int256).min`
  35. return uint256(n >= 0 ? n : -n);
  36. }
  37. }
  38. }