// SPDX-License-Identifier: MIT pragma solidity ^0.8.26; import {Test} from "forge-std/Test.sol"; import {ExpiryBitmap} from "../src/libraries/ExpiryBitmap.sol"; contract BitmapHarness { using ExpiryBitmap for ExpiryBitmap.Bitmap; ExpiryBitmap.Bitmap internal bm; function set(uint256 k) external { bm.set(k); } function clear(uint256 k) external { bm.clear(k); } function isSet(uint256 k) external view returns (bool) { return bm.isSet(k); } function nextSet(uint256 from, uint256 to) external view returns (uint256, bool) { return bm.nextSet(from, to); } } contract ExpiryBitmapTest is Test { BitmapHarness h; uint256 constant MAXT = 1 << 34; // ~54 years of 100 ms blocks function setUp() public { h = new BitmapHarness(); } function test_basic() public { (, bool f) = h.nextSet(0, MAXT); assertFalse(f); h.set(5); h.set(70_000); h.set(20_000_000); h.set(5_000_000_000); // beyond 2^32: top-level scan (uint256 k, bool found) = h.nextSet(0, MAXT); assertTrue(found); assertEq(k, 5); (k,) = h.nextSet(6, MAXT); assertEq(k, 70_000); (k,) = h.nextSet(70_001, MAXT); assertEq(k, 20_000_000); (k,) = h.nextSet(20_000_001, MAXT); assertEq(k, 5_000_000_000); (, found) = h.nextSet(6, 69_999); assertFalse(found); h.clear(70_000); (k,) = h.nextSet(6, MAXT); assertEq(k, 20_000_000); h.clear(5); h.clear(20_000_000); h.clear(5_000_000_000); (, found) = h.nextSet(0, MAXT); assertFalse(found); } function test_gas_skipsLongEmptyRange() public { h.set(30_000_000); uint256 g = gasleft(); (uint256 k,) = h.nextSet(1, 40_000_000); uint256 used = g - gasleft(); assertEq(k, 30_000_000); assertLt(used, 40_000); } /// Differential fuzz against a naive scan. function testFuzz_matchesNaive(uint256 seed) public { bool[1024] memory naive; uint256 s = seed; for (uint256 i; i < 60; ++i) { s = uint256(keccak256(abi.encode(s))); uint256 key = s % 1024; if (s % 3 == 0 && naive[key]) { naive[key] = false; h.clear(key); } else if (!naive[key]) { naive[key] = true; h.set(key); } } for (uint256 q; q < 30; ++q) { s = uint256(keccak256(abi.encode(s, q))); uint256 from = s % 1024; uint256 to = from + (s >> 20) % (1024 - from); uint256 expect; bool exp; for (uint256 j = from; j <= to; ++j) { if (naive[j]) { expect = j; exp = true; break; } } (uint256 k, bool f) = h.nextSet(from, to); assertEq(f, exp); if (exp) assertEq(k, expect); } } }