EnumerableSet.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  1. const format = require('../format-lines');
  2. const { fromBytes32, toBytes32 } = require('./conversion');
  3. const { SET_TYPES } = require('./Enumerable.opts');
  4. const header = `\
  5. pragma solidity ^0.8.20;
  6. import {Arrays} from "../Arrays.sol";
  7. /**
  8. * @dev Library for managing
  9. * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
  10. * types.
  11. *
  12. * Sets have the following properties:
  13. *
  14. * - Elements are added, removed, and checked for existence in constant time
  15. * (O(1)).
  16. * - Elements are enumerated in O(n). No guarantees are made on the ordering.
  17. * - Set can be cleared (all elements removed) in O(n).
  18. *
  19. * \`\`\`solidity
  20. * contract Example {
  21. * // Add the library methods
  22. * using EnumerableSet for EnumerableSet.AddressSet;
  23. *
  24. * // Declare a set state variable
  25. * EnumerableSet.AddressSet private mySet;
  26. * }
  27. * \`\`\`
  28. *
  29. * The following types are supported:
  30. *
  31. * - \`bytes32\` (\`Bytes32Set\`) since v3.3.0
  32. * - \`address\` (\`AddressSet\`) since v3.3.0
  33. * - \`uint256\` (\`UintSet\`) since v3.3.0
  34. * - \`string\` (\`StringSet\`) since v5.4.0
  35. * - \`bytes\` (\`BytesSet\`) since v5.4.0
  36. *
  37. * [WARNING]
  38. * ====
  39. * Trying to delete such a structure from storage will likely result in data corruption, rendering the structure
  40. * unusable.
  41. * See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.
  42. *
  43. * In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an
  44. * array of EnumerableSet.
  45. * ====
  46. */
  47. `;
  48. // NOTE: this should be deprecated in favor of a more native construction in v6.0
  49. const defaultSet = `\
  50. // To implement this library for multiple types with as little code
  51. // repetition as possible, we write it in terms of a generic Set type with
  52. // bytes32 values.
  53. // The Set implementation uses private functions, and user-facing
  54. // implementations (such as AddressSet) are just wrappers around the
  55. // underlying Set.
  56. // This means that we can only create new EnumerableSets for types that fit
  57. // in bytes32.
  58. struct Set {
  59. // Storage of set values
  60. bytes32[] _values;
  61. // Position is the index of the value in the \`values\` array plus 1.
  62. // Position 0 is used to mean a value is not in the set.
  63. mapping(bytes32 value => uint256) _positions;
  64. }
  65. /**
  66. * @dev Add a value to a set. O(1).
  67. *
  68. * Returns true if the value was added to the set, that is if it was not
  69. * already present.
  70. */
  71. function _add(Set storage set, bytes32 value) private returns (bool) {
  72. if (!_contains(set, value)) {
  73. set._values.push(value);
  74. // The value is stored at length-1, but we add 1 to all indexes
  75. // and use 0 as a sentinel value
  76. set._positions[value] = set._values.length;
  77. return true;
  78. } else {
  79. return false;
  80. }
  81. }
  82. /**
  83. * @dev Removes a value from a set. O(1).
  84. *
  85. * Returns true if the value was removed from the set, that is if it was
  86. * present.
  87. */
  88. function _remove(Set storage set, bytes32 value) private returns (bool) {
  89. // We cache the value's position to prevent multiple reads from the same storage slot
  90. uint256 position = set._positions[value];
  91. if (position != 0) {
  92. // Equivalent to contains(set, value)
  93. // To delete an element from the _values array in O(1), we swap the element to delete with the last one in
  94. // the array, and then remove the last element (sometimes called as 'swap and pop').
  95. // This modifies the order of the array, as noted in {at}.
  96. uint256 valueIndex = position - 1;
  97. uint256 lastIndex = set._values.length - 1;
  98. if (valueIndex != lastIndex) {
  99. bytes32 lastValue = set._values[lastIndex];
  100. // Move the lastValue to the index where the value to delete is
  101. set._values[valueIndex] = lastValue;
  102. // Update the tracked position of the lastValue (that was just moved)
  103. set._positions[lastValue] = position;
  104. }
  105. // Delete the slot where the moved value was stored
  106. set._values.pop();
  107. // Delete the tracked position for the deleted slot
  108. delete set._positions[value];
  109. return true;
  110. } else {
  111. return false;
  112. }
  113. }
  114. /**
  115. * @dev Removes all the values from a set. O(n).
  116. *
  117. * WARNING: Developers should keep in mind that this function has an unbounded cost and using it may render the
  118. * function uncallable if the set grows to the point where clearing it consumes too much gas to fit in a block.
  119. */
  120. function _clear(Set storage set) private {
  121. uint256 len = _length(set);
  122. for (uint256 i = 0; i < len; ++i) {
  123. delete set._positions[set._values[i]];
  124. }
  125. Arrays.unsafeSetLength(set._values, 0);
  126. }
  127. /**
  128. * @dev Returns true if the value is in the set. O(1).
  129. */
  130. function _contains(Set storage set, bytes32 value) private view returns (bool) {
  131. return set._positions[value] != 0;
  132. }
  133. /**
  134. * @dev Returns the number of values on the set. O(1).
  135. */
  136. function _length(Set storage set) private view returns (uint256) {
  137. return set._values.length;
  138. }
  139. /**
  140. * @dev Returns the value stored at position \`index\` in the set. O(1).
  141. *
  142. * Note that there are no guarantees on the ordering of values inside the
  143. * array, and it may change when more values are added or removed.
  144. *
  145. * Requirements:
  146. *
  147. * - \`index\` must be strictly less than {length}.
  148. */
  149. function _at(Set storage set, uint256 index) private view returns (bytes32) {
  150. return set._values[index];
  151. }
  152. /**
  153. * @dev Return the entire set in an array
  154. *
  155. * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
  156. * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
  157. * this function has an unbounded cost, and using it as part of a state-changing function may render the function
  158. * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
  159. */
  160. function _values(Set storage set) private view returns (bytes32[] memory) {
  161. return set._values;
  162. }
  163. `;
  164. // NOTE: this should be deprecated in favor of a more native construction in v6.0
  165. const customSet = ({ name, value: { type } }) => `\
  166. // ${name}
  167. struct ${name} {
  168. Set _inner;
  169. }
  170. /**
  171. * @dev Add a value to a set. O(1).
  172. *
  173. * Returns true if the value was added to the set, that is if it was not
  174. * already present.
  175. */
  176. function add(${name} storage set, ${type} value) internal returns (bool) {
  177. return _add(set._inner, ${toBytes32(type, 'value')});
  178. }
  179. /**
  180. * @dev Removes a value from a set. O(1).
  181. *
  182. * Returns true if the value was removed from the set, that is if it was
  183. * present.
  184. */
  185. function remove(${name} storage set, ${type} value) internal returns (bool) {
  186. return _remove(set._inner, ${toBytes32(type, 'value')});
  187. }
  188. /**
  189. * @dev Removes all the values from a set. O(n).
  190. *
  191. * WARNING: Developers should keep in mind that this function has an unbounded cost and using it may render the
  192. * function uncallable if the set grows to the point where clearing it consumes too much gas to fit in a block.
  193. */
  194. function clear(${name} storage set) internal {
  195. _clear(set._inner);
  196. }
  197. /**
  198. * @dev Returns true if the value is in the set. O(1).
  199. */
  200. function contains(${name} storage set, ${type} value) internal view returns (bool) {
  201. return _contains(set._inner, ${toBytes32(type, 'value')});
  202. }
  203. /**
  204. * @dev Returns the number of values in the set. O(1).
  205. */
  206. function length(${name} storage set) internal view returns (uint256) {
  207. return _length(set._inner);
  208. }
  209. /**
  210. * @dev Returns the value stored at position \`index\` in the set. O(1).
  211. *
  212. * Note that there are no guarantees on the ordering of values inside the
  213. * array, and it may change when more values are added or removed.
  214. *
  215. * Requirements:
  216. *
  217. * - \`index\` must be strictly less than {length}.
  218. */
  219. function at(${name} storage set, uint256 index) internal view returns (${type}) {
  220. return ${fromBytes32(type, '_at(set._inner, index)')};
  221. }
  222. /**
  223. * @dev Return the entire set in an array
  224. *
  225. * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
  226. * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
  227. * this function has an unbounded cost, and using it as part of a state-changing function may render the function
  228. * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
  229. */
  230. function values(${name} storage set) internal view returns (${type}[] memory) {
  231. bytes32[] memory store = _values(set._inner);
  232. ${type}[] memory result;
  233. assembly ("memory-safe") {
  234. result := store
  235. }
  236. return result;
  237. }
  238. `;
  239. const memorySet = ({ name, value }) => `\
  240. struct ${name} {
  241. // Storage of set values
  242. ${value.type}[] _values;
  243. // Position is the index of the value in the \`values\` array plus 1.
  244. // Position 0 is used to mean a value is not in the set.
  245. mapping(${value.type} value => uint256) _positions;
  246. }
  247. /**
  248. * @dev Add a value to a set. O(1).
  249. *
  250. * Returns true if the value was added to the set, that is if it was not
  251. * already present.
  252. */
  253. function add(${name} storage self, ${value.type} memory value) internal returns (bool) {
  254. if (!contains(self, value)) {
  255. self._values.push(value);
  256. // The value is stored at length-1, but we add 1 to all indexes
  257. // and use 0 as a sentinel value
  258. self._positions[value] = self._values.length;
  259. return true;
  260. } else {
  261. return false;
  262. }
  263. }
  264. /**
  265. * @dev Removes a value from a set. O(1).
  266. *
  267. * Returns true if the value was removed from the set, that is if it was
  268. * present.
  269. */
  270. function remove(${name} storage self, ${value.type} memory value) internal returns (bool) {
  271. // We cache the value's position to prevent multiple reads from the same storage slot
  272. uint256 position = self._positions[value];
  273. if (position != 0) {
  274. // Equivalent to contains(self, value)
  275. // To delete an element from the _values array in O(1), we swap the element to delete with the last one in
  276. // the array, and then remove the last element (sometimes called as 'swap and pop').
  277. // This modifies the order of the array, as noted in {at}.
  278. uint256 valueIndex = position - 1;
  279. uint256 lastIndex = self._values.length - 1;
  280. if (valueIndex != lastIndex) {
  281. ${value.type} memory lastValue = self._values[lastIndex];
  282. // Move the lastValue to the index where the value to delete is
  283. self._values[valueIndex] = lastValue;
  284. // Update the tracked position of the lastValue (that was just moved)
  285. self._positions[lastValue] = position;
  286. }
  287. // Delete the slot where the moved value was stored
  288. self._values.pop();
  289. // Delete the tracked position for the deleted slot
  290. delete self._positions[value];
  291. return true;
  292. } else {
  293. return false;
  294. }
  295. }
  296. /**
  297. * @dev Removes all the values from a set. O(n).
  298. *
  299. * WARNING: Developers should keep in mind that this function has an unbounded cost and using it may render the
  300. * function uncallable if the set grows to the point where clearing it consumes too much gas to fit in a block.
  301. */
  302. function clear(${name} storage set) internal {
  303. uint256 len = length(set);
  304. for (uint256 i = 0; i < len; ++i) {
  305. delete set._positions[set._values[i]];
  306. }
  307. Arrays.unsafeSetLength(set._values, 0);
  308. }
  309. /**
  310. * @dev Returns true if the value is in the set. O(1).
  311. */
  312. function contains(${name} storage self, ${value.type} memory value) internal view returns (bool) {
  313. return self._positions[value] != 0;
  314. }
  315. /**
  316. * @dev Returns the number of values on the set. O(1).
  317. */
  318. function length(${name} storage self) internal view returns (uint256) {
  319. return self._values.length;
  320. }
  321. /**
  322. * @dev Returns the value stored at position \`index\` in the set. O(1).
  323. *
  324. * Note that there are no guarantees on the ordering of values inside the
  325. * array, and it may change when more values are added or removed.
  326. *
  327. * Requirements:
  328. *
  329. * - \`index\` must be strictly less than {length}.
  330. */
  331. function at(${name} storage self, uint256 index) internal view returns (${value.type} memory) {
  332. return self._values[index];
  333. }
  334. /**
  335. * @dev Return the entire set in an array
  336. *
  337. * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
  338. * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
  339. * this function has an unbounded cost, and using it as part of a state-changing function may render the function
  340. * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
  341. */
  342. function values(${name} storage self) internal view returns (${value.type}[] memory) {
  343. return self._values;
  344. }
  345. `;
  346. // GENERATE
  347. module.exports = format(
  348. header.trimEnd(),
  349. 'library EnumerableSet {',
  350. format(
  351. [].concat(
  352. defaultSet,
  353. SET_TYPES.filter(({ value }) => !value.memory).map(customSet),
  354. SET_TYPES.filter(({ value }) => value.memory).map(memorySet),
  355. ),
  356. ).trimEnd(),
  357. '}',
  358. );