Arrays.sol 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  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. assembly ("memory-safe") {
  124. ptr := add(array, 0x20)
  125. }
  126. }
  127. /**
  128. * @dev Pointer to the memory location of the first memory word (32bytes) after `array`. This is the memory word
  129. * that comes just after the last element of the array.
  130. */
  131. function _end(uint256[] memory array) private pure returns (uint256 ptr) {
  132. unchecked {
  133. return _begin(array) + array.length * 0x20;
  134. }
  135. }
  136. /**
  137. * @dev Load memory word (as a uint256) at location `ptr`.
  138. */
  139. function _mload(uint256 ptr) private pure returns (uint256 value) {
  140. assembly {
  141. value := mload(ptr)
  142. }
  143. }
  144. /**
  145. * @dev Swaps the elements memory location `ptr1` and `ptr2`.
  146. */
  147. function _swap(uint256 ptr1, uint256 ptr2) private pure {
  148. assembly {
  149. let value1 := mload(ptr1)
  150. let value2 := mload(ptr2)
  151. mstore(ptr1, value2)
  152. mstore(ptr2, value1)
  153. }
  154. }
  155. /// @dev Helper: low level cast address memory array to uint256 memory array
  156. function _castToUint256Array(address[] memory input) private pure returns (uint256[] memory output) {
  157. assembly {
  158. output := input
  159. }
  160. }
  161. /// @dev Helper: low level cast bytes32 memory array to uint256 memory array
  162. function _castToUint256Array(bytes32[] memory input) private pure returns (uint256[] memory output) {
  163. assembly {
  164. output := input
  165. }
  166. }
  167. /// @dev Helper: low level cast address comp function to uint256 comp function
  168. function _castToUint256Comp(
  169. function(address, address) pure returns (bool) input
  170. ) private pure returns (function(uint256, uint256) pure returns (bool) output) {
  171. assembly {
  172. output := input
  173. }
  174. }
  175. /// @dev Helper: low level cast bytes32 comp function to uint256 comp function
  176. function _castToUint256Comp(
  177. function(bytes32, bytes32) pure returns (bool) input
  178. ) private pure returns (function(uint256, uint256) pure returns (bool) output) {
  179. assembly {
  180. output := input
  181. }
  182. }
  183. /**
  184. * @dev Searches a sorted `array` and returns the first index that contains
  185. * a value greater or equal to `element`. If no such index exists (i.e. all
  186. * values in the array are strictly less than `element`), the array length is
  187. * returned. Time complexity O(log n).
  188. *
  189. * NOTE: The `array` is expected to be sorted in ascending order, and to
  190. * contain no repeated elements.
  191. *
  192. * IMPORTANT: Deprecated. This implementation behaves as {lowerBound} but lacks
  193. * support for repeated elements in the array. The {lowerBound} function should
  194. * be used instead.
  195. */
  196. function findUpperBound(uint256[] storage array, uint256 element) internal view returns (uint256) {
  197. uint256 low = 0;
  198. uint256 high = array.length;
  199. if (high == 0) {
  200. return 0;
  201. }
  202. while (low < high) {
  203. uint256 mid = Math.average(low, high);
  204. // Note that mid will always be strictly less than high (i.e. it will be a valid array index)
  205. // because Math.average rounds towards zero (it does integer division with truncation).
  206. if (unsafeAccess(array, mid).value > element) {
  207. high = mid;
  208. } else {
  209. low = mid + 1;
  210. }
  211. }
  212. // At this point `low` is the exclusive upper bound. We will return the inclusive upper bound.
  213. if (low > 0 && unsafeAccess(array, low - 1).value == element) {
  214. return low - 1;
  215. } else {
  216. return low;
  217. }
  218. }
  219. /**
  220. * @dev Searches an `array` sorted in ascending order and returns the first
  221. * index that contains a value greater or equal than `element`. If no such index
  222. * exists (i.e. all values in the array are strictly less than `element`), the array
  223. * length is returned. Time complexity O(log n).
  224. *
  225. * See C++'s https://en.cppreference.com/w/cpp/algorithm/lower_bound[lower_bound].
  226. */
  227. function lowerBound(uint256[] storage array, uint256 element) internal view returns (uint256) {
  228. uint256 low = 0;
  229. uint256 high = array.length;
  230. if (high == 0) {
  231. return 0;
  232. }
  233. while (low < high) {
  234. uint256 mid = Math.average(low, high);
  235. // Note that mid will always be strictly less than high (i.e. it will be a valid array index)
  236. // because Math.average rounds towards zero (it does integer division with truncation).
  237. if (unsafeAccess(array, mid).value < element) {
  238. // this cannot overflow because mid < high
  239. unchecked {
  240. low = mid + 1;
  241. }
  242. } else {
  243. high = mid;
  244. }
  245. }
  246. return low;
  247. }
  248. /**
  249. * @dev Searches an `array` sorted in ascending order and returns the first
  250. * index that contains a value strictly greater than `element`. If no such index
  251. * exists (i.e. all values in the array are strictly less than `element`), the array
  252. * length is returned. Time complexity O(log n).
  253. *
  254. * See C++'s https://en.cppreference.com/w/cpp/algorithm/upper_bound[upper_bound].
  255. */
  256. function upperBound(uint256[] storage array, uint256 element) internal view returns (uint256) {
  257. uint256 low = 0;
  258. uint256 high = array.length;
  259. if (high == 0) {
  260. return 0;
  261. }
  262. while (low < high) {
  263. uint256 mid = Math.average(low, high);
  264. // Note that mid will always be strictly less than high (i.e. it will be a valid array index)
  265. // because Math.average rounds towards zero (it does integer division with truncation).
  266. if (unsafeAccess(array, mid).value > element) {
  267. high = mid;
  268. } else {
  269. // this cannot overflow because mid < high
  270. unchecked {
  271. low = mid + 1;
  272. }
  273. }
  274. }
  275. return low;
  276. }
  277. /**
  278. * @dev Same as {lowerBound}, but with an array in memory.
  279. */
  280. function lowerBoundMemory(uint256[] memory array, uint256 element) internal pure returns (uint256) {
  281. uint256 low = 0;
  282. uint256 high = array.length;
  283. if (high == 0) {
  284. return 0;
  285. }
  286. while (low < high) {
  287. uint256 mid = Math.average(low, high);
  288. // Note that mid will always be strictly less than high (i.e. it will be a valid array index)
  289. // because Math.average rounds towards zero (it does integer division with truncation).
  290. if (unsafeMemoryAccess(array, mid) < element) {
  291. // this cannot overflow because mid < high
  292. unchecked {
  293. low = mid + 1;
  294. }
  295. } else {
  296. high = mid;
  297. }
  298. }
  299. return low;
  300. }
  301. /**
  302. * @dev Same as {upperBound}, but with an array in memory.
  303. */
  304. function upperBoundMemory(uint256[] memory array, uint256 element) internal pure returns (uint256) {
  305. uint256 low = 0;
  306. uint256 high = array.length;
  307. if (high == 0) {
  308. return 0;
  309. }
  310. while (low < high) {
  311. uint256 mid = Math.average(low, high);
  312. // Note that mid will always be strictly less than high (i.e. it will be a valid array index)
  313. // because Math.average rounds towards zero (it does integer division with truncation).
  314. if (unsafeMemoryAccess(array, mid) > element) {
  315. high = mid;
  316. } else {
  317. // this cannot overflow because mid < high
  318. unchecked {
  319. low = mid + 1;
  320. }
  321. }
  322. }
  323. return low;
  324. }
  325. /**
  326. * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
  327. *
  328. * WARNING: Only use if you are certain `pos` is lower than the array length.
  329. */
  330. function unsafeAccess(address[] storage arr, uint256 pos) internal pure returns (StorageSlot.AddressSlot storage) {
  331. bytes32 slot;
  332. assembly ("memory-safe") {
  333. slot := arr.slot
  334. }
  335. return slot.deriveArray().offset(pos).getAddressSlot();
  336. }
  337. /**
  338. * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
  339. *
  340. * WARNING: Only use if you are certain `pos` is lower than the array length.
  341. */
  342. function unsafeAccess(bytes32[] storage arr, uint256 pos) internal pure returns (StorageSlot.Bytes32Slot storage) {
  343. bytes32 slot;
  344. assembly ("memory-safe") {
  345. slot := arr.slot
  346. }
  347. return slot.deriveArray().offset(pos).getBytes32Slot();
  348. }
  349. /**
  350. * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
  351. *
  352. * WARNING: Only use if you are certain `pos` is lower than the array length.
  353. */
  354. function unsafeAccess(uint256[] storage arr, uint256 pos) internal pure returns (StorageSlot.Uint256Slot storage) {
  355. bytes32 slot;
  356. assembly ("memory-safe") {
  357. slot := arr.slot
  358. }
  359. return slot.deriveArray().offset(pos).getUint256Slot();
  360. }
  361. /**
  362. * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
  363. *
  364. * WARNING: Only use if you are certain `pos` is lower than the array length.
  365. */
  366. function unsafeMemoryAccess(address[] memory arr, uint256 pos) internal pure returns (address res) {
  367. assembly {
  368. res := mload(add(add(arr, 0x20), mul(pos, 0x20)))
  369. }
  370. }
  371. /**
  372. * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
  373. *
  374. * WARNING: Only use if you are certain `pos` is lower than the array length.
  375. */
  376. function unsafeMemoryAccess(bytes32[] memory arr, uint256 pos) internal pure returns (bytes32 res) {
  377. assembly {
  378. res := mload(add(add(arr, 0x20), mul(pos, 0x20)))
  379. }
  380. }
  381. /**
  382. * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
  383. *
  384. * WARNING: Only use if you are certain `pos` is lower than the array length.
  385. */
  386. function unsafeMemoryAccess(uint256[] memory arr, uint256 pos) internal pure returns (uint256 res) {
  387. assembly {
  388. res := mload(add(add(arr, 0x20), mul(pos, 0x20)))
  389. }
  390. }
  391. /**
  392. * @dev Helper to set the length of an dynamic array. Directly writing to `.length` is forbidden.
  393. *
  394. * WARNING: this does not clear elements if length is reduced, of initialize elements if length is increased.
  395. */
  396. function unsafeSetLength(address[] storage array, uint256 len) internal {
  397. assembly ("memory-safe") {
  398. sstore(array.slot, len)
  399. }
  400. }
  401. /**
  402. * @dev Helper to set the length of an dynamic array. Directly writing to `.length` is forbidden.
  403. *
  404. * WARNING: this does not clear elements if length is reduced, of initialize elements if length is increased.
  405. */
  406. function unsafeSetLength(bytes32[] storage array, uint256 len) internal {
  407. assembly ("memory-safe") {
  408. sstore(array.slot, len)
  409. }
  410. }
  411. /**
  412. * @dev Helper to set the length of an dynamic array. Directly writing to `.length` is forbidden.
  413. *
  414. * WARNING: this does not clear elements if length is reduced, of initialize elements if length is increased.
  415. */
  416. function unsafeSetLength(uint256[] storage array, uint256 len) internal {
  417. assembly ("memory-safe") {
  418. sstore(array.slot, len)
  419. }
  420. }
  421. }