Heap.sol 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  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. * _Available since v5.1._
  35. */
  36. library Heap {
  37. using Arrays for *;
  38. using Math for *;
  39. using SafeCast for *;
  40. /**
  41. * @dev Binary heap that supports values of type uint256.
  42. *
  43. * Each element of that structure uses one storage slot.
  44. */
  45. struct Uint256Heap {
  46. uint256[] tree;
  47. }
  48. /**
  49. * @dev Lookup the root element of the heap.
  50. */
  51. function peek(Uint256Heap storage self) internal view returns (uint256) {
  52. // self.tree[0] will `ARRAY_ACCESS_OUT_OF_BOUNDS` panic if heap is empty.
  53. return self.tree[0];
  54. }
  55. /**
  56. * @dev Remove (and return) the root element for the heap using the default comparator.
  57. *
  58. * NOTE: All inserting and removal from a heap should always be done using the same comparator. Mixing comparator
  59. * during the lifecycle of a heap will result in undefined behavior.
  60. */
  61. function pop(Uint256Heap storage self) internal returns (uint256) {
  62. return pop(self, Comparators.lt);
  63. }
  64. /**
  65. * @dev Remove (and return) the root element for the heap using the provided comparator.
  66. *
  67. * NOTE: All inserting and removal from a heap should always be done using the same comparator. Mixing comparator
  68. * during the lifecycle of a heap will result in undefined behavior.
  69. */
  70. function pop(
  71. Uint256Heap storage self,
  72. function(uint256, uint256) view returns (bool) comp
  73. ) internal returns (uint256) {
  74. unchecked {
  75. uint256 size = length(self);
  76. if (size == 0) Panic.panic(Panic.EMPTY_ARRAY_POP);
  77. // cache
  78. uint256 rootValue = self.tree.unsafeAccess(0).value;
  79. uint256 lastValue = self.tree.unsafeAccess(size - 1).value;
  80. // swap last leaf with root, shrink tree and re-heapify
  81. self.tree.pop();
  82. self.tree.unsafeAccess(0).value = lastValue;
  83. _siftDown(self, size - 1, 0, lastValue, comp);
  84. return rootValue;
  85. }
  86. }
  87. /**
  88. * @dev Insert a new element in the heap using the default comparator.
  89. *
  90. * NOTE: All inserting and removal from a heap should always be done using the same comparator. Mixing comparator
  91. * during the lifecycle of a heap will result in undefined behavior.
  92. */
  93. function insert(Uint256Heap storage self, uint256 value) internal {
  94. insert(self, value, Comparators.lt);
  95. }
  96. /**
  97. * @dev Insert a new element in the heap using the provided comparator.
  98. *
  99. * NOTE: All inserting and removal from a heap should always be done using the same comparator. Mixing comparator
  100. * during the lifecycle of a heap will result in undefined behavior.
  101. */
  102. function insert(
  103. Uint256Heap storage self,
  104. uint256 value,
  105. function(uint256, uint256) view returns (bool) comp
  106. ) internal {
  107. uint256 size = length(self);
  108. // push new item and re-heapify
  109. self.tree.push(value);
  110. _siftUp(self, size, value, comp);
  111. }
  112. /**
  113. * @dev Return the root element for the heap, and replace it with a new value, using the default comparator.
  114. * This is equivalent to using {pop} and {insert}, but requires only one rebalancing operation.
  115. *
  116. * NOTE: All inserting and removal from a heap should always be done using the same comparator. Mixing comparator
  117. * during the lifecycle of a heap will result in undefined behavior.
  118. */
  119. function replace(Uint256Heap storage self, uint256 newValue) internal returns (uint256) {
  120. return replace(self, newValue, Comparators.lt);
  121. }
  122. /**
  123. * @dev Return the root element for the heap, and replace it with a new value, using the provided comparator.
  124. * This is equivalent to using {pop} and {insert}, but requires only one rebalancing operation.
  125. *
  126. * NOTE: All inserting and removal from a heap should always be done using the same comparator. Mixing comparator
  127. * during the lifecycle of a heap will result in undefined behavior.
  128. */
  129. function replace(
  130. Uint256Heap storage self,
  131. uint256 newValue,
  132. function(uint256, uint256) view returns (bool) comp
  133. ) internal returns (uint256) {
  134. uint256 size = length(self);
  135. if (size == 0) Panic.panic(Panic.EMPTY_ARRAY_POP);
  136. // cache
  137. uint256 oldValue = self.tree.unsafeAccess(0).value;
  138. // replace and re-heapify
  139. self.tree.unsafeAccess(0).value = newValue;
  140. _siftDown(self, size, 0, newValue, comp);
  141. return oldValue;
  142. }
  143. /**
  144. * @dev Returns the number of elements in the heap.
  145. */
  146. function length(Uint256Heap storage self) internal view returns (uint256) {
  147. return self.tree.length;
  148. }
  149. /**
  150. * @dev Removes all elements in the heap.
  151. */
  152. function clear(Uint256Heap storage self) internal {
  153. self.tree.unsafeSetLength(0);
  154. }
  155. /**
  156. * @dev Swap node `i` and `j` in the tree.
  157. */
  158. function _swap(Uint256Heap storage self, uint256 i, uint256 j) private {
  159. StorageSlot.Uint256Slot storage ni = self.tree.unsafeAccess(i);
  160. StorageSlot.Uint256Slot storage nj = self.tree.unsafeAccess(j);
  161. (ni.value, nj.value) = (nj.value, ni.value);
  162. }
  163. /**
  164. * @dev Perform heap maintenance on `self`, starting at `index` (with the `value`), using `comp` as a
  165. * comparator, and moving toward the leaves of the underlying tree.
  166. *
  167. * NOTE: This is a private function that is called in a trusted context with already cached parameters. `size`
  168. * and `value` could be extracted from `self` and `index`, but that would require redundant storage read. These
  169. * parameters are not verified. It is the caller role to make sure the parameters are correct.
  170. */
  171. function _siftDown(
  172. Uint256Heap storage self,
  173. uint256 size,
  174. uint256 index,
  175. uint256 value,
  176. function(uint256, uint256) view returns (bool) comp
  177. ) private {
  178. unchecked {
  179. // Check if there is a risk of overflow when computing the indices of the child nodes. If that is the case,
  180. // there cannot be child nodes in the tree, so sifting is done.
  181. if (index >= type(uint256).max / 2) return;
  182. // Compute the indices of the potential child nodes
  183. uint256 lIndex = 2 * index + 1;
  184. uint256 rIndex = 2 * index + 2;
  185. // Three cases:
  186. // 1. Both children exist: sifting may continue on one of the branch (selection required)
  187. // 2. Only left child exist: sifting may continue on the left branch (no selection required)
  188. // 3. Neither child exist: sifting is done
  189. if (rIndex < size) {
  190. uint256 lValue = self.tree.unsafeAccess(lIndex).value;
  191. uint256 rValue = self.tree.unsafeAccess(rIndex).value;
  192. if (comp(lValue, value) || comp(rValue, value)) {
  193. uint256 cIndex = comp(lValue, rValue).ternary(lIndex, rIndex);
  194. _swap(self, index, cIndex);
  195. _siftDown(self, size, cIndex, value, comp);
  196. }
  197. } else if (lIndex < size) {
  198. uint256 lValue = self.tree.unsafeAccess(lIndex).value;
  199. if (comp(lValue, value)) {
  200. _swap(self, index, lIndex);
  201. _siftDown(self, size, lIndex, value, comp);
  202. }
  203. }
  204. }
  205. }
  206. /**
  207. * @dev Perform heap maintenance on `self`, starting at `index` (with the `value`), using `comp` as a
  208. * comparator, and moving toward the root of the underlying tree.
  209. *
  210. * NOTE: This is a private function that is called in a trusted context with already cached parameters. `value`
  211. * could be extracted from `self` and `index`, but that would require redundant storage read. These parameters are not
  212. * verified. It is the caller role to make sure the parameters are correct.
  213. */
  214. function _siftUp(
  215. Uint256Heap storage self,
  216. uint256 index,
  217. uint256 value,
  218. function(uint256, uint256) view returns (bool) comp
  219. ) private {
  220. unchecked {
  221. while (index > 0) {
  222. uint256 parentIndex = (index - 1) / 2;
  223. uint256 parentValue = self.tree.unsafeAccess(parentIndex).value;
  224. if (comp(parentValue, value)) break;
  225. _swap(self, index, parentIndex);
  226. index = parentIndex;
  227. }
  228. }
  229. }
  230. }