Heap.sol 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576
  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 supports 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. assembly ("memory-safe") {
  190. sstore(data.slot, 0)
  191. }
  192. }
  193. /**
  194. * @dev Swap node `i` and `j` in the tree.
  195. */
  196. function _swap(Uint256Heap storage self, uint64 i, uint64 j) private {
  197. Uint256HeapNode storage ni = _unsafeNodeAccess(self, i);
  198. Uint256HeapNode storage nj = _unsafeNodeAccess(self, j);
  199. uint64 ii = ni.index;
  200. uint64 jj = nj.index;
  201. // update pointers to the data (swap the value)
  202. ni.index = jj;
  203. nj.index = ii;
  204. // update lookup pointers for consistency
  205. _unsafeNodeAccess(self, ii).lookup = j;
  206. _unsafeNodeAccess(self, jj).lookup = i;
  207. }
  208. /**
  209. * @dev Perform heap maintenance on `self`, starting at position `pos` (with the `value`), using `comp` as a
  210. * comparator, and moving toward the leaves of the underlying tree.
  211. *
  212. * NOTE: This is a private function that is called in a trusted context with already cached parameters. `length`
  213. * and `value` could be extracted from `self` and `pos`, but that would require redundant storage read. These
  214. * parameters are not verified. It is the caller role to make sure the parameters are correct.
  215. */
  216. function _siftDown(
  217. Uint256Heap storage self,
  218. uint64 size,
  219. uint64 pos,
  220. uint256 value,
  221. function(uint256, uint256) view returns (bool) comp
  222. ) private {
  223. uint256 left = 2 * pos + 1; // this could overflow uint64
  224. uint256 right = 2 * pos + 2; // this could overflow uint64
  225. if (right < size) {
  226. // the check guarantees that `left` and `right` are both valid uint64
  227. uint64 lIndex = uint64(left);
  228. uint64 rIndex = uint64(right);
  229. uint256 lValue = _unsafeNodeAccess(self, _unsafeNodeAccess(self, lIndex).index).value;
  230. uint256 rValue = _unsafeNodeAccess(self, _unsafeNodeAccess(self, rIndex).index).value;
  231. if (comp(lValue, value) || comp(rValue, value)) {
  232. uint64 index = uint64(comp(lValue, rValue).ternary(lIndex, rIndex));
  233. _swap(self, pos, index);
  234. _siftDown(self, size, index, value, comp);
  235. }
  236. } else if (left < size) {
  237. // the check guarantees that `left` is a valid uint64
  238. uint64 lIndex = uint64(left);
  239. uint256 lValue = _unsafeNodeAccess(self, _unsafeNodeAccess(self, lIndex).index).value;
  240. if (comp(lValue, value)) {
  241. _swap(self, pos, lIndex);
  242. _siftDown(self, size, lIndex, value, comp);
  243. }
  244. }
  245. }
  246. /**
  247. * @dev Perform heap maintenance on `self`, starting at position `pos` (with the `value`), using `comp` as a
  248. * comparator, and moving toward the root of the underlying tree.
  249. *
  250. * NOTE: This is a private function that is called in a trusted context with already cached parameters. `value`
  251. * could be extracted from `self` and `pos`, but that would require redundant storage read. These parameters are not
  252. * verified. It is the caller role to make sure the parameters are correct.
  253. */
  254. function _siftUp(
  255. Uint256Heap storage self,
  256. uint64 pos,
  257. uint256 value,
  258. function(uint256, uint256) view returns (bool) comp
  259. ) private {
  260. unchecked {
  261. while (pos > 0) {
  262. uint64 parent = (pos - 1) / 2;
  263. uint256 parentValue = _unsafeNodeAccess(self, _unsafeNodeAccess(self, parent).index).value;
  264. if (comp(parentValue, value)) break;
  265. _swap(self, pos, parent);
  266. pos = parent;
  267. }
  268. }
  269. }
  270. function _unsafeNodeAccess(
  271. Uint256Heap storage self,
  272. uint64 pos
  273. ) private pure returns (Uint256HeapNode storage result) {
  274. assembly ("memory-safe") {
  275. mstore(0x00, self.slot)
  276. result.slot := add(keccak256(0x00, 0x20), mul(pos, 2))
  277. }
  278. }
  279. /**
  280. * @dev Binary heap that supports values of type uint208.
  281. *
  282. * Each element of that structure uses 1 storage slots.
  283. */
  284. struct Uint208Heap {
  285. Uint208HeapNode[] data;
  286. }
  287. /**
  288. * @dev Internal node type for Uint208Heap. Stores a value of type uint208.
  289. */
  290. struct Uint208HeapNode {
  291. uint208 value;
  292. uint24 index; // position -> value
  293. uint24 lookup; // value -> position
  294. }
  295. /**
  296. * @dev Lookup the root element of the heap.
  297. */
  298. function peek(Uint208Heap storage self) internal view returns (uint208) {
  299. // self.data[0] will `ARRAY_ACCESS_OUT_OF_BOUNDS` panic if heap is empty.
  300. return _unsafeNodeAccess(self, self.data[0].index).value;
  301. }
  302. /**
  303. * @dev Remove (and return) the root element for the heap using the default comparator.
  304. *
  305. * NOTE: All inserting and removal from a heap should always be done using the same comparator. Mixing comparator
  306. * during the lifecycle of a heap will result in undefined behavior.
  307. */
  308. function pop(Uint208Heap storage self) internal returns (uint208) {
  309. return pop(self, Comparators.lt);
  310. }
  311. /**
  312. * @dev Remove (and return) the root element for the heap using the provided comparator.
  313. *
  314. * NOTE: All inserting and removal from a heap should always be done using the same comparator. Mixing comparator
  315. * during the lifecycle of a heap will result in undefined behavior.
  316. */
  317. function pop(
  318. Uint208Heap storage self,
  319. function(uint256, uint256) view returns (bool) comp
  320. ) internal returns (uint208) {
  321. unchecked {
  322. uint24 size = length(self);
  323. if (size == 0) Panic.panic(Panic.EMPTY_ARRAY_POP);
  324. uint24 last = size - 1;
  325. // get root location (in the data array) and value
  326. Uint208HeapNode storage rootNode = _unsafeNodeAccess(self, 0);
  327. uint24 rootIdx = rootNode.index;
  328. Uint208HeapNode storage rootData = _unsafeNodeAccess(self, rootIdx);
  329. Uint208HeapNode storage lastNode = _unsafeNodeAccess(self, last);
  330. uint208 rootDataValue = rootData.value;
  331. // if root is not the last element of the data array (that will get popped), reorder the data array.
  332. if (rootIdx != last) {
  333. // get details about the value stored in the last element of the array (that will get popped)
  334. uint24 lastDataIdx = lastNode.lookup;
  335. uint208 lastDataValue = lastNode.value;
  336. // copy these values to the location of the root (that is safe, and that we no longer use)
  337. rootData.value = lastDataValue;
  338. rootData.lookup = lastDataIdx;
  339. // update the tree node that used to point to that last element (value now located where the root was)
  340. _unsafeNodeAccess(self, lastDataIdx).index = rootIdx;
  341. }
  342. // get last leaf location (in the data array) and value
  343. uint24 lastIdx = lastNode.index;
  344. uint208 lastValue = _unsafeNodeAccess(self, lastIdx).value;
  345. // move the last leaf to the root, pop last leaf ...
  346. rootNode.index = lastIdx;
  347. _unsafeNodeAccess(self, lastIdx).lookup = 0;
  348. self.data.pop();
  349. // ... and heapify
  350. _siftDown(self, last, 0, lastValue, comp);
  351. // return root value
  352. return rootDataValue;
  353. }
  354. }
  355. /**
  356. * @dev Insert a new element in the heap using the default comparator.
  357. *
  358. * NOTE: All inserting and removal from a heap should always be done using the same comparator. Mixing comparator
  359. * during the lifecycle of a heap will result in undefined behavior.
  360. */
  361. function insert(Uint208Heap storage self, uint208 value) internal {
  362. insert(self, value, Comparators.lt);
  363. }
  364. /**
  365. * @dev Insert a new element in the heap using the provided comparator.
  366. *
  367. * NOTE: All inserting and removal from a heap should always be done using the same comparator. Mixing comparator
  368. * during the lifecycle of a heap will result in undefined behavior.
  369. */
  370. function insert(
  371. Uint208Heap storage self,
  372. uint208 value,
  373. function(uint256, uint256) view returns (bool) comp
  374. ) internal {
  375. uint24 size = length(self);
  376. if (size == type(uint24).max) Panic.panic(Panic.RESOURCE_ERROR);
  377. self.data.push(Uint208HeapNode({index: size, lookup: size, value: value}));
  378. _siftUp(self, size, value, comp);
  379. }
  380. /**
  381. * @dev Return the root element for the heap, and replace it with a new value, using the default comparator.
  382. * This is equivalent to using {pop} and {insert}, but requires only one rebalancing operation.
  383. *
  384. * NOTE: All inserting and removal from a heap should always be done using the same comparator. Mixing comparator
  385. * during the lifecycle of a heap will result in undefined behavior.
  386. */
  387. function replace(Uint208Heap storage self, uint208 newValue) internal returns (uint208) {
  388. return replace(self, newValue, Comparators.lt);
  389. }
  390. /**
  391. * @dev Return the root element for the heap, and replace it with a new value, using the provided comparator.
  392. * This is equivalent to using {pop} and {insert}, but requires only one rebalancing operation.
  393. *
  394. * NOTE: All inserting and removal from a heap should always be done using the same comparator. Mixing comparator
  395. * during the lifecycle of a heap will result in undefined behavior.
  396. */
  397. function replace(
  398. Uint208Heap storage self,
  399. uint208 newValue,
  400. function(uint256, uint256) view returns (bool) comp
  401. ) internal returns (uint208) {
  402. uint24 size = length(self);
  403. if (size == 0) Panic.panic(Panic.EMPTY_ARRAY_POP);
  404. // position of the node that holds the data for the root
  405. uint24 rootIdx = _unsafeNodeAccess(self, 0).index;
  406. // storage pointer to the node that holds the data for the root
  407. Uint208HeapNode storage rootData = _unsafeNodeAccess(self, rootIdx);
  408. // cache old value and replace it
  409. uint208 oldValue = rootData.value;
  410. rootData.value = newValue;
  411. // re-heapify
  412. _siftDown(self, size, 0, newValue, comp);
  413. // return old root value
  414. return oldValue;
  415. }
  416. /**
  417. * @dev Returns the number of elements in the heap.
  418. */
  419. function length(Uint208Heap storage self) internal view returns (uint24) {
  420. return self.data.length.toUint24();
  421. }
  422. /**
  423. * @dev Removes all elements in the heap.
  424. */
  425. function clear(Uint208Heap storage self) internal {
  426. Uint208HeapNode[] storage data = self.data;
  427. assembly ("memory-safe") {
  428. sstore(data.slot, 0)
  429. }
  430. }
  431. /**
  432. * @dev Swap node `i` and `j` in the tree.
  433. */
  434. function _swap(Uint208Heap storage self, uint24 i, uint24 j) private {
  435. Uint208HeapNode storage ni = _unsafeNodeAccess(self, i);
  436. Uint208HeapNode storage nj = _unsafeNodeAccess(self, j);
  437. uint24 ii = ni.index;
  438. uint24 jj = nj.index;
  439. // update pointers to the data (swap the value)
  440. ni.index = jj;
  441. nj.index = ii;
  442. // update lookup pointers for consistency
  443. _unsafeNodeAccess(self, ii).lookup = j;
  444. _unsafeNodeAccess(self, jj).lookup = i;
  445. }
  446. /**
  447. * @dev Perform heap maintenance on `self`, starting at position `pos` (with the `value`), using `comp` as a
  448. * comparator, and moving toward the leaves of the underlying tree.
  449. *
  450. * NOTE: This is a private function that is called in a trusted context with already cached parameters. `length`
  451. * and `value` could be extracted from `self` and `pos`, but that would require redundant storage read. These
  452. * parameters are not verified. It is the caller role to make sure the parameters are correct.
  453. */
  454. function _siftDown(
  455. Uint208Heap storage self,
  456. uint24 size,
  457. uint24 pos,
  458. uint208 value,
  459. function(uint256, uint256) view returns (bool) comp
  460. ) private {
  461. uint256 left = 2 * pos + 1; // this could overflow uint24
  462. uint256 right = 2 * pos + 2; // this could overflow uint24
  463. if (right < size) {
  464. // the check guarantees that `left` and `right` are both valid uint24
  465. uint24 lIndex = uint24(left);
  466. uint24 rIndex = uint24(right);
  467. uint208 lValue = _unsafeNodeAccess(self, _unsafeNodeAccess(self, lIndex).index).value;
  468. uint208 rValue = _unsafeNodeAccess(self, _unsafeNodeAccess(self, rIndex).index).value;
  469. if (comp(lValue, value) || comp(rValue, value)) {
  470. uint24 index = uint24(comp(lValue, rValue).ternary(lIndex, rIndex));
  471. _swap(self, pos, index);
  472. _siftDown(self, size, index, value, comp);
  473. }
  474. } else if (left < size) {
  475. // the check guarantees that `left` is a valid uint24
  476. uint24 lIndex = uint24(left);
  477. uint208 lValue = _unsafeNodeAccess(self, _unsafeNodeAccess(self, lIndex).index).value;
  478. if (comp(lValue, value)) {
  479. _swap(self, pos, lIndex);
  480. _siftDown(self, size, lIndex, value, comp);
  481. }
  482. }
  483. }
  484. /**
  485. * @dev Perform heap maintenance on `self`, starting at position `pos` (with the `value`), using `comp` as a
  486. * comparator, and moving toward the root of the underlying tree.
  487. *
  488. * NOTE: This is a private function that is called in a trusted context with already cached parameters. `value`
  489. * could be extracted from `self` and `pos`, but that would require redundant storage read. These parameters are not
  490. * verified. It is the caller role to make sure the parameters are correct.
  491. */
  492. function _siftUp(
  493. Uint208Heap storage self,
  494. uint24 pos,
  495. uint208 value,
  496. function(uint256, uint256) view returns (bool) comp
  497. ) private {
  498. unchecked {
  499. while (pos > 0) {
  500. uint24 parent = (pos - 1) / 2;
  501. uint208 parentValue = _unsafeNodeAccess(self, _unsafeNodeAccess(self, parent).index).value;
  502. if (comp(parentValue, value)) break;
  503. _swap(self, pos, parent);
  504. pos = parent;
  505. }
  506. }
  507. }
  508. function _unsafeNodeAccess(
  509. Uint208Heap storage self,
  510. uint24 pos
  511. ) private pure returns (Uint208HeapNode storage result) {
  512. assembly ("memory-safe") {
  513. mstore(0x00, self.slot)
  514. result.slot := add(keccak256(0x00, 0x20), pos)
  515. }
  516. }
  517. }