12345678910111213141516171819202122232425262728293031323334353637383940414243 |
- // SPDX-License-Identifier: MIT
- // OpenZeppelin Contracts (last updated v4.8.0-rc.0) (utils/math/SignedMath.sol)
- pragma solidity ^0.8.0;
- /**
- * @dev Standard signed math utilities missing in the Solidity language.
- */
- library SignedMath {
- /**
- * @dev Returns the largest of two signed numbers.
- */
- function max(int256 a, int256 b) internal pure returns (int256) {
- return a > b ? a : b;
- }
- /**
- * @dev Returns the smallest of two signed numbers.
- */
- function min(int256 a, int256 b) internal pure returns (int256) {
- return a < b ? a : b;
- }
- /**
- * @dev Returns the average of two signed numbers without overflow.
- * The result is rounded towards zero.
- */
- function average(int256 a, int256 b) internal pure returns (int256) {
- // Formula from the book "Hacker's Delight"
- int256 x = (a & b) + ((a ^ b) >> 1);
- return x + (int256(uint256(x) >> 255) & (a ^ b));
- }
- /**
- * @dev Returns the absolute unsigned value of a signed value.
- */
- function abs(int256 n) internal pure returns (uint256) {
- unchecked {
- // must be unchecked in order to support `n = type(int256).min`
- return uint256(n >= 0 ? n : -n);
- }
- }
- }
|