Counters.sol 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. // SPDX-License-Identifier: MIT
  2. pragma solidity >=0.6.0 <0.8.0;
  3. import "../math/SafeMath.sol";
  4. /**
  5. * @title Counters
  6. * @author Matt Condon (@shrugs)
  7. * @dev Provides counters that can only be incremented or decremented by one. 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. * Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath}
  12. * overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never
  13. * directly accessed.
  14. */
  15. library Counters {
  16. using SafeMath for uint256;
  17. struct Counter {
  18. // This variable should never be directly accessed by users of the library: interactions must be restricted to
  19. // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
  20. // this feature: see https://github.com/ethereum/solidity/issues/4637
  21. uint256 _value; // default: 0
  22. }
  23. function current(Counter storage counter) internal view returns (uint256) {
  24. return counter._value;
  25. }
  26. function increment(Counter storage counter) internal {
  27. // The {SafeMath} overflow check can be skipped here, see the comment at the top
  28. counter._value += 1;
  29. }
  30. function decrement(Counter storage counter) internal {
  31. counter._value = counter._value.sub(1);
  32. }
  33. }