| 1 | // SPDX-License-Identifier: MIT |
| 2 | pragma solidity >=0.6.2 <0.9.0; |
| 3 | |
| 4 | library stdMath { |
| 5 | int256 private constant INT256_MIN = -57896044618658097711785492504343953926634992332820282019728792003956564819968; |
| 6 | |
| 7 | function abs(int256 a) internal pure returns (uint256) { |
| 8 | // Required or it will fail when `a = type(int256).min` |
| 9 | if (a == INT256_MIN) { |
| 10 | return 57896044618658097711785492504343953926634992332820282019728792003956564819968; |
| 11 | } |
| 12 | |
| 13 | return uint256(a > 0 ? a : -a); |
| 14 | } |
| 15 | |
| 16 | function delta(uint256 a, uint256 b) internal pure returns (uint256) { |
| 17 | return a > b ? a - b : b - a; |
| 18 | } |
| 19 | |
| 20 | function delta(int256 a, int256 b) internal pure returns (uint256) { |
| 21 | // a and b are of the same sign |
| 22 | // this works thanks to two's complement, the left-most bit is the sign bit |
| 23 | if ((a ^ b) > -1) { |
| 24 | return delta(abs(a), abs(b)); |
| 25 | } |
| 26 | |
| 27 | // a and b are of opposite signs |
| 28 | return abs(a) + abs(b); |
| 29 | } |
| 30 | |
| 31 | function percentDelta(uint256 a, uint256 b) internal pure returns (uint256) { |
| 32 | uint256 absDelta = delta(a, b); |
| 33 | |
| 34 | return absDelta * 1e18 / b; |
| 35 | } |
| 36 | |
| 37 | function percentDelta(int256 a, int256 b) internal pure returns (uint256) { |
| 38 | uint256 absDelta = delta(a, b); |
| 39 | uint256 absB = abs(b); |
| 40 | |
| 41 | return absDelta * 1e18 / absB; |
| 42 | } |
| 43 | } |