Heap.sol 10 KB

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