Heap.t.sol 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. // SPDX-License-Identifier: MIT
  2. pragma solidity ^0.8.20;
  3. import {Test} from "forge-std/Test.sol";
  4. import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
  5. import {Heap} from "@openzeppelin/contracts/utils/structs/Heap.sol";
  6. import {Comparators} from "@openzeppelin/contracts/utils/Comparators.sol";
  7. contract Uint256HeapTest is Test {
  8. using Heap for Heap.Uint256Heap;
  9. Heap.Uint256Heap internal heap;
  10. function _validateHeap(function(uint256, uint256) view returns (bool) comp) internal {
  11. for (uint32 i = 1; i < heap.length(); ++i) {
  12. assertFalse(comp(heap.tree[i], heap.tree[(i - 1) / 2]));
  13. }
  14. }
  15. function testFuzz(uint256[] calldata input) public {
  16. vm.assume(input.length < 0x20);
  17. assertEq(heap.length(), 0);
  18. uint256 min = type(uint256).max;
  19. for (uint256 i = 0; i < input.length; ++i) {
  20. heap.insert(input[i]);
  21. assertEq(heap.length(), i + 1);
  22. _validateHeap(Comparators.lt);
  23. min = Math.min(min, input[i]);
  24. assertEq(heap.peek(), min);
  25. }
  26. uint256 max = 0;
  27. for (uint256 i = 0; i < input.length; ++i) {
  28. uint256 top = heap.peek();
  29. uint256 pop = heap.pop();
  30. assertEq(heap.length(), input.length - i - 1);
  31. _validateHeap(Comparators.lt);
  32. assertEq(pop, top);
  33. assertGe(pop, max);
  34. max = pop;
  35. }
  36. }
  37. function testFuzzGt(uint256[] calldata input) public {
  38. vm.assume(input.length < 0x20);
  39. assertEq(heap.length(), 0);
  40. uint256 max = 0;
  41. for (uint256 i = 0; i < input.length; ++i) {
  42. heap.insert(input[i], Comparators.gt);
  43. assertEq(heap.length(), i + 1);
  44. _validateHeap(Comparators.gt);
  45. max = Math.max(max, input[i]);
  46. assertEq(heap.peek(), max);
  47. }
  48. uint256 min = type(uint256).max;
  49. for (uint256 i = 0; i < input.length; ++i) {
  50. uint256 top = heap.peek();
  51. uint256 pop = heap.pop(Comparators.gt);
  52. assertEq(heap.length(), input.length - i - 1);
  53. _validateHeap(Comparators.gt);
  54. assertEq(pop, top);
  55. assertLe(pop, min);
  56. min = pop;
  57. }
  58. }
  59. }