Arrays.js 12 KB

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