Arrays.sol 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. // SPDX-License-Identifier: MIT
  2. // OpenZeppelin Contracts v4.4.1 (utils/Arrays.sol)
  3. pragma solidity ^0.8.0;
  4. import "./math/Math.sol";
  5. /**
  6. * @dev Collection of functions related to array types.
  7. */
  8. library Arrays {
  9. /**
  10. * @dev Searches a sorted `array` and returns the first index that contains
  11. * a value greater or equal to `element`. If no such index exists (i.e. all
  12. * values in the array are strictly less than `element`), the array length is
  13. * returned. Time complexity O(log n).
  14. *
  15. * `array` is expected to be sorted in ascending order, and to contain no
  16. * repeated elements.
  17. */
  18. function findUpperBound(uint256[] storage array, uint256 element) internal view returns (uint256) {
  19. if (array.length == 0) {
  20. return 0;
  21. }
  22. uint256 low = 0;
  23. uint256 high = array.length;
  24. while (low < high) {
  25. uint256 mid = Math.average(low, high);
  26. // Note that mid will always be strictly less than high (i.e. it will be a valid array index)
  27. // because Math.average rounds down (it does integer division with truncation).
  28. if (array[mid] > element) {
  29. high = mid;
  30. } else {
  31. low = mid + 1;
  32. }
  33. }
  34. // At this point `low` is the exclusive upper bound. We will return the inclusive upper bound.
  35. if (low > 0 && array[low - 1] == element) {
  36. return low - 1;
  37. } else {
  38. return low;
  39. }
  40. }
  41. }