Counters.sol 1.2 KB

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