Skip to content

Commit 29b1b35

Browse files
committed
branchless
1 parent aa1cdb8 commit 29b1b35

File tree

1 file changed

+4
-6
lines changed

1 file changed

+4
-6
lines changed

contracts/utils/Bytes.sol

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -58,12 +58,10 @@ library Bytes {
5858
function lastIndexOf(bytes memory buffer, bytes1 s, uint256 pos) internal pure returns (uint256) {
5959
unchecked {
6060
uint256 length = buffer.length;
61-
if (length > 0) {
62-
// NOTE here we cannot do `i = Math.min(pos + 1, length)` because `pos + 1` could overflow
63-
for (uint256 i = Math.min(pos, length - 1) + 1; i > 0; --i) {
64-
if (bytes1(_unsafeReadBytesOffset(buffer, i - 1)) == s) {
65-
return i - 1;
66-
}
61+
uint256 end = Math.ternary(pos == type(uint256).max, length, Math.min(pos + 1, length));
62+
for (uint256 i = end; i > 0; --i) {
63+
if (bytes1(_unsafeReadBytesOffset(buffer, i - 1)) == s) {
64+
return i - 1;
6765
}
6866
}
6967
return type(uint256).max;

0 commit comments

Comments
 (0)