feat(libraries): add bit math and liquidity delta helpers

This commit is contained in:
dualfroz committed 2026-08-23 17:12:00 +02:00
1 parent d3d2a26bd1
commit 0a1dfd564b
2 files changed
+98

No files matched your search

+83
View File
@@ -0,0 +1,83 @@
// SPDX-License-Identifier: MIT
pragma solidity 0.8.36;
/// @title Most and least significant bit lookups over a 256 bit word.
library BitMath {
function mostSignificantBit(uint256 x) internal pure returns (uint8 r) {
require(x > 0, "BitMath: ZERO");
unchecked {
if (x >= 0x100000000000000000000000000000000) {
x >>= 128;
r += 128;
}
if (x >= 0x10000000000000000) {
x >>= 64;
r += 64;
}
if (x >= 0x100000000) {
x >>= 32;
r += 32;
}
if (x >= 0x10000) {
x >>= 16;
r += 16;
}
if (x >= 0x100) {
x >>= 8;
r += 8;
}
if (x >= 0x10) {
x >>= 4;
r += 4;
}
if (x >= 0x4) {
x >>= 2;
r += 2;
}
if (x >= 0x2) r += 1;
}
}
function leastSignificantBit(uint256 x) internal pure returns (uint8 r) {
require(x > 0, "BitMath: ZERO");
unchecked {
r = 255;
if (x & type(uint128).max > 0) {
r -= 128;
} else {
x >>= 128;
}
if (x & type(uint64).max > 0) {
r -= 64;
} else {
x >>= 64;
}
if (x & type(uint32).max > 0) {
r -= 32;
} else {
x >>= 32;
}
if (x & type(uint16).max > 0) {
r -= 16;
} else {
x >>= 16;
}
if (x & type(uint8).max > 0) {
r -= 8;
} else {
x >>= 8;
}
if (x & 0xf > 0) {
r -= 4;
} else {
x >>= 4;
}
if (x & 0x3 > 0) {
r -= 2;
} else {
x >>= 2;
}
if (x & 0x1 > 0) r -= 1;
}
}
}
+15
View File
@@ -0,0 +1,15 @@
// SPDX-License-Identifier: MIT
pragma solidity 0.8.36;
/// @title Adds a signed delta to an unsigned liquidity amount with overflow guards.
library LiquidityMath {
function addDelta(uint128 x, int128 y) internal pure returns (uint128 z) {
unchecked {
if (y < 0) {
require((z = x - uint128(-y)) < x, "LiquidityMath: SUB");
} else {
require((z = x + uint128(y)) >= x, "LiquidityMath: ADD");
}
}
}
}