Skip to content

Reading Elysium

Mine

ExpiryBitmap.t.sol

108 lines · sha256 d97b3b9bf498914acaf4914b780503b36ba8e12523864a1ceda8874e1a732a22 · Raw

1// SPDX-License-Identifier: MIT
2pragma solidity ^0.8.26;
3
4import {Test} from "forge-std/Test.sol";
5import {ExpiryBitmap} from "../src/libraries/ExpiryBitmap.sol";
6
7contract BitmapHarness {
8 using ExpiryBitmap for ExpiryBitmap.Bitmap;
9
10 ExpiryBitmap.Bitmap internal bm;
11
12 function set(uint256 k) external {
13 bm.set(k);
14 }
15
16 function clear(uint256 k) external {
17 bm.clear(k);
18 }
19
20 function isSet(uint256 k) external view returns (bool) {
21 return bm.isSet(k);
22 }
23
24 function nextSet(uint256 from, uint256 to) external view returns (uint256, bool) {
25 return bm.nextSet(from, to);
26 }
27}
28
29contract ExpiryBitmapTest is Test {
30 BitmapHarness h;
31 uint256 constant MAXT = 1 << 34; // ~54 years of 100 ms blocks
32
33 function setUp() public {
34 h = new BitmapHarness();
35 }
36
37 function test_basic() public {
38 (, bool f) = h.nextSet(0, MAXT);
39 assertFalse(f);
40 h.set(5);
41 h.set(70_000);
42 h.set(20_000_000);
43 h.set(5_000_000_000); // beyond 2^32: top-level scan
44 (uint256 k, bool found) = h.nextSet(0, MAXT);
45 assertTrue(found);
46 assertEq(k, 5);
47 (k,) = h.nextSet(6, MAXT);
48 assertEq(k, 70_000);
49 (k,) = h.nextSet(70_001, MAXT);
50 assertEq(k, 20_000_000);
51 (k,) = h.nextSet(20_000_001, MAXT);
52 assertEq(k, 5_000_000_000);
53 (, found) = h.nextSet(6, 69_999);
54 assertFalse(found);
55 h.clear(70_000);
56 (k,) = h.nextSet(6, MAXT);
57 assertEq(k, 20_000_000);
58 h.clear(5);
59 h.clear(20_000_000);
60 h.clear(5_000_000_000);
61 (, found) = h.nextSet(0, MAXT);
62 assertFalse(found);
63 }
64
65 function test_gas_skipsLongEmptyRange() public {
66 h.set(30_000_000);
67 uint256 g = gasleft();
68 (uint256 k,) = h.nextSet(1, 40_000_000);
69 uint256 used = g - gasleft();
70 assertEq(k, 30_000_000);
71 assertLt(used, 40_000);
72 }
73
74 /// Differential fuzz against a naive scan.
75 function testFuzz_matchesNaive(uint256 seed) public {
76 bool[1024] memory naive;
77 uint256 s = seed;
78 for (uint256 i; i < 60; ++i) {
79 s = uint256(keccak256(abi.encode(s)));
80 uint256 key = s % 1024;
81 if (s % 3 == 0 && naive[key]) {
82 naive[key] = false;
83 h.clear(key);
84 } else if (!naive[key]) {
85 naive[key] = true;
86 h.set(key);
87 }
88 }
89 for (uint256 q; q < 30; ++q) {
90 s = uint256(keccak256(abi.encode(s, q)));
91 uint256 from = s % 1024;
92 uint256 to = from + (s >> 20) % (1024 - from);
93 uint256 expect;
94 bool exp;
95 for (uint256 j = from; j <= to; ++j) {
96 if (naive[j]) {
97 expect = j;
98 exp = true;
99 break;
100 }
101 }
102 (uint256 k, bool f) = h.nextSet(from, to);
103 assertEq(f, exp);
104 if (exp) assertEq(k, expect);
105 }
106 }
107}
108