Counters.sol 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. // SPDX-License-Identifier: MIT
  2. // OpenZeppelin Contracts v4.4.1 (utils/Counters.sol)
  3. pragma solidity ^0.8.0;
  4. /**
  5. * @title Counters
  6. * @author Matt Condon (@shrugs)
  7. * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
  8. * of elements in a mapping, issuing ERC721 ids, or counting request ids.
  9. *
  10. * Include with `using Counters for Counters.Counter;`
  11. */
  12. library Counters {
  13. struct Counter {
  14. // This variable should never be directly accessed by users of the library: interactions must be restricted to
  15. // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
  16. // this feature: see https://github.com/ethereum/solidity/issues/4637
  17. uint256 _value; // default: 0
  18. }
  19. function current(Counter storage counter) internal view returns (uint256) {
  20. return counter._value;
  21. }
  22. function increment(Counter storage counter) internal {
  23. unchecked {
  24. counter._value += 1;
  25. }
  26. }
  27. function decrement(Counter storage counter) internal {
  28. uint256 value = counter._value;
  29. require(value > 0, "Counter: decrement overflow");
  30. unchecked {
  31. counter._value = value - 1;
  32. }
  33. }
  34. function reset(Counter storage counter) internal {
  35. counter._value = 0;
  36. }
  37. }