Skip to content

feat(math): implement fast Yul bit-search indexer and unit tests (#751) - #759

Merged
mijinummi merged 2 commits into
MDTechLabs:mainfrom
Francis6-git:perf/yul-bit-search-751
Aug 21, 2026
Merged

feat(math): implement fast Yul bit-search indexer and unit tests (#751)#759
mijinummi merged 2 commits into
MDTechLabs:mainfrom
Francis6-git:perf/yul-bit-search-751

Conversation

@Francis6-git

Copy link
Copy Markdown
Contributor

Description

This PR implements a constant-time $O(1)$ bit-search library in Yul (contracts/math/YulBitSearch.sol) to locate the Most Significant Bit (MSB) and Least Significant Bit (LSB) in a uint256 word.

High-level Solidity while loops iterate bit-by-bit, causing substantial gas overhead on large numbers. This implementation uses an 8-stage binary search bitwise shift approach directly in Yul inline assembly, guaranteeing predictable constant gas execution regardless of the bit position.


Changes Included

  • contracts/math/YulBitSearch.sol: Implemented mostSignificantBit and leastSignificantBit using constant-time binary search shifts in Yul.
  • test/math/YulBitSearch.test.ts: Added comprehensive Vitest suite covering singleton bits ($2^0$ to $2^{255}$), dense bit masks (MAX_UINT256), edge values, and zero-word handling.

Test Results

Ran unit test suite via Vitest targeting the newly added test file:

npx vitest run test/math/YulBitSearch.test.ts

 RUN  v4.1.11 C:/Users/BUMBLECODE/Documents/Projects/GasGuard

 ✓ test/math/YulBitSearch.test.ts (3 tests) 40ms
   ✓ YulBitSearch (3)
     ✓ returns zero for a zero word 4ms
     ✓ finds every singleton bit position 31ms
     ✓ handles edge and dense values 1ms

 Test Files  1 passed (1)
      Tests  3 passed (3)
   Start at  16:51:17
   Duration  1.50s (transform 125ms, setup 0ms, import 203ms, tests 40ms, environment 0ms)

Closes #751

@mijinummi

Copy link
Copy Markdown
Collaborator

Hello @Francis6-git , thank you for your contribution.

Please kindly fix the ci failures.

@mijinummi
mijinummi merged commit 35255b3 into MDTechLabs:main Aug 21, 2026
5 of 7 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[PERF] Implement Fast Bit-Search Indexer in Yul (Find First Set Bit)

2 participants