Arrays.js 12 KB

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