EnumerableSet.js 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  1. const format = require('../format-lines');
  2. const { fromBytes32, toBytes32 } = require('./conversion');
  3. const { TYPES } = require('./EnumerableSet.opts');
  4. /* eslint-disable max-len */
  5. const header = `\
  6. pragma solidity ^0.8.20;
  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. *
  18. * \`\`\`solidity
  19. * contract Example {
  20. * // Add the library methods
  21. * using EnumerableSet for EnumerableSet.AddressSet;
  22. *
  23. * // Declare a set state variable
  24. * EnumerableSet.AddressSet private mySet;
  25. * }
  26. * \`\`\`
  27. *
  28. * As of v3.3.0, sets of type \`bytes32\` (\`Bytes32Set\`), \`address\` (\`AddressSet\`)
  29. * and \`uint256\` (\`UintSet\`) are supported.
  30. *
  31. * [WARNING]
  32. * ====
  33. * Trying to delete such a structure from storage will likely result in data corruption, rendering the structure
  34. * unusable.
  35. * See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.
  36. *
  37. * In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an
  38. * array of EnumerableSet.
  39. * ====
  40. */
  41. `;
  42. /* eslint-enable max-len */
  43. const defaultSet = `\
  44. // To implement this library for multiple types with as little code
  45. // repetition as possible, we write it in terms of a generic Set type with
  46. // bytes32 values.
  47. // The Set implementation uses private functions, and user-facing
  48. // implementations (such as AddressSet) are just wrappers around the
  49. // underlying Set.
  50. // This means that we can only create new EnumerableSets for types that fit
  51. // in bytes32.
  52. struct Set {
  53. // Storage of set values
  54. bytes32[] _values;
  55. // Position is the index of the value in the \`values\` array plus 1.
  56. // Position 0 is used to mean a value is not in the set.
  57. mapping(bytes32 value => uint256) _positions;
  58. }
  59. /**
  60. * @dev Add a value to a set. O(1).
  61. *
  62. * Returns true if the value was added to the set, that is if it was not
  63. * already present.
  64. */
  65. function _add(Set storage set, bytes32 value) private returns (bool) {
  66. if (!_contains(set, value)) {
  67. set._values.push(value);
  68. // The value is stored at length-1, but we add 1 to all indexes
  69. // and use 0 as a sentinel value
  70. set._positions[value] = set._values.length;
  71. return true;
  72. } else {
  73. return false;
  74. }
  75. }
  76. /**
  77. * @dev Removes a value from a set. O(1).
  78. *
  79. * Returns true if the value was removed from the set, that is if it was
  80. * present.
  81. */
  82. function _remove(Set storage set, bytes32 value) private returns (bool) {
  83. // We cache the value's position to prevent multiple reads from the same storage slot
  84. uint256 position = set._positions[value];
  85. if (position != 0) {
  86. // Equivalent to contains(set, value)
  87. // To delete an element from the _values array in O(1), we swap the element to delete with the last one in
  88. // the array, and then remove the last element (sometimes called as 'swap and pop').
  89. // This modifies the order of the array, as noted in {at}.
  90. uint256 valueIndex = position - 1;
  91. uint256 lastIndex = set._values.length - 1;
  92. if (valueIndex != lastIndex) {
  93. bytes32 lastValue = set._values[lastIndex];
  94. // Move the lastValue to the index where the value to delete is
  95. set._values[valueIndex] = lastValue;
  96. // Update the tracked position of the lastValue (that was just moved)
  97. set._positions[lastValue] = position;
  98. }
  99. // Delete the slot where the moved value was stored
  100. set._values.pop();
  101. // Delete the tracked position for the deleted slot
  102. delete set._positions[value];
  103. return true;
  104. } else {
  105. return false;
  106. }
  107. }
  108. /**
  109. * @dev Returns true if the value is in the set. O(1).
  110. */
  111. function _contains(Set storage set, bytes32 value) private view returns (bool) {
  112. return set._positions[value] != 0;
  113. }
  114. /**
  115. * @dev Returns the number of values on the set. O(1).
  116. */
  117. function _length(Set storage set) private view returns (uint256) {
  118. return set._values.length;
  119. }
  120. /**
  121. * @dev Returns the value stored at position \`index\` in the set. O(1).
  122. *
  123. * Note that there are no guarantees on the ordering of values inside the
  124. * array, and it may change when more values are added or removed.
  125. *
  126. * Requirements:
  127. *
  128. * - \`index\` must be strictly less than {length}.
  129. */
  130. function _at(Set storage set, uint256 index) private view returns (bytes32) {
  131. return set._values[index];
  132. }
  133. /**
  134. * @dev Return the entire set in an array
  135. *
  136. * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
  137. * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
  138. * this function has an unbounded cost, and using it as part of a state-changing function may render the function
  139. * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
  140. */
  141. function _values(Set storage set) private view returns (bytes32[] memory) {
  142. return set._values;
  143. }
  144. `;
  145. const customSet = ({ name, type }) => `\
  146. // ${name}
  147. struct ${name} {
  148. Set _inner;
  149. }
  150. /**
  151. * @dev Add a value to a set. O(1).
  152. *
  153. * Returns true if the value was added to the set, that is if it was not
  154. * already present.
  155. */
  156. function add(${name} storage set, ${type} value) internal returns (bool) {
  157. return _add(set._inner, ${toBytes32(type, 'value')});
  158. }
  159. /**
  160. * @dev Removes a value from a set. O(1).
  161. *
  162. * Returns true if the value was removed from the set, that is if it was
  163. * present.
  164. */
  165. function remove(${name} storage set, ${type} value) internal returns (bool) {
  166. return _remove(set._inner, ${toBytes32(type, 'value')});
  167. }
  168. /**
  169. * @dev Returns true if the value is in the set. O(1).
  170. */
  171. function contains(${name} storage set, ${type} value) internal view returns (bool) {
  172. return _contains(set._inner, ${toBytes32(type, 'value')});
  173. }
  174. /**
  175. * @dev Returns the number of values in the set. O(1).
  176. */
  177. function length(${name} storage set) internal view returns (uint256) {
  178. return _length(set._inner);
  179. }
  180. /**
  181. * @dev Returns the value stored at position \`index\` in the set. O(1).
  182. *
  183. * Note that there are no guarantees on the ordering of values inside the
  184. * array, and it may change when more values are added or removed.
  185. *
  186. * Requirements:
  187. *
  188. * - \`index\` must be strictly less than {length}.
  189. */
  190. function at(${name} storage set, uint256 index) internal view returns (${type}) {
  191. return ${fromBytes32(type, '_at(set._inner, index)')};
  192. }
  193. /**
  194. * @dev Return the entire set in an array
  195. *
  196. * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
  197. * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
  198. * this function has an unbounded cost, and using it as part of a state-changing function may render the function
  199. * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
  200. */
  201. function values(${name} storage set) internal view returns (${type}[] memory) {
  202. bytes32[] memory store = _values(set._inner);
  203. ${type}[] memory result;
  204. /// @solidity memory-safe-assembly
  205. assembly {
  206. result := store
  207. }
  208. return result;
  209. }
  210. `;
  211. // GENERATE
  212. module.exports = format(
  213. header.trimEnd(),
  214. 'library EnumerableSet {',
  215. format(
  216. [].concat(
  217. defaultSet,
  218. TYPES.map(details => customSet(details)),
  219. ),
  220. ).trimEnd(),
  221. '}',
  222. );