Sitelet https://github.com/Vectorized/solady/pull/1412/files
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions src/utils/LibBit.sol
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,19 @@ library LibBit {
}
}

/// @dev Returns the number of zero bits in `x`.
/// To get the number of non-zero bytes, simply do `32 - countZeroBytes(x)`
function countZeroBytes(uint256 x) internal pure returns (uint256 c) {
/// @solidity memory-safe-assembly
assembly {
c := 0x7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f
c := not(or(or(add(and(x, c), c), x), c)) // `.each(b => b == 0x00 ? 0x80 : 0x00)`.
c := shr(7, c)
c := mul(0x0101010101010101010101010101010101010101010101010101010101010101, c)
c := byte(0, c)
}
}

/// @dev Returns whether `x` is a power of 2.
function isPo2(uint256 x) internal pure returns (bool result) {
/// @solidity memory-safe-assembly
Expand Down
19 changes: 19 additions & 0 deletions test/LibBit.t.sol
Original file line number Diff line number Diff line change
Expand Up @@ -276,4 +276,23 @@ contract LibBitTest is SoladyTest {
m >>= 1;
}
}

function testCountZeroBytesDifferential(uint256 x) public {
assertEq(LibBit.countZeroBytes(x), _countZeroBytesOriginal(x));
}

function testCountZeroBytes() public {
uint256 x = 0xff00ffffffffffffffffffffffffffffffffffffffffffffffffffffffff00ff;
x |= uint256(uint160(address(this))) << 16;
assertEq(LibBit.countZeroBytes(x), 2);
}

function _countZeroBytesOriginal(uint256 x) internal pure returns (uint256 c) {
unchecked {
for (uint256 i; i < 32; ++i) {
c += ((x & (0xff << (i * 8))) == 0 ? 1 : 0);
}
return c;
}
}
}