Arrays.sol 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  1. // SPDX-License-Identifier: MIT
  2. // OpenZeppelin Contracts (last updated v5.0.0) (utils/Arrays.sol)
  3. // This file was procedurally generated from scripts/generate/templates/Arrays.js.
  4. pragma solidity ^0.8.20;
  5. import {Comparators} from "./Comparators.sol";
  6. import {SlotDerivation} from "./SlotDerivation.sol";
  7. import {StorageSlot} from "./StorageSlot.sol";
  8. import {Math} from "./math/Math.sol";
  9. /**
  10. * @dev Collection of functions related to array types.
  11. */
  12. library Arrays {
  13. using SlotDerivation for bytes32;
  14. using StorageSlot for bytes32;
  15. /**
  16. * @dev Sort an array of uint256 (in memory) following the provided comparator function.
  17. *
  18. * This function does the sorting "in place", meaning that it overrides the input. The object is returned for
  19. * convenience, but that returned value can be discarded safely if the caller has a memory pointer to the array.
  20. *
  21. * NOTE: this function's cost is `O(n · log(n))` in average and `O(n²)` in the worst case, with n the length of the
  22. * array. Using it in view functions that are executed through `eth_call` is safe, but one should be very careful
  23. * when executing this as part of a transaction. If the array being sorted is too large, the sort operation may
  24. * consume more gas than is available in a block, leading to potential DoS.
  25. */
  26. function sort(
  27. uint256[] memory array,
  28. function(uint256, uint256) pure returns (bool) comp
  29. ) internal pure returns (uint256[] memory) {
  30. _quickSort(_begin(array), _end(array), comp);
  31. return array;
  32. }
  33. /**
  34. * @dev Variant of {sort} that sorts an array of uint256 in increasing order.
  35. */
  36. function sort(uint256[] memory array) internal pure returns (uint256[] memory) {
  37. sort(array, Comparators.lt);
  38. return array;
  39. }
  40. /**
  41. * @dev Sort an array of address (in memory) following the provided comparator function.
  42. *
  43. * This function does the sorting "in place", meaning that it overrides the input. The object is returned for
  44. * convenience, but that returned value can be discarded safely if the caller has a memory pointer to the array.
  45. *
  46. * NOTE: this function's cost is `O(n · log(n))` in average and `O(n²)` in the worst case, with n the length of the
  47. * array. Using it in view functions that are executed through `eth_call` is safe, but one should be very careful
  48. * when executing this as part of a transaction. If the array being sorted is too large, the sort operation may
  49. * consume more gas than is available in a block, leading to potential DoS.
  50. */
  51. function sort(
  52. address[] memory array,
  53. function(address, address) pure returns (bool) comp
  54. ) internal pure returns (address[] memory) {
  55. sort(_castToUint256Array(array), _castToUint256Comp(comp));
  56. return array;
  57. }
  58. /**
  59. * @dev Variant of {sort} that sorts an array of address in increasing order.
  60. */
  61. function sort(address[] memory array) internal pure returns (address[] memory) {
  62. sort(_castToUint256Array(array), Comparators.lt);
  63. return array;
  64. }
  65. /**
  66. * @dev Sort an array of bytes32 (in memory) following the provided comparator function.
  67. *
  68. * This function does the sorting "in place", meaning that it overrides the input. The object is returned for
  69. * convenience, but that returned value can be discarded safely if the caller has a memory pointer to the array.
  70. *
  71. * NOTE: this function's cost is `O(n · log(n))` in average and `O(n²)` in the worst case, with n the length of the
  72. * array. Using it in view functions that are executed through `eth_call` is safe, but one should be very careful
  73. * when executing this as part of a transaction. If the array being sorted is too large, the sort operation may
  74. * consume more gas than is available in a block, leading to potential DoS.
  75. */
  76. function sort(
  77. bytes32[] memory array,
  78. function(bytes32, bytes32) pure returns (bool) comp
  79. ) internal pure returns (bytes32[] memory) {
  80. sort(_castToUint256Array(array), _castToUint256Comp(comp));
  81. return array;
  82. }
  83. /**
  84. * @dev Variant of {sort} that sorts an array of bytes32 in increasing order.
  85. */
  86. function sort(bytes32[] memory array) internal pure returns (bytes32[] memory) {
  87. sort(_castToUint256Array(array), Comparators.lt);
  88. return array;
  89. }
  90. /**
  91. * @dev Performs a quick sort of a segment of memory. The segment sorted starts at `begin` (inclusive), and stops
  92. * at end (exclusive). Sorting follows the `comp` comparator.
  93. *
  94. * Invariant: `begin <= end`. This is the case when initially called by {sort} and is preserved in subcalls.
  95. *
  96. * IMPORTANT: Memory locations between `begin` and `end` are not validated/zeroed. This function should
  97. * be used only if the limits are within a memory array.
  98. */
  99. function _quickSort(uint256 begin, uint256 end, function(uint256, uint256) pure returns (bool) comp) private pure {
  100. unchecked {
  101. if (end - begin < 0x40) return;
  102. // Use first element as pivot
  103. uint256 pivot = _mload(begin);
  104. // Position where the pivot should be at the end of the loop
  105. uint256 pos = begin;
  106. for (uint256 it = begin + 0x20; it < end; it += 0x20) {
  107. if (comp(_mload(it), pivot)) {
  108. // If the value stored at the iterator's position comes before the pivot, we increment the
  109. // position of the pivot and move the value there.
  110. pos += 0x20;
  111. _swap(pos, it);
  112. }
  113. }
  114. _swap(begin, pos); // Swap pivot into place
  115. _quickSort(begin, pos, comp); // Sort the left side of the pivot
  116. _quickSort(pos + 0x20, end, comp); // Sort the right side of the pivot
  117. }
  118. }
  119. /**
  120. * @dev Pointer to the memory location of the first element of `array`.
  121. */
  122. function _begin(uint256[] memory array) private pure returns (uint256 ptr) {
  123. /// @solidity memory-safe-assembly
  124. assembly {
  125. ptr := add(array, 0x20)
  126. }
  127. }
  128. /**
  129. * @dev Pointer to the memory location of the first memory word (32bytes) after `array`. This is the memory word
  130. * that comes just after the last element of the array.
  131. */
  132. function _end(uint256[] memory array) private pure returns (uint256 ptr) {
  133. unchecked {
  134. return _begin(array) + array.length * 0x20;
  135. }
  136. }
  137. /**
  138. * @dev Load memory word (as a uint256) at location `ptr`.
  139. */
  140. function _mload(uint256 ptr) private pure returns (uint256 value) {
  141. assembly {
  142. value := mload(ptr)
  143. }
  144. }
  145. /**
  146. * @dev Swaps the elements memory location `ptr1` and `ptr2`.
  147. */
  148. function _swap(uint256 ptr1, uint256 ptr2) private pure {
  149. assembly {
  150. let value1 := mload(ptr1)
  151. let value2 := mload(ptr2)
  152. mstore(ptr1, value2)
  153. mstore(ptr2, value1)
  154. }
  155. }
  156. /// @dev Helper: low level cast address memory array to uint256 memory array
  157. function _castToUint256Array(address[] memory input) private pure returns (uint256[] memory output) {
  158. assembly {
  159. output := input
  160. }
  161. }
  162. /// @dev Helper: low level cast bytes32 memory array to uint256 memory array
  163. function _castToUint256Array(bytes32[] memory input) private pure returns (uint256[] memory output) {
  164. assembly {
  165. output := input
  166. }
  167. }
  168. /// @dev Helper: low level cast address comp function to uint256 comp function
  169. function _castToUint256Comp(
  170. function(address, address) pure returns (bool) input
  171. ) private pure returns (function(uint256, uint256) pure returns (bool) output) {
  172. assembly {
  173. output := input
  174. }
  175. }
  176. /// @dev Helper: low level cast bytes32 comp function to uint256 comp function
  177. function _castToUint256Comp(
  178. function(bytes32, bytes32) pure returns (bool) input
  179. ) private pure returns (function(uint256, uint256) pure returns (bool) output) {
  180. assembly {
  181. output := input
  182. }
  183. }
  184. /**
  185. * @dev Searches a sorted `array` and returns the first index that contains
  186. * a value greater or equal to `element`. If no such index exists (i.e. all
  187. * values in the array are strictly less than `element`), the array length is
  188. * returned. Time complexity O(log n).
  189. *
  190. * NOTE: The `array` is expected to be sorted in ascending order, and to
  191. * contain no repeated elements.
  192. *
  193. * IMPORTANT: Deprecated. This implementation behaves as {lowerBound} but lacks
  194. * support for repeated elements in the array. The {lowerBound} function should
  195. * be used instead.
  196. */
  197. function findUpperBound(uint256[] storage array, uint256 element) internal view returns (uint256) {
  198. uint256 low = 0;
  199. uint256 high = array.length;
  200. if (high == 0) {
  201. return 0;
  202. }
  203. while (low < high) {
  204. uint256 mid = Math.average(low, high);
  205. // Note that mid will always be strictly less than high (i.e. it will be a valid array index)
  206. // because Math.average rounds towards zero (it does integer division with truncation).
  207. if (unsafeAccess(array, mid).value > element) {
  208. high = mid;
  209. } else {
  210. low = mid + 1;
  211. }
  212. }
  213. // At this point `low` is the exclusive upper bound. We will return the inclusive upper bound.
  214. if (low > 0 && unsafeAccess(array, low - 1).value == element) {
  215. return low - 1;
  216. } else {
  217. return low;
  218. }
  219. }
  220. /**
  221. * @dev Searches an `array` sorted in ascending order and returns the first
  222. * index that contains a value greater or equal than `element`. If no such index
  223. * exists (i.e. all values in the array are strictly less than `element`), the array
  224. * length is returned. Time complexity O(log n).
  225. *
  226. * See C++'s https://en.cppreference.com/w/cpp/algorithm/lower_bound[lower_bound].
  227. */
  228. function lowerBound(uint256[] storage array, uint256 element) internal view returns (uint256) {
  229. uint256 low = 0;
  230. uint256 high = array.length;
  231. if (high == 0) {
  232. return 0;
  233. }
  234. while (low < high) {
  235. uint256 mid = Math.average(low, high);
  236. // Note that mid will always be strictly less than high (i.e. it will be a valid array index)
  237. // because Math.average rounds towards zero (it does integer division with truncation).
  238. if (unsafeAccess(array, mid).value < element) {
  239. // this cannot overflow because mid < high
  240. unchecked {
  241. low = mid + 1;
  242. }
  243. } else {
  244. high = mid;
  245. }
  246. }
  247. return low;
  248. }
  249. /**
  250. * @dev Searches an `array` sorted in ascending order and returns the first
  251. * index that contains a value strictly greater than `element`. If no such index
  252. * exists (i.e. all values in the array are strictly less than `element`), the array
  253. * length is returned. Time complexity O(log n).
  254. *
  255. * See C++'s https://en.cppreference.com/w/cpp/algorithm/upper_bound[upper_bound].
  256. */
  257. function upperBound(uint256[] storage array, uint256 element) internal view returns (uint256) {
  258. uint256 low = 0;
  259. uint256 high = array.length;
  260. if (high == 0) {
  261. return 0;
  262. }
  263. while (low < high) {
  264. uint256 mid = Math.average(low, high);
  265. // Note that mid will always be strictly less than high (i.e. it will be a valid array index)
  266. // because Math.average rounds towards zero (it does integer division with truncation).
  267. if (unsafeAccess(array, mid).value > element) {
  268. high = mid;
  269. } else {
  270. // this cannot overflow because mid < high
  271. unchecked {
  272. low = mid + 1;
  273. }
  274. }
  275. }
  276. return low;
  277. }
  278. /**
  279. * @dev Same as {lowerBound}, but with an array in memory.
  280. */
  281. function lowerBoundMemory(uint256[] memory array, uint256 element) internal pure returns (uint256) {
  282. uint256 low = 0;
  283. uint256 high = array.length;
  284. if (high == 0) {
  285. return 0;
  286. }
  287. while (low < high) {
  288. uint256 mid = Math.average(low, high);
  289. // Note that mid will always be strictly less than high (i.e. it will be a valid array index)
  290. // because Math.average rounds towards zero (it does integer division with truncation).
  291. if (unsafeMemoryAccess(array, mid) < element) {
  292. // this cannot overflow because mid < high
  293. unchecked {
  294. low = mid + 1;
  295. }
  296. } else {
  297. high = mid;
  298. }
  299. }
  300. return low;
  301. }
  302. /**
  303. * @dev Same as {upperBound}, but with an array in memory.
  304. */
  305. function upperBoundMemory(uint256[] memory array, uint256 element) internal pure returns (uint256) {
  306. uint256 low = 0;
  307. uint256 high = array.length;
  308. if (high == 0) {
  309. return 0;
  310. }
  311. while (low < high) {
  312. uint256 mid = Math.average(low, high);
  313. // Note that mid will always be strictly less than high (i.e. it will be a valid array index)
  314. // because Math.average rounds towards zero (it does integer division with truncation).
  315. if (unsafeMemoryAccess(array, mid) > element) {
  316. high = mid;
  317. } else {
  318. // this cannot overflow because mid < high
  319. unchecked {
  320. low = mid + 1;
  321. }
  322. }
  323. }
  324. return low;
  325. }
  326. /**
  327. * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
  328. *
  329. * WARNING: Only use if you are certain `pos` is lower than the array length.
  330. */
  331. function unsafeAccess(address[] storage arr, uint256 pos) internal pure returns (StorageSlot.AddressSlot storage) {
  332. bytes32 slot;
  333. /// @solidity memory-safe-assembly
  334. assembly {
  335. slot := arr.slot
  336. }
  337. return slot.deriveArray().offset(pos).getAddressSlot();
  338. }
  339. /**
  340. * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
  341. *
  342. * WARNING: Only use if you are certain `pos` is lower than the array length.
  343. */
  344. function unsafeAccess(bytes32[] storage arr, uint256 pos) internal pure returns (StorageSlot.Bytes32Slot storage) {
  345. bytes32 slot;
  346. /// @solidity memory-safe-assembly
  347. assembly {
  348. slot := arr.slot
  349. }
  350. return slot.deriveArray().offset(pos).getBytes32Slot();
  351. }
  352. /**
  353. * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
  354. *
  355. * WARNING: Only use if you are certain `pos` is lower than the array length.
  356. */
  357. function unsafeAccess(uint256[] storage arr, uint256 pos) internal pure returns (StorageSlot.Uint256Slot storage) {
  358. bytes32 slot;
  359. /// @solidity memory-safe-assembly
  360. assembly {
  361. slot := arr.slot
  362. }
  363. return slot.deriveArray().offset(pos).getUint256Slot();
  364. }
  365. /**
  366. * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
  367. *
  368. * WARNING: Only use if you are certain `pos` is lower than the array length.
  369. */
  370. function unsafeMemoryAccess(address[] memory arr, uint256 pos) internal pure returns (address res) {
  371. assembly {
  372. res := mload(add(add(arr, 0x20), mul(pos, 0x20)))
  373. }
  374. }
  375. /**
  376. * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
  377. *
  378. * WARNING: Only use if you are certain `pos` is lower than the array length.
  379. */
  380. function unsafeMemoryAccess(bytes32[] memory arr, uint256 pos) internal pure returns (bytes32 res) {
  381. assembly {
  382. res := mload(add(add(arr, 0x20), mul(pos, 0x20)))
  383. }
  384. }
  385. /**
  386. * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
  387. *
  388. * WARNING: Only use if you are certain `pos` is lower than the array length.
  389. */
  390. function unsafeMemoryAccess(uint256[] memory arr, uint256 pos) internal pure returns (uint256 res) {
  391. assembly {
  392. res := mload(add(add(arr, 0x20), mul(pos, 0x20)))
  393. }
  394. }
  395. /**
  396. * @dev Helper to set the length of an dynamic array. Directly writing to `.length` is forbidden.
  397. *
  398. * WARNING: this does not clear elements if length is reduced, of initialize elements if length is increased.
  399. */
  400. function unsafeSetLength(address[] storage array, uint256 len) internal {
  401. /// @solidity memory-safe-assembly
  402. assembly {
  403. sstore(array.slot, len)
  404. }
  405. }
  406. /**
  407. * @dev Helper to set the length of an dynamic array. Directly writing to `.length` is forbidden.
  408. *
  409. * WARNING: this does not clear elements if length is reduced, of initialize elements if length is increased.
  410. */
  411. function unsafeSetLength(bytes32[] storage array, uint256 len) internal {
  412. /// @solidity memory-safe-assembly
  413. assembly {
  414. sstore(array.slot, len)
  415. }
  416. }
  417. /**
  418. * @dev Helper to set the length of an dynamic array. Directly writing to `.length` is forbidden.
  419. *
  420. * WARNING: this does not clear elements if length is reduced, of initialize elements if length is increased.
  421. */
  422. function unsafeSetLength(uint256[] storage array, uint256 len) internal {
  423. /// @solidity memory-safe-assembly
  424. assembly {
  425. sstore(array.slot, len)
  426. }
  427. }
  428. }