Arrays.sol 18 KB

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