123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331 |
- // SPDX-License-Identifier: MIT
- // OpenZeppelin Contracts (last updated v5.0.0) (utils/Arrays.sol)
- pragma solidity ^0.8.20;
- import {StorageSlot} from "./StorageSlot.sol";
- import {Math} from "./math/Math.sol";
- /**
- * @dev Collection of functions related to array types.
- */
- library Arrays {
- using StorageSlot for bytes32;
- /**
- * @dev Sort an array (in memory) in increasing order.
- *
- * This function does the sorting "in place", meaning that it overrides the input. The object is returned for
- * convenience, but that returned value can be discarded safely if the caller has a memory pointer to the array.
- *
- * 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
- * array. Using it in view functions that are executed through `eth_call` is safe, but one should be very careful
- * when executing this as part of a transaction. If the array being sorted is too large, the sort operation may
- * consume more gas than is available in a block, leading to potential DoS.
- */
- function sort(uint256[] memory array) internal pure returns (uint256[] memory) {
- _quickSort(array, 0, array.length);
- return array;
- }
- /**
- * @dev Performs a quick sort on an array in memory. The array is sorted in increasing order.
- *
- * Invariant: `i <= j <= array.length`. This is the case when initially called by {sort} and is preserved in
- * subcalls.
- */
- function _quickSort(uint256[] memory array, uint256 i, uint256 j) private pure {
- unchecked {
- // Can't overflow given `i <= j`
- if (j - i < 2) return;
- // Use first element as pivot
- uint256 pivot = unsafeMemoryAccess(array, i);
- // Position where the pivot should be at the end of the loop
- uint256 index = i;
- for (uint256 k = i + 1; k < j; ++k) {
- // Unsafe access is safe given `k < j <= array.length`.
- if (unsafeMemoryAccess(array, k) < pivot) {
- // If array[k] is smaller than the pivot, we increment the index and move array[k] there.
- _swap(array, ++index, k);
- }
- }
- // Swap pivot into place
- _swap(array, i, index);
- _quickSort(array, i, index); // Sort the left side of the pivot
- _quickSort(array, index + 1, j); // Sort the right side of the pivot
- }
- }
- /**
- * @dev Swaps the elements at positions `i` and `j` in the `arr` array.
- */
- function _swap(uint256[] memory arr, uint256 i, uint256 j) private pure {
- assembly {
- let start := add(arr, 0x20) // Pointer to the first element of the array
- let pos_i := add(start, mul(i, 0x20))
- let pos_j := add(start, mul(j, 0x20))
- let val_i := mload(pos_i)
- let val_j := mload(pos_j)
- mstore(pos_i, val_j)
- mstore(pos_j, val_i)
- }
- }
- /**
- * @dev Searches a sorted `array` and returns the first index that contains
- * a value greater or equal to `element`. If no such index exists (i.e. all
- * values in the array are strictly less than `element`), the array length is
- * returned. Time complexity O(log n).
- *
- * NOTE: The `array` is expected to be sorted in ascending order, and to
- * contain no repeated elements.
- *
- * IMPORTANT: Deprecated. This implementation behaves as {lowerBound} but lacks
- * support for repeated elements in the array. The {lowerBound} function should
- * be used instead.
- */
- function findUpperBound(uint256[] storage array, uint256 element) internal view returns (uint256) {
- uint256 low = 0;
- uint256 high = array.length;
- if (high == 0) {
- return 0;
- }
- while (low < high) {
- uint256 mid = Math.average(low, high);
- // Note that mid will always be strictly less than high (i.e. it will be a valid array index)
- // because Math.average rounds towards zero (it does integer division with truncation).
- if (unsafeAccess(array, mid).value > element) {
- high = mid;
- } else {
- low = mid + 1;
- }
- }
- // At this point `low` is the exclusive upper bound. We will return the inclusive upper bound.
- if (low > 0 && unsafeAccess(array, low - 1).value == element) {
- return low - 1;
- } else {
- return low;
- }
- }
- /**
- * @dev Searches an `array` sorted in ascending order and returns the first
- * index that contains a value greater or equal than `element`. If no such index
- * exists (i.e. all values in the array are strictly less than `element`), the array
- * length is returned. Time complexity O(log n).
- *
- * See C++'s https://en.cppreference.com/w/cpp/algorithm/lower_bound[lower_bound].
- */
- function lowerBound(uint256[] storage array, uint256 element) internal view returns (uint256) {
- uint256 low = 0;
- uint256 high = array.length;
- if (high == 0) {
- return 0;
- }
- while (low < high) {
- uint256 mid = Math.average(low, high);
- // Note that mid will always be strictly less than high (i.e. it will be a valid array index)
- // because Math.average rounds towards zero (it does integer division with truncation).
- if (unsafeAccess(array, mid).value < element) {
- // this cannot overflow because mid < high
- unchecked {
- low = mid + 1;
- }
- } else {
- high = mid;
- }
- }
- return low;
- }
- /**
- * @dev Searches an `array` sorted in ascending order and returns the first
- * index that contains a value strictly greater than `element`. If no such index
- * exists (i.e. all values in the array are strictly less than `element`), the array
- * length is returned. Time complexity O(log n).
- *
- * See C++'s https://en.cppreference.com/w/cpp/algorithm/upper_bound[upper_bound].
- */
- function upperBound(uint256[] storage array, uint256 element) internal view returns (uint256) {
- uint256 low = 0;
- uint256 high = array.length;
- if (high == 0) {
- return 0;
- }
- while (low < high) {
- uint256 mid = Math.average(low, high);
- // Note that mid will always be strictly less than high (i.e. it will be a valid array index)
- // because Math.average rounds towards zero (it does integer division with truncation).
- if (unsafeAccess(array, mid).value > element) {
- high = mid;
- } else {
- // this cannot overflow because mid < high
- unchecked {
- low = mid + 1;
- }
- }
- }
- return low;
- }
- /**
- * @dev Same as {lowerBound}, but with an array in memory.
- */
- function lowerBoundMemory(uint256[] memory array, uint256 element) internal pure returns (uint256) {
- uint256 low = 0;
- uint256 high = array.length;
- if (high == 0) {
- return 0;
- }
- while (low < high) {
- uint256 mid = Math.average(low, high);
- // Note that mid will always be strictly less than high (i.e. it will be a valid array index)
- // because Math.average rounds towards zero (it does integer division with truncation).
- if (unsafeMemoryAccess(array, mid) < element) {
- // this cannot overflow because mid < high
- unchecked {
- low = mid + 1;
- }
- } else {
- high = mid;
- }
- }
- return low;
- }
- /**
- * @dev Same as {upperBound}, but with an array in memory.
- */
- function upperBoundMemory(uint256[] memory array, uint256 element) internal pure returns (uint256) {
- uint256 low = 0;
- uint256 high = array.length;
- if (high == 0) {
- return 0;
- }
- while (low < high) {
- uint256 mid = Math.average(low, high);
- // Note that mid will always be strictly less than high (i.e. it will be a valid array index)
- // because Math.average rounds towards zero (it does integer division with truncation).
- if (unsafeMemoryAccess(array, mid) > element) {
- high = mid;
- } else {
- // this cannot overflow because mid < high
- unchecked {
- low = mid + 1;
- }
- }
- }
- return low;
- }
- /**
- * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
- *
- * WARNING: Only use if you are certain `pos` is lower than the array length.
- */
- function unsafeAccess(address[] storage arr, uint256 pos) internal pure returns (StorageSlot.AddressSlot storage) {
- bytes32 slot;
- // We use assembly to calculate the storage slot of the element at index `pos` of the dynamic array `arr`
- // following https://docs.soliditylang.org/en/v0.8.20/internals/layout_in_storage.html#mappings-and-dynamic-arrays.
- /// @solidity memory-safe-assembly
- assembly {
- mstore(0, arr.slot)
- slot := add(keccak256(0, 0x20), pos)
- }
- return slot.getAddressSlot();
- }
- /**
- * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
- *
- * WARNING: Only use if you are certain `pos` is lower than the array length.
- */
- function unsafeAccess(bytes32[] storage arr, uint256 pos) internal pure returns (StorageSlot.Bytes32Slot storage) {
- bytes32 slot;
- // We use assembly to calculate the storage slot of the element at index `pos` of the dynamic array `arr`
- // following https://docs.soliditylang.org/en/v0.8.20/internals/layout_in_storage.html#mappings-and-dynamic-arrays.
- /// @solidity memory-safe-assembly
- assembly {
- mstore(0, arr.slot)
- slot := add(keccak256(0, 0x20), pos)
- }
- return slot.getBytes32Slot();
- }
- /**
- * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
- *
- * WARNING: Only use if you are certain `pos` is lower than the array length.
- */
- function unsafeAccess(uint256[] storage arr, uint256 pos) internal pure returns (StorageSlot.Uint256Slot storage) {
- bytes32 slot;
- // We use assembly to calculate the storage slot of the element at index `pos` of the dynamic array `arr`
- // following https://docs.soliditylang.org/en/v0.8.20/internals/layout_in_storage.html#mappings-and-dynamic-arrays.
- /// @solidity memory-safe-assembly
- assembly {
- mstore(0, arr.slot)
- slot := add(keccak256(0, 0x20), pos)
- }
- return slot.getUint256Slot();
- }
- /**
- * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
- *
- * WARNING: Only use if you are certain `pos` is lower than the array length.
- */
- function unsafeMemoryAccess(address[] memory arr, uint256 pos) internal pure returns (address res) {
- assembly {
- res := mload(add(add(arr, 0x20), mul(pos, 0x20)))
- }
- }
- /**
- * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
- *
- * WARNING: Only use if you are certain `pos` is lower than the array length.
- */
- function unsafeMemoryAccess(bytes32[] memory arr, uint256 pos) internal pure returns (bytes32 res) {
- assembly {
- res := mload(add(add(arr, 0x20), mul(pos, 0x20)))
- }
- }
- /**
- * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
- *
- * WARNING: Only use if you are certain `pos` is lower than the array length.
- */
- function unsafeMemoryAccess(uint256[] memory arr, uint256 pos) internal pure returns (uint256 res) {
- assembly {
- res := mload(add(add(arr, 0x20), mul(pos, 0x20)))
- }
- }
- }
|