Arrays.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  1. const format = require('../format-lines');
  2. const { capitalize } = require('../../helpers');
  3. const { TYPES } = require('./Arrays.opts');
  4. const header = `\
  5. pragma solidity ^0.8.20;
  6. import {Comparators} from "./Comparators.sol";
  7. import {SlotDerivation} from "./SlotDerivation.sol";
  8. import {StorageSlot} from "./StorageSlot.sol";
  9. import {Math} from "./math/Math.sol";
  10. /**
  11. * @dev Collection of functions related to array types.
  12. */
  13. `;
  14. const sort = type => `\
  15. /**
  16. * @dev Sort an array of ${type} (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. ${type}[] memory array,
  30. function(${type}, ${type}) pure returns (bool) comp
  31. ) internal pure returns (${type}[] memory) {
  32. ${
  33. type === 'uint256'
  34. ? '_quickSort(_begin(array), _end(array), comp);'
  35. : 'sort(_castToUint256Array(array), _castToUint256Comp(comp));'
  36. }
  37. return array;
  38. }
  39. /**
  40. * @dev Variant of {sort} that sorts an array of ${type} in increasing order.
  41. */
  42. function sort(${type}[] memory array) internal pure returns (${type}[] memory) {
  43. ${type === 'uint256' ? 'sort(array, Comparators.lt);' : 'sort(_castToUint256Array(array), Comparators.lt);'}
  44. return array;
  45. }
  46. `;
  47. const quickSort = `\
  48. /**
  49. * @dev Performs a quick sort of a segment of memory. The segment sorted starts at \`begin\` (inclusive), and stops
  50. * at end (exclusive). Sorting follows the \`comp\` comparator.
  51. *
  52. * Invariant: \`begin <= end\`. This is the case when initially called by {sort} and is preserved in subcalls.
  53. *
  54. * IMPORTANT: Memory locations between \`begin\` and \`end\` are not validated/zeroed. This function should
  55. * be used only if the limits are within a memory array.
  56. */
  57. function _quickSort(uint256 begin, uint256 end, function(uint256, uint256) pure returns (bool) comp) private pure {
  58. unchecked {
  59. if (end - begin < 0x40) return;
  60. // Use first element as pivot
  61. uint256 pivot = _mload(begin);
  62. // Position where the pivot should be at the end of the loop
  63. uint256 pos = begin;
  64. for (uint256 it = begin + 0x20; it < end; it += 0x20) {
  65. if (comp(_mload(it), pivot)) {
  66. // If the value stored at the iterator's position comes before the pivot, we increment the
  67. // position of the pivot and move the value there.
  68. pos += 0x20;
  69. _swap(pos, it);
  70. }
  71. }
  72. _swap(begin, pos); // Swap pivot into place
  73. _quickSort(begin, pos, comp); // Sort the left side of the pivot
  74. _quickSort(pos + 0x20, end, comp); // Sort the right side of the pivot
  75. }
  76. }
  77. /**
  78. * @dev Pointer to the memory location of the first element of \`array\`.
  79. */
  80. function _begin(uint256[] memory array) private pure returns (uint256 ptr) {
  81. assembly ("memory-safe") {
  82. ptr := add(array, 0x20)
  83. }
  84. }
  85. /**
  86. * @dev Pointer to the memory location of the first memory word (32bytes) after \`array\`. This is the memory word
  87. * that comes just after the last element of the array.
  88. */
  89. function _end(uint256[] memory array) private pure returns (uint256 ptr) {
  90. unchecked {
  91. return _begin(array) + array.length * 0x20;
  92. }
  93. }
  94. /**
  95. * @dev Load memory word (as a uint256) at location \`ptr\`.
  96. */
  97. function _mload(uint256 ptr) private pure returns (uint256 value) {
  98. assembly {
  99. value := mload(ptr)
  100. }
  101. }
  102. /**
  103. * @dev Swaps the elements memory location \`ptr1\` and \`ptr2\`.
  104. */
  105. function _swap(uint256 ptr1, uint256 ptr2) private pure {
  106. assembly {
  107. let value1 := mload(ptr1)
  108. let value2 := mload(ptr2)
  109. mstore(ptr1, value2)
  110. mstore(ptr2, value1)
  111. }
  112. }
  113. `;
  114. const castArray = type => `\
  115. /// @dev Helper: low level cast ${type} memory array to uint256 memory array
  116. function _castToUint256Array(${type}[] memory input) private pure returns (uint256[] memory output) {
  117. assembly {
  118. output := input
  119. }
  120. }
  121. `;
  122. const castComparator = type => `\
  123. /// @dev Helper: low level cast ${type} comp function to uint256 comp function
  124. function _castToUint256Comp(
  125. function(${type}, ${type}) pure returns (bool) input
  126. ) private pure returns (function(uint256, uint256) pure returns (bool) output) {
  127. assembly {
  128. output := input
  129. }
  130. }
  131. `;
  132. const search = `\
  133. /**
  134. * @dev Searches a sorted \`array\` and returns the first index that contains
  135. * a value greater or equal to \`element\`. If no such index exists (i.e. all
  136. * values in the array are strictly less than \`element\`), the array length is
  137. * returned. Time complexity O(log n).
  138. *
  139. * NOTE: The \`array\` is expected to be sorted in ascending order, and to
  140. * contain no repeated elements.
  141. *
  142. * IMPORTANT: Deprecated. This implementation behaves as {lowerBound} but lacks
  143. * support for repeated elements in the array. The {lowerBound} function should
  144. * be used instead.
  145. */
  146. function findUpperBound(uint256[] storage array, uint256 element) internal view returns (uint256) {
  147. uint256 low = 0;
  148. uint256 high = array.length;
  149. if (high == 0) {
  150. return 0;
  151. }
  152. while (low < high) {
  153. uint256 mid = Math.average(low, high);
  154. // Note that mid will always be strictly less than high (i.e. it will be a valid array index)
  155. // because Math.average rounds towards zero (it does integer division with truncation).
  156. if (unsafeAccess(array, mid).value > element) {
  157. high = mid;
  158. } else {
  159. low = mid + 1;
  160. }
  161. }
  162. // At this point \`low\` is the exclusive upper bound. We will return the inclusive upper bound.
  163. if (low > 0 && unsafeAccess(array, low - 1).value == element) {
  164. return low - 1;
  165. } else {
  166. return low;
  167. }
  168. }
  169. /**
  170. * @dev Searches an \`array\` sorted in ascending order and returns the first
  171. * index that contains a value greater or equal than \`element\`. If no such index
  172. * exists (i.e. all values in the array are strictly less than \`element\`), the array
  173. * length is returned. Time complexity O(log n).
  174. *
  175. * See C++'s https://en.cppreference.com/w/cpp/algorithm/lower_bound[lower_bound].
  176. */
  177. function lowerBound(uint256[] storage array, uint256 element) internal view returns (uint256) {
  178. uint256 low = 0;
  179. uint256 high = array.length;
  180. if (high == 0) {
  181. return 0;
  182. }
  183. while (low < high) {
  184. uint256 mid = Math.average(low, high);
  185. // Note that mid will always be strictly less than high (i.e. it will be a valid array index)
  186. // because Math.average rounds towards zero (it does integer division with truncation).
  187. if (unsafeAccess(array, mid).value < element) {
  188. // this cannot overflow because mid < high
  189. unchecked {
  190. low = mid + 1;
  191. }
  192. } else {
  193. high = mid;
  194. }
  195. }
  196. return low;
  197. }
  198. /**
  199. * @dev Searches an \`array\` sorted in ascending order and returns the first
  200. * index that contains a value strictly greater than \`element\`. If no such index
  201. * exists (i.e. all values in the array are strictly less than \`element\`), the array
  202. * length is returned. Time complexity O(log n).
  203. *
  204. * See C++'s https://en.cppreference.com/w/cpp/algorithm/upper_bound[upper_bound].
  205. */
  206. function upperBound(uint256[] storage array, uint256 element) internal view returns (uint256) {
  207. uint256 low = 0;
  208. uint256 high = array.length;
  209. if (high == 0) {
  210. return 0;
  211. }
  212. while (low < high) {
  213. uint256 mid = Math.average(low, high);
  214. // Note that mid will always be strictly less than high (i.e. it will be a valid array index)
  215. // because Math.average rounds towards zero (it does integer division with truncation).
  216. if (unsafeAccess(array, mid).value > element) {
  217. high = mid;
  218. } else {
  219. // this cannot overflow because mid < high
  220. unchecked {
  221. low = mid + 1;
  222. }
  223. }
  224. }
  225. return low;
  226. }
  227. /**
  228. * @dev Same as {lowerBound}, but with an array in memory.
  229. */
  230. function lowerBoundMemory(uint256[] memory array, uint256 element) internal pure returns (uint256) {
  231. uint256 low = 0;
  232. uint256 high = array.length;
  233. if (high == 0) {
  234. return 0;
  235. }
  236. while (low < high) {
  237. uint256 mid = Math.average(low, high);
  238. // Note that mid will always be strictly less than high (i.e. it will be a valid array index)
  239. // because Math.average rounds towards zero (it does integer division with truncation).
  240. if (unsafeMemoryAccess(array, mid) < element) {
  241. // this cannot overflow because mid < high
  242. unchecked {
  243. low = mid + 1;
  244. }
  245. } else {
  246. high = mid;
  247. }
  248. }
  249. return low;
  250. }
  251. /**
  252. * @dev Same as {upperBound}, but with an array in memory.
  253. */
  254. function upperBoundMemory(uint256[] memory array, uint256 element) internal pure returns (uint256) {
  255. uint256 low = 0;
  256. uint256 high = array.length;
  257. if (high == 0) {
  258. return 0;
  259. }
  260. while (low < high) {
  261. uint256 mid = Math.average(low, high);
  262. // Note that mid will always be strictly less than high (i.e. it will be a valid array index)
  263. // because Math.average rounds towards zero (it does integer division with truncation).
  264. if (unsafeMemoryAccess(array, mid) > element) {
  265. high = mid;
  266. } else {
  267. // this cannot overflow because mid < high
  268. unchecked {
  269. low = mid + 1;
  270. }
  271. }
  272. }
  273. return low;
  274. }
  275. `;
  276. const unsafeAccessStorage = type => `\
  277. /**
  278. * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
  279. *
  280. * WARNING: Only use if you are certain \`pos\` is lower than the array length.
  281. */
  282. function unsafeAccess(${type}[] storage arr, uint256 pos) internal pure returns (StorageSlot.${capitalize(
  283. type,
  284. )}Slot storage) {
  285. bytes32 slot;
  286. assembly ("memory-safe") {
  287. slot := arr.slot
  288. }
  289. return slot.deriveArray().offset(pos).get${capitalize(type)}Slot();
  290. }
  291. `;
  292. const unsafeAccessMemory = type => `\
  293. /**
  294. * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
  295. *
  296. * WARNING: Only use if you are certain \`pos\` is lower than the array length.
  297. */
  298. function unsafeMemoryAccess(${type}[] memory arr, uint256 pos) internal pure returns (${type} res) {
  299. assembly {
  300. res := mload(add(add(arr, 0x20), mul(pos, 0x20)))
  301. }
  302. }
  303. `;
  304. const unsafeSetLength = type => `\
  305. /**
  306. * @dev Helper to set the length of an dynamic array. Directly writing to \`.length\` is forbidden.
  307. *
  308. * WARNING: this does not clear elements if length is reduced, of initialize elements if length is increased.
  309. */
  310. function unsafeSetLength(${type}[] storage array, uint256 len) internal {
  311. assembly ("memory-safe") {
  312. sstore(array.slot, len)
  313. }
  314. }
  315. `;
  316. // GENERATE
  317. module.exports = format(
  318. header.trimEnd(),
  319. 'library Arrays {',
  320. format(
  321. [].concat(
  322. 'using SlotDerivation for bytes32;',
  323. 'using StorageSlot for bytes32;',
  324. '',
  325. // sorting, comparator, helpers and internal
  326. sort('uint256'),
  327. TYPES.filter(type => type !== 'uint256').map(sort),
  328. quickSort,
  329. TYPES.filter(type => type !== 'uint256').map(castArray),
  330. TYPES.filter(type => type !== 'uint256').map(castComparator),
  331. // lookup
  332. search,
  333. // unsafe (direct) storage and memory access
  334. TYPES.map(unsafeAccessStorage),
  335. TYPES.map(unsafeAccessMemory),
  336. TYPES.map(unsafeSetLength),
  337. ),
  338. ).trimEnd(),
  339. '}',
  340. );