// SPDX-License-Identifier: MIT pragma solidity ^0.8.26; import {BitMath} from "@uniswap/v4-core/src/libraries/BitMath.sol"; /// @title ExpiryBitmap /// @notice Sorted set of expiry keys (mining-time blocks) as a 4-level, 256-ary bitmap tree. /// @dev Level 0 bit `k` marks key k; level l+1 bit `w` marks a non-empty level-l word `w`. /// `nextSet` finds the smallest key >= from in O(levels) storage reads (at most ~8 SLOADs for any key /// below 2^32, i.e. ~13 years of 100 ms blocks), however many empty blocks lie in between. /// set / clear cost at most 4 SSTOREs each. library ExpiryBitmap { uint256 internal constant LEVELS = 4; struct Bitmap { mapping(uint256 => uint256)[LEVELS] words; } function set(Bitmap storage bm, uint256 key) internal { for (uint256 l; l < LEVELS; ++l) { uint256 w = key >> 8; uint256 old = bm.words[l][w]; bm.words[l][w] = old | (uint256(1) << (key & 255)); if (old != 0) return; key = w; } } function clear(Bitmap storage bm, uint256 key) internal { for (uint256 l; l < LEVELS; ++l) { uint256 w = key >> 8; uint256 updated = bm.words[l][w] & ~(uint256(1) << (key & 255)); bm.words[l][w] = updated; if (updated != 0) return; key = w; } } function isSet(Bitmap storage bm, uint256 key) internal view returns (bool) { return bm.words[0][key >> 8] & (uint256(1) << (key & 255)) != 0; } /// @notice Smallest set key k with from <= k <= to. function nextSet(Bitmap storage bm, uint256 from, uint256 to) internal view returns (uint256 key, bool found) { if (from > to) return (0, false); uint256 k = from; uint256 l; while (true) { uint256 w = k >> 8; uint256 masked = bm.words[l][w] & (type(uint256).max << (k & 255)); if (masked != 0) { k = (w << 8) | BitMath.leastSignificantBit(masked); break; } if (l == LEVELS - 1) { k = (w + 1) << 8; if ((k << (8 * l)) > to) return (0, false); } else { k = w + 1; ++l; if ((k << (8 * l)) > to) return (0, false); } } while (l > 0) { --l; k = (k << 8) | BitMath.leastSignificantBit(bm.words[l][k]); } if (k > to) return (0, false); return (k, true); } }