Skip to content

Commit

Permalink
Update comments on use of xor
Browse files Browse the repository at this point in the history
  • Loading branch information
shuhuiluo committed May 21, 2024
1 parent 0f4d817 commit 192b294
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 5 deletions.
6 changes: 5 additions & 1 deletion src/libraries/SqrtPriceMath.sol
Original file line number Diff line number Diff line change
Expand Up @@ -169,11 +169,15 @@ library SqrtPriceMath {
}
}

/// @notice Equivalent to: `a > b ? a - b : b - a`
/// @notice Equivalent to: `a >= b ? a - b : b - a`
function absDiff(uint160 a, uint160 b) internal pure returns (uint256 res) {
assembly {
let diff := sub(a, b)
// mask = 0 if a >= b else -1 (all 1s)
let mask := sar(255, diff)
// if a >= b, res = a - b = 0 ^ (a - b)
// if a < b, res = b - a = ~~(b - a) = ~(-(b - a) - 1) = ~(a - b - 1) = (-1) ^ (a - b - 1)
// either way, res = mask ^ (a - b + mask)
res := xor(mask, add(mask, diff))
}
}
Expand Down
8 changes: 4 additions & 4 deletions src/libraries/TickMath.sol
Original file line number Diff line number Diff line change
Expand Up @@ -51,11 +51,11 @@ library TickMath {
unchecked {
uint256 absTick;
assembly {
// mask = 0 if tick >= 0 else -1
// mask = 0 if tick >= 0 else -1 (all 1s)
let mask := sar(255, tick)
// If tick >= 0, |tick| = tick = 0 ^ tick
// If tick < 0, |tick| = ~~|tick| = ~(-|tick| - 1) = ~(tick - 1) = (-1) ^ (tick - 1)
// Either case, |tick| = mask ^ (tick + mask)
// if tick >= 0, |tick| = tick = 0 ^ tick
// if tick < 0, |tick| = ~~|tick| = ~(-|tick| - 1) = ~(tick - 1) = (-1) ^ (tick - 1)
// either way, |tick| = mask ^ (tick + mask)
absTick := xor(mask, add(mask, tick))
}
// Equivalent: if (absTick > MAX_TICK) revert InvalidTick();
Expand Down

0 comments on commit 192b294

Please sign in to comment.