EnumerableSet.js 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  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. 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. * As of v3.3.0, sets of type \`bytes32\` (\`Bytes32Set\`), \`address\` (\`AddressSet\`)
  30. * and \`uint256\` (\`UintSet\`) are supported.
  31. *
  32. * [WARNING]
  33. * ====
  34. * Trying to delete such a structure from storage will likely result in data corruption, rendering the structure
  35. * unusable.
  36. * See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.
  37. *
  38. * In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an
  39. * array of EnumerableSet.
  40. * ====
  41. */
  42. `;
  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 Removes all the values from a set. O(n).
  110. *
  111. * WARNING: Developers should keep in mind that this function has an unbounded cost and using it may render the
  112. * function uncallable if the set grows to the point where clearing it consumes too much gas to fit in a block.
  113. */
  114. function _clear(Set storage set) private {
  115. uint256 len = _length(set);
  116. for (uint256 i = 0; i < len; ++i) {
  117. delete set._positions[set._values[i]];
  118. }
  119. Arrays.unsafeSetLength(set._values, 0);
  120. }
  121. /**
  122. * @dev Returns true if the value is in the set. O(1).
  123. */
  124. function _contains(Set storage set, bytes32 value) private view returns (bool) {
  125. return set._positions[value] != 0;
  126. }
  127. /**
  128. * @dev Returns the number of values on the set. O(1).
  129. */
  130. function _length(Set storage set) private view returns (uint256) {
  131. return set._values.length;
  132. }
  133. /**
  134. * @dev Returns the value stored at position \`index\` in the set. O(1).
  135. *
  136. * Note that there are no guarantees on the ordering of values inside the
  137. * array, and it may change when more values are added or removed.
  138. *
  139. * Requirements:
  140. *
  141. * - \`index\` must be strictly less than {length}.
  142. */
  143. function _at(Set storage set, uint256 index) private view returns (bytes32) {
  144. return set._values[index];
  145. }
  146. /**
  147. * @dev Return the entire set in an array
  148. *
  149. * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
  150. * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
  151. * this function has an unbounded cost, and using it as part of a state-changing function may render the function
  152. * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
  153. */
  154. function _values(Set storage set) private view returns (bytes32[] memory) {
  155. return set._values;
  156. }
  157. `;
  158. const customSet = ({ name, type }) => `\
  159. // ${name}
  160. struct ${name} {
  161. Set _inner;
  162. }
  163. /**
  164. * @dev Add a value to a set. O(1).
  165. *
  166. * Returns true if the value was added to the set, that is if it was not
  167. * already present.
  168. */
  169. function add(${name} storage set, ${type} value) internal returns (bool) {
  170. return _add(set._inner, ${toBytes32(type, 'value')});
  171. }
  172. /**
  173. * @dev Removes a value from a set. O(1).
  174. *
  175. * Returns true if the value was removed from the set, that is if it was
  176. * present.
  177. */
  178. function remove(${name} storage set, ${type} value) internal returns (bool) {
  179. return _remove(set._inner, ${toBytes32(type, 'value')});
  180. }
  181. /**
  182. * @dev Removes all the values from a set. O(n).
  183. *
  184. * WARNING: Developers should keep in mind that this function has an unbounded cost and using it may render the
  185. * function uncallable if the set grows to the point where clearing it consumes too much gas to fit in a block.
  186. */
  187. function clear(${name} storage set) internal {
  188. _clear(set._inner);
  189. }
  190. /**
  191. * @dev Returns true if the value is in the set. O(1).
  192. */
  193. function contains(${name} storage set, ${type} value) internal view returns (bool) {
  194. return _contains(set._inner, ${toBytes32(type, 'value')});
  195. }
  196. /**
  197. * @dev Returns the number of values in the set. O(1).
  198. */
  199. function length(${name} storage set) internal view returns (uint256) {
  200. return _length(set._inner);
  201. }
  202. /**
  203. * @dev Returns the value stored at position \`index\` in the set. O(1).
  204. *
  205. * Note that there are no guarantees on the ordering of values inside the
  206. * array, and it may change when more values are added or removed.
  207. *
  208. * Requirements:
  209. *
  210. * - \`index\` must be strictly less than {length}.
  211. */
  212. function at(${name} storage set, uint256 index) internal view returns (${type}) {
  213. return ${fromBytes32(type, '_at(set._inner, index)')};
  214. }
  215. /**
  216. * @dev Return the entire set in an array
  217. *
  218. * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
  219. * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
  220. * this function has an unbounded cost, and using it as part of a state-changing function may render the function
  221. * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
  222. */
  223. function values(${name} storage set) internal view returns (${type}[] memory) {
  224. bytes32[] memory store = _values(set._inner);
  225. ${type}[] memory result;
  226. assembly ("memory-safe") {
  227. result := store
  228. }
  229. return result;
  230. }
  231. `;
  232. // GENERATE
  233. module.exports = format(
  234. header.trimEnd(),
  235. 'library EnumerableSet {',
  236. format(
  237. [].concat(
  238. defaultSet,
  239. TYPES.map(details => customSet(details)),
  240. ),
  241. ).trimEnd(),
  242. '}',
  243. );