EnumerableSet.js 7.5 KB

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