Heap.sol 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  1. // SPDX-License-Identifier: MIT
  2. pragma solidity ^0.8.20;
  3. import {Math} from "../math/Math.sol";
  4. import {SafeCast} from "../math/SafeCast.sol";
  5. import {Comparators} from "../Comparators.sol";
  6. import {Arrays} from "../Arrays.sol";
  7. import {Panic} from "../Panic.sol";
  8. import {StorageSlot} from "../StorageSlot.sol";
  9. /**
  10. * @dev Library for managing https://en.wikipedia.org/wiki/Binary_heap[binary heap] that can be used as
  11. * https://en.wikipedia.org/wiki/Priority_queue[priority queue].
  12. *
  13. * Heaps are represented as a tree of values where the first element (index 0) is the root, and where the node at
  14. * index i is the child of the node at index (i-1)/2 and the parent of nodes at index 2*i+1 and 2*i+2. Each node
  15. * stores an element of the heap.
  16. *
  17. * The structure is ordered so that each node is bigger than its parent. An immediate consequence is that the
  18. * highest priority value is the one at the root. This value can be looked up in constant time (O(1)) at
  19. * `heap.tree[0]`
  20. *
  21. * The structure is designed to perform the following operations with the corresponding complexities:
  22. *
  23. * * peek (get the highest priority value): O(1)
  24. * * insert (insert a value): O(log(n))
  25. * * pop (remove the highest priority value): O(log(n))
  26. * * replace (replace the highest priority value with a new value): O(log(n))
  27. * * length (get the number of elements): O(1)
  28. * * clear (remove all elements): O(1)
  29. *
  30. * IMPORTANT: This library allows for the use of custom comparator functions. Given that manipulating
  31. * memory can lead to unexpected behavior. Consider verifying that the comparator does not manipulate
  32. * the Heap's state directly and that it follows the Solidity memory safety rules.
  33. */
  34. library Heap {
  35. using Arrays for *;
  36. using Math for *;
  37. using SafeCast for *;
  38. /**
  39. * @dev Binary heap that supports values of type uint256.
  40. *
  41. * Each element of that structure uses one storage slot.
  42. */
  43. struct Uint256Heap {
  44. uint256[] tree;
  45. }
  46. /**
  47. * @dev Lookup the root element of the heap.
  48. */
  49. function peek(Uint256Heap storage self) internal view returns (uint256) {
  50. // self.tree[0] will `ARRAY_ACCESS_OUT_OF_BOUNDS` panic if heap is empty.
  51. return self.tree[0];
  52. }
  53. /**
  54. * @dev Remove (and return) the root element for the heap using the default comparator.
  55. *
  56. * NOTE: All inserting and removal from a heap should always be done using the same comparator. Mixing comparator
  57. * during the lifecycle of a heap will result in undefined behavior.
  58. */
  59. function pop(Uint256Heap storage self) internal returns (uint256) {
  60. return pop(self, Comparators.lt);
  61. }
  62. /**
  63. * @dev Remove (and return) the root element for the heap using the provided comparator.
  64. *
  65. * NOTE: All inserting and removal from a heap should always be done using the same comparator. Mixing comparator
  66. * during the lifecycle of a heap will result in undefined behavior.
  67. */
  68. function pop(
  69. Uint256Heap storage self,
  70. function(uint256, uint256) view returns (bool) comp
  71. ) internal returns (uint256) {
  72. unchecked {
  73. uint256 size = length(self);
  74. if (size == 0) Panic.panic(Panic.EMPTY_ARRAY_POP);
  75. // cache
  76. uint256 rootValue = self.tree.unsafeAccess(0).value;
  77. uint256 lastValue = self.tree.unsafeAccess(size - 1).value;
  78. // swap last leaf with root, shrink tree and re-heapify
  79. self.tree.pop();
  80. self.tree.unsafeAccess(0).value = lastValue;
  81. _siftDown(self, size - 1, 0, lastValue, comp);
  82. return rootValue;
  83. }
  84. }
  85. /**
  86. * @dev Insert a new element in the heap using the default comparator.
  87. *
  88. * NOTE: All inserting and removal from a heap should always be done using the same comparator. Mixing comparator
  89. * during the lifecycle of a heap will result in undefined behavior.
  90. */
  91. function insert(Uint256Heap storage self, uint256 value) internal {
  92. insert(self, value, Comparators.lt);
  93. }
  94. /**
  95. * @dev Insert a new element in the heap using the provided comparator.
  96. *
  97. * NOTE: All inserting and removal from a heap should always be done using the same comparator. Mixing comparator
  98. * during the lifecycle of a heap will result in undefined behavior.
  99. */
  100. function insert(
  101. Uint256Heap storage self,
  102. uint256 value,
  103. function(uint256, uint256) view returns (bool) comp
  104. ) internal {
  105. uint256 size = length(self);
  106. // push new item and re-heapify
  107. self.tree.push(value);
  108. _siftUp(self, size, value, comp);
  109. }
  110. /**
  111. * @dev Return the root element for the heap, and replace it with a new value, using the default comparator.
  112. * This is equivalent to using {pop} and {insert}, but requires only one rebalancing operation.
  113. *
  114. * NOTE: All inserting and removal from a heap should always be done using the same comparator. Mixing comparator
  115. * during the lifecycle of a heap will result in undefined behavior.
  116. */
  117. function replace(Uint256Heap storage self, uint256 newValue) internal returns (uint256) {
  118. return replace(self, newValue, Comparators.lt);
  119. }
  120. /**
  121. * @dev Return the root element for the heap, and replace it with a new value, using the provided comparator.
  122. * This is equivalent to using {pop} and {insert}, but requires only one rebalancing operation.
  123. *
  124. * NOTE: All inserting and removal from a heap should always be done using the same comparator. Mixing comparator
  125. * during the lifecycle of a heap will result in undefined behavior.
  126. */
  127. function replace(
  128. Uint256Heap storage self,
  129. uint256 newValue,
  130. function(uint256, uint256) view returns (bool) comp
  131. ) internal returns (uint256) {
  132. uint256 size = length(self);
  133. if (size == 0) Panic.panic(Panic.EMPTY_ARRAY_POP);
  134. // cache
  135. uint256 oldValue = self.tree.unsafeAccess(0).value;
  136. // replace and re-heapify
  137. self.tree.unsafeAccess(0).value = newValue;
  138. _siftDown(self, size, 0, newValue, comp);
  139. return oldValue;
  140. }
  141. /**
  142. * @dev Returns the number of elements in the heap.
  143. */
  144. function length(Uint256Heap storage self) internal view returns (uint256) {
  145. return self.tree.length;
  146. }
  147. /**
  148. * @dev Removes all elements in the heap.
  149. */
  150. function clear(Uint256Heap storage self) internal {
  151. self.tree.unsafeSetLength(0);
  152. }
  153. /**
  154. * @dev Swap node `i` and `j` in the tree.
  155. */
  156. function _swap(Uint256Heap storage self, uint256 i, uint256 j) private {
  157. StorageSlot.Uint256Slot storage ni = self.tree.unsafeAccess(i);
  158. StorageSlot.Uint256Slot storage nj = self.tree.unsafeAccess(j);
  159. (ni.value, nj.value) = (nj.value, ni.value);
  160. }
  161. /**
  162. * @dev Perform heap maintenance on `self`, starting at `index` (with the `value`), using `comp` as a
  163. * comparator, and moving toward the leaves of the underlying tree.
  164. *
  165. * NOTE: This is a private function that is called in a trusted context with already cached parameters. `size`
  166. * and `value` could be extracted from `self` and `index`, but that would require redundant storage read. These
  167. * parameters are not verified. It is the caller role to make sure the parameters are correct.
  168. */
  169. function _siftDown(
  170. Uint256Heap storage self,
  171. uint256 size,
  172. uint256 index,
  173. uint256 value,
  174. function(uint256, uint256) view returns (bool) comp
  175. ) private {
  176. unchecked {
  177. // Check if there is a risk of overflow when computing the indices of the child nodes. If that is the case,
  178. // there cannot be child nodes in the tree, so sifting is done.
  179. if (index >= type(uint256).max / 2) return;
  180. // Compute the indices of the potential child nodes
  181. uint256 lIndex = 2 * index + 1;
  182. uint256 rIndex = 2 * index + 2;
  183. // Three cases:
  184. // 1. Both children exist: sifting may continue on one of the branch (selection required)
  185. // 2. Only left child exist: sifting may continue on the left branch (no selection required)
  186. // 3. Neither child exist: sifting is done
  187. if (rIndex < size) {
  188. uint256 lValue = self.tree.unsafeAccess(lIndex).value;
  189. uint256 rValue = self.tree.unsafeAccess(rIndex).value;
  190. if (comp(lValue, value) || comp(rValue, value)) {
  191. uint256 cIndex = comp(lValue, rValue).ternary(lIndex, rIndex);
  192. _swap(self, index, cIndex);
  193. _siftDown(self, size, cIndex, value, comp);
  194. }
  195. } else if (lIndex < size) {
  196. uint256 lValue = self.tree.unsafeAccess(lIndex).value;
  197. if (comp(lValue, value)) {
  198. _swap(self, index, lIndex);
  199. _siftDown(self, size, lIndex, value, comp);
  200. }
  201. }
  202. }
  203. }
  204. /**
  205. * @dev Perform heap maintenance on `self`, starting at `index` (with the `value`), using `comp` as a
  206. * comparator, and moving toward the root of the underlying tree.
  207. *
  208. * NOTE: This is a private function that is called in a trusted context with already cached parameters. `value`
  209. * could be extracted from `self` and `index`, but that would require redundant storage read. These parameters are not
  210. * verified. It is the caller role to make sure the parameters are correct.
  211. */
  212. function _siftUp(
  213. Uint256Heap storage self,
  214. uint256 index,
  215. uint256 value,
  216. function(uint256, uint256) view returns (bool) comp
  217. ) private {
  218. unchecked {
  219. while (index > 0) {
  220. uint256 parentIndex = (index - 1) / 2;
  221. uint256 parentValue = self.tree.unsafeAccess(parentIndex).value;
  222. if (comp(parentValue, value)) break;
  223. _swap(self, index, parentIndex);
  224. index = parentIndex;
  225. }
  226. }
  227. }
  228. }