SignedMath.sol 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  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. /**
  29. * @dev Returns the absolute unsigned value of a signed value.
  30. */
  31. function abs(int256 n) internal pure returns (uint256) {
  32. unchecked {
  33. // must be unchecked in order to support `n = type(int256).min`
  34. return uint256(n >= 0 ? n : -n);
  35. }
  36. }
  37. }