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