Heap.sol 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579
  1. // SPDX-License-Identifier: MIT
  2. // OpenZeppelin Contracts (last updated v5.1.0-rc.0) (utils/structs/Heap.sol)
  3. // This file was procedurally generated from scripts/generate/templates/Heap.js.
  4. pragma solidity ^0.8.20;
  5. import {Math} from "../math/Math.sol";
  6. import {SafeCast} from "../math/SafeCast.sol";
  7. import {Comparators} from "../Comparators.sol";
  8. import {Panic} from "../Panic.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 an array of Node objects. This array stores two overlapping structures:
  14. * * A tree structure where the first element (index 0) is the root, and where the node at index i is the child of the
  15. * node at index (i-1)/2 and the father of nodes at index 2*i+1 and 2*i+2. Each node stores the index (in the array)
  16. * where the corresponding value is stored.
  17. * * A list of payloads values where each index contains a value and a lookup index. The type of the value depends on
  18. * the variant being used. The lookup is the index of the node (in the tree) that points to this value.
  19. *
  20. * Some invariants:
  21. * ```
  22. * i == heap.data[heap.data[i].index].lookup // for all indices i
  23. * i == heap.data[heap.data[i].lookup].index // for all indices i
  24. * ```
  25. *
  26. * The structure is ordered so that each node is bigger than its parent. An immediate consequence is that the
  27. * highest priority value is the one at the root. This value can be looked up in constant time (O(1)) at
  28. * `heap.data[heap.data[0].index].value`
  29. *
  30. * The structure is designed to perform the following operations with the corresponding complexities:
  31. *
  32. * * peek (get the highest priority value): O(1)
  33. * * insert (insert a value): O(log(n))
  34. * * pop (remove the highest priority value): O(log(n))
  35. * * replace (replace the highest priority value with a new value): O(log(n))
  36. * * length (get the number of elements): O(1)
  37. * * clear (remove all elements): O(1)
  38. */
  39. library Heap {
  40. using Math for *;
  41. using SafeCast for *;
  42. /**
  43. * @dev Binary heap that support values of type uint256.
  44. *
  45. * Each element of that structure uses 2 storage slots.
  46. */
  47. struct Uint256Heap {
  48. Uint256HeapNode[] data;
  49. }
  50. /**
  51. * @dev Internal node type for Uint256Heap. Stores a value of type uint256.
  52. */
  53. struct Uint256HeapNode {
  54. uint256 value;
  55. uint64 index; // position -> value
  56. uint64 lookup; // value -> position
  57. }
  58. /**
  59. * @dev Lookup the root element of the heap.
  60. */
  61. function peek(Uint256Heap storage self) internal view returns (uint256) {
  62. // self.data[0] will `ARRAY_ACCESS_OUT_OF_BOUNDS` panic if heap is empty.
  63. return _unsafeNodeAccess(self, self.data[0].index).value;
  64. }
  65. /**
  66. * @dev Remove (and return) the root element for the heap using the default 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(Uint256Heap storage self) internal returns (uint256) {
  72. return pop(self, Comparators.lt);
  73. }
  74. /**
  75. * @dev Remove (and return) the root element for the heap using the provided comparator.
  76. *
  77. * NOTE: All inserting and removal from a heap should always be done using the same comparator. Mixing comparator
  78. * during the lifecycle of a heap will result in undefined behavior.
  79. */
  80. function pop(
  81. Uint256Heap storage self,
  82. function(uint256, uint256) view returns (bool) comp
  83. ) internal returns (uint256) {
  84. unchecked {
  85. uint64 size = length(self);
  86. if (size == 0) Panic.panic(Panic.EMPTY_ARRAY_POP);
  87. uint64 last = size - 1;
  88. // get root location (in the data array) and value
  89. Uint256HeapNode storage rootNode = _unsafeNodeAccess(self, 0);
  90. uint64 rootIdx = rootNode.index;
  91. Uint256HeapNode storage rootData = _unsafeNodeAccess(self, rootIdx);
  92. Uint256HeapNode storage lastNode = _unsafeNodeAccess(self, last);
  93. uint256 rootDataValue = rootData.value;
  94. // if root is not the last element of the data array (that will get popped), reorder the data array.
  95. if (rootIdx != last) {
  96. // get details about the value stored in the last element of the array (that will get popped)
  97. uint64 lastDataIdx = lastNode.lookup;
  98. uint256 lastDataValue = lastNode.value;
  99. // copy these values to the location of the root (that is safe, and that we no longer use)
  100. rootData.value = lastDataValue;
  101. rootData.lookup = lastDataIdx;
  102. // update the tree node that used to point to that last element (value now located where the root was)
  103. _unsafeNodeAccess(self, lastDataIdx).index = rootIdx;
  104. }
  105. // get last leaf location (in the data array) and value
  106. uint64 lastIdx = lastNode.index;
  107. uint256 lastValue = _unsafeNodeAccess(self, lastIdx).value;
  108. // move the last leaf to the root, pop last leaf ...
  109. rootNode.index = lastIdx;
  110. _unsafeNodeAccess(self, lastIdx).lookup = 0;
  111. self.data.pop();
  112. // ... and heapify
  113. _siftDown(self, last, 0, lastValue, comp);
  114. // return root value
  115. return rootDataValue;
  116. }
  117. }
  118. /**
  119. * @dev Insert a new element in the heap using the default comparator.
  120. *
  121. * NOTE: All inserting and removal from a heap should always be done using the same comparator. Mixing comparator
  122. * during the lifecycle of a heap will result in undefined behavior.
  123. */
  124. function insert(Uint256Heap storage self, uint256 value) internal {
  125. insert(self, value, Comparators.lt);
  126. }
  127. /**
  128. * @dev Insert a new element in the heap using the provided comparator.
  129. *
  130. * NOTE: All inserting and removal from a heap should always be done using the same comparator. Mixing comparator
  131. * during the lifecycle of a heap will result in undefined behavior.
  132. */
  133. function insert(
  134. Uint256Heap storage self,
  135. uint256 value,
  136. function(uint256, uint256) view returns (bool) comp
  137. ) internal {
  138. uint64 size = length(self);
  139. if (size == type(uint64).max) Panic.panic(Panic.RESOURCE_ERROR);
  140. self.data.push(Uint256HeapNode({index: size, lookup: size, value: value}));
  141. _siftUp(self, size, value, comp);
  142. }
  143. /**
  144. * @dev Return the root element for the heap, and replace it with a new value, using the default comparator.
  145. * This is equivalent to using {pop} and {insert}, but requires only one rebalancing operation.
  146. *
  147. * NOTE: All inserting and removal from a heap should always be done using the same comparator. Mixing comparator
  148. * during the lifecycle of a heap will result in undefined behavior.
  149. */
  150. function replace(Uint256Heap storage self, uint256 newValue) internal returns (uint256) {
  151. return replace(self, newValue, Comparators.lt);
  152. }
  153. /**
  154. * @dev Return the root element for the heap, and replace it with a new value, using the provided comparator.
  155. * This is equivalent to using {pop} and {insert}, but requires only one rebalancing operation.
  156. *
  157. * NOTE: All inserting and removal from a heap should always be done using the same comparator. Mixing comparator
  158. * during the lifecycle of a heap will result in undefined behavior.
  159. */
  160. function replace(
  161. Uint256Heap storage self,
  162. uint256 newValue,
  163. function(uint256, uint256) view returns (bool) comp
  164. ) internal returns (uint256) {
  165. uint64 size = length(self);
  166. if (size == 0) Panic.panic(Panic.EMPTY_ARRAY_POP);
  167. // position of the node that holds the data for the root
  168. uint64 rootIdx = _unsafeNodeAccess(self, 0).index;
  169. // storage pointer to the node that holds the data for the root
  170. Uint256HeapNode storage rootData = _unsafeNodeAccess(self, rootIdx);
  171. // cache old value and replace it
  172. uint256 oldValue = rootData.value;
  173. rootData.value = newValue;
  174. // re-heapify
  175. _siftDown(self, size, 0, newValue, comp);
  176. // return old root value
  177. return oldValue;
  178. }
  179. /**
  180. * @dev Returns the number of elements in the heap.
  181. */
  182. function length(Uint256Heap storage self) internal view returns (uint64) {
  183. return self.data.length.toUint64();
  184. }
  185. /**
  186. * @dev Removes all elements in the heap.
  187. */
  188. function clear(Uint256Heap storage self) internal {
  189. Uint256HeapNode[] storage data = self.data;
  190. /// @solidity memory-safe-assembly
  191. assembly {
  192. sstore(data.slot, 0)
  193. }
  194. }
  195. /*
  196. * @dev Swap node `i` and `j` in the tree.
  197. */
  198. function _swap(Uint256Heap storage self, uint64 i, uint64 j) private {
  199. Uint256HeapNode storage ni = _unsafeNodeAccess(self, i);
  200. Uint256HeapNode storage nj = _unsafeNodeAccess(self, j);
  201. uint64 ii = ni.index;
  202. uint64 jj = nj.index;
  203. // update pointers to the data (swap the value)
  204. ni.index = jj;
  205. nj.index = ii;
  206. // update lookup pointers for consistency
  207. _unsafeNodeAccess(self, ii).lookup = j;
  208. _unsafeNodeAccess(self, jj).lookup = i;
  209. }
  210. /**
  211. * @dev Perform heap maintenance on `self`, starting at position `pos` (with the `value`), using `comp` as a
  212. * comparator, and moving toward the leafs of the underlying tree.
  213. *
  214. * NOTE: This is a private function that is called in a trusted context with already cached parameters. `length`
  215. * and `value` could be extracted from `self` and `pos`, but that would require redundant storage read. These
  216. * parameters are not verified. It is the caller role to make sure the parameters are correct.
  217. */
  218. function _siftDown(
  219. Uint256Heap storage self,
  220. uint64 size,
  221. uint64 pos,
  222. uint256 value,
  223. function(uint256, uint256) view returns (bool) comp
  224. ) private {
  225. uint256 left = 2 * pos + 1; // this could overflow uint64
  226. uint256 right = 2 * pos + 2; // this could overflow uint64
  227. if (right < size) {
  228. // the check guarantees that `left` and `right` are both valid uint64
  229. uint64 lIndex = uint64(left);
  230. uint64 rIndex = uint64(right);
  231. uint256 lValue = _unsafeNodeAccess(self, _unsafeNodeAccess(self, lIndex).index).value;
  232. uint256 rValue = _unsafeNodeAccess(self, _unsafeNodeAccess(self, rIndex).index).value;
  233. if (comp(lValue, value) || comp(rValue, value)) {
  234. uint64 index = uint64(comp(lValue, rValue).ternary(lIndex, rIndex));
  235. _swap(self, pos, index);
  236. _siftDown(self, size, index, value, comp);
  237. }
  238. } else if (left < size) {
  239. // the check guarantees that `left` is a valid uint64
  240. uint64 lIndex = uint64(left);
  241. uint256 lValue = _unsafeNodeAccess(self, _unsafeNodeAccess(self, lIndex).index).value;
  242. if (comp(lValue, value)) {
  243. _swap(self, pos, lIndex);
  244. _siftDown(self, size, lIndex, value, comp);
  245. }
  246. }
  247. }
  248. /**
  249. * @dev Perform heap maintenance on `self`, starting at position `pos` (with the `value`), using `comp` as a
  250. * comparator, and moving toward the root of the underlying tree.
  251. *
  252. * NOTE: This is a private function that is called in a trusted context with already cached parameters. `value`
  253. * could be extracted from `self` and `pos`, but that would require redundant storage read. These parameters are not
  254. * verified. It is the caller role to make sure the parameters are correct.
  255. */
  256. function _siftUp(
  257. Uint256Heap storage self,
  258. uint64 pos,
  259. uint256 value,
  260. function(uint256, uint256) view returns (bool) comp
  261. ) private {
  262. unchecked {
  263. while (pos > 0) {
  264. uint64 parent = (pos - 1) / 2;
  265. uint256 parentValue = _unsafeNodeAccess(self, _unsafeNodeAccess(self, parent).index).value;
  266. if (comp(parentValue, value)) break;
  267. _swap(self, pos, parent);
  268. pos = parent;
  269. }
  270. }
  271. }
  272. function _unsafeNodeAccess(
  273. Uint256Heap storage self,
  274. uint64 pos
  275. ) private pure returns (Uint256HeapNode storage result) {
  276. assembly ("memory-safe") {
  277. mstore(0x00, self.slot)
  278. result.slot := add(keccak256(0x00, 0x20), mul(pos, 2))
  279. }
  280. }
  281. /**
  282. * @dev Binary heap that support values of type uint208.
  283. *
  284. * Each element of that structure uses 1 storage slots.
  285. */
  286. struct Uint208Heap {
  287. Uint208HeapNode[] data;
  288. }
  289. /**
  290. * @dev Internal node type for Uint208Heap. Stores a value of type uint208.
  291. */
  292. struct Uint208HeapNode {
  293. uint208 value;
  294. uint24 index; // position -> value
  295. uint24 lookup; // value -> position
  296. }
  297. /**
  298. * @dev Lookup the root element of the heap.
  299. */
  300. function peek(Uint208Heap storage self) internal view returns (uint208) {
  301. // self.data[0] will `ARRAY_ACCESS_OUT_OF_BOUNDS` panic if heap is empty.
  302. return _unsafeNodeAccess(self, self.data[0].index).value;
  303. }
  304. /**
  305. * @dev Remove (and return) the root element for the heap using the default comparator.
  306. *
  307. * NOTE: All inserting and removal from a heap should always be done using the same comparator. Mixing comparator
  308. * during the lifecycle of a heap will result in undefined behavior.
  309. */
  310. function pop(Uint208Heap storage self) internal returns (uint208) {
  311. return pop(self, Comparators.lt);
  312. }
  313. /**
  314. * @dev Remove (and return) the root element for the heap using the provided comparator.
  315. *
  316. * NOTE: All inserting and removal from a heap should always be done using the same comparator. Mixing comparator
  317. * during the lifecycle of a heap will result in undefined behavior.
  318. */
  319. function pop(
  320. Uint208Heap storage self,
  321. function(uint256, uint256) view returns (bool) comp
  322. ) internal returns (uint208) {
  323. unchecked {
  324. uint24 size = length(self);
  325. if (size == 0) Panic.panic(Panic.EMPTY_ARRAY_POP);
  326. uint24 last = size - 1;
  327. // get root location (in the data array) and value
  328. Uint208HeapNode storage rootNode = _unsafeNodeAccess(self, 0);
  329. uint24 rootIdx = rootNode.index;
  330. Uint208HeapNode storage rootData = _unsafeNodeAccess(self, rootIdx);
  331. Uint208HeapNode storage lastNode = _unsafeNodeAccess(self, last);
  332. uint208 rootDataValue = rootData.value;
  333. // if root is not the last element of the data array (that will get popped), reorder the data array.
  334. if (rootIdx != last) {
  335. // get details about the value stored in the last element of the array (that will get popped)
  336. uint24 lastDataIdx = lastNode.lookup;
  337. uint208 lastDataValue = lastNode.value;
  338. // copy these values to the location of the root (that is safe, and that we no longer use)
  339. rootData.value = lastDataValue;
  340. rootData.lookup = lastDataIdx;
  341. // update the tree node that used to point to that last element (value now located where the root was)
  342. _unsafeNodeAccess(self, lastDataIdx).index = rootIdx;
  343. }
  344. // get last leaf location (in the data array) and value
  345. uint24 lastIdx = lastNode.index;
  346. uint208 lastValue = _unsafeNodeAccess(self, lastIdx).value;
  347. // move the last leaf to the root, pop last leaf ...
  348. rootNode.index = lastIdx;
  349. _unsafeNodeAccess(self, lastIdx).lookup = 0;
  350. self.data.pop();
  351. // ... and heapify
  352. _siftDown(self, last, 0, lastValue, comp);
  353. // return root value
  354. return rootDataValue;
  355. }
  356. }
  357. /**
  358. * @dev Insert a new element in the heap using the default comparator.
  359. *
  360. * NOTE: All inserting and removal from a heap should always be done using the same comparator. Mixing comparator
  361. * during the lifecycle of a heap will result in undefined behavior.
  362. */
  363. function insert(Uint208Heap storage self, uint208 value) internal {
  364. insert(self, value, Comparators.lt);
  365. }
  366. /**
  367. * @dev Insert a new element in the heap using the provided comparator.
  368. *
  369. * NOTE: All inserting and removal from a heap should always be done using the same comparator. Mixing comparator
  370. * during the lifecycle of a heap will result in undefined behavior.
  371. */
  372. function insert(
  373. Uint208Heap storage self,
  374. uint208 value,
  375. function(uint256, uint256) view returns (bool) comp
  376. ) internal {
  377. uint24 size = length(self);
  378. if (size == type(uint24).max) Panic.panic(Panic.RESOURCE_ERROR);
  379. self.data.push(Uint208HeapNode({index: size, lookup: size, value: value}));
  380. _siftUp(self, size, value, comp);
  381. }
  382. /**
  383. * @dev Return the root element for the heap, and replace it with a new value, using the default comparator.
  384. * This is equivalent to using {pop} and {insert}, but requires only one rebalancing operation.
  385. *
  386. * NOTE: All inserting and removal from a heap should always be done using the same comparator. Mixing comparator
  387. * during the lifecycle of a heap will result in undefined behavior.
  388. */
  389. function replace(Uint208Heap storage self, uint208 newValue) internal returns (uint208) {
  390. return replace(self, newValue, Comparators.lt);
  391. }
  392. /**
  393. * @dev Return the root element for the heap, and replace it with a new value, using the provided comparator.
  394. * This is equivalent to using {pop} and {insert}, but requires only one rebalancing operation.
  395. *
  396. * NOTE: All inserting and removal from a heap should always be done using the same comparator. Mixing comparator
  397. * during the lifecycle of a heap will result in undefined behavior.
  398. */
  399. function replace(
  400. Uint208Heap storage self,
  401. uint208 newValue,
  402. function(uint256, uint256) view returns (bool) comp
  403. ) internal returns (uint208) {
  404. uint24 size = length(self);
  405. if (size == 0) Panic.panic(Panic.EMPTY_ARRAY_POP);
  406. // position of the node that holds the data for the root
  407. uint24 rootIdx = _unsafeNodeAccess(self, 0).index;
  408. // storage pointer to the node that holds the data for the root
  409. Uint208HeapNode storage rootData = _unsafeNodeAccess(self, rootIdx);
  410. // cache old value and replace it
  411. uint208 oldValue = rootData.value;
  412. rootData.value = newValue;
  413. // re-heapify
  414. _siftDown(self, size, 0, newValue, comp);
  415. // return old root value
  416. return oldValue;
  417. }
  418. /**
  419. * @dev Returns the number of elements in the heap.
  420. */
  421. function length(Uint208Heap storage self) internal view returns (uint24) {
  422. return self.data.length.toUint24();
  423. }
  424. /**
  425. * @dev Removes all elements in the heap.
  426. */
  427. function clear(Uint208Heap storage self) internal {
  428. Uint208HeapNode[] storage data = self.data;
  429. /// @solidity memory-safe-assembly
  430. assembly {
  431. sstore(data.slot, 0)
  432. }
  433. }
  434. /*
  435. * @dev Swap node `i` and `j` in the tree.
  436. */
  437. function _swap(Uint208Heap storage self, uint24 i, uint24 j) private {
  438. Uint208HeapNode storage ni = _unsafeNodeAccess(self, i);
  439. Uint208HeapNode storage nj = _unsafeNodeAccess(self, j);
  440. uint24 ii = ni.index;
  441. uint24 jj = nj.index;
  442. // update pointers to the data (swap the value)
  443. ni.index = jj;
  444. nj.index = ii;
  445. // update lookup pointers for consistency
  446. _unsafeNodeAccess(self, ii).lookup = j;
  447. _unsafeNodeAccess(self, jj).lookup = i;
  448. }
  449. /**
  450. * @dev Perform heap maintenance on `self`, starting at position `pos` (with the `value`), using `comp` as a
  451. * comparator, and moving toward the leafs of the underlying tree.
  452. *
  453. * NOTE: This is a private function that is called in a trusted context with already cached parameters. `length`
  454. * and `value` could be extracted from `self` and `pos`, but that would require redundant storage read. These
  455. * parameters are not verified. It is the caller role to make sure the parameters are correct.
  456. */
  457. function _siftDown(
  458. Uint208Heap storage self,
  459. uint24 size,
  460. uint24 pos,
  461. uint208 value,
  462. function(uint256, uint256) view returns (bool) comp
  463. ) private {
  464. uint256 left = 2 * pos + 1; // this could overflow uint24
  465. uint256 right = 2 * pos + 2; // this could overflow uint24
  466. if (right < size) {
  467. // the check guarantees that `left` and `right` are both valid uint24
  468. uint24 lIndex = uint24(left);
  469. uint24 rIndex = uint24(right);
  470. uint208 lValue = _unsafeNodeAccess(self, _unsafeNodeAccess(self, lIndex).index).value;
  471. uint208 rValue = _unsafeNodeAccess(self, _unsafeNodeAccess(self, rIndex).index).value;
  472. if (comp(lValue, value) || comp(rValue, value)) {
  473. uint24 index = uint24(comp(lValue, rValue).ternary(lIndex, rIndex));
  474. _swap(self, pos, index);
  475. _siftDown(self, size, index, value, comp);
  476. }
  477. } else if (left < size) {
  478. // the check guarantees that `left` is a valid uint24
  479. uint24 lIndex = uint24(left);
  480. uint208 lValue = _unsafeNodeAccess(self, _unsafeNodeAccess(self, lIndex).index).value;
  481. if (comp(lValue, value)) {
  482. _swap(self, pos, lIndex);
  483. _siftDown(self, size, lIndex, value, comp);
  484. }
  485. }
  486. }
  487. /**
  488. * @dev Perform heap maintenance on `self`, starting at position `pos` (with the `value`), using `comp` as a
  489. * comparator, and moving toward the root of the underlying tree.
  490. *
  491. * NOTE: This is a private function that is called in a trusted context with already cached parameters. `value`
  492. * could be extracted from `self` and `pos`, but that would require redundant storage read. These parameters are not
  493. * verified. It is the caller role to make sure the parameters are correct.
  494. */
  495. function _siftUp(
  496. Uint208Heap storage self,
  497. uint24 pos,
  498. uint208 value,
  499. function(uint256, uint256) view returns (bool) comp
  500. ) private {
  501. unchecked {
  502. while (pos > 0) {
  503. uint24 parent = (pos - 1) / 2;
  504. uint208 parentValue = _unsafeNodeAccess(self, _unsafeNodeAccess(self, parent).index).value;
  505. if (comp(parentValue, value)) break;
  506. _swap(self, pos, parent);
  507. pos = parent;
  508. }
  509. }
  510. }
  511. function _unsafeNodeAccess(
  512. Uint208Heap storage self,
  513. uint24 pos
  514. ) private pure returns (Uint208HeapNode storage result) {
  515. assembly ("memory-safe") {
  516. mstore(0x00, self.slot)
  517. result.slot := add(keccak256(0x00, 0x20), pos)
  518. }
  519. }
  520. }