ExpiryBitmap.sol
72 lines · sha256 5d0f1f99aafce7a7d00bf566614f97a9eda77b590f7878fe877908341b489da2 · Raw
| 1 | // SPDX-License-Identifier: MIT |
| 2 | pragma solidity ^0.8.26; |
| 3 | |
| 4 | import {BitMath} from "@uniswap/v4-core/src/libraries/BitMath.sol"; |
| 5 | |
| 6 | /// @title ExpiryBitmap |
| 7 | /// @notice Sorted set of expiry keys (mining-time blocks) as a 4-level, 256-ary bitmap tree. |
| 8 | /// @dev Level 0 bit `k` marks key k; level l+1 bit `w` marks a non-empty level-l word `w`. |
| 9 | /// `nextSet` finds the smallest key >= from in O(levels) storage reads (at most ~8 SLOADs for any key |
| 10 | /// below 2^32, i.e. ~13 years of 100 ms blocks), however many empty blocks lie in between. |
| 11 | /// set / clear cost at most 4 SSTOREs each. |
| 12 | library ExpiryBitmap { |
| 13 | uint256 internal constant LEVELS = 4; |
| 14 | |
| 15 | struct Bitmap { |
| 16 | mapping(uint256 => uint256)[LEVELS] words; |
| 17 | } |
| 18 | |
| 19 | function set(Bitmap storage bm, uint256 key) internal { |
| 20 | for (uint256 l; l < LEVELS; ++l) { |
| 21 | uint256 w = key >> 8; |
| 22 | uint256 old = bm.words[l][w]; |
| 23 | bm.words[l][w] = old | (uint256(1) << (key & 255)); |
| 24 | if (old != 0) return; |
| 25 | key = w; |
| 26 | } |
| 27 | } |
| 28 | |
| 29 | function clear(Bitmap storage bm, uint256 key) internal { |
| 30 | for (uint256 l; l < LEVELS; ++l) { |
| 31 | uint256 w = key >> 8; |
| 32 | uint256 updated = bm.words[l][w] & ~(uint256(1) << (key & 255)); |
| 33 | bm.words[l][w] = updated; |
| 34 | if (updated != 0) return; |
| 35 | key = w; |
| 36 | } |
| 37 | } |
| 38 | |
| 39 | function isSet(Bitmap storage bm, uint256 key) internal view returns (bool) { |
| 40 | return bm.words[0][key >> 8] & (uint256(1) << (key & 255)) != 0; |
| 41 | } |
| 42 | |
| 43 | /// @notice Smallest set key k with from <= k <= to. |
| 44 | function nextSet(Bitmap storage bm, uint256 from, uint256 to) internal view returns (uint256 key, bool found) { |
| 45 | if (from > to) return (0, false); |
| 46 | uint256 k = from; |
| 47 | uint256 l; |
| 48 | while (true) { |
| 49 | uint256 w = k >> 8; |
| 50 | uint256 masked = bm.words[l][w] & (type(uint256).max << (k & 255)); |
| 51 | if (masked != 0) { |
| 52 | k = (w << 8) | BitMath.leastSignificantBit(masked); |
| 53 | break; |
| 54 | } |
| 55 | if (l == LEVELS - 1) { |
| 56 | k = (w + 1) << 8; |
| 57 | if ((k << (8 * l)) > to) return (0, false); |
| 58 | } else { |
| 59 | k = w + 1; |
| 60 | ++l; |
| 61 | if ((k << (8 * l)) > to) return (0, false); |
| 62 | } |
| 63 | } |
| 64 | while (l > 0) { |
| 65 | --l; |
| 66 | k = (k << 8) | BitMath.leastSignificantBit(bm.words[l][k]); |
| 67 | } |
| 68 | if (k > to) return (0, false); |
| 69 | return (k, true); |
| 70 | } |
| 71 | } |
| 72 |