Heap.sol 23 KB

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