Arrays.sol 17 KB

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